diff --git a/cocos/2d/CCActionTiledGrid.cpp b/cocos/2d/CCActionTiledGrid.cpp index 85558d98e3..74665cd9b4 100644 --- a/cocos/2d/CCActionTiledGrid.cpp +++ b/cocos/2d/CCActionTiledGrid.cpp @@ -247,7 +247,7 @@ Vec2 ShuffleTiles::getDelta(const Vec2& pos) const pos2.x = (float)(_tilesOrder[idx] / (int)_gridSize.height); pos2.y = (float)(_tilesOrder[idx] % (int)_gridSize.height); - return Vec2((int)(pos2.x - pos.width), (int)(pos2.y - pos.height)); + return Vec2(static_cast((int)(pos2.x - pos.width)), static_cast((int)(pos2.y - pos.height))); } void ShuffleTiles::placeTile(const Vec2& pos, Tile* t) diff --git a/cocos/2d/CCActionTween.cpp b/cocos/2d/CCActionTween.cpp index 37f93ffae1..68b84f63ba 100644 --- a/cocos/2d/CCActionTween.cpp +++ b/cocos/2d/CCActionTween.cpp @@ -29,7 +29,7 @@ THE SOFTWARE. NS_CC_BEGIN -ActionTween* ActionTween::create(float duration, const std::string& key, float from, float to) +ActionTween* ActionTween::create(float duration, std::string_view key, float from, float to) { ActionTween* ret = new ActionTween(); if (ret->initWithDuration(duration, key, from, to)) @@ -42,7 +42,7 @@ ActionTween* ActionTween::create(float duration, const std::string& key, float f return nullptr; } -bool ActionTween::initWithDuration(float duration, const std::string& key, float from, float to) +bool ActionTween::initWithDuration(float duration, std::string_view key, float from, float to) { if (ActionInterval::initWithDuration(duration)) { diff --git a/cocos/2d/CCActionTween.h b/cocos/2d/CCActionTween.h index 4890f07a93..c0d1b7454f 100644 --- a/cocos/2d/CCActionTween.h +++ b/cocos/2d/CCActionTween.h @@ -59,7 +59,7 @@ public: @param value The new value of the specified key. @param key The key of property which should be updated. */ - virtual void updateTweenAction(float value, const std::string& key) = 0; + virtual void updateTweenAction(float value, std::string_view key) = 0; }; /** ActionTween @@ -93,7 +93,7 @@ public: * @param to The value of the specified property when the action end. * @return If the creation success, return a pointer of ActionTween; otherwise, return nil. */ - static ActionTween* create(float duration, const std::string& key, float from, float to); + static ActionTween* create(float duration, std::string_view key, float from, float to); // Overrides void startWithTarget(Node* target) override; @@ -111,7 +111,7 @@ public: * @return If the initialization success, return true; otherwise, return false. */ bool - initWithDuration(float duration, const std::string& key, float from, float to); + initWithDuration(float duration, std::string_view key, float from, float to); protected: std::string _key; diff --git a/cocos/2d/CCAnimation.cpp b/cocos/2d/CCAnimation.cpp index 7909c0e9a3..7f08879645 100644 --- a/cocos/2d/CCAnimation.cpp +++ b/cocos/2d/CCAnimation.cpp @@ -165,7 +165,7 @@ void Animation::addSpriteFrame(SpriteFrame* spriteFrame) _totalDelayUnits++; } -void Animation::addSpriteFrameWithFile(const std::string& filename) +void Animation::addSpriteFrameWithFile(std::string_view filename) { Texture2D* texture = Director::getInstance()->getTextureCache()->addImage(filename); Rect rect = Rect::ZERO; diff --git a/cocos/2d/CCAnimation.h b/cocos/2d/CCAnimation.h index 1a312fc3f7..b9b266c617 100644 --- a/cocos/2d/CCAnimation.h +++ b/cocos/2d/CCAnimation.h @@ -199,7 +199,7 @@ public: * Added to facilitate the migration from v0.8 to v0.9. * @param filename The path of SpriteFrame. */ - void addSpriteFrameWithFile(const std::string& filename); + void addSpriteFrameWithFile(std::string_view filename); /** Adds a frame with a texture and a rect. Internally it will create a SpriteFrame and it will add it. * The frame will be added with one "delay unit". diff --git a/cocos/2d/CCAnimationCache.cpp b/cocos/2d/CCAnimationCache.cpp index 6c3f62eecb..eefbf411d7 100644 --- a/cocos/2d/CCAnimationCache.cpp +++ b/cocos/2d/CCAnimationCache.cpp @@ -63,12 +63,12 @@ AnimationCache::~AnimationCache() CCLOGINFO("deallocing AnimationCache: %p", this); } -void AnimationCache::addAnimation(Animation* animation, const std::string& name) +void AnimationCache::addAnimation(Animation* animation, std::string_view name) { - _animations.insert(name, animation); + _animations.insert(std::string{name}, animation); } -void AnimationCache::removeAnimation(const std::string& name) +void AnimationCache::removeAnimation(std::string_view name) { if (name.empty()) return; @@ -76,7 +76,7 @@ void AnimationCache::removeAnimation(const std::string& name) _animations.erase(name); } -Animation* AnimationCache::getAnimation(const std::string& name) +Animation* AnimationCache::getAnimation(std::string_view name) { return _animations.at(name); } @@ -205,7 +205,7 @@ void AnimationCache::parseVersion2(const ValueMap& animations) } } -void AnimationCache::addAnimationsWithDictionary(const ValueMap& dictionary, const std::string& plist) +void AnimationCache::addAnimationsWithDictionary(const ValueMap& dictionary, std::string_view plist) { auto anisItr = dictionary.find("animations"); if (anisItr == dictionary.end()) @@ -245,7 +245,7 @@ void AnimationCache::addAnimationsWithDictionary(const ValueMap& dictionary, con } /** Read an NSDictionary from a plist file and parse it automatically for animations */ -void AnimationCache::addAnimationsWithFile(const std::string& plist) +void AnimationCache::addAnimationsWithFile(std::string_view plist) { CCASSERT(!plist.empty(), "Invalid texture file name"); if (plist.empty()) @@ -259,7 +259,7 @@ void AnimationCache::addAnimationsWithFile(const std::string& plist) CCASSERT(!dict.empty(), "CCAnimationCache: File could not be found"); if (dict.empty()) { - log("AnimationCache::addAnimationsWithFile error:%s not exist!", plist.c_str()); + log("AnimationCache::addAnimationsWithFile error:%s not exist!", plist.data()); } addAnimationsWithDictionary(dict, plist); diff --git a/cocos/2d/CCAnimationCache.h b/cocos/2d/CCAnimationCache.h index 0c41b66454..e64fa50c26 100644 --- a/cocos/2d/CCAnimationCache.h +++ b/cocos/2d/CCAnimationCache.h @@ -81,13 +81,13 @@ public: * @param animation An animation. * @param name The name of animation. */ - void addAnimation(Animation* animation, const std::string& name); + void addAnimation(Animation* animation, std::string_view name); /** Deletes a Animation from the cache. * * @param name The name of animation. */ - void removeAnimation(const std::string& name); + void removeAnimation(std::string_view name); /** Returns a Animation that was previously added. * If the name is not found it will return nil. @@ -95,7 +95,7 @@ public: * * @return A Animation that was previously added. If the name is not found it will return nil. */ - Animation* getAnimation(const std::string& name); + Animation* getAnimation(std::string_view name); /** Adds an animation from an NSDictionary. * Make sure that the frames were previously loaded in the SpriteFrameCache. @@ -104,7 +104,7 @@ public: * @since v1.1 @js NA */ - void addAnimationsWithDictionary(const ValueMap& dictionary, const std::string& plist); + void addAnimationsWithDictionary(const ValueMap& dictionary, std::string_view plist); /** Adds an animation from a plist file. * Make sure that the frames were previously loaded in the SpriteFrameCache. @@ -113,14 +113,14 @@ public: * @lua addAnimations * @param plist An animation from a plist file. */ - void addAnimationsWithFile(const std::string& plist); + void addAnimationsWithFile(std::string_view plist); private: void parseVersion1(const ValueMap& animations); void parseVersion2(const ValueMap& animations); private: - Map _animations; + Map _animations; static AnimationCache* s_sharedAnimationCache; }; diff --git a/cocos/2d/CCAtlasNode.cpp b/cocos/2d/CCAtlasNode.cpp index d1448ebdb4..6f38d89350 100644 --- a/cocos/2d/CCAtlasNode.cpp +++ b/cocos/2d/CCAtlasNode.cpp @@ -47,7 +47,7 @@ AtlasNode::~AtlasNode() CC_SAFE_RELEASE(_textureAtlas); } -AtlasNode* AtlasNode::create(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender) +AtlasNode* AtlasNode::create(std::string_view tile, int tileWidth, int tileHeight, int itemsToRender) { AtlasNode* ret = new AtlasNode(); if (ret->initWithTileFile(tile, tileWidth, tileHeight, itemsToRender)) @@ -59,7 +59,7 @@ AtlasNode* AtlasNode::create(const std::string& tile, int tileWidth, int tileHei return nullptr; } -bool AtlasNode::initWithTileFile(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender) +bool AtlasNode::initWithTileFile(std::string_view tile, int tileWidth, int tileHeight, int itemsToRender) { CCASSERT(!tile.empty(), "file size should not be empty"); Texture2D* texture = _director->getTextureCache()->addImage(tile); @@ -222,7 +222,7 @@ void AtlasNode::setIgnoreContentScaleFactor(bool ignoreContentScaleFactor) auto label = dynamic_cast(this); if (label) { - Vec2 s = Vec2(label->getString().size() * _itemWidth, _itemHeight); + Vec2 s = Vec2(static_cast(label->getString().size() * _itemWidth), static_cast(_itemHeight)); this->setContentSize(s); } } diff --git a/cocos/2d/CCAtlasNode.h b/cocos/2d/CCAtlasNode.h index e35c14942d..63125c6d33 100644 --- a/cocos/2d/CCAtlasNode.h +++ b/cocos/2d/CCAtlasNode.h @@ -57,7 +57,7 @@ public: * @param tileHeight The height of the item. * @param itemsToRender The quantity of items to render. */ - static AtlasNode* create(const std::string& filename, int tileWidth, int tileHeight, int itemsToRender); + static AtlasNode* create(std::string_view filename, int tileWidth, int tileHeight, int itemsToRender); /** updates the Atlas (indexed vertex array). * Shall be overridden in subclasses. @@ -106,7 +106,7 @@ public: /** Initializes an AtlasNode with an Atlas file the width and height of each item and the quantity of items to * render*/ - bool initWithTileFile(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender); + bool initWithTileFile(std::string_view tile, int tileWidth, int tileHeight, int itemsToRender); /** Initializes an AtlasNode with a texture the width and height of each item measured in points and the quantity * of items to render*/ diff --git a/cocos/2d/CCAutoPolygon.cpp b/cocos/2d/CCAutoPolygon.cpp index 6becd122ec..6cec415131 100644 --- a/cocos/2d/CCAutoPolygon.cpp +++ b/cocos/2d/CCAutoPolygon.cpp @@ -168,7 +168,7 @@ float PolygonInfo::getArea() const return area; } -AutoPolygon::AutoPolygon(const std::string& filename) +AutoPolygon::AutoPolygon(std::string_view filename) : _image(nullptr), _data(nullptr), _filename(""), _width(0), _height(0), _scaleFactor(0) { _filename = filename; @@ -714,7 +714,7 @@ PolygonInfo AutoPolygon::generateTriangles(const Rect& rect, float epsilon, floa return ret; } -PolygonInfo AutoPolygon::generatePolygon(const std::string& filename, const Rect& rect, float epsilon, float threshold) +PolygonInfo AutoPolygon::generatePolygon(std::string_view filename, const Rect& rect, float epsilon, float threshold) { AutoPolygon ap(filename); return ap.generateTriangles(rect, epsilon, threshold); diff --git a/cocos/2d/CCAutoPolygon.h b/cocos/2d/CCAutoPolygon.h index 1552ab99af..676c6bd03b 100644 --- a/cocos/2d/CCAutoPolygon.h +++ b/cocos/2d/CCAutoPolygon.h @@ -117,8 +117,8 @@ public: const Rect& getRect() const { return _rect; } void setRect(const Rect& rect) { _rect = rect; } - const std::string& getFilename() const { return _filename; } - void setFilename(const std::string& filename) { _filename = filename; } + std::string_view getFilename() const { return _filename; } + void setFilename(std::string_view filename) { _filename = filename; } // FIXME: this should be a property, not a public ivar TrianglesCommand::Triangles triangles; @@ -147,7 +147,7 @@ public: * @param filename a path to image file, e.g., "scene1/monster.png". * @return an AutoPolygon object; */ - AutoPolygon(const std::string& filename); + AutoPolygon(std::string_view filename); /** * Destructor of AutoPolygon. @@ -254,7 +254,7 @@ public: * auto sp = Sprite::create(AutoPolygon::generatePolygon("grossini.png")); * @endcode */ - static PolygonInfo generatePolygon(const std::string& filename, + static PolygonInfo generatePolygon(std::string_view filename, const Rect& rect = Rect::ZERO, float epsilon = 2.0f, float threshold = 0.05f); diff --git a/cocos/2d/CCCameraBackgroundBrush.cpp b/cocos/2d/CCCameraBackgroundBrush.cpp index 442ca25bcb..f983bfa87f 100644 --- a/cocos/2d/CCCameraBackgroundBrush.cpp +++ b/cocos/2d/CCCameraBackgroundBrush.cpp @@ -71,12 +71,12 @@ CameraBackgroundDepthBrush* CameraBackgroundBrush::createDepthBrush(float depth) return CameraBackgroundDepthBrush::create(depth); } -CameraBackgroundSkyBoxBrush* CameraBackgroundBrush::createSkyboxBrush(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z) +CameraBackgroundSkyBoxBrush* CameraBackgroundBrush::createSkyboxBrush(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z) { return CameraBackgroundSkyBoxBrush::create(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z); } @@ -303,12 +303,12 @@ CameraBackgroundSkyBoxBrush::~CameraBackgroundSkyBoxBrush() #endif } -CameraBackgroundSkyBoxBrush* CameraBackgroundSkyBoxBrush::create(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z) +CameraBackgroundSkyBoxBrush* CameraBackgroundSkyBoxBrush::create(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z) { CameraBackgroundSkyBoxBrush* ret = nullptr; diff --git a/cocos/2d/CCCameraBackgroundBrush.h b/cocos/2d/CCCameraBackgroundBrush.h index 1f884cff85..630b1a87e3 100644 --- a/cocos/2d/CCCameraBackgroundBrush.h +++ b/cocos/2d/CCCameraBackgroundBrush.h @@ -105,12 +105,12 @@ public: @param negative_z texture for the rear side of the texture cube face. @return A new brush inited with given parameters. */ - static CameraBackgroundSkyBoxBrush* createSkyboxBrush(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z); + static CameraBackgroundSkyBoxBrush* createSkyboxBrush(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z); /** * draw the background */ @@ -253,12 +253,12 @@ public: @param negative_z texture for the rear side of the texture cube face. @return A new brush inited with given parameters. */ - static CameraBackgroundSkyBoxBrush* create(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z); + static CameraBackgroundSkyBoxBrush* create(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z); /** Creates a Skybox brush with 6 textures. */ diff --git a/cocos/2d/CCComponent.h b/cocos/2d/CCComponent.h index d780a665e6..6fa5ff0859 100644 --- a/cocos/2d/CCComponent.h +++ b/cocos/2d/CCComponent.h @@ -60,8 +60,8 @@ public: bool isEnabled() const { return _enabled; } virtual void setEnabled(bool enabled); - const std::string& getName() const { return _name; } - virtual void setName(const std::string& name) { _name = name; } + std::string_view getName() const { return _name; } + virtual void setName(std::string_view name) { _name = name; } Node* getOwner() const { return _owner; } virtual void setOwner(Node* owner); diff --git a/cocos/2d/CCComponentContainer.cpp b/cocos/2d/CCComponentContainer.cpp index 92f5788415..dda4e93b8c 100644 --- a/cocos/2d/CCComponentContainer.cpp +++ b/cocos/2d/CCComponentContainer.cpp @@ -33,7 +33,7 @@ ComponentContainer::ComponentContainer(Node* node) : _owner(node) {} ComponentContainer::~ComponentContainer() {} -Component* ComponentContainer::get(const std::string& name) const +Component* ComponentContainer::get(std::string_view name) const { Component* ret = nullptr; @@ -60,7 +60,7 @@ bool ComponentContainer::add(Component* com) CCASSERT(false, "ComponentContainer already have this kind of component"); break; } - _componentMap[componentName] = com; + hlookup::set_item(_componentMap, componentName, com);//_componentMap[componentName] = com; com->retain(); com->setOwner(_owner); com->onAdd(); @@ -70,7 +70,7 @@ bool ComponentContainer::add(Component* com) return ret; } -bool ComponentContainer::remove(const std::string& componentName) +bool ComponentContainer::remove(std::string_view componentName) { bool ret = false; do diff --git a/cocos/2d/CCComponentContainer.h b/cocos/2d/CCComponentContainer.h index caba0e1a24..bdc08df759 100644 --- a/cocos/2d/CCComponentContainer.h +++ b/cocos/2d/CCComponentContainer.h @@ -54,10 +54,10 @@ public: /** * @js getComponent */ - Component* get(const std::string& name) const; + Component* get(std::string_view name) const; bool add(Component* com); - bool remove(const std::string& name); + bool remove(std::string_view name); bool remove(Component* com); void removeAll(); void visit(float delta); @@ -68,7 +68,7 @@ public: bool isEmpty() const { return _componentMap.empty(); } private: - std::unordered_map _componentMap; + hlookup::string_map _componentMap; Node* _owner; friend class Node; diff --git a/cocos/2d/CCFastTMXLayer.cpp b/cocos/2d/CCFastTMXLayer.cpp index c3f82291a9..566eae8223 100644 --- a/cocos/2d/CCFastTMXLayer.cpp +++ b/cocos/2d/CCFastTMXLayer.cpp @@ -799,7 +799,7 @@ void FastTMXLayer::removeChild(Node* node, bool cleanup) } // TMXLayer - Properties -Value FastTMXLayer::getProperty(const std::string& propertyName) const +Value FastTMXLayer::getProperty(std::string_view propertyName) const { auto propItr = _properties.find(propertyName); if (propItr != _properties.end()) diff --git a/cocos/2d/CCFastTMXLayer.h b/cocos/2d/CCFastTMXLayer.h index 0c69484ed8..0da9a39e8d 100644 --- a/cocos/2d/CCFastTMXLayer.h +++ b/cocos/2d/CCFastTMXLayer.h @@ -152,7 +152,7 @@ public: * @param propertyName The value for the specific property name. * @return The value for the specific property name. */ - Value getProperty(const std::string& propertyName) const; + Value getProperty(std::string_view propertyName) const; /** Creates the tiles. */ void setupTiles(); @@ -161,13 +161,13 @@ public: * * @return The tile layer name. */ - const std::string& getLayerName() { return _layerName; } + std::string_view getLayerName() { return _layerName; } /** Set the tile layer name. * * @param layerName The new layer name. */ - void setLayerName(const std::string& layerName) { _layerName = layerName; } + void setLayerName(std::string_view layerName) { _layerName = layerName; } /** Gets the size of the layer in tiles. * diff --git a/cocos/2d/CCFastTMXTiledMap.cpp b/cocos/2d/CCFastTMXTiledMap.cpp index b17ff6328f..d06d483a7c 100644 --- a/cocos/2d/CCFastTMXTiledMap.cpp +++ b/cocos/2d/CCFastTMXTiledMap.cpp @@ -33,7 +33,7 @@ NS_CC_BEGIN // implementation FastTMXTiledMap -FastTMXTiledMap* FastTMXTiledMap::create(const std::string& tmxFile) +FastTMXTiledMap* FastTMXTiledMap::create(std::string_view tmxFile) { FastTMXTiledMap* ret = new FastTMXTiledMap(); if (ret->initWithTMXFile(tmxFile)) @@ -45,7 +45,7 @@ FastTMXTiledMap* FastTMXTiledMap::create(const std::string& tmxFile) return nullptr; } -FastTMXTiledMap* FastTMXTiledMap::createWithXML(const std::string& tmxString, const std::string& resourcePath) +FastTMXTiledMap* FastTMXTiledMap::createWithXML(std::string_view tmxString, std::string_view resourcePath) { FastTMXTiledMap* ret = new FastTMXTiledMap(); if (ret->initWithXML(tmxString, resourcePath)) @@ -57,7 +57,7 @@ FastTMXTiledMap* FastTMXTiledMap::createWithXML(const std::string& tmxString, co return nullptr; } -bool FastTMXTiledMap::initWithTMXFile(const std::string& tmxFile) +bool FastTMXTiledMap::initWithTMXFile(std::string_view tmxFile) { CCASSERT(tmxFile.size() > 0, "FastTMXTiledMap: tmx file should not be empty"); @@ -77,7 +77,7 @@ bool FastTMXTiledMap::initWithTMXFile(const std::string& tmxFile) return true; } -bool FastTMXTiledMap::initWithXML(const std::string& tmxString, const std::string& resourcePath) +bool FastTMXTiledMap::initWithXML(std::string_view tmxString, std::string_view resourcePath) { setContentSize(Vec2::ZERO); @@ -194,7 +194,7 @@ void FastTMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo) } // public -FastTMXLayer* FastTMXTiledMap::getLayer(const std::string& layerName) const +FastTMXLayer* FastTMXTiledMap::getLayer(std::string_view layerName) const { CCASSERT(!layerName.empty(), "Invalid layer name!"); @@ -214,7 +214,7 @@ FastTMXLayer* FastTMXTiledMap::getLayer(const std::string& layerName) const return nullptr; } -TMXObjectGroup* FastTMXTiledMap::getObjectGroup(const std::string& groupName) const +TMXObjectGroup* FastTMXTiledMap::getObjectGroup(std::string_view groupName) const { CCASSERT(!groupName.empty(), "Invalid group name!"); @@ -233,7 +233,7 @@ TMXObjectGroup* FastTMXTiledMap::getObjectGroup(const std::string& groupName) co return nullptr; } -Value FastTMXTiledMap::getProperty(const std::string& propertyName) const +Value FastTMXTiledMap::getProperty(std::string_view propertyName) const { auto propsItr = _properties.find(propertyName); if (propsItr != _properties.end()) diff --git a/cocos/2d/CCFastTMXTiledMap.h b/cocos/2d/CCFastTMXTiledMap.h index da7a0273ac..9790ea746b 100644 --- a/cocos/2d/CCFastTMXTiledMap.h +++ b/cocos/2d/CCFastTMXTiledMap.h @@ -101,7 +101,7 @@ public: * * @return An autorelease object. */ - static FastTMXTiledMap* create(const std::string& tmxFile); + static FastTMXTiledMap* create(std::string_view tmxFile); /** Initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources. * @@ -109,25 +109,25 @@ public: * @param resourcePath A path to TMX resources. * @return An autorelease object. */ - static FastTMXTiledMap* createWithXML(const std::string& tmxString, const std::string& resourcePath); + static FastTMXTiledMap* createWithXML(std::string_view tmxString, std::string_view resourcePath); /** Return the FastTMXLayer for the specific layer. * * @return Return the FastTMXLayer for the specific layer. */ - FastTMXLayer* getLayer(const std::string& layerName) const; + FastTMXLayer* getLayer(std::string_view layerName) const; /** Return the TMXObjectGroup for the specific group. * * @return Return the TMXObjectGroup for the specific group. */ - TMXObjectGroup* getObjectGroup(const std::string& groupName) const; + TMXObjectGroup* getObjectGroup(std::string_view groupName) const; /** Return the value for the specific property name. * * @return Return the value for the specific property name. */ - Value getProperty(const std::string& propertyName) const; + Value getProperty(std::string_view propertyName) const; /** Return properties dictionary for tile GID. * @@ -207,7 +207,7 @@ public: int getLayerCount() const { return _layerCount; } - const std::string& getResourceFile() const { return _tmxFile; } + std::string_view getResourceFile() const { return _tmxFile; } CC_CONSTRUCTOR_ACCESS : /** @@ -221,10 +221,10 @@ public: virtual ~FastTMXTiledMap(); /** initializes a TMX Tiled Map with a TMX file */ - bool initWithTMXFile(const std::string& tmxFile); + bool initWithTMXFile(std::string_view tmxFile); /** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ - bool initWithXML(const std::string& tmxString, const std::string& resourcePath); + bool initWithXML(std::string_view tmxString, std::string_view resourcePath); protected: FastTMXLayer* parseLayer(TMXLayerInfo* layerInfo, TMXMapInfo* mapInfo); diff --git a/cocos/2d/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp index df0db9bc02..fc1aabd928 100644 --- a/cocos/2d/CCFontAtlas.cpp +++ b/cocos/2d/CCFontAtlas.cpp @@ -520,9 +520,9 @@ void FontAtlas::setLineHeight(float newHeight) _lineHeight = newHeight; } -std::string FontAtlas::getFontName() const +std::string_view FontAtlas::getFontName() const { - std::string fontName = _fontFreeType ? _fontFreeType->getFontName() : ""; + std::string_view fontName = _fontFreeType ? _fontFreeType->getFontName() : ""sv; if (fontName.empty()) return fontName; auto idx = fontName.rfind('/'); diff --git a/cocos/2d/CCFontAtlas.h b/cocos/2d/CCFontAtlas.h index 384aecb254..16bcfc72a8 100644 --- a/cocos/2d/CCFontAtlas.h +++ b/cocos/2d/CCFontAtlas.h @@ -86,7 +86,7 @@ public: float getLineHeight() const { return _lineHeight; } void setLineHeight(float newHeight); - std::string getFontName() const; + std::string_view getFontName() const; Texture2D* getTexture(int slot); const Font* getFont() const { return _font; } diff --git a/cocos/2d/CCFontAtlasCache.cpp b/cocos/2d/CCFontAtlasCache.cpp index d9df5ab566..60a359c334 100644 --- a/cocos/2d/CCFontAtlasCache.cpp +++ b/cocos/2d/CCFontAtlasCache.cpp @@ -36,7 +36,7 @@ NS_CC_BEGIN -std::unordered_map FontAtlasCache::_atlasMap; +hlookup::string_map FontAtlasCache::_atlasMap; #define ATLAS_MAP_KEY_PREFIX_BUFFER_SIZE 255 void FontAtlasCache::purgeCachedData() @@ -91,16 +91,17 @@ FontAtlas* FontAtlasCache::getFontAtlasTTF(const _ttfConfig* config) return nullptr; } -FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName) +FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName) { return getFontAtlasFNT(fontFileName, Rect::ZERO, false); } -FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName, const std::string& subTextureKey) +FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName, std::string_view subTextureKey) { const auto realFontFilename = FileUtils::getInstance()->getNewFilename( fontFileName); // resolves real file path, to prevent storing multiple atlases for the same file. - std::string atlasName = subTextureKey + " " + realFontFilename; + std::string atlasName{subTextureKey}; + atlasName.append(" ", 1).append(realFontFilename); const auto it = _atlasMap.find(atlasName); if (it == _atlasMap.end()) @@ -123,7 +124,7 @@ FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName, cons return nullptr; } -FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName, const Rect& imageRect, bool imageRotated) +FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName, const Rect& imageRect, bool imageRotated) { const auto realFontFilename = FileUtils::getInstance()->getNewFilename( fontFileName); // resolves real file path, to prevent storing multiple atlases for the same file. @@ -153,14 +154,14 @@ FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName, cons return nullptr; } -FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName, const Vec2& imageOffset) +FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName, const Vec2& imageOffset) { return getFontAtlasFNT(fontFileName, Rect(imageOffset.x, imageOffset.y, 0, 0), false); } -FontAtlas* FontAtlasCache::getFontAtlasCharMap(const std::string& plistFile) +FontAtlas* FontAtlasCache::getFontAtlasCharMap(std::string_view plistFile) { - const std::string& atlasName = plistFile; + std::string_view atlasName = plistFile; auto it = _atlasMap.find(atlasName); if (it == _atlasMap.end()) @@ -172,8 +173,8 @@ FontAtlas* FontAtlasCache::getFontAtlasCharMap(const std::string& plistFile) auto tempAtlas = font->newFontAtlas(); if (tempAtlas) { - _atlasMap[atlasName] = tempAtlas; - return _atlasMap[atlasName]; + hlookup::set_item(_atlasMap, atlasName, tempAtlas); // _atlasMap[atlasName] = tempAtlas; + return tempAtlas; } } } @@ -210,7 +211,7 @@ FontAtlas* FontAtlasCache::getFontAtlasCharMap(Texture2D* texture, int itemWidth return nullptr; } -FontAtlas* FontAtlasCache::getFontAtlasCharMap(const std::string& charMapFile, +FontAtlas* FontAtlasCache::getFontAtlasCharMap(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap) @@ -263,7 +264,7 @@ bool FontAtlasCache::releaseFontAtlas(FontAtlas* atlas) return false; } -void FontAtlasCache::reloadFontAtlasFNT(const std::string& fontFileName, const Rect& imageRect, bool imageRotated) +void FontAtlasCache::reloadFontAtlasFNT(std::string_view fontFileName, const Rect& imageRect, bool imageRotated) { char keyPrefix[ATLAS_MAP_KEY_PREFIX_BUFFER_SIZE]; snprintf(keyPrefix, ATLAS_MAP_KEY_PREFIX_BUFFER_SIZE, "%.2f %.2f ", imageRect.origin.x, imageRect.origin.y); @@ -288,12 +289,12 @@ void FontAtlasCache::reloadFontAtlasFNT(const std::string& fontFileName, const R } } -void FontAtlasCache::reloadFontAtlasFNT(const std::string& fontFileName, const Vec2& imageOffset) +void FontAtlasCache::reloadFontAtlasFNT(std::string_view fontFileName, const Vec2& imageOffset) { reloadFontAtlasFNT(fontFileName, Rect(imageOffset.x, imageOffset.y, 0, 0), false); } -void FontAtlasCache::unloadFontAtlasTTF(const std::string& fontFileName) +void FontAtlasCache::unloadFontAtlasTTF(std::string_view fontFileName) { auto item = _atlasMap.begin(); while (item != _atlasMap.end()) diff --git a/cocos/2d/CCFontAtlasCache.h b/cocos/2d/CCFontAtlasCache.h index d995d2a92f..f02e41ad22 100644 --- a/cocos/2d/CCFontAtlasCache.h +++ b/cocos/2d/CCFontAtlasCache.h @@ -43,17 +43,17 @@ class CC_DLL FontAtlasCache public: static FontAtlas* getFontAtlasTTF(const _ttfConfig* config); - static FontAtlas* getFontAtlasFNT(const std::string& fontFileName); - static FontAtlas* getFontAtlasFNT(const std::string& fontFileName, const std::string& subTextureKey); - static FontAtlas* getFontAtlasFNT(const std::string& fontFileName, const Rect& imageRect, bool imageRotated); - CC_DEPRECATED_ATTRIBUTE static FontAtlas* getFontAtlasFNT(const std::string& fontFileName, const Vec2& imageOffset); + static FontAtlas* getFontAtlasFNT(std::string_view fontFileName); + static FontAtlas* getFontAtlasFNT(std::string_view fontFileName, std::string_view subTextureKey); + static FontAtlas* getFontAtlasFNT(std::string_view fontFileName, const Rect& imageRect, bool imageRotated); + CC_DEPRECATED_ATTRIBUTE static FontAtlas* getFontAtlasFNT(std::string_view fontFileName, const Vec2& imageOffset); - static FontAtlas* getFontAtlasCharMap(const std::string& charMapFile, + static FontAtlas* getFontAtlasCharMap(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap); static FontAtlas* getFontAtlasCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); - static FontAtlas* getFontAtlasCharMap(const std::string& plistFile); + static FontAtlas* getFontAtlasCharMap(std::string_view plistFile); static bool releaseFontAtlas(FontAtlas* atlas); @@ -66,19 +66,19 @@ public: CAUTION : All component use this font texture should be reset font name, though the file name is same! otherwise, it will cause program crash! */ - static void reloadFontAtlasFNT(const std::string& fontFileName, const Rect& imageRect, bool imageRotated); + static void reloadFontAtlasFNT(std::string_view fontFileName, const Rect& imageRect, bool imageRotated); - CC_DEPRECATED_ATTRIBUTE static void reloadFontAtlasFNT(const std::string& fontFileName, + CC_DEPRECATED_ATTRIBUTE static void reloadFontAtlasFNT(std::string_view fontFileName, const Vec2& imageOffset = Vec2::ZERO); /** Unload all texture atlas texture create by special file name. CAUTION : All component use this font texture should be reset font name, though the file name is same! otherwise, it will cause program crash! */ - static void unloadFontAtlasTTF(const std::string& fontFileName); + static void unloadFontAtlasTTF(std::string_view fontFileName); private: - static std::unordered_map _atlasMap; + static hlookup::string_map _atlasMap; }; NS_CC_END diff --git a/cocos/2d/CCFontCharMap.cpp b/cocos/2d/CCFontCharMap.cpp index c8625143b9..8eb4986c83 100644 --- a/cocos/2d/CCFontCharMap.cpp +++ b/cocos/2d/CCFontCharMap.cpp @@ -33,7 +33,7 @@ NS_CC_BEGIN -FontCharMap* FontCharMap::create(const std::string& plistFile) +FontCharMap* FontCharMap::create(std::string_view plistFile) { std::string pathStr = FileUtils::getInstance()->fullPathForFilename(plistFile); std::string relPathStr = pathStr.substr(0, pathStr.find_last_of('/')) + "/"; @@ -64,7 +64,7 @@ FontCharMap* FontCharMap::create(const std::string& plistFile) return tempFont; } -FontCharMap* FontCharMap::create(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) +FontCharMap* FontCharMap::create(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap) { Texture2D* tempTexture = Director::getInstance()->getTextureCache()->addImage(charMapFile); diff --git a/cocos/2d/CCFontCharMap.h b/cocos/2d/CCFontCharMap.h index 1c57657196..436290471d 100644 --- a/cocos/2d/CCFontCharMap.h +++ b/cocos/2d/CCFontCharMap.h @@ -38,9 +38,9 @@ class Texture2D; class FontCharMap : public Font { public: - static FontCharMap* create(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); + static FontCharMap* create(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap); static FontCharMap* create(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); - static FontCharMap* create(const std::string& plistFile); + static FontCharMap* create(std::string_view plistFile); virtual int* getHorizontalKerningForTextUTF32(const std::u32string& text, int& outNumLetters) const override; virtual FontAtlas* newFontAtlas() override; diff --git a/cocos/2d/CCFontFNT.cpp b/cocos/2d/CCFontFNT.cpp index d3b252a4b2..87fa76440d 100644 --- a/cocos/2d/CCFontFNT.cpp +++ b/cocos/2d/CCFontFNT.cpp @@ -56,15 +56,15 @@ struct _FontDefHashElement; // // FNTConfig Cache - free functions // -static Map* s_configurations = nullptr; +static StringMap* s_configurations = nullptr; -BMFontConfiguration* FNTConfigLoadFile(const std::string& fntFile) +BMFontConfiguration* FNTConfigLoadFile(std::string_view fntFile) { BMFontConfiguration* ret = nullptr; if (s_configurations == nullptr) { - s_configurations = new Map(); + s_configurations = new StringMap(); } ret = s_configurations->at(fntFile); @@ -84,7 +84,7 @@ BMFontConfiguration* FNTConfigLoadFile(const std::string& fntFile) // BitmapFontConfiguration // -BMFontConfiguration* BMFontConfiguration::create(const std::string& FNTfile) +BMFontConfiguration* BMFontConfiguration::create(std::string_view FNTfile) { BMFontConfiguration* ret = new BMFontConfiguration(); if (ret->initWithFNTfile(FNTfile)) @@ -96,7 +96,7 @@ BMFontConfiguration* BMFontConfiguration::create(const std::string& FNTfile) return nullptr; } -bool BMFontConfiguration::initWithFNTfile(const std::string& FNTfile) +bool BMFontConfiguration::initWithFNTfile(std::string_view FNTfile) { _characterSet = this->parseConfigFile(FNTfile); @@ -141,7 +141,7 @@ void BMFontConfiguration::purgeFontDefDictionary() _fontDefDictionary.clear(); } -std::set* BMFontConfiguration::parseConfigFile(const std::string& controlFile) +std::set* BMFontConfiguration::parseConfigFile(std::string_view controlFile) { std::string data = FileUtils::getInstance()->getStringFromFile(controlFile); if (data.empty()) @@ -156,7 +156,7 @@ std::set* BMFontConfiguration::parseConfigFile(const std::string& } if (data[0] == 0) { - CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.c_str()); + CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.data()); return nullptr; } auto contents = data.c_str(); @@ -223,7 +223,7 @@ std::set* BMFontConfiguration::parseConfigFile(const std::string& std::set* BMFontConfiguration::parseBinaryConfigFile(unsigned char* pData, uint32_t size, - const std::string& controlFile) + std::string_view controlFile) { /* based on http://www.angelcode.com/products/bmfont/doc/file_format.html file format */ @@ -399,7 +399,7 @@ std::set* BMFontConfiguration::parseBinaryConfigFile(unsigned char return validCharsString; } -void BMFontConfiguration::parseImageFileName(const char* line, const std::string& fntFile) +void BMFontConfiguration::parseImageFileName(const char* line, std::string_view fntFile) { ////////////////////////////////////////////////////////////////////////// // line to parse: @@ -528,7 +528,7 @@ void BMFontConfiguration::parseKerningEntry(const char* line) _kerningDictionary[key] = amount; } -FontFNT* FontFNT::create(const std::string& fntFilePath, const Rect& imageRect, bool imageRotated) +FontFNT* FontFNT::create(std::string_view fntFilePath, const Rect& imageRect, bool imageRotated) { const auto newConf = FNTConfigLoadFile(fntFilePath); if (!newConf) @@ -545,7 +545,7 @@ FontFNT* FontFNT::create(const std::string& fntFilePath, const Rect& imageRect, return tempFont; } -FontFNT* FontFNT::create(const std::string& fntFilePath, const std::string& subTextureKey) +FontFNT* FontFNT::create(std::string_view fntFilePath, std::string_view subTextureKey) { const auto newConf = FNTConfigLoadFile(fntFilePath); if (!newConf) @@ -567,7 +567,7 @@ FontFNT* FontFNT::create(const std::string& fntFilePath, const std::string& subT return tempFont; } -FontFNT* FontFNT::create(const std::string& fntFilePath) +FontFNT* FontFNT::create(std::string_view fntFilePath) { const auto newConf = FNTConfigLoadFile(fntFilePath); if (!newConf) @@ -590,7 +590,7 @@ FontFNT* FontFNT::create(const std::string& fntFilePath) return tempFont; } -FontFNT* FontFNT::create(const std::string& fntFilePath, const Vec2& imageOffset) +FontFNT* FontFNT::create(std::string_view fntFilePath, const Vec2& imageOffset) { return create(fntFilePath, Rect(imageOffset.x, imageOffset.y, 0, 0), false); } @@ -762,11 +762,11 @@ FontAtlas* FontFNT::newFontAtlas() return tempAtlas; } -void FontFNT::reloadBMFontResource(const std::string& fntFilePath) +void FontFNT::reloadBMFontResource(std::string_view fntFilePath) { if (s_configurations == nullptr) { - s_configurations = new Map(); + s_configurations = new StringMap(); } BMFontConfiguration* ret = s_configurations->at(fntFilePath); diff --git a/cocos/2d/CCFontFNT.h b/cocos/2d/CCFontFNT.h index 3e6cb364a6..b1eb88ad5c 100644 --- a/cocos/2d/CCFontFNT.h +++ b/cocos/2d/CCFontFNT.h @@ -115,27 +115,27 @@ public: std::string description() const; /** allocates a BMFontConfiguration with a FNT file */ - static BMFontConfiguration* create(const std::string& FNTfile); + static BMFontConfiguration* create(std::string_view FNTfile); /** initializes a BitmapFontConfiguration with a FNT file */ - bool initWithFNTfile(const std::string& FNTfile); + bool initWithFNTfile(std::string_view FNTfile); - const std::string& getAtlasName() { return _atlasName; } - void setAtlasName(const std::string& atlasName) { _atlasName = atlasName; } + std::string_view getAtlasName() { return _atlasName; } + void setAtlasName(std::string_view atlasName) { _atlasName = atlasName; } std::set* getCharacterSet() const; protected: - virtual std::set* parseConfigFile(const std::string& controlFile); + virtual std::set* parseConfigFile(std::string_view controlFile); virtual std::set* parseBinaryConfigFile(unsigned char* pData, uint32_t size, - const std::string& controlFile); + std::string_view controlFile); private: unsigned int parseCharacterDefinition(const char* line); void parseInfoArguments(const char* line); void parseCommonArguments(const char* line); - void parseImageFileName(const char* line, const std::string& fntFile); + void parseImageFileName(const char* line, std::string_view fntFile); void parseKerningEntry(const char* line); void purgeKerningDictionary(); void purgeFontDefDictionary(); @@ -145,11 +145,11 @@ class CC_DLL FontFNT : public Font { public: - static FontFNT* create(const std::string& fntFilePath, const Rect& imageRect, bool imageRotated); - static FontFNT* create(const std::string& fntFilePath, const std::string& subTextureKey); - static FontFNT* create(const std::string& fntFilePath); + static FontFNT* create(std::string_view fntFilePath, const Rect& imageRect, bool imageRotated); + static FontFNT* create(std::string_view fntFilePath, std::string_view subTextureKey); + static FontFNT* create(std::string_view fntFilePath); - CC_DEPRECATED_ATTRIBUTE static FontFNT* create(const std::string& fntFilePath, + CC_DEPRECATED_ATTRIBUTE static FontFNT* create(std::string_view fntFilePath, const Vec2& imageOffset = Vec2::ZERO); /** Purges the cached data. @@ -164,7 +164,7 @@ public: int getOriginalFontSize() const; - static void reloadBMFontResource(const std::string& fntFilePath); + static void reloadBMFontResource(std::string_view fntFilePath); protected: FontFNT(BMFontConfiguration* theContfig, const Rect& imageRect, bool imageRotated); diff --git a/cocos/2d/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp index 4a93709cb1..c038926bc7 100644 --- a/cocos/2d/CCFontFreeType.cpp +++ b/cocos/2d/CCFontFreeType.cpp @@ -653,7 +653,7 @@ std::string_view FontFreeType::getGlyphCollection() const return glyphCollection; } -void FontFreeType::releaseFont(const std::string& fontName) +void FontFreeType::releaseFont(std::string_view fontName) { auto item = s_cacheFontData.begin(); while (s_cacheFontData.end() != item) diff --git a/cocos/2d/CCFontFreeType.h b/cocos/2d/CCFontFreeType.h index 177571476b..505812e87c 100644 --- a/cocos/2d/CCFontFreeType.h +++ b/cocos/2d/CCFontFreeType.h @@ -101,12 +101,12 @@ public: int getFontAscender() const; const char* getFontFamily() const; - const std::string& getFontName() const { return _fontName; } + std::string_view getFontName() const { return _fontName; } virtual FontAtlas* newFontAtlas() override; virtual int getFontMaxHeight() const override { return _lineHeight; } - static void releaseFont(const std::string& fontName); + static void releaseFont(std::string_view fontName); static FT_Library getFTLibrary(); diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index a184fa67d3..ba6b570aaf 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -240,8 +240,8 @@ Label* Label::create() return ret; } -Label* Label::createWithSystemFont(const std::string& text, - const std::string& font, +Label* Label::createWithSystemFont(std::string_view text, + std::string_view font, float fontSize, const Vec2& dimensions /* = Vec2::ZERO */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */, @@ -259,8 +259,8 @@ Label* Label::createWithSystemFont(const std::string& text, return ret; } -Label* Label::createWithTTF(const std::string& text, - const std::string& fontFile, +Label* Label::createWithTTF(std::string_view text, + std::string_view fontFile, float fontSize, const Vec2& dimensions /* = Vec2::ZERO */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */, @@ -279,7 +279,7 @@ Label* Label::createWithTTF(const std::string& text, } Label* Label::createWithTTF(const TTFConfig& ttfConfig, - const std::string& text, + std::string_view text, TextHAlignment hAlignment /* = TextHAlignment::CENTER */, int maxLineWidth /* = 0 */) { @@ -295,8 +295,8 @@ Label* Label::createWithTTF(const TTFConfig& ttfConfig, return nullptr; } -Label* Label::createWithBMFont(const std::string& bmfontPath, - const std::string& text, +Label* Label::createWithBMFont(std::string_view bmfontPath, + std::string_view text, const TextHAlignment& hAlignment, int maxLineWidth) { @@ -315,8 +315,8 @@ Label* Label::createWithBMFont(const std::string& bmfontPath, return nullptr; } -Label* Label::createWithBMFont(const std::string& bmfontPath, - const std::string& text, +Label* Label::createWithBMFont(std::string_view bmfontPath, + std::string_view text, const TextHAlignment& hAlignment, int maxLineWidth, const Rect& imageRect, @@ -337,11 +337,11 @@ Label* Label::createWithBMFont(const std::string& bmfontPath, return nullptr; } -Label* Label::createWithBMFont(const std::string& bmfontPath, - const std::string& text, +Label* Label::createWithBMFont(std::string_view bmfontPath, + std::string_view text, const TextHAlignment& hAlignment, int maxLineWidth, - const std::string& subTextureKey) + std::string_view subTextureKey) { auto ret = new Label(hAlignment); @@ -358,8 +358,8 @@ Label* Label::createWithBMFont(const std::string& bmfontPath, return nullptr; } -Label* Label::createWithBMFont(const std::string& bmfontPath, - const std::string& text, +Label* Label::createWithBMFont(std::string_view bmfontPath, + std::string_view text, const TextHAlignment& hAlignment, int maxLineWidth, const Vec2& imageOffset) @@ -368,7 +368,7 @@ Label* Label::createWithBMFont(const std::string& bmfontPath, false); } -Label* Label::createWithCharMap(const std::string& plistFile) +Label* Label::createWithCharMap(std::string_view plistFile) { auto ret = new Label(); @@ -396,7 +396,7 @@ Label* Label::createWithCharMap(Texture2D* texture, int itemWidth, int itemHeigh return nullptr; } -Label* Label::createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) +Label* Label::createWithCharMap(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap) { auto ret = new Label(); @@ -410,7 +410,7 @@ Label* Label::createWithCharMap(const std::string& charMapFile, int itemWidth, i return nullptr; } -bool Label::setCharMap(const std::string& plistFile) +bool Label::setCharMap(std::string_view plistFile) { auto newAtlas = FontAtlasCache::getFontAtlasCharMap(plistFile); @@ -426,8 +426,8 @@ bool Label::setCharMap(const std::string& plistFile) return true; } -bool Label::initWithTTF(const std::string& text, - const std::string& fontFilePath, +bool Label::initWithTTF(std::string_view text, + std::string_view fontFilePath, float fontSize, const Vec2& dimensions, TextHAlignment /*hAlignment*/, @@ -447,7 +447,7 @@ bool Label::initWithTTF(const std::string& text, } bool Label::initWithTTF(const TTFConfig& ttfConfig, - const std::string& text, + std::string_view text, TextHAlignment /*hAlignment*/, int maxLineWidth) { @@ -476,7 +476,7 @@ bool Label::setCharMap(Texture2D* texture, int itemWidth, int itemHeight, int st return true; } -bool Label::setCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) +bool Label::setCharMap(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap) { auto newAtlas = FontAtlasCache::getFontAtlasCharMap(charMapFile, itemWidth, itemHeight, startCharMap); @@ -841,7 +841,7 @@ bool Label::setTTFConfig(const TTFConfig& ttfConfig) return setTTFConfigInternal(ttfConfig); } -bool Label::setBMFontFilePath(const std::string& bmfontFilePath, float fontSize) +bool Label::setBMFontFilePath(std::string_view bmfontFilePath, float fontSize) { FontAtlas* newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath); @@ -875,7 +875,7 @@ bool Label::setBMFontFilePath(const std::string& bmfontFilePath, float fontSize) return true; } -bool Label::setBMFontFilePath(const std::string& bmfontFilePath, +bool Label::setBMFontFilePath(std::string_view bmfontFilePath, const Rect& imageRect, bool imageRotated, float fontSize) @@ -914,7 +914,7 @@ bool Label::setBMFontFilePath(const std::string& bmfontFilePath, return true; } -bool Label::setBMFontFilePath(const std::string& bmfontFilePath, const std::string& subTextureKey, float fontSize) +bool Label::setBMFontFilePath(std::string_view bmfontFilePath, std::string_view subTextureKey, float fontSize) { FontAtlas* newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath, subTextureKey); @@ -949,7 +949,7 @@ bool Label::setBMFontFilePath(const std::string& bmfontFilePath, const std::stri return true; } -bool Label::setBMFontFilePath(const std::string& bmfontFilePath, const Vec2& imageOffset, float fontSize) +bool Label::setBMFontFilePath(std::string_view bmfontFilePath, const Vec2& imageOffset, float fontSize) { return setBMFontFilePath(bmfontFilePath, Rect(imageOffset.x, imageOffset.y, 0, 0), false); } @@ -2105,7 +2105,7 @@ void Label::drawSelf(bool visibleByCamera, Renderer* renderer, uint32_t flags) } } -void Label::setSystemFontName(const std::string& systemFont) +void Label::setSystemFontName(std::string_view systemFont) { if (systemFont != _systemFont) { diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index 66d4669cd8..fa6b9622ea 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -166,8 +166,8 @@ public: * * @return An automatically released Label object. */ - static Label* createWithSystemFont(const std::string& text, - const std::string& font, + static Label* createWithSystemFont(std::string_view text, + std::string_view font, float fontSize, const Vec2& dimensions = Vec2::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT, @@ -185,8 +185,8 @@ public: * * @return An automatically released Label object. */ - static Label* createWithTTF(const std::string& text, - const std::string& fontFilePath, + static Label* createWithTTF(std::string_view text, + std::string_view fontFilePath, float fontSize, const Vec2& dimensions = Vec2::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT, @@ -204,7 +204,7 @@ public: * @see TTFConfig setTTFConfig setMaxLineWidth */ static Label* createWithTTF(const TTFConfig& ttfConfig, - const std::string& text, + std::string_view text, TextHAlignment hAlignment = TextHAlignment::LEFT, int maxLineWidth = 0); @@ -219,8 +219,8 @@ public: * @return An automatically released Label object. * @see setBMFontFilePath setMaxLineWidth */ - static Label* createWithBMFont(const std::string& bmfontPath, - const std::string& text, + static Label* createWithBMFont(std::string_view bmfontPath, + std::string_view text, const TextHAlignment& hAlignment = TextHAlignment::LEFT, int maxLineWidth = 0); @@ -237,8 +237,8 @@ public: * @return An automatically released Label object. * @see setBMFontFilePath setMaxLineWidth */ - static Label* createWithBMFont(const std::string& bmfontPath, - const std::string& text, + static Label* createWithBMFont(std::string_view bmfontPath, + std::string_view text, const TextHAlignment& hAlignment, int maxLineWidth, const Rect& imageRect, @@ -256,11 +256,11 @@ public: * @return An automatically released Label object. * @see setBMFontFilePath setMaxLineWidth */ - static Label* createWithBMFont(const std::string& bmfontPath, - const std::string& text, + static Label* createWithBMFont(std::string_view bmfontPath, + std::string_view text, const TextHAlignment& hAlignment, int maxLineWidth, - const std::string& subTextureKey); + std::string_view subTextureKey); /** * Allocates and initializes a Label, with a bitmap font file. @@ -274,8 +274,8 @@ public: * @return An automatically released Label object. * @see setBMFontFilePath setMaxLineWidth */ - CC_DEPRECATED_ATTRIBUTE static Label* createWithBMFont(const std::string& bmfontPath, - const std::string& text, + CC_DEPRECATED_ATTRIBUTE static Label* createWithBMFont(std::string_view bmfontPath, + std::string_view text, const TextHAlignment& hAlignment, int maxLineWidth, const Vec2& imageOffset); @@ -290,7 +290,7 @@ public: * * @return An automatically released Label object. */ - static Label* createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); + static Label* createWithCharMap(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap); /** * Allocates and initializes a Label, with char map configuration. @@ -311,7 +311,7 @@ public: * * @return An automatically released Label object. */ - static Label* createWithCharMap(const std::string& plistFile); + static Label* createWithCharMap(std::string_view plistFile); // end of creators group /// @} @@ -332,33 +332,33 @@ public: virtual const TTFConfig& getTTFConfig() const { return _fontConfig; } /** Sets a new bitmap font to Label */ - virtual bool setBMFontFilePath(const std::string& bmfontFilePath, float fontSize = 0); + virtual bool setBMFontFilePath(std::string_view bmfontFilePath, float fontSize = 0); /** Sets a new bitmap font to Label */ - virtual bool setBMFontFilePath(const std::string& bmfontFilePath, + virtual bool setBMFontFilePath(std::string_view bmfontFilePath, const Rect& imageRect, bool imageRotated, float fontSize = 0); /** Sets a new bitmap font to Label */ - virtual bool setBMFontFilePath(const std::string& bmfontFilePath, - const std::string& subTextureKey, + virtual bool setBMFontFilePath(std::string_view bmfontFilePath, + std::string_view subTextureKey, float fontSize = 0); /** Sets a new bitmap font to Label */ - CC_DEPRECATED_ATTRIBUTE virtual bool setBMFontFilePath(const std::string& bmfontFilePath, + CC_DEPRECATED_ATTRIBUTE virtual bool setBMFontFilePath(std::string_view bmfontFilePath, const Vec2& imageOffset, float fontSize = 0); /** Returns the bitmap font used by the Label.*/ - const std::string& getBMFontFilePath() const { return _bmFontPath; } + std::string_view getBMFontFilePath() const { return _bmFontPath; } /** * Sets a new char map configuration to Label. * - * @see `createWithCharMap(const std::string&,int,int,int)` + * @see `createWithCharMap(std::string_view,int,int,int)` */ - virtual bool setCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); + virtual bool setCharMap(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap); /** * Sets a new char map configuration to Label. @@ -370,9 +370,9 @@ public: /** * Sets a new char map configuration to Label. * - * @see `createWithCharMap(const std::string&)` + * @see `createWithCharMap(std::string_view)` */ - virtual bool setCharMap(const std::string& plistFile); + virtual bool setCharMap(std::string_view plistFile); /** * Sets a new system font to Label. @@ -380,10 +380,10 @@ public: * @param font A font file or a font family name. * @warning */ - virtual void setSystemFontName(const std::string& font); + virtual void setSystemFontName(std::string_view font); /** Returns the system font used by the Label.*/ - virtual const std::string& getSystemFontName() const { return _systemFont; } + virtual std::string_view getSystemFontName() const { return _systemFont; } /* Sets the system font size of Label.*/ virtual void setSystemFontSize(float fontSize); @@ -403,7 +403,7 @@ public: virtual void setString(std::string_view text) override; /** Return the text the Label is currently displaying.*/ - virtual const std::string& getString() const override { return _utf8Text; } + virtual std::string_view getString() const override { return _utf8Text; } /** * Return the number of lines of text. @@ -716,15 +716,15 @@ public: */ virtual ~Label(); - bool initWithTTF(const std::string& text, - const std::string& fontFilePath, + bool initWithTTF(std::string_view text, + std::string_view fontFilePath, float fontSize, const Vec2& dimensions = Vec2::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT, TextVAlignment vAlignment = TextVAlignment::TOP); bool initWithTTF(const TTFConfig& ttfConfig, - const std::string& text, + std::string_view text, TextHAlignment hAlignment = TextHAlignment::LEFT, int maxLineWidth = 0); diff --git a/cocos/2d/CCLabelAtlas.cpp b/cocos/2d/CCLabelAtlas.cpp index 4b45ff28bd..5179b6ff06 100644 --- a/cocos/2d/CCLabelAtlas.cpp +++ b/cocos/2d/CCLabelAtlas.cpp @@ -40,8 +40,8 @@ NS_CC_BEGIN // CCLabelAtlas - Creation & Init -LabelAtlas* LabelAtlas::create(const std::string& string, - const std::string& charMapFile, +LabelAtlas* LabelAtlas::create(std::string_view string, + std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap) @@ -56,8 +56,8 @@ LabelAtlas* LabelAtlas::create(const std::string& string, return nullptr; } -bool LabelAtlas::initWithString(const std::string& string, - const std::string& charMapFile, +bool LabelAtlas::initWithString(std::string_view string, + std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap) @@ -66,7 +66,7 @@ bool LabelAtlas::initWithString(const std::string& string, return initWithString(string, texture, itemWidth, itemHeight, startCharMap); } -bool LabelAtlas::initWithString(const std::string& string, +bool LabelAtlas::initWithString(std::string_view string, Texture2D* texture, int itemWidth, int itemHeight, @@ -81,7 +81,7 @@ bool LabelAtlas::initWithString(const std::string& string, return false; } -LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& fntFile) +LabelAtlas* LabelAtlas::create(std::string_view string, std::string_view fntFile) { LabelAtlas* ret = new LabelAtlas(); @@ -97,7 +97,7 @@ LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& fnt return ret; } -LabelAtlas* LabelAtlas::create(const std::string& string, +LabelAtlas* LabelAtlas::create(std::string_view string, Texture2D* texture, int itemWidth, int itemHeight, @@ -117,7 +117,7 @@ LabelAtlas* LabelAtlas::create(const std::string& string, return ret; } -bool LabelAtlas::initWithString(const std::string& theString, const std::string& fntFile) +bool LabelAtlas::initWithString(std::string_view theString, std::string_view fntFile) { std::string pathStr = FileUtils::getInstance()->fullPathForFilename(fntFile); std::string relPathStr = pathStr.substr(0, pathStr.find_last_of('/')) + "/"; @@ -128,8 +128,8 @@ bool LabelAtlas::initWithString(const std::string& theString, const std::string& std::string textureFilename = relPathStr + dict["textureFilename"].asString(); - unsigned int width = dict["itemWidth"].asInt() / CC_CONTENT_SCALE_FACTOR(); - unsigned int height = dict["itemHeight"].asInt() / CC_CONTENT_SCALE_FACTOR(); + unsigned int width = static_cast(dict["itemWidth"].asInt() / CC_CONTENT_SCALE_FACTOR()); + unsigned int height = static_cast(dict["itemHeight"].asInt() / CC_CONTENT_SCALE_FACTOR()); unsigned int startChar = dict["firstChar"].asInt(); this->initWithString(theString, textureFilename, width, height, startChar); @@ -156,8 +156,8 @@ void LabelAtlas::updateAtlasValues() float itemHeightInPixels = _itemHeight * CC_CONTENT_SCALE_FACTOR(); if (_ignoreContentScaleFactor) { - itemWidthInPixels = _itemWidth; - itemHeightInPixels = _itemHeight; + itemWidthInPixels = static_cast(_itemWidth); + itemHeightInPixels = static_cast(_itemHeight); } CCASSERT(n <= _textureAtlas->getCapacity(), "updateAtlasValues: Invalid String length"); @@ -239,7 +239,7 @@ void LabelAtlas::setString(std::string_view label) _quadsToDraw = len; } -const std::string& LabelAtlas::getString() const +std::string_view LabelAtlas::getString() const { return _string; } diff --git a/cocos/2d/CCLabelAtlas.h b/cocos/2d/CCLabelAtlas.h index b1f10ca9a9..1965e75f32 100644 --- a/cocos/2d/CCLabelAtlas.h +++ b/cocos/2d/CCLabelAtlas.h @@ -58,8 +58,8 @@ class CC_DLL LabelAtlas : public AtlasNode, public LabelProtocol public: /** Creates the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the * starting char of the atlas. */ - static LabelAtlas* create(const std::string& string, - const std::string& charMapFile, + static LabelAtlas* create(std::string_view string, + std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap); @@ -68,13 +68,13 @@ public: * Creates the LabelAtlas with a string and a configuration file. * @since v2.0 */ - static LabelAtlas* create(const std::string& string, const std::string& fntFile); + static LabelAtlas* create(std::string_view string, std::string_view fntFile); /** * Creates the LabelAtlas with a string, a texture, the width and height of each element and the starting char of * the atlas. */ - static LabelAtlas* create(const std::string& string, + static LabelAtlas* create(std::string_view string, Texture2D* texture, int itemWidth, int itemHeight, @@ -82,8 +82,8 @@ public: /** Initializes the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and * the starting char of the atlas. */ - bool initWithString(const std::string& string, - const std::string& charMapFile, + bool initWithString(std::string_view string, + std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap); @@ -92,14 +92,14 @@ public: * Initializes the LabelAtlas with a string and a configuration file. * @since v2.0 */ - bool initWithString(const std::string& string, const std::string& fntFile); + bool initWithString(std::string_view string, std::string_view fntFile); /** Initializes the LabelAtlas with a string, a texture, the width and height in points of each element and the * starting char of the atlas */ - bool initWithString(const std::string& string, Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); + bool initWithString(std::string_view string, Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); virtual void setString(std::string_view label) override; - virtual const std::string& getString() const override; + virtual std::string_view getString() const override; virtual void updateAtlasValues() override; /** diff --git a/cocos/2d/CCLabelTextFormatter.cpp b/cocos/2d/CCLabelTextFormatter.cpp index a357c06ede..33dc2474ae 100644 --- a/cocos/2d/CCLabelTextFormatter.cpp +++ b/cocos/2d/CCLabelTextFormatter.cpp @@ -109,7 +109,7 @@ int Label::getFirstWordLen(const std::u32string& utf32Text, int startIndex, int break; } - nextLetterX += letterDef.xAdvance * _bmfontScale + _additionalKerning; + nextLetterX += static_cast(letterDef.xAdvance * _bmfontScale + _additionalKerning); len++; } @@ -140,7 +140,7 @@ void Label::updateBMFontScale() if (_currentLabelType == LabelType::BMFONT) { FontFNT* bmFont = (FontFNT*)font; - float originalFontSize = bmFont->getOriginalFontSize(); + auto originalFontSize = bmFont->getOriginalFontSize(); _bmfontScale = _bmFontSize * CC_CONTENT_SCALE_FACTOR() / originalFontSize; } else @@ -242,7 +242,7 @@ bool Label::multilineTextWrap(const std::function(_horizontalKernings[letterIndex + 1]); newLetterWidth += letterDef.xAdvance * _bmfontScale + _additionalKerning; nextLetterX += newLetterWidth; diff --git a/cocos/2d/CCMenu.cpp b/cocos/2d/CCMenu.cpp index bbd8808cc6..d24e015291 100644 --- a/cocos/2d/CCMenu.cpp +++ b/cocos/2d/CCMenu.cpp @@ -175,7 +175,7 @@ void Menu::addChild(Node* child, int zOrder, int tag) Layer::addChild(child, zOrder, tag); } -void Menu::addChild(Node* child, int zOrder, const std::string& name) +void Menu::addChild(Node* child, int zOrder, std::string_view name) { CCASSERT(dynamic_cast(child) != nullptr, "Menu only supports MenuItem objects as children"); Layer::addChild(child, zOrder, name); diff --git a/cocos/2d/CCMenu.h b/cocos/2d/CCMenu.h index 560c75c8e5..37d86df332 100644 --- a/cocos/2d/CCMenu.h +++ b/cocos/2d/CCMenu.h @@ -148,7 +148,7 @@ public: virtual void addChild(Node* child) override; virtual void addChild(Node* child, int zOrder) override; virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, const std::string& name) override; + virtual void addChild(Node* child, int zOrder, std::string_view name) override; virtual void onEnter() override; virtual void onExit() override; diff --git a/cocos/2d/CCMenuItem.cpp b/cocos/2d/CCMenuItem.cpp index 83927a12d2..fb797cc864 100644 --- a/cocos/2d/CCMenuItem.cpp +++ b/cocos/2d/CCMenuItem.cpp @@ -180,13 +180,13 @@ bool MenuItemLabel::initWithLabel(Node* label, const ccMenuCallback& callback) MenuItemLabel::~MenuItemLabel() {} -void MenuItemLabel::setString(const std::string& label) +void MenuItemLabel::setString(std::string_view label) { dynamic_cast(_label)->setString(label); this->setContentSize(_label->getContentSize()); } -std::string MenuItemLabel::getString() const +std::string_view MenuItemLabel::getString() const { auto label = dynamic_cast(_label); return label->getString(); @@ -259,8 +259,8 @@ void MenuItemLabel::setEnabled(bool enabled) // CCMenuItemAtlasFont // -MenuItemAtlasFont* MenuItemAtlasFont::create(const std::string& value, - const std::string& charMapFile, +MenuItemAtlasFont* MenuItemAtlasFont::create(std::string_view value, + std::string_view charMapFile, int itemWidth, int itemHeight, char startCharMap) @@ -269,8 +269,8 @@ MenuItemAtlasFont* MenuItemAtlasFont::create(const std::string& value, (const ccMenuCallback&)nullptr); } -MenuItemAtlasFont* MenuItemAtlasFont::create(const std::string& value, - const std::string& charMapFile, +MenuItemAtlasFont* MenuItemAtlasFont::create(std::string_view value, + std::string_view charMapFile, int itemWidth, int itemHeight, char startCharMap, @@ -282,8 +282,8 @@ MenuItemAtlasFont* MenuItemAtlasFont::create(const std::string& value, return ret; } -bool MenuItemAtlasFont::initWithString(const std::string& value, - const std::string& charMapFile, +bool MenuItemAtlasFont::initWithString(std::string_view value, + std::string_view charMapFile, int itemWidth, int itemHeight, char startCharMap, @@ -312,7 +312,7 @@ int MenuItemFont::getFontSize() return _globalFontSize; } -void MenuItemFont::setFontName(const std::string& name) +void MenuItemFont::setFontName(std::string_view name) { if (_globalFontNameRelease) { @@ -322,12 +322,12 @@ void MenuItemFont::setFontName(const std::string& name) _globalFontNameRelease = true; } -const std::string& MenuItemFont::getFontName() +std::string_view MenuItemFont::getFontName() { return _globalFontName; } -MenuItemFont* MenuItemFont::create(const std::string& value, const ccMenuCallback& callback) +MenuItemFont* MenuItemFont::create(std::string_view value, const ccMenuCallback& callback) { MenuItemFont* ret = new MenuItemFont(); ret->initWithString(value, callback); @@ -335,7 +335,7 @@ MenuItemFont* MenuItemFont::create(const std::string& value, const ccMenuCallbac return ret; } -MenuItemFont* MenuItemFont::create(const std::string& value) +MenuItemFont* MenuItemFont::create(std::string_view value) { MenuItemFont* ret = new MenuItemFont(); ret->initWithString(value, (const ccMenuCallback&)nullptr); @@ -350,7 +350,7 @@ MenuItemFont::~MenuItemFont() CCLOGINFO("In the destructor of MenuItemFont (%p).", this); } -bool MenuItemFont::initWithString(const std::string& value, const ccMenuCallback& callback) +bool MenuItemFont::initWithString(std::string_view value, const ccMenuCallback& callback) { CCASSERT(!value.empty(), "Value length must be greater than 0"); @@ -377,14 +377,14 @@ int MenuItemFont::getFontSizeObj() const return _fontSize; } -void MenuItemFont::setFontNameObj(const std::string& name) +void MenuItemFont::setFontNameObj(std::string_view name) { _fontName = name; dynamic_cast(_label)->setSystemFontName(_fontName); this->setContentSize(dynamic_cast(_label)->getContentSize()); } -const std::string& MenuItemFont::getFontNameObj() const +std::string_view MenuItemFont::getFontNameObj() const { return _fontName; } @@ -600,21 +600,21 @@ bool MenuItemImage::init() return initWithNormalImage("", "", "", (const ccMenuCallback&)nullptr); } -MenuItemImage* MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage) +MenuItemImage* MenuItemImage::create(std::string_view normalImage, std::string_view selectedImage) { return MenuItemImage::create(normalImage, selectedImage, "", (const ccMenuCallback&)nullptr); } -MenuItemImage* MenuItemImage::create(const std::string& normalImage, - const std::string& selectedImage, +MenuItemImage* MenuItemImage::create(std::string_view normalImage, + std::string_view selectedImage, const ccMenuCallback& callback) { return MenuItemImage::create(normalImage, selectedImage, "", callback); } -MenuItemImage* MenuItemImage::create(const std::string& normalImage, - const std::string& selectedImage, - const std::string& disabledImage, +MenuItemImage* MenuItemImage::create(std::string_view normalImage, + std::string_view selectedImage, + std::string_view disabledImage, const ccMenuCallback& callback) { MenuItemImage* ret = new MenuItemImage(); @@ -627,9 +627,9 @@ MenuItemImage* MenuItemImage::create(const std::string& normalImage, return nullptr; } -MenuItemImage* MenuItemImage::create(const std::string& normalImage, - const std::string& selectedImage, - const std::string& disabledImage) +MenuItemImage* MenuItemImage::create(std::string_view normalImage, + std::string_view selectedImage, + std::string_view disabledImage) { MenuItemImage* ret = new MenuItemImage(); if (ret->initWithNormalImage(normalImage, selectedImage, disabledImage, (const ccMenuCallback&)nullptr)) @@ -641,9 +641,9 @@ MenuItemImage* MenuItemImage::create(const std::string& normalImage, return nullptr; } -bool MenuItemImage::initWithNormalImage(const std::string& normalImage, - const std::string& selectedImage, - const std::string& disabledImage, +bool MenuItemImage::initWithNormalImage(std::string_view normalImage, + std::string_view selectedImage, + std::string_view disabledImage, const ccMenuCallback& callback) { Node* normalSprite = nullptr; diff --git a/cocos/2d/CCMenuItem.h b/cocos/2d/CCMenuItem.h index a36b65aaf6..20639746c9 100644 --- a/cocos/2d/CCMenuItem.h +++ b/cocos/2d/CCMenuItem.h @@ -137,10 +137,10 @@ public: static MenuItemLabel* create(Node* label); /** Sets a new string to the inner label. */ - void setString(const std::string& label); + void setString(std::string_view label); /** Get the inner string of the inner label. */ - std::string getString() const; + std::string_view getString() const; /** Gets the color that will be used when the item is disabled. */ const Color3B& getDisabledColor() const { return _disabledColor; } @@ -196,14 +196,14 @@ class CC_DLL MenuItemAtlasFont : public MenuItemLabel { public: /** Creates a menu item from a string and atlas with a target/selector. */ - static MenuItemAtlasFont* create(const std::string& value, - const std::string& charMapFile, + static MenuItemAtlasFont* create(std::string_view value, + std::string_view charMapFile, int itemWidth, int itemHeight, char startCharMap); /** Creates a menu item from a string and atlas. Use it with MenuItemToggle. */ - static MenuItemAtlasFont* create(const std::string& value, - const std::string& charMapFile, + static MenuItemAtlasFont* create(std::string_view value, + std::string_view charMapFile, int itemWidth, int itemHeight, char startCharMap, @@ -222,8 +222,8 @@ public: virtual ~MenuItemAtlasFont() {} /** Initializes a menu item from a string and atlas with a target/selector. */ - bool initWithString(const std::string& value, - const std::string& charMapFile, + bool initWithString(std::string_view value, + std::string_view charMapFile, int itemWidth, int itemHeight, char startCharMap, @@ -240,18 +240,18 @@ class CC_DLL MenuItemFont : public MenuItemLabel { public: /** Creates a menu item from a string without target/selector. To be used with MenuItemToggle. */ - static MenuItemFont* create(const std::string& value = ""); + static MenuItemFont* create(std::string_view value = ""); /** Creates a menu item from a string with a target/selector. */ - static MenuItemFont* create(const std::string& value, const ccMenuCallback& callback); + static MenuItemFont* create(std::string_view value, const ccMenuCallback& callback); /** Set default font size. */ static void setFontSize(int size); /** Get default font size. */ static int getFontSize(); /** Set the default font name. */ - static void setFontName(const std::string& name); + static void setFontName(std::string_view name); /** Get the default font name. */ - static const std::string& getFontName(); + static std::string_view getFontName(); /** Set font size. * c++ can not overload static and non-static member functions with the same parameter types. @@ -274,13 +274,13 @@ public: * @js setFontName * @js NA */ - void setFontNameObj(const std::string& name); + void setFontNameObj(std::string_view name); /** Returns the name of the Font. * @js getFontNameObj * @js NA */ - const std::string& getFontNameObj() const; + std::string_view getFontNameObj() const; CC_CONSTRUCTOR_ACCESS : /** @@ -294,7 +294,7 @@ public: virtual ~MenuItemFont(); /** Initializes a menu item from a string with a target/selector. */ - bool initWithString(const std::string& value, const ccMenuCallback& callback); + bool initWithString(std::string_view value, const ccMenuCallback& callback); protected: int _fontSize; @@ -392,19 +392,19 @@ public: /** Creates an MenuItemImage. */ static MenuItemImage* create(); /** Creates a menu item with a normal and selected image.*/ - static MenuItemImage* create(const std::string& normalImage, const std::string& selectedImage); + static MenuItemImage* create(std::string_view normalImage, std::string_view selectedImage); /** Creates a menu item with a normal,selected and disabled image.*/ - static MenuItemImage* create(const std::string& normalImage, - const std::string& selectedImage, - const std::string& disabledImage); + static MenuItemImage* create(std::string_view normalImage, + std::string_view selectedImage, + std::string_view disabledImage); /** Creates a menu item with a normal and selected image with a callable object. */ - static MenuItemImage* create(const std::string& normalImage, - const std::string& selectedImage, + static MenuItemImage* create(std::string_view normalImage, + std::string_view selectedImage, const ccMenuCallback& callback); /** Creates a menu item with a normal,selected and disabled image with a callable object. */ - static MenuItemImage* create(const std::string& normalImage, - const std::string& selectedImage, - const std::string& disabledImage, + static MenuItemImage* create(std::string_view normalImage, + std::string_view selectedImage, + std::string_view disabledImage, const ccMenuCallback& callback); /** Sets the sprite frame for the normal image. */ @@ -429,9 +429,9 @@ public: bool init(); /** Initializes a menu item with a normal, selected and disabled image with a callable object. */ - bool initWithNormalImage(const std::string& normalImage, - const std::string& selectedImage, - const std::string& disabledImage, + bool initWithNormalImage(std::string_view normalImage, + std::string_view selectedImage, + std::string_view disabledImage, const ccMenuCallback& callback); private: diff --git a/cocos/2d/CCMotionStreak.cpp b/cocos/2d/CCMotionStreak.cpp index d92839e954..93833932a3 100644 --- a/cocos/2d/CCMotionStreak.cpp +++ b/cocos/2d/CCMotionStreak.cpp @@ -56,7 +56,7 @@ MotionStreak* MotionStreak::create(float fade, float minSeg, float stroke, const Color3B& color, - const std::string& path) + std::string_view path) { MotionStreak* ret = new MotionStreak(); if (ret->initWithFade(fade, minSeg, stroke, color, path)) @@ -82,7 +82,7 @@ MotionStreak* MotionStreak::create(float fade, float minSeg, float stroke, const return nullptr; } -bool MotionStreak::initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path) +bool MotionStreak::initWithFade(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path) { CCASSERT(!path.empty(), "Invalid filename"); diff --git a/cocos/2d/CCMotionStreak.h b/cocos/2d/CCMotionStreak.h index 07ab945dd5..7ce1ca2c74 100644 --- a/cocos/2d/CCMotionStreak.h +++ b/cocos/2d/CCMotionStreak.h @@ -59,7 +59,7 @@ public: float minSeg, float strokeWidth, const Color3B& strokeColor, - const std::string& imagePath); + std::string_view imagePath); /** Creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture. * * @param timeToFade The fade time, in seconds. @@ -163,7 +163,7 @@ public: /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture filename */ - bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path); + bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path); /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture */ bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture); diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index aa068ac8fd..49fa7a83f1 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -56,7 +56,7 @@ THE SOFTWARE. /* * 4.5x faster than std::hash in release mode */ -#define CC_HASH_NODE_NAME(name) (!name.empty() ? XXH3_64bits(name.c_str(), name.length()) : 0) +#define CC_HASH_NODE_NAME(name) (!name.empty() ? XXH3_64bits(name.data(), name.length()) : 0) NS_CC_BEGIN @@ -695,12 +695,12 @@ void Node::setTag(int tag) _tag = tag; } -const std::string& Node::getName() const +std::string_view Node::getName() const { return _name; } -void Node::setName(const std::string& name) +void Node::setName(std::string_view name) { updateParentChildrenIndexer(name); _name = name; @@ -717,7 +717,7 @@ void Node::updateParentChildrenIndexer(int tag) } } -void Node::updateParentChildrenIndexer(const std::string& name) +void Node::updateParentChildrenIndexer(std::string_view name) { uint64_t newHash = CC_HASH_NODE_NAME(name); auto parentChildrenIndexer = getParentChildrenIndexer(); @@ -817,7 +817,7 @@ Node* Node::getChildByTag(int tag) const return nullptr; } -Node* Node::getChildByName(const std::string& name) const +Node* Node::getChildByName(std::string_view name) const { // CCASSERT(!name.empty(), "Invalid name"); auto hash = CC_HASH_NODE_NAME(name); @@ -837,7 +837,7 @@ Node* Node::getChildByName(const std::string& name) const return nullptr; } -void Node::enumerateChildren(const std::string& name, std::function callback) const +void Node::enumerateChildren(std::string_view name, std::function callback) const { CCASSERT(!name.empty(), "Invalid name"); CCASSERT(callback != nullptr, "Invalid callback function"); @@ -865,7 +865,7 @@ void Node::enumerateChildren(const std::string& name, std::function } // Remove '//', '/..' if exist - std::string newName = name.substr(subStrStartPos, subStrlength); + auto newName = name.substr(subStrStartPos, subStrlength); const Node* target = this; @@ -886,15 +886,15 @@ void Node::enumerateChildren(const std::string& name, std::function else { // name is xxx - target->doEnumerate(newName, callback); + target->doEnumerate(std::string{newName}, callback); } } -bool Node::doEnumerateRecursive(const Node* node, const std::string& name, std::function callback) const +bool Node::doEnumerateRecursive(const Node* node, std::string_view name, std::function callback) const { bool ret = false; - if (node->doEnumerate(name, callback)) + if (node->doEnumerate(std::string{name}, callback)) { // search itself ret = true; @@ -966,7 +966,7 @@ void Node::addChild(Node* child, int localZOrder, int tag) addChildHelper(child, localZOrder, tag, "", true); } -void Node::addChild(Node* child, int localZOrder, const std::string& name) +void Node::addChild(Node* child, int localZOrder, std::string_view name) { CCASSERT(child != nullptr, "Argument must be non-nil"); CCASSERT(child->_parent == nullptr, "child already added. It can't be added again"); @@ -974,7 +974,7 @@ void Node::addChild(Node* child, int localZOrder, const std::string& name) addChildHelper(child, localZOrder, INVALID_TAG, name, false); } -void Node::addChildHelper(Node* child, int localZOrder, int tag, const std::string& name, bool setTag) +void Node::addChildHelper(Node* child, int localZOrder, int tag, std::string_view name, bool setTag) { auto assertNotSelfChild([this, child]() -> bool { for (Node* parent(getParent()); parent != nullptr; parent = parent->getParent()) @@ -1088,7 +1088,7 @@ void Node::removeChildByTag(int tag, bool cleanup /* = true */) } } -void Node::removeChildByName(const std::string& name, bool cleanup) +void Node::removeChildByName(std::string_view name, bool cleanup) { CCASSERT(!name.empty(), "Invalid name"); @@ -1096,7 +1096,7 @@ void Node::removeChildByName(const std::string& name, bool cleanup) if (child == nullptr) { - CCLOG("cocos2d: removeChildByName(name = %s): child not found!", name.c_str()); + CCLOG("cocos2d: removeChildByName(name = %s): child not found!", name.data()); } else { @@ -1490,7 +1490,7 @@ bool Node::isScheduled(SEL_SCHEDULE selector) const return _scheduler->isScheduled(selector, this); } -bool Node::isScheduled(const std::string& key) const +bool Node::isScheduled(std::string_view key) const { return _scheduler->isScheduled(key, this); } @@ -1547,12 +1547,12 @@ void Node::schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, _scheduler->schedule(selector, this, interval, repeat, delay, !_running); } -void Node::schedule(const std::function& callback, const std::string& key) +void Node::schedule(const std::function& callback, std::string_view key) { _scheduler->schedule(callback, this, 0, !_running, key); } -void Node::schedule(const std::function& callback, float interval, const std::string& key) +void Node::schedule(const std::function& callback, float interval, std::string_view key) { _scheduler->schedule(callback, this, interval, !_running, key); } @@ -1561,7 +1561,7 @@ void Node::schedule(const std::function& callback, float interval, unsigned int repeat, float delay, - const std::string& key) + std::string_view key) { _scheduler->schedule(callback, this, interval, repeat, delay, !_running, key); } @@ -1571,7 +1571,7 @@ void Node::scheduleOnce(SEL_SCHEDULE selector, float delay) this->schedule(selector, 0.0f, 0, delay); } -void Node::scheduleOnce(const std::function& callback, float delay, const std::string& key) +void Node::scheduleOnce(const std::function& callback, float delay, std::string_view key) { _scheduler->schedule(callback, this, 0, 0, delay, !_running, key); } @@ -1585,7 +1585,7 @@ void Node::unschedule(SEL_SCHEDULE selector) _scheduler->unschedule(selector, this); } -void Node::unschedule(const std::string& key) +void Node::unschedule(std::string_view key) { _scheduler->unschedule(key, this); } @@ -1923,7 +1923,7 @@ void Node::updateTransform() // MARK: components -Component* Node::getComponent(const std::string& name) +Component* Node::getComponent(std::string_view name) { if (_componentContainer) return _componentContainer->get(name); @@ -1943,7 +1943,7 @@ bool Node::addComponent(Component* component) return _componentContainer->add(component); } -bool Node::removeComponent(const std::string& name) +bool Node::removeComponent(std::string_view name) { if (_componentContainer) return _componentContainer->remove(name); diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index 01bd103303..9ebc5b5f67 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -762,7 +762,7 @@ public: * @param name A string to identify the node easily. Please refer to `setName(int)`. * */ - virtual void addChild(Node* child, int localZOrder, const std::string& name); + virtual void addChild(Node* child, int localZOrder, std::string_view name); /** * Gets a child from the container with its tag. * @@ -796,7 +796,7 @@ public: * * @since v3.2 */ - virtual Node* getChildByName(const std::string& name) const; + virtual Node* getChildByName(std::string_view name) const; /** * Gets a child from the container with its name that can be cast to Type T. * @@ -805,7 +805,7 @@ public: * @return a Node with the given name that can be cast to Type T. */ template - T getChildByName(const std::string& name) const + T getChildByName(std::string_view name) const { return static_cast(getChildByName(name)); } @@ -835,7 +835,7 @@ public: * * @since v3.2 */ - virtual void enumerateChildren(const std::string& name, std::function callback) const; + virtual void enumerateChildren(std::string_view name, std::function callback) const; /** * Returns the array of the node's children. * @@ -909,7 +909,7 @@ public: * @param name A string that identifies a child node. * @param cleanup True if all running actions and callbacks on the child node will be cleanup, false otherwise. */ - virtual void removeChildByName(const std::string& name, bool cleanup = true); + virtual void removeChildByName(std::string_view name, bool cleanup = true); /** * Removes all children from the container with a cleanup. * @@ -989,13 +989,13 @@ public: * * @since v3.2 */ - virtual const std::string& getName() const; + virtual std::string_view getName() const; /** Changes the name that is used to identify the node easily. * @param name A string that identifies the node. * * @since v3.2 */ - virtual void setName(const std::string& name); + virtual void setName(std::string_view name); /** * Returns a custom user data pointer. @@ -1306,7 +1306,7 @@ public: * @js NA * @lua NA */ - bool isScheduled(const std::string& key) const; + bool isScheduled(std::string_view key) const; /** * Schedules the "update" method. @@ -1385,7 +1385,7 @@ public: * @param key The key of the lambda function. To be used if you want to unschedule it. * @lua NA */ - void scheduleOnce(const std::function& callback, float delay, const std::string& key); + void scheduleOnce(const std::function& callback, float delay, std::string_view key); /** * Schedules a custom selector, the scheduled selector will be ticked every frame. @@ -1403,7 +1403,7 @@ public: * @param key The key of the lambda function. To be used if you want to unschedule it. * @lua NA */ - void schedule(const std::function& callback, const std::string& key); + void schedule(const std::function& callback, std::string_view key); /** * Schedules a lambda function. The scheduled lambda function will be called every "interval" seconds @@ -1413,7 +1413,7 @@ public: * @param key The key of the lambda function. To be used if you want to unschedule it * @lua NA */ - void schedule(const std::function& callback, float interval, const std::string& key); + void schedule(const std::function& callback, float interval, std::string_view key); /** * Schedules a lambda function. @@ -1430,7 +1430,7 @@ public: float interval, unsigned int repeat, float delay, - const std::string& key); + std::string_view key); /** * Unschedules a custom selector. @@ -1447,7 +1447,7 @@ public: * @param key The key of the lambda function to be unscheduled. * @lua NA */ - void unschedule(const std::string& key); + void unschedule(std::string_view key); /** * Unschedule all scheduled selectors and lambda functions: custom selectors, and the 'update' selector and lambda @@ -1633,7 +1633,7 @@ public: * @param name A given name of component. * @return The Component by name. */ - Component* getComponent(const std::string& name); + Component* getComponent(std::string_view name); /** * Adds a component. @@ -1649,7 +1649,7 @@ public: * @param name A given name of component. * @return True if removed success. */ - virtual bool removeComponent(const std::string& name); + virtual bool removeComponent(std::string_view name); /** * Removes a component by its pointer. @@ -1854,7 +1854,7 @@ protected: virtual void updateColor() {} bool doEnumerate(std::string name, std::function callback) const; - bool doEnumerateRecursive(const Node* node, const std::string& name, std::function callback) const; + bool doEnumerateRecursive(const Node* node, std::string_view name, std::function callback) const; // check whether this camera mask is visible by the current visiting camera bool isVisitableByVisitingCamera() const; @@ -1865,10 +1865,10 @@ protected: void updateRotation3D(); void updateParentChildrenIndexer(int tag); - void updateParentChildrenIndexer(const std::string& name); + void updateParentChildrenIndexer(std::string_view name); private: - void addChildHelper(Node* child, int localZOrder, int tag, const std::string& name, bool setTag); + void addChildHelper(Node* child, int localZOrder, int tag, std::string_view name, bool setTag); NodeIndexerMap_t* getParentChildrenIndexer(); diff --git a/cocos/2d/CCParallaxNode.cpp b/cocos/2d/CCParallaxNode.cpp index 7282e416a4..a2c04f4ec2 100644 --- a/cocos/2d/CCParallaxNode.cpp +++ b/cocos/2d/CCParallaxNode.cpp @@ -91,7 +91,7 @@ void ParallaxNode::addChild(Node* /*child*/, int /*zOrder*/, int /*tag*/) CCASSERT(0, "ParallaxNode: use addChild:z:parallaxRatio:positionOffset instead"); } -void ParallaxNode::addChild(Node* /*child*/, int /*zOrder*/, const std::string& /*name*/) +void ParallaxNode::addChild(Node* /*child*/, int /*zOrder*/, std::string_view /*name*/) { CCASSERT(0, "ParallaxNode: use addChild:z:parallaxRatio:positionOffset instead"); } diff --git a/cocos/2d/CCParallaxNode.h b/cocos/2d/CCParallaxNode.h index 577069ec82..409717a0e9 100644 --- a/cocos/2d/CCParallaxNode.h +++ b/cocos/2d/CCParallaxNode.h @@ -83,7 +83,7 @@ public: // Overrides // virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, const std::string& name) override; + virtual void addChild(Node* child, int zOrder, std::string_view name) override; virtual void removeChild(Node* child, bool cleanup) override; virtual void removeAllChildrenWithCleanup(bool cleanup) override; virtual void visit(Renderer* renderer, const Mat4& parentTransform, uint32_t parentFlags) override; diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index e91e27c5f6..e9f8edabb1 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -108,7 +108,7 @@ ParticleBatchNode* ParticleBatchNode::createWithTexture(Texture2D* tex, int capa * creation with File Image */ -ParticleBatchNode* ParticleBatchNode::create(const std::string& imageFile, int capacity /* = kParticleDefaultCapacity*/) +ParticleBatchNode* ParticleBatchNode::create(std::string_view imageFile, int capacity /* = kParticleDefaultCapacity*/) { ParticleBatchNode* p = new ParticleBatchNode(); if (p->initWithFile(imageFile, capacity)) @@ -140,7 +140,7 @@ bool ParticleBatchNode::initWithTexture(Texture2D* tex, int capacity) /* * init with FileImage */ -bool ParticleBatchNode::initWithFile(const std::string& fileImage, int capacity) +bool ParticleBatchNode::initWithFile(std::string_view fileImage, int capacity) { Texture2D* tex = _director->getTextureCache()->addImage(fileImage); return initWithTexture(tex, capacity); @@ -193,7 +193,7 @@ void ParticleBatchNode::addChild(Node* aChild, int zOrder, int tag) addChildByTagOrName(child, zOrder, tag, "", true); } -void ParticleBatchNode::addChild(Node* aChild, int zOrder, const std::string& name) +void ParticleBatchNode::addChild(Node* aChild, int zOrder, std::string_view name) { CCASSERT(aChild != nullptr, "Argument must be non-nullptr"); CCASSERT(dynamic_cast(aChild) != nullptr, @@ -208,7 +208,7 @@ void ParticleBatchNode::addChild(Node* aChild, int zOrder, const std::string& na void ParticleBatchNode::addChildByTagOrName(ParticleSystem* child, int zOrder, int tag, - const std::string& name, + std::string_view name, bool setTag) { // If this is the 1st children, then copy blending function @@ -251,7 +251,7 @@ void ParticleBatchNode::addChildByTagOrName(ParticleSystem* child, // faster // FIXME: or possibly using vertexZ for reordering, that would be fastest // this helper is almost equivalent to Node's addChild, but doesn't make use of the lazy sorting -int ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag, const std::string& name, bool setTag) +int ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag, std::string_view name, bool setTag) { CCASSERT(child != nullptr, "Argument must be non-nil"); CCASSERT(child->getParent() == nullptr, "child already added. It can't be added again"); diff --git a/cocos/2d/CCParticleBatchNode.h b/cocos/2d/CCParticleBatchNode.h index 442416209d..6ad5991e53 100644 --- a/cocos/2d/CCParticleBatchNode.h +++ b/cocos/2d/CCParticleBatchNode.h @@ -87,7 +87,7 @@ public: * @param capacity A capacity of particles. * @return An autoreleased ParticleBatchNode object. */ - static ParticleBatchNode* create(const std::string& fileImage, int capacity = kParticleDefaultCapacity); + static ParticleBatchNode* create(std::string_view fileImage, int capacity = kParticleDefaultCapacity); /** Inserts a child into the ParticleBatchNode. * @@ -127,7 +127,7 @@ public: using Node::addChild; virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, const std::string& name) override; + virtual void addChild(Node* child, int zOrder, std::string_view name) override; virtual void removeChild(Node* child, bool cleanup) override; virtual void reorderChild(Node* child, int zOrder) override; virtual void draw(Renderer* renderer, const Mat4& transform, uint32_t flags) override; @@ -163,15 +163,15 @@ public: /** initializes the particle system with the name of a file on disk (for a list of supported formats look at the * Texture2D class), a capacity of particles */ - bool initWithFile(const std::string& fileImage, int capacity); + bool initWithFile(std::string_view fileImage, int capacity); private: void updateAllAtlasIndexes(); void increaseAtlasCapacityTo(ssize_t quantity); int searchNewPositionInChildrenForZ(int z); void getCurrentIndex(int* oldIndex, int* newIndex, Node* child, int z); - int addChildHelper(ParticleSystem* child, int z, int aTag, const std::string& name, bool setTag); - void addChildByTagOrName(ParticleSystem* child, int z, int tag, const std::string& name, bool setTag); + int addChildHelper(ParticleSystem* child, int z, int aTag, std::string_view name, bool setTag); + void addChildByTagOrName(ParticleSystem* child, int z, int tag, std::string_view name, bool setTag); void updateBlendFunc(); void updateProgramStateTexture(); diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index 8a40ac94f1..b2820844ed 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -191,11 +191,6 @@ void ParticleData::release() Vector ParticleSystem::__allInstances; float ParticleSystem::__totalParticleCountFactor = 1.0f; -inline static const cocos2d::Value& optValue(const ValueMap& dictionary, const std::string& key) -{ - return dictionary.find(key) != dictionary.cend() ? dictionary.at(key) : cocos2d::Value::Null; -} - ParticleSystem::ParticleSystem() : _isBlendAdditive(false) , _isAutoRemoveOnFinish(false) @@ -250,7 +245,7 @@ ParticleSystem::ParticleSystem() } // implementation ParticleSystem -ParticleSystem* ParticleSystem::create(const std::string& plistFile) +ParticleSystem* ParticleSystem::create(std::string_view plistFile) { ParticleSystem* ret = new ParticleSystem(); if (ret->initWithFile(plistFile)) @@ -290,7 +285,7 @@ bool ParticleSystem::init() return initWithTotalParticles(150); } -bool ParticleSystem::initWithFile(const std::string& plistFile) +bool ParticleSystem::initWithFile(std::string_view plistFile) { bool ret = false; _plistFile = FileUtils::getInstance()->fullPathForFilename(plistFile); @@ -299,7 +294,7 @@ bool ParticleSystem::initWithFile(const std::string& plistFile) CCASSERT(!dict.empty(), "Particles: file not found"); // FIXME: compute path from a path, should define a function somewhere to do it - string listFilePath = plistFile; + auto listFilePath = plistFile; if (listFilePath.find('/') != string::npos) { listFilePath = listFilePath.substr(0, listFilePath.rfind('/') + 1); @@ -318,7 +313,7 @@ bool ParticleSystem::initWithDictionary(const ValueMap& dictionary) return initWithDictionary(dictionary, ""); } -bool ParticleSystem::initWithDictionary(const ValueMap& dictionary, const std::string& dirname) +bool ParticleSystem::initWithDictionary(const ValueMap& dictionary, std::string_view dirname) { bool ret = false; unsigned char* buffer = nullptr; @@ -487,12 +482,12 @@ bool ParticleSystem::initWithDictionary(const ValueMap& dictionary, const std::s if (!dirname.empty() && textureDir != dirname) { textureName = textureName.substr(rPos + 1); - textureName = dirname + textureName; + textureName.insert(0, dirname); // textureName = dirname + textureName; } } else if (!dirname.empty() && !textureName.empty()) { - textureName = dirname + textureName; + textureName.insert(0, dirname); // textureName = dirname + textureName; } Texture2D* tex = nullptr; diff --git a/cocos/2d/CCParticleSystem.h b/cocos/2d/CCParticleSystem.h index 558cf87111..6e9dcff08c 100644 --- a/cocos/2d/CCParticleSystem.h +++ b/cocos/2d/CCParticleSystem.h @@ -237,7 +237,7 @@ public: * @param plistFile Particle plist file name. * @return An autoreleased ParticleSystem object. */ - static ParticleSystem* create(const std::string& plistFile); + static ParticleSystem* create(std::string_view plistFile); /** Create a system with a fixed number of particles. * @@ -761,7 +761,7 @@ public: */ virtual const BlendFunc& getBlendFunc() const override; - const std::string& getResourceFile() const { return _plistFile; } + std::string_view getResourceFile() const { return _plistFile; } /// @{ /// @name implement Playable Protocol @@ -793,7 +793,7 @@ public: http://particledesigner.71squared.com/ @since v0.99.3 */ - bool initWithFile(const std::string& plistFile); + bool initWithFile(std::string_view plistFile); /** initializes a QuadParticleSystem from a Dictionary. @since v0.99.3 @@ -803,7 +803,7 @@ public: /** initializes a particle system from a NSDictionary and the path from where to load the png @since v2.1 */ - bool initWithDictionary(const ValueMap& dictionary, const std::string& dirname); + bool initWithDictionary(const ValueMap& dictionary, std::string_view dirname); //! Initializes a system with a fixed number of particles virtual bool initWithTotalParticles(int numberOfParticles); diff --git a/cocos/2d/CCParticleSystemQuad.cpp b/cocos/2d/CCParticleSystemQuad.cpp index 17e1b7de46..0c87d08083 100644 --- a/cocos/2d/CCParticleSystemQuad.cpp +++ b/cocos/2d/CCParticleSystemQuad.cpp @@ -91,7 +91,7 @@ ParticleSystemQuad::~ParticleSystemQuad() // implementation ParticleSystemQuad -ParticleSystemQuad* ParticleSystemQuad::create(const std::string& filename) +ParticleSystemQuad* ParticleSystemQuad::create(std::string_view filename) { ParticleSystemQuad* ret = new ParticleSystemQuad(); if (ret->initWithFile(filename)) diff --git a/cocos/2d/CCParticleSystemQuad.h b/cocos/2d/CCParticleSystemQuad.h index 5ab1210352..65229bd27f 100644 --- a/cocos/2d/CCParticleSystemQuad.h +++ b/cocos/2d/CCParticleSystemQuad.h @@ -75,7 +75,7 @@ public: * @param filename Particle plist file name. * @return An autoreleased ParticleSystemQuad object. */ - static ParticleSystemQuad* create(const std::string& filename); + static ParticleSystemQuad* create(std::string_view filename); /** Creates a Particle Emitter with a dictionary. * * @param dictionary Particle dictionary. diff --git a/cocos/2d/CCPlistSpriteSheetLoader.cpp b/cocos/2d/CCPlistSpriteSheetLoader.cpp index 93a2a975e7..98eef1d152 100644 --- a/cocos/2d/CCPlistSpriteSheetLoader.cpp +++ b/cocos/2d/CCPlistSpriteSheetLoader.cpp @@ -18,7 +18,7 @@ using namespace std; NS_CC_BEGIN -void PlistSpriteSheetLoader::load(const std::string& filePath, SpriteFrameCache& cache) +void PlistSpriteSheetLoader::load(std::string_view filePath, SpriteFrameCache& cache) { CCASSERT(!filePath.empty(), "plist filename should not be nullptr"); @@ -26,7 +26,7 @@ void PlistSpriteSheetLoader::load(const std::string& filePath, SpriteFrameCache& if (fullPath.empty()) { // return if plist file doesn't exist - CCLOG("cocos2d: SpriteFrameCache: can not find %s", filePath.c_str()); + CCLOG("cocos2d: SpriteFrameCache: can not find %s", filePath.data()); return; } @@ -66,7 +66,7 @@ void PlistSpriteSheetLoader::load(const std::string& filePath, SpriteFrameCache& addSpriteFramesWithDictionary(dict, texturePath, filePath, cache); } -void PlistSpriteSheetLoader::load(const std::string& filePath, Texture2D* texture, SpriteFrameCache& cache) +void PlistSpriteSheetLoader::load(std::string_view filePath, Texture2D* texture, SpriteFrameCache& cache) { const auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); @@ -74,8 +74,8 @@ void PlistSpriteSheetLoader::load(const std::string& filePath, Texture2D* textur addSpriteFramesWithDictionary(dict, texture, filePath, cache); } -void PlistSpriteSheetLoader::load(const std::string& filePath, - const std::string& textureFileName, +void PlistSpriteSheetLoader::load(std::string_view filePath, + std::string_view textureFileName, SpriteFrameCache& cache) { CCASSERT(!textureFileName.empty(), "texture name should not be null"); @@ -98,7 +98,7 @@ void PlistSpriteSheetLoader::load(const Data& content, Texture2D* texture, Sprit addSpriteFramesWithDictionary(dict, texture, "by#addSpriteFramesWithFileContent()", cache); } -void PlistSpriteSheetLoader::reload(const std::string& filePath, SpriteFrameCache& cache) +void PlistSpriteSheetLoader::reload(std::string_view filePath, SpriteFrameCache& cache) { const auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); @@ -151,7 +151,7 @@ void PlistSpriteSheetLoader::reload(const std::string& filePath, SpriteFrameCach void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, Texture2D* texture, - const std::string& plist, + std::string_view plist, SpriteFrameCache& cache) { /* @@ -178,15 +178,15 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, Vec2 textureSize; // get the format - auto metaItr = dictionary.find("metadata"); + auto metaItr = dictionary.find("metadata"sv); if (metaItr != dictionary.end()) { auto& metadataDict = metaItr->second.asValueMap(); - format = metadataDict["format"].asInt(); + format = optValue(metadataDict, "format"sv).asInt(); - if (metadataDict.find("size") != metadataDict.end()) + if (metadataDict.find("size"sv) != metadataDict.end()) { - textureSize = SizeFromString(metadataDict["size"].asString()); + textureSize = SizeFromString(optValue(metadataDict, "size"sv).asString()); } } @@ -210,14 +210,14 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, if (format == 0) { - auto x = frameDict["x"].asFloat(); - auto y = frameDict["y"].asFloat(); - auto w = frameDict["width"].asFloat(); - auto h = frameDict["height"].asFloat(); - auto ox = frameDict["offsetX"].asFloat(); - auto oy = frameDict["offsetY"].asFloat(); - auto ow = frameDict["originalWidth"].asInt(); - auto oh = frameDict["originalHeight"].asInt(); + auto x = optValue(frameDict, "x"sv).asFloat(); + auto y = optValue(frameDict, "y"sv).asFloat(); + auto w = optValue(frameDict, "width"sv).asFloat(); + auto h = optValue(frameDict, "height"sv).asFloat(); + auto ox = optValue(frameDict, "offsetX"sv).asFloat(); + auto oy = optValue(frameDict, "offsetY"sv).asFloat(); + auto ow = optValue(frameDict, "originalWidth"sv).asInt(); + auto oh = optValue(frameDict, "originalHeight"sv).asInt(); // check ow/oh if (!ow || !oh) { @@ -234,17 +234,17 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, } else if (format == 1 || format == 2) { - auto frame = RectFromString(frameDict["frame"].asString()); + auto frame = RectFromString(optValue(frameDict, "frame"sv).asString()); auto rotated = false; // rotation if (format == 2) { - rotated = frameDict["rotated"].asBool(); + rotated = optValue(frameDict, "rotated"sv).asBool(); } - auto offset = PointFromString(frameDict["offset"].asString()); - auto sourceSize = SizeFromString(frameDict["sourceSize"].asString()); + auto offset = PointFromString(optValue(frameDict, "offset"sv).asString()); + auto sourceSize = SizeFromString(optValue(frameDict, "sourceSize"sv).asString()); // create frame spriteFrame = SpriteFrame::createWithTexture(texture, frame, rotated, offset, sourceSize); @@ -252,14 +252,14 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, else if (format == 3) { // get values - auto spriteSize = SizeFromString(frameDict["spriteSize"].asString()); - auto spriteOffset = PointFromString(frameDict["spriteOffset"].asString()); - auto spriteSourceSize = SizeFromString(frameDict["spriteSourceSize"].asString()); - auto textureRect = RectFromString(frameDict["textureRect"].asString()); - auto textureRotated = frameDict["textureRotated"].asBool(); + auto spriteSize = SizeFromString(optValue(frameDict, "spriteSize"sv).asString()); + auto spriteOffset = PointFromString(optValue(frameDict, "spriteOffset"sv).asString()); + auto spriteSourceSize = SizeFromString(optValue(frameDict, "spriteSourceSize"sv).asString()); + auto textureRect = RectFromString(optValue(frameDict, "textureRect"sv).asString()); + auto textureRotated = optValue(frameDict, "textureRotated"sv).asBool(); // get aliases - auto& aliases = frameDict["aliases"].asValueVector(); + auto& aliases = optValue(frameDict, "aliases"sv).asValueVector(); for (const auto& value : aliases) { @@ -282,9 +282,9 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, if (frameDict.find("vertices") != frameDict.end()) { using cocos2d::utils::parseIntegerList; - auto vertices = parseIntegerList(frameDict["vertices"].asString()); - auto verticesUV = parseIntegerList(frameDict["verticesUV"].asString()); - auto indices = parseIntegerList(frameDict["triangles"].asString()); + auto vertices = parseIntegerList(optValue(frameDict, "vertices"sv).asString()); + auto verticesUV = parseIntegerList(optValue(frameDict, "verticesUV"sv).asString()); + auto indices = parseIntegerList(optValue(frameDict, "triangles"sv).asString()); PolygonInfo info; initializePolygonInfo(textureSize, spriteSourceSize, vertices, verticesUV, indices, info); @@ -292,7 +292,7 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, } if (frameDict.find("anchor") != frameDict.end()) { - spriteFrame->setAnchorPoint(PointFromString(frameDict["anchor"].asString())); + spriteFrame->setAnchorPoint(PointFromString(optValue(frameDict, "anchor"sv).asString())); } } @@ -323,8 +323,8 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, } void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dict, - const std::string& texturePath, - const std::string& plist, + std::string_view texturePath, + std::string_view plist, SpriteFrameCache& cache) { std::string pixelFormatName; @@ -378,7 +378,7 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dict, void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict, Texture2D* texture, - const std::string& plist, + std::string_view plist, SpriteFrameCache& cache) { auto& framesDict = dict["frames"].asValueMap(); @@ -401,8 +401,8 @@ void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict, for (auto& iter : framesDict) { - ValueMap& frameDict = iter.second.asValueMap(); - std::string spriteFrameName = iter.first; + const ValueMap& frameDict = iter.second.asValueMap(); + std::string_view spriteFrameName = iter.first; cache.eraseFrame(spriteFrameName); @@ -411,14 +411,14 @@ void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict, if (format == 0) { - const auto x = frameDict["x"].asFloat(); - const auto y = frameDict["y"].asFloat(); - const auto w = frameDict["width"].asFloat(); - const auto h = frameDict["height"].asFloat(); - const auto ox = frameDict["offsetX"].asFloat(); - const auto oy = frameDict["offsetY"].asFloat(); - auto ow = frameDict["originalWidth"].asInt(); - auto oh = frameDict["originalHeight"].asInt(); + const auto x = optValue(frameDict, "x"sv).asFloat(); + const auto y = optValue(frameDict, "y"sv).asFloat(); + const auto w = optValue(frameDict, "width"sv).asFloat(); + const auto h = optValue(frameDict, "height"sv).asFloat(); + const auto ox = optValue(frameDict, "offsetX"sv).asFloat(); + const auto oy = optValue(frameDict, "offsetY"sv).asFloat(); + auto ow = optValue(frameDict, "originalWidth"sv).asInt(); + auto oh = optValue(frameDict, "originalHeight"sv).asInt(); // check ow/oh if (!ow || !oh) { @@ -435,17 +435,17 @@ void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict, } else if (format == 1 || format == 2) { - auto frame = RectFromString(frameDict["frame"].asString()); + auto frame = RectFromString(optValue(frameDict, "frame"sv).asString()); auto rotated = false; // rotation if (format == 2) { - rotated = frameDict["rotated"].asBool(); + rotated = optValue(frameDict, "rotated"sv).asBool(); } - auto offset = PointFromString(frameDict["offset"].asString()); - auto sourceSize = SizeFromString(frameDict["sourceSize"].asString()); + auto offset = PointFromString(optValue(frameDict, "offset"sv).asString()); + auto sourceSize = SizeFromString(optValue(frameDict, "sourceSize"sv).asString()); // create frame spriteFrame = SpriteFrame::createWithTexture(texture, frame, rotated, offset, sourceSize); @@ -453,14 +453,14 @@ void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict, else if (format == 3) { // get values - const auto spriteSize = SizeFromString(frameDict["spriteSize"].asString()); - auto spriteOffset = PointFromString(frameDict["spriteOffset"].asString()); - auto spriteSourceSize = SizeFromString(frameDict["spriteSourceSize"].asString()); - const auto textureRect = RectFromString(frameDict["textureRect"].asString()); - const auto textureRotated = frameDict["textureRotated"].asBool(); + const auto spriteSize = SizeFromString(optValue(frameDict, "spriteSize"sv).asString()); + auto spriteOffset = PointFromString(optValue(frameDict, "spriteOffset"sv).asString()); + auto spriteSourceSize = SizeFromString(optValue(frameDict, "spriteSourceSize"sv).asString()); + const auto textureRect = RectFromString(optValue(frameDict, "textureRect"sv).asString()); + const auto textureRotated = optValue(frameDict, "textureRotated"sv).asBool(); // get aliases - ValueVector& aliases = frameDict["aliases"].asValueVector(); + const ValueVector& aliases = optValue(frameDict, "aliases"sv).asValueVector(); for (const auto& value : aliases) { diff --git a/cocos/2d/CCPlistSpriteSheetLoader.h b/cocos/2d/CCPlistSpriteSheetLoader.h index 79aa405400..6f36caad0b 100644 --- a/cocos/2d/CCPlistSpriteSheetLoader.h +++ b/cocos/2d/CCPlistSpriteSheetLoader.h @@ -14,30 +14,30 @@ public: static constexpr uint32_t FORMAT = SpriteSheetFormat::PLIST; uint32_t getFormat() override { return FORMAT; } - void load(const std::string& filePath, SpriteFrameCache& cache) override; - void load(const std::string& filePath, Texture2D* texture, SpriteFrameCache& cache) override; - void load(const std::string& filePath, const std::string& textureFileName, SpriteFrameCache& cache) override; + void load(std::string_view filePath, SpriteFrameCache& cache) override; + void load(std::string_view filePath, Texture2D* texture, SpriteFrameCache& cache) override; + void load(std::string_view filePath, std::string_view textureFileName, SpriteFrameCache& cache) override; void load(const Data& content, Texture2D* texture, SpriteFrameCache& cache) override; - void reload(const std::string& filePath, SpriteFrameCache& cache) override; + void reload(std::string_view filePath, SpriteFrameCache& cache) override; protected: /*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames. */ void addSpriteFramesWithDictionary(ValueMap& dictionary, Texture2D* texture, - const std::string& plist, + std::string_view plist, SpriteFrameCache& cache); /*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames. */ void addSpriteFramesWithDictionary(ValueMap& dict, - const std::string& texturePath, - const std::string& plist, + std::string_view texturePath, + std::string_view plist, SpriteFrameCache& cache); void reloadSpriteFramesWithDictionary(ValueMap& dict, Texture2D* texture, - const std::string& plist, + std::string_view plist, SpriteFrameCache& cache); }; diff --git a/cocos/2d/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp index 067237e12e..7525359dbf 100644 --- a/cocos/2d/CCRenderTexture.cpp +++ b/cocos/2d/CCRenderTexture.cpp @@ -357,9 +357,7 @@ void RenderTexture::visit(Renderer* renderer, const Mat4& parentTransform, uint3 // setOrderOfArrival(0); } -bool RenderTexture::saveToFileAsNonPMA(const std::string& filename, - bool isRGBA, - std::function callback) +bool RenderTexture::saveToFileAsNonPMA(std::string_view filename, bool isRGBA, SaveFileCallbackType callback) { std::string basename(filename); std::transform(basename.begin(), basename.end(), basename.begin(), ::tolower); @@ -382,9 +380,7 @@ bool RenderTexture::saveToFileAsNonPMA(const std::string& filename, return saveToFileAsNonPMA(filename, Image::Format::JPG, false, callback); } -bool RenderTexture::saveToFile(const std::string& filename, - bool isRGBA, - std::function callback) +bool RenderTexture::saveToFile(std::string_view filename, bool isRGBA, SaveFileCallbackType callback) { std::string basename(filename); std::transform(basename.begin(), basename.end(), basename.begin(), ::tolower); @@ -407,10 +403,10 @@ bool RenderTexture::saveToFile(const std::string& filename, return saveToFile(filename, Image::Format::JPG, false, callback); } -bool RenderTexture::saveToFileAsNonPMA(const std::string& fileName, +bool RenderTexture::saveToFileAsNonPMA(std::string_view fileName, Image::Format format, bool isRGBA, - std::function callback) + SaveFileCallbackType callback) { CCASSERT(format == Image::Format::JPG || format == Image::Format::PNG, "the image can only be saved as JPG or PNG format"); @@ -419,7 +415,7 @@ bool RenderTexture::saveToFileAsNonPMA(const std::string& fileName, _saveFileCallback = callback; - std::string fullpath = FileUtils::getInstance()->getWritablePath() + fileName; + std::string fullpath = FileUtils::getInstance()->getWritablePath().append(fileName); _saveToFileCommand.init(_globalZOrder); _saveToFileCommand.func = CC_CALLBACK_0(RenderTexture::onSaveToFile, this, fullpath, isRGBA, true); @@ -427,10 +423,10 @@ bool RenderTexture::saveToFileAsNonPMA(const std::string& fileName, return true; } -bool RenderTexture::saveToFile(const std::string& fileName, +bool RenderTexture::saveToFile(std::string_view fileName, Image::Format format, bool isRGBA, - std::function callback) + std::function callback) { CCASSERT(format == Image::Format::JPG || format == Image::Format::PNG, "the image can only be saved as JPG or PNG format"); @@ -439,7 +435,7 @@ bool RenderTexture::saveToFile(const std::string& fileName, _saveFileCallback = callback; - std::string fullpath = FileUtils::getInstance()->getWritablePath() + fileName; + std::string fullpath = FileUtils::getInstance()->getWritablePath().append(fileName); _saveToFileCommand.init(_globalZOrder); _saveToFileCommand.func = CC_CALLBACK_0(RenderTexture::onSaveToFile, this, fullpath, isRGBA, false); @@ -447,7 +443,7 @@ bool RenderTexture::saveToFile(const std::string& fileName, return true; } -void RenderTexture::onSaveToFile(const std::string& filename, bool isRGBA, bool forceNonPMA) +void RenderTexture::onSaveToFile(std::string_view filename, bool isRGBA, bool forceNonPMA) { auto callbackFunc = [&, filename, isRGBA, forceNonPMA](RefPtr image) { if (image) diff --git a/cocos/2d/CCRenderTexture.h b/cocos/2d/CCRenderTexture.h index 0fdfb5f543..b43e9c380b 100644 --- a/cocos/2d/CCRenderTexture.h +++ b/cocos/2d/CCRenderTexture.h @@ -61,6 +61,7 @@ class EventCustom; class CC_DLL RenderTexture : public Node { public: + using SaveFileCallbackType = std::function; /** Initializes a RenderTexture object with width and height in Points and a pixel format( only RGB and RGBA formats * are valid ) and depthStencil format. * @@ -171,9 +172,7 @@ public: * @param callback When the file is save finished,it will callback this function. * @return Returns true if the operation is successful. */ - bool saveToFileAsNonPMA(const std::string& filename, - bool isRGBA = true, - std::function callback = nullptr); + bool saveToFileAsNonPMA(std::string_view filename, bool isRGBA = true, SaveFileCallbackType = nullptr); /** Saves the texture into a file using JPEG format. The file will be saved in the Documents folder. * Returns true if the operation is successful. @@ -183,9 +182,7 @@ public: * @param callback When the file is save finished,it will callback this function. * @return Returns true if the operation is successful. */ - bool saveToFile(const std::string& filename, - bool isRGBA = true, - std::function callback = nullptr); + bool saveToFile(std::string_view filename, bool isRGBA = true, SaveFileCallbackType = nullptr); /** saves the texture into a file in non-PMA. The format could be JPG or PNG. The file will be saved in the Documents folder. Returns true if the operation is successful. @@ -201,10 +198,10 @@ public: * @param callback When the file is save finished,it will callback this function. * @return Returns true if the operation is successful. */ - bool saveToFileAsNonPMA(const std::string& fileName, + bool saveToFileAsNonPMA(std::string_view fileName, Image::Format format, bool isRGBA, - std::function callback); + SaveFileCallbackType callback); /** saves the texture into a file. The format could be JPG or PNG. The file will be saved in the Documents folder. Returns true if the operation is successful. @@ -220,10 +217,10 @@ public: * @param callback When the file is save finished,it will callback this function. * @return Returns true if the operation is successful. */ - bool saveToFile(const std::string& filename, + bool saveToFile(std::string_view filename, Image::Format format, - bool isRGBA = true, - std::function callback = nullptr); + bool isRGBA = true, + SaveFileCallbackType callback = nullptr); /** Listen "come to background" message, and save render texture. * It only has effect on Android. @@ -367,7 +364,7 @@ protected: void onEnd(); void clearColorAttachment(); - void onSaveToFile(const std::string& fileName, bool isRGBA = true, bool forceNonPMA = false); + void onSaveToFile(std::string_view fileName, bool isRGBA = true, bool forceNonPMA = false); bool _keepMatrix = false; Rect _rtTextureRect; @@ -411,7 +408,7 @@ protected: and the command and callback will be executed twice. */ CallbackCommand _saveToFileCommand; - std::function _saveFileCallback = nullptr; + std::function _saveFileCallback = nullptr; Mat4 _oldTransMatrix, _oldProjMatrix; Mat4 _transformMatrix, _projectionMatrix; diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index f5e87fcd73..2a97c4f247 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -72,7 +72,7 @@ Sprite* Sprite::createWithTexture(Texture2D* texture, const Rect& rect, bool rot return nullptr; } -Sprite* Sprite::create(const std::string& filename) +Sprite* Sprite::create(std::string_view filename) { Sprite* sprite = new Sprite(); if (sprite->initWithFile(filename)) @@ -96,7 +96,7 @@ Sprite* Sprite::create(const PolygonInfo& info) return nullptr; } -Sprite* Sprite::create(const std::string& filename, const Rect& rect) +Sprite* Sprite::create(std::string_view filename, const Rect& rect) { Sprite* sprite = new Sprite(); if (sprite->initWithFile(filename, rect)) @@ -120,13 +120,13 @@ Sprite* Sprite::createWithSpriteFrame(SpriteFrame* spriteFrame) return nullptr; } -Sprite* Sprite::createWithSpriteFrameName(const std::string& spriteFrameName) +Sprite* Sprite::createWithSpriteFrameName(std::string_view spriteFrameName) { SpriteFrame* frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); #if COCOS2D_DEBUG > 0 char msg[256] = {0}; - sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName.c_str()); + sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName.data()); CCASSERT(frame != nullptr, msg); #endif @@ -167,7 +167,7 @@ bool Sprite::initWithTexture(Texture2D* texture, const Rect& rect) return initWithTexture(texture, rect, false); } -bool Sprite::initWithFile(const std::string& filename) +bool Sprite::initWithFile(std::string_view filename) { if (filename.empty()) { @@ -191,7 +191,7 @@ bool Sprite::initWithFile(const std::string& filename) return false; } -bool Sprite::initWithFile(const std::string& filename, const Rect& rect) +bool Sprite::initWithFile(std::string_view filename, const Rect& rect) { CCASSERT(!filename.empty(), "Invalid filename"); if (filename.empty()) @@ -209,7 +209,7 @@ bool Sprite::initWithFile(const std::string& filename, const Rect& rect) return false; } -bool Sprite::initWithSpriteFrameName(const std::string& spriteFrameName) +bool Sprite::initWithSpriteFrameName(std::string_view spriteFrameName) { CCASSERT(!spriteFrameName.empty(), "Invalid spriteFrameName"); if (spriteFrameName.empty()) @@ -332,7 +332,7 @@ static unsigned char cc_2x2_white_image[] = { #define CC_2x2_WHITE_IMAGE_KEY "/cc_2x2_white_image" // MARK: texture -void Sprite::setTexture(const std::string& filename) +void Sprite::setTexture(std::string_view filename) { Texture2D* texture = _director->getTextureCache()->addImage(filename); setTexture(texture); @@ -1132,7 +1132,7 @@ void Sprite::addChild(Node* child, int zOrder, int tag) Node::addChild(child, zOrder, tag); } -void Sprite::addChild(Node* child, int zOrder, const std::string& name) +void Sprite::addChild(Node* child, int zOrder, std::string_view name) { CCASSERT(child != nullptr, "Argument must be non-nullptr"); if (child == nullptr) @@ -1539,7 +1539,7 @@ bool Sprite::isOpacityModifyRGB() const // MARK: Frames -void Sprite::setSpriteFrame(const std::string& spriteFrameName) +void Sprite::setSpriteFrame(std::string_view spriteFrameName) { CCASSERT(!spriteFrameName.empty(), "spriteFrameName must not be empty"); if (spriteFrameName.empty()) @@ -1590,7 +1590,7 @@ void Sprite::setSpriteFrame(SpriteFrame* spriteFrame) setCenterRect(spriteFrame->getCenterRect()); } -void Sprite::setDisplayFrameWithAnimationName(const std::string& animationName, unsigned int frameIndex) +void Sprite::setDisplayFrameWithAnimationName(std::string_view animationName, unsigned int frameIndex) { CCASSERT(!animationName.empty(), "CCSprite#setDisplayFrameWithAnimationName. animationName must not be nullptr"); if (animationName.empty()) diff --git a/cocos/2d/CCSprite.h b/cocos/2d/CCSprite.h index e81f18064e..d993a6fef2 100644 --- a/cocos/2d/CCSprite.h +++ b/cocos/2d/CCSprite.h @@ -129,7 +129,7 @@ public: * @param filename A path to image file, e.g., "scene1/monster.png". * @return An autoreleased sprite object. */ - static Sprite* create(const std::string& filename); + static Sprite* create(std::string_view filename); /** * Creates a polygon sprite with a polygon info. @@ -149,7 +149,7 @@ public: * @param rect A subrect of the image file. * @return An autoreleased sprite object. */ - static Sprite* create(const std::string& filename, const Rect& rect); + static Sprite* create(std::string_view filename, const Rect& rect); /** * Creates a sprite with a Texture2D object. @@ -191,7 +191,7 @@ public: * @param spriteFrameName The name of sprite frame. * @return An autoreleased sprite object. */ - static Sprite* createWithSpriteFrameName(const std::string& spriteFrameName); + static Sprite* createWithSpriteFrameName(std::string_view spriteFrameName); // end of creators group /// @} @@ -233,7 +233,7 @@ public: * @memberof Sprite * It will call `setTextureRect()` with the texture's content size. */ - virtual void setTexture(const std::string& filename); + virtual void setTexture(std::string_view filename); /** @overload * @@ -304,7 +304,7 @@ public: /** @{ * Sets a new SpriteFrame to the Sprite. */ - virtual void setSpriteFrame(const std::string& spriteFrameName); + virtual void setSpriteFrame(std::string_view spriteFrameName); virtual void setSpriteFrame(SpriteFrame* newFrame); /** @} */ @@ -326,7 +326,7 @@ public: * Changes the display frame with animation name and index. * The animation name will be get from the AnimationCache. */ - virtual void setDisplayFrameWithAnimationName(const std::string& animationName, unsigned int frameIndex); + virtual void setDisplayFrameWithAnimationName(std::string_view animationName, unsigned int frameIndex); /// @} /// @{ @@ -370,7 +370,7 @@ public: virtual void reorderChild(Node* child, int zOrder) override; using Node::addChild; virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, const std::string& name) override; + virtual void addChild(Node* child, int zOrder, std::string_view name) override; virtual void sortAllChildren() override; virtual void setScale(float scale) override; virtual void setPositionZ(float positionZ) override; @@ -513,7 +513,7 @@ public: /// @} int getResourceType() const { return _fileType; } - const std::string& getResourceName() const { return _fileName; } + std::string_view getResourceName() const { return _fileName; } CC_CONSTRUCTOR_ACCESS : /** @@ -588,7 +588,7 @@ public: * @param spriteFrameName A key string that can fetched a valid SpriteFrame from SpriteFrameCache. * @return True if the sprite is initialized properly, false otherwise. */ - virtual bool initWithSpriteFrameName(const std::string& spriteFrameName); + virtual bool initWithSpriteFrameName(std::string_view spriteFrameName); /** * Initializes a sprite with an image filename. @@ -601,7 +601,7 @@ public: * @return True if the sprite is initialized properly, false otherwise. * @lua init */ - virtual bool initWithFile(const std::string& filename); + virtual bool initWithFile(std::string_view filename); /** * Initializes a sprite with an image filename, and a rect. @@ -615,7 +615,7 @@ public: * @return True if the sprite is initialized properly, false otherwise. * @lua init */ - virtual bool initWithFile(const std::string& filename, const Rect& rect); + virtual bool initWithFile(std::string_view filename, const Rect& rect); virtual void setVertexLayout(); diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index c2c809c518..4888ac8b5f 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -64,7 +64,7 @@ SpriteBatchNode* SpriteBatchNode::createWithTexture(Texture2D* tex, ssize_t capa * creation with File Image */ -SpriteBatchNode* SpriteBatchNode::create(const std::string& fileImage, ssize_t capacity /* = DEFAULT_CAPACITY*/) +SpriteBatchNode* SpriteBatchNode::create(std::string_view fileImage, ssize_t capacity /* = DEFAULT_CAPACITY*/) { SpriteBatchNode* batchNode = new SpriteBatchNode(); if (batchNode->initWithFile(fileImage, capacity)) @@ -168,7 +168,7 @@ bool SpriteBatchNode::init() /* * init with FileImage */ -bool SpriteBatchNode::initWithFile(const std::string& fileImage, ssize_t capacity /* = DEFAULT_CAPACITY*/) +bool SpriteBatchNode::initWithFile(std::string_view fileImage, ssize_t capacity /* = DEFAULT_CAPACITY*/) { Texture2D* texture2D = _director->getTextureCache()->addImage(fileImage); return initWithTexture(texture2D, capacity); @@ -236,7 +236,7 @@ void SpriteBatchNode::addChild(Node* child, int zOrder, int tag) appendChild(sprite); } -void SpriteBatchNode::addChild(Node* child, int zOrder, const std::string& name) +void SpriteBatchNode::addChild(Node* child, int zOrder, std::string_view name) { CCASSERT(child != nullptr, "child should not be null"); CCASSERT(dynamic_cast(child) != nullptr, "CCSpriteBatchNode only supports Sprites as children"); diff --git a/cocos/2d/CCSpriteBatchNode.h b/cocos/2d/CCSpriteBatchNode.h index 3d99cdfa52..cb68aed0f4 100644 --- a/cocos/2d/CCSpriteBatchNode.h +++ b/cocos/2d/CCSpriteBatchNode.h @@ -84,7 +84,7 @@ public: * @param capacity The capacity of children. * @return Return an autorelease object. */ - static SpriteBatchNode* create(const std::string& fileImage, ssize_t capacity = DEFAULT_CAPACITY); + static SpriteBatchNode* create(std::string_view fileImage, ssize_t capacity = DEFAULT_CAPACITY); /** Returns the TextureAtlas object. * @@ -195,7 +195,7 @@ public: using Node::addChild; virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, const std::string& name) override; + virtual void addChild(Node* child, int zOrder, std::string_view name) override; virtual void reorderChild(Node* child, int zOrder) override; virtual void removeChild(Node* child, bool cleanup) override; @@ -250,7 +250,7 @@ public: * @js init * @lua init */ - bool initWithFile(const std::string& fileImage, ssize_t capacity = DEFAULT_CAPACITY); + bool initWithFile(std::string_view fileImage, ssize_t capacity = DEFAULT_CAPACITY); bool init() override; protected: diff --git a/cocos/2d/CCSpriteFrame.cpp b/cocos/2d/CCSpriteFrame.cpp index 7fa6769020..6ef46c7e67 100644 --- a/cocos/2d/CCSpriteFrame.cpp +++ b/cocos/2d/CCSpriteFrame.cpp @@ -35,7 +35,7 @@ NS_CC_BEGIN // implementation of SpriteFrame -SpriteFrame* SpriteFrame::create(const std::string& filename, const Rect& rect) +SpriteFrame* SpriteFrame::create(std::string_view filename, const Rect& rect) { SpriteFrame* spriteFrame = new SpriteFrame(); spriteFrame->initWithTextureFilename(filename, rect); @@ -70,7 +70,7 @@ SpriteFrame* SpriteFrame::createWithTexture(Texture2D* texture, return nullptr; } -SpriteFrame* SpriteFrame::create(const std::string& filename, +SpriteFrame* SpriteFrame::create(std::string_view filename, const Rect& rect, bool rotated, const Vec2& offset, @@ -94,7 +94,7 @@ bool SpriteFrame::initWithTexture(Texture2D* texture, const Rect& rect) return initWithTexture(texture, rectInPixels, false, Vec2::ZERO, rectInPixels.size); } -bool SpriteFrame::initWithTextureFilename(const std::string& filename, const Rect& rect) +bool SpriteFrame::initWithTextureFilename(std::string_view filename, const Rect& rect) { Rect rectInPixels = CC_RECT_POINTS_TO_PIXELS(rect); return initWithTextureFilename(filename, rectInPixels, false, Vec2::ZERO, rectInPixels.size); @@ -126,7 +126,7 @@ bool SpriteFrame::initWithTexture(Texture2D* texture, return true; } -bool SpriteFrame::initWithTextureFilename(const std::string& filename, +bool SpriteFrame::initWithTextureFilename(std::string_view filename, const Rect& rect, bool rotated, const Vec2& offset, diff --git a/cocos/2d/CCSpriteFrame.h b/cocos/2d/CCSpriteFrame.h index 32e93be8ee..5f17fc1280 100644 --- a/cocos/2d/CCSpriteFrame.h +++ b/cocos/2d/CCSpriteFrame.h @@ -66,7 +66,7 @@ public: * @param rect A specified rect. * @return An autoreleased SpriteFrame object. */ - static SpriteFrame* create(const std::string& filename, const Rect& rect); + static SpriteFrame* create(std::string_view filename, const Rect& rect); /** Create a SpriteFrame with a texture filename, rect, rotated, offset and originalSize in pixels. The originalSize is the size in pixels of the frame before being trimmed. @@ -78,7 +78,7 @@ public: * @param originalSize A specified original size. * @return An autoreleased SpriteFrame object. */ - static SpriteFrame* create(const std::string& filename, + static SpriteFrame* create(std::string_view filename, const Rect& rect, bool rotated, const Vec2& offset, @@ -279,7 +279,7 @@ public: /** Initializes a SpriteFrame with a texture filename, rect in points; It is assumed that the frame was not trimmed. */ - bool initWithTextureFilename(const std::string& filename, const Rect& rect); + bool initWithTextureFilename(std::string_view filename, const Rect& rect); /** Initializes a SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels. The originalSize is the size in points of the frame before being trimmed. @@ -295,7 +295,7 @@ public: @since v1.1 */ - bool initWithTextureFilename(const std::string& filename, + bool initWithTextureFilename(std::string_view filename, const Rect& rect, bool rotated, const Vec2& offset, diff --git a/cocos/2d/CCSpriteFrameCache.cpp b/cocos/2d/CCSpriteFrameCache.cpp index db7b977458..537a33e9a4 100644 --- a/cocos/2d/CCSpriteFrameCache.cpp +++ b/cocos/2d/CCSpriteFrameCache.cpp @@ -75,8 +75,8 @@ bool SpriteFrameCache::init() SpriteFrameCache::~SpriteFrameCache() {} -void SpriteFrameCache::addSpriteFramesWithFile(const std::string& spriteSheetFileName, - const std::string& textureFileName, +void SpriteFrameCache::addSpriteFramesWithFile(std::string_view spriteSheetFileName, + std::string_view textureFileName, uint32_t spriteSheetFormat) { auto* loader = getSpriteSheetLoader(spriteSheetFormat); @@ -86,7 +86,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(const std::string& spriteSheetFil } } -void SpriteFrameCache::addSpriteFramesWithFile(const std::string& spriteSheetFileName, +void SpriteFrameCache::addSpriteFramesWithFile(std::string_view spriteSheetFileName, Texture2D* texture, uint32_t spriteSheetFormat) { @@ -97,7 +97,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(const std::string& spriteSheetFil } } -void SpriteFrameCache::addSpriteFramesWithFile(const std::string& spriteSheetFileName, uint32_t spriteSheetFormat) +void SpriteFrameCache::addSpriteFramesWithFile(std::string_view spriteSheetFileName, uint32_t spriteSheetFormat) { auto* loader = getSpriteSheetLoader(spriteSheetFormat); if (loader) @@ -117,12 +117,12 @@ void SpriteFrameCache::addSpriteFramesWithFileContent(const Data& content, } } -bool SpriteFrameCache::isSpriteFramesWithFileLoaded(const std::string& plist) const +bool SpriteFrameCache::isSpriteFramesWithFileLoaded(std::string_view plist) const { return isSpriteSheetInUse(plist) && isPlistFull(plist); } -void SpriteFrameCache::addSpriteFrame(SpriteFrame* frame, const std::string& frameName) +void SpriteFrameCache::addSpriteFrame(SpriteFrame* frame, std::string_view frameName) { CCASSERT(frame, "frame should not be nil"); @@ -169,7 +169,7 @@ void SpriteFrameCache::removeUnusedSpriteFrames() } } -void SpriteFrameCache::removeSpriteFrameByName(const std::string& name) +void SpriteFrameCache::removeSpriteFrameByName(std::string_view name) { // explicit nil handling if (name.empty()) @@ -178,7 +178,7 @@ void SpriteFrameCache::removeSpriteFrameByName(const std::string& name) eraseFrame(name); } -void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& atlasPath) +void SpriteFrameCache::removeSpriteFramesFromFile(std::string_view atlasPath) { // const auto fullPath = FileUtils::getInstance()->fullPathForFilename(plist); // auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); @@ -193,7 +193,7 @@ void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& atlasPath) removeSpriteSheet(atlasPath); } -void SpriteFrameCache::removeSpriteFramesFromFileContent(const std::string& plist_content) +void SpriteFrameCache::removeSpriteFramesFromFileContent(std::string_view plist_content) { auto dict = FileUtils::getInstance()->getValueMapFromData(plist_content.data(), static_cast(plist_content.size())); @@ -241,17 +241,17 @@ void SpriteFrameCache::removeSpriteFramesFromTexture(Texture2D* texture) eraseFrames(keysToRemove); } -SpriteFrame* SpriteFrameCache::getSpriteFrameByName(const std::string& name) +SpriteFrame* SpriteFrameCache::getSpriteFrameByName(std::string_view name) { auto* frame = findFrame(name); if (!frame) { - CCLOG("cocos2d: SpriteFrameCache: Frame '%s' isn't found", name.c_str()); + CCLOG("cocos2d: SpriteFrameCache: Frame '%s' isn't found", name.data()); } return frame; } -bool SpriteFrameCache::reloadTexture(const std::string& spriteSheetFileName) +bool SpriteFrameCache::reloadTexture(std::string_view spriteSheetFileName) { CCASSERT(!spriteSheetFileName.empty(), "plist filename should not be nullptr"); @@ -283,16 +283,17 @@ bool SpriteFrameCache::reloadTexture(const std::string& spriteSheetFileName) } void SpriteFrameCache::insertFrame(const std::shared_ptr& spriteSheet, - const std::string& frameName, + std::string_view frameName, SpriteFrame* spriteFrame) { - spriteSheet->frames.insert(frameName); + spriteSheet->frames.emplace(frameName); _spriteFrames.insert(frameName, spriteFrame); // add SpriteFrame _spriteSheets[spriteSheet->path] = spriteSheet; - _spriteFrameToSpriteSheetMap[frameName] = spriteSheet; // insert index frameName->plist + hlookup::set_item(_spriteFrameToSpriteSheetMap, frameName, spriteSheet); // _spriteFrameToSpriteSheetMap[frameName] = spriteSheet; // insert + // index frameName->plist } -bool SpriteFrameCache::eraseFrame(const std::string& frameName) +bool SpriteFrameCache::eraseFrame(std::string_view frameName) { _spriteFrames.erase(frameName); // drop SpriteFrame const auto itFrame = _spriteFrameToSpriteSheetMap.find(frameName); @@ -330,7 +331,7 @@ bool SpriteFrameCache::eraseFrames(const std::vector& frames) return ret; } -bool SpriteFrameCache::removeSpriteSheet(const std::string& spriteSheetFileName) +bool SpriteFrameCache::removeSpriteSheet(std::string_view spriteSheetFileName) { auto it = _spriteSheets.find(spriteSheetFileName); if (it == _spriteSheets.end()) @@ -356,18 +357,18 @@ void SpriteFrameCache::clear() _spriteFrames.clear(); } -bool SpriteFrameCache::hasFrame(const std::string& frame) const +bool SpriteFrameCache::hasFrame(std::string_view frame) const { return _spriteFrameToSpriteSheetMap.find(frame) != _spriteFrameToSpriteSheetMap.end(); } -bool SpriteFrameCache::isSpriteSheetInUse(const std::string& spriteSheetFileName) const +bool SpriteFrameCache::isSpriteSheetInUse(std::string_view spriteSheetFileName) const { const auto spriteSheetItr = _spriteSheets.find(spriteSheetFileName); return spriteSheetItr != _spriteSheets.end() && !spriteSheetItr->second->frames.empty(); } -SpriteFrame* SpriteFrameCache::findFrame(const std::string& frame) +SpriteFrame* SpriteFrameCache::findFrame(std::string_view frame) { return _spriteFrames.at(frame); } @@ -377,7 +378,7 @@ void SpriteFrameCache::addSpriteFrameCapInset(SpriteFrame* spriteFrame, const Re texture->addSpriteFrameCapInset(spriteFrame, capInsets); } -Map& SpriteFrameCache::getSpriteFrames() +StringMap& SpriteFrameCache::getSpriteFrames() { return _spriteFrames; } diff --git a/cocos/2d/CCSpriteFrameCache.h b/cocos/2d/CCSpriteFrameCache.h index 3009a6bd85..78db1c5bff 100644 --- a/cocos/2d/CCSpriteFrameCache.h +++ b/cocos/2d/CCSpriteFrameCache.h @@ -117,7 +117,7 @@ public: /** Adds multiple Sprite Frames from a plist file. * A texture will be loaded automatically. The texture name will composed by replacing the .plist suffix with .png. - * If you want to use another texture, you should use the addSpriteFramesWithFile(const std::string& plist, const + * If you want to use another texture, you should use the addSpriteFramesWithFile(std::string_view plist, const * std::string& textureFileName) method. * @js addSpriteFrames * @lua addSpriteFrames @@ -125,7 +125,7 @@ public: * @param spriteSheetFileName file name. * @param spriteSheetFormat */ - void addSpriteFramesWithFile(const std::string& spriteSheetFileName, + void addSpriteFramesWithFile(std::string_view spriteSheetFileName, uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST); /** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. @@ -137,8 +137,8 @@ public: * @param textureFileName Texture file name. * @param spriteSheetFormat */ - void addSpriteFramesWithFile(const std::string& spriteSheetFileName, - const std::string& textureFileName, + void addSpriteFramesWithFile(std::string_view spriteSheetFileName, + std::string_view textureFileName, uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST); /** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. @@ -149,7 +149,7 @@ public: * @param texture Texture pointer. * @param spriteSheetFormat */ - void addSpriteFramesWithFile(const std::string& spriteSheetFileName, + void addSpriteFramesWithFile(std::string_view spriteSheetFileName, Texture2D* texture, uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST); @@ -172,7 +172,7 @@ public: * @param frame A certain sprite frame. * @param frameName The name of the sprite frame. */ - void addSpriteFrame(SpriteFrame* frame, const std::string& frameName); + void addSpriteFrame(SpriteFrame* frame, std::string_view frameName); /** Check if multiple Sprite Frames from a plist file have been loaded. * @js NA @@ -181,7 +181,7 @@ public: * @param plist Plist file name. * @return True if the file is loaded. */ - bool isSpriteFramesWithFileLoaded(const std::string& plist) const; + bool isSpriteFramesWithFileLoaded(std::string_view plist) const; /** Purges the dictionary of loaded sprite frames. * Call this method if you receive the "Memory Warning". @@ -202,7 +202,7 @@ public: * * @param name The name of the sprite frame that needs to removed. */ - void removeSpriteFrameByName(const std::string& name); + void removeSpriteFrameByName(std::string_view name); /** Removes multiple Sprite Frames from a plist file. * Sprite Frames stored in this file will be removed. @@ -211,7 +211,7 @@ public: * * @param plist The name of the plist that needs to removed. */ - void removeSpriteFramesFromFile(const std::string& plist); + void removeSpriteFramesFromFile(std::string_view plist); /** Removes multiple Sprite Frames from a plist file content. * Sprite Frames stored in this file will be removed. @@ -220,7 +220,7 @@ public: * @param plist_content The string of the plist content that needs to removed. * @js NA */ - void removeSpriteFramesFromFileContent(const std::string& plist_content); + void removeSpriteFramesFromFileContent(std::string_view plist_content); /** Removes all Sprite Frames associated with the specified textures. * It is convenient to call this method when a specific texture needs to be removed. @@ -239,22 +239,22 @@ public: * @param name A certain sprite frame name. * @return The sprite frame. */ - SpriteFrame* getSpriteFrameByName(const std::string& name); + SpriteFrame* getSpriteFrameByName(std::string_view name); - bool reloadTexture(const std::string& spriteSheetFileName); + bool reloadTexture(std::string_view spriteSheetFileName); - SpriteFrame* findFrame(const std::string& frame); + SpriteFrame* findFrame(std::string_view frame); /** Record SpriteFrame with plist and frame name, add frame name * and plist to index */ void insertFrame(const std::shared_ptr& spriteSheet, - const std::string& frameName, + std::string_view frameName, SpriteFrame* frameObj); /** Delete frame from cache, rebuild index */ - bool eraseFrame(const std::string& frameName); + bool eraseFrame(std::string_view frameName); void addSpriteFrameCapInset(SpriteFrame* spriteFrame, const Rect& capInsets, Texture2D* texture); @@ -277,30 +277,35 @@ protected: bool eraseFrames(const std::vector& frame); /** Delete frame from index and SpriteFrame is kept. */ - bool removeSpriteSheet(const std::string& spriteSheetFileName); + bool removeSpriteSheet(std::string_view spriteSheetFileName); /** Clear index and all SpriteFrames. */ void clear(); - inline bool hasFrame(const std::string& frame) const; - inline bool isSpriteSheetInUse(const std::string& spriteSheetFileName) const; + inline bool hasFrame(std::string_view frame) const; + inline bool isSpriteSheetInUse(std::string_view spriteSheetFileName) const; - inline Map& getSpriteFrames(); + inline StringMap& getSpriteFrames(); - void markPlistFull(const std::string& spriteSheetFileName, bool full) + void markPlistFull(std::string_view spriteSheetFileName, bool full) { - _spriteSheets[spriteSheetFileName]->full = full; + // _spriteSheets[spriteSheetFileName]->full = full; + auto it = _spriteSheets.find(spriteSheetFileName); + if (it != _spriteSheets.end()) + { + it.value()->full = full; + } } - bool isPlistFull(const std::string& spriteSheetFileName) const + bool isPlistFull(std::string_view spriteSheetFileName) const { - auto&& it = _spriteSheets.find(spriteSheetFileName); + auto it = _spriteSheets.find(spriteSheetFileName); return it == _spriteSheets.end() ? false : it->second->full; } private: - Map _spriteFrames; - std::unordered_map> _spriteSheets; - std::unordered_map> _spriteFrameToSpriteSheetMap; + StringMap _spriteFrames; + hlookup::string_map> _spriteSheets; + hlookup::string_map> _spriteFrameToSpriteSheetMap; std::map> _spriteSheetLoaders; }; diff --git a/cocos/2d/CCSpriteSheetLoader.h b/cocos/2d/CCSpriteSheetLoader.h index 80d93632d5..1fee38854f 100644 --- a/cocos/2d/CCSpriteSheetLoader.h +++ b/cocos/2d/CCSpriteSheetLoader.h @@ -65,7 +65,7 @@ class SpriteSheet public: std::string path; uint32_t format; - std::set frames; + hlookup::string_set frames; bool full = false; }; @@ -74,11 +74,11 @@ class ISpriteSheetLoader public: virtual ~ISpriteSheetLoader() = default; virtual uint32_t getFormat() = 0; - virtual void load(const std::string& filePath, SpriteFrameCache& cache) = 0; - virtual void load(const std::string& filePath, Texture2D* texture, SpriteFrameCache& cache) = 0; - virtual void load(const std::string& filePath, const std::string& textureFileName, SpriteFrameCache& cache) = 0; + virtual void load(std::string_view filePath, SpriteFrameCache& cache) = 0; + virtual void load(std::string_view filePath, Texture2D* texture, SpriteFrameCache& cache) = 0; + virtual void load(std::string_view filePath, std::string_view textureFileName, SpriteFrameCache& cache) = 0; virtual void load(const Data& content, Texture2D* texture, SpriteFrameCache& cache) = 0; - virtual void reload(const std::string& filePath, SpriteFrameCache& cache) = 0; + virtual void reload(std::string_view filePath, SpriteFrameCache& cache) = 0; }; class SpriteSheetLoader : public ISpriteSheetLoader @@ -93,11 +93,11 @@ public: PolygonInfo& polygonInfo); uint32_t getFormat() override = 0; - void load(const std::string& filePath, SpriteFrameCache& cache) override = 0; - void load(const std::string& filePath, Texture2D* texture, SpriteFrameCache& cache) override = 0; - void load(const std::string& filePath, const std::string& textureFileName, SpriteFrameCache& cache) override = 0; + void load(std::string_view filePath, SpriteFrameCache& cache) override = 0; + void load(std::string_view filePath, Texture2D* texture, SpriteFrameCache& cache) override = 0; + void load(std::string_view filePath, std::string_view textureFileName, SpriteFrameCache& cache) override = 0; void load(const Data& content, Texture2D* texture, SpriteFrameCache& cache) override = 0; - void reload(const std::string& filePath, SpriteFrameCache& cache) override = 0; + void reload(std::string_view filePath, SpriteFrameCache& cache) override = 0; }; // end of _2d group diff --git a/cocos/2d/CCTMXObjectGroup.cpp b/cocos/2d/CCTMXObjectGroup.cpp index 7196acad9b..99042b01b3 100644 --- a/cocos/2d/CCTMXObjectGroup.cpp +++ b/cocos/2d/CCTMXObjectGroup.cpp @@ -40,7 +40,7 @@ TMXObjectGroup::~TMXObjectGroup() CCLOGINFO("deallocing TMXObjectGroup: %p", this); } -ValueMap TMXObjectGroup::getObject(const std::string& objectName) const +ValueMap TMXObjectGroup::getObject(std::string_view objectName) const { if (!_objects.empty()) { @@ -59,7 +59,7 @@ ValueMap TMXObjectGroup::getObject(const std::string& objectName) const return ValueMap(); } -Value TMXObjectGroup::getProperty(const std::string& propertyName) const +Value TMXObjectGroup::getProperty(std::string_view propertyName) const { if (_properties.find(propertyName) != _properties.end()) return _properties.at(propertyName); diff --git a/cocos/2d/CCTMXObjectGroup.h b/cocos/2d/CCTMXObjectGroup.h index d7df9de64b..5a012fc180 100644 --- a/cocos/2d/CCTMXObjectGroup.h +++ b/cocos/2d/CCTMXObjectGroup.h @@ -60,13 +60,13 @@ public: * * @return The group name. */ - const std::string& getGroupName() const { return _groupName; } + std::string_view getGroupName() const { return _groupName; } /** Set the group name. * * @param groupName A string,it is used to set the group name. */ - void setGroupName(const std::string& groupName) { _groupName = groupName; } + void setGroupName(std::string_view groupName) { _groupName = groupName; } /** Return the value for the specific property name. * @@ -74,14 +74,14 @@ public: * @return Return the value for the specific property name. * @js NA */ - Value getProperty(const std::string& propertyName) const; + Value getProperty(std::string_view propertyName) const; /** Return the dictionary for the specific object name. * It will return the 1st object found on the array for the given name. * * @return Return the dictionary for the specific object name. */ - ValueMap getObject(const std::string& objectName) const; + ValueMap getObject(std::string_view objectName) const; /** Gets the offset position of child objects. * diff --git a/cocos/2d/CCTMXXMLParser.cpp b/cocos/2d/CCTMXXMLParser.cpp index 6916188548..e8d33801d8 100644 --- a/cocos/2d/CCTMXXMLParser.cpp +++ b/cocos/2d/CCTMXXMLParser.cpp @@ -92,7 +92,7 @@ Rect TMXTilesetInfo::getRectForGID(uint32_t gid) // implementation TMXMapInfo -TMXMapInfo* TMXMapInfo::create(const std::string& tmxFile) +TMXMapInfo* TMXMapInfo::create(std::string_view tmxFile) { TMXMapInfo* ret = new TMXMapInfo(); if (ret->initWithTMXFile(tmxFile)) @@ -104,7 +104,7 @@ TMXMapInfo* TMXMapInfo::create(const std::string& tmxFile) return nullptr; } -TMXMapInfo* TMXMapInfo::createWithXML(const std::string& tmxString, const std::string& resourcePath) +TMXMapInfo* TMXMapInfo::createWithXML(std::string_view tmxString, std::string_view resourcePath) { TMXMapInfo* ret = new TMXMapInfo(); if (ret->initWithXML(tmxString, resourcePath)) @@ -116,7 +116,7 @@ TMXMapInfo* TMXMapInfo::createWithXML(const std::string& tmxString, const std::s return nullptr; } -void TMXMapInfo::internalInit(const std::string& tmxFileName, const std::string& resourcePath) +void TMXMapInfo::internalInit(std::string_view tmxFileName, std::string_view resourcePath) { if (!tmxFileName.empty()) { @@ -138,13 +138,13 @@ void TMXMapInfo::internalInit(const std::string& tmxFileName, const std::string& _currentFirstGID = -1; } -bool TMXMapInfo::initWithXML(const std::string& tmxString, const std::string& resourcePath) +bool TMXMapInfo::initWithXML(std::string_view tmxString, std::string_view resourcePath) { internalInit("", resourcePath); return parseXMLString(tmxString); } -bool TMXMapInfo::initWithTMXFile(const std::string& tmxFile) +bool TMXMapInfo::initWithTMXFile(std::string_view tmxFile) { internalInit(tmxFile, ""); return parseXMLFile(_TMXFileName); @@ -171,7 +171,7 @@ TMXMapInfo::~TMXMapInfo() CCLOGINFO("deallocing TMXMapInfo: %p", this); } -bool TMXMapInfo::parseXMLString(const std::string& xmlString) +bool TMXMapInfo::parseXMLString(std::string_view xmlString) { size_t len = xmlString.size(); if (len <= 0) @@ -186,10 +186,10 @@ bool TMXMapInfo::parseXMLString(const std::string& xmlString) parser.setDelegator(this); - return parser.parse(xmlString.c_str(), len); + return parser.parse(xmlString.data(), len); } -bool TMXMapInfo::parseXMLFile(const std::string& xmlFilename) +bool TMXMapInfo::parseXMLFile(std::string_view xmlFilename) { SAXParser parser; @@ -265,7 +265,7 @@ void TMXMapInfo::startElement(void* /*ctx*/, const char* name, const char** atts tmxMapInfo->setStaggerIndex(TMXStaggerIndex_Even); } - float hexSideLength = attributeDict["hexsidelength"].asFloat(); + auto hexSideLength = attributeDict["hexsidelength"].asInt(); tmxMapInfo->setHexSideLength(hexSideLength); Vec2 s; @@ -348,7 +348,7 @@ void TMXMapInfo::startElement(void* /*ctx*/, const char* name, const char** atts TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); Vec2 layerSize = layer->_layerSize; uint32_t gid = static_cast(attributeDict["gid"].asUnsignedInt()); - int tilesAmount = layerSize.width * layerSize.height; + int tilesAmount = static_cast(layerSize.width * layerSize.height); if (_xmlTileIndex < tilesAmount) { @@ -443,7 +443,7 @@ void TMXMapInfo::startElement(void* /*ctx*/, const char* name, const char** atts TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); Vec2 layerSize = layer->_layerSize; - int tilesAmount = layerSize.width * layerSize.height; + int tilesAmount = static_cast(layerSize.width * layerSize.height); uint32_t* tiles = (uint32_t*)malloc(tilesAmount * sizeof(uint32_t)); // set all value to 0 @@ -688,10 +688,10 @@ void TMXMapInfo::endElement(void* /*ctx*/, const char* name) TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); - std::string currentString = tmxMapInfo->getCurrentString(); + auto currentString = tmxMapInfo->getCurrentString(); unsigned char* buffer; auto len = - base64Decode((unsigned char*)currentString.c_str(), (unsigned int)currentString.length(), &buffer); + base64Decode((unsigned char*)currentString.data(), (unsigned int)currentString.length(), &buffer); if (!buffer) { CCLOG("cocos2d: TiledMap: decode data error"); @@ -733,10 +733,11 @@ void TMXMapInfo::endElement(void* /*ctx*/, const char* name) TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); tmxMapInfo->setStoringCharacters(false); - std::string currentString = tmxMapInfo->getCurrentString(); + auto currentString = tmxMapInfo->getCurrentString(); vector gidTokens; - istringstream filestr(currentString); + std::stringstream filestr; + filestr << currentString; string sRow; while (getline(filestr, sRow, '\n')) { @@ -810,7 +811,7 @@ void TMXMapInfo::textHandler(void* /*ctx*/, const char* ch, size_t len) if (tmxMapInfo->isStoringCharacters()) { - std::string currentString = tmxMapInfo->getCurrentString(); + std::string currentString{tmxMapInfo->getCurrentString()}; currentString += text; tmxMapInfo->setCurrentString(currentString); } diff --git a/cocos/2d/CCTMXXMLParser.h b/cocos/2d/CCTMXXMLParser.h index 20f780526c..1ec2a821f4 100644 --- a/cocos/2d/CCTMXXMLParser.h +++ b/cocos/2d/CCTMXXMLParser.h @@ -250,9 +250,9 @@ class CC_DLL TMXMapInfo : public Ref, public SAXDelegator { public: /** creates a TMX Format with a tmx file */ - static TMXMapInfo* create(const std::string& tmxFile); + static TMXMapInfo* create(std::string_view tmxFile); /** creates a TMX Format with an XML string and a TMX resource path */ - static TMXMapInfo* createWithXML(const std::string& tmxString, const std::string& resourcePath); + static TMXMapInfo* createWithXML(std::string_view tmxString, std::string_view resourcePath); /** * @js ctor @@ -265,13 +265,13 @@ public: virtual ~TMXMapInfo(); /** initializes a TMX format with a tmx file */ - bool initWithTMXFile(const std::string& tmxFile); + bool initWithTMXFile(std::string_view tmxFile); /** initializes a TMX format with an XML string and a TMX resource path */ - bool initWithXML(const std::string& tmxString, const std::string& resourcePath); + bool initWithXML(std::string_view tmxString, std::string_view resourcePath); /** initializes parsing of an XML file, either a tmx (Map) file or tsx (Tileset) file */ - bool parseXMLFile(const std::string& xmlFilename); + bool parseXMLFile(std::string_view xmlFilename); /* initializes parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string */ - bool parseXMLString(const std::string& xmlString); + bool parseXMLString(std::string_view xmlString); ValueMapIntKey& getTileProperties() { return _tileProperties; }; void setTileProperties(const ValueMapIntKey& tileProperties) { _tileProperties = tileProperties; } @@ -353,14 +353,14 @@ public: */ void textHandler(void* ctx, const char* ch, size_t len) override; - const std::string& getCurrentString() const { return _currentString; } - void setCurrentString(const std::string& currentString) { _currentString = currentString; } - const std::string& getTMXFileName() const { return _TMXFileName; } - void setTMXFileName(const std::string& fileName) { _TMXFileName = fileName; } - const std::string& getExternalTilesetFileName() const { return _externalTilesetFilename; } + std::string_view getCurrentString() const { return _currentString; } + void setCurrentString(std::string_view currentString) { _currentString = currentString; } + std::string_view getTMXFileName() const { return _TMXFileName; } + void setTMXFileName(std::string_view fileName) { _TMXFileName = fileName; } + std::string_view getExternalTilesetFileName() const { return _externalTilesetFilename; } protected: - void internalInit(const std::string& tmxFileName, const std::string& resourcePath); + void internalInit(std::string_view tmxFileName, std::string_view resourcePath); /// map orientation int _orientation; diff --git a/cocos/2d/CCTextFieldTTF.cpp b/cocos/2d/CCTextFieldTTF.cpp index 8ccdaace71..a134395fb9 100644 --- a/cocos/2d/CCTextFieldTTF.cpp +++ b/cocos/2d/CCTextFieldTTF.cpp @@ -109,10 +109,10 @@ TextFieldTTF::~TextFieldTTF() {} // static constructor ////////////////////////////////////////////////////////////////////////// -TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder, +TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(std::string_view placeholder, const Vec2& dimensions, TextHAlignment alignment, - const std::string& fontName, + std::string_view fontName, float fontSize) { TextFieldTTF* ret = new TextFieldTTF(); @@ -129,8 +129,8 @@ TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(const std::string& placehol return nullptr; } -TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder, - const std::string& fontName, +TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(std::string_view placeholder, + std::string_view fontName, float fontSize) { TextFieldTTF* ret = new TextFieldTTF(); @@ -151,10 +151,10 @@ TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(const std::string& placehol // initialize ////////////////////////////////////////////////////////////////////////// -bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, +bool TextFieldTTF::initWithPlaceHolder(std::string_view placeholder, const Vec2& dimensions, TextHAlignment alignment, - const std::string& fontName, + std::string_view fontName, float fontSize) { setDimensions(dimensions.width, dimensions.height); @@ -162,7 +162,7 @@ bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, return initWithPlaceHolder(placeholder, fontName, fontSize); } -bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize) +bool TextFieldTTF::initWithPlaceHolder(std::string_view placeholder, std::string_view fontName, float fontSize) { _placeHolder = placeholder; @@ -366,7 +366,7 @@ void TextFieldTTF::deleteBackward() } } -const std::string& TextFieldTTF::getContentText() +std::string_view TextFieldTTF::getContentText() { return _inputText; } @@ -573,9 +573,9 @@ void TextFieldTTF::setString(std::string_view text) _charCount = charCount; } -void TextFieldTTF::appendString(const std::string& text) +void TextFieldTTF::appendString(std::string_view text) { - insertText(text.c_str(), text.length()); + insertText(text.data(), text.length()); } void TextFieldTTF::makeStringSupportCursor(std::string& displayText) @@ -677,13 +677,13 @@ void TextFieldTTF::controlKey(EventKeyboard::KeyCode keyCode) } } -const std::string& TextFieldTTF::getString() const +std::string_view TextFieldTTF::getString() const { return _inputText; } // place holder text property -void TextFieldTTF::setPlaceHolder(const std::string& text) +void TextFieldTTF::setPlaceHolder(std::string_view text) { _placeHolder = text; if (_inputText.empty() && !_isAttachWithIME) @@ -693,7 +693,7 @@ void TextFieldTTF::setPlaceHolder(const std::string& text) } } -const std::string& TextFieldTTF::getPlaceHolder() const +std::string_view TextFieldTTF::getPlaceHolder() const { return _placeHolder; } @@ -733,7 +733,7 @@ void TextFieldTTF::setSecureTextEntry(bool value) } } -void TextFieldTTF::setPasswordTextStyle(const std::string& text) +void TextFieldTTF::setPasswordTextStyle(std::string_view text) { if (text.length() < 1) { @@ -747,7 +747,7 @@ void TextFieldTTF::setPasswordTextStyle(const std::string& text) } } -const std::string& TextFieldTTF::getPasswordTextStyle() const +std::string_view TextFieldTTF::getPasswordTextStyle() const { return _passwordStyleText; } diff --git a/cocos/2d/CCTextFieldTTF.h b/cocos/2d/CCTextFieldTTF.h index 4eee6e0f86..b9276ffb4a 100644 --- a/cocos/2d/CCTextFieldTTF.h +++ b/cocos/2d/CCTextFieldTTF.h @@ -98,28 +98,28 @@ public: /** Creates a TextFieldTTF from a fontname, alignment, dimension and font size. * @js NA */ - static TextFieldTTF* textFieldWithPlaceHolder(const std::string& placeholder, + static TextFieldTTF* textFieldWithPlaceHolder(std::string_view placeholder, const Vec2& dimensions, TextHAlignment alignment, - const std::string& fontName, + std::string_view fontName, float fontSize); /** Creates a TextFieldTTF from a fontname and font size. * @js NA */ - static TextFieldTTF* textFieldWithPlaceHolder(const std::string& placeholder, - const std::string& fontName, + static TextFieldTTF* textFieldWithPlaceHolder(std::string_view placeholder, + std::string_view fontName, float fontSize); /** Initializes the TextFieldTTF with a font name, alignment, dimension and font size. */ - bool initWithPlaceHolder(const std::string& placeholder, + bool initWithPlaceHolder(std::string_view placeholder, const Vec2& dimensions, TextHAlignment alignment, - const std::string& fontName, + std::string_view fontName, float fontSize); /** Initializes the TextFieldTTF with a font name and font size. */ - bool initWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize); + bool initWithPlaceHolder(std::string_view placeholder, std::string_view fontName, float fontSize); /** *@brief Open keyboard and receive input text. @@ -183,26 +183,26 @@ public: * Append to input text of TextField. *@param text The append text of TextField. */ - virtual void appendString(const std::string& text); + virtual void appendString(std::string_view text); /** * Query the input text of TextField. *@return Get the input text of TextField. */ - virtual const std::string& getString() const override; + virtual std::string_view getString() const override; /** * Change placeholder text. * place holder text displayed when there is no text in the text field. *@param text The placeholder string. */ - virtual void setPlaceHolder(const std::string& text); + virtual void setPlaceHolder(std::string_view text); /** * Query the placeholder string. *@return The placeholder string. */ - virtual const std::string& getPlaceHolder() const; + virtual std::string_view getPlaceHolder() const; /** * Set enable secure text entry representation. @@ -211,8 +211,8 @@ public: * @js NA */ virtual void setSecureTextEntry(bool value); - virtual void setPasswordTextStyle(const std::string& text); - const std::string& getPasswordTextStyle() const; + virtual void setPasswordTextStyle(std::string_view text); + std::string_view getPasswordTextStyle() const; /** * Query whether the currently display mode is secure text entry or not. @@ -260,7 +260,7 @@ protected: virtual void didDetachWithIME() override; virtual void insertText(const char* text, size_t len) override; virtual void deleteBackward() override; - virtual const std::string& getContentText() override; + virtual std::string_view getContentText() override; virtual void controlKey(EventKeyboard::KeyCode keyCode) override; TextFieldDelegate* _delegate; diff --git a/cocos/2d/CCTileMapAtlas.cpp b/cocos/2d/CCTileMapAtlas.cpp index 987d598f7e..f0ca242ed4 100644 --- a/cocos/2d/CCTileMapAtlas.cpp +++ b/cocos/2d/CCTileMapAtlas.cpp @@ -36,7 +36,7 @@ NS_CC_BEGIN // implementation TileMapAtlas -TileMapAtlas* TileMapAtlas::create(const std::string& tile, const std::string& mapFile, int tileWidth, int tileHeight) +TileMapAtlas* TileMapAtlas::create(std::string_view tile, std::string_view mapFile, int tileWidth, int tileHeight) { TileMapAtlas* ret = new TileMapAtlas(); if (ret->initWithTileFile(tile, mapFile, tileWidth, tileHeight)) @@ -48,7 +48,7 @@ TileMapAtlas* TileMapAtlas::create(const std::string& tile, const std::string& m return nullptr; } -bool TileMapAtlas::initWithTileFile(const std::string& tile, const std::string& mapFile, int tileWidth, int tileHeight) +bool TileMapAtlas::initWithTileFile(std::string_view tile, std::string_view mapFile, int tileWidth, int tileHeight) { this->loadTGAfile(mapFile); this->calculateItemsToRender(); @@ -100,7 +100,7 @@ void TileMapAtlas::calculateItemsToRender() } } -void TileMapAtlas::loadTGAfile(const std::string& file) +void TileMapAtlas::loadTGAfile(std::string_view file) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(file); diff --git a/cocos/2d/CCTileMapAtlas.h b/cocos/2d/CCTileMapAtlas.h index 711f9e1399..b5adc261e2 100644 --- a/cocos/2d/CCTileMapAtlas.h +++ b/cocos/2d/CCTileMapAtlas.h @@ -59,7 +59,7 @@ public: /** creates a TileMap with a tile file (atlas) with a map file and the width and height of each tile in points. The tile file will be loaded using the TextureMgr. */ - static TileMapAtlas* create(const std::string& tile, const std::string& mapFile, int tileWidth, int tileHeight); + static TileMapAtlas* create(std::string_view tile, std::string_view mapFile, int tileWidth, int tileHeight); /** * @js ctor */ @@ -73,7 +73,7 @@ public: /** initializes a TileMap with a tile file (atlas) with a map file and the width and height of each tile in points. The file will be loaded using the TextureMgr. */ - bool initWithTileFile(const std::string& tile, const std::string& mapFile, int tileWidth, int tileHeight); + bool initWithTileFile(std::string_view tile, std::string_view mapFile, int tileWidth, int tileHeight); /** * Returns a tile from position x,y. *For the moment only channel R is used @@ -100,7 +100,7 @@ public: void setTGAInfo(struct sImageTGA* TGAInfo) { _TGAInfo = TGAInfo; } protected: - void loadTGAfile(const std::string& file); + void loadTGAfile(std::string_view file); void calculateItemsToRender(); void updateAtlasValueAt(const Vec2& pos, const Color3B& value, int index); void updateAtlasValues(); diff --git a/cocos/3d/CCAnimate3D.cpp b/cocos/3d/CCAnimate3D.cpp index 7ad77b1ce5..2376a4715e 100644 --- a/cocos/3d/CCAnimate3D.cpp +++ b/cocos/3d/CCAnimate3D.cpp @@ -128,9 +128,9 @@ Animate3D* Animate3D::reverse() const return animate; } -Node* findChildByNameRecursively(Node* node, const std::string& childName) +Node* findChildByNameRecursively(Node* node, std::string_view childName) { - const std::string& name = node->getName(); + std::string_view name = node->getName(); if (name == childName) return node; @@ -162,10 +162,10 @@ void Animate3D::startWithTarget(Node* target) { if (_animation) { - const std::unordered_map& boneCurves = _animation->getBoneCurves(); + auto& boneCurves = _animation->getBoneCurves(); for (const auto& iter : boneCurves) { - const std::string& boneName = iter.first; + std::string_view boneName = iter.first; auto skin = sprite->getSkeleton(); if (skin) { @@ -200,10 +200,10 @@ void Animate3D::startWithTarget(Node* target) } else { - const std::unordered_map& boneCurves = _animation->getBoneCurves(); + auto& boneCurves = _animation->getBoneCurves(); for (const auto& iter : boneCurves) { - const std::string& boneName = iter.first; + std::string_view boneName = iter.first; Node* node = nullptr; if (target->getName() == boneName) node = target; diff --git a/cocos/3d/CCAnimation3D.cpp b/cocos/3d/CCAnimation3D.cpp index 7657842afd..4cc34726c4 100644 --- a/cocos/3d/CCAnimation3D.cpp +++ b/cocos/3d/CCAnimation3D.cpp @@ -29,11 +29,11 @@ NS_CC_BEGIN -Animation3D* Animation3D::create(const std::string& fileName, const std::string& animationName) +Animation3D* Animation3D::create(std::string_view fileName, std::string_view animationName) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(fileName); - std::string key = fullPath + "#" + animationName; - auto animation = Animation3DCache::getInstance()->getAnimation(key); + fullPath.append("#").append(animationName); + auto animation = Animation3DCache::getInstance()->getAnimation(fullPath); if (animation != nullptr) return animation; @@ -50,7 +50,7 @@ Animation3D* Animation3D::create(const std::string& fileName, const std::string& return animation; } -bool Animation3D::initWithFile(const std::string& filename, const std::string& animationName) +bool Animation3D::initWithFile(std::string_view filename, std::string_view animationName) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename); @@ -59,8 +59,8 @@ bool Animation3D::initWithFile(const std::string& filename, const std::string& a Animation3DData animationdata; if (bundle->load(fullPath) && bundle->loadAnimationData(animationName, &animationdata) && init(animationdata)) { - std::string key = fullPath + "#" + animationName; - Animation3DCache::getInstance()->addAnimation(key, this); + fullPath.append("#").append(animationName); + Animation3DCache::getInstance()->addAnimation(fullPath, this); Bundle3D::destroyBundle(bundle); return true; } @@ -70,7 +70,7 @@ bool Animation3D::initWithFile(const std::string& filename, const std::string& a return false; } -Animation3D::Curve* Animation3D::getBoneCurveByName(const std::string& name) const +Animation3D::Curve* Animation3D::getBoneCurveByName(std::string_view name) const { auto it = _boneCurves.find(name); if (it != _boneCurves.end()) @@ -199,7 +199,7 @@ void Animation3DCache::destroyInstance() CC_SAFE_DELETE(_cacheInstance); } -Animation3D* Animation3DCache::getAnimation(const std::string& key) +Animation3D* Animation3DCache::getAnimation(std::string_view key) { auto it = _animations.find(key); if (it != _animations.end()) @@ -207,14 +207,14 @@ Animation3D* Animation3DCache::getAnimation(const std::string& key) return nullptr; } -void Animation3DCache::addAnimation(const std::string& key, Animation3D* animation) +void Animation3DCache::addAnimation(std::string_view key, Animation3D* animation) { const auto& it = _animations.find(key); if (it != _animations.end()) { return; // already have this key } - _animations[key] = animation; + _animations.emplace(key, animation); //_animations[key] = animation; animation->retain(); } diff --git a/cocos/3d/CCAnimation3D.h b/cocos/3d/CCAnimation3D.h index 80f528ae27..64b1302d83 100644 --- a/cocos/3d/CCAnimation3D.h +++ b/cocos/3d/CCAnimation3D.h @@ -69,7 +69,7 @@ public: }; /**read all animation or only the animation with given animationName? animationName == "" read the first.*/ - static Animation3D* create(const std::string& filename, const std::string& animationName = ""); + static Animation3D* create(std::string_view filename, std::string_view animationName = ""); /**get duration*/ float getDuration() const { return _duration; } @@ -79,10 +79,10 @@ public: * * @lua NA */ - Curve* getBoneCurveByName(const std::string& name) const; + Curve* getBoneCurveByName(std::string_view name) const; /**get the bone Curves set*/ - const std::unordered_map& getBoneCurves() const { return _boneCurves; } + const hlookup::string_map& getBoneCurves() const { return _boneCurves; } CC_CONSTRUCTOR_ACCESS : Animation3D(); virtual ~Animation3D(); @@ -90,10 +90,10 @@ public: bool init(const Animation3DData& data); /**init Animation3D with file name and animation name*/ - bool initWithFile(const std::string& filename, const std::string& animationName); + bool initWithFile(std::string_view filename, std::string_view animationName); protected: - std::unordered_map _boneCurves; // bone curves map, key bone name, value AnimationCurve + hlookup::string_map _boneCurves; // bone curves map, key bone name, value AnimationCurve float _duration; // animation duration }; @@ -109,10 +109,10 @@ public: static void destroyInstance(); /**get animation by key*/ - Animation3D* getAnimation(const std::string& key); + Animation3D* getAnimation(std::string_view key); /**add animation to cache*/ - void addAnimation(const std::string& key, Animation3D* animation); + void addAnimation(std::string_view key, Animation3D* animation); /**remove all animation*/ void removeAllAnimations(); @@ -125,7 +125,7 @@ protected: static Animation3DCache* _cacheInstance; // cache instance - std::unordered_map _animations; // cached animations + hlookup::string_map _animations; // cached animations }; // end of 3d group diff --git a/cocos/3d/CCBillBoard.cpp b/cocos/3d/CCBillBoard.cpp index 427d262a4c..5eaba2dbb0 100644 --- a/cocos/3d/CCBillBoard.cpp +++ b/cocos/3d/CCBillBoard.cpp @@ -53,7 +53,7 @@ BillBoard* BillBoard::createWithTexture(Texture2D* texture, Mode mode) return nullptr; } -BillBoard* BillBoard::create(const std::string& filename, Mode mode) +BillBoard* BillBoard::create(std::string_view filename, Mode mode) { BillBoard* billboard = new BillBoard(); if (billboard->initWithFile(filename)) @@ -66,7 +66,7 @@ BillBoard* BillBoard::create(const std::string& filename, Mode mode) return nullptr; } -BillBoard* BillBoard::create(const std::string& filename, const Rect& rect, Mode mode) +BillBoard* BillBoard::create(std::string_view filename, const Rect& rect, Mode mode) { BillBoard* billboard = new BillBoard(); if (billboard->initWithFile(filename, rect)) diff --git a/cocos/3d/CCBillBoard.h b/cocos/3d/CCBillBoard.h index 4eef5d257a..2f32370235 100644 --- a/cocos/3d/CCBillBoard.h +++ b/cocos/3d/CCBillBoard.h @@ -63,7 +63,7 @@ public: * @param filename A path to image file, e.g., "scene1/monster.png" * @return An autoreleased BillBoard object. */ - static BillBoard* create(const std::string& filename, Mode mode = Mode::VIEW_POINT_ORIENTED); + static BillBoard* create(std::string_view filename, Mode mode = Mode::VIEW_POINT_ORIENTED); /** * Creates a BillBoard with an image filename and a rect. @@ -72,7 +72,7 @@ public: * @param rect A subrect of the image file * @return An autoreleased BillBoard object */ - static BillBoard* create(const std::string& filename, const Rect& rect, Mode mode = Mode::VIEW_POINT_ORIENTED); + static BillBoard* create(std::string_view filename, const Rect& rect, Mode mode = Mode::VIEW_POINT_ORIENTED); /** * Creates a BillBoard with a Texture2D object. diff --git a/cocos/3d/CCBundle3D.cpp b/cocos/3d/CCBundle3D.cpp index d735f5f39d..2f18d15daa 100644 --- a/cocos/3d/CCBundle3D.cpp +++ b/cocos/3d/CCBundle3D.cpp @@ -169,7 +169,7 @@ void Bundle3D::clear() } } -bool Bundle3D::load(const std::string& path) +bool Bundle3D::load(std::string_view path) { if (path.empty()) return false; @@ -193,7 +193,7 @@ bool Bundle3D::load(const std::string& path) } else { - CCLOG("warning: %s is invalid file formate", path.c_str()); + CCLOG("warning: %s is invalid file formate", path.data()); } ret ? (_path = path) : (_path = ""); @@ -204,7 +204,7 @@ bool Bundle3D::load(const std::string& path) bool Bundle3D::loadObj(MeshDatas& meshdatas, MaterialDatas& materialdatas, NodeDatas& nodedatas, - const std::string& fullPath, + std::string_view fullPath, const char* mtl_basepath) { meshdatas.resetData(); @@ -219,7 +219,7 @@ bool Bundle3D::loadObj(MeshDatas& meshdatas, std::vector shapes; std::vector materials; - auto ret = tinyobj::LoadObj(shapes, materials, fullPath.c_str(), mtlPath.c_str()); + auto ret = tinyobj::LoadObj(shapes, materials, fullPath.data(), mtlPath.c_str()); if (ret.empty()) { // fill data @@ -329,11 +329,11 @@ bool Bundle3D::loadObj(MeshDatas& meshdatas, return true; } - CCLOG("warning: load %s file error: %s", fullPath.c_str(), ret.c_str()); + CCLOG("warning: load %s file error: %s", fullPath.data(), ret.c_str()); return false; } -bool Bundle3D::loadSkinData(const std::string& /*id*/, SkinData* skindata) +bool Bundle3D::loadSkinData(std::string_view /*id*/, SkinData* skindata) { skindata->resetData(); @@ -347,7 +347,7 @@ bool Bundle3D::loadSkinData(const std::string& /*id*/, SkinData* skindata) } } -bool Bundle3D::loadAnimationData(const std::string& id, Animation3DData* animationdata) +bool Bundle3D::loadAnimationData(std::string_view id, Animation3DData* animationdata) { animationdata->resetData(); @@ -1062,7 +1062,7 @@ bool Bundle3D::loadMaterialsJson(MaterialDatas& materialdatas) } return true; } -bool Bundle3D::loadJson(const std::string& path) +bool Bundle3D::loadJson(std::string_view path) { clear(); @@ -1084,7 +1084,7 @@ bool Bundle3D::loadJson(const std::string& path) return true; } -bool Bundle3D::loadBinary(const std::string& path) +bool Bundle3D::loadBinary(std::string_view path) { clear(); @@ -1094,7 +1094,7 @@ bool Bundle3D::loadBinary(const std::string& path) if (_binaryBuffer.isNull()) { clear(); - CCLOG("warning: Failed to read file: %s", path.c_str()); + CCLOG("warning: Failed to read file: %s", path.data()); return false; } @@ -1107,7 +1107,7 @@ bool Bundle3D::loadBinary(const std::string& path) if (_binaryReader.read(sig, 1, 4) != 4 || memcmp(sig, identifier, 4) != 0) { clear(); - CCLOG("warning: Invalid identifier: %s", path.c_str()); + CCLOG("warning: Invalid identifier: %s", path.data()); return false; } @@ -1127,7 +1127,7 @@ bool Bundle3D::loadBinary(const std::string& path) if (_binaryReader.read(&_referenceCount, 4, 1) != 1) { clear(); - CCLOG("warning: Failed to read ref table size '%s'.", path.c_str()); + CCLOG("warning: Failed to read ref table size '%s'.", path.data()); return false; } @@ -1141,7 +1141,7 @@ bool Bundle3D::loadBinary(const std::string& path) _binaryReader.read(&_references[i].offset, 4, 1) != 1) { clear(); - CCLOG("warning: Failed to read ref number %u for bundle '%s'.", i, path.c_str()); + CCLOG("warning: Failed to read ref number %u for bundle '%s'.", i, path.data()); CC_SAFE_DELETE_ARRAY(_references); return false; } @@ -1460,7 +1460,7 @@ bool loadMaterialDataJson_0_2(MaterialData* /*materialdata*/) return true; } -bool Bundle3D::loadAnimationDataJson(const std::string& id, Animation3DData* animationdata) +bool Bundle3D::loadAnimationDataJson(std::string_view id, Animation3DData* animationdata) { std::string anim = ""; if (_version == "1.2" || _version == "0.2") @@ -1549,7 +1549,7 @@ bool Bundle3D::loadAnimationDataJson(const std::string& id, Animation3DData* ani return true; } -bool Bundle3D::loadAnimationDataBinary(const std::string& id, Animation3DData* animationdata) +bool Bundle3D::loadAnimationDataBinary(std::string_view id, Animation3DData* animationdata) { if (_version == "0.1" || _version == "0.2" || _version == "0.3" || _version == "0.4") @@ -1560,9 +1560,9 @@ bool Bundle3D::loadAnimationDataBinary(const std::string& id, Animation3DData* a else { // if id is not a null string, we need to add a suffix of "animation" for seeding. - std::string id_ = id; - if (id != "") - id_ = id + "animation"; + std::string id_{id}; + if (!id.empty()) + id_.append("animation"); if (!seekToFirstType(BUNDLE_TYPE_ANIMATIONS, id_)) return false; @@ -1998,7 +1998,7 @@ NodeData* Bundle3D::parseNodesRecursivelyBinary(bool& skeleton, bool singleSprit return nodedata; } -backend::VertexFormat Bundle3D::parseGLDataType(const std::string& str, int size) +backend::VertexFormat Bundle3D::parseGLDataType(std::string_view str, int size) { backend::VertexFormat ret = backend::VertexFormat::INT; if (str == "GL_BYTE") @@ -2097,7 +2097,7 @@ backend::VertexFormat Bundle3D::parseGLDataType(const std::string& str, int size return ret; } -backend::SamplerAddressMode Bundle3D::parseSamplerAddressMode(const std::string& str) +backend::SamplerAddressMode Bundle3D::parseSamplerAddressMode(std::string_view str) { if (str == "REPEAT") @@ -2115,7 +2115,7 @@ backend::SamplerAddressMode Bundle3D::parseSamplerAddressMode(const std::string& } } -NTextureData::Usage Bundle3D::parseGLTextureType(const std::string& str) +NTextureData::Usage Bundle3D::parseGLTextureType(std::string_view str) { if (str == "AMBIENT") { @@ -2163,7 +2163,7 @@ NTextureData::Usage Bundle3D::parseGLTextureType(const std::string& str) return NTextureData::Usage::Unknown; } } -shaderinfos::VertexKey Bundle3D::parseGLProgramAttribute(const std::string& str) +shaderinfos::VertexKey Bundle3D::parseGLProgramAttribute(std::string_view str) { if (str == "VERTEX_ATTRIB_POSITION") { @@ -2233,14 +2233,14 @@ shaderinfos::VertexKey Bundle3D::parseGLProgramAttribute(const std::string& str) } } -void Bundle3D::getModelRelativePath(const std::string& path) +void Bundle3D::getModelRelativePath(std::string_view path) { ssize_t index = path.find_last_of('/'); std::string fullModelPath; _modelPath = path.substr(0, index + 1); } -Reference* Bundle3D::seekToFirstType(unsigned int type, const std::string& id) +Reference* Bundle3D::seekToFirstType(unsigned int type, std::string_view id) { // for each Reference for (unsigned int i = 0; i < _referenceCount; ++i) @@ -2266,7 +2266,7 @@ Reference* Bundle3D::seekToFirstType(unsigned int type, const std::string& id) return nullptr; } -std::vector Bundle3D::getTrianglesList(const std::string& path) +std::vector Bundle3D::getTrianglesList(std::string_view path) { std::vector trianglesList; diff --git a/cocos/3d/CCBundle3D.h b/cocos/3d/CCBundle3D.h index 1a92eeb20d..6fb3d760a1 100644 --- a/cocos/3d/CCBundle3D.h +++ b/cocos/3d/CCBundle3D.h @@ -64,32 +64,32 @@ public: * get define data type * @param str The type in string */ - static backend::VertexFormat parseGLDataType(const std::string& str, int size); + static backend::VertexFormat parseGLDataType(std::string_view str, int size); /** * get define data type * @param str The type in string */ - static backend::SamplerAddressMode parseSamplerAddressMode(const std::string& str); + static backend::SamplerAddressMode parseSamplerAddressMode(std::string_view str); /** * load a file. You must load a file first, then call loadMeshData, loadSkinData, and so on * @param path File to be loaded * @return result of load */ - virtual bool load(const std::string& path); + virtual bool load(std::string_view path); /** * load skin data from bundle * @param id The ID of the skin, load the first Skin in the bundle if it is empty */ - virtual bool loadSkinData(const std::string& id, SkinData* skindata); + virtual bool loadSkinData(std::string_view id, SkinData* skindata); /** * load material data from bundle * @param id The ID of the animation, load the first animation in the bundle if it is empty */ - virtual bool loadAnimationData(const std::string& id, Animation3DData* animationdata); + virtual bool loadAnimationData(std::string_view id, Animation3DData* animationdata); // since 3.3, to support reskin virtual bool loadMeshDatas(MeshDatas& meshdatas); @@ -102,21 +102,21 @@ public: * load triangle list * @param path the file path to load */ - static std::vector getTrianglesList(const std::string& path); + static std::vector getTrianglesList(std::string_view path); // load .obj file static bool loadObj(MeshDatas& meshdatas, MaterialDatas& materialdatas, NodeDatas& nodedatas, - const std::string& fullPath, + std::string_view fullPath, const char* mtl_basepath = nullptr); // calculate aabb static AABB calculateAABB(const std::vector& vertex, int stride, const std::vector& index); protected: - bool loadJson(const std::string& path); - bool loadBinary(const std::string& path); + bool loadJson(std::string_view path); + bool loadBinary(std::string_view path); bool loadMeshDatasJson(MeshDatas& meshdatas); bool loadMeshDataJson_0_1(MeshDatas& meshdatas); bool loadMeshDataJson_0_2(MeshDatas& meshdatas); @@ -137,8 +137,8 @@ protected: bool loadMaterialDataJson(MaterialData* materialdata); bool loadMaterialDataJson_0_1(MaterialData* materialdata); bool loadMaterialDataJson_0_2(MaterialData* materialdata); - bool loadAnimationDataJson(const std::string& id, Animation3DData* animationdata); - bool loadAnimationDataBinary(const std::string& id, Animation3DData* animationdata); + bool loadAnimationDataJson(std::string_view id, Animation3DData* animationdata); + bool loadAnimationDataBinary(std::string_view id, Animation3DData* animationdata); /** * load nodes of json @@ -156,26 +156,26 @@ protected: * get define data type * @param str The type in string */ - NTextureData::Usage parseGLTextureType(const std::string& str); + NTextureData::Usage parseGLTextureType(std::string_view str); /** * get vertex attribute type * @param str The type in string */ - shaderinfos::VertexKey parseGLProgramAttribute(const std::string& str); + shaderinfos::VertexKey parseGLProgramAttribute(std::string_view str); /* * get model path * @param str Full path of model file */ - void getModelRelativePath(const std::string& path); + void getModelRelativePath(std::string_view path); /* * set the read position in buffer to the target type * @param The data type * @param The data id */ - Reference* seekToFirstType(unsigned int type, const std::string& id = ""); + Reference* seekToFirstType(unsigned int type, std::string_view id = ""); CC_CONSTRUCTOR_ACCESS : Bundle3D(); virtual ~Bundle3D(); diff --git a/cocos/3d/CCBundle3DData.h b/cocos/3d/CCBundle3DData.h index 2f54bdfcf2..2538209458 100644 --- a/cocos/3d/CCBundle3DData.h +++ b/cocos/3d/CCBundle3DData.h @@ -220,21 +220,21 @@ struct SkinData rootBoneIndex = -1; } - void addSkinBoneNames(const std::string& name) + void addSkinBoneNames(std::string_view name) { auto it = std::find(skinBoneNames.begin(), skinBoneNames.end(), name); if (it == skinBoneNames.end()) - skinBoneNames.push_back(name); + skinBoneNames.push_back(std::string{name}); } - void addNodeBoneNames(const std::string& name) + void addNodeBoneNames(std::string_view name) { auto it = std::find(nodeBoneNames.begin(), nodeBoneNames.end(), name); if (it == nodeBoneNames.end()) - nodeBoneNames.push_back(name); + nodeBoneNames.push_back(std::string{name}); } - int getSkinBoneNameIndex(const std::string& name) const + int getSkinBoneNameIndex(std::string_view name) const { int i = 0; for (const auto& iter : skinBoneNames) @@ -246,7 +246,7 @@ struct SkinData return -1; } - int getBoneNameIndex(const std::string& name) const + int getBoneNameIndex(std::string_view name) const { int i = 0; for (const auto& iter : skinBoneNames) @@ -323,7 +323,7 @@ struct MaterialDatas { std::vector materials; void resetData() { materials.clear(); } - const NMaterialData* getMaterialData(const std::string& materialid) const + const NMaterialData* getMaterialData(std::string_view materialid) const { for (const auto& it : materials) { diff --git a/cocos/3d/CCMesh.cpp b/cocos/3d/CCMesh.cpp index 92a9434da0..31aa63a016 100644 --- a/cocos/3d/CCMesh.cpp +++ b/cocos/3d/CCMesh.cpp @@ -228,7 +228,7 @@ Mesh* Mesh::create(const std::vector& vertices, return create("", indexData); } -Mesh* Mesh::create(const std::string& name, MeshIndexData* indexData, MeshSkin* skin) +Mesh* Mesh::create(std::string_view name, MeshIndexData* indexData, MeshSkin* skin) { auto state = new Mesh(); state->autorelease(); @@ -255,7 +255,7 @@ bool Mesh::isVisible() const return _visible; } -void Mesh::setTexture(const std::string& texPath) +void Mesh::setTexture(std::string_view texPath) { _texFile = texPath; auto tex = Director::getInstance()->getTextureCache()->addImage(texPath); @@ -307,7 +307,7 @@ void Mesh::setTexture(Texture2D* tex, NTextureData::Usage usage, bool cacheFileN } } -void Mesh::setTexture(const std::string& texPath, NTextureData::Usage usage) +void Mesh::setTexture(std::string_view texPath, NTextureData::Usage usage) { auto tex = Director::getInstance()->getTextureCache()->addImage(texPath); setTexture(tex, usage); diff --git a/cocos/3d/CCMesh.h b/cocos/3d/CCMesh.h index bbd9610b7a..3f8490edca 100644 --- a/cocos/3d/CCMesh.h +++ b/cocos/3d/CCMesh.h @@ -83,7 +83,7 @@ public: * create mesh * @lua NA */ - static Mesh* create(const std::string& name, MeshIndexData* indexData, MeshSkin* skin = nullptr); + static Mesh* create(std::string_view name, MeshIndexData* indexData, MeshSkin* skin = nullptr); /** * get vertex buffer @@ -109,7 +109,7 @@ public: * call setTexture(texPath, NTextureData::Usage::Diffuse) * @param texPath texture path */ - void setTexture(const std::string& texPath); + void setTexture(std::string_view texPath); /** * set texture (diffuse), which is responsible for the main appearance. It is also means main texture, you can also * call setTexture(texPath, NTextureData::Usage::Diffuse) @@ -128,7 +128,7 @@ public: * @param texPath texture path * @param usage Usage of this texture */ - void setTexture(const std::string& texPath, NTextureData::Usage usage); + void setTexture(std::string_view texPath, NTextureData::Usage usage); /** * Get texture (diffuse), which is responsible for the main appearance. It is also means main texture, you can also * call getTexture(NTextureData::Usage::Diffuse) @@ -168,7 +168,7 @@ public: backend::ProgramState* getProgramState() const; /**name getter */ - const std::string& getName() const { return _name; } + std::string_view getName() const { return _name; } void setBlendFunc(const BlendFunc& blendFunc); const BlendFunc& getBlendFunc() const; @@ -225,7 +225,7 @@ public: /**Mesh index data setter*/ void setMeshIndexData(MeshIndexData* indexdata); /**name setter*/ - void setName(const std::string& name) { _name = name; } + void setName(std::string_view name) { _name = name; } /** * calculate the AABB of the mesh diff --git a/cocos/3d/CCMeshSkin.cpp b/cocos/3d/CCMeshSkin.cpp index 903ff6cc7b..868aa50e08 100644 --- a/cocos/3d/CCMeshSkin.cpp +++ b/cocos/3d/CCMeshSkin.cpp @@ -75,7 +75,7 @@ Bone3D* MeshSkin::getBoneByIndex(unsigned int index) const return nullptr; } -Bone3D* MeshSkin::getBoneByName(const std::string& id) const +Bone3D* MeshSkin::getBoneByName(std::string_view id) const { // search from skin bones for (const auto& it : _skinBones) diff --git a/cocos/3d/CCMeshSkin.h b/cocos/3d/CCMeshSkin.h index 13df178572..3533f11337 100644 --- a/cocos/3d/CCMeshSkin.h +++ b/cocos/3d/CCMeshSkin.h @@ -54,7 +54,7 @@ class CC_DLL MeshSkin : public Ref public: /**create a new meshskin if do not want to share meshskin*/ - static MeshSkin* create(Skeleton3D* skeleton, const std::string& filename, const std::string& name); + static MeshSkin* create(Skeleton3D* skeleton, std::string_view filename, std::string_view name); static MeshSkin* create(Skeleton3D* skeleton, const std::vector& boneNames, @@ -65,7 +65,7 @@ public: /**get bone*/ Bone3D* getBoneByIndex(unsigned int index) const; - Bone3D* getBoneByName(const std::string& id) const; + Bone3D* getBoneByName(std::string_view id) const; /**get bone index*/ int getBoneIndex(Bone3D* bone) const; diff --git a/cocos/3d/CCMeshVertexIndexData.cpp b/cocos/3d/CCMeshVertexIndexData.cpp index 0f4c730859..3e0544022d 100644 --- a/cocos/3d/CCMeshVertexIndexData.cpp +++ b/cocos/3d/CCMeshVertexIndexData.cpp @@ -49,7 +49,7 @@ using namespace std; NS_CC_BEGIN ///////////////////////////////////////////////////////////////////////////////////////////////////////////// -MeshIndexData* MeshIndexData::create(const std::string& id, +MeshIndexData* MeshIndexData::create(std::string_view id, MeshVertexData* vertexData, backend::Buffer* indexbuffer, const AABB& aabb) @@ -160,7 +160,7 @@ MeshVertexData* MeshVertexData::create(const MeshData& meshdata) return vertexdata; } -MeshIndexData* MeshVertexData::getMeshIndexDataById(const std::string& id) const +MeshIndexData* MeshVertexData::getMeshIndexDataById(std::string_view id) const { for (auto it : _indexs) { diff --git a/cocos/3d/CCMeshVertexIndexData.h b/cocos/3d/CCMeshVertexIndexData.h index a65a9ab641..ef68b9455c 100644 --- a/cocos/3d/CCMeshVertexIndexData.h +++ b/cocos/3d/CCMeshVertexIndexData.h @@ -55,7 +55,7 @@ class CC_DLL MeshIndexData : public Ref { public: /** create */ - static MeshIndexData* create(const std::string& id, + static MeshIndexData* create(std::string_view id, MeshVertexData* vertexData, backend::Buffer* indexbuffer, const AABB& aabb); @@ -74,8 +74,8 @@ public: const AABB& getAABB() const { return _aabb; } /** id setter and getter */ - void setId(const std::string& id) { _id = id; } - const std::string& getId() const { return _id; } + void setId(std::string_view id) { _id = id; } + std::string_view getId() const { return _id; } /**primitive type setter & getter*/ MeshCommand::PrimitiveType getPrimitiveType() const { return _primitiveType; } @@ -128,7 +128,7 @@ public: /** get index data by index */ MeshIndexData* getMeshIndexDataByIndex(int index) const { return _indexs.at(index); } /** get index data by id */ - MeshIndexData* getMeshIndexDataById(const std::string& id) const; + MeshIndexData* getMeshIndexDataById(std::string_view id) const; ssize_t getSizePerVertex() const { return _sizePerVertex; } diff --git a/cocos/3d/CCMotionStreak3D.cpp b/cocos/3d/CCMotionStreak3D.cpp index e7ca8d32df..6337c9fd66 100644 --- a/cocos/3d/CCMotionStreak3D.cpp +++ b/cocos/3d/CCMotionStreak3D.cpp @@ -61,7 +61,7 @@ MotionStreak3D* MotionStreak3D::create(float fade, float minSeg, float stroke, const Color3B& color, - const std::string& path) + std::string_view path) { MotionStreak3D* ret = new MotionStreak3D(); if (ret && ret->initWithFade(fade, minSeg, stroke, color, path)) @@ -87,7 +87,7 @@ MotionStreak3D* MotionStreak3D::create(float fade, float minSeg, float stroke, c return nullptr; } -bool MotionStreak3D::initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path) +bool MotionStreak3D::initWithFade(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path) { CCASSERT(!path.empty(), "Invalid filename"); diff --git a/cocos/3d/CCMotionStreak3D.h b/cocos/3d/CCMotionStreak3D.h index 6b020a02cd..59111ff86d 100644 --- a/cocos/3d/CCMotionStreak3D.h +++ b/cocos/3d/CCMotionStreak3D.h @@ -61,7 +61,7 @@ public: float minSeg, float stroke, const Color3B& color, - const std::string& path); + std::string_view path); /** Creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture. * * @param fade The fade time, in seconds. @@ -164,7 +164,7 @@ public: /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture filename */ - bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path); + bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path); /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture */ bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture); diff --git a/cocos/3d/CCObjLoader.cpp b/cocos/3d/CCObjLoader.cpp index 4d78b5d475..b3f0935f86 100644 --- a/cocos/3d/CCObjLoader.cpp +++ b/cocos/3d/CCObjLoader.cpp @@ -395,7 +395,7 @@ static bool exportFaceGroupToShape(shape_t& shape, const std::vector& in_texcoords, const std::vector>& faceGroup, const int material_id, - const std::string& name, + std::string_view name, bool clearCache) { if (faceGroup.empty()) @@ -517,7 +517,7 @@ std::string LoadMtl(std::map& material_map, char namebuf[TINYOBJ_SSCANF_BUFFER_SIZE]; token += 7; #ifdef _MSC_VER - sscanf_s(token, "%s", namebuf, _countof(namebuf)); + sscanf_s(token, "%s", namebuf, static_cast(_countof(namebuf))); #else sscanf(token, "%s", namebuf); #endif @@ -681,7 +681,7 @@ std::string LoadMtl(std::map& material_map, return err.str(); } -std::string MaterialFileReader::operator()(const std::string& matId, +std::string MaterialFileReader::operator()(std::string_view matId, std::vector& materials, std::map& matMap) { @@ -689,7 +689,7 @@ std::string MaterialFileReader::operator()(const std::string& matId, if (!m_mtlBasePath.empty()) { - filepath = std::string(m_mtlBasePath) + matId; + filepath.append(m_mtlBasePath).append(matId); } else { diff --git a/cocos/3d/CCObjLoader.h b/cocos/3d/CCObjLoader.h index ef0dde2912..af64222dc3 100644 --- a/cocos/3d/CCObjLoader.h +++ b/cocos/3d/CCObjLoader.h @@ -75,7 +75,7 @@ public: MaterialReader() {} virtual ~MaterialReader() {} - virtual std::string operator()(const std::string& matId, + virtual std::string operator()(std::string_view matId, std::vector& materials, std::map& matMap) = 0; }; @@ -83,9 +83,9 @@ public: class MaterialFileReader : public MaterialReader { public: - MaterialFileReader(const std::string& mtl_basepath) : m_mtlBasePath(mtl_basepath) {} + MaterialFileReader(std::string_view mtl_basepath) : m_mtlBasePath(mtl_basepath) {} virtual ~MaterialFileReader() {} - virtual std::string operator()(const std::string& matId, + virtual std::string operator()(std::string_view matId, std::vector& materials, std::map& matMap); diff --git a/cocos/3d/CCSkeleton3D.cpp b/cocos/3d/CCSkeleton3D.cpp index 4bf8763fba..7aa8d6a386 100644 --- a/cocos/3d/CCSkeleton3D.cpp +++ b/cocos/3d/CCSkeleton3D.cpp @@ -136,7 +136,7 @@ void Bone3D::clearBoneBlendState() /** * Creates C3DBone. */ -Bone3D* Bone3D::create(const std::string& id) +Bone3D* Bone3D::create(std::string_view id) { auto bone = new Bone3D(id); bone->autorelease(); @@ -185,7 +185,7 @@ void Bone3D::removeAllChildBone() _children.clear(); } -Bone3D::Bone3D(const std::string& id) : _name(id), _parent(nullptr), _worldDirty(true) {} +Bone3D::Bone3D(std::string_view id) : _name(id), _parent(nullptr), _worldDirty(true) {} Bone3D::~Bone3D() { @@ -279,7 +279,7 @@ Bone3D* Skeleton3D::getBoneByIndex(unsigned int index) const return nullptr; } -Bone3D* Skeleton3D::getBoneByName(const std::string& id) const +Bone3D* Skeleton3D::getBoneByName(std::string_view id) const { // search from bones for (auto it : _bones) diff --git a/cocos/3d/CCSkeleton3D.h b/cocos/3d/CCSkeleton3D.h index e63a06050c..bd13a8a959 100644 --- a/cocos/3d/CCSkeleton3D.h +++ b/cocos/3d/CCSkeleton3D.h @@ -61,7 +61,7 @@ public: const Mat4& getWorldMat(); /**get bone name*/ - const std::string& getName() const { return _name; } + std::string_view getName() const { return _name; } /** * set animation value @@ -78,7 +78,7 @@ public: /** * Creates C3DBone. */ - static Bone3D* create(const std::string& id); + static Bone3D* create(std::string_view id); /** * Sets the inverse bind pose matrix. @@ -139,7 +139,7 @@ protected: /** * Constructor. */ - Bone3D(const std::string& id); + Bone3D(std::string_view id); /** * Destructor. @@ -190,7 +190,7 @@ public: /**get bone*/ Bone3D* getBoneByIndex(unsigned int index) const; - Bone3D* getBoneByName(const std::string& id) const; + Bone3D* getBoneByName(std::string_view id) const; /**get & set root bone*/ ssize_t getRootCount() const; diff --git a/cocos/3d/CCSkybox.cpp b/cocos/3d/CCSkybox.cpp index e21c9770f8..7e9d1fc2e8 100644 --- a/cocos/3d/CCSkybox.cpp +++ b/cocos/3d/CCSkybox.cpp @@ -41,12 +41,12 @@ Skybox::~Skybox() _texture->release(); } -Skybox* Skybox::create(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z) +Skybox* Skybox::create(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z) { auto ret = new Skybox(); ret->init(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z); @@ -90,12 +90,12 @@ bool Skybox::init() return true; } -bool Skybox::init(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z) +bool Skybox::init(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z) { auto texture = TextureCube::create(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z); if (texture == nullptr) diff --git a/cocos/3d/CCSkybox.h b/cocos/3d/CCSkybox.h index 644da64463..40560f2978 100644 --- a/cocos/3d/CCSkybox.h +++ b/cocos/3d/CCSkybox.h @@ -58,12 +58,12 @@ public: @param negative_z texture for the rear side of the texture cube face. @return A new skybox inited with given parameters. */ - static Skybox* create(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z); + static Skybox* create(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z); /**texture getter and setter*/ void setTexture(TextureCube*); @@ -93,12 +93,12 @@ public: /** * initialize with texture path */ - bool init(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z); + bool init(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z); protected: /** diff --git a/cocos/3d/CCSprite3D.cpp b/cocos/3d/CCSprite3D.cpp index 3dcdf8e65a..f4d2e8cb68 100644 --- a/cocos/3d/CCSprite3D.cpp +++ b/cocos/3d/CCSprite3D.cpp @@ -63,7 +63,7 @@ Sprite3D* Sprite3D::create() return nullptr; } -Sprite3D* Sprite3D::create(const std::string& modelPath) +Sprite3D* Sprite3D::create(std::string_view modelPath) { CCASSERT(modelPath.length() >= 4, "invalid filename for Sprite3D"); @@ -77,7 +77,7 @@ Sprite3D* Sprite3D::create(const std::string& modelPath) CC_SAFE_DELETE(sprite); return nullptr; } -Sprite3D* Sprite3D::create(const std::string& modelPath, const std::string& texturePath) +Sprite3D* Sprite3D::create(std::string_view modelPath, std::string_view texturePath) { auto sprite = create(modelPath); if (sprite) @@ -88,15 +88,15 @@ Sprite3D* Sprite3D::create(const std::string& modelPath, const std::string& text return sprite; } -void Sprite3D::createAsync(const std::string& modelPath, +void Sprite3D::createAsync(std::string_view modelPath, const std::function& callback, void* callbackparam) { createAsync(modelPath, "", callback, callbackparam); } -void Sprite3D::createAsync(const std::string& modelPath, - const std::string& texturePath, +void Sprite3D::createAsync(std::string_view modelPath, + std::string_view texturePath, const std::function& callback, void* callbackparam) { @@ -197,7 +197,7 @@ AABB Sprite3D::getAABBRecursivelyImp(Node* node) return aabb; } -bool Sprite3D::loadFromCache(const std::string& path) +bool Sprite3D::loadFromCache(std::string_view path) { auto spritedata = Sprite3DCache::getInstance()->getSpriteData(path); if (spritedata) @@ -238,7 +238,7 @@ bool Sprite3D::loadFromCache(const std::string& path) return false; } -bool Sprite3D::loadFromFile(const std::string& path, +bool Sprite3D::loadFromFile(std::string_view path, NodeDatas* nodedatas, MeshDatas* meshdatas, MaterialDatas* materialdatas) @@ -296,7 +296,7 @@ bool Sprite3D::init() return false; } -bool Sprite3D::initWithFile(const std::string& path) +bool Sprite3D::initWithFile(std::string_view path) { _aabbDirty = true; _meshes.clear(); @@ -654,7 +654,7 @@ void Sprite3D::createNode(NodeData* nodedata, Node* root, const MaterialDatas& m } } -MeshIndexData* Sprite3D::getMeshIndexData(const std::string& indexId) const +MeshIndexData* Sprite3D::getMeshIndexData(std::string_view indexId) const { for (auto it : _meshVertexDatas) { @@ -672,7 +672,7 @@ void Sprite3D::addMesh(Mesh* mesh) _meshes.pushBack(mesh); } -void Sprite3D::setTexture(const std::string& texFile) +void Sprite3D::setTexture(std::string_view texFile) { auto tex = _director->getTextureCache()->addImage(texFile); setTexture(tex); @@ -685,7 +685,7 @@ void Sprite3D::setTexture(Texture2D* texture) mesh->setTexture(texture); } } -AttachNode* Sprite3D::getAttachNode(const std::string& boneName) +AttachNode* Sprite3D::getAttachNode(std::string_view boneName) { auto it = _attachments.find(boneName); if (it != _attachments.end()) @@ -698,7 +698,7 @@ AttachNode* Sprite3D::getAttachNode(const std::string& boneName) { auto attachNode = AttachNode::create(bone); addChild(attachNode); - _attachments[boneName] = attachNode; + _attachments.emplace(boneName, attachNode); // _attachments[boneName] = attachNode; return attachNode; } } @@ -706,7 +706,7 @@ AttachNode* Sprite3D::getAttachNode(const std::string& boneName) return nullptr; } -void Sprite3D::removeAttachNode(const std::string& boneName) +void Sprite3D::removeAttachNode(std::string_view boneName) { auto it = _attachments.find(boneName); if (it != _attachments.end()) @@ -918,7 +918,7 @@ Mesh* Sprite3D::getMeshByIndex(int index) const } /**get Mesh by Name */ -Mesh* Sprite3D::getMeshByName(const std::string& name) const +Mesh* Sprite3D::getMeshByName(std::string_view name) const { for (const auto& it : _meshes) { @@ -928,7 +928,7 @@ Mesh* Sprite3D::getMeshByName(const std::string& name) const return nullptr; } -std::vector Sprite3D::getMeshArrayByName(const std::string& name) const +std::vector Sprite3D::getMeshArrayByName(std::string_view name) const { std::vector meshes; for (const auto& it : _meshes) @@ -973,7 +973,7 @@ void Sprite3DCache::destroyInstance() } } -Sprite3DCache::Sprite3DData* Sprite3DCache::getSpriteData(const std::string& key) const +Sprite3DCache::Sprite3DData* Sprite3DCache::getSpriteData(std::string_view key) const { auto it = _spriteDatas.find(key); if (it != _spriteDatas.end()) @@ -981,18 +981,18 @@ Sprite3DCache::Sprite3DData* Sprite3DCache::getSpriteData(const std::string& key return nullptr; } -bool Sprite3DCache::addSprite3DData(const std::string& key, Sprite3DCache::Sprite3DData* spritedata) +bool Sprite3DCache::addSprite3DData(std::string_view key, Sprite3DCache::Sprite3DData* spritedata) { auto it = _spriteDatas.find(key); if (it == _spriteDatas.end()) { - _spriteDatas[key] = spritedata; + _spriteDatas.emplace(key, spritedata); // _spriteDatas[key] = spritedata; return true; } return false; } -void Sprite3DCache::removeSprite3DData(const std::string& key) +void Sprite3DCache::removeSprite3DData(std::string_view key) { auto it = _spriteDatas.find(key); if (it != _spriteDatas.end()) diff --git a/cocos/3d/CCSprite3D.h b/cocos/3d/CCSprite3D.h index 477b6968ce..ec5127ecd3 100644 --- a/cocos/3d/CCSprite3D.h +++ b/cocos/3d/CCSprite3D.h @@ -62,10 +62,10 @@ public: static Sprite3D* create(); /** creates a Sprite3D*/ - static Sprite3D* create(const std::string& modelPath); + static Sprite3D* create(std::string_view modelPath); // creates a Sprite3D. It only supports one texture, and overrides the internal texture with 'texturePath' - static Sprite3D* create(const std::string& modelPath, const std::string& texturePath); + static Sprite3D* create(std::string_view modelPath, std::string_view texturePath); /** create 3d sprite asynchronously * If the 3d model was previously loaded, it will create a new 3d sprite and the callback will be called at once. @@ -76,31 +76,31 @@ public: * @param callback callback after loading * @param callbackparam user defined parameter for the callback */ - static void createAsync(const std::string& modelPath, + static void createAsync(std::string_view modelPath, const std::function& callback, void* callbackparam); - static void createAsync(const std::string& modelPath, - const std::string& texturePath, + static void createAsync(std::string_view modelPath, + std::string_view texturePath, const std::function& callback, void* callbackparam); /**set diffuse texture, set the first if multiple textures exist*/ - void setTexture(const std::string& texFile); + void setTexture(std::string_view texFile); void setTexture(Texture2D* texture); /**get Mesh by index*/ Mesh* getMeshByIndex(int index) const; /**get Mesh by Name, it returns the first one if there are more than one mesh with the same name */ - Mesh* getMeshByName(const std::string& name) const; + Mesh* getMeshByName(std::string_view name) const; /** * get mesh array by name, returns all meshes with the given name * * @lua NA */ - std::vector getMeshArrayByName(const std::string& name) const; + std::vector getMeshArrayByName(std::string_view name) const; /**get mesh*/ Mesh* getMesh() const; @@ -111,10 +111,10 @@ public: Skeleton3D* getSkeleton() const { return _skeleton; } /**get AttachNode by bone name, return nullptr if not exist*/ - AttachNode* getAttachNode(const std::string& boneName); + AttachNode* getAttachNode(std::string_view boneName); /**remove attach node*/ - void removeAttachNode(const std::string& boneName); + void removeAttachNode(std::string_view boneName); /**remove all attach nodes*/ void removeAllAttachNode(); @@ -214,16 +214,16 @@ public: virtual bool init() override; - bool initWithFile(const std::string& path); + bool initWithFile(std::string_view path); bool initFrom(const NodeDatas& nodedatas, const MeshDatas& meshdatas, const MaterialDatas& materialdatas); /**load sprite3d from cache, return true if succeed, false otherwise*/ - bool loadFromCache(const std::string& path); + bool loadFromCache(std::string_view path); /** load file and set it to meshedatas, nodedatas and materialdatas, obj file .mtl file should be at the same * directory if exist */ - bool loadFromFile(const std::string& path, + bool loadFromFile(std::string_view path, NodeDatas* nodedatas, MeshDatas* meshdatas, MaterialDatas* materialdatas); @@ -242,7 +242,7 @@ public: Sprite3D* createSprite3DNode(NodeData* nodedata, ModelData* modeldata, const MaterialDatas& materialdatas); /**get MeshIndexData by Id*/ - MeshIndexData* getMeshIndexData(const std::string& indexId) const; + MeshIndexData* getMeshIndexData(std::string_view indexId) const; void addMesh(Mesh* mesh); @@ -257,7 +257,7 @@ protected: Vector _meshVertexDatas; - std::unordered_map _attachments; + hlookup::string_map _attachments; BlendFunc _blend; @@ -319,17 +319,17 @@ public: * * @lua NA */ - Sprite3DData* getSpriteData(const std::string& key) const; + Sprite3DData* getSpriteData(std::string_view key) const; /** * add the SpriteData into Sprite3D by given the specified key * * @lua NA */ - bool addSprite3DData(const std::string& key, Sprite3DData* spritedata); + bool addSprite3DData(std::string_view key, Sprite3DData* spritedata); /**remove the SpriteData from Sprite3D by given the specified key*/ - void removeSprite3DData(const std::string& key); + void removeSprite3DData(std::string_view key); /**remove all the SpriteData from Sprite3D*/ void removeAllSprite3DData(); @@ -339,7 +339,7 @@ public: protected: static Sprite3DCache* _cacheInstance; - std::unordered_map _spriteDatas; // cached sprite data + hlookup::string_map _spriteDatas; // cached sprite data }; // end of 3d group diff --git a/cocos/3d/CCSprite3DMaterial.cpp b/cocos/3d/CCSprite3DMaterial.cpp index 5be1ec6974..7181b6bfc4 100644 --- a/cocos/3d/CCSprite3DMaterial.cpp +++ b/cocos/3d/CCSprite3DMaterial.cpp @@ -238,7 +238,7 @@ Sprite3DMaterial* Sprite3DMaterial::createBuiltInMaterial(MaterialType type, boo return nullptr; } -Sprite3DMaterial* Sprite3DMaterial::createWithFilename(const std::string& path) +Sprite3DMaterial* Sprite3DMaterial::createWithFilename(std::string_view path) { auto validfilename = FileUtils::getInstance()->fullPathForFilename(path); if (!validfilename.empty()) @@ -311,19 +311,19 @@ void Sprite3DMaterialCache::destroyInstance() } } -bool Sprite3DMaterialCache::addSprite3DMaterial(const std::string& key, Texture2D* texture) +bool Sprite3DMaterialCache::addSprite3DMaterial(std::string_view key, Texture2D* texture) { auto itr = _materials.find(key); if (itr == _materials.end()) { CC_SAFE_RETAIN(texture); - _materials[key] = texture; + _materials.emplace(key, texture); return true; } return false; } -Texture2D* Sprite3DMaterialCache::getSprite3DMaterial(const std::string& key) +Texture2D* Sprite3DMaterialCache::getSprite3DMaterial(std::string_view key) { auto itr = _materials.find(key); if (itr != _materials.end()) @@ -337,7 +337,7 @@ void Sprite3DMaterialCache::removeAllSprite3DMaterial() { for (auto& itr : _materials) { - CC_SAFE_RELEASE_NULL(itr.second); + CC_SAFE_RELEASE_NULL(const_cast(itr.second)); } _materials.clear(); } diff --git a/cocos/3d/CCSprite3DMaterial.h b/cocos/3d/CCSprite3DMaterial.h index 1a128d0218..d89fc10a33 100644 --- a/cocos/3d/CCSprite3DMaterial.h +++ b/cocos/3d/CCSprite3DMaterial.h @@ -87,7 +87,7 @@ public: * @param path Path of material file * @return Created material */ - static Sprite3DMaterial* createWithFilename(const std::string& path); + static Sprite3DMaterial* createWithFilename(std::string_view path); /** * Create material with GLProgramState @@ -162,10 +162,10 @@ public: static void destroyInstance(); /**add to cache*/ - bool addSprite3DMaterial(const std::string& key, Texture2D* tex); + bool addSprite3DMaterial(std::string_view key, Texture2D* tex); /**get material from cache*/ - Texture2D* getSprite3DMaterial(const std::string& key); + Texture2D* getSprite3DMaterial(std::string_view key); /**remove all spritematerial*/ void removeAllSprite3DMaterial(); @@ -179,7 +179,7 @@ public: protected: static Sprite3DMaterialCache* _cacheInstance; // instance - std::unordered_map _materials; // cached material + hlookup::string_map _materials; // cached material }; // end of 3d group diff --git a/cocos/3d/CCTerrain.cpp b/cocos/3d/CCTerrain.cpp index cc3bea4f6c..df626733e8 100644 --- a/cocos/3d/CCTerrain.cpp +++ b/cocos/3d/CCTerrain.cpp @@ -83,7 +83,7 @@ bool Terrain::initWithTerrainData(TerrainData& parameter, CrackFixedType fixedTy return initResult; } -void cocos2d::Terrain::setLightMap(const std::string& fileName) +void cocos2d::Terrain::setLightMap(std::string_view fileName) { CC_SAFE_RELEASE(_lightMap); auto image = new Image(); @@ -197,7 +197,7 @@ void Terrain::draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, } } -bool Terrain::initHeightMap(const std::string& heightMap) +bool Terrain::initHeightMap(std::string_view heightMap) { _heightMapImage = new Image(); _heightMapImage->initWithImageFile(heightMap); @@ -611,7 +611,7 @@ cocos2d::Vec2 Terrain::convertToTerrainSpace(const Vec2& worldSpaceXZ) const return Vec2(image_x, image_y); } -void Terrain::resetHeightMap(const std::string& heightMap) +void Terrain::resetHeightMap(std::string_view heightMap) { _heightMapImage->release(); _vertices.clear(); @@ -1154,8 +1154,8 @@ void Terrain::Chunk::updateIndicesLOD() } memcpy(_neighborOldLOD, currentNeighborLOD, sizeof(currentNeighborLOD)); _oldLod = _currentLod; - int gridY = _size.height; - int gridX = _size.width; + int gridY = static_cast(_size.height); + int gridX = static_cast(_size.width); int step = 1 << _currentLod; if ((_left && _left->_currentLod > _currentLod) || (_right && _right->_currentLod > _currentLod) || @@ -1644,8 +1644,8 @@ Terrain::QuadTree::~QuadTree() delete _br; } -Terrain::TerrainData::TerrainData(const std::string& heightMapsrc, - const std::string& textureSrc, +Terrain::TerrainData::TerrainData(std::string_view heightMapsrc, + std::string_view textureSrc, const Vec2& chunksize, float height, float scale) @@ -1659,8 +1659,8 @@ Terrain::TerrainData::TerrainData(const std::string& heightMapsrc, _skirtHeightRatio = 1; } -Terrain::TerrainData::TerrainData(const std::string& heightMapsrc, - const std::string& alphamap, +Terrain::TerrainData::TerrainData(std::string_view heightMapsrc, + std::string_view alphamap, const DetailMap& detail1, const DetailMap& detail2, const DetailMap& detail3, @@ -1682,8 +1682,8 @@ Terrain::TerrainData::TerrainData(const std::string& heightMapsrc, _skirtHeightRatio = 1; } -Terrain::TerrainData::TerrainData(const std::string& heightMapsrc, - const std::string& alphamap, +Terrain::TerrainData::TerrainData(std::string_view heightMapsrc, + std::string_view alphamap, const DetailMap& detail1, const DetailMap& detail2, const DetailMap& detail3, @@ -1729,7 +1729,7 @@ Terrain::ChunkIndices::~ChunkIndices() CC_SAFE_RELEASE_NULL(_indexBuffer); } -Terrain::DetailMap::DetailMap(const std::string& detailMapPath, float size /*= 35*/) +Terrain::DetailMap::DetailMap(std::string_view detailMapPath, float size /*= 35*/) { this->_detailMapSrc = detailMapPath; this->_detailMapSize = size; diff --git a/cocos/3d/CCTerrain.h b/cocos/3d/CCTerrain.h index 25ebc401c9..e05a5721b2 100644 --- a/cocos/3d/CCTerrain.h +++ b/cocos/3d/CCTerrain.h @@ -108,7 +108,7 @@ public: { /*Constructors*/ DetailMap(); - DetailMap(const std::string& detailMapSrc, float size = 35); + DetailMap(std::string_view detailMapSrc, float size = 35); /*detail Image source file path*/ std::string _detailMapSrc; /*detailMapSize determine how many tiles that Terrain represent*/ @@ -136,14 +136,14 @@ public: /**empty constructor*/ TerrainData(); /**constructor, this constructor construct a simple terrain which only have 1 detailmap*/ - TerrainData(const std::string& heightMapsrc, - const std::string& textureSrc, + TerrainData(std::string_view heightMapsrc, + std::string_view textureSrc, const Vec2& chunksize = Vec2(32, 32), float mapHeight = 2, float mapScale = 0.1); /**constructor, this constructor construct a terrain which have 4 detailmaps, 1 alpha map*/ - TerrainData(const std::string& heightMapsrc, - const std::string& alphamap, + TerrainData(std::string_view heightMapsrc, + std::string_view alphamap, const DetailMap& detail1, const DetailMap& detail2, const DetailMap& detail3, @@ -152,8 +152,8 @@ public: float mapHeight = 2, float mapScale = 0.1); /**constructor, this constructor construct a terrain which have 3 detailmaps, 1 alpha map*/ - TerrainData(const std::string& heightMapsrc, - const std::string& alphamap, + TerrainData(std::string_view heightMapsrc, + std::string_view alphamap, const DetailMap& detail1, const DetailMap& detail2, const DetailMap& detail3, @@ -337,7 +337,7 @@ private: public: /** set light map texture */ - void setLightMap(const std::string& fileName); + void setLightMap(std::string_view fileName); /** set directional light for the terrain @@ -349,7 +349,7 @@ public: /**initialize all Properties which terrain need */ bool initProperties(); /**initialize heightMap data */ - bool initHeightMap(const std::string& heightMap); + bool initHeightMap(std::string_view heightMap); /**initialize alphaMap ,detailMaps textures*/ bool initTextures(); /**create entry*/ @@ -429,7 +429,7 @@ public: /** * reset the heightmap data. */ - void resetHeightMap(const std::string& heightMap); + void resetHeightMap(std::string_view heightMap); /** * get the terrain's minimal height. diff --git a/cocos/3d/CCVertexAttribBinding.cpp b/cocos/3d/CCVertexAttribBinding.cpp index 9aa5e165b7..761a061dd8 100644 --- a/cocos/3d/CCVertexAttribBinding.cpp +++ b/cocos/3d/CCVertexAttribBinding.cpp @@ -133,7 +133,7 @@ bool VertexAttribBinding::hasAttribute(const shaderinfos::VertexKey& key) const return _attributes.find(name) != _attributes.end(); } -backend::AttributeBindInfo* VertexAttribBinding::getVertexAttribValue(const std::string& name) +backend::AttributeBindInfo* VertexAttribBinding::getVertexAttribValue(std::string_view name) { const auto itr = _attributes.find(name); if (itr != _attributes.end()) @@ -141,7 +141,7 @@ backend::AttributeBindInfo* VertexAttribBinding::getVertexAttribValue(const std: return nullptr; } -void VertexAttribBinding::setVertexAttribPointer(const std::string& name, +void VertexAttribBinding::setVertexAttribPointer(std::string_view name, backend::VertexFormat type, bool normalized, int offset, diff --git a/cocos/3d/CCVertexAttribBinding.h b/cocos/3d/CCVertexAttribBinding.h index 20879586c0..e923782625 100644 --- a/cocos/3d/CCVertexAttribBinding.h +++ b/cocos/3d/CCVertexAttribBinding.h @@ -107,18 +107,18 @@ private: VertexAttribBinding& operator=(const VertexAttribBinding&); bool init(MeshIndexData* meshIndexData, Pass* pass, MeshCommand*); - void setVertexAttribPointer(const std::string& name, + void setVertexAttribPointer(std::string_view name, backend::VertexFormat type, bool normalized, int offset, int flag); - backend::AttributeBindInfo* getVertexAttribValue(const std::string& name); + backend::AttributeBindInfo* getVertexAttribValue(std::string_view name); void parseAttributes(); MeshIndexData* _meshIndexData; backend::ProgramState* _programState; std::shared_ptr _vertexLayout = std::make_shared(); - std::unordered_map _attributes; + hlookup::string_map _attributes; uint32_t _vertexAttribsFlags; }; diff --git a/cocos/audio/include/AudioDecoder.h b/cocos/audio/include/AudioDecoder.h index 1e1a27043d..780ddc2933 100644 --- a/cocos/audio/include/AudioDecoder.h +++ b/cocos/audio/include/AudioDecoder.h @@ -60,7 +60,7 @@ public: * @brief Opens an audio file specified by a file path. * @return true if succeed, otherwise false. */ - virtual bool open(const std::string& path) = 0; + virtual bool open(std::string_view path) = 0; /** * @brief Checks whether decoder has opened file successfully. diff --git a/cocos/audio/include/AudioDecoderEXT.h b/cocos/audio/include/AudioDecoderEXT.h index d8d598c8ae..f6eea0dbd2 100644 --- a/cocos/audio/include/AudioDecoderEXT.h +++ b/cocos/audio/include/AudioDecoderEXT.h @@ -49,7 +49,7 @@ public: * @brief Opens an audio file specified by a file path. * @return true if succeed, otherwise false. */ - bool open(const std::string& path) override; + bool open(std::string_view path) override; /** * @brief Closes opened audio file. diff --git a/cocos/audio/include/AudioDecoderManager.h b/cocos/audio/include/AudioDecoderManager.h index fe5c2d1ed9..3075bf10d9 100644 --- a/cocos/audio/include/AudioDecoderManager.h +++ b/cocos/audio/include/AudioDecoderManager.h @@ -37,7 +37,7 @@ class AudioDecoderManager public: static bool init(); static void destroy(); - static AudioDecoder* createDecoder(const std::string& path); + static AudioDecoder* createDecoder(std::string_view path); static void destroyDecoder(AudioDecoder* decoder); }; diff --git a/cocos/audio/include/AudioDecoderMp3.h b/cocos/audio/include/AudioDecoderMp3.h index a8be6fbeb3..9731157397 100644 --- a/cocos/audio/include/AudioDecoderMp3.h +++ b/cocos/audio/include/AudioDecoderMp3.h @@ -52,7 +52,7 @@ public: * @brief Opens an audio file specified by a file path. * @return true if succeed, otherwise false. */ - bool open(const std::string& path) override; + bool open(std::string_view path) override; /** * @brief Closes opened audio file. diff --git a/cocos/audio/include/AudioDecoderOgg.h b/cocos/audio/include/AudioDecoderOgg.h index 0ca447b680..18d86ebced 100644 --- a/cocos/audio/include/AudioDecoderOgg.h +++ b/cocos/audio/include/AudioDecoderOgg.h @@ -44,7 +44,7 @@ public: * @brief Opens an audio file specified by a file path. * @return true if succeed, otherwise false. */ - bool open(const std::string& path) override; + bool open(std::string_view path) override; /** * @brief Closes opened audio file. diff --git a/cocos/audio/include/AudioDecoderWav.h b/cocos/audio/include/AudioDecoderWav.h index 5986449463..8e9e101dd2 100644 --- a/cocos/audio/include/AudioDecoderWav.h +++ b/cocos/audio/include/AudioDecoderWav.h @@ -128,7 +128,7 @@ public: * @brief Opens an audio file specified by a file path. * @return true if succeed, otherwise false. */ - bool open(const std::string& path) override; + bool open(std::string_view path) override; /** * @brief The helper function for convert frames to bytes diff --git a/cocos/audio/include/AudioEngine.h b/cocos/audio/include/AudioEngine.h index ee89635def..2d864b78ee 100644 --- a/cocos/audio/include/AudioEngine.h +++ b/cocos/audio/include/AudioEngine.h @@ -126,7 +126,7 @@ public: * * @see `AudioProfile` */ - static AUDIO_ID play2d(const std::string& filePath, + static AUDIO_ID play2d(std::string_view filePath, bool loop = false, float volume = 1.0f, const AudioProfile* profile = nullptr); @@ -232,7 +232,7 @@ public: * @param audioID An audioID returned by the play2d function. * @param callback */ - static void setFinishCallback(AUDIO_ID audioID, const std::function& callback); + static void setFinishCallback(AUDIO_ID audioID, const std::function& callback); /** * Gets the maximum number of simultaneous audio instance of AudioEngine. @@ -253,7 +253,7 @@ public: * @warning This can lead to stop related audio first. * @param filePath Audio file path. */ - static void uncache(const std::string& filePath); + static void uncache(std::string_view filePath); /** * Uncache all audio data from internal buffer. @@ -276,20 +276,20 @@ public: * @param profileName A name of audio profile. * @return The audio profile. */ - static AudioProfile* getProfile(const std::string& profileName); + static AudioProfile* getProfile(std::string_view profileName); /** * Preload audio file. * @param filePath The file path of an audio. */ - static void preload(const std::string& filePath) { preload(filePath, nullptr); } + static void preload(std::string_view filePath) { preload(filePath, nullptr); } /** * Preload audio file. * @param filePath The file path of an audio. * @param callback A callback which will be called after loading is finished. */ - static void preload(const std::string& filePath, std::function callback); + static void preload(std::string_view filePath, std::function callback); /** * Gets playing audio count. @@ -346,10 +346,10 @@ protected: static std::unordered_map _audioIDInfoMap; // audio file path,audio IDs - static std::unordered_map> _audioPathIDMap; + static hlookup::string_map> _audioPathIDMap; // profileName,ProfileHelper - static std::unordered_map _audioPathProfileHelperMap; + static hlookup::string_map _audioPathProfileHelperMap; static unsigned int _maxInstances; diff --git a/cocos/audio/include/AudioEngineImpl.h b/cocos/audio/include/AudioEngineImpl.h index cbb5c7284a..eb1c4c9610 100644 --- a/cocos/audio/include/AudioEngineImpl.h +++ b/cocos/audio/include/AudioEngineImpl.h @@ -49,7 +49,7 @@ public: ~AudioEngineImpl(); bool init(); - AUDIO_ID play2d(const std::string& fileFullPath, bool loop, float volume); + AUDIO_ID play2d(std::string_view fileFullPath, bool loop, float volume); void setVolume(AUDIO_ID audioID, float volume); void setLoop(AUDIO_ID audioID, bool loop); bool pause(AUDIO_ID audioID); @@ -59,11 +59,11 @@ public: float getDuration(AUDIO_ID audioID); float getCurrentTime(AUDIO_ID audioID); bool setCurrentTime(AUDIO_ID audioID, float time); - void setFinishCallback(AUDIO_ID audioID, const std::function& callback); + void setFinishCallback(AUDIO_ID audioID, const std::function& callback); - void uncache(const std::string& filePath); + void uncache(std::string_view filePath); void uncacheAll(); - AudioCache* preload(const std::string& filePath, std::function callback); + AudioCache* preload(std::string_view filePath, std::function callback); void update(float dt); private: @@ -81,7 +81,7 @@ private: std::queue _unusedSourcesPool; // filePath,bufferInfo - std::unordered_map _audioCaches; + hlookup::string_map> _audioCaches; // audioID,AudioInfo std::unordered_map _audioPlayers; diff --git a/cocos/audio/include/AudioPlayer.h b/cocos/audio/include/AudioPlayer.h index e114c5ea81..81512b98d9 100644 --- a/cocos/audio/include/AudioPlayer.h +++ b/cocos/audio/include/AudioPlayer.h @@ -72,7 +72,7 @@ protected: float _volume; bool _loop; - std::function _finishCallbak; + std::function _finishCallbak; bool _isDestroyed; bool _removeByAudioEngine; diff --git a/cocos/audio/src/AudioDecoderEXT.mm b/cocos/audio/src/AudioDecoderEXT.mm index d310eb38e8..3b1a99bc10 100644 --- a/cocos/audio/src/AudioDecoderEXT.mm +++ b/cocos/audio/src/AudioDecoderEXT.mm @@ -45,7 +45,7 @@ namespace cocos2d { closeInternal(); } - bool AudioDecoderEXT::open(const std::string& fullPath) + bool AudioDecoderEXT::open(std::string_view fullPath) { bool ret = false; CFURLRef fileURL = nil; diff --git a/cocos/audio/src/AudioDecoderManager.cpp b/cocos/audio/src/AudioDecoderManager.cpp index fc0730e1c4..879d893a63 100644 --- a/cocos/audio/src/AudioDecoderManager.cpp +++ b/cocos/audio/src/AudioDecoderManager.cpp @@ -60,7 +60,7 @@ void AudioDecoderManager::destroy() #endif } -AudioDecoder* AudioDecoderManager::createDecoder(const std::string& path) +AudioDecoder* AudioDecoderManager::createDecoder(std::string_view path) { cxx17::string_view svPath(path); if (cxx20::ic::ends_with(svPath, ".ogg")) diff --git a/cocos/audio/src/AudioDecoderMp3.cpp b/cocos/audio/src/AudioDecoderMp3.cpp index a1c8c2cc5a..b02cecc2a1 100644 --- a/cocos/audio/src/AudioDecoderMp3.cpp +++ b/cocos/audio/src/AudioDecoderMp3.cpp @@ -126,7 +126,7 @@ AudioDecoderMp3::~AudioDecoderMp3() close(); } -bool AudioDecoderMp3::open(const std::string& fullPath) +bool AudioDecoderMp3::open(std::string_view fullPath) { #if !CC_USE_MPG123 do diff --git a/cocos/audio/src/AudioDecoderOgg.cpp b/cocos/audio/src/AudioDecoderOgg.cpp index 15c4cc9ce8..bad5a4f6f4 100644 --- a/cocos/audio/src/AudioDecoderOgg.cpp +++ b/cocos/audio/src/AudioDecoderOgg.cpp @@ -70,7 +70,7 @@ AudioDecoderOgg::~AudioDecoderOgg() close(); } -bool AudioDecoderOgg::open(const std::string& fullPath) +bool AudioDecoderOgg::open(std::string_view fullPath) { auto fs = FileUtils::getInstance()->openFileStream(fullPath, FileStream::Mode::READ).release(); if (!fs) diff --git a/cocos/audio/src/AudioDecoderWav.cpp b/cocos/audio/src/AudioDecoderWav.cpp index 28366caed4..3d6be1e0fe 100644 --- a/cocos/audio/src/AudioDecoderWav.cpp +++ b/cocos/audio/src/AudioDecoderWav.cpp @@ -78,7 +78,7 @@ static bool wav_scan_chunk(WAV_FILE* wavf, uint32_t chunkID, void* header, void* } return false; } -static bool wav_open(const std::string& fullPath, WAV_FILE* wavf) +static bool wav_open(std::string_view fullPath, WAV_FILE* wavf) { wavf->Stream = FileUtils::getInstance()->openFileStream(fullPath, FileStream::Mode::READ); if (!wavf->Stream) @@ -192,7 +192,7 @@ AudioDecoderWav::~AudioDecoderWav() close(); } -bool AudioDecoderWav::open(const std::string& fullPath) +bool AudioDecoderWav::open(std::string_view fullPath) { if (wav_open(fullPath, &_wavf)) { diff --git a/cocos/audio/src/AudioEngine.cpp b/cocos/audio/src/AudioEngine.cpp index a59ac5b9a9..8590394e97 100644 --- a/cocos/audio/src/AudioEngine.cpp +++ b/cocos/audio/src/AudioEngine.cpp @@ -47,9 +47,9 @@ const int AudioEngine::INVALID_AUDIO_ID = -1; const float AudioEngine::TIME_UNKNOWN = -1.0f; // audio file path,audio IDs -std::unordered_map> AudioEngine::_audioPathIDMap; +hlookup::string_map> AudioEngine::_audioPathIDMap; // profileName,ProfileHelper -std::unordered_map AudioEngine::_audioPathProfileHelperMap; +hlookup::string_map AudioEngine::_audioPathProfileHelperMap; unsigned int AudioEngine::_maxInstances = MAX_AUDIOINSTANCES; AudioEngine::ProfileHelper* AudioEngine::_defaultProfileHelper = nullptr; std::unordered_map AudioEngine::_audioIDInfoMap; @@ -172,7 +172,7 @@ bool AudioEngine::lazyInit() return true; } -AUDIO_ID AudioEngine::play2d(const std::string& filePath, bool loop, float volume, const AudioProfile* profile) +AUDIO_ID AudioEngine::play2d(std::string_view filePath, bool loop, float volume, const AudioProfile* profile) { AUDIO_ID ret = AudioEngine::INVALID_AUDIO_ID; @@ -203,7 +203,7 @@ AUDIO_ID AudioEngine::play2d(const std::string& filePath, bool loop, float volum if (_audioIDInfoMap.size() >= _maxInstances) { - log("Fail to play %s cause by limited max instance of AudioEngine", filePath.c_str()); + log("Fail to play %s cause by limited max instance of AudioEngine", filePath.data()); break; } if (profileHelper) @@ -211,7 +211,7 @@ AUDIO_ID AudioEngine::play2d(const std::string& filePath, bool loop, float volum if (profileHelper->profile.maxInstances != 0 && profileHelper->audioIDs.size() >= profileHelper->profile.maxInstances) { - log("Fail to play %s cause by limited max instance of AudioProfile", filePath.c_str()); + log("Fail to play %s cause by limited max instance of AudioProfile", filePath.data()); break; } if (profileHelper->profile.minDelay > TIME_DELAY_PRECISION) @@ -220,7 +220,7 @@ AUDIO_ID AudioEngine::play2d(const std::string& filePath, bool loop, float volum if (profileHelper->lastPlayTime > TIME_DELAY_PRECISION && currTime - profileHelper->lastPlayTime <= profileHelper->profile.minDelay) { - log("Fail to play %s cause by limited minimum delay", filePath.c_str()); + log("Fail to play %s cause by limited minimum delay", filePath.data()); break; } } @@ -238,7 +238,7 @@ AUDIO_ID AudioEngine::play2d(const std::string& filePath, bool loop, float volum ret = _audioEngineImpl->play2d(filePath, loop, volume); if (ret != INVALID_AUDIO_ID) { - _audioPathIDMap[filePath].push_back(ret); + _audioPathIDMap[filePath.data()].push_back(ret); auto it = _audioPathIDMap.find(filePath); auto& audioRef = _audioIDInfoMap[ret]; @@ -380,7 +380,7 @@ void AudioEngine::stopAll() _audioIDInfoMap.clear(); } -void AudioEngine::uncache(const std::string& filePath) +void AudioEngine::uncache(std::string_view filePath) { if (!_audioEngineImpl) { @@ -463,7 +463,7 @@ float AudioEngine::getCurrentTime(AUDIO_ID audioID) return 0.0f; } -void AudioEngine::setFinishCallback(AUDIO_ID audioID, const std::function& callback) +void AudioEngine::setFinishCallback(AUDIO_ID audioID, const std::function& callback) { auto it = _audioIDInfoMap.find(audioID); if (it != _audioIDInfoMap.end()) @@ -539,7 +539,7 @@ AudioProfile* AudioEngine::getDefaultProfile() return &_defaultProfileHelper->profile; } -AudioProfile* AudioEngine::getProfile(const std::string& name) +AudioProfile* AudioEngine::getProfile(std::string_view name) { auto it = _audioPathProfileHelperMap.find(name); if (it != _audioPathProfileHelperMap.end()) @@ -552,7 +552,7 @@ AudioProfile* AudioEngine::getProfile(const std::string& name) } } -void AudioEngine::preload(const std::string& filePath, std::function callback) +void AudioEngine::preload(std::string_view filePath, std::function callback) { if (!isEnabled()) { diff --git a/cocos/audio/src/AudioEngineImpl.mm b/cocos/audio/src/AudioEngineImpl.mm index f51ed483fc..55809b1fb5 100644 --- a/cocos/audio/src/AudioEngineImpl.mm +++ b/cocos/audio/src/AudioEngineImpl.mm @@ -32,7 +32,7 @@ #include "audio/include/AudioDecoderManager.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC -#import +# import #endif #include "audio/include/AudioEngine.h" @@ -42,31 +42,33 @@ #include "base/ccUtils.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS -#import +# import #endif using namespace cocos2d; -static ALCdevice* s_ALDevice = nullptr; -static ALCcontext* s_ALContext = nullptr; +static ALCdevice* s_ALDevice = nullptr; +static ALCcontext* s_ALContext = nullptr; static AudioEngineImpl* s_instance = nullptr; -static void ccALPauseDevice() { +static void ccALPauseDevice() +{ ALOGD("%s", "===> ccALPauseDevice"); #if CC_USE_ALSOFT alcDevicePauseSOFT(s_ALDevice); #else - if(alcGetCurrentContext()) + if (alcGetCurrentContext()) alcMakeContextCurrent(nullptr); #endif } -static void ccALResumeDevice() { +static void ccALResumeDevice() +{ ALOGD("%s", "===> ccALResumeDevice"); #if CC_USE_ALSOFT alcDeviceResumeSOFT(s_ALDevice); #else - if(alcGetCurrentContext()) + if (alcGetCurrentContext()) alcMakeContextCurrent(nullptr); alcMakeContextCurrent(s_ALContext); #endif @@ -75,8 +77,14 @@ static void ccALResumeDevice() { #if defined(__APPLE__) typedef ALvoid (*alSourceNotificationProc)(ALuint sid, ALuint notificationID, ALvoid* userData); -typedef ALenum (*alSourceAddNotificationProcPtr)(ALuint sid, ALuint notificationID, alSourceNotificationProc notifyProc, ALvoid* userData); -static ALenum alSourceAddNotificationExt(ALuint sid, ALuint notificationID, alSourceNotificationProc notifyProc, ALvoid* userData) +typedef ALenum (*alSourceAddNotificationProcPtr)(ALuint sid, + ALuint notificationID, + alSourceNotificationProc notifyProc, + ALvoid* userData); +static ALenum alSourceAddNotificationExt(ALuint sid, + ALuint notificationID, + alSourceNotificationProc notifyProc, + ALvoid* userData) { static alSourceAddNotificationProcPtr proc = nullptr; @@ -92,42 +100,48 @@ static ALenum alSourceAddNotificationExt(ALuint sid, ALuint notificationID, alSo return AL_INVALID_VALUE; } -#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS -@interface AudioEngineSessionHandler : NSObject -{ +# if CC_TARGET_PLATFORM == CC_PLATFORM_IOS +@interface AudioEngineSessionHandler : NSObject { } --(id) init; --(void)handleInterruption:(NSNotification*)notification; +- (id)init; +- (void)handleInterruption:(NSNotification*)notification; @end @implementation AudioEngineSessionHandler --(id) init +- (id)init { if (self = [super init]) { int deviceVer = [[[UIDevice currentDevice] systemVersion] intValue]; ALOGD("===> The device version: %d", deviceVer); - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:UIApplicationDidBecomeActiveNotification object:nil]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:UIApplicationWillResignActiveNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(handleInterruption:) + name:AVAudioSessionInterruptionNotification + object:[AVAudioSession sharedInstance]]; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(handleInterruption:) + name:UIApplicationDidBecomeActiveNotification + object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(handleInterruption:) + name:UIApplicationWillResignActiveNotification + object:nil]; - BOOL success = [[AVAudioSession sharedInstance] - setCategory: AVAudioSessionCategoryAmbient - error: nil]; + BOOL success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil]; if (!success) ALOGE("Fail to set audio session."); } return self; } --(void)handleInterruption:(NSNotification*)notification +- (void)handleInterruption:(NSNotification*)notification { static bool isAudioSessionInterrupted = false; - static bool resumeOnBecomingActive = false; - static bool pauseOnResignActive = false; + static bool resumeOnBecomingActive = false; + static bool pauseOnResignActive = false; if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification]) { @@ -138,13 +152,15 @@ static ALenum alSourceAddNotificationExt(ALuint sid, ALuint notificationID, alSo if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) { - ALOGD("AVAudioSessionInterruptionTypeBegan, application != UIApplicationStateActive, alcMakeContextCurrent(nullptr)"); + ALOGD("AVAudioSessionInterruptionTypeBegan, application != UIApplicationStateActive, " + "alcMakeContextCurrent(nullptr)"); } else { - ALOGD("AVAudioSessionInterruptionTypeBegan, application == UIApplicationStateActive, pauseOnResignActive = true"); + ALOGD("AVAudioSessionInterruptionTypeBegan, application == UIApplicationStateActive, " + "pauseOnResignActive = true"); } - + // We always pause device when interruption began ccALPauseDevice(); } @@ -154,8 +170,9 @@ static ALenum alSourceAddNotificationExt(ALuint sid, ALuint notificationID, alSo if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) { - ALOGD("AVAudioSessionInterruptionTypeEnded, application == UIApplicationStateActive, alcMakeContextCurrent(s_ALContext)"); - NSError *error = nil; + ALOGD("AVAudioSessionInterruptionTypeEnded, application == UIApplicationStateActive, " + "alcMakeContextCurrent(s_ALContext)"); + NSError* error = nil; [[AVAudioSession sharedInstance] setActive:YES error:&error]; ccALResumeDevice(); if (Director::getInstance()->isPaused()) @@ -166,7 +183,8 @@ static ALenum alSourceAddNotificationExt(ALuint sid, ALuint notificationID, alSo } else { - ALOGD("AVAudioSessionInterruptionTypeEnded, application != UIApplicationStateActive, resumeOnBecomingActive = true"); + ALOGD("AVAudioSessionInterruptionTypeEnded, application != UIApplicationStateActive, " + "resumeOnBecomingActive = true"); resumeOnBecomingActive = true; } } @@ -188,14 +206,15 @@ static ALenum alSourceAddNotificationExt(ALuint sid, ALuint notificationID, alSo { resumeOnBecomingActive = false; ALOGD("UIApplicationDidBecomeActiveNotification, alcMakeContextCurrent(s_ALContext)"); - NSError *error = nil; - BOOL success = [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: &error]; - if (!success) { + NSError* error = nil; + BOOL success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&error]; + if (!success) + { ALOGE("Fail to set audio session."); return; } [[AVAudioSession sharedInstance] setActive:YES error:&error]; - + ccALResumeDevice(); } else if (isAudioSessionInterrupted) @@ -205,18 +224,20 @@ static ALenum alSourceAddNotificationExt(ALuint sid, ALuint notificationID, alSo } } --(void) dealloc +- (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionInterruptionNotification object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil]; - [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:self + name:UIApplicationWillResignActiveNotification + object:nil]; [super dealloc]; } @end static id s_AudioEngineSessionHandler = nullptr; -#endif +# endif ALvoid AudioEngineImpl::myAlSourceNotificationCallback(ALuint sid, ALuint notificationID, ALvoid* userData) { @@ -239,10 +260,7 @@ ALvoid AudioEngineImpl::myAlSourceNotificationCallback(ALuint sid, ALuint notifi #endif -AudioEngineImpl::AudioEngineImpl() -: _scheduled(false) -, _currentAudioID(0) -, _scheduler(nullptr) +AudioEngineImpl::AudioEngineImpl() : _scheduled(false), _currentAudioID(0), _scheduler(nullptr) { s_instance = this; } @@ -254,7 +272,8 @@ AudioEngineImpl::~AudioEngineImpl() _scheduler->unschedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this); } - if (s_ALContext) { + if (s_ALContext) + { alDeleteSources(MAX_AUDIOINSTANCES, _alSources); _audioCaches.clear(); @@ -264,7 +283,8 @@ AudioEngineImpl::~AudioEngineImpl() s_ALContext = nullptr; } - if (s_ALDevice) { + if (s_ALDevice) + { alcCloseDevice(s_ALDevice); s_ALDevice = nullptr; } @@ -280,30 +300,34 @@ AudioEngineImpl::~AudioEngineImpl() bool AudioEngineImpl::init() { bool ret = false; - do{ + do + { #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS s_AudioEngineSessionHandler = [[AudioEngineSessionHandler alloc] init]; #endif s_ALDevice = alcOpenDevice(nullptr); - if (s_ALDevice) { + if (s_ALDevice) + { alGetError(); s_ALContext = alcCreateContext(s_ALDevice, nullptr); alcMakeContextCurrent(s_ALContext); alGenSources(MAX_AUDIOINSTANCES, _alSources); auto alError = alGetError(); - if(alError != AL_NO_ERROR) + if (alError != AL_NO_ERROR) { ALOGE("%s:generating sources failed! error = %x\n", __FUNCTION__, alError); break; } - for (int i = 0; i < MAX_AUDIOINSTANCES; ++i) { + for (int i = 0; i < MAX_AUDIOINSTANCES; ++i) + { _unusedSourcesPool.push(_alSources[i]); #if defined(__APPLE__) - alSourceAddNotificationExt(_alSources[i], AL_BUFFERS_PROCESSED, myAlSourceNotificationCallback, nullptr); + alSourceAddNotificationExt(_alSources[i], AL_BUFFERS_PROCESSED, myAlSourceNotificationCallback, + nullptr); #endif } @@ -368,28 +392,30 @@ bool AudioEngineImpl::init() #endif // ================ Workaround end ================ // - _scheduler = Director::getInstance()->getScheduler(); - ret = AudioDecoderManager::init(); - const char* vender = alGetString(AL_VENDOR); + _scheduler = Director::getInstance()->getScheduler(); + ret = AudioDecoderManager::init(); + const char* vender = alGetString(AL_VENDOR); const char* version = alGetString(AL_VERSION); ALOGI("OpenAL was initialized successfully, vender:%s, version:%s", vender, version); } - }while (false); + } while (false); return ret; } -AudioCache* AudioEngineImpl::preload(const std::string& filePath, std::function callback) +AudioCache* AudioEngineImpl::preload(std::string_view filePath, std::function callback) { AudioCache* audioCache = nullptr; auto it = _audioCaches.find(filePath); - if (it == _audioCaches.end()) { - audioCache = &_audioCaches[filePath]; + if (it == _audioCaches.end()) + { + audioCache = new AudioCache(); // hlookup_second(it); + _audioCaches.emplace(filePath, std::unique_ptr(audioCache)); audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath); - unsigned int cacheId = audioCache->_id; - auto isCacheDestroyed = audioCache->_isDestroyed; - AudioEngine::addTask([audioCache, cacheId, isCacheDestroyed](){ + unsigned int cacheId = audioCache->_id; + auto isCacheDestroyed = audioCache->_isDestroyed; + AudioEngine::addTask([audioCache, cacheId, isCacheDestroyed]() { if (*isCacheDestroyed) { ALOGV("AudioCache (id=%u) was destroyed, no need to launch readDataTask.", cacheId); @@ -399,8 +425,9 @@ AudioCache* AudioEngineImpl::preload(const std::string& filePath, std::function< audioCache->readDataTask(cacheId); }); } - else { - audioCache = &it->second; + else + { + audioCache = it->second.get(); } if (audioCache && callback) @@ -410,9 +437,10 @@ AudioCache* AudioEngineImpl::preload(const std::string& filePath, std::function< return audioCache; } -AUDIO_ID AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume) +AUDIO_ID AudioEngineImpl::play2d(std::string_view filePath, bool loop, float volume) { - if (s_ALDevice == nullptr) { + if (s_ALDevice == nullptr) + { return AudioEngine::INVALID_AUDIO_ID; } @@ -423,16 +451,18 @@ AUDIO_ID AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float v } auto player = new AudioPlayer; - if (player == nullptr) { + if (player == nullptr) + { return AudioEngine::INVALID_AUDIO_ID; } player->_alSource = alSource; - player->_loop = loop; - player->_volume = volume; + player->_loop = loop; + player->_volume = volume; auto audioCache = preload(filePath, nullptr); - if (audioCache == nullptr) { + if (audioCache == nullptr) + { delete player; return AudioEngine::INVALID_AUDIO_ID; } @@ -442,7 +472,7 @@ AUDIO_ID AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float v _audioPlayers.emplace(++_currentAudioID, player); _threadMutex.unlock(); - audioCache->addPlayCallback(std::bind(&AudioEngineImpl::_play2d,this,audioCache,_currentAudioID)); + audioCache->addPlayCallback(std::bind(&AudioEngineImpl::_play2d, this, audioCache, _currentAudioID)); if (!_scheduled) { @@ -453,7 +483,7 @@ AUDIO_ID AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float v return _currentAudioID; } -void AudioEngineImpl::_play2d(AudioCache *cache, AUDIO_ID audioID) +void AudioEngineImpl::_play2d(AudioCache* cache, AUDIO_ID audioID) { std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); @@ -461,13 +491,14 @@ void AudioEngineImpl::_play2d(AudioCache *cache, AUDIO_ID audioID) return; auto player = iter->second; - //Note: It maybe in sub thread or main thread :( + // Note: It maybe in sub thread or main thread :( if (!*cache->_isDestroyed && cache->_state == AudioCache::State::READY) { - if (player->play2d()) { - _scheduler->performFunctionInCocosThread([audioID](){ - - if (AudioEngine::_audioIDInfoMap.find(audioID) != AudioEngine::_audioIDInfoMap.end()) { + if (player->play2d()) + { + _scheduler->performFunctionInCocosThread([audioID]() { + if (AudioEngine::_audioIDInfoMap.find(audioID) != AudioEngine::_audioIDInfoMap.end()) + { AudioEngine::_audioIDInfoMap[audioID].state = AudioEngine::AudioState::PLAYING; } }); @@ -492,23 +523,25 @@ ALuint AudioEngineImpl::findValidSource() return sourceId; } -void AudioEngineImpl::setVolume(AUDIO_ID audioID,float volume) +void AudioEngineImpl::setVolume(AUDIO_ID audioID, float volume) { std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if(iter == _audioPlayers.end()) + if (iter == _audioPlayers.end()) return; - + auto player = iter->second; lck.unlock(); - + player->_volume = volume; - if (player->_ready) { + if (player->_ready) + { alSourcef(player->_alSource, AL_GAIN, volume); auto error = alGetError(); - if (error != AL_NO_ERROR) { + if (error != AL_NO_ERROR) + { ALOGE("%s: audio id = " AUDIO_ID_PRID ", error = %x", __FUNCTION__, audioID, error); } } @@ -518,30 +551,39 @@ void AudioEngineImpl::setLoop(AUDIO_ID audioID, bool loop) { std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if(iter == _audioPlayers.end()) + if (iter == _audioPlayers.end()) return; - + auto player = iter->second; lck.unlock(); - - if (player->_ready) { - if (player->_streamingSource) { + + if (player->_ready) + { + if (player->_streamingSource) + { player->setLoop(loop); - } else { - if (loop) { + } + else + { + if (loop) + { alSourcei(player->_alSource, AL_LOOPING, AL_TRUE); - } else { + } + else + { alSourcei(player->_alSource, AL_LOOPING, AL_FALSE); } auto error = alGetError(); - if (error != AL_NO_ERROR) { + if (error != AL_NO_ERROR) + { ALOGE("%s: audio id = " AUDIO_ID_PRID ", error = %x", __FUNCTION__, audioID, error); } } } - else { + else + { player->_loop = loop; } } @@ -550,18 +592,19 @@ bool AudioEngineImpl::pause(AUDIO_ID audioID) { std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if(iter == _audioPlayers.end()) + if (iter == _audioPlayers.end()) return false; - + auto player = iter->second; - + lck.unlock(); - + bool ret = true; alSourcePause(player->_alSource); auto error = alGetError(); - if (error != AL_NO_ERROR) { + if (error != AL_NO_ERROR) + { ret = false; ALOGE("%s: audio id = " AUDIO_ID_PRID ", error = %x\n", __FUNCTION__, audioID, error); } @@ -574,16 +617,17 @@ bool AudioEngineImpl::resume(AUDIO_ID audioID) bool ret = true; std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if(iter == _audioPlayers.end()) + if (iter == _audioPlayers.end()) return false; - + auto player = iter->second; lck.unlock(); - + alSourcePlay(player->_alSource); auto error = alGetError(); - if (error != AL_NO_ERROR) { + if (error != AL_NO_ERROR) + { ret = false; ALOGE("%s: audio id = " AUDIO_ID_PRID ", error = %x\n", __FUNCTION__, audioID, error); } @@ -595,29 +639,30 @@ void AudioEngineImpl::stop(AUDIO_ID audioID) { std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if(iter == _audioPlayers.end()) + if (iter == _audioPlayers.end()) return; - + auto player = iter->second; player->destroy(); - // Call '_updatePlayersState' method to cleanup immediately since the schedule may be cancelled without any notification. + // Call '_updatePlayersState' method to cleanup immediately since the schedule may be cancelled without any + // notification. _updatePlayers(true); } void AudioEngineImpl::stopAll() { std::lock_guard lck(_threadMutex); - for(auto&& player : _audioPlayers) + for (auto&& player : _audioPlayers) { player.second->destroy(); } - //Note: Don't set the flag to false here, it should be set in 'update' function. + // Note: Don't set the flag to false here, it should be set in 'update' function. // Otherwise, the state got from alSourceState may be wrong -// for(int index = 0; index < MAX_AUDIOINSTANCES; ++index) -// { -// _alSourceUsed[_alSources[index]] = false; -// } + // for(int index = 0; index < MAX_AUDIOINSTANCES; ++index) + // { + // _alSourceUsed[_alSources[index]] = false; + // } // Call '_updatePlayers' method to cleanup immediately since the schedule may be cancelled without any notification. _updatePlayers(true); @@ -627,9 +672,11 @@ float AudioEngineImpl::getDuration(AUDIO_ID audioID) { std::lock_guard lck(_threadMutex); auto it = _audioPlayers.find(audioID); - if (it != _audioPlayers.end()) { + if (it != _audioPlayers.end()) + { auto player = it->second; - if (player->_ready) { + if (player->_ready) + { return player->_audioCache->_duration; } } @@ -639,21 +686,25 @@ float AudioEngineImpl::getDuration(AUDIO_ID audioID) float AudioEngineImpl::getCurrentTime(AUDIO_ID audioID) { std::unique_lock lck(_threadMutex); - auto it = _audioPlayers.find(audioID); + auto it = _audioPlayers.find(audioID); if (it == _audioPlayers.end()) return 0.0f; - float ret = 0.0f; + float ret = 0.0f; auto player = it->second; - if (player->_ready) { - if (player->_streamingSource) { + if (player->_ready) + { + if (player->_streamingSource) + { ret = player->getTime(); } - else { + else + { alGetSourcef(player->_alSource, AL_SEC_OFFSET, &ret); auto error = alGetError(); - if (error != AL_NO_ERROR) { + if (error != AL_NO_ERROR) + { ALOGE("%s, audio id:" AUDIO_ID_PRID ",error code:%x", __FUNCTION__, audioID, error); } } @@ -667,23 +718,28 @@ bool AudioEngineImpl::setCurrentTime(AUDIO_ID audioID, float time) bool ret = false; std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if(iter == _audioPlayers.end()) + if (iter == _audioPlayers.end()) return false; - + auto player = iter->second; - do { - if (!player->_ready) { + do + { + if (!player->_ready) + { break; } - if (player->_streamingSource) { + if (player->_streamingSource) + { ret = player->setTime(time); break; } - else { + else + { if (player->_audioCache->_framesRead != player->_audioCache->_totalFrames && - (time * player->_audioCache->_sampleRate) > player->_audioCache->_framesRead) { + (time * player->_audioCache->_sampleRate) > player->_audioCache->_framesRead) + { ALOGE("%s: audio id = " AUDIO_ID_PRID, __FUNCTION__, audioID); break; } @@ -691,7 +747,8 @@ bool AudioEngineImpl::setCurrentTime(AUDIO_ID audioID, float time) alSourcef(player->_alSource, AL_SEC_OFFSET, time); auto error = alGetError(); - if (error != AL_NO_ERROR) { + if (error != AL_NO_ERROR) + { ALOGE("%s: audio id = " AUDIO_ID_PRID ", error = %x", __FUNCTION__, audioID, error); } ret = true; @@ -701,16 +758,17 @@ bool AudioEngineImpl::setCurrentTime(AUDIO_ID audioID, float time) return ret; } -void AudioEngineImpl::setFinishCallback(AUDIO_ID audioID, const std::function &callback) +void AudioEngineImpl::setFinishCallback(AUDIO_ID audioID, + const std::function& callback) { std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if(iter == _audioPlayers.end()) + if (iter == _audioPlayers.end()) return; - + auto player = iter->second; lck.unlock(); - + player->_finishCallbak = callback; } @@ -726,45 +784,49 @@ void AudioEngineImpl::_updatePlayers(bool forStop) AudioPlayer* player; ALuint alSource; -// ALOGV("AudioPlayer count: %d", (int)_audioPlayers.size()); - for (auto it = _audioPlayers.begin(); it != _audioPlayers.end(); ) { - audioID = it->first; - player = it->second; + // ALOGV("AudioPlayer count: %d", (int)_audioPlayers.size()); + for (auto it = _audioPlayers.begin(); it != _audioPlayers.end();) + { + audioID = it->first; + player = it->second; alSource = player->_alSource; if (player->_removeByAudioEngine) { AudioEngine::remove(audioID); - + it = _audioPlayers.erase(it); delete player; _unusedSourcesPool.push(alSource); } - else if (player->_ready && player->isFinished()) { + else if (player->_ready && player->isFinished()) + { std::string filePath; - if (player->_finishCallbak) { + if (player->_finishCallbak) + { auto& audioInfo = AudioEngine::_audioIDInfoMap[audioID]; - filePath = audioInfo.filePath; + filePath = audioInfo.filePath; } AudioEngine::remove(audioID); - + it = _audioPlayers.erase(it); - if (player->_finishCallbak) { + if (player->_finishCallbak) + { /// ###IMPORTANT: don't call immidiately, because at callback, user-end may play a new audio /// cause _audioPlayers' iterator goan to invalid. - _finishCallbacks.push_back([finishCallback = std::move(player->_finishCallbak), audioID, filePath = std::move(filePath)](){ - finishCallback(audioID, filePath); - }); + _finishCallbacks.push_back([finishCallback = std::move(player->_finishCallbak), audioID, + filePath = std::move(filePath)]() { finishCallback(audioID, filePath); }); } // clear cache when audio player finsihed properly player->setCache(nullptr); delete player; _unusedSourcesPool.push(alSource); } - else{ + else + { ++it; } } @@ -786,7 +848,8 @@ void AudioEngineImpl::_updatePlayers(bool forStop) _unscheduleUpdate(); } -void AudioEngineImpl::_unscheduleUpdate() { +void AudioEngineImpl::_unscheduleUpdate() +{ if (_scheduled) { _scheduled = false; @@ -794,7 +857,7 @@ void AudioEngineImpl::_unscheduleUpdate() { } } -void AudioEngineImpl::uncache(const std::string &filePath) +void AudioEngineImpl::uncache(std::string_view filePath) { _audioCaches.erase(filePath); } diff --git a/cocos/base/CCAutoreleasePool.cpp b/cocos/base/CCAutoreleasePool.cpp index 9be2e9cdf0..3027fee8a0 100644 --- a/cocos/base/CCAutoreleasePool.cpp +++ b/cocos/base/CCAutoreleasePool.cpp @@ -38,7 +38,7 @@ AutoreleasePool::AutoreleasePool() PoolManager::getInstance()->push(this); } -AutoreleasePool::AutoreleasePool(const std::string& name) +AutoreleasePool::AutoreleasePool(std::string_view name) : _name(name) #if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) , _isClearing(false) diff --git a/cocos/base/CCAutoreleasePool.h b/cocos/base/CCAutoreleasePool.h index fde07e39de..d2a8341ade 100644 --- a/cocos/base/CCAutoreleasePool.h +++ b/cocos/base/CCAutoreleasePool.h @@ -58,7 +58,7 @@ public: * * @param name The name of created autorelease pool. */ - AutoreleasePool(const std::string& name); + AutoreleasePool(std::string_view name); /** * @js NA diff --git a/cocos/base/CCConfiguration.cpp b/cocos/base/CCConfiguration.cpp index 0d623209a9..1979f0225c 100644 --- a/cocos/base/CCConfiguration.cpp +++ b/cocos/base/CCConfiguration.cpp @@ -186,7 +186,7 @@ void Configuration::destroyInstance() CC_SAFE_RELEASE_NULL(s_sharedConfiguration); } -bool Configuration::checkForGLExtension(const std::string& searchName) const +bool Configuration::checkForGLExtension(std::string_view searchName) const { return _glExtensions.find(searchName) != std::string::npos; } @@ -315,7 +315,7 @@ Animate3DQuality Configuration::getAnimate3DQuality() const // // generic getters for properties // -const Value& Configuration::getValue(const std::string& key, const Value& defaultValue) const +const Value& Configuration::getValue(std::string_view key, const Value& defaultValue) const { auto iter = _valueDict.find(key); if (iter != _valueDict.cend()) @@ -324,15 +324,15 @@ const Value& Configuration::getValue(const std::string& key, const Value& defaul return defaultValue; } -void Configuration::setValue(const std::string& key, const Value& value) +void Configuration::setValue(std::string_view key, const Value& value) { - _valueDict[key] = value; + hlookup::set_item(_valueDict, key, value); // _valueDict[key] = value; } // // load file // -void Configuration::loadConfigFile(const std::string& filename) +void Configuration::loadConfigFile(std::string_view filename) { ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(filename); CCASSERT(!dict.empty(), "cannot create dictionary"); @@ -360,14 +360,14 @@ void Configuration::loadConfigFile(const std::string& filename) if (!validMetadata) { - CCLOG("Invalid config format for file: %s", filename.c_str()); + CCLOG("Invalid config format for file: %s", filename.data()); return; } auto dataIter = dict.find("data"); if (dataIter == dict.cend() || dataIter->second.getType() != Value::Type::MAP) { - CCLOG("Expected 'data' dict, but not found. Config file: %s", filename.c_str()); + CCLOG("Expected 'data' dict, but not found. Config file: %s", filename.data()); return; } diff --git a/cocos/base/CCConfiguration.h b/cocos/base/CCConfiguration.h index 9761135884..aefcefbede 100644 --- a/cocos/base/CCConfiguration.h +++ b/cocos/base/CCConfiguration.h @@ -205,7 +205,7 @@ public: * @param searchName A given search name. * @return Is true if an OpenGL is supported. */ - bool checkForGLExtension(const std::string& searchName) const; + bool checkForGLExtension(std::string_view searchName) const; /** Initialize method. * @@ -219,14 +219,14 @@ public: * @param defaultValue if not find the value, return the defaultValue. * @return */ - const Value& getValue(const std::string& key, const Value& defaultValue = Value::Null) const; + const Value& getValue(std::string_view key, const Value& defaultValue = Value::Null) const; /** Sets a new key/value pair in the configuration dictionary. * * @param key A given key. * @param value A given value. */ - void setValue(const std::string& key, const Value& value); + void setValue(std::string_view key, const Value& value); /** Returns the Configuration info. * @@ -243,7 +243,7 @@ public: * * @param filename Config file name. */ - void loadConfigFile(const std::string& filename); + void loadConfigFile(std::string_view filename); static const char* CONFIG_FILE_LOADED; diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index c0953cb9e5..e481a75603 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -204,9 +204,10 @@ std::string& Console::Utility::trim(std::string& s) return Console::Utility::ltrim(Console::Utility::rtrim(s)); } -std::vector& Console::Utility::split(const std::string& s, char delim, std::vector& elems) +std::vector& Console::Utility::split(std::string_view s, char delim, std::vector& elems) { - std::stringstream ss(s); + std::stringstream ss; + ss << s; std::string item; while (std::getline(ss, item, delim)) { @@ -215,7 +216,7 @@ std::vector& Console::Utility::split(const std::string& s, char del return elems; } -std::vector Console::Utility::split(const std::string& s, char delim) +std::vector Console::Utility::split(std::string_view s, char delim) { std::vector elems; Console::Utility::split(s, delim, elems); @@ -223,13 +224,14 @@ std::vector Console::Utility::split(const std::string& s, char deli } // isFloat taken from http://stackoverflow.com/questions/447206/c-isfloat-function -bool Console::Utility::isFloat(const std::string& myString) +bool Console::Utility::isFloat(std::string_view myString) { - std::istringstream iss(myString); + std::stringstream ss; + ss << myString; float f; - iss >> std::noskipws >> f; // noskipws considers leading whitespace invalid + ss >> std::noskipws >> f; // noskipws considers leading whitespace invalid // Check the entire string was consumed and if either failbit or badbit is set - return iss.eof() && !iss.fail(); + return ss.eof() && !ss.fail(); } ssize_t Console::Utility::sendToConsole(int fd, const void* buffer, size_t length, int flags) @@ -275,12 +277,12 @@ void Console::Utility::sendPrompt(int fd) send(fd, prompt, strlen(prompt), 0); } -void Console::Utility::setPrompt(const std::string& prompt) +void Console::Utility::setPrompt(std::string_view prompt) { _prompt = prompt; } -const std::string& Console::Utility::getPrompt() +std::string_view Console::Utility::getPrompt() { return _prompt; } @@ -291,11 +293,11 @@ const std::string& Console::Utility::getPrompt() Console::Command::Command() : _callback(nullptr) {} -Console::Command::Command(const std::string& name, const std::string& help) +Console::Command::Command(std::string_view name, std::string_view help) : _name(name), _help(help), _callback(nullptr) {} -Console::Command::Command(const std::string& name, const std::string& help, const Callback& callback) +Console::Command::Command(std::string_view name, std::string_view help, const Callback& callback) : _name(name), _help(help), _callback(callback) {} @@ -378,7 +380,7 @@ void Console::Command::addSubCommand(const Command& subCmd) _subCommands[subCmd._name] = cmd; } -const Console::Command* Console::Command::getSubCommand(const std::string& subCmdName) const +const Console::Command* Console::Command::getSubCommand(std::string_view subCmdName) const { auto it = _subCommands.find(subCmdName); if (it != _subCommands.end()) @@ -389,7 +391,7 @@ const Console::Command* Console::Command::getSubCommand(const std::string& subCm return nullptr; } -void Console::Command::delSubCommand(const std::string& subCmdName) +void Console::Command::delSubCommand(std::string_view subCmdName) { auto iter = _subCommands.find(subCmdName); if (iter != _subCommands.end()) @@ -399,7 +401,7 @@ void Console::Command::delSubCommand(const std::string& subCmdName) } } -void Console::Command::commandHelp(int fd, const std::string& /*args*/) +void Console::Command::commandHelp(int fd, std::string_view /*args*/) { if (!_help.empty()) { @@ -412,7 +414,7 @@ void Console::Command::commandHelp(int fd, const std::string& /*args*/) } } -void Console::Command::commandGeneric(int fd, const std::string& args) +void Console::Command::commandGeneric(int fd, std::string_view args) { // The first argument (including the empty) std::string key(args); @@ -621,10 +623,10 @@ void Console::addCommand(const Command& cmd) delete iter->second; _commands.erase(iter); } - _commands[cmd.getName()] = newCommand; + _commands.emplace(cmd.getName(), newCommand); // _commands[cmd.getName()] = newCommand; } -void Console::addSubCommand(const std::string& cmdName, const Command& subCmd) +void Console::addSubCommand(std::string_view cmdName, const Command& subCmd) { auto it = _commands.find(cmdName); if (it != _commands.end()) @@ -639,7 +641,7 @@ void Console::addSubCommand(Command& cmd, const Command& subCmd) cmd.addSubCommand(subCmd); } -const Console::Command* Console::getCommand(const std::string& cmdName) +const Console::Command* Console::getCommand(std::string_view cmdName) { auto it = _commands.find(cmdName); if (it != _commands.end()) @@ -650,7 +652,7 @@ const Console::Command* Console::getCommand(const std::string& cmdName) return nullptr; } -const Console::Command* Console::getSubCommand(const std::string& cmdName, const std::string& subCmdName) +const Console::Command* Console::getSubCommand(std::string_view cmdName, std::string_view subCmdName) { auto it = _commands.find(cmdName); if (it != _commands.end()) @@ -661,12 +663,12 @@ const Console::Command* Console::getSubCommand(const std::string& cmdName, const return nullptr; } -const Console::Command* Console::getSubCommand(const Command& cmd, const std::string& subCmdName) +const Console::Command* Console::getSubCommand(const Command& cmd, std::string_view subCmdName) { return cmd.getSubCommand(subCmdName); } -void Console::delCommand(const std::string& cmdName) +void Console::delCommand(std::string_view cmdName) { auto it = _commands.find(cmdName); if (it != _commands.end()) @@ -676,7 +678,7 @@ void Console::delCommand(const std::string& cmdName) } } -void Console::delSubCommand(const std::string& cmdName, const std::string& subCmdName) +void Console::delSubCommand(std::string_view cmdName, std::string_view subCmdName) { auto it = _commands.find(cmdName); if (it != _commands.end()) @@ -686,7 +688,7 @@ void Console::delSubCommand(const std::string& cmdName, const std::string& subCm } } -void Console::delSubCommand(Command& cmd, const std::string& subCmdName) +void Console::delSubCommand(Command& cmd, std::string_view subCmdName) { cmd.delSubCommand(subCmdName); } @@ -701,7 +703,7 @@ void Console::log(const char* buf) } } -void Console::setBindAddress(const std::string& address) +void Console::setBindAddress(std::string_view address) { _bindAddress = address; } @@ -973,7 +975,7 @@ bool Console::parseCommand(socket_native_type fd) return true; } -void Console::performCommand(socket_native_type fd, const std::string& command) +void Console::performCommand(socket_native_type fd, std::string_view command) { std::vector args = Console::Utility::split(command, ' '); if (args.empty()) @@ -998,7 +1000,7 @@ void Console::performCommand(socket_native_type fd, const std::string& command) } else { - throw std::runtime_error("Unknown command " + command + ". Type 'help' for options\n"); + throw std::runtime_error(std::string{"Unknown command "}.append(command).append(". Type 'help' for options\n")); } } @@ -1162,7 +1164,7 @@ void Console::createCommandVersion() // commands // -void Console::commandAllocator(socket_native_type fd, const std::string& /*args*/) +void Console::commandAllocator(socket_native_type fd, std::string_view /*args*/) { #if CC_ENABLE_ALLOCATOR_DIAGNOSTICS auto info = allocator::AllocatorDiagnostics::instance()->diagnostics(); @@ -1173,7 +1175,7 @@ void Console::commandAllocator(socket_native_type fd, const std::string& /*args* #endif } -void Console::commandConfig(socket_native_type fd, const std::string& /*args*/) +void Console::commandConfig(socket_native_type fd, std::string_view /*args*/) { Scheduler* sched = Director::getInstance()->getScheduler(); sched->performFunctionInCocosThread([=]() { @@ -1182,49 +1184,49 @@ void Console::commandConfig(socket_native_type fd, const std::string& /*args*/) }); } -void Console::commandDebugMsg(socket_native_type fd, const std::string& /*args*/) +void Console::commandDebugMsg(socket_native_type fd, std::string_view /*args*/) { Console::Utility::mydprintf(fd, "Debug message is: %s\n", _sendDebugStrings ? "on" : "off"); } -void Console::commandDebugMsgSubCommandOnOff(socket_native_type /*fd*/, const std::string& args) +void Console::commandDebugMsgSubCommandOnOff(socket_native_type /*fd*/, std::string_view args) { _sendDebugStrings = (args.compare("on") == 0); } -void Console::commandDirectorSubCommandPause(socket_native_type /*fd*/, const std::string& /*args*/) +void Console::commandDirectorSubCommandPause(socket_native_type /*fd*/, std::string_view /*args*/) { auto director = Director::getInstance(); Scheduler* sched = director->getScheduler(); sched->performFunctionInCocosThread([]() { Director::getInstance()->pause(); }); } -void Console::commandDirectorSubCommandResume(socket_native_type /*fd*/, const std::string& /*args*/) +void Console::commandDirectorSubCommandResume(socket_native_type /*fd*/, std::string_view /*args*/) { auto director = Director::getInstance(); director->resume(); } -void Console::commandDirectorSubCommandStop(socket_native_type /*fd*/, const std::string& /*args*/) +void Console::commandDirectorSubCommandStop(socket_native_type /*fd*/, std::string_view /*args*/) { auto director = Director::getInstance(); Scheduler* sched = director->getScheduler(); sched->performFunctionInCocosThread([]() { Director::getInstance()->stopAnimation(); }); } -void Console::commandDirectorSubCommandStart(socket_native_type /*fd*/, const std::string& /*args*/) +void Console::commandDirectorSubCommandStart(socket_native_type /*fd*/, std::string_view /*args*/) { auto director = Director::getInstance(); director->startAnimation(); } -void Console::commandDirectorSubCommandEnd(socket_native_type /*fd*/, const std::string& /*args*/) +void Console::commandDirectorSubCommandEnd(socket_native_type /*fd*/, std::string_view /*args*/) { auto director = Director::getInstance(); director->end(); } -void Console::commandExit(socket_native_type fd, const std::string& /*args*/) +void Console::commandExit(socket_native_type fd, std::string_view /*args*/) { FD_CLR(fd, &_read_set); _fds.erase(std::remove(_fds.begin(), _fds.end(), fd), _fds.end()); @@ -1235,23 +1237,23 @@ void Console::commandExit(socket_native_type fd, const std::string& /*args*/) #endif } -void Console::commandFileUtils(socket_native_type fd, const std::string& /*args*/) +void Console::commandFileUtils(socket_native_type fd, std::string_view /*args*/) { Scheduler* sched = Director::getInstance()->getScheduler(); sched->performFunctionInCocosThread(std::bind(&Console::printFileUtils, this, fd)); } -void Console::commandFileUtilsSubCommandFlush(socket_native_type /*fd*/, const std::string& /*args*/) +void Console::commandFileUtilsSubCommandFlush(socket_native_type /*fd*/, std::string_view /*args*/) { FileUtils::getInstance()->purgeCachedEntries(); } -void Console::commandFps(socket_native_type fd, const std::string& /*args*/) +void Console::commandFps(socket_native_type fd, std::string_view /*args*/) { Console::Utility::mydprintf(fd, "FPS is: %s\n", Director::getInstance()->isDisplayStats() ? "on" : "off"); } -void Console::commandFpsSubCommandOnOff(socket_native_type /*fd*/, const std::string& args) +void Console::commandFpsSubCommandOnOff(socket_native_type /*fd*/, std::string_view args) { bool state = (args.compare("on") == 0); Director* dir = Director::getInstance(); @@ -1259,12 +1261,12 @@ void Console::commandFpsSubCommandOnOff(socket_native_type /*fd*/, const std::st sched->performFunctionInCocosThread(std::bind(&Director::setDisplayStats, dir, state)); } -void Console::commandHelp(socket_native_type fd, const std::string& /*args*/) +void Console::commandHelp(socket_native_type fd, std::string_view /*args*/) { sendHelp(fd, _commands, "\nAvailable commands:\n"); } -void Console::commandProjection(socket_native_type fd, const std::string& /*args*/) +void Console::commandProjection(socket_native_type fd, std::string_view /*args*/) { auto director = Director::getInstance(); char buf[20]; @@ -1288,25 +1290,26 @@ void Console::commandProjection(socket_native_type fd, const std::string& /*args Console::Utility::mydprintf(fd, "Current projection: %s\n", buf); } -void Console::commandProjectionSubCommand2d(socket_native_type /*fd*/, const std::string& /*args*/) +void Console::commandProjectionSubCommand2d(socket_native_type /*fd*/, std::string_view /*args*/) { auto director = Director::getInstance(); Scheduler* sched = director->getScheduler(); sched->performFunctionInCocosThread([=]() { director->setProjection(Director::Projection::_2D); }); } -void Console::commandProjectionSubCommand3d(socket_native_type /*fd*/, const std::string& /*args*/) +void Console::commandProjectionSubCommand3d(socket_native_type /*fd*/, std::string_view /*args*/) { auto director = Director::getInstance(); Scheduler* sched = director->getScheduler(); sched->performFunctionInCocosThread([=]() { director->setProjection(Director::Projection::_3D); }); } -void Console::commandResolution(socket_native_type /*fd*/, const std::string& args) +void Console::commandResolution(socket_native_type /*fd*/, std::string_view args) { int policy; float width, height; - std::istringstream stream(args); + std::stringstream stream; + stream << args; stream >> width >> height >> policy; Scheduler* sched = Director::getInstance()->getScheduler(); @@ -1316,7 +1319,7 @@ void Console::commandResolution(socket_native_type /*fd*/, const std::string& ar }); } -void Console::commandResolutionSubCommandEmpty(socket_native_type fd, const std::string& /*args*/) +void Console::commandResolutionSubCommandEmpty(socket_native_type fd, std::string_view /*args*/) { auto director = Director::getInstance(); Vec2 points = director->getWinSize(); @@ -1340,13 +1343,13 @@ void Console::commandResolutionSubCommandEmpty(socket_native_type fd, const std: (int)visibleRect.origin.y, (int)visibleRect.size.width, (int)visibleRect.size.height); } -void Console::commandSceneGraph(socket_native_type fd, const std::string& /*args*/) +void Console::commandSceneGraph(socket_native_type fd, std::string_view /*args*/) { Scheduler* sched = Director::getInstance()->getScheduler(); sched->performFunctionInCocosThread(std::bind(&Console::printSceneGraphBoot, this, fd)); } -void Console::commandTextures(socket_native_type fd, const std::string& /*args*/) +void Console::commandTextures(socket_native_type fd, std::string_view /*args*/) { Scheduler* sched = Director::getInstance()->getScheduler(); sched->performFunctionInCocosThread([=]() { @@ -1356,13 +1359,13 @@ void Console::commandTextures(socket_native_type fd, const std::string& /*args*/ }); } -void Console::commandTexturesSubCommandFlush(socket_native_type /*fd*/, const std::string& /*args*/) +void Console::commandTexturesSubCommandFlush(socket_native_type /*fd*/, std::string_view /*args*/) { Scheduler* sched = Director::getInstance()->getScheduler(); sched->performFunctionInCocosThread([]() { Director::getInstance()->getTextureCache()->removeAllTextures(); }); } -void Console::commandTouchSubCommandTap(socket_native_type fd, const std::string& args) +void Console::commandTouchSubCommandTap(socket_native_type fd, std::string_view args) { auto argv = Console::Utility::split(args, ' '); @@ -1387,7 +1390,7 @@ void Console::commandTouchSubCommandTap(socket_native_type fd, const std::string } } -void Console::commandTouchSubCommandSwipe(socket_native_type fd, const std::string& args) +void Console::commandTouchSubCommandSwipe(socket_native_type fd, std::string_view args) { auto argv = Console::Utility::split(args, ' '); @@ -1558,7 +1561,7 @@ void Console::commandUpload(socket_native_type fd) } } -void Console::commandVersion(socket_native_type fd, const std::string& /*args*/) +void Console::commandVersion(socket_native_type fd, std::string_view /*args*/) { Console::Utility::mydprintf(fd, "%s\n", adxeVersion()); } @@ -1619,7 +1622,7 @@ void Console::printFileUtils(socket_native_type fd) } void Console::sendHelp(socket_native_type fd, - const std::unordered_map& commands, + const hlookup::string_map& commands, const char* msg) { Console::Utility::sendToConsole(fd, msg, strlen(msg)); @@ -1629,14 +1632,14 @@ void Console::sendHelp(socket_native_type fd, if (command->getHelp().empty()) continue; - Console::Utility::mydprintf(fd, "\t%s", command->getName().c_str()); - ssize_t tabs = strlen(command->getName().c_str()) / 8; + Console::Utility::mydprintf(fd, "\t%s", command->getName().data()); + ssize_t tabs = strlen(command->getName().data()) / 8; tabs = 3 - tabs; for (int j = 0; j < tabs; j++) { Console::Utility::mydprintf(fd, "\t"); } - Console::Utility::mydprintf(fd, "%s\n", command->getHelp().c_str()); + Console::Utility::mydprintf(fd, "%s\n", command->getHelp().data()); } } diff --git a/cocos/base/CCConsole.h b/cocos/base/CCConsole.h index 20f5aa54f4..cfe23de808 100644 --- a/cocos/base/CCConsole.h +++ b/cocos/base/CCConsole.h @@ -82,11 +82,11 @@ public: static std::string& trim(std::string& s); // split - static std::vector& split(const std::string& s, char delim, std::vector& elems); - static std::vector split(const std::string& s, char delim); + static std::vector& split(std::string_view s, char delim, std::vector& elems); + static std::vector split(std::string_view s, char delim); /** Checks myString is a floating-point type. */ - static bool isFloat(const std::string& myString); + static bool isFloat(std::string_view myString); /** send a message to console */ static ssize_t sendToConsole(int fd, const void* buffer, size_t length, int flags = 0); @@ -98,10 +98,10 @@ public: static void sendPrompt(int fd); /** set a new string for the prompt. */ - static void setPrompt(const std::string& prompt); + static void setPrompt(std::string_view prompt); /** get the prompt string. */ - static const std::string& getPrompt(); + static std::string_view getPrompt(); private: static std::string _prompt; /*!< prompt */ @@ -111,11 +111,11 @@ public: class CC_DLL Command { public: - using Callback = std::function; + using Callback = std::function; /** Constructor */ Command(); - Command(const std::string& name, const std::string& help); - Command(const std::string& name, const std::string& help, const Callback& callback); + Command(std::string_view name, std::string_view help); + Command(std::string_view name, std::string_view help, const Callback& callback); /** Copy constructor */ Command(const Command& o); @@ -139,29 +139,29 @@ public: void addSubCommand(const Command& subCmd); /** get sub command */ - const Command* getSubCommand(const std::string& subCmdName) const; + const Command* getSubCommand(std::string_view subCmdName) const; /** delete sub command */ - void delSubCommand(const std::string& subCmdName); + void delSubCommand(std::string_view subCmdName); /** help command handler */ - void commandHelp(int fd, const std::string& args); + void commandHelp(int fd, std::string_view args); /** generic command handler */ - void commandGeneric(int fd, const std::string& args); + void commandGeneric(int fd, std::string_view args); /** Gets the name of the current command */ - const std::string& getName() const { return _name; } + std::string_view getName() const { return _name; } /** Gets the help information of the current command */ - const std::string& getHelp() const { return _help; } + std::string_view getHelp() const { return _help; } private: std::string _name; std::string _help; Callback _callback; - std::unordered_map _subCommands; + hlookup::string_map _subCommands; }; /** Constructor */ @@ -181,18 +181,18 @@ public: /** add custom command */ void addCommand(const Command& cmd); - void addSubCommand(const std::string& cmdName, const Command& subCmd); + void addSubCommand(std::string_view cmdName, const Command& subCmd); void addSubCommand(Command& cmd, const Command& subCmd); /** get custom command */ - const Command* getCommand(const std::string& cmdName); - const Command* getSubCommand(const std::string& cmdName, const std::string& subCmdName); - const Command* getSubCommand(const Command& cmd, const std::string& subCmdName); + const Command* getCommand(std::string_view cmdName); + const Command* getSubCommand(std::string_view cmdName, std::string_view subCmdName); + const Command* getSubCommand(const Command& cmd, std::string_view subCmdName); /** delete custom command */ - void delCommand(const std::string& cmdName); - void delSubCommand(const std::string& cmdName, const std::string& subCmdName); - void delSubCommand(Command& cmd, const std::string& subCmdName); + void delCommand(std::string_view cmdName); + void delSubCommand(std::string_view cmdName, std::string_view subCmdName); + void delSubCommand(Command& cmd, std::string_view subCmdName); /** log something in the console */ void log(const char* buf); @@ -202,7 +202,7 @@ public: * * @address : 127.0.0.1 */ - void setBindAddress(const std::string& address); + void setBindAddress(std::string_view address); /** Checks whether the server for console is bound with ipv6 address */ bool isIpv6Server() const; @@ -218,7 +218,7 @@ protected: ssize_t readline(socket_native_type fd, char* buf, size_t maxlen); ssize_t readBytes(socket_native_type fd, char* buffer, size_t maxlen, bool* more); bool parseCommand(socket_native_type fd); - void performCommand(socket_native_type fd, const std::string& command); + void performCommand(socket_native_type fd, std::string_view command); void addClient(); @@ -240,33 +240,33 @@ protected: void createCommandVersion(); // Add commands here - void commandAllocator(socket_native_type fd, const std::string& args); - void commandConfig(socket_native_type fd, const std::string& args); - void commandDebugMsg(socket_native_type fd, const std::string& args); - void commandDebugMsgSubCommandOnOff(socket_native_type fd, const std::string& args); - void commandDirectorSubCommandPause(socket_native_type fd, const std::string& args); - void commandDirectorSubCommandResume(socket_native_type fd, const std::string& args); - void commandDirectorSubCommandStop(socket_native_type fd, const std::string& args); - void commandDirectorSubCommandStart(socket_native_type fd, const std::string& args); - void commandDirectorSubCommandEnd(socket_native_type fd, const std::string& args); - void commandExit(socket_native_type fd, const std::string& args); - void commandFileUtils(socket_native_type fd, const std::string& args); - void commandFileUtilsSubCommandFlush(socket_native_type fd, const std::string& args); - void commandFps(socket_native_type fd, const std::string& args); - void commandFpsSubCommandOnOff(socket_native_type fd, const std::string& args); - void commandHelp(socket_native_type fd, const std::string& args); - void commandProjection(socket_native_type fd, const std::string& args); - void commandProjectionSubCommand2d(socket_native_type fd, const std::string& args); - void commandProjectionSubCommand3d(socket_native_type fd, const std::string& args); - void commandResolution(socket_native_type fd, const std::string& args); - void commandResolutionSubCommandEmpty(socket_native_type fd, const std::string& args); - void commandSceneGraph(socket_native_type fd, const std::string& args); - void commandTextures(socket_native_type fd, const std::string& args); - void commandTexturesSubCommandFlush(socket_native_type fd, const std::string& args); - void commandTouchSubCommandTap(socket_native_type fd, const std::string& args); - void commandTouchSubCommandSwipe(socket_native_type fd, const std::string& args); + void commandAllocator(socket_native_type fd, std::string_view args); + void commandConfig(socket_native_type fd, std::string_view args); + void commandDebugMsg(socket_native_type fd, std::string_view args); + void commandDebugMsgSubCommandOnOff(socket_native_type fd, std::string_view args); + void commandDirectorSubCommandPause(socket_native_type fd, std::string_view args); + void commandDirectorSubCommandResume(socket_native_type fd, std::string_view args); + void commandDirectorSubCommandStop(socket_native_type fd, std::string_view args); + void commandDirectorSubCommandStart(socket_native_type fd, std::string_view args); + void commandDirectorSubCommandEnd(socket_native_type fd, std::string_view args); + void commandExit(socket_native_type fd, std::string_view args); + void commandFileUtils(socket_native_type fd, std::string_view args); + void commandFileUtilsSubCommandFlush(socket_native_type fd, std::string_view args); + void commandFps(socket_native_type fd, std::string_view args); + void commandFpsSubCommandOnOff(socket_native_type fd, std::string_view args); + void commandHelp(socket_native_type fd, std::string_view args); + void commandProjection(socket_native_type fd, std::string_view args); + void commandProjectionSubCommand2d(socket_native_type fd, std::string_view args); + void commandProjectionSubCommand3d(socket_native_type fd, std::string_view args); + void commandResolution(socket_native_type fd, std::string_view args); + void commandResolutionSubCommandEmpty(socket_native_type fd, std::string_view args); + void commandSceneGraph(socket_native_type fd, std::string_view args); + void commandTextures(socket_native_type fd, std::string_view args); + void commandTexturesSubCommandFlush(socket_native_type fd, std::string_view args); + void commandTouchSubCommandTap(socket_native_type fd, std::string_view args); + void commandTouchSubCommandSwipe(socket_native_type fd, std::string_view args); void commandUpload(socket_native_type fd); - void commandVersion(socket_native_type fd, const std::string& args); + void commandVersion(socket_native_type fd, std::string_view args); // file descriptor: socket, console, etc. socket_native_type _listenfd; socket_native_type _maxfd; @@ -279,7 +279,7 @@ protected: bool _endThread; bool _isIpv6Server; - std::unordered_map _commands; + hlookup::string_map _commands; // strings generated by cocos2d sent to the remote console bool _sendDebugStrings; @@ -300,7 +300,7 @@ private: /** send help message to console */ static void sendHelp(socket_native_type fd, - const std::unordered_map& commands, + const hlookup::string_map& commands, const char* msg); }; diff --git a/cocos/base/CCController-android.cpp b/cocos/base/CCController-android.cpp index 564735b5c9..ba8da87ab5 100644 --- a/cocos/base/CCController-android.cpp +++ b/cocos/base/CCController-android.cpp @@ -40,7 +40,7 @@ class ControllerImpl public: ControllerImpl(Controller* controller) : _controller(controller) {} - static std::vector::iterator findController(const std::string& deviceName, int deviceId) + static std::vector::iterator findController(std::string_view deviceName, int deviceId) { auto iter = std::find_if( Controller::s_allController.begin(), Controller::s_allController.end(), [&](Controller* controller) { @@ -50,7 +50,7 @@ public: return iter; } - static void onConnected(const std::string& deviceName, int deviceId) + static void onConnected(std::string_view deviceName, int deviceId) { // Check whether the controller is already connected. CCLOG("onConnected %s,%d", deviceName.c_str(), deviceId); @@ -68,7 +68,7 @@ public: controller->onConnected(); } - static void onDisconnected(const std::string& deviceName, int deviceId) + static void onDisconnected(std::string_view deviceName, int deviceId) { CCLOG("onDisconnected %s,%d", deviceName.c_str(), deviceId); @@ -83,7 +83,7 @@ public: Controller::s_allController.erase(iter); } - static void onButtonEvent(const std::string& deviceName, + static void onButtonEvent(std::string_view deviceName, int deviceId, int keyCode, bool isPressed, @@ -101,7 +101,7 @@ public: (*iter)->onButtonEvent(keyCode, isPressed, value, isAnalog); } - static void onAxisEvent(const std::string& deviceName, int deviceId, int axisCode, float value, bool isAnalog) + static void onAxisEvent(std::string_view deviceName, int deviceId, int axisCode, float value, bool isAnalog) { auto iter = findController(deviceName, deviceId); if (iter == Controller::s_allController.end()) diff --git a/cocos/base/CCController-linux-win32.cpp b/cocos/base/CCController-linux-win32.cpp index cca3d2ee2c..f99e23b641 100644 --- a/cocos/base/CCController-linux-win32.cpp +++ b/cocos/base/CCController-linux-win32.cpp @@ -4203,7 +4203,7 @@ public: return iter; } - static void onConnected(const std::string& deviceName, int deviceId) + static void onConnected(std::string_view deviceName, int deviceId) { // Check whether the controller is already registered auto iter = findController(deviceId); @@ -4222,7 +4222,7 @@ public: if (deviceName.compare(it.first) == 0) { // Found controller profile. Attach it to the controller: - CCLOG("ControllerImpl: Found input profile for controller: %s", deviceName.c_str()); + CCLOG("ControllerImpl: Found input profile for controller: %s", deviceName.data()); controller->_buttonInputMap = it.second.first; controller->_axisInputMap = it.second.second; @@ -4241,7 +4241,7 @@ public: CCLOG( "ControllerImpl: Could not find a button input mapping for controller \"%s\", and keyCode " "\"%d\". This keyCode will not match any from Controller::Key", - controller->getDeviceName().c_str(), i); + controller->getDeviceName().data(), i); } } @@ -4255,7 +4255,7 @@ public: CCLOG( "ControllerImpl: Could not find an axis input mapping for controller \"%s\", and keyCode " "\"%d\". This keyCode will not match any from Controller::Key", - controller->getDeviceName().c_str(), i); + controller->getDeviceName().data(), i); } } # endif @@ -4268,12 +4268,12 @@ public: # ifdef COCOS2D_DEBUG if (controller->_buttonInputMap.empty()) { - CCLOG("ControllerImpl: Could not find a button input map for controller: %s", deviceName.c_str()); + CCLOG("ControllerImpl: Could not find a button input map for controller: %s", deviceName.data()); } if (controller->_axisInputMap.empty()) { - CCLOG("ControllerImpl: Could not find an axis input map for controller: %s", deviceName.c_str()); + CCLOG("ControllerImpl: Could not find an axis input map for controller: %s", deviceName.data()); } # endif diff --git a/cocos/base/CCController.h b/cocos/base/CCController.h index 646195def4..f6c3bc70f4 100644 --- a/cocos/base/CCController.h +++ b/cocos/base/CCController.h @@ -153,7 +153,7 @@ public: /** * Gets the name of this Controller object. */ - const std::string& getDeviceName() const { return _deviceName; } + std::string_view getDeviceName() const { return _deviceName; } /** * Gets the Controller id. diff --git a/cocos/base/CCEventCustom.cpp b/cocos/base/CCEventCustom.cpp index 025252f7a7..e0d2671854 100644 --- a/cocos/base/CCEventCustom.cpp +++ b/cocos/base/CCEventCustom.cpp @@ -28,7 +28,7 @@ NS_CC_BEGIN -EventCustom::EventCustom(const std::string& eventName) : Event(Type::CUSTOM), _userData(nullptr), _eventName(eventName) +EventCustom::EventCustom(std::string_view eventName) : Event(Type::CUSTOM), _userData(nullptr), _eventName(eventName) {} NS_CC_END diff --git a/cocos/base/CCEventCustom.h b/cocos/base/CCEventCustom.h index ae14031001..e7a03091c7 100644 --- a/cocos/base/CCEventCustom.h +++ b/cocos/base/CCEventCustom.h @@ -47,7 +47,7 @@ public: * @param eventName A given name of the custom event. * @js ctor */ - EventCustom(const std::string& eventName); + EventCustom(std::string_view eventName); /** Sets user data. * @@ -65,7 +65,7 @@ public: * * @return The name of the event. */ - const std::string& getEventName() const { return _eventName; } + std::string_view getEventName() const { return _eventName; } protected: void* _userData; ///< User data diff --git a/cocos/base/CCEventDispatcher.cpp b/cocos/base/CCEventDispatcher.cpp index 7a18512e66..1c251a4f96 100644 --- a/cocos/base/CCEventDispatcher.cpp +++ b/cocos/base/CCEventDispatcher.cpp @@ -452,7 +452,7 @@ void EventDispatcher::addEventListener(EventListener* listener) void EventDispatcher::forceAddEventListener(EventListener* listener) { EventListenerVector* listeners = nullptr; - EventListener::ListenerID listenerID = listener->getListenerID(); + auto listenerID = listener->getListenerID(); auto itr = _listenerMap.find(listenerID); if (itr == _listenerMap.end()) { @@ -579,7 +579,7 @@ void EventDispatcher::addEventListenerWithFixedPriority(EventListener* listener, addEventListener(listener); } -EventListenerCustom* EventDispatcher::addCustomEventListener(const std::string& eventName, +EventListenerCustom* EventDispatcher::addCustomEventListener(std::string_view eventName, const std::function& callback) { EventListenerCustom* listener = EventListenerCustom::create(eventName, callback); @@ -931,14 +931,14 @@ void EventDispatcher::dispatchEvent(Event* event) updateListeners(event); } -void EventDispatcher::dispatchCustomEvent(const std::string& eventName, void* optionalUserData) +void EventDispatcher::dispatchCustomEvent(std::string_view eventName, void* optionalUserData) { EventCustom ev(eventName); ev.setUserData(optionalUserData); dispatchEvent(&ev); } -bool EventDispatcher::hasEventListener(const EventListener::ListenerID& listenerID) const +bool EventDispatcher::hasEventListener(std::string_view listenerID) const { return getListeners(listenerID) != nullptr; } @@ -1268,7 +1268,7 @@ void EventDispatcher::updateDirtyFlagForSceneGraph() } } -void EventDispatcher::sortEventListeners(const EventListener::ListenerID& listenerID) +void EventDispatcher::sortEventListeners(std::string_view listenerID) { DirtyFlag dirtyFlag = DirtyFlag::NONE; @@ -1303,7 +1303,7 @@ void EventDispatcher::sortEventListeners(const EventListener::ListenerID& listen } } -void EventDispatcher::sortEventListenersOfSceneGraphPriority(const EventListener::ListenerID& listenerID, +void EventDispatcher::sortEventListenersOfSceneGraphPriority(std::string_view listenerID, Node* rootNode) { auto listeners = getListeners(listenerID); @@ -1337,7 +1337,7 @@ void EventDispatcher::sortEventListenersOfSceneGraphPriority(const EventListener #endif } -void EventDispatcher::sortEventListenersOfFixedPriority(const EventListener::ListenerID& listenerID) +void EventDispatcher::sortEventListenersOfFixedPriority(std::string_view listenerID) { auto listeners = getListeners(listenerID); @@ -1374,7 +1374,7 @@ void EventDispatcher::sortEventListenersOfFixedPriority(const EventListener::Lis #endif } -EventDispatcher::EventListenerVector* EventDispatcher::getListeners(const EventListener::ListenerID& listenerID) const +EventDispatcher::EventListenerVector* EventDispatcher::getListeners(std::string_view listenerID) const { auto iter = _listenerMap.find(listenerID); if (iter != _listenerMap.end()) @@ -1385,7 +1385,7 @@ EventDispatcher::EventListenerVector* EventDispatcher::getListeners(const EventL return nullptr; } -void EventDispatcher::removeEventListenersForListenerID(const EventListener::ListenerID& listenerID) +void EventDispatcher::removeEventListenersForListenerID(std::string_view listenerID) { auto listenerItemIter = _listenerMap.find(listenerID); if (listenerItemIter != _listenerMap.end()) @@ -1479,7 +1479,7 @@ void EventDispatcher::removeEventListenersForType(EventListener::Type listenerTy } } -void EventDispatcher::removeCustomEventListeners(const std::string& customEventName) +void EventDispatcher::removeCustomEventListeners(std::string_view customEventName) { removeEventListenersForListenerID(customEventName); } @@ -1539,7 +1539,7 @@ void EventDispatcher::setDirtyForNode(Node* node) } } -void EventDispatcher::setDirty(const EventListener::ListenerID& listenerID, DirtyFlag flag) +void EventDispatcher::setDirty(std::string_view listenerID, DirtyFlag flag) { auto iter = _priorityDirtyFlagMap.find(listenerID); if (iter == _priorityDirtyFlagMap.end()) diff --git a/cocos/base/CCEventDispatcher.h b/cocos/base/CCEventDispatcher.h index 2523f7ff2b..9c01a79663 100644 --- a/cocos/base/CCEventDispatcher.h +++ b/cocos/base/CCEventDispatcher.h @@ -87,7 +87,7 @@ public: * @param callback A given callback method that associated the event name. * @return the generated event. Needed in order to remove the event from the dispatcher */ - EventListenerCustom* addCustomEventListener(const std::string& eventName, + EventListenerCustom* addCustomEventListener(std::string_view eventName, const std::function& callback); ///////////////////////////////////////////// @@ -117,7 +117,7 @@ public: * * @param customEventName A given event listener name which needs to be removed. */ - void removeCustomEventListeners(const std::string& customEventName); + void removeCustomEventListeners(std::string_view customEventName); /** Removes all listeners. */ @@ -177,7 +177,7 @@ public: * @param eventName The name of the event which needs to be dispatched. * @param optionalUserData The optional user data, it's a void*, the default value is nullptr. */ - void dispatchCustomEvent(const std::string& eventName, void* optionalUserData = nullptr); + void dispatchCustomEvent(std::string_view eventName, void* optionalUserData = nullptr); /** Query whether the specified event listener id has been added. * @@ -185,7 +185,7 @@ public: * * @return True if dispatching events is exist */ - bool hasEventListener(const EventListener::ListenerID& listenerID) const; + bool hasEventListener(std::string_view listenerID) const; ///////////////////////////////////////////// @@ -252,22 +252,22 @@ protected: void forceAddEventListener(EventListener* listener); /** Gets event the listener list for the event listener type. */ - EventListenerVector* getListeners(const EventListener::ListenerID& listenerID) const; + EventListenerVector* getListeners(std::string_view listenerID) const; /** Update dirty flag */ void updateDirtyFlagForSceneGraph(); /** Removes all listeners with the same event listener ID */ - void removeEventListenersForListenerID(const EventListener::ListenerID& listenerID); + void removeEventListenersForListenerID(std::string_view listenerID); /** Sort event listener */ - void sortEventListeners(const EventListener::ListenerID& listenerID); + void sortEventListeners(std::string_view listenerID); /** Sorts the listeners of specified type by scene graph priority */ - void sortEventListenersOfSceneGraphPriority(const EventListener::ListenerID& listenerID, Node* rootNode); + void sortEventListenersOfSceneGraphPriority(std::string_view listenerID, Node* rootNode); /** Sorts the listeners of specified type by fixed priority */ - void sortEventListenersOfFixedPriority(const EventListener::ListenerID& listenerID); + void sortEventListenersOfFixedPriority(std::string_view listenerID); /** Updates all listeners * 1) Removes all listener items that have been marked as 'removed' when dispatching event. @@ -311,7 +311,7 @@ protected: }; /** Sets the dirty flag for a specified listener ID */ - void setDirty(const EventListener::ListenerID& listenerID, DirtyFlag flag); + void setDirty(std::string_view listenerID, DirtyFlag flag); /** Walks though scene graph to get the draw order for each node, it's called before sorting event listener with * scene graph priority */ @@ -321,10 +321,10 @@ protected: void cleanToRemovedListeners(); /** Listeners map */ - std::unordered_map _listenerMap; + hlookup::string_map _listenerMap; /** The map of dirty flag */ - std::unordered_map _priorityDirtyFlagMap; + hlookup::string_map _priorityDirtyFlagMap; /** The map of node and event listeners */ std::unordered_map*> _nodeListenersMap; diff --git a/cocos/base/CCEventListener.cpp b/cocos/base/CCEventListener.cpp index 5da92081a7..d2e9e29c88 100644 --- a/cocos/base/CCEventListener.cpp +++ b/cocos/base/CCEventListener.cpp @@ -35,7 +35,7 @@ EventListener::~EventListener() CCLOGINFO("In the destructor of EventListener. %p", this); } -bool EventListener::init(Type t, const ListenerID& listenerID, const std::function& callback) +bool EventListener::init(Type t, std::string_view listenerID, const std::function& callback) { _onEvent = callback; _type = t; diff --git a/cocos/base/CCEventListener.h b/cocos/base/CCEventListener.h index 3f8a64631d..6eb1f728ed 100644 --- a/cocos/base/CCEventListener.h +++ b/cocos/base/CCEventListener.h @@ -79,7 +79,7 @@ public: * Initializes event with type and callback function * @js NA */ - bool init(Type t, const ListenerID& listenerID, const std::function& callback); + bool init(Type t, std::string_view listenerID, const std::function& callback); public: /** Destructor. @@ -143,7 +143,7 @@ protected: /** Gets the listener ID of this listener * When event is being dispatched, listener ID is used as key for searching listeners according to event type. */ - const ListenerID& getListenerID() const { return _listenerID; } + std::string_view getListenerID() const { return _listenerID; } /** Sets the fixed priority for this listener * @note This method is only used for `fixed priority listeners`, it needs to access a non-zero value. diff --git a/cocos/base/CCEventListenerCustom.cpp b/cocos/base/CCEventListenerCustom.cpp index 6ccfe80712..299d6724fc 100644 --- a/cocos/base/CCEventListenerCustom.cpp +++ b/cocos/base/CCEventListenerCustom.cpp @@ -30,7 +30,7 @@ NS_CC_BEGIN EventListenerCustom::EventListenerCustom() : _onCustomEvent(nullptr) {} -EventListenerCustom* EventListenerCustom::create(const std::string& eventName, +EventListenerCustom* EventListenerCustom::create(std::string_view eventName, const std::function& callback) { EventListenerCustom* ret = new EventListenerCustom(); @@ -45,7 +45,7 @@ EventListenerCustom* EventListenerCustom::create(const std::string& eventName, return ret; } -bool EventListenerCustom::init(const ListenerID& listenerId, const std::function& callback) +bool EventListenerCustom::init(std::string_view listenerId, const std::function& callback) { bool ret = false; diff --git a/cocos/base/CCEventListenerCustom.h b/cocos/base/CCEventListenerCustom.h index b982162491..ea68f2302e 100644 --- a/cocos/base/CCEventListenerCustom.h +++ b/cocos/base/CCEventListenerCustom.h @@ -66,7 +66,7 @@ public: * @param callback The callback function when the specified event was emitted. * @return An autoreleased EventListenerCustom object. */ - static EventListenerCustom* create(const std::string& eventName, const std::function& callback); + static EventListenerCustom* create(std::string_view eventName, const std::function& callback); /// Overrides virtual bool checkAvailable() override; @@ -77,7 +77,7 @@ public: EventListenerCustom(); /** Initializes event with type and callback function */ - bool init(const ListenerID& listenerId, const std::function& callback); + bool init(std::string_view listenerId, const std::function& callback); protected: std::function _onCustomEvent; diff --git a/cocos/base/CCIMEDelegate.h b/cocos/base/CCIMEDelegate.h index 9c9c63574c..276c0d5d24 100644 --- a/cocos/base/CCIMEDelegate.h +++ b/cocos/base/CCIMEDelegate.h @@ -137,7 +137,7 @@ protected: * @js NA * @lua NA */ - virtual const std::string& getContentText() { return STD_STRING_EMPTY; } + virtual std::string_view getContentText() { return STD_STRING_EMPTY; } ////////////////////////////////////////////////////////////////////////// // keyboard show/hide notification diff --git a/cocos/base/CCIMEDispatcher.cpp b/cocos/base/CCIMEDispatcher.cpp index ccd59f96dc..7444466678 100644 --- a/cocos/base/CCIMEDispatcher.cpp +++ b/cocos/base/CCIMEDispatcher.cpp @@ -247,7 +247,7 @@ void IMEDispatcher::dispatchControlKey(EventKeyboard::KeyCode keyCode) } while (0); } -const std::string& IMEDispatcher::getContentText() +std::string_view IMEDispatcher::getContentText() { if (_impl && _impl->_delegateWithIme) { diff --git a/cocos/base/CCIMEDispatcher.h b/cocos/base/CCIMEDispatcher.h index 5040b9d324..4ab9b6f5b4 100644 --- a/cocos/base/CCIMEDispatcher.h +++ b/cocos/base/CCIMEDispatcher.h @@ -76,7 +76,7 @@ public: * @brief Get the content text from IMEDelegate, retrieved previously from IME. * @lua NA */ - const std::string& getContentText(); + std::string_view getContentText(); ////////////////////////////////////////////////////////////////////////// // dispatch keyboard notification diff --git a/cocos/base/CCMap.h b/cocos/base/CCMap.h index 8bfd817dfa..0fd8b66f9f 100644 --- a/cocos/base/CCMap.h +++ b/cocos/base/CCMap.h @@ -51,12 +51,12 @@ NS_CC_BEGIN * @js NA * @lua NA */ -template +template , typename E = std::equal_to> class Map { public: #if USE_STD_UNORDERED_MAP - typedef std::unordered_map RefMap; + typedef tsl::robin_map RefMap; #else typedef std::map RefMap; #endif @@ -86,14 +86,14 @@ public: const_iterator cend() const { return _data.cend(); } /** Default constructor */ - Map() : _data() + Map() : _data() { static_assert(std::is_convertible::value, "Invalid Type for cocos2d::Map!"); CCLOGINFO("In the default constructor of Map!"); } /** Constructor with capacity. */ - explicit Map(ssize_t capacity) : _data() + explicit Map(ssize_t capacity) : _data() { static_assert(std::is_convertible::value, "Invalid Type for cocos2d::Map!"); CCLOGINFO("In the constructor with capacity of Map!"); @@ -101,7 +101,7 @@ public: } /** Copy constructor. */ - Map(const Map& other) + Map(const Map& other) { static_assert(std::is_convertible::value, "Invalid Type for cocos2d::Map!"); CCLOGINFO("In the copy constructor of Map!"); @@ -110,7 +110,7 @@ public: } /** Move constructor. */ - Map(Map&& other) + Map(Map&& other) { static_assert(std::is_convertible::value, "Invalid Type for cocos2d::Map!"); CCLOGINFO("In the move constructor of Map!"); @@ -121,7 +121,7 @@ public: * Destructor. * It will release all objects in map. */ - ~Map() + ~Map() { CCLOGINFO("In the destructor of Map!"); clear(); @@ -223,7 +223,8 @@ public: * Member type K is the keys for the elements in the container. defined in Map as an alias of its first * template parameter (Key). */ - const V at(const K& key) const + template + const V at(const K2& key) const { auto iter = _data.find(key); if (iter != _data.end()) @@ -231,7 +232,8 @@ public: return nullptr; } - V at(const K& key) + template + V at(const K2& key) { auto iter = _data.find(key); if (iter != _data.end()) @@ -247,9 +249,17 @@ public: * Member type 'K' is the type of the keys for the elements in the container, * defined in Map as an alias of its first template parameter (Key). */ - const_iterator find(const K& key) const { return _data.find(key); } + template + const_iterator find(const K2& key) const + { + return _data.find(key); + } - iterator find(const K& key) { return _data.find(key); } + template + iterator find(const K2& key) + { + return _data.find(key); + } /** * Inserts new elements in the map. @@ -259,7 +269,8 @@ public: * @param key The key to be inserted. * @param object The object to be inserted. */ - void insert(const K& key, V object) + template + void insert(const K2& key, V object) { CCASSERT(object != nullptr, "Object is nullptr!"); object->retain(); @@ -287,7 +298,20 @@ public: * Member type 'K' is the type of the keys for the elements in the container, * defined in Map as an alias of its first template parameter (Key). */ - size_t erase(const K& k) + //size_t erase(const K& k) + //{ + // auto iter = _data.find(k); + // if (iter != _data.end()) + // { + // iter->second->release(); + // _data.erase(iter); + // return 1; + // } + // return 0; + //} + + template + size_t erase(const _K2& k) { auto iter = _data.find(k); if (iter != _data.end()) @@ -304,7 +328,8 @@ public: * * @param keys Keys of elements to be erased. */ - void erase(const std::vector& keys) + template + void erase(const std::vector<_K2>& keys) { for (const auto& key : keys) { @@ -369,7 +394,7 @@ public: // } /** Copy assignment operator. */ - Map& operator=(const Map& other) + Map& operator=(const Map& other) { if (this != &other) { @@ -382,7 +407,7 @@ public: } /** Move assignment operator. */ - Map& operator=(Map&& other) + Map& operator=(Map&& other) { if (this != &other) { @@ -406,6 +431,9 @@ protected: RefMap _data; }; +template +using StringMap = Map; + NS_CC_END // end group /// @} diff --git a/cocos/base/CCNS.cpp b/cocos/base/CCNS.cpp index 2ebd2ff5a6..17d4165860 100644 --- a/cocos/base/CCNS.cpp +++ b/cocos/base/CCNS.cpp @@ -38,7 +38,7 @@ NS_CC_BEGIN typedef std::vector strArray; // string toolkit -static inline void split(const std::string& src, const std::string& token, strArray& vect) +static inline void split(std::string_view src, std::string_view token, strArray& vect) { size_t nend = 0; size_t nbegin = 0; @@ -47,9 +47,9 @@ static inline void split(const std::string& src, const std::string& token, strAr { nend = src.find(token, nbegin); if (nend == std::string::npos) - vect.push_back(src.substr(nbegin, src.length() - nbegin)); + vect.push_back(std::string{src.substr(nbegin, src.length() - nbegin)}); else - vect.push_back(src.substr(nbegin, nend - nbegin)); + vect.push_back(std::string{src.substr(nbegin, nend - nbegin)}); nbegin = nend + tokenSize; } } @@ -58,7 +58,7 @@ static inline void split(const std::string& src, const std::string& token, strAr // if the form is right,the string will be split into the parameter strs; // or the parameter strs will be empty. // if the form is right return true,else return false. -static bool splitWithForm(const std::string& content, strArray& strs) +static bool splitWithForm(std::string_view content, strArray& strs) { bool bRet = false; @@ -74,7 +74,7 @@ static bool splitWithForm(const std::string& content, strArray& strs) // '}' is before '{' CC_BREAK_IF(nPosLeft > nPosRight); - const std::string pointStr = content.substr(nPosLeft + 1, nPosRight - nPosLeft - 1); + auto pointStr = content.substr(nPosLeft + 1, nPosRight - nPosLeft - 1); // nothing between '{' and '}' CC_BREAK_IF(pointStr.empty()); @@ -98,14 +98,14 @@ static bool splitWithForm(const std::string& content, strArray& strs) // implement the functions -Rect RectFromString(const std::string& str) +Rect RectFromString(std::string_view str) { Rect result = Rect::ZERO; do { CC_BREAK_IF(str.empty()); - std::string content = str; + auto content = str; // find the first '{' and the third '}' size_t nPosLeft = content.find('{'); @@ -127,8 +127,8 @@ Rect RectFromString(const std::string& str) CC_BREAK_IF(nPointEnd == std::string::npos); // get the point string and size string - const std::string pointStr = content.substr(0, nPointEnd); - const std::string sizeStr = content.substr(nPointEnd + 1, content.length() - nPointEnd); + auto pointStr = content.substr(0, nPointEnd); + auto sizeStr = content.substr(nPointEnd + 1, content.length() - nPointEnd); // split the string with ',' strArray pointInfo; @@ -147,7 +147,7 @@ Rect RectFromString(const std::string& str) return result; } -Vec2 PointFromString(const std::string& str) +Vec2 PointFromString(std::string_view str) { Vec2 ret; @@ -165,7 +165,7 @@ Vec2 PointFromString(const std::string& str) return ret; } -Vec2 SizeFromString(const std::string& pszContent) +Vec2 SizeFromString(std::string_view pszContent) { Vec2 ret = Vec2::ZERO; diff --git a/cocos/base/CCNS.h b/cocos/base/CCNS.h index 730fd94faa..c08b799992 100644 --- a/cocos/base/CCNS.h +++ b/cocos/base/CCNS.h @@ -46,7 +46,7 @@ NS_CC_BEGIN * @return A Core Graphics structure that represents a rectangle. * If the string is not well-formed, the function returns Rect::ZERO. */ -Rect CC_DLL RectFromString(const std::string& str); +Rect CC_DLL RectFromString(std::string_view str); /** * @brief Returns a Core Graphics point structure corresponding to the data in a given string. @@ -58,7 +58,7 @@ Rect CC_DLL RectFromString(const std::string& str); * @return A Core Graphics structure that represents a point. * If the string is not well-formed, the function returns Vec2::ZERO. */ -Vec2 CC_DLL PointFromString(const std::string& str); +Vec2 CC_DLL PointFromString(std::string_view str); /** * @brief Returns a Core Graphics size structure corresponding to the data in a given string. @@ -70,7 +70,7 @@ Vec2 CC_DLL PointFromString(const std::string& str); * @return A Core Graphics structure that represents a size. * If the string is not well-formed, the function returns Vec2::ZERO. */ -Vec2 CC_DLL SizeFromString(const std::string& str); +Vec2 CC_DLL SizeFromString(std::string_view str); // end of data_structure group /** @} */ diff --git a/cocos/base/CCNinePatchImageParser.cpp b/cocos/base/CCNinePatchImageParser.cpp index ab71f14fdd..5d23b2041f 100644 --- a/cocos/base/CCNinePatchImageParser.cpp +++ b/cocos/base/CCNinePatchImageParser.cpp @@ -179,7 +179,7 @@ void NinePatchImageParser::setSpriteFrameInfo(Image* image, const cocos2d::Rect& this->_isRotated = rotated; } -bool NinePatchImageParser::isNinePatchImage(const std::string& filepath) +bool NinePatchImageParser::isNinePatchImage(std::string_view filepath) { size_t length = filepath.length(); if (length < 7) diff --git a/cocos/base/CCNinePatchImageParser.h b/cocos/base/CCNinePatchImageParser.h index c695e10b85..b16c6be593 100644 --- a/cocos/base/CCNinePatchImageParser.h +++ b/cocos/base/CCNinePatchImageParser.h @@ -51,7 +51,7 @@ public: * * @return If the filename contains ".9.png", then return true, otherwise false. */ - static bool isNinePatchImage(const std::string& filename); + static bool isNinePatchImage(std::string_view filename); /** * Default constructor. diff --git a/cocos/base/CCProperties.cpp b/cocos/base/CCProperties.cpp index a518a91d7f..1d8b96fed5 100644 --- a/cocos/base/CCProperties.cpp +++ b/cocos/base/CCProperties.cpp @@ -38,7 +38,7 @@ USING_NS_CC; // Utility functions (shared with SceneLoader). /** @script{ignore} */ -void calculateNamespacePath(const std::string& urlString, +void calculateNamespacePath(std::string_view urlString, std::string& fileString, std::vector& namespacePath); /** @script{ignore} */ @@ -79,7 +79,7 @@ Properties::Properties(Data* data, ssize_t* dataIdx) Properties::Properties(Data* data, ssize_t* dataIdx, - const std::string& name, + std::string_view name, const char* id, const char* parentID, Properties* parent) @@ -97,7 +97,7 @@ Properties::Properties(Data* data, rewind(); } -Properties* Properties::createNonRefCounted(const std::string& url) +Properties* Properties::createNonRefCounted(std::string_view url) { if (url.empty()) { @@ -106,7 +106,7 @@ Properties* Properties::createNonRefCounted(const std::string& url) } // Calculate the file and full namespace path from the specified url. - std::string urlString = url; + auto& urlString = url; std::string fileString; std::vector namespacePath; calculateNamespacePath(urlString, fileString, namespacePath); @@ -122,7 +122,7 @@ Properties* Properties::createNonRefCounted(const std::string& url) Properties* p = getPropertiesFromNamespacePath(properties, namespacePath); if (!p) { - CCLOGWARN("Failed to load properties from url '%s'.", url.c_str()); + CCLOGWARN("Failed to load properties from url '%s'.", url.data()); CC_SAFE_DELETE(properties); return nullptr; } @@ -1093,7 +1093,7 @@ void Properties::setDirectoryPath(const std::string* path) } } -void Properties::setDirectoryPath(const std::string& path) +void Properties::setDirectoryPath(std::string_view path) { if (_dirPath == NULL) { @@ -1105,7 +1105,7 @@ void Properties::setDirectoryPath(const std::string& path) } } -void calculateNamespacePath(const std::string& urlString, +void calculateNamespacePath(std::string_view urlString, std::string& fileString, std::vector& namespacePath) { @@ -1115,13 +1115,13 @@ void calculateNamespacePath(const std::string& urlString, if (loc != std::string::npos) { fileString = urlString.substr(0, loc); - std::string namespacePathString = urlString.substr(loc + 1); + auto namespacePathString = urlString.substr(loc + 1); while ((loc = namespacePathString.find('/')) != std::string::npos) { - namespacePath.push_back(namespacePathString.substr(0, loc)); + namespacePath.push_back(std::string{namespacePathString.substr(0, loc)}); namespacePathString = namespacePathString.substr(loc + 1); } - namespacePath.push_back(namespacePathString); + namespacePath.push_back(std::string{namespacePathString}); } else { diff --git a/cocos/base/CCProperties.h b/cocos/base/CCProperties.h index 97c123802c..14ddc7eeb3 100644 --- a/cocos/base/CCProperties.h +++ b/cocos/base/CCProperties.h @@ -183,7 +183,7 @@ public: * @return The created Properties or NULL if there was an error. * @script{create} */ - static Properties* createNonRefCounted(const std::string& url); + static Properties* createNonRefCounted(std::string_view url); /** * Destructor. @@ -533,7 +533,7 @@ private: { std::string name; std::string value; - Property(const std::string& aname, const std::string& avalue) : name(aname), value(avalue) {} + Property(std::string_view aname, std::string_view avalue) : name(aname), value(avalue) {} }; /** @@ -554,7 +554,7 @@ private: */ Properties(Data* data, ssize_t* dataIdx, - const std::string& name, + std::string_view name, const char* id, const char* parentID, Properties* parent); @@ -578,7 +578,7 @@ private: Properties* clone(); void setDirectoryPath(const std::string* path); - void setDirectoryPath(const std::string& path); + void setDirectoryPath(std::string_view path); /** * Reads the next character from the Data. Returns EOF if the end of the Data is reached. diff --git a/cocos/base/CCProtocols.h b/cocos/base/CCProtocols.h index 99708d8fc1..a5e3a138ef 100644 --- a/cocos/base/CCProtocols.h +++ b/cocos/base/CCProtocols.h @@ -250,7 +250,7 @@ public: * @js NA * @lua NA */ - virtual const std::string& getString() const = 0; + virtual std::string_view getString() const = 0; }; /** diff --git a/cocos/base/CCScheduler.cpp b/cocos/base/CCScheduler.cpp index 029a12f1b6..7709d94687 100644 --- a/cocos/base/CCScheduler.cpp +++ b/cocos/base/CCScheduler.cpp @@ -188,7 +188,7 @@ TimerTargetCallback::TimerTargetCallback() : _target(nullptr), _callback(nullptr bool TimerTargetCallback::initWithCallback(Scheduler* scheduler, const ccSchedulerFunc& callback, void* target, - const std::string& key, + std::string_view key, float seconds, unsigned int repeat, float delay) @@ -283,7 +283,7 @@ void Scheduler::schedule(const ccSchedulerFunc& callback, void* target, float interval, bool paused, - const std::string& key) + std::string_view key) { this->schedule(callback, target, interval, CC_REPEAT_FOREVER, 0.0f, paused, key); } @@ -294,7 +294,7 @@ void Scheduler::schedule(const ccSchedulerFunc& callback, unsigned int repeat, float delay, bool paused, - const std::string& key) + std::string_view key) { CCASSERT(target, "Argument target must be non-nullptr"); CCASSERT(!key.empty(), "key should not be empty!"); @@ -344,7 +344,7 @@ void Scheduler::schedule(const ccSchedulerFunc& callback, timer->release(); } -void Scheduler::unschedule(const std::string& key, void* target) +void Scheduler::unschedule(std::string_view key, void* target) { // explicit handle nil arguments when removing an object if (target == nullptr || key.empty()) @@ -513,7 +513,7 @@ void Scheduler::schedulePerFrame(const ccSchedulerFunc& callback, void* target, } } -bool Scheduler::isScheduled(const std::string& key, const void* target) const +bool Scheduler::isScheduled(std::string_view key, const void* target) const { CCASSERT(!key.empty(), "Argument key must not be empty"); CCASSERT(target, "Argument target must be non-nullptr"); diff --git a/cocos/base/CCScheduler.h b/cocos/base/CCScheduler.h index 5cf609f375..2dfe4283c4 100644 --- a/cocos/base/CCScheduler.h +++ b/cocos/base/CCScheduler.h @@ -109,13 +109,13 @@ public: bool initWithCallback(Scheduler* scheduler, const ccSchedulerFunc& callback, void* target, - const std::string& key, + std::string_view key, float seconds, unsigned int repeat, float delay); const ccSchedulerFunc& getCallback() const { return _callback; } - const std::string& getKey() const { return _key; } + std::string_view getKey() const { return _key; } virtual void trigger(float dt) override; virtual void cancel() override; @@ -252,7 +252,7 @@ public: unsigned int repeat, float delay, bool paused, - const std::string& key); + std::string_view key); /** The scheduled method will be called every 'interval' seconds for ever. @param callback The callback function. @@ -263,7 +263,7 @@ public: @param key The key to identify the callback function, because there is not way to identify a std::function<>. @since v3.0 */ - void schedule(const ccSchedulerFunc& callback, void* target, float interval, bool paused, const std::string& key); + void schedule(const ccSchedulerFunc& callback, void* target, float interval, bool paused, std::string_view key); /** The scheduled method will be called every `interval` seconds. If paused is true, then it won't be called until it is resumed. @@ -329,7 +329,7 @@ public: @param target The target to be unscheduled. @since v3.0 */ - void unschedule(const std::string& key, void* target); + void unschedule(std::string_view key, void* target); /** Unschedules a selector for a given target. If you want to unschedule the "update", use `unscheduleUpdate()`. @@ -386,7 +386,7 @@ public: @return True if the specified callback is invoked, false if not. @since v3.0.0 */ - bool isScheduled(const std::string& key, const void* target) const; + bool isScheduled(std::string_view key, const void* target) const; /** Checks whether a selector for a given target is scheduled. @param selector The selector to be checked. diff --git a/cocos/base/CCScriptSupport.h b/cocos/base/CCScriptSupport.h index 318eec1da0..6613b152da 100644 --- a/cocos/base/CCScriptSupport.h +++ b/cocos/base/CCScriptSupport.h @@ -756,7 +756,7 @@ public: * @lua NA * @js NA */ - virtual bool parseConfig(ConfigType type, const std::string& str) = 0; + virtual bool parseConfig(ConfigType type, std::string_view str) = 0; /** Root a Reference. It tells the Garbage Collector that the associated Scripting object should not be collected diff --git a/cocos/base/CCUserDefault.cpp b/cocos/base/CCUserDefault.cpp index e3b243fe9c..d241ca88a4 100644 --- a/cocos/base/CCUserDefault.cpp +++ b/cocos/base/CCUserDefault.cpp @@ -211,12 +211,12 @@ double UserDefault::getDoubleForKey(const char* pKey, double defaultValue) return defaultValue; } -std::string UserDefault::getStringForKey(const char* pKey) +std::string_view UserDefault::getStringForKey(const char* pKey) { return getStringForKey(pKey, ""); } -std::string UserDefault::getStringForKey(const char* pKey, const std::string& defaultValue) +std::string_view UserDefault::getStringForKey(const char* pKey, std::string_view defaultValue) { auto pValue = getValueForKey(pKey); if (pValue) @@ -225,7 +225,7 @@ std::string UserDefault::getStringForKey(const char* pKey, const std::string& de return defaultValue; } -const std::string* UserDefault::getValueForKey(const std::string& key) +const std::string* UserDefault::getValueForKey(std::string_view key) { // do lazyInit at here to make sure _encryptEnabled works well, lazyInit(); @@ -294,7 +294,7 @@ void UserDefault::setDoubleForKey(const char* pKey, double value) setStringForKey(pKey, tmp); } -void UserDefault::setStringForKey(const char* pKey, const std::string& value) +void UserDefault::setStringForKey(const char* pKey, std::string_view value) { // ignore empty key if (!pKey || !*pKey) @@ -338,7 +338,7 @@ void UserDefault::setStringForKey(const char* pKey, const std::string& value) #endif } -void UserDefault::setValueForKey(const std::string& key, const std::string& value) +void UserDefault::setValueForKey(std::string_view key, std::string_view value) { // do lazyInit at here to make sure _encryptEnabled works well lazyInit(); @@ -346,7 +346,7 @@ void UserDefault::setValueForKey(const std::string& key, const std::string& valu updateValueForKey(key, value); } -void UserDefault::updateValueForKey(const std::string& key, const std::string& value) +void UserDefault::updateValueForKey(std::string_view key, std::string_view value) { auto it = _values.find(key); if (it != _values.end()) diff --git a/cocos/base/CCUserDefault.h b/cocos/base/CCUserDefault.h index 6f10045045..cf5de7f394 100644 --- a/cocos/base/CCUserDefault.h +++ b/cocos/base/CCUserDefault.h @@ -149,7 +149,7 @@ public: * @return String value of the key. * @js NA */ - std::string getStringForKey(const char* key); + std::string_view getStringForKey(const char* key); /** * Get string value by key, if the key doesn't exist, will return passed default value. @@ -158,7 +158,7 @@ public: * @return String value of the key. * @js NA */ - virtual std::string getStringForKey(const char* key, const std::string& defaultValue); + virtual std::string_view getStringForKey(const char* key, std::string_view defaultValue); // set value methods @@ -203,7 +203,7 @@ public: * @param value A string value to set to the key. * @js NA */ - virtual void setStringForKey(const char* key, const std::string& value); + virtual void setStringForKey(const char* key, std::string_view value); /** * Since we reimplement UserDefault with file mapping io, @@ -265,16 +265,16 @@ protected: void closeFileMapping(); // The low level API of all getXXXForKey - const std::string* getValueForKey(const std::string& key); + const std::string* getValueForKey(std::string_view key); // The low level API of all setXXXForKey - void setValueForKey(const std::string& key, const std::string& value); + void setValueForKey(std::string_view key, std::string_view value); // Update value without lazyInit - void updateValueForKey(const std::string& key, const std::string& value); + void updateValueForKey(std::string_view key, std::string_view value); protected: - std::unordered_map _values; + hlookup::string_map _values; static UserDefault* _userDefault; std::string _filePath; diff --git a/cocos/base/CCValue.cpp b/cocos/base/CCValue.cpp index 8045669764..225d8976ba 100644 --- a/cocos/base/CCValue.cpp +++ b/cocos/base/CCValue.cpp @@ -92,7 +92,7 @@ Value::Value(const char* v) : _type(Type::STRING) _field.strVal = new std::string(v ? v : ""); } -Value::Value(const std::string& v) : _type(Type::STRING) +Value::Value(std::string_view v) : _type(Type::STRING) { _field.strVal = new std::string(v); } @@ -308,7 +308,7 @@ Value& Value::operator=(const char* v) return *this; } -Value& Value::operator=(const std::string& v) +Value& Value::operator=(std::string_view v) { reset(Type::STRING); *_field.strVal = v; @@ -769,7 +769,7 @@ std::string Value::asString() const return ret; } -const std::string& Value::asStringRef() const +std::string_view Value::asStringRef() const { if (_type == Type::STRING) return *_field.strVal; diff --git a/cocos/base/CCValue.h b/cocos/base/CCValue.h index 47e511cf43..27c8c94fc1 100644 --- a/cocos/base/CCValue.h +++ b/cocos/base/CCValue.h @@ -43,7 +43,7 @@ NS_CC_BEGIN class Value; typedef std::vector ValueVector; -typedef std::unordered_map ValueMap; +typedef hlookup::string_map ValueMap; typedef std::unordered_map ValueMapIntKey; CC_DLL extern const ValueVector ValueVectorNull; @@ -91,7 +91,7 @@ public: explicit Value(const char* v); /** Create a Value by a string. */ - explicit Value(const std::string& v); + explicit Value(std::string_view v); explicit Value(std::string&& v); @@ -142,7 +142,7 @@ public: /** Assignment operator, assign from char* to Value. */ Value& operator=(const char* v); /** Assignment operator, assign from string to Value. */ - Value& operator=(const std::string& v); + Value& operator=(std::string_view v); Value& operator=(std::string&& v); /** Assignment operator, assign from ValueVector to Value. */ @@ -193,7 +193,7 @@ public: std::string asString() const; /** Gets as a string value reference without conversion, if value type is not string will return "" */ - const std::string& asStringRef() const; + std::string_view asStringRef() const; /** Gets as a ValueVector reference. Will convert to ValueVector if possible, or will trigger assert error. */ ValueVector& asValueVector(); @@ -279,6 +279,11 @@ private: Type _type; }; +inline const cocos2d::Value& optValue(const ValueMap& dictionary, std::string_view key) +{ + return dictionary.find(key) != dictionary.cend() ? dictionary.at(key) : cocos2d::Value::Null; +} + /** @} */ NS_CC_END diff --git a/cocos/base/ObjectFactory.cpp b/cocos/base/ObjectFactory.cpp index 065d70f049..d0920f7dff 100644 --- a/cocos/base/ObjectFactory.cpp +++ b/cocos/base/ObjectFactory.cpp @@ -30,12 +30,12 @@ NS_CC_BEGIN ObjectFactory::TInfo::TInfo() : _class(""), _fun(nullptr), _func(nullptr) {} -ObjectFactory::TInfo::TInfo(const std::string& type, Instance ins) : _class(type), _fun(ins), _func(nullptr) +ObjectFactory::TInfo::TInfo(std::string_view type, Instance ins) : _class(type), _fun(ins), _func(nullptr) { ObjectFactory::getInstance()->registerType(*this); } -ObjectFactory::TInfo::TInfo(const std::string& type, InstanceFunc ins) : _class(type), _fun(nullptr), _func(ins) +ObjectFactory::TInfo::TInfo(std::string_view type, InstanceFunc ins) : _class(type), _fun(nullptr), _func(ins) { ObjectFactory::getInstance()->registerType(*this); } @@ -85,12 +85,16 @@ void ObjectFactory::destroyInstance() CC_SAFE_DELETE(_sharedFactory); } -Ref* ObjectFactory::createObject(const std::string& name) +Ref* ObjectFactory::createObject(std::string_view name) { Ref* o = nullptr; do { - const TInfo t = _typeMap[name]; + // const TInfo t = _typeMap[name.data]; + auto it = _typeMap.find(name); + if (it == _typeMap.end()) + break; + auto& t = it->second; if (t._fun != nullptr) { o = t._fun(); diff --git a/cocos/base/ObjectFactory.h b/cocos/base/ObjectFactory.h index e7499b08e0..0ee3ad46f7 100644 --- a/cocos/base/ObjectFactory.h +++ b/cocos/base/ObjectFactory.h @@ -42,8 +42,8 @@ public: struct CC_DLL TInfo { TInfo(); - TInfo(const std::string& type, Instance ins = nullptr); - TInfo(const std::string& type, InstanceFunc ins = nullptr); + TInfo(std::string_view type, Instance ins = nullptr); + TInfo(std::string_view type, InstanceFunc ins = nullptr); TInfo(const TInfo& t); ~TInfo(); TInfo& operator=(const TInfo& t); @@ -51,11 +51,11 @@ public: Instance _fun; InstanceFunc _func; }; - typedef std::unordered_map FactoryMap; + typedef hlookup::string_map FactoryMap; static ObjectFactory* getInstance(); static void destroyInstance(); - cocos2d::Ref* createObject(const std::string& name); + cocos2d::Ref* createObject(std::string_view name); void registerType(const TInfo& t); void removeAll(); diff --git a/cocos/base/ZipUtils.cpp b/cocos/base/ZipUtils.cpp index f5fa6beb31..4454de57a8 100644 --- a/cocos/base/ZipUtils.cpp +++ b/cocos/base/ZipUtils.cpp @@ -658,7 +658,7 @@ struct ZipFilePrivate std::unique_ptr memfs; // std::unordered_map is faster if available on the platform - typedef std::unordered_map FileListContainer; + typedef hlookup::string_map FileListContainer; FileListContainer fileList; zlib_filefunc_def functionOverrides{}; @@ -683,10 +683,10 @@ ZipFile::ZipFile() : _data(new ZipFilePrivate()) _data->zipFile = nullptr; } -ZipFile::ZipFile(const std::string& zipFile, const std::string& filter) : _data(new ZipFilePrivate()) +ZipFile::ZipFile(std::string_view zipFile, std::string_view filter) : _data(new ZipFilePrivate()) { _data->zipFileName = zipFile; - _data->zipFile = unzOpen2(zipFile.c_str(), &_data->functionOverrides); + _data->zipFile = unzOpen2(zipFile.data(), &_data->functionOverrides); setFilter(filter); } @@ -700,7 +700,7 @@ ZipFile::~ZipFile() CC_SAFE_DELETE(_data); } -bool ZipFile::setFilter(const std::string& filter) +bool ZipFile::setFilter(std::string_view filter) { bool ret = false; do @@ -743,7 +743,7 @@ bool ZipFile::setFilter(const std::string& filter) return ret; } -bool ZipFile::fileExists(const std::string& fileName) const +bool ZipFile::fileExists(std::string_view fileName) const { bool ret = false; do @@ -756,7 +756,7 @@ bool ZipFile::fileExists(const std::string& fileName) const return ret; } -std::vector ZipFile::listFiles(const std::string& pathname) const +std::vector ZipFile::listFiles(std::string_view pathname) const { // filter files which `filename.startsWith(pathname)` @@ -766,22 +766,23 @@ std::vector ZipFile::listFiles(const std::string& pathname) const ZipFilePrivate::FileListContainer::const_iterator it = _data->fileList.begin(); ZipFilePrivate::FileListContainer::const_iterator end = _data->fileList.end(); // ensure pathname ends with `/` as a directory - std::string dirname = pathname[pathname.length() - 1] == '/' ? pathname : pathname + "/"; + std::string ensureDir; + std::string_view dirname = pathname[pathname.length() - 1] == '/' ? pathname : (ensureDir.append(pathname) += '/'); for (auto& item : _data->fileList) { - const std::string& filename = item.first; - if (cxx20::starts_with(cxx17::string_view{filename}, cxx17::string_view{dirname})) + std::string_view filename = item.first; + if (cxx20::starts_with(filename, cxx17::string_view{dirname})) { - std::string suffix = filename.substr(dirname.length()); + std::string_view suffix{filename.substr(dirname.length())}; auto pos = suffix.find('/'); if (pos == std::string::npos) { - fileSet.insert(suffix); + fileSet.insert(std::string{suffix}); } else { // fileSet.insert(parts[0] + "/"); - fileSet.insert(suffix.substr(0, pos + 1)); + fileSet.insert(std::string{suffix.substr(0, pos + 1)}); } } } @@ -789,7 +790,7 @@ std::vector ZipFile::listFiles(const std::string& pathname) const return std::vector{fileSet.begin(), fileSet.end()}; } -unsigned char* ZipFile::getFileData(const std::string& fileName, ssize_t* size) +unsigned char* ZipFile::getFileData(std::string_view fileName, ssize_t* size) { unsigned char* buffer = nullptr; if (size) @@ -800,7 +801,7 @@ unsigned char* ZipFile::getFileData(const std::string& fileName, ssize_t* size) CC_BREAK_IF(!_data->zipFile); CC_BREAK_IF(fileName.empty()); - ZipFilePrivate::FileListContainer::iterator it = _data->fileList.find(fileName); + auto it = _data->fileList.find(fileName); CC_BREAK_IF(it == _data->fileList.end()); ZipEntryInfo& fileInfo = it->second; @@ -828,7 +829,7 @@ unsigned char* ZipFile::getFileData(const std::string& fileName, ssize_t* size) return buffer; } -bool ZipFile::getFileData(const std::string& fileName, ResizableBuffer* buffer) +bool ZipFile::getFileData(std::string_view fileName, ResizableBuffer* buffer) { bool res = false; do @@ -915,14 +916,14 @@ bool ZipFile::initWithBuffer(const void* buffer, unsigned int size) return true; } -bool ZipFile::zfopen(const std::string& fileName, ZipFileStream* zfs) +bool ZipFile::zfopen(std::string_view fileName, ZipFileStream* zfs) { if (!zfs) return false; auto it = _data->fileList.find(fileName); if (it != _data->fileList.end()) { - zfs->entry = &it->second; + zfs->entry = &it->second; zfs->offset = 0; return true; } @@ -1005,7 +1006,7 @@ long long ZipFile::zfsize(ZipFileStream* zfs) return -1; } -unsigned char* ZipFile::getFileDataFromZip(const std::string& zipFilePath, const std::string& filename, ssize_t* size) +unsigned char* ZipFile::getFileDataFromZip(std::string_view zipFilePath, std::string_view filename, ssize_t* size) { unsigned char* buffer = nullptr; unzFile file = nullptr; @@ -1015,11 +1016,11 @@ unsigned char* ZipFile::getFileDataFromZip(const std::string& zipFilePath, const { CC_BREAK_IF(zipFilePath.empty()); - file = unzOpen(zipFilePath.c_str()); + file = unzOpen(zipFilePath.data()); CC_BREAK_IF(!file); // minizip 1.2.0 is same with other platforms - int ret = unzLocateFile(file, filename.c_str(), nullptr); + int ret = unzLocateFile(file, filename.data(), nullptr); CC_BREAK_IF(UNZ_OK != ret); diff --git a/cocos/base/ZipUtils.h b/cocos/base/ZipUtils.h index 4a74a38fb2..de982b90dc 100644 --- a/cocos/base/ZipUtils.h +++ b/cocos/base/ZipUtils.h @@ -250,7 +250,7 @@ public: * * @since v2.0.5 */ - ZipFile(const std::string& zipFile, const std::string& filter = std::string()); + ZipFile(std::string_view zipFile, std::string_view filter = std::string()); virtual ~ZipFile(); /** @@ -262,7 +262,7 @@ public: * * @since v2.0.5 */ - bool setFilter(const std::string& filter); + bool setFilter(std::string_view filter); /** * Check does a file exists or not in zip file @@ -272,7 +272,7 @@ public: * * @since v2.0.5 */ - bool fileExists(const std::string& fileName) const; + bool fileExists(std::string_view fileName) const; /** * Get files and folders in pathname @@ -280,7 +280,7 @@ public: * @param dirname * @return */ - std::vector listFiles(const std::string& pathname) const; + std::vector listFiles(std::string_view pathname) const; /** * Get resource file data from a zip file. @@ -291,7 +291,7 @@ public: * * @since v2.0.5 */ - unsigned char* getFileData(const std::string& fileName, ssize_t* size); + unsigned char* getFileData(std::string_view fileName, ssize_t* size); /** * Get resource file data from a zip file. @@ -299,7 +299,7 @@ public: * @param[out] buffer If the file read operation succeeds, if will contain the file data. * @return True if successful. */ - bool getFileData(const std::string& fileName, ResizableBuffer* buffer); + bool getFileData(std::string_view fileName, ResizableBuffer* buffer); std::string getFirstFilename(); std::string getNextFilename(); @@ -310,7 +310,7 @@ public: * zipFile Streaming support, !!!important, the file in zip must no compress level, otherwise * stream seek doesn't work. */ - bool zfopen(const std::string& fileName, ZipFileStream* zfs); + bool zfopen(std::string_view fileName, ZipFileStream* zfs); int zfread(ZipFileStream* zfs, void* buf, unsigned int size); int32_t zfseek(ZipFileStream* zfs, int32_t offset, int origin); void zfclose(ZipFileStream* zfs); @@ -325,8 +325,8 @@ public: * @warning Recall: you are responsible for calling free() on any Non-nullptr pointer returned. */ CC_DEPRECATED() - static unsigned char* getFileDataFromZip(const std::string& zipFilePath, - const std::string& filename, + static unsigned char* getFileDataFromZip(std::string_view zipFilePath, + std::string_view filename, ssize_t* size); private: diff --git a/cocos/base/ccUTF8.cpp b/cocos/base/ccUTF8.cpp index 1c993a6299..2db5969e2b 100644 --- a/cocos/base/ccUTF8.cpp +++ b/cocos/base/ccUTF8.cpp @@ -375,7 +375,7 @@ std::string getStringUTFCharsJNI(JNIEnv* env, jstring srcjStr, bool* ret) return utf8Str; } -jstring newStringUTFJNI(JNIEnv* env, const std::string& utf8Str, bool* ret) +jstring newStringUTFJNI(JNIEnv* env, std::string_view utf8Str, bool* ret) { std::u16string utf16Str; bool flag = cocos2d::StringUtils::UTF8ToUTF16(utf8Str, utf16Str); @@ -399,9 +399,9 @@ std::vector getChar16VectorFromUTF16String(const std::u16string& utf16 return std::vector(utf16.begin(), utf16.end()); } -int32_t getCharacterCountInUTF8String(const std::string& utf8) +int32_t getCharacterCountInUTF8String(std::string_view utf8) { - return getUTF8StringLength((const UTF8*)utf8.c_str()); + return getUTF8StringLength((const UTF8*)utf8.data()); } bool hasNonAsciiUTF8(const char* str, size_t len) @@ -455,7 +455,7 @@ bool isLegalUTF8String(const char* str, size_t len) StringUTF8::StringUTF8() {} -StringUTF8::StringUTF8(const std::string& newStr) +StringUTF8::StringUTF8(std::string_view newStr) { replace(newStr); } @@ -467,18 +467,18 @@ std::size_t StringUTF8::length() const return _str.size(); } -void StringUTF8::replace(const std::string& newStr) +void StringUTF8::replace(std::string_view newStr) { _str.clear(); if (!newStr.empty()) { - UTF8* sequenceUtf8 = (UTF8*)newStr.c_str(); + UTF8* sequenceUtf8 = (UTF8*)newStr.data(); int lengthString = getUTF8StringLength(sequenceUtf8); if (lengthString == 0) { - CCLOG("Bad utf-8 set string: %s", newStr.c_str()); + CCLOG("Bad utf-8 set string: %s", newStr.data()); return; } @@ -536,7 +536,7 @@ bool StringUTF8::deleteChar(std::size_t pos) } } -bool StringUTF8::insert(std::size_t pos, const std::string& insertStr) +bool StringUTF8::insert(std::size_t pos, std::string_view insertStr) { StringUTF8 utf8(insertStr); diff --git a/cocos/base/ccUTF8.h b/cocos/base/ccUTF8.h index 80626a4bc8..a648372018 100644 --- a/cocos/base/ccUTF8.h +++ b/cocos/base/ccUTF8.h @@ -147,7 +147,7 @@ CC_DLL std::string getStringUTFCharsJNI(JNIEnv* env, jstring srcjStr, bool* ret * @param ret True if the conversion succeeds and the ret pointer isn't null * @returns the result of jstring,the jstring need to DeleteLocalRef(jstring); */ -CC_DLL jstring newStringUTFJNI(JNIEnv* env, const std::string& utf8Str, bool* ret = nullptr); +CC_DLL jstring newStringUTFJNI(JNIEnv* env, std::string_view utf8Str, bool* ret = nullptr); #endif /** @@ -199,7 +199,7 @@ CC_DLL bool isUnicodeNonBreaking(char32_t ch); * @param utf8 An UTF-8 encoded string. * @returns The length of the string in characters. */ -CC_DLL int32_t getCharacterCountInUTF8String(const std::string& utf8); +CC_DLL int32_t getCharacterCountInUTF8String(std::string_view utf8); /** * @brief Gets the index of the last character that is not equal to the character given. @@ -245,18 +245,18 @@ public: typedef std::vector CharUTF8Store; StringUTF8(); - StringUTF8(const std::string& newStr); + StringUTF8(std::string_view newStr); ~StringUTF8(); std::size_t length() const; - void replace(const std::string& newStr); + void replace(std::string_view newStr); std::string getAsCharSequence() const; std::string getAsCharSequence(std::size_t pos) const; std::string getAsCharSequence(std::size_t pos, std::size_t len) const; bool deleteChar(std::size_t pos); - bool insert(std::size_t pos, const std::string& insertStr); + bool insert(std::size_t pos, std::string_view insertStr); bool insert(std::size_t pos, const StringUTF8& insertStr); CharUTF8Store& getString() { return _str; } diff --git a/cocos/base/ccUtils.cpp b/cocos/base/ccUtils.cpp index a661939ab0..c10a345f0b 100644 --- a/cocos/base/ccUtils.cpp +++ b/cocos/base/ccUtils.cpp @@ -178,13 +178,13 @@ void captureNode(Node* startNode, std::function)> imageCallba } // [DEPRECATED] -void captureScreen(std::function afterCap, const std::string& filename) +void captureScreen(std::function afterCap, std::string_view filename) { std::string outfile; if (FileUtils::getInstance()->isAbsolutePath(filename)) outfile = filename; else - outfile = FileUtils::getInstance()->getWritablePath() + filename; + outfile = FileUtils::getInstance()->getWritablePath().append(filename); captureScreen([_afterCap = std::move(afterCap), _outfile = std::move(outfile)](RefPtr image) mutable { AsyncTaskPool::getInstance()->enqueue( @@ -199,7 +199,7 @@ void captureScreen(std::function afterCap, const }); } -std::vector findChildren(const Node& node, const std::string& name) +std::vector findChildren(const Node& node, std::string_view name) { std::vector vec; @@ -348,7 +348,7 @@ Sprite* createSpriteFromBase64(const char* base64String) return sprite; } -Node* findChild(Node* levelRoot, const std::string& name) +Node* findChild(Node* levelRoot, std::string_view name) { if (levelRoot == nullptr || name.empty()) return nullptr; @@ -389,7 +389,7 @@ Node* findChild(Node* levelRoot, int tag) return nullptr; } -std::string getFileMD5Hash(const std::string& filename) +std::string getFileMD5Hash(std::string_view filename) { Data data; FileUtils::getInstance()->getContents(filename, &data); diff --git a/cocos/base/ccUtils.h b/cocos/base/ccUtils.h index 9ea8fad56d..8276c42355 100644 --- a/cocos/base/ccUtils.h +++ b/cocos/base/ccUtils.h @@ -92,7 +92,7 @@ CC_DLL void captureNode(Node* startNode, std::function)> imag * etc.). * @since v4.0 */ -CC_DLL void captureScreen(std::function afterCap, const std::string& filename); +CC_DLL void captureScreen(std::function afterCap, std::string_view filename); /** Find children by name, it will return all child that has the same name. * It supports c++ 11 regular expression. It is a helper function of `Node::enumerateChildren()`. @@ -103,7 +103,7 @@ CC_DLL void captureScreen(std::function afterCap * @return Array of Nodes that matches the name * @since v3.2 */ -CC_DLL std::vector findChildren(const Node& node, const std::string& name); +CC_DLL std::vector findChildren(const Node& node, std::string_view name); /** Same to ::atof, but strip the string, remain 7 numbers after '.' before call atof. * Why we need this? Because in android c++_static, atof ( and std::atof ) is unsupported for numbers have long decimal @@ -151,7 +151,7 @@ CC_DLL Sprite* createSpriteFromBase64(const char* base64String); * @return Returns found node or nullptr */ -CC_DLL Node* findChild(Node* levelRoot, const std::string& name); +CC_DLL Node* findChild(Node* levelRoot, std::string_view name); /** * Find a child by tag recursively @@ -166,7 +166,7 @@ CC_DLL Node* findChild(Node* levelRoot, int tag); * @return Returns found node or nullptr with specified type 'T' */ template -inline T findChild(Node* levelRoot, const std::string& name) +inline T findChild(Node* levelRoot, std::string_view name) { return dynamic_cast(findChild(levelRoot, name)); } @@ -187,7 +187,7 @@ inline T findChild(Node* levelRoot, int tag) * @param filename The file to calculate md5 hash. * @return The md5 hash for the file */ -CC_DLL std::string getFileMD5Hash(const std::string& filename); +CC_DLL std::string getFileMD5Hash(std::string_view filename); /** * Gets the md5 hash for the given buffer. diff --git a/cocos/base/hlookup.h b/cocos/base/hlookup.h new file mode 100644 index 0000000000..4a855cccff --- /dev/null +++ b/cocos/base/hlookup.h @@ -0,0 +1,62 @@ +// C++20 demo: Heterogeneous lookup for unordered containers (transparent hashing) +// https://en.cppreference.com/w/cpp/container/unordered_map/find +#pragma once +#include +#include +#include +#include +#include +#include +#include "tsl/robin_map.h" +#include "tsl/robin_set.h" + +using namespace std::string_literals; +using namespace std::string_view_literals; + +namespace hlookup +{ +struct string_hash +{ + using hash_type = std::hash; + using is_transparent = void; + + size_t operator()(const char* str) const { return hash_type{}(str); } + size_t operator()(std::string_view str) const { return hash_type{}(str); } + size_t operator()(std::string const& str) const { return hash_type{}(str); } +}; + +struct equal_to +{ + template + constexpr auto operator()(_Ty1&& _Left, _Ty2&& _Right) const + noexcept(noexcept(static_cast<_Ty1&&>(_Left) == static_cast<_Ty2&&>(_Right))) // strengthened + -> decltype(static_cast<_Ty1&&>(_Left) == static_cast<_Ty2&&>(_Right)) + { + return static_cast<_Ty1&&>(_Left) == static_cast<_Ty2&&>(_Right); + } + + using is_transparent = int; +}; + +template +using stl_string_map = std::map>; +using stl_string_set = std::set>; + +template +using string_map = tsl::robin_map; +using string_set = tsl::robin_set; + +template +inline auto set_item(_Cont& cont, std::string_view key, _Valty&& _Val) +{ + typename _Cont::iterator it = cont.find(key); + if (it != cont.end()) + it.value() = std::move(_Val); + else + it = cont.emplace(std::string{key}, std::forward<_Valty>(_Val)).first; + return it; +} + +constexpr auto empty_sv = ""sv; + +} // namespace hlookup diff --git a/cocos/navmesh/CCNavMesh.cpp b/cocos/navmesh/CCNavMesh.cpp index cd990f580f..dacb3948fb 100644 --- a/cocos/navmesh/CCNavMesh.cpp +++ b/cocos/navmesh/CCNavMesh.cpp @@ -90,7 +90,7 @@ static const int TILECACHESET_MAGIC = 'T' << 24 | 'S' << 16 | 'E' << 8 | 'T'; static const int TILECACHESET_VERSION = 2; // 1: fastlz, 2: lz4 static const int MAX_AGENTS = 128; -NavMesh* NavMesh::create(const std::string& navFilePath, const std::string& geomFilePath) +NavMesh* NavMesh::create(std::string_view navFilePath, std::string_view geomFilePath) { auto ref = new NavMesh(); if (ref->initWithFilePath(navFilePath, geomFilePath)) @@ -138,7 +138,7 @@ NavMesh::~NavMesh() _obstacleList.clear(); } -bool NavMesh::initWithFilePath(const std::string& navFilePath, const std::string& geomFilePath) +bool NavMesh::initWithFilePath(std::string_view navFilePath, std::string_view geomFilePath) { _navFilePath = navFilePath; _geomFilePath = geomFilePath; diff --git a/cocos/navmesh/CCNavMesh.h b/cocos/navmesh/CCNavMesh.h index 44aaaa1d03..41ad2f8d6b 100644 --- a/cocos/navmesh/CCNavMesh.h +++ b/cocos/navmesh/CCNavMesh.h @@ -60,7 +60,7 @@ public: @param navFilePath The NavMesh File path. @param geomFilePath The geometry File Path,include offmesh information,etc. */ - static NavMesh* create(const std::string& navFilePath, const std::string& geomFilePath); + static NavMesh* create(std::string_view navFilePath, std::string_view geomFilePath); /** update navmesh. */ void update(float dt); @@ -99,7 +99,7 @@ public: virtual ~NavMesh(); protected: - bool initWithFilePath(const std::string& navFilePath, const std::string& geomFilePath); + bool initWithFilePath(std::string_view navFilePath, std::string_view geomFilePath); bool read(); bool loadNavMeshFile(); bool loadGeomFile(); diff --git a/cocos/navmesh/CCNavMeshAgent.cpp b/cocos/navmesh/CCNavMeshAgent.cpp index 920bd386d1..f72ee758a2 100644 --- a/cocos/navmesh/CCNavMeshAgent.cpp +++ b/cocos/navmesh/CCNavMeshAgent.cpp @@ -60,7 +60,7 @@ NavMeshAgent* NavMeshAgent::create(const NavMeshAgentParam& param) return nullptr; } -const std::string& NavMeshAgent::getNavMeshAgentComponentName() +std::string_view NavMeshAgent::getNavMeshAgentComponentName() { static std::string comName = "___NavMeshAgentComponent___"; return comName; diff --git a/cocos/navmesh/CCNavMeshAgent.h b/cocos/navmesh/CCNavMeshAgent.h index d92e541d61..9b532cfd4a 100644 --- a/cocos/navmesh/CCNavMeshAgent.h +++ b/cocos/navmesh/CCNavMeshAgent.h @@ -97,7 +97,7 @@ public: @param param The parameters of agent. */ static NavMeshAgent* create(const NavMeshAgentParam& param); - static const std::string& getNavMeshAgentComponentName(); + static std::string_view getNavMeshAgentComponentName(); virtual void onEnter() override; virtual void onExit() override; diff --git a/cocos/navmesh/CCNavMeshObstacle.cpp b/cocos/navmesh/CCNavMeshObstacle.cpp index 61ad5d183a..81e9ec900f 100644 --- a/cocos/navmesh/CCNavMeshObstacle.cpp +++ b/cocos/navmesh/CCNavMeshObstacle.cpp @@ -45,7 +45,7 @@ NavMeshObstacle* NavMeshObstacle::create(float radius, float height) return nullptr; } -const std::string& NavMeshObstacle::getNavMeshObstacleComponentName() +std::string_view NavMeshObstacle::getNavMeshObstacleComponentName() { static std::string comName = "___NavMeshObstacleComponent___"; return comName; diff --git a/cocos/navmesh/CCNavMeshObstacle.h b/cocos/navmesh/CCNavMeshObstacle.h index 0dc5677284..b0a0ad32f3 100644 --- a/cocos/navmesh/CCNavMeshObstacle.h +++ b/cocos/navmesh/CCNavMeshObstacle.h @@ -64,7 +64,7 @@ public: @param height The height of obstacle. */ static NavMeshObstacle* create(float radius, float height); - static const std::string& getNavMeshObstacleComponentName(); + static std::string_view getNavMeshObstacleComponentName(); virtual void onEnter() override; virtual void onExit() override; diff --git a/cocos/network/CCDownloader-curl.cpp b/cocos/network/CCDownloader-curl.cpp index c91129d971..843d4b34c8 100644 --- a/cocos/network/CCDownloader-curl.cpp +++ b/cocos/network/CCDownloader-curl.cpp @@ -102,7 +102,7 @@ public: DLLOG("Destruct DownloadTaskCURL %p", this); } - bool init(const std::string& filename, const std::string& tempSuffix) + bool init(std::string_view filename, std::string_view tempSuffix) { if (0 == filename.length()) { @@ -166,7 +166,7 @@ public: } // init md5 state - _checksumFileName = filename + ".chksum"; + _checksumFileName = _tempFileName + ".chksum"; _fsMd5 = FileUtils::getInstance()->openFileStream(_checksumFileName, FileStream::Mode::OVERLAPPED); _fsMd5->seek(0, SEEK_END); @@ -215,7 +215,7 @@ public: /* retval: 0. don't check, 1. check succeed, 2. check failed */ - int checkFileMd5(const std::string& requiredsum, std::string* outsum = nullptr) + int checkFileMd5(std::string_view requiredsum, std::string* outsum = nullptr) { int status = 0; if (!requiredsum.empty()) diff --git a/cocos/network/CCDownloader.cpp b/cocos/network/CCDownloader.cpp index 14c337a1c2..5c9e67a36a 100644 --- a/cocos/network/CCDownloader.cpp +++ b/cocos/network/CCDownloader.cpp @@ -39,17 +39,17 @@ DownloadTask::DownloadTask() DLLOG("Construct DownloadTask %p", this); } -DownloadTask::DownloadTask(const std::string& srcUrl, const std::string& identifier) +DownloadTask::DownloadTask(std::string_view srcUrl, std::string_view identifier) { this->requestURL = srcUrl; this->identifier = identifier; this->background = false; } -DownloadTask::DownloadTask(const std::string& srcUrl, - const std::string& storagePath, - const std::string& checksum, - const std::string& identifier, +DownloadTask::DownloadTask(std::string_view srcUrl, + std::string_view storagePath, + std::string_view checksum, + std::string_view identifier, bool background) { this->requestURL = srcUrl; @@ -87,7 +87,7 @@ Downloader::Downloader(const DownloaderHints& hints) }; _impl->onTaskFinish = [this](const DownloadTask& task, int errorCode, int errorCodeInternal, - const std::string& errorStr, std::vector& data) { + std::string_view errorStr, std::vector& data) { if (DownloadTask::ERROR_NO_ERROR != errorCode) { if (onTaskError) @@ -121,8 +121,8 @@ Downloader::~Downloader() DLLOG("Destruct Downloader %p", this); } -std::shared_ptr Downloader::createDownloadDataTask(const std::string& srcUrl, - const std::string& identifier /* = ""*/) +std::shared_ptr Downloader::createDownloadDataTask(std::string_view srcUrl, + std::string_view identifier /* = ""*/) { auto task = std::make_shared(srcUrl, identifier); @@ -143,10 +143,10 @@ std::shared_ptr Downloader::createDownloadDataTask(const std::stri return task; } -std::shared_ptr Downloader::createDownloadFileTask(const std::string& srcUrl, - const std::string& storagePath, - const std::string& identifier, - const std::string& md5checksum, +std::shared_ptr Downloader::createDownloadFileTask(std::string_view srcUrl, + std::string_view storagePath, + std::string_view identifier, + std::string_view md5checksum, bool background) { auto task = std::make_shared(srcUrl, storagePath, md5checksum, identifier, background); @@ -167,7 +167,7 @@ std::shared_ptr Downloader::createDownloadFileTask(const std::stri return task; } -// std::string Downloader::getFileNameFromUrl(const std::string& srcUrl) +// std::string Downloader::getFileNameFromUrl(std::string_view srcUrl) //{ // // Find file name and file extension // std::string filename; diff --git a/cocos/network/CCDownloader.h b/cocos/network/CCDownloader.h index 164859bb73..16a6009ace 100644 --- a/cocos/network/CCDownloader.h +++ b/cocos/network/CCDownloader.h @@ -72,11 +72,11 @@ public: } mutable progressInfo; DownloadTask(); - DownloadTask(const std::string& srcUrl, const std::string& identifier); - DownloadTask(const std::string& srcUrl, - const std::string& storagePath, - const std::string& checksum, // currently is MD5 - const std::string& identifier, + DownloadTask(std::string_view srcUrl, std::string_view identifier); + DownloadTask(std::string_view srcUrl, + std::string_view storagePath, + std::string_view checksum, // currently is MD5 + std::string_view identifier, bool background); virtual ~DownloadTask(); @@ -114,7 +114,7 @@ public: std::function onTaskProgress; - std::function + std::function onTaskError; void setOnFileTaskSuccess(const std::function& callback) @@ -129,18 +129,18 @@ public: void setOnTaskError( const std::function< - void(const DownloadTask& task, int errorCode, int errorCodeInternal, const std::string& errorStr)>& + void(const DownloadTask& task, int errorCode, int errorCodeInternal, std::string_view errorStr)>& callback) { onTaskError = callback; }; - std::shared_ptr createDownloadDataTask(const std::string& srcUrl, const std::string& identifier = ""); + std::shared_ptr createDownloadDataTask(std::string_view srcUrl, std::string_view identifier = ""); - std::shared_ptr createDownloadFileTask(const std::string& srcUrl, - const std::string& storagePath, - const std::string& identifier = "", - const std::string& checksum = "", + std::shared_ptr createDownloadFileTask(std::string_view srcUrl, + std::string_view storagePath, + std::string_view identifier = "", + std::string_view checksum = "", bool background = false); private: diff --git a/cocos/network/CCIDownloaderImpl.h b/cocos/network/CCIDownloaderImpl.h index 71ffa79253..ceefec26fe 100644 --- a/cocos/network/CCIDownloaderImpl.h +++ b/cocos/network/CCIDownloaderImpl.h @@ -67,7 +67,7 @@ public: std::function& data)> onTaskFinish; diff --git a/cocos/network/HttpClient.cpp b/cocos/network/HttpClient.cpp index 0f2f78290e..81b6dcfc5e 100644 --- a/cocos/network/HttpClient.cpp +++ b/cocos/network/HttpClient.cpp @@ -104,7 +104,7 @@ void HttpClient::enableCookies(const char* cookieFile) _cookie->readFile(); } -void HttpClient::setSSLVerification(const std::string& caFile) +void HttpClient::setSSLVerification(std::string_view caFile) { std::lock_guard lock(_sslCaFileMutex); _sslCaFilename = caFile; @@ -167,9 +167,9 @@ void HttpClient::handleNetworkStatusChanged() _service->set_option(YOPT_S_DNS_DIRTY, 1); } -void HttpClient::setNameServers(const std::string& servers) +void HttpClient::setNameServers(std::string_view servers) { - _service->set_option(YOPT_S_DNS_LIST, servers.c_str()); + _service->set_option(YOPT_S_DNS_LIST, servers.data()); } yasio::io_service* HttpClient::getInternalService() @@ -208,7 +208,7 @@ int HttpClient::tryTakeAvailChannel() return -1; } -void HttpClient::processResponse(HttpResponse* response, const std::string& url) +void HttpClient::processResponse(HttpResponse* response, std::string_view url) { auto channelIndex = tryTakeAvailChannel(); response->retain(); @@ -221,7 +221,7 @@ void HttpClient::processResponse(HttpResponse* response, const std::string& url) auto& requestUri = response->getRequestUri(); auto channelHandle = _service->channel_at(channelIndex); channelHandle->ud_.ptr = response; - _service->set_option(YOPT_C_REMOTE_ENDPOINT, channelIndex, requestUri.getHost().c_str(), + _service->set_option(YOPT_C_REMOTE_ENDPOINT, channelIndex, requestUri.getHost().data(), (int)requestUri.getPort()); if (requestUri.isSecure()) _service->open(channelIndex, YCK_SSL_CLIENT); @@ -530,13 +530,13 @@ int HttpClient::getTimeoutForRead() return _timeoutForRead; } -const std::string& HttpClient::getCookieFilename() +std::string_view HttpClient::getCookieFilename() { std::lock_guard lock(_cookieFileMutex); return _cookieFilename; } -const std::string& HttpClient::getSSLVerification() +std::string_view HttpClient::getSSLVerification() { std::lock_guard lock(_sslCaFileMutex); return _sslCaFilename; diff --git a/cocos/network/HttpClient.h b/cocos/network/HttpClient.h index 7d6fd1a7a6..36a191fbf6 100644 --- a/cocos/network/HttpClient.h +++ b/cocos/network/HttpClient.h @@ -89,21 +89,21 @@ public: * * @return the cookie filename */ - const std::string& getCookieFilename(); + std::string_view getCookieFilename(); /** * Set root certificate path for SSL verification. * * @param caFile a full path of root certificate.if it is empty, SSL verification is disabled. */ - void setSSLVerification(const std::string& caFile); + void setSSLVerification(std::string_view caFile); /** * Get the ssl CA filename * * @return the ssl CA filename */ - const std::string& getSSLVerification(); + std::string_view getSSLVerification(); /** * Send http request concurrently, non-blocking @@ -197,7 +197,7 @@ public: * Sets custom dns server list: * format: "xxx.xxx.xxx.xxx[:port],xxx.xxx.xxx.xxx[:port] */ - void setNameServers(const std::string& servers); + void setNameServers(std::string_view servers); yasio::io_service* getInternalService(); @@ -205,7 +205,7 @@ private: HttpClient(); virtual ~HttpClient(); - void processResponse(HttpResponse* response, const std::string& url); + void processResponse(HttpResponse* response, std::string_view url); int tryTakeAvailChannel(); diff --git a/cocos/network/HttpCookie.cpp b/cocos/network/HttpCookie.cpp index be22e571b1..bfe76554e1 100644 --- a/cocos/network/HttpCookie.cpp +++ b/cocos/network/HttpCookie.cpp @@ -151,11 +151,11 @@ std::string HttpCookie::checkAndGetFormatedMatchCookies(const Uri& uri) return ret; } -bool HttpCookie::updateOrAddCookie(const std::string& cookie, const Uri& uri) +bool HttpCookie::updateOrAddCookie(std::string_view cookie, const Uri& uri) { unsigned int count = 0; CookieInfo info; - xsbase::nzls::fast_split(cookie.c_str(), cookie.length(), ';', [&](const char* start, const char* end) { + xsbase::nzls::fast_split(cookie.data(), cookie.length(), ';', [&](const char* start, const char* end) { unsigned int count_ = 0; while (*start == ' ') ++start; // skip ws @@ -289,7 +289,7 @@ void HttpCookie::writeFile() fclose(out); } -void HttpCookie::setCookieFileName(const std::string& filename) +void HttpCookie::setCookieFileName(std::string_view filename) { _cookieFileName = filename; } diff --git a/cocos/network/HttpCookie.h b/cocos/network/HttpCookie.h index 8e7d116cac..4ba517d2d2 100644 --- a/cocos/network/HttpCookie.h +++ b/cocos/network/HttpCookie.h @@ -90,7 +90,7 @@ public: void readFile(); void writeFile(); - void setCookieFileName(const std::string& fileName); + void setCookieFileName(std::string_view fileName); const std::vector* getCookies() const; const CookieInfo* getMatchCookie(const Uri& uri) const; @@ -98,7 +98,7 @@ public: // Check match cookies for http request std::string checkAndGetFormatedMatchCookies(const Uri& uri); - bool updateOrAddCookie(const std::string& cookie, const Uri& uri); + bool updateOrAddCookie(std::string_view cookie, const Uri& uri); private: std::string _cookieFileName; diff --git a/cocos/network/HttpRequest.h b/cocos/network/HttpRequest.h index 2dee876f32..10a5ad0072 100644 --- a/cocos/network/HttpRequest.h +++ b/cocos/network/HttpRequest.h @@ -125,14 +125,14 @@ public: * * @param url the string object. */ - void setUrl(const std::string& url) { _url = url; } + void setUrl(std::string_view url) { _url = url; } /** * Get the url address of HttpRequest object. * * @return const char* the pointer of _url. */ - const std::string& getUrl() const { return _url; } + std::string_view getUrl() const { return _url; } /** * Set the request data of HttpRequest object. @@ -168,7 +168,7 @@ public: * * @param tag the string object. */ - void setTag(const std::string& tag) { _tag = tag; } + void setTag(std::string_view tag) { _tag = tag; } /** * Get the string tag to identify the request. diff --git a/cocos/network/HttpResponse.h b/cocos/network/HttpResponse.h index 8909c36440..68b3694df6 100644 --- a/cocos/network/HttpResponse.h +++ b/cocos/network/HttpResponse.h @@ -155,7 +155,7 @@ private: * @param value a string pointer that point to response data buffer. * @param n the defined size that the response data buffer would be copied. */ - bool prepareForProcess(const std::string& url) + bool prepareForProcess(std::string_view url) { /* Resets response status */ _finished = false; diff --git a/cocos/network/Uri.cpp b/cocos/network/Uri.cpp index 665837fccc..835738740b 100644 --- a/cocos/network/Uri.cpp +++ b/cocos/network/Uri.cpp @@ -143,7 +143,7 @@ bool Uri::operator==(const Uri& o) const _queryParams == o._queryParams); } -Uri Uri::parse(const std::string& str) +Uri Uri::parse(std::string_view str) { Uri uri; @@ -155,7 +155,7 @@ Uri Uri::parse(const std::string& str) return uri; } -bool Uri::doParse(const std::string& str) +bool Uri::doParse(std::string_view str) { static const std::regex uriRegex( "([a-zA-Z][a-zA-Z0-9+.-]*):" // scheme: @@ -182,7 +182,7 @@ bool Uri::doParse(const std::string& str) std::smatch match; if (UNLIKELY(!std::regex_match(copied.cbegin(), copied.cend(), match, uriRegex))) { - CCLOGERROR("Invalid URI: %s", str.c_str()); + CCLOGERROR("Invalid URI: %s", str.data()); return false; } diff --git a/cocos/network/Uri.h b/cocos/network/Uri.h index aa24b1d924..de32b98921 100644 --- a/cocos/network/Uri.h +++ b/cocos/network/Uri.h @@ -58,7 +58,7 @@ public: /** * Parse a Uri from a string. Throws std::invalid_argument on parse error. */ - static Uri parse(const std::string& str); + static Uri parse(std::string_view str); /** Default constructor */ Uri(); @@ -85,18 +85,18 @@ public: bool isSecure() const { return _isSecure; } /** Gets the scheme name for this URI. */ - const std::string& getScheme() const { return _scheme; } + std::string_view getScheme() const { return _scheme; } /** Gets the user name with the specified URI. */ - const std::string& getUserName() const { return _username; } + std::string_view getUserName() const { return _username; } /** Gets the password with the specified URI. */ - const std::string& getPassword() const { return _password; } + std::string_view getPassword() const { return _password; } /** * Get host part of URI. If host is an IPv6 address, square brackets will be * returned, for example: "[::1]". */ - const std::string& getHost() const { return _host; } + std::string_view getHost() const { return _host; } /** * Get host part of URI. If host is an IPv6 address, square brackets will not * be returned, for exmaple "::1"; otherwise it returns the same thing as @@ -106,29 +106,29 @@ public: * or API that connects to that host/port; e.g. getaddrinfo() only understands * IPv6 host without square brackets */ - const std::string& getHostName() const { return _hostName; } + std::string_view getHostName() const { return _hostName; } /** Gets the port number of the URI. */ uint16_t getPort() const { return _port; } /** Gets the path part of the URI. */ - const std::string& getPath() const { return _path; } + std::string_view getPath() const { return _path; } /// Gets the path, query and fragment parts of the URI. - const std::string& getPathEtc() const { return _pathEtc; } + std::string_view getPathEtc() const { return _pathEtc; } /** Gets the query part of the URI. */ - const std::string& getQuery() const { return _query; } + std::string_view getQuery() const { return _query; } /** Gets the fragment part of the URI */ - const std::string& getFragment() const { return _fragment; } + std::string_view getFragment() const { return _fragment; } /** Gets the authority part (userName, password, host and port) of the URI. * @note If the port number is a well-known port * number for the given scheme (e.g., 80 for http), it * is not included in the authority. */ - const std::string& getAuthority() const { return _authority; } + std::string_view getAuthority() const { return _authority; } /** Gets a string representation of the URI. */ std::string toString() const; @@ -159,7 +159,7 @@ public: void clear(); private: - bool doParse(const std::string& str); + bool doParse(std::string_view str); bool _isValid; bool _isSecure; diff --git a/cocos/physics3d/CCPhysicsSprite3D.cpp b/cocos/physics3d/CCPhysicsSprite3D.cpp index be3b008054..26a0da9a7f 100644 --- a/cocos/physics3d/CCPhysicsSprite3D.cpp +++ b/cocos/physics3d/CCPhysicsSprite3D.cpp @@ -31,7 +31,7 @@ NS_CC_BEGIN -PhysicsSprite3D* PhysicsSprite3D::create(const std::string& modelPath, +PhysicsSprite3D* PhysicsSprite3D::create(std::string_view modelPath, Physics3DRigidBodyDes* rigidDes, const cocos2d::Vec3& translateInPhysics, const cocos2d::Quaternion& rotInPhsyics) @@ -50,7 +50,7 @@ PhysicsSprite3D* PhysicsSprite3D::create(const std::string& modelPath, return ret; } -PhysicsSprite3D* PhysicsSprite3D::createWithCollider(const std::string& modelPath, +PhysicsSprite3D* PhysicsSprite3D::createWithCollider(std::string_view modelPath, Physics3DColliderDes* colliderDes, const cocos2d::Vec3& translateInPhysics, const cocos2d::Quaternion& rotInPhsyics) diff --git a/cocos/physics3d/CCPhysicsSprite3D.h b/cocos/physics3d/CCPhysicsSprite3D.h index 3a61876de4..7e94346f55 100644 --- a/cocos/physics3d/CCPhysicsSprite3D.h +++ b/cocos/physics3d/CCPhysicsSprite3D.h @@ -48,13 +48,13 @@ class CC_DLL PhysicsSprite3D : public cocos2d::Sprite3D { public: /** creates a PhysicsSprite3D*/ - static PhysicsSprite3D* create(const std::string& modelPath, + static PhysicsSprite3D* create(std::string_view modelPath, Physics3DRigidBodyDes* rigidDes, const cocos2d::Vec3& translateInPhysics = cocos2d::Vec3::ZERO, const cocos2d::Quaternion& rotInPhsyics = cocos2d::Quaternion::ZERO); /** creates a PhysicsSprite3D as a collider*/ - static PhysicsSprite3D* createWithCollider(const std::string& modelPath, + static PhysicsSprite3D* createWithCollider(std::string_view modelPath, Physics3DColliderDes* colliderDes, const cocos2d::Vec3& translateInPhysics = cocos2d::Vec3::ZERO, const cocos2d::Quaternion& rotInPhsyics = cocos2d::Quaternion::ZERO); diff --git a/cocos/platform/CCApplicationProtocol.h b/cocos/platform/CCApplicationProtocol.h index 7bb1e930fd..cfb3b0ba04 100644 --- a/cocos/platform/CCApplicationProtocol.h +++ b/cocos/platform/CCApplicationProtocol.h @@ -152,7 +152,7 @@ public: * @js NA * @lua NA */ - virtual bool openURL(const std::string& url) = 0; + virtual bool openURL(std::string_view url) = 0; }; // end of platform group diff --git a/cocos/platform/CCFileStream.h b/cocos/platform/CCFileStream.h index e44e74a512..74caba22bc 100644 --- a/cocos/platform/CCFileStream.h +++ b/cocos/platform/CCFileStream.h @@ -28,7 +28,7 @@ public: * @param mode File open mode, being READ | WRITE | APPEND * @return true if successful, false if not */ - virtual bool open(const std::string& path, FileStream::Mode mode) = 0; + virtual bool open(std::string_view path, FileStream::Mode mode) = 0; /** * Close a file stream diff --git a/cocos/platform/CCFileUtils.cpp b/cocos/platform/CCFileUtils.cpp index 06fd8061c8..588465d382 100644 --- a/cocos/platform/CCFileUtils.cpp +++ b/cocos/platform/CCFileUtils.cpp @@ -92,7 +92,7 @@ public: ~DictMaker() {} - ValueMap dictionaryWithContentsOfFile(const std::string& fileName) + ValueMap dictionaryWithContentsOfFile(std::string_view fileName) { _resultType = SAX_RESULT_DICT; SAXParser parser; @@ -116,7 +116,7 @@ public: return _rootDict; } - ValueVector arrayWithContentsOfFile(const std::string& fileName) + ValueVector arrayWithContentsOfFile(std::string_view fileName) { _resultType = SAX_RESULT_ARRAY; SAXParser parser; @@ -321,7 +321,7 @@ public: } }; -ValueMap FileUtils::getValueMapFromFile(const std::string& filename) const +ValueMap FileUtils::getValueMapFromFile(std::string_view filename) const { const std::string fullPath = fullPathForFilename(filename); DictMaker tMaker; @@ -334,7 +334,7 @@ ValueMap FileUtils::getValueMapFromData(const char* filedata, int filesize) cons return tMaker.dictionaryWithDataOfFile(filedata, filesize); } -ValueVector FileUtils::getValueVectorFromFile(const std::string& filename) const +ValueVector FileUtils::getValueVectorFromFile(std::string_view filename) const { const std::string fullPath = fullPathForFilename(filename); DictMaker tMaker; @@ -350,12 +350,12 @@ static void generateElementForDict(const ValueMap& dict, pugi::xml_node& innerDi /* * Use pugixml to write plist files */ -bool FileUtils::writeToFile(const ValueMap& dict, const std::string& fullPath) const +bool FileUtils::writeToFile(const ValueMap& dict, std::string_view fullPath) const { return writeValueMapToFile(dict, fullPath); } -bool FileUtils::writeValueMapToFile(const ValueMap& dict, const std::string& fullPath) const +bool FileUtils::writeValueMapToFile(const ValueMap& dict, std::string_view fullPath) const { pugi::xml_document doc; doc.load_string(R"( @@ -371,7 +371,7 @@ bool FileUtils::writeValueMapToFile(const ValueMap& dict, const std::string& ful return writeStringToFile(ss.str(), fullPath); } -bool FileUtils::writeValueVectorToFile(const ValueVector& vecData, const std::string& fullPath) const +bool FileUtils::writeValueVectorToFile(const ValueVector& vecData, std::string_view fullPath) const { pugi::xml_document doc; doc.load_string(R"( @@ -460,35 +460,35 @@ FileUtils::FileUtils() : _writablePath("") {} FileUtils::~FileUtils() {} -bool FileUtils::writeStringToFile(const std::string& dataStr, const std::string& fullPath) const +bool FileUtils::writeStringToFile(std::string_view dataStr, std::string_view fullPath) const { - return FileUtils::writeBinaryToFile(dataStr.c_str(), dataStr.size(), fullPath); + return FileUtils::writeBinaryToFile(dataStr.data(), dataStr.size(), fullPath); } void FileUtils::writeStringToFile(std::string dataStr, - const std::string& fullPath, + std::string_view fullPath, std::function callback) const { performOperationOffthread( - [fullPath](const std::string& dataStrIn) -> bool { + [fullPath](std::string_view dataStrIn) -> bool { return FileUtils::getInstance()->writeStringToFile(dataStrIn, fullPath); }, std::move(callback), std::move(dataStr)); } -bool FileUtils::writeDataToFile(const Data& data, const std::string& fullPath) const +bool FileUtils::writeDataToFile(const Data& data, std::string_view fullPath) const { return FileUtils::writeBinaryToFile(data.getBytes(), data.getSize(), fullPath); } -void FileUtils::writeDataToFile(Data data, const std::string& fullPath, std::function callback) const +void FileUtils::writeDataToFile(Data data, std::string_view fullPath, std::function callback) const { performOperationOffthread( [fullPath](const Data& dataIn) -> bool { return FileUtils::getInstance()->writeDataToFile(dataIn, fullPath); }, std::move(callback), std::move(data)); } -bool FileUtils::writeBinaryToFile(const void* data, size_t dataSize, const std::string& fullPath) +bool FileUtils::writeBinaryToFile(const void* data, size_t dataSize, std::string_view fullPath) { CCASSERT(!fullPath.empty() && dataSize > 0, "Invalid parameters."); @@ -521,14 +521,14 @@ void FileUtils::purgeCachedEntries() _fullPathCacheDir.clear(); } -std::string FileUtils::getStringFromFile(const std::string& filename) const +std::string FileUtils::getStringFromFile(std::string_view filename) const { std::string s; getContents(filename, &s); return s; } -void FileUtils::getStringFromFile(const std::string& path, std::function callback) const +void FileUtils::getStringFromFile(std::string_view path, std::function callback) const { // Get the full path on the main thread, to avoid the issue that FileUtil's is not // thread safe, and accessing the fullPath cache and searching the search paths is not thread safe @@ -538,21 +538,21 @@ void FileUtils::getStringFromFile(const std::string& path, std::function callback) const +void FileUtils::getDataFromFile(std::string_view filename, std::function callback) const { auto fullPath = fullPathForFilename(filename); performOperationOffthread([fullPath]() -> Data { return FileUtils::getInstance()->getDataFromFile(fullPath); }, std::move(callback)); } -FileUtils::Status FileUtils::getContents(const std::string& filename, ResizableBuffer* buffer) const +FileUtils::Status FileUtils::getContents(std::string_view filename, ResizableBuffer* buffer) const { if (filename.empty()) return Status::NotExists; @@ -591,7 +591,7 @@ FileUtils::Status FileUtils::getContents(const std::string& filename, ResizableB } void FileUtils::writeValueMapToFile(ValueMap dict, - const std::string& fullPath, + std::string_view fullPath, std::function callback) const { @@ -603,7 +603,7 @@ void FileUtils::writeValueMapToFile(ValueMap dict, } void FileUtils::writeValueVectorToFile(ValueVector vecData, - const std::string& fullPath, + std::string_view fullPath, std::function callback) const { performOperationOffthread( @@ -613,7 +613,7 @@ void FileUtils::writeValueVectorToFile(ValueVector vecData, std::move(callback), std::move(vecData)); } -std::string FileUtils::getNewFilename(const std::string& filename) const +std::string FileUtils::getNewFilename(std::string_view filename) const { std::string newFileName; @@ -633,11 +633,11 @@ std::string FileUtils::getNewFilename(const std::string& filename) const return newFileName; } -std::string FileUtils::getPathForFilename(const std::string& filename, - const std::string& resolutionDirectory, - const std::string& searchPath) const +std::string FileUtils::getPathForFilename(std::string_view filename, + std::string_view resolutionDirectory, + std::string_view searchPath) const { - std::string file = filename; + auto file = filename; std::string file_path = ""; size_t pos = filename.find_last_of('/'); if (pos != std::string::npos) @@ -647,7 +647,7 @@ std::string FileUtils::getPathForFilename(const std::string& filename, } // searchPath + file_path + resourceDirectory - std::string path = searchPath; + std::string path{searchPath}; path += file_path; path += resolutionDirectory; @@ -656,14 +656,14 @@ std::string FileUtils::getPathForFilename(const std::string& filename, return path; } -std::string FileUtils::getPathForDirectory(const std::string& dir, - const std::string& resolutionDiretory, - const std::string& searchPath) const +std::string FileUtils::getPathForDirectory(std::string_view dir, + std::string_view resolutionDiretory, + std::string_view searchPath) const { - return searchPath + resolutionDiretory + dir; + return std::string{searchPath}.append(resolutionDiretory).append(dir); } -std::string FileUtils::fullPathForFilename(const std::string& filename) const +std::string FileUtils::fullPathForFilename(std::string_view filename) const { DECLARE_GUARD; @@ -681,7 +681,7 @@ std::string FileUtils::fullPathForFilename(const std::string& filename) const */ if (isAbsolutePath(filename)) { - return filename; + return std::string{filename}; } // Already Cached ? @@ -713,14 +713,14 @@ std::string FileUtils::fullPathForFilename(const std::string& filename) const if (isPopupNotify()) { - CCLOG("cocos2d: fullPathForFilename: No file found at %s. Possible missing file.", filename.c_str()); + CCLOG("cocos2d: fullPathForFilename: No file found at %s. Possible missing file.", filename.data()); } // The file wasn't found, return empty string. - return ""; + return std::string{}; } -std::string FileUtils::fullPathForDirectory(const std::string& dir) const +std::string FileUtils::fullPathForDirectory(std::string_view dir) const { DECLARE_GUARD; @@ -731,7 +731,7 @@ std::string FileUtils::fullPathForDirectory(const std::string& dir) const if (isAbsolutePath(dir)) { - return dir; + return std::string{dir}; } // Already Cached ? @@ -740,7 +740,7 @@ std::string FileUtils::fullPathForDirectory(const std::string& dir) const { return cacheIter->second; } - std::string longdir = dir; + std::string longdir{dir}; std::string fullpath; if (longdir[longdir.length() - 1] != '/') @@ -766,16 +766,16 @@ std::string FileUtils::fullPathForDirectory(const std::string& dir) const if (isPopupNotify()) { - CCLOG("cocos2d: fullPathForDirectory: No directory found at %s. Possible missing directory.", dir.c_str()); + CCLOG("cocos2d: fullPathForDirectory: No directory found at %s. Possible missing directory.", dir.data()); } // The file wasn't found, return empty string. return ""; } -std::string FileUtils::fullPathFromRelativeFile(const std::string& filename, const std::string& relativeFile) const +std::string FileUtils::fullPathFromRelativeFile(std::string_view filename, std::string_view relativeFile) const { - return relativeFile.substr(0, relativeFile.rfind('/') + 1) + getNewFilename(filename); + return std::string{relativeFile.substr(0, relativeFile.rfind('/') + 1)}.append(getNewFilename(filename)); } void FileUtils::setSearchResolutionsOrder(const std::vector& searchResolutionsOrder) @@ -795,7 +795,7 @@ void FileUtils::setSearchResolutionsOrder(const std::vector& search for (const auto& iter : searchResolutionsOrder) { std::string resolutionDirectory = iter; - if (!existDefault && resolutionDirectory == "") + if (!existDefault && resolutionDirectory.empty()) { existDefault = true; } @@ -814,12 +814,12 @@ void FileUtils::setSearchResolutionsOrder(const std::vector& search } } -void FileUtils::addSearchResolutionsOrder(const std::string& order, const bool front) +void FileUtils::addSearchResolutionsOrder(std::string_view order, const bool front) { DECLARE_GUARD; - std::string resOrder = order; + std::string resOrder{order}; if (!resOrder.empty() && resOrder[resOrder.length() - 1] != '/') resOrder.push_back('/'); @@ -851,7 +851,7 @@ const std::vector FileUtils::getOriginalSearchPaths() const return _originalSearchPaths; } -void FileUtils::setWritablePath(const std::string& writablePath) +void FileUtils::setWritablePath(std::string_view writablePath) { DECLARE_GUARD; _writablePath = writablePath; @@ -863,7 +863,7 @@ const std::string FileUtils::getDefaultResourceRootPath() const return _defaultResRootPath; } -void FileUtils::setDefaultResourceRootPath(const std::string& path) +void FileUtils::setDefaultResourceRootPath(std::string_view path) { DECLARE_GUARD; if (_defaultResRootPath != path) @@ -919,14 +919,14 @@ void FileUtils::setSearchPaths(const std::vector& searchPaths) } } -void FileUtils::addSearchPath(const std::string& searchpath, const bool front) +void FileUtils::addSearchPath(std::string_view searchpath, const bool front) { DECLARE_GUARD; - std::string prefix; + std::string path; if (!isAbsolutePath(searchpath)) - prefix = _defaultResRootPath; + path = _defaultResRootPath; - std::string path = prefix + searchpath; + path.append(searchpath); if (!path.empty() && path[path.length() - 1] != '/') { path += "/"; @@ -934,13 +934,13 @@ void FileUtils::addSearchPath(const std::string& searchpath, const bool front) if (front) { - _originalSearchPaths.insert(_originalSearchPaths.begin(), searchpath); - _searchPathArray.insert(_searchPathArray.begin(), path); + _originalSearchPaths.insert(_originalSearchPaths.begin(), std::string{searchpath}); + _searchPathArray.insert(_searchPathArray.begin(), std::move(path)); } else { - _originalSearchPaths.push_back(searchpath); - _searchPathArray.push_back(path); + _originalSearchPaths.push_back(std::string{searchpath}); + _searchPathArray.push_back(std::move(path)); } } @@ -952,7 +952,7 @@ void FileUtils::setFilenameLookupDictionary(const ValueMap& filenameLookupDict) _filenameLookupDict = filenameLookupDict; } -void FileUtils::loadFilenameLookupDictionaryFromFile(const std::string& filename) +void FileUtils::loadFilenameLookupDictionaryFromFile(std::string_view filename) { const std::string fullPath = fullPathForFilename(filename); if (!fullPath.empty()) @@ -965,7 +965,7 @@ void FileUtils::loadFilenameLookupDictionaryFromFile(const std::string& filename if (version != 1) { CCLOG("cocos2d: ERROR: Invalid filenameLookup dictionary version: %d. Filename: %s", version, - filename.c_str()); + filename.data()); return; } setFilenameLookupDictionary(dict["filenames"].asValueMap()); @@ -973,12 +973,12 @@ void FileUtils::loadFilenameLookupDictionaryFromFile(const std::string& filename } } -std::string FileUtils::getFullPathForFilenameWithinDirectory(const std::string& directory, - const std::string& filename) const +std::string FileUtils::getFullPathForFilenameWithinDirectory(std::string_view directory, + std::string_view filename) const { // get directory+filename, safely adding '/' as necessary - std::string ret = directory; - if (directory.size() && directory[directory.size() - 1] != '/') + std::string ret{directory}; + if (!directory.empty() && directory[directory.size() - 1] != '/') { ret += '/'; } @@ -986,12 +986,12 @@ std::string FileUtils::getFullPathForFilenameWithinDirectory(const std::string& // if the file doesn't exist, return an empty string if (!isFileExistInternal(ret)) { - ret = ""; + ret.clear(); } return ret; } -bool FileUtils::isFileExist(const std::string& filename) const +bool FileUtils::isFileExist(std::string_view filename) const { if (isAbsolutePath(filename)) { @@ -1007,19 +1007,19 @@ bool FileUtils::isFileExist(const std::string& filename) const } } -void FileUtils::isFileExist(const std::string& filename, std::function callback) const +void FileUtils::isFileExist(std::string_view filename, std::function callback) const { auto fullPath = fullPathForFilename(filename); performOperationOffthread([fullPath]() -> bool { return FileUtils::getInstance()->isFileExist(fullPath); }, std::move(callback)); } -bool FileUtils::isAbsolutePath(const std::string& path) const +bool FileUtils::isAbsolutePath(std::string_view path) const { return isAbsolutePathInternal(path); } -bool FileUtils::isAbsolutePathInternal(const std::string& path) +bool FileUtils::isAbsolutePathInternal(std::string_view path) { #if defined(_WIN32) // see also: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file?redirectedfrom=MSDN @@ -1034,7 +1034,7 @@ bool FileUtils::isAbsolutePathInternal(const std::string& path) #endif } -bool FileUtils::isDirectoryExist(const std::string& dirPath) const +bool FileUtils::isDirectoryExist(std::string_view dirPath) const { CCASSERT(!dirPath.empty(), "Invalid path"); @@ -1051,35 +1051,35 @@ bool FileUtils::isDirectoryExist(const std::string& dirPath) const } } -void FileUtils::isDirectoryExist(const std::string& fullPath, std::function callback) const +void FileUtils::isDirectoryExist(std::string_view fullPath, std::function callback) const { CCASSERT(isAbsolutePath(fullPath), "Async isDirectoryExist only accepts absolute file paths"); performOperationOffthread([fullPath]() -> bool { return FileUtils::getInstance()->isDirectoryExist(fullPath); }, std::move(callback)); } -void FileUtils::createDirectory(const std::string& dirPath, std::function callback) const +void FileUtils::createDirectory(std::string_view dirPath, std::function callback) const { performOperationOffthread([dirPath]() -> bool { return FileUtils::getInstance()->createDirectory(dirPath); }, std::move(callback)); } -void FileUtils::removeDirectory(const std::string& dirPath, std::function callback) const +void FileUtils::removeDirectory(std::string_view dirPath, std::function callback) const { performOperationOffthread([dirPath]() -> bool { return FileUtils::getInstance()->removeDirectory(dirPath); }, std::move(callback)); } -void FileUtils::removeFile(const std::string& filepath, std::function callback) const +void FileUtils::removeFile(std::string_view filepath, std::function callback) const { auto fullPath = fullPathForFilename(filepath); performOperationOffthread([fullPath]() -> bool { return FileUtils::getInstance()->removeFile(fullPath); }, std::move(callback)); } -void FileUtils::renameFile(const std::string& path, - const std::string& oldname, - const std::string& name, +void FileUtils::renameFile(std::string_view path, + std::string_view oldname, + std::string_view name, std::function callback) const { performOperationOffthread( @@ -1087,8 +1087,8 @@ void FileUtils::renameFile(const std::string& path, std::move(callback)); } -void FileUtils::renameFile(const std::string& oldfullpath, - const std::string& newfullpath, +void FileUtils::renameFile(std::string_view oldfullpath, + std::string_view newfullpath, std::function callback) const { performOperationOffthread( @@ -1096,21 +1096,21 @@ void FileUtils::renameFile(const std::string& oldfullpath, std::move(callback)); } -void FileUtils::getFileSize(const std::string& filepath, std::function callback) const +void FileUtils::getFileSize(std::string_view filepath, std::function callback) const { auto fullPath = fullPathForFilename(filepath); performOperationOffthread([fullPath]() { return FileUtils::getInstance()->getFileSize(fullPath); }, std::move(callback)); } -void FileUtils::listFilesAsync(const std::string& dirPath, std::function)> callback) const +void FileUtils::listFilesAsync(std::string_view dirPath, std::function)> callback) const { auto fullPath = fullPathForDirectory(dirPath); performOperationOffthread([fullPath]() { return FileUtils::getInstance()->listFiles(fullPath); }, std::move(callback)); } -void FileUtils::listFilesRecursivelyAsync(const std::string& dirPath, +void FileUtils::listFilesRecursivelyAsync(std::string_view dirPath, std::function)> callback) const { auto fullPath = fullPathForDirectory(dirPath); @@ -1123,7 +1123,7 @@ void FileUtils::listFilesRecursivelyAsync(const std::string& dirPath, std::move(callback)); } -std::unique_ptr FileUtils::openFileStream(const std::string& filePath, FileStream::Mode mode) +std::unique_ptr FileUtils::openFileStream(std::string_view filePath, FileStream::Mode mode) { PosixFileStream fs; @@ -1137,55 +1137,55 @@ std::unique_ptr FileUtils::openFileStream(const std::string& filePat #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) // windows os implement should override in platform specific FileUtiles class -bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const +bool FileUtils::isDirectoryExistInternal(std::string_view dirPath) const { CCASSERT(false, "FileUtils not support isDirectoryExistInternal"); return false; } -bool FileUtils::createDirectory(const std::string& path) const +bool FileUtils::createDirectory(std::string_view path) const { CCASSERT(false, "FileUtils not support createDirectory"); return false; } -bool FileUtils::removeDirectory(const std::string& path) const +bool FileUtils::removeDirectory(std::string_view path) const { CCASSERT(false, "FileUtils not support removeDirectory"); return false; } -bool FileUtils::removeFile(const std::string& path) const +bool FileUtils::removeFile(std::string_view path) const { CCASSERT(false, "FileUtils not support removeFile"); return false; } -bool FileUtils::renameFile(const std::string& oldfullpath, const std::string& newfullpath) const +bool FileUtils::renameFile(std::string_view oldfullpath, std::string_view newfullpath) const { CCASSERT(false, "FileUtils not support renameFile"); return false; } -bool FileUtils::renameFile(const std::string& path, const std::string& oldname, const std::string& name) const +bool FileUtils::renameFile(std::string_view path, std::string_view oldname, std::string_view name) const { CCASSERT(false, "FileUtils not support renameFile"); return false; } -int64_t FileUtils::getFileSize(const std::string& filepath) const +int64_t FileUtils::getFileSize(std::string_view filepath) const { CCASSERT(false, "getFileSize should be override by platform FileUtils"); return 0; } -std::vector FileUtils::listFiles(const std::string& dirPath) const +std::vector FileUtils::listFiles(std::string_view dirPath) const { CCASSERT(false, "FileUtils not support listFiles"); return std::vector(); } -void FileUtils::listFilesRecursively(const std::string& dirPath, std::vector* files) const +void FileUtils::listFilesRecursively(std::string_view dirPath, std::vector* files) const { CCASSERT(false, "FileUtils not support listFilesRecursively"); return; @@ -1203,7 +1203,7 @@ void FileUtils::listFilesRecursively(const std::string& dirPath, std::vector # endif -bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const +bool FileUtils::isDirectoryExistInternal(std::string_view dirPath) const { struct stat st; if (stat(dirPath.c_str(), &st) == 0) @@ -1213,7 +1213,7 @@ bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const return false; } -bool FileUtils::createDirectory(const std::string& path) const +bool FileUtils::createDirectory(std::string_view path) const { CCASSERT(!path.empty(), "Invalid path"); @@ -1291,7 +1291,7 @@ int unlink_cb(const char* fpath, const struct stat* sb, int typeflag, struct FTW # endif } // namespace -bool FileUtils::removeDirectory(const std::string& path) const +bool FileUtils::removeDirectory(std::string_view path) const { # if !defined(CC_TARGET_OS_TVOS) @@ -1315,7 +1315,7 @@ bool FileUtils::removeDirectory(const std::string& path) const # endif // !defined(CC_TARGET_OS_TVOS) } -bool FileUtils::removeFile(const std::string& path) const +bool FileUtils::removeFile(std::string_view path) const { if (remove(path.c_str())) { @@ -1327,7 +1327,7 @@ bool FileUtils::removeFile(const std::string& path) const } } -bool FileUtils::renameFile(const std::string& oldfullpath, const std::string& newfullpath) const +bool FileUtils::renameFile(std::string_view oldfullpath, std::string_view newfullpath) const { CCASSERT(!oldfullpath.empty(), "Invalid path"); CCASSERT(!newfullpath.empty(), "Invalid path"); @@ -1343,7 +1343,7 @@ bool FileUtils::renameFile(const std::string& oldfullpath, const std::string& ne return true; } -bool FileUtils::renameFile(const std::string& path, const std::string& oldname, const std::string& name) const +bool FileUtils::renameFile(std::string_view path, std::string_view oldname, std::string_view name) const { CCASSERT(!path.empty(), "Invalid path"); std::string oldPath = path + oldname; @@ -1352,7 +1352,7 @@ bool FileUtils::renameFile(const std::string& path, const std::string& oldname, return this->renameFile(oldPath, newPath); } -int64_t FileUtils::getFileSize(const std::string& filepath) const +int64_t FileUtils::getFileSize(std::string_view filepath) const { CCASSERT(!filepath.empty(), "Invalid path"); @@ -1380,7 +1380,7 @@ int64_t FileUtils::getFileSize(const std::string& filepath) const } } -std::vector FileUtils::listFiles(const std::string& dirPath) const +std::vector FileUtils::listFiles(std::string_view dirPath) const { std::vector files; std::string fullpath = fullPathForDirectory(dirPath); @@ -1421,7 +1421,7 @@ std::vector FileUtils::listFiles(const std::string& dirPath) const return files; } -void FileUtils::listFilesRecursively(const std::string& dirPath, std::vector* files) const +void FileUtils::listFilesRecursively(std::string_view dirPath, std::vector* files) const { std::string fullpath = fullPathForDirectory(dirPath); if (isDirectoryExist(fullpath)) @@ -1483,7 +1483,7 @@ bool FileUtils::isPopupNotify() const return s_popupNotify; } -std::string FileUtils::getFileExtension(const std::string& filePath) const +std::string FileUtils::getFileExtension(std::string_view filePath) const { std::string fileExtension; size_t pos = filePath.find_last_of('.'); @@ -1497,16 +1497,16 @@ std::string FileUtils::getFileExtension(const std::string& filePath) const return fileExtension; } -std::string FileUtils::getFileShortName(const std::string& filePath) +std::string FileUtils::getFileShortName(std::string_view filePath) { - std::string fileExtension; + // std::string fileExtension; size_t pos = filePath.find_last_of("/\\"); if (pos != std::string::npos) { - return filePath.substr(pos + 1); + return std::string{filePath.substr(pos + 1)}; } - return filePath; + return std::string{filePath}; } void FileUtils::valueMapCompact(ValueMap& /*valueMap*/) const {} diff --git a/cocos/platform/CCFileUtils.h b/cocos/platform/CCFileUtils.h index 3376b9035d..93810f5423 100644 --- a/cocos/platform/CCFileUtils.h +++ b/cocos/platform/CCFileUtils.h @@ -157,7 +157,7 @@ public: /** * Gets string from a file. */ - virtual std::string getStringFromFile(const std::string& filename) const; + virtual std::string getStringFromFile(std::string_view filename) const; /** * Gets string from a file, async off the main cocos thread @@ -166,13 +166,13 @@ public: * @param callback Function that will be called when file is read. Will be called * on the main cocos thread. */ - virtual void getStringFromFile(const std::string& path, std::function callback) const; + virtual void getStringFromFile(std::string_view path, std::function callback) const; /** * Creates binary data from a file. * @return A data object. */ - virtual Data getDataFromFile(const std::string& filename) const; + virtual Data getDataFromFile(std::string_view filename) const; /** * Gets a binary data object from a file, async off the main cocos thread. @@ -181,7 +181,7 @@ public: * @param callback Function that will be called when file is read. Will be called * on the main cocos thread. */ - virtual void getDataFromFile(const std::string& filename, std::function callback) const; + virtual void getDataFromFile(std::string_view filename, std::function callback) const; enum class Status { @@ -255,12 +255,12 @@ public: template >::value>::type> - Status getContents(const std::string& filename, T* buffer) const + Status getContents(std::string_view filename, T* buffer) const { ResizableBufferAdapter buf(buffer); return getContents(filename, &buf); } - virtual Status getContents(const std::string& filename, ResizableBuffer* buffer) const; + virtual Status getContents(std::string_view filename, ResizableBuffer* buffer) const; /** Returns the fullpath for a given filename. @@ -310,7 +310,7 @@ public: @since v2.1 */ - virtual std::string fullPathForFilename(const std::string& filename) const; + virtual std::string fullPathForFilename(std::string_view filename) const; /** * Loads the filenameLookup dictionary from the contents of a filename. @@ -345,7 +345,7 @@ public: * @js loadFilenameLookup * @lua loadFilenameLookup */ - virtual void loadFilenameLookupDictionaryFromFile(const std::string& filename); + virtual void loadFilenameLookupDictionaryFromFile(std::string_view filename); /** * Sets the filenameLookup dictionary. @@ -365,7 +365,7 @@ public: * dictionary. ) * */ - virtual std::string fullPathFromRelativeFile(const std::string& filename, const std::string& relativeFile) const; + virtual std::string fullPathFromRelativeFile(std::string_view filename, std::string_view relativeFile) const; /** * Sets the array that contains the search order of the resources. @@ -384,7 +384,7 @@ public: * @see setSearchResolutionsOrder(), fullPathForFilename(). * @since v2.1 */ - virtual void addSearchResolutionsOrder(const std::string& order, const bool front = false); + virtual void addSearchResolutionsOrder(std::string_view order, const bool front = false); /** * Gets the array that contains the search order of the resources. @@ -424,14 +424,14 @@ public: /** * Set default resource root path. */ - void setDefaultResourceRootPath(const std::string& path); + void setDefaultResourceRootPath(std::string_view path); /** * Add search path. * * @since v2.1 */ - void addSearchPath(const std::string& path, const bool front = false); + void addSearchPath(std::string_view path, const bool front = false); /** * Gets the array of search paths. @@ -468,7 +468,7 @@ public: /** * Sets writable path. */ - virtual void setWritablePath(const std::string& writablePath); + virtual void setWritablePath(std::string_view writablePath); /** * Sets whether to pop-up a message box when failed to load an image. @@ -486,7 +486,7 @@ public: * @return ValueMap of the file contents. * @note This method is used internally. */ - virtual ValueMap getValueMapFromFile(const std::string& filename) const; + virtual ValueMap getValueMapFromFile(std::string_view filename) const; /** Converts the contents of a file to a ValueMap. * This method is used internally. @@ -500,7 +500,7 @@ public: *@param fullPath The full path to the file you want to save a string *@return bool */ - virtual bool writeToFile(const ValueMap& dict, const std::string& fullPath) const; + virtual bool writeToFile(const ValueMap& dict, std::string_view fullPath) const; /** * write a string into a file @@ -509,7 +509,7 @@ public: * @param fullPath The full path to the file you want to save a string * @return bool True if write success */ - virtual bool writeStringToFile(const std::string& dataStr, const std::string& fullPath) const; + virtual bool writeStringToFile(std::string_view dataStr, std::string_view fullPath) const; /** * Write a string to a file, done async off the main cocos thread @@ -525,7 +525,7 @@ public: * signifying if the write was successful. */ virtual void writeStringToFile(std::string dataStr, - const std::string& fullPath, + std::string_view fullPath, std::function callback) const; /** @@ -535,12 +535,12 @@ public: *@param fullPath The full path to the file you want to save a string *@return bool */ - virtual bool writeDataToFile(const Data& data, const std::string& fullPath) const; + virtual bool writeDataToFile(const Data& data, std::string_view fullPath) const; /** * save data to file */ - static bool writeBinaryToFile(const void* data, size_t dataSize, const std::string& fullPath); + static bool writeBinaryToFile(const void* data, size_t dataSize, std::string_view fullPath); /** * Write Data into a file, done async off the main cocos thread. @@ -556,7 +556,7 @@ public: * function will be executed on the main cocos thread. It will have on boolean argument * signifying if the write was successful. */ - virtual void writeDataToFile(Data data, const std::string& fullPath, std::function callback) const; + virtual void writeDataToFile(Data data, std::string_view fullPath, std::function callback) const; /** * write ValueMap into a plist file @@ -565,7 +565,7 @@ public: *@param fullPath The full path to the file you want to save a string *@return bool */ - virtual bool writeValueMapToFile(const ValueMap& dict, const std::string& fullPath) const; + virtual bool writeValueMapToFile(const ValueMap& dict, std::string_view fullPath) const; /** * Write a ValueMap into a file, done async off the main cocos thread. @@ -582,7 +582,7 @@ public: * signifying if the write was successful. */ virtual void writeValueMapToFile(ValueMap dict, - const std::string& fullPath, + std::string_view fullPath, std::function callback) const; /** @@ -592,7 +592,7 @@ public: *@param fullPath The full path to the file you want to save a string *@return bool */ - virtual bool writeValueVectorToFile(const ValueVector& vecData, const std::string& fullPath) const; + virtual bool writeValueVectorToFile(const ValueVector& vecData, std::string_view fullPath) const; /** * Write a ValueVector into a file, done async off the main cocos thread. @@ -609,12 +609,12 @@ public: * signifying if the write was successful. */ virtual void writeValueVectorToFile(ValueVector vecData, - const std::string& fullPath, + std::string_view fullPath, std::function callback) const; // Converts the contents of a file to a ValueVector. // This method is used internally. - virtual ValueVector getValueVectorFromFile(const std::string& filename) const; + virtual ValueVector getValueVectorFromFile(std::string_view filename) const; /** * Checks whether a file exists. @@ -623,7 +623,7 @@ public: * @param filename The path of the file, it could be a relative or absolute path. * @return True if the file exists, false if not. */ - virtual bool isFileExist(const std::string& filename) const; + virtual bool isFileExist(std::string_view filename) const; /** * Checks if a file exists, done async off the main cocos thread. @@ -635,7 +635,7 @@ public: * @param callback The function that will be called when the operation is complete. Will have one boolean * argument, true if the file exists, false otherwise. */ - virtual void isFileExist(const std::string& filename, std::function callback) const; + virtual void isFileExist(std::string_view filename, std::function callback) const; /** * Gets filename extension is a suffix (separated from the base filename by a dot) in lower case. @@ -643,14 +643,14 @@ public: * @param filePath The path of the file, it could be a relative or absolute path. * @return suffix for filename in lower case or empty if a dot not found. */ - virtual std::string getFileExtension(const std::string& filePath) const; + virtual std::string getFileExtension(std::string_view filePath) const; /** * Gets filename shotName * @param filePath The path of the file, it could be a relative or absolute path. * @return fileName.Extension without path */ - static std::string getFileShortName(const std::string& filePath); + static std::string getFileShortName(std::string_view filePath); /** * Checks whether the path is an absolute path. @@ -661,9 +661,9 @@ public: * @param path The path that needs to be checked. * @return True if it's an absolute path, false if not. */ - virtual bool isAbsolutePath(const std::string& path) const; + virtual bool isAbsolutePath(std::string_view path) const; - static bool isAbsolutePathInternal(const std::string& path); + static bool isAbsolutePathInternal(std::string_view path); /** * Checks whether the path is a directory. @@ -671,7 +671,7 @@ public: * @param dirPath The path of the directory, it could be a relative or an absolute path. * @return True if the directory exists, false if not. */ - virtual bool isDirectoryExist(const std::string& dirPath) const; + virtual bool isDirectoryExist(std::string_view dirPath) const; /** * Checks whether the absoulate path is a directory, async off of the main cocos thread. @@ -680,7 +680,7 @@ public: * @param callback that will accept a boolean, true if the file exists, false otherwise. * Callback will happen on the main cocos thread. */ - virtual void isDirectoryExist(const std::string& fullPath, std::function callback) const; + virtual void isDirectoryExist(std::string_view fullPath, std::function callback) const; /** * Creates a directory. @@ -688,7 +688,7 @@ public: * @param dirPath The path of the directory, it must be an absolute path. * @return True if the directory have been created successfully, false if not. */ - virtual bool createDirectory(const std::string& dirPath) const; + virtual bool createDirectory(std::string_view dirPath) const; /** * Create a directory, async off the main cocos thread. @@ -697,7 +697,7 @@ public: * @param callback The function that will be called when the operation is complete. Will have one boolean * argument, true if the directory was successfully, false otherwise. */ - virtual void createDirectory(const std::string& dirPath, std::function callback) const; + virtual void createDirectory(std::string_view dirPath, std::function callback) const; /** * Removes a directory. @@ -705,7 +705,7 @@ public: * @param dirPath The full path of the directory, it must be an absolute path. * @return True if the directory have been removed successfully, false if not. */ - virtual bool removeDirectory(const std::string& dirPath) const; + virtual bool removeDirectory(std::string_view dirPath) const; /** * Removes a directory, async off the main cocos thread. @@ -714,7 +714,7 @@ public: * @param callback The function that will be called when the operation is complete. Will have one boolean * argument, true if the directory was successfully removed, false otherwise. */ - virtual void removeDirectory(const std::string& dirPath, std::function callback) const; + virtual void removeDirectory(std::string_view dirPath, std::function callback) const; /** * Removes a file. @@ -722,7 +722,7 @@ public: * @param filepath The full path of the file, it must be an absolute path. * @return True if the file have been removed successfully, false if not. */ - virtual bool removeFile(const std::string& filepath) const; + virtual bool removeFile(std::string_view filepath) const; /** * Removes a file, async off the main cocos thread. @@ -731,7 +731,7 @@ public: * @param callback The function that will be called when the operation is complete. Will have one boolean * argument, true if the file was successfully removed, false otherwise. */ - virtual void removeFile(const std::string& filepath, std::function callback) const; + virtual void removeFile(std::string_view filepath, std::function callback) const; /** * Renames a file under the given directory. @@ -741,7 +741,7 @@ public: * @param name The new name of the file. * @return True if the file have been renamed successfully, false if not. */ - virtual bool renameFile(const std::string& path, const std::string& oldname, const std::string& name) const; + virtual bool renameFile(std::string_view path, std::string_view oldname, std::string_view name) const; /** * Renames a file under the given directory, async off the main cocos thread. @@ -752,9 +752,9 @@ public: * @param callback The function that will be called when the operation is complete. Will have one boolean * argument, true if the file was successfully renamed, false otherwise. */ - virtual void renameFile(const std::string& path, - const std::string& oldname, - const std::string& name, + virtual void renameFile(std::string_view path, + std::string_view oldname, + std::string_view name, std::function callback) const; /** @@ -764,7 +764,7 @@ public: * @param newfullpath The new fullpath of the file. Includes path and name. * @return True if the file have been renamed successfully, false if not. */ - virtual bool renameFile(const std::string& oldfullpath, const std::string& newfullpath) const; + virtual bool renameFile(std::string_view oldfullpath, std::string_view newfullpath) const; /** * Renames a file under the given directory, async off the main cocos thread. @@ -774,8 +774,8 @@ public: * @param callback The function that will be called when the operation is complete. Will have one boolean * argument, true if the file was successfully renamed, false otherwise. */ - virtual void renameFile(const std::string& oldfullpath, - const std::string& newfullpath, + virtual void renameFile(std::string_view oldfullpath, + std::string_view newfullpath, std::function callback) const; /** @@ -785,7 +785,7 @@ public: * @param filepath The path of the file, it could be a relative or absolute path. * @return The file size. */ - virtual int64_t getFileSize(const std::string& filepath) const; + virtual int64_t getFileSize(std::string_view filepath) const; /** * Retrieve the file size, async off the main cocos thread. @@ -795,7 +795,7 @@ public: * @param callback The function that will be called when the operation is complete. Will have one long * argument, the file size. */ - virtual void getFileSize(const std::string& filepath, std::function callback) const; + virtual void getFileSize(std::string_view filepath, std::function callback) const; /** * List all files in a directory. @@ -803,7 +803,7 @@ public: * @param dirPath The path of the directory, it could be a relative or an absolute path. * @return File paths in a string vector */ - virtual std::vector listFiles(const std::string& dirPath) const; + virtual std::vector listFiles(std::string_view dirPath) const; /** * List all files in a directory async, off of the main cocos thread. @@ -814,7 +814,7 @@ public: * @js NA * @lua NA */ - virtual void listFilesAsync(const std::string& dirPath, + virtual void listFilesAsync(std::string_view dirPath, std::function)> callback) const; /** @@ -823,7 +823,7 @@ public: * @param dirPath The path of the directory, it could be a relative or an absolute path. * @return File paths in a string vector */ - virtual void listFilesRecursively(const std::string& dirPath, std::vector* files) const; + virtual void listFilesRecursively(std::string_view dirPath, std::vector* files) const; /** * List all files recursively in a directory, async off the main cocos thread. @@ -834,11 +834,11 @@ public: * @js NA * @lua NA */ - virtual void listFilesRecursivelyAsync(const std::string& dirPath, + virtual void listFilesRecursivelyAsync(std::string_view dirPath, std::function)> callback) const; /** Returns the full path cache. */ - const std::unordered_map getFullPathCache() const { return _fullPathCache; } + const hlookup::string_map getFullPathCache() const { return _fullPathCache; } /** * Gets the new filename from the filename lookup dictionary. @@ -847,21 +847,21 @@ public: * @return The new filename after searching in the filename lookup dictionary. * If the original filename wasn't in the dictionary, it will return the original filename. */ - virtual std::string getNewFilename(const std::string& filename) const; + virtual std::string getNewFilename(std::string_view filename) const; /** * Checks whether a file exists without considering search paths and resolution orders. * @param filename The file (with absolute path) to look up for * @return Returns true if the file found at the given absolute path, otherwise returns false */ - virtual bool isFileExistInternal(const std::string& filename) const = 0; + virtual bool isFileExistInternal(std::string_view filename) const = 0; /** * Checks whether a directory exists without considering search paths and resolution orders. * @param dirPath The directory (with absolute path) to look up for * @return Returns true if the directory found at the given absolute path, otherwise returns false */ - virtual bool isDirectoryExistInternal(const std::string& dirPath) const; + virtual bool isDirectoryExistInternal(std::string_view dirPath) const; /** * Open a FileStream based on the implementation provided in openFileStream or its overrides @@ -869,7 +869,7 @@ public: * @param mode The mode to open the file in, being READ | WRITE | APPEND * @return Returns a pointer to the file stream */ - virtual std::unique_ptr openFileStream(const std::string& filePath, FileStream::Mode mode); + virtual std::unique_ptr openFileStream(std::string_view filePath, FileStream::Mode mode); protected: /** @@ -897,13 +897,13 @@ protected: * @param searchPath The search path. * @return The full path of the file. It will return an empty string if the full path of the file doesn't exist. */ - virtual std::string getPathForFilename(const std::string& filename, - const std::string& resolutionDirectory, - const std::string& searchPath) const; + virtual std::string getPathForFilename(std::string_view filename, + std::string_view resolutionDirectory, + std::string_view searchPath) const; - virtual std::string getPathForDirectory(const std::string& dir, - const std::string& resolutionDiretory, - const std::string& searchPath) const; + virtual std::string getPathForDirectory(std::string_view dir, + std::string_view resolutionDiretory, + std::string_view searchPath) const; /** * Gets full path for the directory and the filename. @@ -915,14 +915,14 @@ protected: * @param filename The name of the file. * @return The full path of the file, if the file can't be found, it will return an empty string. */ - virtual std::string getFullPathForFilenameWithinDirectory(const std::string& directory, - const std::string& filename) const; + virtual std::string getFullPathForFilenameWithinDirectory(std::string_view directory, + std::string_view filename) const; /** * Returns the fullpath for a given dirname. * @since 3.17.1 */ - virtual std::string fullPathForDirectory(const std::string& dirname) const; + virtual std::string fullPathForDirectory(std::string_view dirname) const; /** * mutex used to protect fields. @@ -968,13 +968,13 @@ protected: * The full path cache for normal files. When a file is found, it will be added into this cache. * This variable is used for improving the performance of file search. */ - mutable std::unordered_map _fullPathCache; + mutable hlookup::string_map _fullPathCache; /** * The full path cache for directories. When a diretory is found, it will be added into this cache. * This variable is used for improving the performance of file search. */ - mutable std::unordered_map _fullPathCacheDir; + mutable hlookup::string_map _fullPathCacheDir; /** * Writable path. diff --git a/cocos/platform/CCGLView.cpp b/cocos/platform/CCGLView.cpp index 5c8494362a..7ee97868af 100644 --- a/cocos/platform/CCGLView.cpp +++ b/cocos/platform/CCGLView.cpp @@ -279,12 +279,12 @@ Rect GLView::getScissorRect() const return Rect(x, y, w, h); } -void GLView::setViewName(const std::string& viewname) +void GLView::setViewName(std::string_view viewname) { _viewName = viewname; } -const std::string& GLView::getViewName() const +std::string_view GLView::getViewName() const { return _viewName; } diff --git a/cocos/platform/CCGLView.h b/cocos/platform/CCGLView.h index 6cd6c1568b..f5bbc43547 100644 --- a/cocos/platform/CCGLView.h +++ b/cocos/platform/CCGLView.h @@ -308,13 +308,13 @@ public: * * @param viewname A string will be set to the view as name. */ - virtual void setViewName(const std::string& viewname); + virtual void setViewName(std::string_view viewname); /** Get the view name. * * @return The view name. */ - const std::string& getViewName() const; + std::string_view getViewName() const; /** Touch events are handled by default; if you want to customize your handlers, please override this function. * @@ -367,14 +367,14 @@ public: * * @param filename A path to image file, e.g., "icons/cusom.png". */ - virtual void setIcon(const std::string& filename) const {}; + virtual void setIcon(std::string_view filename) const {}; /** Set window icon (implemented for windows and linux). * Best icon (based on size) will be auto selected. * * @param filelist The array contains icons. */ - virtual void setIcon(const std::vector& filelist) const {}; + virtual void setIcon(const std::vector& filelist) const {}; /** Set default window icon (implemented for windows and linux). * On windows it will use icon from .exe file (if included). diff --git a/cocos/platform/CCImage.cpp b/cocos/platform/CCImage.cpp index 6f2340a153..7296355cae 100644 --- a/cocos/platform/CCImage.cpp +++ b/cocos/platform/CCImage.cpp @@ -601,7 +601,7 @@ Image::~Image() } } -bool Image::initWithImageFile(const std::string& path) +bool Image::initWithImageFile(std::string_view path) { bool ret = false; _filePath = FileUtils::getInstance()->fullPathForFilename(path); @@ -618,7 +618,7 @@ bool Image::initWithImageFile(const std::string& path) return ret; } -bool Image::initWithImageFileThreadSafe(const std::string& fullpath) +bool Image::initWithImageFileThreadSafe(std::string_view fullpath) { bool ret = false; _filePath = fullpath; @@ -2193,7 +2193,7 @@ void Image::forwardPixels(uint8_t* data, ssize_t dataLen, int offset, bool ownDa } #if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) -bool Image::saveToFile(const std::string& filename, bool isToRGB) +bool Image::saveToFile(std::string_view filename, bool isToRGB) { // only support for backend::PixelFormat::RGB8 or backend::PixelFormat::RGBA8 uncompressed data if (isCompressed() || (_pixelFormat != backend::PixelFormat::RGB8 && _pixelFormat != backend::PixelFormat::RGBA8)) @@ -2216,13 +2216,13 @@ bool Image::saveToFile(const std::string& filename, bool isToRGB) } else { - CCLOG("cocos2d: Image: saveToFile no support file extension(only .png or .jpg) for file: %s", filename.c_str()); + CCLOG("cocos2d: Image: saveToFile no support file extension(only .png or .jpg) for file: %s", filename.data()); return false; } } #endif -bool Image::saveImageToPNG(const std::string& filePath, bool isToRGB) +bool Image::saveImageToPNG(std::string_view filePath, bool isToRGB) { #if CC_USE_PNG bool ret = false; @@ -2365,7 +2365,7 @@ bool Image::saveImageToPNG(const std::string& filePath, bool isToRGB) #endif // CC_USE_PNG } -bool Image::saveImageToJPG(const std::string& filePath) +bool Image::saveImageToJPG(std::string_view filePath) { #if CC_USE_JPEG bool ret = false; diff --git a/cocos/platform/CCImage.h b/cocos/platform/CCImage.h index 3466dbe617..ae1adc4ff3 100644 --- a/cocos/platform/CCImage.h +++ b/cocos/platform/CCImage.h @@ -148,7 +148,7 @@ public: @param path the absolute file path. @return true if loaded correctly. */ - bool initWithImageFile(const std::string& path); + bool initWithImageFile(std::string_view path); /** @brief Load image from stream buffer. @@ -191,7 +191,7 @@ public: @param filePath the file's absolute path, including file suffix. @param isToRGB whether the image is saved as RGB format. */ - bool saveToFile(const std::string& filename, bool isToRGB = true); + bool saveToFile(std::string_view filename, bool isToRGB = true); void premultiplyAlpha(); void reversePremultipliedAlpha(); @@ -218,8 +218,8 @@ protected: // fast forward pixels to GPU if ownData void forwardPixels(uint8_t* data, ssize_t dataLen, int offset, bool ownData); - bool saveImageToPNG(const std::string& filePath, bool isToRGB = true); - bool saveImageToJPG(const std::string& filePath); + bool saveImageToPNG(std::string_view filePath, bool isToRGB = true); + bool saveImageToJPG(std::string_view filePath); protected: /** @@ -259,7 +259,7 @@ protected: @param imageType the type of image, currently only supporting two types. @return true if loaded correctly. */ - bool initWithImageFileThreadSafe(const std::string& fullpath); + bool initWithImageFileThreadSafe(std::string_view fullpath); Format detectFormat(const uint8_t* data, ssize_t dataLen); bool isPng(const uint8_t* data, ssize_t dataLen); diff --git a/cocos/platform/CCPlatformMacros.h b/cocos/platform/CCPlatformMacros.h index 4f2a33e3e0..b8a6516c14 100644 --- a/cocos/platform/CCPlatformMacros.h +++ b/cocos/platform/CCPlatformMacros.h @@ -32,6 +32,7 @@ Copyright (c) 2021 Bytedance Inc. * Define some platform specific macros. */ #include "base/ccConfig.h" +#include "base/hlookup.h" #include "platform/CCPlatformConfig.h" #include "platform/CCPlatformDefine.h" diff --git a/cocos/platform/CCPosixFileStream.cpp b/cocos/platform/CCPosixFileStream.cpp index 6606cc594c..cdf1f76bee 100644 --- a/cocos/platform/CCPosixFileStream.cpp +++ b/cocos/platform/CCPosixFileStream.cpp @@ -19,7 +19,7 @@ struct PXIoF long long (*size)(PXFileHandle& handle); }; -static int pfs_posix_open(const std::string& path, FileStream::Mode mode, PXFileHandle& handle) +static int pfs_posix_open(std::string_view path, FileStream::Mode mode, PXFileHandle& handle) { switch (mode) { @@ -127,7 +127,7 @@ PosixFileStream::~PosixFileStream() internalClose(); } -bool PosixFileStream::open(const std::string& path, FileStream::Mode mode) +bool PosixFileStream::open(std::string_view path, FileStream::Mode mode) { bool ok = false; #if CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID diff --git a/cocos/platform/CCPosixFileStream.h b/cocos/platform/CCPosixFileStream.h index 183f6d5dea..46504a15a4 100644 --- a/cocos/platform/CCPosixFileStream.h +++ b/cocos/platform/CCPosixFileStream.h @@ -114,7 +114,7 @@ public: APPEND, }; - bool open(const std::string& path, FileStream::Mode mode) override; + bool open(std::string_view path, FileStream::Mode mode) override; int close() override; int seek(int64_t offset, int origin) override; diff --git a/cocos/platform/CCSAXParser.cpp b/cocos/platform/CCSAXParser.cpp index 2629c6a856..7af489f71f 100644 --- a/cocos/platform/CCSAXParser.cpp +++ b/cocos/platform/CCSAXParser.cpp @@ -108,7 +108,7 @@ bool SAXParser::parse(const char* xmlData, size_t dataLength) return false; } -bool SAXParser::parse(const std::string& filename) +bool SAXParser::parse(std::string_view filename) { bool ret = false; Data data = FileUtils::getInstance()->getDataFromFile(filename); diff --git a/cocos/platform/CCSAXParser.h b/cocos/platform/CCSAXParser.h index 7b948fc071..ecb4c7bbe5 100644 --- a/cocos/platform/CCSAXParser.h +++ b/cocos/platform/CCSAXParser.h @@ -90,7 +90,7 @@ public: * @js NA * @lua NA */ - bool parse(const std::string& filename); + bool parse(std::string_view filename); /** * New API for performance. diff --git a/cocos/platform/android/CCApplication-android.cpp b/cocos/platform/android/CCApplication-android.cpp index 08809fb6d7..7c1f36e811 100644 --- a/cocos/platform/android/CCApplication-android.cpp +++ b/cocos/platform/android/CCApplication-android.cpp @@ -119,7 +119,7 @@ std::string Application::getVersion() return JniHelper::callStaticStringMethod(helperClassName, "getVersion"); } -bool Application::openURL(const std::string& url) +bool Application::openURL(std::string_view url) { return JniHelper::callStaticBooleanMethod(helperClassName, "openURL", url); } diff --git a/cocos/platform/android/CCApplication-android.h b/cocos/platform/android/CCApplication-android.h index 42cf2dc287..71f0e2146e 100644 --- a/cocos/platform/android/CCApplication-android.h +++ b/cocos/platform/android/CCApplication-android.h @@ -90,7 +90,7 @@ public: @param String with url to open. @return true if the resource located by the URL was successfully opened; otherwise false. */ - virtual bool openURL(const std::string& url) override; + virtual bool openURL(std::string_view url) override; /** @brief This function will be called when the application screen size is changed. diff --git a/cocos/platform/android/CCFileUtils-android.cpp b/cocos/platform/android/CCFileUtils-android.cpp index dabb0a4148..7b4647f4c6 100644 --- a/cocos/platform/android/CCFileUtils-android.cpp +++ b/cocos/platform/android/CCFileUtils-android.cpp @@ -103,7 +103,7 @@ bool FileUtilsAndroid::init() return FileUtils::init(); } -std::string FileUtilsAndroid::getNewFilename(const std::string& filename) const +std::string FileUtilsAndroid::getNewFilename(std::string_view filename) const { std::string newFileName = FileUtils::getNewFilename(filename); // ../xxx do not fix this path @@ -156,7 +156,7 @@ std::string FileUtilsAndroid::getNewFilename(const std::string& filename) const return newFileName; } -bool FileUtilsAndroid::isFileExistInternal(const std::string& strFilePath) const +bool FileUtilsAndroid::isFileExistInternal(std::string_view strFilePath) const { DECLARE_GUARD; @@ -204,7 +204,7 @@ bool FileUtilsAndroid::isFileExistInternal(const std::string& strFilePath) const return bFound; } -bool FileUtilsAndroid::isDirectoryExistInternal(const std::string& dirPath) const +bool FileUtilsAndroid::isDirectoryExistInternal(std::string_view dirPath) const { if (dirPath.empty()) { @@ -254,7 +254,7 @@ bool FileUtilsAndroid::isDirectoryExistInternal(const std::string& dirPath) cons return false; } -bool FileUtilsAndroid::isAbsolutePath(const std::string& strPath) const +bool FileUtilsAndroid::isAbsolutePath(std::string_view strPath) const { DECLARE_GUARD; // On Android, there are two situations for full path. @@ -264,7 +264,7 @@ bool FileUtilsAndroid::isAbsolutePath(const std::string& strPath) const return (strPath[0] == '/' || strPath.find(_defaultResRootPath) == 0); } -int64_t FileUtilsAndroid::getFileSize(const std::string& filepath) const +int64_t FileUtilsAndroid::getFileSize(std::string_view filepath) const { DECLARE_GUARD; int64_t size = FileUtils::getFileSize(filepath); @@ -292,7 +292,7 @@ int64_t FileUtilsAndroid::getFileSize(const std::string& filepath) const return size; } -std::vector FileUtilsAndroid::listFiles(const std::string& dirPath) const +std::vector FileUtilsAndroid::listFiles(std::string_view dirPath) const { if (!dirPath.empty() && dirPath[0] == '/') @@ -347,7 +347,7 @@ std::vector FileUtilsAndroid::listFiles(const std::string& dirPath) return fileList; } -FileUtils::Status FileUtilsAndroid::getContents(const std::string& filename, ResizableBuffer* buffer) const +FileUtils::Status FileUtilsAndroid::getContents(std::string_view filename, ResizableBuffer* buffer) const { static const std::string apkprefix("assets/"); if (filename.empty()) diff --git a/cocos/platform/android/CCFileUtils-android.h b/cocos/platform/android/CCFileUtils-android.h index 44ef3864fb..fc3c6c8577 100644 --- a/cocos/platform/android/CCFileUtils-android.h +++ b/cocos/platform/android/CCFileUtils-android.h @@ -64,20 +64,20 @@ public: /* override functions */ bool init() override; - virtual std::string getNewFilename(const std::string& filename) const override; + virtual std::string getNewFilename(std::string_view filename) const override; - virtual FileUtils::Status getContents(const std::string& filename, ResizableBuffer* buffer) const override; + virtual FileUtils::Status getContents(std::string_view filename, ResizableBuffer* buffer) const override; virtual std::string getWritablePath() const override; std::string getNativeWritableAbsolutePath() const override; - virtual bool isAbsolutePath(const std::string& strPath) const override; + virtual bool isAbsolutePath(std::string_view strPath) const override; - virtual int64_t getFileSize(const std::string& filepath) const override; - virtual std::vector listFiles(const std::string& dirPath) const override; + virtual int64_t getFileSize(std::string_view filepath) const override; + virtual std::vector listFiles(std::string_view dirPath) const override; private: - virtual bool isFileExistInternal(const std::string& strFilePath) const override; - virtual bool isDirectoryExistInternal(const std::string& dirPath) const override; + virtual bool isFileExistInternal(std::string_view strFilePath) const override; + virtual bool isDirectoryExistInternal(std::string_view dirPath) const override; static AAssetManager* assetmanager; static ZipFile* obbfile; diff --git a/cocos/platform/android/CCGLViewImpl-android.cpp b/cocos/platform/android/CCGLViewImpl-android.cpp index b094714312..8a0ff6eb3c 100644 --- a/cocos/platform/android/CCGLViewImpl-android.cpp +++ b/cocos/platform/android/CCGLViewImpl-android.cpp @@ -50,7 +50,7 @@ void initExtensions() NS_CC_BEGIN -GLViewImpl* GLViewImpl::createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor) +GLViewImpl* GLViewImpl::createWithRect(std::string_view viewName, Rect rect, float frameZoomFactor) { auto ret = new GLViewImpl; if (ret && ret->initWithRect(viewName, rect, frameZoomFactor)) @@ -62,7 +62,7 @@ GLViewImpl* GLViewImpl::createWithRect(const std::string& viewName, Rect rect, f return nullptr; } -GLViewImpl* GLViewImpl::create(const std::string& viewName) +GLViewImpl* GLViewImpl::create(std::string_view viewName) { auto ret = new GLViewImpl; if (ret && ret->initWithFullScreen(viewName)) @@ -74,7 +74,7 @@ GLViewImpl* GLViewImpl::create(const std::string& viewName) return nullptr; } -GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName) +GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName) { auto ret = new GLViewImpl(); if (ret && ret->initWithFullScreen(viewName)) @@ -93,12 +93,12 @@ GLViewImpl::GLViewImpl() GLViewImpl::~GLViewImpl() {} -bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor) +bool GLViewImpl::initWithRect(std::string_view viewName, Rect rect, float frameZoomFactor) { return true; } -bool GLViewImpl::initWithFullScreen(const std::string& viewName) +bool GLViewImpl::initWithFullScreen(std::string_view viewName) { return true; } diff --git a/cocos/platform/android/CCGLViewImpl-android.h b/cocos/platform/android/CCGLViewImpl-android.h index 0f7e2d539b..fc42130964 100644 --- a/cocos/platform/android/CCGLViewImpl-android.h +++ b/cocos/platform/android/CCGLViewImpl-android.h @@ -35,9 +35,9 @@ class CC_DLL GLViewImpl : public GLView { public: // static function - static GLViewImpl* create(const std::string& viewname); - static GLViewImpl* createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor = 1.0f); - static GLViewImpl* createWithFullScreen(const std::string& viewName); + static GLViewImpl* create(std::string_view viewname); + static GLViewImpl* createWithRect(std::string_view viewName, Rect rect, float frameZoomFactor = 1.0f); + static GLViewImpl* createWithFullScreen(std::string_view viewName); bool isOpenGLReady() override; void end() override; @@ -49,8 +49,8 @@ protected: GLViewImpl(); virtual ~GLViewImpl(); - bool initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor); - bool initWithFullScreen(const std::string& viewName); + bool initWithRect(std::string_view viewName, Rect rect, float frameZoomFactor); + bool initWithFullScreen(std::string_view viewName); }; NS_CC_END diff --git a/cocos/platform/android/jni/JniHelper.cpp b/cocos/platform/android/jni/JniHelper.cpp index bddad033df..248f0c23cd 100644 --- a/cocos/platform/android/jni/JniHelper.cpp +++ b/cocos/platform/android/jni/JniHelper.cpp @@ -319,7 +319,7 @@ jstring JniHelper::convert(LocalRefMapType& localRefs, cocos2d::JniMethodInfo& t return ret; } -jstring JniHelper::convert(LocalRefMapType& localRefs, cocos2d::JniMethodInfo& t, const std::string& x) +jstring JniHelper::convert(LocalRefMapType& localRefs, cocos2d::JniMethodInfo& t, std::string_view x) { return convert(localRefs, t, x.c_str()); } @@ -338,7 +338,7 @@ void JniHelper::deleteLocalRefs(JNIEnv* env, LocalRefMapType& localRefs) localRefs[env].clear(); } -void JniHelper::reportError(const std::string& className, const std::string& methodName, const std::string& signature) +void JniHelper::reportError(std::string_view className, std::string_view methodName, std::string_view signature) { LOGE("Failed to find static java method. Class name: %s, method name: %s, signature: %s ", className.c_str(), methodName.c_str(), signature.c_str()); diff --git a/cocos/platform/android/jni/JniHelper.h b/cocos/platform/android/jni/JniHelper.h index 1367b95c5a..52dcc2b3e3 100644 --- a/cocos/platform/android/jni/JniHelper.h +++ b/cocos/platform/android/jni/JniHelper.h @@ -74,7 +74,7 @@ public: @if no such method will log error */ template - static void callStaticVoidMethod(const std::string& className, const std::string& methodName, Ts... xs) + static void callStaticVoidMethod(std::string_view className, std::string_view methodName, Ts... xs) { cocos2d::JniMethodInfo t; std::string signature = "(" + std::string(getJNISignature(xs...)) + ")V"; @@ -96,7 +96,7 @@ public: @return value from Java static boolean method if there are proper JniMethodInfo; otherwise false. */ template - static bool callStaticBooleanMethod(const std::string& className, const std::string& methodName, Ts... xs) + static bool callStaticBooleanMethod(std::string_view className, std::string_view methodName, Ts... xs) { jboolean jret = JNI_FALSE; cocos2d::JniMethodInfo t; @@ -120,7 +120,7 @@ public: @return value from Java static int method if there are proper JniMethodInfo; otherwise 0. */ template - static int callStaticIntMethod(const std::string& className, const std::string& methodName, Ts... xs) + static int callStaticIntMethod(std::string_view className, std::string_view methodName, Ts... xs) { jint ret = 0; cocos2d::JniMethodInfo t; @@ -144,7 +144,7 @@ public: @return value from Java static float method if there are proper JniMethodInfo; otherwise 0. */ template - static float callStaticFloatMethod(const std::string& className, const std::string& methodName, Ts... xs) + static float callStaticFloatMethod(std::string_view className, std::string_view methodName, Ts... xs) { jfloat ret = 0.0; cocos2d::JniMethodInfo t; @@ -168,7 +168,7 @@ public: @return address of JniMethodInfo if there are proper JniMethodInfo; otherwise nullptr. */ template - static float* callStaticFloatArrayMethod(const std::string& className, const std::string& methodName, Ts... xs) + static float* callStaticFloatArrayMethod(std::string_view className, std::string_view methodName, Ts... xs) { static float ret[32]; cocos2d::JniMethodInfo t; @@ -204,7 +204,7 @@ public: @return address of JniMethodInfo if there are proper JniMethodInfo; otherwise nullptr. */ template - static int* callStaticIntArrayMethod(const std::string& className, const std::string& methodName, Ts... xs) + static int* callStaticIntArrayMethod(std::string_view className, std::string_view methodName, Ts... xs) { static int ret[32]; cocos2d::JniMethodInfo t; @@ -240,7 +240,7 @@ public: @return JniMethodInfo of Vec3 type if there are proper JniMethodInfo; otherwise Vec3(0, 0, 0). */ template - static Vec3 callStaticVec3Method(const std::string& className, const std::string& methodName, Ts... xs) + static Vec3 callStaticVec3Method(std::string_view className, std::string_view methodName, Ts... xs) { Vec3 ret; cocos2d::JniMethodInfo t; @@ -274,7 +274,7 @@ public: @return value from Java static double method if there are proper JniMethodInfo; otherwise 0. */ template - static double callStaticDoubleMethod(const std::string& className, const std::string& methodName, Ts... xs) + static double callStaticDoubleMethod(std::string_view className, std::string_view methodName, Ts... xs) { jdouble ret = 0.0; cocos2d::JniMethodInfo t; @@ -298,7 +298,7 @@ public: @return JniMethodInfo of string type if there are proper JniMethodInfo; otherwise empty string. */ template - static std::string callStaticStringMethod(const std::string& className, const std::string& methodName, Ts... xs) + static std::string callStaticStringMethod(std::string_view className, std::string_view methodName, Ts... xs) { std::string ret; @@ -334,7 +334,7 @@ private: static jstring convert(LocalRefMapType& localRefs, cocos2d::JniMethodInfo& t, const char* x); - static jstring convert(LocalRefMapType& localRefs, cocos2d::JniMethodInfo& t, const std::string& x); + static jstring convert(LocalRefMapType& localRefs, cocos2d::JniMethodInfo& t, std::string_view x); inline static jint convert(LocalRefMapType&, cocos2d::JniMethodInfo&, int32_t value) { @@ -395,7 +395,7 @@ private: static std::string getJNISignature(const char*) { return "Ljava/lang/String;"; } - static std::string getJNISignature(const std::string&) { return "Ljava/lang/String;"; } + static std::string getJNISignature(std::string_view) { return "Ljava/lang/String;"; } template static std::string getJNISignature(T x) @@ -411,7 +411,7 @@ private: return getJNISignature(x) + getJNISignature(xs...); } - static void reportError(const std::string& className, const std::string& methodName, const std::string& signature); + static void reportError(std::string_view className, std::string_view methodName, std::string_view signature); }; NS_CC_END diff --git a/cocos/platform/apple/CCFileUtils-apple.h b/cocos/platform/apple/CCFileUtils-apple.h index 8eff83505a..14a3fb62e4 100644 --- a/cocos/platform/apple/CCFileUtils-apple.h +++ b/cocos/platform/apple/CCFileUtils-apple.h @@ -51,21 +51,21 @@ public: /* override functions */ virtual std::string getWritablePath() const override; virtual std::string getNativeWritableAbsolutePath() const override; - virtual std::string getFullPathForFilenameWithinDirectory(const std::string& directory, - const std::string& filename) const override; + virtual std::string getFullPathForFilenameWithinDirectory(std::string_view directory, + std::string_view filename) const override; #if CC_FILEUTILS_APPLE_ENABLE_OBJC void setBundle(NSBundle* bundle); #endif - virtual bool createDirectory(const std::string& path) const override; - virtual std::string getPathForDirectory(const std::string& dir, - const std::string& resolutionDiretory, - const std::string& searchPath) const override; + virtual bool createDirectory(std::string_view path) const override; + virtual std::string getPathForDirectory(std::string_view dir, + std::string_view resolutionDiretory, + std::string_view searchPath) const override; private: - virtual bool isFileExistInternal(const std::string& filePath) const override; - virtual bool removeDirectory(const std::string& dirPath) const override; + virtual bool isFileExistInternal(std::string_view filePath) const override; + virtual bool removeDirectory(std::string_view dirPath) const override; struct IMPL; std::unique_ptr pimpl_; diff --git a/cocos/platform/apple/CCFileUtils-apple.mm b/cocos/platform/apple/CCFileUtils-apple.mm index 75dabafb21..1154fa28e5 100644 --- a/cocos/platform/apple/CCFileUtils-apple.mm +++ b/cocos/platform/apple/CCFileUtils-apple.mm @@ -105,7 +105,7 @@ std::string FileUtilsApple::getNativeWritableAbsolutePath() const return strRet; } -bool FileUtilsApple::isFileExistInternal(const std::string& filePath) const +bool FileUtilsApple::isFileExistInternal(std::string_view filePath) const { if (filePath.empty()) { @@ -158,7 +158,7 @@ static int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, str return ret; } -bool FileUtilsApple::removeDirectory(const std::string& path) const +bool FileUtilsApple::removeDirectory(std::string_view path) const { if (path.empty()) { @@ -200,7 +200,7 @@ std::string FileUtilsApple::getPathForDirectory(const std::string &dir, const st } -std::string FileUtilsApple::getFullPathForFilenameWithinDirectory(const std::string& directory, const std::string& filename) const +std::string FileUtilsApple::getFullPathForFilenameWithinDirectory(std::string_view directory, std::string_view filename) const { if (directory[0] != '/') { @@ -222,7 +222,7 @@ std::string FileUtilsApple::getFullPathForFilenameWithinDirectory(const std::str return ""; } -bool FileUtilsApple::createDirectory(const std::string& path) const +bool FileUtilsApple::createDirectory(std::string_view path) const { CCASSERT(!path.empty(), "Invalid path"); diff --git a/cocos/platform/desktop/CCGLViewImpl-desktop.cpp b/cocos/platform/desktop/CCGLViewImpl-desktop.cpp index 7f18509643..2b3b152d22 100644 --- a/cocos/platform/desktop/CCGLViewImpl-desktop.cpp +++ b/cocos/platform/desktop/CCGLViewImpl-desktop.cpp @@ -326,12 +326,12 @@ GLViewImpl::~GLViewImpl() #endif } -GLViewImpl* GLViewImpl::create(const std::string& viewName) +GLViewImpl* GLViewImpl::create(std::string_view viewName) { return GLViewImpl::create(viewName, false); } -GLViewImpl* GLViewImpl::create(const std::string& viewName, bool resizable) +GLViewImpl* GLViewImpl::create(std::string_view viewName, bool resizable) { auto ret = new GLViewImpl; if (ret->initWithRect(viewName, Rect(0, 0, 960, 640), 1.0f, resizable)) @@ -343,7 +343,7 @@ GLViewImpl* GLViewImpl::create(const std::string& viewName, bool resizable) return nullptr; } -GLViewImpl* GLViewImpl::createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable) +GLViewImpl* GLViewImpl::createWithRect(std::string_view viewName, Rect rect, float frameZoomFactor, bool resizable) { auto ret = new GLViewImpl; if (ret->initWithRect(viewName, rect, frameZoomFactor, resizable)) @@ -355,7 +355,7 @@ GLViewImpl* GLViewImpl::createWithRect(const std::string& viewName, Rect rect, f return nullptr; } -GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName) +GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName) { auto ret = new GLViewImpl(); if (ret->initWithFullScreen(viewName)) @@ -367,7 +367,7 @@ GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName) return nullptr; } -GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName, +GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName, const GLFWvidmode& videoMode, GLFWmonitor* monitor) { @@ -381,7 +381,7 @@ GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName, return nullptr; } -bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable) +bool GLViewImpl::initWithRect(std::string_view viewName, Rect rect, float frameZoomFactor, bool resizable) { setViewName(viewName); @@ -509,7 +509,7 @@ bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float fram return true; } -bool GLViewImpl::initWithFullScreen(const std::string& viewName) +bool GLViewImpl::initWithFullScreen(std::string_view viewName) { // Create fullscreen window on primary monitor at its current video mode. _monitor = glfwGetPrimaryMonitor(); @@ -520,7 +520,7 @@ bool GLViewImpl::initWithFullScreen(const std::string& viewName) return initWithRect(viewName, Rect(0, 0, (float)videoMode->width, (float)videoMode->height), 1.0f, false); } -bool GLViewImpl::initWithFullscreen(const std::string& viewname, const GLFWvidmode& videoMode, GLFWmonitor* monitor) +bool GLViewImpl::initWithFullscreen(std::string_view viewname, const GLFWvidmode& videoMode, GLFWmonitor* monitor) { // Create fullscreen on specified monitor at the specified video mode. _monitor = monitor; @@ -592,13 +592,12 @@ void GLViewImpl::enableRetina(bool enabled) void GLViewImpl::setIMEKeyboardState(bool /*bOpen*/) {} #if CC_ICON_SET_SUPPORT -void GLViewImpl::setIcon(const std::string& filename) const +void GLViewImpl::setIcon(std::string_view filename) const { - std::vector vec = {filename}; - this->setIcon(vec); + this->setIcon(std::vector{filename}); } -void GLViewImpl::setIcon(const std::vector& filelist) const +void GLViewImpl::setIcon(const std::vector& filelist) const { if (filelist.empty()) return; diff --git a/cocos/platform/desktop/CCGLViewImpl-desktop.h b/cocos/platform/desktop/CCGLViewImpl-desktop.h index f46a0f0ec2..74c7d895fe 100644 --- a/cocos/platform/desktop/CCGLViewImpl-desktop.h +++ b/cocos/platform/desktop/CCGLViewImpl-desktop.h @@ -60,14 +60,14 @@ class CC_DLL GLViewImpl : public GLView friend class GLFWEventHandler; public: - static GLViewImpl* create(const std::string& viewName); - static GLViewImpl* create(const std::string& viewName, bool resizable); - static GLViewImpl* createWithRect(const std::string& viewName, + static GLViewImpl* create(std::string_view viewName); + static GLViewImpl* create(std::string_view viewName, bool resizable); + static GLViewImpl* createWithRect(std::string_view viewName, Rect size, float frameZoomFactor = 1.0f, bool resizable = false); - static GLViewImpl* createWithFullScreen(const std::string& viewName); - static GLViewImpl* createWithFullScreen(const std::string& viewName, + static GLViewImpl* createWithFullScreen(std::string_view viewName); + static GLViewImpl* createWithFullScreen(std::string_view viewName, const GLFWvidmode& videoMode, GLFWmonitor* monitor); @@ -121,8 +121,8 @@ public: virtual void setIMEKeyboardState(bool bOpen) override; #if CC_ICON_SET_SUPPORT - virtual void setIcon(const std::string& filename) const override; - virtual void setIcon(const std::vector& filelist) const override; + virtual void setIcon(std::string_view filename) const override; + virtual void setIcon(const std::vector& filelist) const override; virtual void setDefaultIcon() const override; #endif /* CC_ICON_SET_SUPPORT */ @@ -157,9 +157,9 @@ protected: GLViewImpl(bool initglfw = true); virtual ~GLViewImpl(); - bool initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable); - bool initWithFullScreen(const std::string& viewName); - bool initWithFullscreen(const std::string& viewname, const GLFWvidmode& videoMode, GLFWmonitor* monitor); + bool initWithRect(std::string_view viewName, Rect rect, float frameZoomFactor, bool resizable); + bool initWithFullScreen(std::string_view viewName); + bool initWithFullscreen(std::string_view viewname, const GLFWvidmode& videoMode, GLFWmonitor* monitor); bool loadGL(); diff --git a/cocos/platform/ios/CCApplication-ios.h b/cocos/platform/ios/CCApplication-ios.h index bcced55ac1..d87e7a79bc 100644 --- a/cocos/platform/ios/CCApplication-ios.h +++ b/cocos/platform/ios/CCApplication-ios.h @@ -87,7 +87,7 @@ public: @param String with url to open. @return true if the resource located by the URL was successfully opened; otherwise false. */ - virtual bool openURL(const std::string& url) override; + virtual bool openURL(std::string_view url) override; /** @brief This function will be called when the application screen size is changed. diff --git a/cocos/platform/ios/CCGLViewImpl-ios.h b/cocos/platform/ios/CCGLViewImpl-ios.h index 0aa8892865..f8ab60f75b 100644 --- a/cocos/platform/ios/CCGLViewImpl-ios.h +++ b/cocos/platform/ios/CCGLViewImpl-ios.h @@ -40,13 +40,13 @@ public: static GLViewImpl* createWithEAGLView(void* eaGLView); /** creates a GLViewImpl with a title name in fullscreen mode */ - static GLViewImpl* create(const std::string& viewName); + static GLViewImpl* create(std::string_view viewName); /** creates a GLViewImpl with a title name, a rect and the zoom factor */ - static GLViewImpl* createWithRect(const std::string& viewName, const Rect& rect, float frameZoomFactor = 1.0f); + static GLViewImpl* createWithRect(std::string_view viewName, const Rect& rect, float frameZoomFactor = 1.0f); /** creates a GLViewImpl with a name in fullscreen mode */ - static GLViewImpl* createWithFullScreen(const std::string& viewName); + static GLViewImpl* createWithFullScreen(std::string_view viewName); static void convertAttrs(); static void* _pixelFormat; @@ -78,8 +78,8 @@ protected: virtual ~GLViewImpl(); bool initWithEAGLView(void* eaGLView); - bool initWithRect(const std::string& viewName, const Rect& rect, float frameZoomFactor); - bool initWithFullScreen(const std::string& viewName); + bool initWithRect(std::string_view viewName, const Rect& rect, float frameZoomFactor); + bool initWithFullScreen(std::string_view viewName); // the objective-c CCEAGLView instance void* _eaglview; diff --git a/cocos/platform/ios/CCGLViewImpl-ios.mm b/cocos/platform/ios/CCGLViewImpl-ios.mm index 53a1e78194..91e1dc06de 100644 --- a/cocos/platform/ios/CCGLViewImpl-ios.mm +++ b/cocos/platform/ios/CCGLViewImpl-ios.mm @@ -48,7 +48,7 @@ GLViewImpl* GLViewImpl::createWithEAGLView(void *eaglview) return nullptr; } -GLViewImpl* GLViewImpl::create(const std::string& viewName) +GLViewImpl* GLViewImpl::create(std::string_view viewName) { auto ret = new GLViewImpl; if(ret->initWithFullScreen(viewName)) { @@ -59,7 +59,7 @@ GLViewImpl* GLViewImpl::create(const std::string& viewName) return nullptr; } -GLViewImpl* GLViewImpl::createWithRect(const std::string& viewName, const Rect& rect, float frameZoomFactor) +GLViewImpl* GLViewImpl::createWithRect(std::string_view viewName, const Rect& rect, float frameZoomFactor) { auto ret = new GLViewImpl; if(ret->initWithRect(viewName, rect, frameZoomFactor)) { @@ -70,7 +70,7 @@ GLViewImpl* GLViewImpl::createWithRect(const std::string& viewName, const Rect& return nullptr; } -GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName) +GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName) { auto ret = new GLViewImpl(); if(ret->initWithFullScreen(viewName)) { @@ -130,7 +130,7 @@ bool GLViewImpl::initWithEAGLView(void *eaglview) return true; } -bool GLViewImpl::initWithRect(const std::string& viewName, const Rect& rect, float frameZoomFactor) +bool GLViewImpl::initWithRect(std::string_view viewName, const Rect& rect, float frameZoomFactor) { CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height); convertAttrs(); @@ -156,7 +156,7 @@ bool GLViewImpl::initWithRect(const std::string& viewName, const Rect& rect, flo return true; } -bool GLViewImpl::initWithFullScreen(const std::string& viewName) +bool GLViewImpl::initWithFullScreen(std::string_view viewName) { CGRect rect = [[UIScreen mainScreen] bounds]; Rect r; diff --git a/cocos/platform/ios/CCImage-ios.mm b/cocos/platform/ios/CCImage-ios.mm index b5b9387998..9c323ccb36 100644 --- a/cocos/platform/ios/CCImage-ios.mm +++ b/cocos/platform/ios/CCImage-ios.mm @@ -35,7 +35,7 @@ THE SOFTWARE. NS_CC_BEGIN -bool cocos2d::Image::saveToFile(const std::string& filename, bool isToRGB) +bool cocos2d::Image::saveToFile(std::string_view filename, bool isToRGB) { //only support for backend::PixelFormat::RGB8 or backend::PixelFormat::RGBA8 uncompressed data if (isCompressed() || (_pixelFormat != backend::PixelFormat::RGB8 && _pixelFormat != backend::PixelFormat::RGBA8)) diff --git a/cocos/platform/linux/CCApplication-linux.cpp b/cocos/platform/linux/CCApplication-linux.cpp index be903a2dab..fa98b686a6 100644 --- a/cocos/platform/linux/CCApplication-linux.cpp +++ b/cocos/platform/linux/CCApplication-linux.cpp @@ -110,7 +110,7 @@ void Application::setAnimationInterval(float interval) _animationInterval = interval * 1000.0f; } -void Application::setResourceRootPath(const std::string& rootResDir) +void Application::setResourceRootPath(std::string_view rootResDir) { _resourceRootPath = rootResDir; if (_resourceRootPath[_resourceRootPath.length() - 1] != '/') @@ -123,7 +123,7 @@ void Application::setResourceRootPath(const std::string& rootResDir) pFileUtils->setSearchPaths(searchPaths); } -const std::string& Application::getResourceRootPath() +std::string_view Application::getResourceRootPath() { return _resourceRootPath; } @@ -138,7 +138,7 @@ std::string Application::getVersion() return ""; } -bool Application::openURL(const std::string& url) +bool Application::openURL(std::string_view url) { std::string op = std::string("xdg-open '").append(url).append("'"); return system(op.c_str()) == 0; diff --git a/cocos/platform/linux/CCApplication-linux.h b/cocos/platform/linux/CCApplication-linux.h index 8f40f7ea00..3d5c05e602 100644 --- a/cocos/platform/linux/CCApplication-linux.h +++ b/cocos/platform/linux/CCApplication-linux.h @@ -84,19 +84,19 @@ public: @param String with url to open. @return true if the resource located by the URL was successfully opened; otherwise false. */ - virtual bool openURL(const std::string& url) override; + virtual bool openURL(std::string_view url) override; /** * Sets the Resource root path. * @deprecated Please use FileUtils::getInstance()->setSearchPaths() instead. */ - CC_DEPRECATED_ATTRIBUTE void setResourceRootPath(const std::string& rootResDir); + CC_DEPRECATED_ATTRIBUTE void setResourceRootPath(std::string_view rootResDir); /** * Gets the Resource root path. * @deprecated Please use FileUtils::getInstance()->getSearchPaths() instead. */ - CC_DEPRECATED_ATTRIBUTE const std::string& getResourceRootPath(); + CC_DEPRECATED_ATTRIBUTE std::string_view getResourceRootPath(); /** @brief Get target platform diff --git a/cocos/platform/linux/CCFileUtils-linux.cpp b/cocos/platform/linux/CCFileUtils-linux.cpp index 0ec3a38d07..91edc06910 100644 --- a/cocos/platform/linux/CCFileUtils-linux.cpp +++ b/cocos/platform/linux/CCFileUtils-linux.cpp @@ -115,7 +115,7 @@ std::string FileUtilsLinux::getNativeWritableAbsolutePath() const return _writablePath; } -bool FileUtilsLinux::isFileExistInternal(const std::string& strFilePath) const +bool FileUtilsLinux::isFileExistInternal(std::string_view strFilePath) const { DECLARE_GUARD; if (strFilePath.empty()) diff --git a/cocos/platform/linux/CCFileUtils-linux.h b/cocos/platform/linux/CCFileUtils-linux.h index 258ac96d99..1dc54ec213 100644 --- a/cocos/platform/linux/CCFileUtils-linux.h +++ b/cocos/platform/linux/CCFileUtils-linux.h @@ -56,7 +56,7 @@ public: std::string getNativeWritableAbsolutePath() const override; private: - virtual bool isFileExistInternal(const std::string& strFilePath) const override; + virtual bool isFileExistInternal(std::string_view strFilePath) const override; }; // end of platform group diff --git a/cocos/platform/mac/CCApplication-mac.h b/cocos/platform/mac/CCApplication-mac.h index 9636b4af88..fe6bbbff1a 100644 --- a/cocos/platform/mac/CCApplication-mac.h +++ b/cocos/platform/mac/CCApplication-mac.h @@ -90,11 +90,11 @@ public: @param String with url to open. @return true if the resource located by the URL was successfully opened; otherwise false. */ - virtual bool openURL(const std::string& url) override; + virtual bool openURL(std::string_view url) override; - void setStartupScriptFilename(const std::string& startupScriptFile); + void setStartupScriptFilename(std::string_view startupScriptFile); - const std::string& getStartupScriptFilename(); + std::string_view getStartupScriptFilename(); protected: static Application* sm_pSharedApplication; diff --git a/cocos/platform/mac/CCApplication-mac.mm b/cocos/platform/mac/CCApplication-mac.mm index 8d8a92b313..dddafef71d 100644 --- a/cocos/platform/mac/CCApplication-mac.mm +++ b/cocos/platform/mac/CCApplication-mac.mm @@ -172,13 +172,13 @@ bool Application::openURL(const std::string &url) return [[NSWorkspace sharedWorkspace] openURL:nsUrl]; } -void Application::setStartupScriptFilename(const std::string& startupScriptFile) +void Application::setStartupScriptFilename(std::string_view startupScriptFile) { _startupScriptFilename = startupScriptFile; std::replace(_startupScriptFilename.begin(), _startupScriptFilename.end(), '\\', '/'); } -const std::string& Application::getStartupScriptFilename() +std::string_view Application::getStartupScriptFilename() { return _startupScriptFilename; } diff --git a/cocos/platform/mac/CCGLViewImpl-mac.h b/cocos/platform/mac/CCGLViewImpl-mac.h index 7c2d480dfa..01317ae283 100644 --- a/cocos/platform/mac/CCGLViewImpl-mac.h +++ b/cocos/platform/mac/CCGLViewImpl-mac.h @@ -58,14 +58,14 @@ class CC_DLL GLViewImpl : public GLView friend class GLFWEventHandler; public: - static GLViewImpl* create(const std::string& viewName); - static GLViewImpl* create(const std::string& viewName, bool resizable); - static GLViewImpl* createWithRect(const std::string& viewName, + static GLViewImpl* create(std::string_view viewName); + static GLViewImpl* create(std::string_view viewName, bool resizable); + static GLViewImpl* createWithRect(std::string_view viewName, Rect size, float frameZoomFactor = 1.0f, bool resizable = false); - static GLViewImpl* createWithFullScreen(const std::string& viewName); - static GLViewImpl* createWithFullScreen(const std::string& viewName, + static GLViewImpl* createWithFullScreen(std::string_view viewName); + static GLViewImpl* createWithFullScreen(std::string_view viewName, const GLFWvidmode& videoMode, GLFWmonitor* monitor); @@ -119,7 +119,7 @@ public: virtual void setIMEKeyboardState(bool bOpen) override; #if CC_ICON_SET_SUPPORT - virtual void setIcon(const std::string& filename) const override; + virtual void setIcon(std::string_view filename) const override; virtual void setIcon(const std::vector& filelist) const override; virtual void setDefaultIcon() const override; #endif /* CC_ICON_SET_SUPPORT */ @@ -149,9 +149,9 @@ protected: GLViewImpl(bool initglfw = true); virtual ~GLViewImpl(); - bool initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable); - bool initWithFullScreen(const std::string& viewName); - bool initWithFullscreen(const std::string& viewname, const GLFWvidmode& videoMode, GLFWmonitor* monitor); + bool initWithRect(std::string_view viewName, Rect rect, float frameZoomFactor, bool resizable); + bool initWithFullScreen(std::string_view viewName); + bool initWithFullscreen(std::string_view viewname, const GLFWvidmode& videoMode, GLFWmonitor* monitor); /* update frame layout when enter/exit full screen mode */ void updateWindowSize(); diff --git a/cocos/platform/mac/CCGLViewImpl-mac.mm b/cocos/platform/mac/CCGLViewImpl-mac.mm index 8d47ababc9..6e76c24941 100644 --- a/cocos/platform/mac/CCGLViewImpl-mac.mm +++ b/cocos/platform/mac/CCGLViewImpl-mac.mm @@ -314,12 +314,12 @@ GLViewImpl::~GLViewImpl() glfwTerminate(); } -GLViewImpl* GLViewImpl::create(const std::string& viewName) +GLViewImpl* GLViewImpl::create(std::string_view viewName) { return GLViewImpl::create(viewName, false); } -GLViewImpl* GLViewImpl::create(const std::string& viewName, bool resizable) +GLViewImpl* GLViewImpl::create(std::string_view viewName, bool resizable) { auto ret = new GLViewImpl; if(ret->initWithRect(viewName, Rect(0, 0, 960, 640), 1.0f, resizable)) { @@ -330,7 +330,7 @@ GLViewImpl* GLViewImpl::create(const std::string& viewName, bool resizable) return nullptr; } -GLViewImpl* GLViewImpl::createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable) +GLViewImpl* GLViewImpl::createWithRect(std::string_view viewName, Rect rect, float frameZoomFactor, bool resizable) { auto ret = new GLViewImpl; if(ret->initWithRect(viewName, rect, frameZoomFactor, resizable)) { @@ -341,7 +341,7 @@ GLViewImpl* GLViewImpl::createWithRect(const std::string& viewName, Rect rect, f return nullptr; } -GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName) +GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName) { auto ret = new GLViewImpl(); if(ret->initWithFullScreen(viewName)) { @@ -352,7 +352,7 @@ GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName) return nullptr; } -GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName, const GLFWvidmode &videoMode, GLFWmonitor *monitor) +GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName, const GLFWvidmode &videoMode, GLFWmonitor *monitor) { auto ret = new GLViewImpl(); if(ret->initWithFullscreen(viewName, videoMode, monitor)) { @@ -363,7 +363,7 @@ GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName, const return nullptr; } -bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable) +bool GLViewImpl::initWithRect(std::string_view viewName, Rect rect, float frameZoomFactor, bool resizable) { setViewName(viewName); @@ -470,7 +470,7 @@ bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float fram return true; } -bool GLViewImpl::initWithFullScreen(const std::string& viewName) +bool GLViewImpl::initWithFullScreen(std::string_view viewName) { //Create fullscreen window on primary monitor at its current video mode. _monitor = glfwGetPrimaryMonitor(); @@ -555,7 +555,7 @@ void GLViewImpl::setIMEKeyboardState(bool /*bOpen*/) } #if CC_ICON_SET_SUPPORT -void GLViewImpl::setIcon(const std::string& filename) const { +void GLViewImpl::setIcon(std::string_view filename) const { std::vector vec = {filename}; this->setIcon(vec); } diff --git a/cocos/platform/win32/CCApplication-win32.cpp b/cocos/platform/win32/CCApplication-win32.cpp index 3f51532ce9..ea159d973b 100644 --- a/cocos/platform/win32/CCApplication-win32.cpp +++ b/cocos/platform/win32/CCApplication-win32.cpp @@ -287,14 +287,14 @@ std::string Application::getVersion() return verString; } -bool Application::openURL(const std::string& url) +bool Application::openURL(std::string_view url) { std::wstring wURL = ntcvt::from_chars(url, CP_UTF8); HINSTANCE r = ShellExecuteW(NULL, L"open", wURL.c_str(), NULL, NULL, SW_SHOWNORMAL); return (size_t)r > 32; } -void Application::setResourceRootPath(const std::string& rootResDir) +void Application::setResourceRootPath(std::string_view rootResDir) { _resourceRootPath = rootResDir; std::replace(_resourceRootPath.begin(), _resourceRootPath.end(), '\\', '/'); @@ -308,12 +308,12 @@ void Application::setResourceRootPath(const std::string& rootResDir) pFileUtils->setSearchPaths(searchPaths); } -const std::string& Application::getResourceRootPath(void) +std::string_view Application::getResourceRootPath(void) { return _resourceRootPath; } -void Application::setStartupScriptFilename(const std::string& startupScriptFile) +void Application::setStartupScriptFilename(std::string_view startupScriptFile) { _startupScriptFilename = startupScriptFile; std::replace(_startupScriptFilename.begin(), _startupScriptFilename.end(), '\\', '/'); diff --git a/cocos/platform/win32/CCApplication-win32.h b/cocos/platform/win32/CCApplication-win32.h index 011100a3f2..56fcc81e84 100644 --- a/cocos/platform/win32/CCApplication-win32.h +++ b/cocos/platform/win32/CCApplication-win32.h @@ -78,23 +78,23 @@ public: @param String with url to open. @return true if the resource located by the URL was successfully opened; otherwise false. */ - virtual bool openURL(const std::string& url); + virtual bool openURL(std::string_view url); /** * Sets the Resource root path. * @deprecated Please use FileUtils::getInstance()->setSearchPaths() instead. */ - CC_DEPRECATED_ATTRIBUTE void setResourceRootPath(const std::string& rootResDir); + CC_DEPRECATED_ATTRIBUTE void setResourceRootPath(std::string_view rootResDir); /** * Gets the Resource root path. * @deprecated Please use FileUtils::getInstance()->getSearchPaths() instead. */ - CC_DEPRECATED_ATTRIBUTE const std::string& getResourceRootPath(); + CC_DEPRECATED_ATTRIBUTE std::string_view getResourceRootPath(); - void setStartupScriptFilename(const std::string& startupScriptFile); + void setStartupScriptFilename(std::string_view startupScriptFile); - const std::string& getStartupScriptFilename() { return _startupScriptFilename; } + std::string_view getStartupScriptFilename() { return _startupScriptFilename; } protected: HINSTANCE _instance; diff --git a/cocos/platform/win32/CCFileUtils-win32.cpp b/cocos/platform/win32/CCFileUtils-win32.cpp index 1dd25374af..acc434b155 100644 --- a/cocos/platform/win32/CCFileUtils-win32.cpp +++ b/cocos/platform/win32/CCFileUtils-win32.cpp @@ -45,13 +45,13 @@ NS_CC_BEGIN // The root path of resources, the character encoding is UTF-8. // UTF-8 is the only encoding supported by adxe API by default. -static std::string s_workingPath = ""; -static std::string s_exePath = ""; +static std::wstring s_workingPath; +static std::string s_exePath; // D:\aaa\bbb\ccc\ddd\abc.txt --> D:/aaa/bbb/ccc/ddd/abc.txt -static std::string convertPathFormatToUnixStyle(const std::string& path) +static std::string convertPathFormatToUnixStyle(std::string_view path) { - std::string ret = path; + std::string ret{path}; int len = ret.length(); for (int i = 0; i < len; ++i) { @@ -63,6 +63,20 @@ static std::string convertPathFormatToUnixStyle(const std::string& path) return ret; } +static std::string convertPathFormatToWinStyle(std::string_view path) +{ + std::string ret{path}; + int len = ret.length(); + for (int i = 0; i < len; ++i) + { + if (ret[i] == '/') + { + ret[i] = '\\'; + } + } + return ret; +} + static void _checkWorkingPath() { if (s_workingPath.empty()) @@ -70,15 +84,17 @@ static void _checkWorkingPath() WCHAR utf16Path[CC_MAX_PATH] = {0}; int nNum = GetCurrentDirectoryW(CC_MAX_PATH - 2, utf16Path); - char utf8WorkingDir[CC_MAX_PATH] = {0}; - nNum = - WideCharToMultiByte(CP_UTF8, 0, utf16Path, nNum, utf8WorkingDir, sizeof(utf8WorkingDir), nullptr, nullptr); - if (nNum < (CC_MAX_PATH - 2)) - { - utf8WorkingDir[nNum] = '\\'; - utf8WorkingDir[nNum + 1] = '\0'; - s_workingPath = convertPathFormatToUnixStyle(utf8WorkingDir); - } + s_workingPath.assign(utf16Path, nNum); + + //char utf8WorkingDir[CC_MAX_PATH] = {0}; + //nNum = + // WideCharToMultiByte(CP_UTF8, 0, utf16Path, nNum, utf8WorkingDir, sizeof(utf8WorkingDir), nullptr, nullptr); + //if (nNum < (CC_MAX_PATH - 2)) + //{ + // utf8WorkingDir[nNum] = '\\'; + // utf8WorkingDir[nNum + 1] = '\0'; + // s_workingPath = convertPathFormatToUnixStyle(utf8WorkingDir); + //} } } @@ -121,25 +137,26 @@ bool FileUtilsWin32::init() DECLARE_GUARD; _checkWorkingPath(); - _defaultResRootPath = s_workingPath; + _defaultResRootPath = ntcvt::from_chars(s_workingPath); + _defaultResRootPathUtf16 = s_workingPath; bool bRet = FileUtils::init(); _checkExePath(); - if (s_workingPath != s_exePath) + if (_defaultResRootPath != s_exePath) addSearchPath(s_exePath); return bRet; } -bool FileUtilsWin32::isDirectoryExistInternal(const std::string& dirPath) const +bool FileUtilsWin32::isDirectoryExistInternal(std::string_view dirPath) const { uint32_t fAttrib = GetFileAttributesW(ntcvt::from_chars(dirPath).c_str()); return (fAttrib != INVALID_FILE_ATTRIBUTES && (fAttrib & FILE_ATTRIBUTE_DIRECTORY)); } -bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const +bool FileUtilsWin32::isFileExistInternal(std::string_view strFilePath) const { DECLARE_GUARD; if (strFilePath.empty()) @@ -147,17 +164,19 @@ bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const return false; } - std::string strPath = strFilePath; - if (!isAbsolutePath(strPath)) + std::wstring strPathUtf16; + if (!isAbsolutePath(strFilePath)) { // Not absolute path, add the default root path at the beginning. - strPath.insert(0, _defaultResRootPath); + strPathUtf16.insert(0, _defaultResRootPathUtf16); } + else + strPathUtf16 = ntcvt::from_chars(strFilePath); - DWORD attr = GetFileAttributesW(ntcvt::from_chars(strPath).c_str()); + DWORD attr = GetFileAttributesW(strPathUtf16.c_str()); return (attr != INVALID_FILE_ATTRIBUTES && !(attr & FILE_ATTRIBUTE_DIRECTORY)); } -FileUtils::Status FileUtilsWin32::getContents(const std::string& filename, ResizableBuffer* buffer) const +FileUtils::Status FileUtilsWin32::getContents(std::string_view filename, ResizableBuffer* buffer) const { if (filename.empty()) return FileUtils::Status::NotExists; @@ -199,9 +218,9 @@ FileUtils::Status FileUtilsWin32::getContents(const std::string& filename, Resiz return FileUtils::Status::OK; } -std::string FileUtilsWin32::getPathForFilename(const std::string& filename, - const std::string& resolutionDirectory, - const std::string& searchPath) const +std::string FileUtilsWin32::getPathForFilename(std::string_view filename, + std::string_view resolutionDirectory, + std::string_view searchPath) const { std::string unixFileName = convertPathFormatToUnixStyle(filename); std::string unixResolutionDirectory = convertPathFormatToUnixStyle(resolutionDirectory); @@ -210,8 +229,8 @@ std::string FileUtilsWin32::getPathForFilename(const std::string& filename, return FileUtils::getPathForFilename(unixFileName, unixResolutionDirectory, unixSearchPath); } -std::string FileUtilsWin32::getFullPathForFilenameWithinDirectory(const std::string& strDirectory, - const std::string& strFilename) const +std::string FileUtilsWin32::getFullPathForFilenameWithinDirectory(std::string_view strDirectory, + std::string_view strFilename) const { std::string unixDirectory = convertPathFormatToUnixStyle(strDirectory); std::string unixFilename = convertPathFormatToUnixStyle(strFilename); @@ -219,7 +238,7 @@ std::string FileUtilsWin32::getFullPathForFilenameWithinDirectory(const std::str return FileUtils::getFullPathForFilenameWithinDirectory(unixDirectory, unixFilename); } -void FileUtilsWin32::listFilesRecursively(const std::string& dirPath, std::vector* files) const +void FileUtilsWin32::listFilesRecursively(std::string_view dirPath, std::vector* files) const { std::string fullpath = fullPathForDirectory(dirPath); if (isDirectoryExist(fullpath)) @@ -265,7 +284,7 @@ void FileUtilsWin32::listFilesRecursively(const std::string& dirPath, std::vecto } } -int64_t FileUtilsWin32::getFileSize(const std::string& filepath) const +int64_t FileUtilsWin32::getFileSize(std::string_view filepath) const { if (filepath.empty()) return -1; @@ -276,7 +295,7 @@ int64_t FileUtilsWin32::getFileSize(const std::string& filepath) const return -1; } -std::vector FileUtilsWin32::listFiles(const std::string& dirPath) const +std::vector FileUtilsWin32::listFiles(std::string_view dirPath) const { std::string fullpath = fullPathForDirectory(dirPath); std::vector files; @@ -380,7 +399,7 @@ std::string FileUtilsWin32::getNativeWritableAbsolutePath() const return convertPathFormatToUnixStyle(ntcvt::from_chars(retPath)); } -bool FileUtilsWin32::renameFile(const std::string& oldfullpath, const std::string& newfullpath) const +bool FileUtilsWin32::renameFile(std::string_view oldfullpath, std::string_view newfullpath) const { CCASSERT(!oldfullpath.empty(), "Invalid path"); CCASSERT(!newfullpath.empty(), "Invalid path"); @@ -392,7 +411,7 @@ bool FileUtilsWin32::renameFile(const std::string& oldfullpath, const std::strin { if (!DeleteFile(_wNew.c_str())) { - CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newfullpath.c_str(), GetLastError()); + CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newfullpath.data(), GetLastError()); } } @@ -402,17 +421,19 @@ bool FileUtilsWin32::renameFile(const std::string& oldfullpath, const std::strin } else { - CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldfullpath.c_str(), newfullpath.c_str(), + CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldfullpath.data(), newfullpath.data(), GetLastError()); return false; } } -bool FileUtilsWin32::renameFile(const std::string& path, const std::string& oldname, const std::string& name) const +bool FileUtilsWin32::renameFile(std::string_view path, std::string_view oldname, std::string_view name) const { CCASSERT(!path.empty(), "Invalid path"); - std::string oldPath = path + oldname; - std::string newPath = path + name; + std::string oldPath{path}; + oldPath += oldname; + std::string newPath{path}; + newPath += name; std::regex pat("\\/"); std::string _old = std::regex_replace(oldPath, pat, "\\"); @@ -421,7 +442,7 @@ bool FileUtilsWin32::renameFile(const std::string& path, const std::string& oldn return renameFile(_old, _new); } -bool FileUtilsWin32::createDirectory(const std::string& dirPath) const +bool FileUtilsWin32::createDirectory(std::string_view dirPath) const { CCASSERT(!dirPath.empty(), "Invalid path"); @@ -478,10 +499,9 @@ bool FileUtilsWin32::createDirectory(const std::string& dirPath) const return true; } -bool FileUtilsWin32::removeFile(const std::string& filepath) const +bool FileUtilsWin32::removeFile(std::string_view filepath) const { - std::regex pat("\\/"); - std::string win32path = std::regex_replace(filepath, pat, "\\"); + std::string win32path = convertPathFormatToWinStyle(filepath); if (DeleteFileW(ntcvt::from_chars(win32path).c_str())) { @@ -489,14 +509,14 @@ bool FileUtilsWin32::removeFile(const std::string& filepath) const } else { - CCLOGERROR("Fail remove file %s !Error code is 0x%x", filepath.c_str(), GetLastError()); + CCLOGERROR("Fail remove file %s !Error code is 0x%x", filepath.data(), GetLastError()); return false; } } -bool FileUtilsWin32::removeDirectory(const std::string& dirPath) const +bool FileUtilsWin32::removeDirectory(std::string_view dirPath) const { - std::string dirPathCopy = dirPath; + std::string dirPathCopy{dirPath}; if (!dirPath.empty() && dirPath[dirPath.length() - 1] != '/' && dirPath[dirPath.length() - 1] != '\\') { dirPathCopy.push_back('/'); diff --git a/cocos/platform/win32/CCFileUtils-win32.h b/cocos/platform/win32/CCFileUtils-win32.h index 5188e7f83a..9cfdb703f0 100644 --- a/cocos/platform/win32/CCFileUtils-win32.h +++ b/cocos/platform/win32/CCFileUtils-win32.h @@ -53,7 +53,7 @@ public: virtual std::string getNativeWritableAbsolutePath() const override; protected: - virtual bool isFileExistInternal(const std::string& strFilePath) const override; + virtual bool isFileExistInternal(std::string_view strFilePath) const override; /** * Renames a file under the given directory. @@ -63,9 +63,9 @@ protected: * @param name The new name of the file. * @return True if the file have been renamed successfully, false if not. */ - virtual bool renameFile(const std::string& path, - const std::string& oldname, - const std::string& name) const override; + virtual bool renameFile(std::string_view path, + std::string_view oldname, + std::string_view name) const override; /** * Renames a file under the given directory. @@ -74,14 +74,14 @@ protected: * @param newfullpath The new path + name of the file. * @return True if the file have been renamed successfully, false if not. */ - virtual bool renameFile(const std::string& oldfullpath, const std::string& newfullpath) const override; + virtual bool renameFile(std::string_view oldfullpath, std::string_view newfullpath) const override; /** * Checks whether a directory exists without considering search paths and resolution orders. * @param dirPath The directory (with absolute path) to look up for * @return Returns true if the directory found at the given absolute path, otherwise returns false */ - virtual bool isDirectoryExistInternal(const std::string& dirPath) const override; + virtual bool isDirectoryExistInternal(std::string_view dirPath) const override; /** * Removes a file. @@ -89,7 +89,7 @@ protected: * @param filepath The full path of the file, it must be an absolute path. * @return True if the file have been removed successfully, false if not. */ - virtual bool removeFile(const std::string& filepath) const override; + virtual bool removeFile(std::string_view filepath) const override; /** * Creates a directory. @@ -97,7 +97,7 @@ protected: * @param dirPath The path of the directory, it must be an absolute path. * @return True if the directory have been created successfully, false if not. */ - virtual bool createDirectory(const std::string& dirPath) const override; + virtual bool createDirectory(std::string_view dirPath) const override; /** * Removes a directory. @@ -105,11 +105,11 @@ protected: * @param dirPath The full path of the directory, it must be an absolute path. * @return True if the directory have been removed successfully, false if not. */ - virtual bool removeDirectory(const std::string& dirPath) const override; + virtual bool removeDirectory(std::string_view dirPath) const override; - virtual FileUtils::Status getContents(const std::string& filename, ResizableBuffer* buffer) const override; + virtual FileUtils::Status getContents(std::string_view filename, ResizableBuffer* buffer) const override; - virtual int64_t getFileSize(const std::string& filepath) const override; + virtual int64_t getFileSize(std::string_view filepath) const override; /** * Gets full path for filename, resolution directory and search path. @@ -119,9 +119,9 @@ protected: * @param searchPath The search path. * @return The full path of the file. It will return an empty string if the full path of the file doesn't exist. */ - virtual std::string getPathForFilename(const std::string& filename, - const std::string& resolutionDirectory, - const std::string& searchPath) const override; + virtual std::string getPathForFilename(std::string_view filename, + std::string_view resolutionDirectory, + std::string_view searchPath) const override; /** * Gets full path for the directory and the filename. @@ -133,8 +133,8 @@ protected: * @param filename The name of the file. * @return The full path of the file, if the file can't be found, it will return an empty string. */ - virtual std::string getFullPathForFilenameWithinDirectory(const std::string& directory, - const std::string& filename) const override; + virtual std::string getFullPathForFilenameWithinDirectory(std::string_view directory, + std::string_view filename) const override; /** * List all files in a directory. @@ -142,7 +142,7 @@ protected: * @param dirPath The path of the directory, it could be a relative or an absolute path. * @return File paths in a string vector */ - virtual std::vector listFiles(const std::string& dirPath) const override; + virtual std::vector listFiles(std::string_view dirPath) const override; /** * List all files recursively in a directory. @@ -150,7 +150,10 @@ protected: * @param dirPath The path of the directory, it could be a relative or an absolute path. * @return File paths in a string vector */ - virtual void listFilesRecursively(const std::string& dirPath, std::vector* files) const override; + virtual void listFilesRecursively(std::string_view dirPath, std::vector* files) const override; + +private: + std::wstring_view _defaultResRootPathUtf16; }; // end of platform group diff --git a/cocos/renderer/CCMaterial.cpp b/cocos/renderer/CCMaterial.cpp index 17a43f39b9..da4aeb7cf1 100644 --- a/cocos/renderer/CCMaterial.cpp +++ b/cocos/renderer/CCMaterial.cpp @@ -48,7 +48,7 @@ NS_CC_BEGIN namespace { -std::string replaceDefines(const std::string& compileTimeDefines) +std::string replaceDefines(std::string_view compileTimeDefines) { auto defineParts = Console::Utility::split(compileTimeDefines, ';'); @@ -72,7 +72,7 @@ std::string replaceDefines(const std::string& compileTimeDefines) static const char* getOptionalString(Properties* properties, const char* key, const char* defaultValue); static bool isValidUniform(const char* name); -Material* Material::createWithFilename(const std::string& filepath) +Material* Material::createWithFilename(std::string_view filepath) { auto validfilename = FileUtils::getInstance()->fullPathForFilename(filepath); if (!validfilename.empty()) @@ -130,7 +130,7 @@ bool Material::initWithProgramState(backend::ProgramState* state) return false; } -bool Material::initWithFile(const std::string& validfilename) +bool Material::initWithFile(std::string_view validfilename) { // Warning: properties is not a "Ref" object, must be manually deleted Properties* properties = Properties::createNonRefCounted(validfilename); @@ -496,7 +496,7 @@ bool Material::parseRenderState(RenderState::StateBlock* state, Properties* prop return true; } -void Material::setName(const std::string& name) +void Material::setName(std::string_view name) { _name = name; } @@ -542,7 +542,7 @@ const Vector& Material::getTechniques() const return _techniques; } -Technique* Material::getTechniqueByName(const std::string& name) +Technique* Material::getTechniqueByName(std::string_view name) { for (const auto& technique : _techniques) { @@ -564,7 +564,7 @@ void Material::addTechnique(Technique* technique) _techniques.pushBack(technique); } -void Material::setTechnique(const std::string& techniqueName) +void Material::setTechnique(std::string_view techniqueName) { auto technique = getTechniqueByName(techniqueName); if (technique) diff --git a/cocos/renderer/CCMaterial.h b/cocos/renderer/CCMaterial.h index acc8ccdda2..bc94addc47 100644 --- a/cocos/renderer/CCMaterial.h +++ b/cocos/renderer/CCMaterial.h @@ -78,7 +78,7 @@ public: * * @return A new Material or NULL if there was an error. */ - static Material* createWithFilename(const std::string& path); + static Material* createWithFilename(std::string_view path); /** Creates a Material with a GLProgramState. It will only contain one Technique and one Pass. @@ -107,12 +107,12 @@ public: /// returns the material name std::string getName() const; /// sets the material name - void setName(const std::string& name); + void setName(std::string_view name); /** Returns a Technique by its name. returns `nullptr` if the Technique can't be found. */ - Technique* getTechniqueByName(const std::string& name); + Technique* getTechniqueByName(std::string_view name); /** Returns a Technique by index. returns `nullptr` if the index is invalid. @@ -132,7 +132,7 @@ public: void addTechnique(Technique* technique); /** Sets the current technique */ - void setTechnique(const std::string& techniqueName); + void setTechnique(std::string_view techniqueName); /** returns a clone (deep-copy) of the material */ virtual Material* clone() const; @@ -147,7 +147,7 @@ protected: Material(); ~Material(); bool initWithProgramState(backend::ProgramState* state); - bool initWithFile(const std::string& file); + bool initWithFile(std::string_view file); bool initWithProperties(Properties* materialProperties); void setTarget(Node* target); diff --git a/cocos/renderer/CCPass.h b/cocos/renderer/CCPass.h index ee095d854f..483112611e 100644 --- a/cocos/renderer/CCPass.h +++ b/cocos/renderer/CCPass.h @@ -94,8 +94,8 @@ public: */ VertexAttribBinding* getVertexAttributeBinding() const; - void setName(const std::string& name) { _name = name; } - const std::string& getName() const { return _name; } + void setName(std::string_view name) { _name = name; } + std::string_view getName() const { return _name; } inline RenderState::StateBlock& getStateBlock() { return _renderState._state; } diff --git a/cocos/renderer/CCRenderState.cpp b/cocos/renderer/CCRenderState.cpp index 4a1b8821d7..690af0e459 100644 --- a/cocos/renderer/CCRenderState.cpp +++ b/cocos/renderer/CCRenderState.cpp @@ -183,12 +183,12 @@ void RenderState::StateBlock::restoreUnmodifiedStates(int32_t overrideBits, Pipe } } -static bool parseBoolean(const std::string& value) +static bool parseBoolean(std::string_view value) { return (value.compare("true") == 0); } -static backend::BlendFactor parseBlend(const std::string& value) +static backend::BlendFactor parseBlend(std::string_view value) { // Convert the string to uppercase for comparison. std::string upper(value); @@ -222,12 +222,12 @@ static backend::BlendFactor parseBlend(const std::string& value) else { CCLOG("Unsupported blend value (%s). (Will default to BLEND_ONE if errors are treated as warnings)", - value.c_str()); + value.data()); return backend::BlendFactor::ONE; } } -static DepthFunction parseDepthFunc(const std::string& value) +static DepthFunction parseDepthFunc(std::string_view value) { // Convert string to uppercase for comparison std::string upper(value); @@ -251,12 +251,12 @@ static DepthFunction parseDepthFunc(const std::string& value) else { CCLOG("Unsupported depth function value (%s). Will default to DEPTH_LESS if errors are treated as warnings)", - value.c_str()); + value.data()); return DepthFunction::LESS; } } -static CullFaceSide parseCullFaceSide(const std::string& value) +static CullFaceSide parseCullFaceSide(std::string_view value) { // Convert string to uppercase for comparison std::string upper(value); @@ -271,12 +271,12 @@ static CullFaceSide parseCullFaceSide(const std::string& value) else { CCLOG("Unsupported cull face side value (%s). Will default to BACK if errors are treated as warnings.", - value.c_str()); + value.data()); return CullFaceSide::BACK; } } -static FrontFace parseFrontFace(const std::string& value) +static FrontFace parseFrontFace(std::string_view value) { // Convert string to uppercase for comparison std::string upper(value); @@ -288,12 +288,12 @@ static FrontFace parseFrontFace(const std::string& value) else { CCLOG("Unsupported front face side value (%s). Will default to CCW if errors are treated as warnings.", - value.c_str()); + value.data()); return FrontFace::COUNTER_CLOCK_WISE; } } -void RenderState::StateBlock::setState(const std::string& name, const std::string& value) +void RenderState::StateBlock::setState(std::string_view name, std::string_view value) { if (name.compare("blend") == 0) { @@ -333,7 +333,7 @@ void RenderState::StateBlock::setState(const std::string& name, const std::strin } else { - CCLOG("Unsupported render state string '%s'.", name.c_str()); + CCLOG("Unsupported render state string '%s'.", name.data()); } } diff --git a/cocos/renderer/CCRenderState.h b/cocos/renderer/CCRenderState.h index 3e94b36afb..27fd7c4973 100644 --- a/cocos/renderer/CCRenderState.h +++ b/cocos/renderer/CCRenderState.h @@ -194,7 +194,7 @@ public: * @param name Name of the render state to set. * @param value Value of the specified render state. */ - void setState(const std::string& name, const std::string& value); + void setState(std::string_view name, std::string_view value); uint32_t getHash() const; bool isDirty() const; diff --git a/cocos/renderer/CCTechnique.cpp b/cocos/renderer/CCTechnique.cpp index 88e5ee9e8b..bc7e20896a 100644 --- a/cocos/renderer/CCTechnique.cpp +++ b/cocos/renderer/CCTechnique.cpp @@ -98,7 +98,7 @@ std::string Technique::getName() const return _name; } -void Technique::setName(const std::string& name) +void Technique::setName(std::string_view name) { _name = name; } diff --git a/cocos/renderer/CCTechnique.h b/cocos/renderer/CCTechnique.h index aaf4c937d8..6c7641b557 100644 --- a/cocos/renderer/CCTechnique.h +++ b/cocos/renderer/CCTechnique.h @@ -91,7 +91,7 @@ protected: ~Technique(); bool init(Material* parent); - void setName(const std::string& name); + void setName(std::string_view name); RenderState _renderState; std::string _name; Vector _passes; diff --git a/cocos/renderer/CCTexture2D.cpp b/cocos/renderer/CCTexture2D.cpp index 55995f8d5a..c9209ec6f3 100644 --- a/cocos/renderer/CCTexture2D.cpp +++ b/cocos/renderer/CCTexture2D.cpp @@ -460,7 +460,7 @@ bool Texture2D::initWithImage(Image* image, backend::PixelFormat format) // implementation Texture2D (Text) bool Texture2D::initWithString(const char* text, - const std::string& fontName, + std::string_view fontName, float fontSize, const Vec2& dimensions /* = Vec2(0, 0)*/, TextHAlignment hAlignment /* = TextHAlignment::CENTER */, diff --git a/cocos/renderer/CCTexture2D.h b/cocos/renderer/CCTexture2D.h index 19afa61928..9d4fb89c84 100644 --- a/cocos/renderer/CCTexture2D.h +++ b/cocos/renderer/CCTexture2D.h @@ -273,7 +273,7 @@ public: @param overflow Whether shrink font size when content larger than the dimensions. */ bool initWithString(const char* text, - const std::string& fontName, + std::string_view fontName, float fontSize, const Vec2& dimensions = Vec2(0, 0), TextHAlignment hAlignment = TextHAlignment::CENTER, diff --git a/cocos/renderer/CCTextureAtlas.cpp b/cocos/renderer/CCTextureAtlas.cpp index 5617481f55..0810493c9f 100644 --- a/cocos/renderer/CCTextureAtlas.cpp +++ b/cocos/renderer/CCTextureAtlas.cpp @@ -99,7 +99,7 @@ void TextureAtlas::setQuads(V3F_C4B_T2F_Quad* quads) // TextureAtlas - alloc & init -TextureAtlas* TextureAtlas::create(const std::string& file, ssize_t capacity) +TextureAtlas* TextureAtlas::create(std::string_view file, ssize_t capacity) { TextureAtlas* textureAtlas = new TextureAtlas(); if (textureAtlas->initWithFile(file, capacity)) @@ -123,7 +123,7 @@ TextureAtlas* TextureAtlas::createWithTexture(Texture2D* texture, ssize_t capaci return nullptr; } -bool TextureAtlas::initWithFile(const std::string& file, ssize_t capacity) +bool TextureAtlas::initWithFile(std::string_view file, ssize_t capacity) { // retained in property Texture2D* texture = Director::getInstance()->getTextureCache()->addImage(file); @@ -134,7 +134,7 @@ bool TextureAtlas::initWithFile(const std::string& file, ssize_t capacity) } else { - CCLOG("cocos2d: Could not open file: %s", file.c_str()); + CCLOG("cocos2d: Could not open file: %s", file.data()); return false; } } diff --git a/cocos/renderer/CCTextureAtlas.h b/cocos/renderer/CCTextureAtlas.h index 0f8abffd26..e088f3e95f 100644 --- a/cocos/renderer/CCTextureAtlas.h +++ b/cocos/renderer/CCTextureAtlas.h @@ -68,7 +68,7 @@ public: @param file The file path. @param capacity Capacity for Quads. */ - static TextureAtlas* create(const std::string& file, ssize_t capacity); + static TextureAtlas* create(std::string_view file, ssize_t capacity); /** Creates a TextureAtlas with a previously initialized Texture2D object, and * with an initial capacity for n Quads. @@ -95,7 +95,7 @@ public: @param file The file path. @param capacity Capacity for Quads. */ - bool initWithFile(const std::string& file, ssize_t capacity); + bool initWithFile(std::string_view file, ssize_t capacity); /** Initializes a TextureAtlas with a previously initialized Texture2D object, and * with an initial capacity for Quads. diff --git a/cocos/renderer/CCTextureCache.cpp b/cocos/renderer/CCTextureCache.cpp index 3315479d7b..36b3296ace 100644 --- a/cocos/renderer/CCTextureCache.cpp +++ b/cocos/renderer/CCTextureCache.cpp @@ -52,7 +52,7 @@ std::string TextureCache::s_etc1AlphaFileSuffix = "@alpha"; // implementation TextureCache -void TextureCache::setETC1AlphaFileSuffix(const std::string& suffix) +void TextureCache::setETC1AlphaFileSuffix(std::string_view suffix) { s_etc1AlphaFileSuffix = suffix; } @@ -82,7 +82,7 @@ std::string TextureCache::getDescription() const struct TextureCache::AsyncStruct { public: - AsyncStruct(const std::string& fn, const std::function& f, const std::string& key) + AsyncStruct(std::string_view fn, const std::function& f, std::string_view key) : filename(fn) , callback(f) , callbackKey(key) @@ -131,7 +131,7 @@ public: Call unbindImageAsync(path) to prevent the call to the callback when the texture is loaded. */ -void TextureCache::addImageAsync(const std::string& path, const std::function& callback) +void TextureCache::addImageAsync(std::string_view path, const std::function& callback) { addImageAsync(path, callback, path); } @@ -170,9 +170,9 @@ void TextureCache::addImageAsync(const std::string& path, const std::function& callback, - const std::string& callbackKey) + std::string_view callbackKey) { Texture2D* texture = nullptr; @@ -223,7 +223,7 @@ void TextureCache::addImageAsync(const std::string& path, _sleepCondition.notify_one(); } -void TextureCache::unbindImageAsync(const std::string& callbackKey) +void TextureCache::unbindImageAsync(std::string_view callbackKey) { if (_asyncStructQueue.empty()) { @@ -383,7 +383,7 @@ void TextureCache::addImageAsyncCallBack(float /*dt*/) } } -Texture2D* TextureCache::addImage(const std::string& path) +Texture2D* TextureCache::addImage(std::string_view path) { Texture2D* texture = nullptr; Image* image = nullptr; @@ -422,7 +422,8 @@ Texture2D* TextureCache::addImage(const std::string& path) _textures.emplace(fullpath, texture); //-- ANDROID ETC1 ALPHA SUPPORTS. - std::string alphaFullPath = path + s_etc1AlphaFileSuffix; + std::string alphaFullPath{path}; + alphaFullPath += s_etc1AlphaFileSuffix; if (image->getFileType() == Image::Format::ETC1 && !s_etc1AlphaFileSuffix.empty() && FileUtils::getInstance()->isFileExist(alphaFullPath)) { @@ -438,7 +439,7 @@ Texture2D* TextureCache::addImage(const std::string& path) } else { - CCLOG("cocos2d: Couldn't create texture for file:%s in TextureCache", path.c_str()); + CCLOG("cocos2d: Couldn't create texture for file:%s in TextureCache", path.data()); CC_SAFE_RELEASE(texture); texture = nullptr; } @@ -450,7 +451,7 @@ Texture2D* TextureCache::addImage(const std::string& path) return texture; } -void TextureCache::parseNinePatchImage(cocos2d::Image* image, cocos2d::Texture2D* texture, const std::string& path) +void TextureCache::parseNinePatchImage(cocos2d::Image* image, cocos2d::Texture2D* texture, std::string_view path) { if (NinePatchImageParser::isNinePatchImage(path)) { @@ -460,7 +461,7 @@ void TextureCache::parseNinePatchImage(cocos2d::Image* image, cocos2d::Texture2D } } -Texture2D* TextureCache::addImage(Image* image, const std::string& key) +Texture2D* TextureCache::addImage(Image* image, std::string_view key) { CCASSERT(image != nullptr, "TextureCache: image MUST not be nil"); CCASSERT(image->getData() != nullptr, "TextureCache: image MUST not be nil"); @@ -497,7 +498,7 @@ Texture2D* TextureCache::addImage(Image* image, const std::string& key) return texture; } -bool TextureCache::reloadTexture(const std::string& fileName) +bool TextureCache::reloadTexture(std::string_view fileName) { Texture2D* texture = nullptr; @@ -585,14 +586,13 @@ void TextureCache::removeTexture(Texture2D* texture) } } -void TextureCache::removeTextureForKey(const std::string& textureKeyName) +void TextureCache::removeTextureForKey(std::string_view textureKeyName) { - std::string key = textureKeyName; - auto it = _textures.find(key); + auto it = _textures.find(textureKeyName); if (it == _textures.end()) { - key = FileUtils::getInstance()->fullPathForFilename(textureKeyName); + auto key = FileUtils::getInstance()->fullPathForFilename(textureKeyName); it = _textures.find(key); } @@ -603,14 +603,13 @@ void TextureCache::removeTextureForKey(const std::string& textureKeyName) } } -Texture2D* TextureCache::getTextureForKey(const std::string& textureKeyName) const +Texture2D* TextureCache::getTextureForKey(std::string_view textureKeyName) const { - std::string key = textureKeyName; - auto it = _textures.find(key); + auto it = _textures.find(textureKeyName); if (it == _textures.end()) { - key = FileUtils::getInstance()->fullPathForFilename(textureKeyName); + auto key = FileUtils::getInstance()->fullPathForFilename(textureKeyName); it = _textures.find(key); } @@ -676,14 +675,13 @@ std::string TextureCache::getCachedTextureInfo() const return buffer; } -void TextureCache::renameTextureWithKey(const std::string& srcName, const std::string& dstName) +void TextureCache::renameTextureWithKey(std::string_view srcName, std::string_view dstName) { - std::string key = srcName; - auto it = _textures.find(key); + auto it = _textures.find(srcName); if (it == _textures.end()) { - key = FileUtils::getInstance()->fullPathForFilename(srcName); + auto key = FileUtils::getInstance()->fullPathForFilename(srcName); it = _textures.find(key); } @@ -723,7 +721,7 @@ VolatileTexture::~VolatileTexture() CC_SAFE_RELEASE(_uiImage); } -void VolatileTextureMgr::addImageTexture(Texture2D* tt, const std::string& imageFileName) +void VolatileTextureMgr::addImageTexture(Texture2D* tt, std::string_view imageFileName) { if (_isReloading) { @@ -867,7 +865,7 @@ void VolatileTextureMgr::reloadAllTextures() } void VolatileTextureMgr::reloadTexture(Texture2D* texture, - const std::string& filename, + std::string_view filename, backend::PixelFormat pixelFormat) { if (!texture) diff --git a/cocos/renderer/CCTextureCache.h b/cocos/renderer/CCTextureCache.h index 2aca398feb..f066436758 100644 --- a/cocos/renderer/CCTextureCache.h +++ b/cocos/renderer/CCTextureCache.h @@ -64,7 +64,7 @@ class CC_DLL TextureCache : public Ref { public: // ETC1 ALPHA supports. - static void setETC1AlphaFileSuffix(const std::string& suffix); + static void setETC1AlphaFileSuffix(std::string_view suffix); static std::string getETC1AlphaFileSuffix(); public: @@ -92,7 +92,7 @@ public: * Supported image extensions: .png, .bmp, .jpeg, .pvr. @param filepath The file path. */ - Texture2D* addImage(const std::string& filepath); + Texture2D* addImage(std::string_view filepath); /** Returns a Texture2D object given a file image. * If the file image was not previously loaded, it will create a new Texture2D object and it will return it. @@ -104,11 +104,11 @@ public: @param callback A callback function would be invoked after the image is loaded. @since v0.8 */ - virtual void addImageAsync(const std::string& filepath, const std::function& callback); + virtual void addImageAsync(std::string_view filepath, const std::function& callback); - void addImageAsync(const std::string& path, + void addImageAsync(std::string_view path, const std::function& callback, - const std::string& callbackKey); + std::string_view callbackKey); /** Unbind a specified bound image asynchronous callback. * In the case an object who was bound to an image asynchronous callback was destroyed before the callback is @@ -116,7 +116,7 @@ public: * @param filename It's the related/absolute path of the file image. * @since v3.1 */ - virtual void unbindImageAsync(const std::string& filename); + virtual void unbindImageAsync(std::string_view filename); /** Unbind all bound image asynchronous load callbacks. * @since v3.1 @@ -129,13 +129,13 @@ public: * @param key The "key" parameter will be used as the "key" for the cache. * If "key" is nil, then a new texture will be created each time. */ - Texture2D* addImage(Image* image, const std::string& key); + Texture2D* addImage(Image* image, std::string_view key); /** Returns an already created texture. Returns nil if the texture doesn't exist. @param key It's the related/absolute path of the file image. @since v0.99.5 */ - Texture2D* getTextureForKey(const std::string& key) const; + Texture2D* getTextureForKey(std::string_view key) const; /** Reload texture from the image file. * If the file image hasn't loaded before, load it. @@ -143,7 +143,7 @@ public: * @param fileName It's the related/absolute path of the file image. * @return True if the reloading is succeed, otherwise return false. */ - bool reloadTexture(const std::string& fileName); + bool reloadTexture(std::string_view fileName); /** Purges the dictionary of loaded textures. * Call this method if you receive the "Memory Warning". @@ -168,7 +168,7 @@ public: @param key It's the related/absolute path of the file image. @since v0.99.4 */ - void removeTextureForKey(const std::string& key); + void removeTextureForKey(std::string_view key); /** Output to CCLOG the current contents of this TextureCache. * This will attempt to calculate the size of each texture, and the total texture memory in use. @@ -198,12 +198,12 @@ public: * * @since v3.10 */ - void renameTextureWithKey(const std::string& srcName, const std::string& dstName); + void renameTextureWithKey(std::string_view srcName, std::string_view dstName); private: void addImageAsyncCallBack(float dt); void loadImage(); - void parseNinePatchImage(Image* image, Texture2D* texture, const std::string& path); + void parseNinePatchImage(Image* image, Texture2D* texture, std::string_view path); public: protected: @@ -224,7 +224,7 @@ protected: int _asyncRefCount; - std::unordered_map _textures; + hlookup::string_map _textures; static std::string s_etc1AlphaFileSuffix; }; @@ -272,7 +272,7 @@ protected: class CC_DLL VolatileTextureMgr { public: - static void addImageTexture(Texture2D* tt, const std::string& imageFileName); + static void addImageTexture(Texture2D* tt, std::string_view imageFileName); static void addStringTexture(Texture2D* tt, const char* text, const FontDefinition& fontDefinition); static void addDataTexture(Texture2D* tt, void* data, @@ -292,7 +292,7 @@ public: static VolatileTexture* findVolotileTexture(Texture2D* tt); private: - static void reloadTexture(Texture2D* texture, const std::string& filename, backend::PixelFormat pixelFormat); + static void reloadTexture(Texture2D* texture, std::string_view filename, backend::PixelFormat pixelFormat); }; #endif diff --git a/cocos/renderer/CCTextureCube.cpp b/cocos/renderer/CCTextureCube.cpp index d7a7929cb4..9a757b2264 100644 --- a/cocos/renderer/CCTextureCube.cpp +++ b/cocos/renderer/CCTextureCube.cpp @@ -119,7 +119,7 @@ unsigned char* getImageData(Image* img, backend::PixelFormat& ePixFmt) return pTmpData; } -Image* createImage(const std::string& path) +Image* createImage(std::string_view path) { // Split up directory and filename // MUTEX: @@ -150,12 +150,12 @@ TextureCube::~TextureCube() CC_SAFE_RELEASE_NULL(_texture); } -TextureCube* TextureCube::create(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z) +TextureCube* TextureCube::create(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z) { auto ret = new TextureCube(); if (ret->init(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z)) @@ -167,12 +167,12 @@ TextureCube* TextureCube::create(const std::string& positive_x, return nullptr; } -bool TextureCube::init(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z) +bool TextureCube::init(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z) { _imgPath[0] = positive_x; _imgPath[1] = negative_x; diff --git a/cocos/renderer/CCTextureCube.h b/cocos/renderer/CCTextureCube.h index 99ee3f1c3e..578c32ecca 100644 --- a/cocos/renderer/CCTextureCube.h +++ b/cocos/renderer/CCTextureCube.h @@ -56,12 +56,12 @@ public: @param negative_z texture for the rear side of the texture cube face. @return A new texture cube inited with given parameters. */ - static TextureCube* create(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z); + static TextureCube* create(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z); /** Sets the min filter, mag filter, wrap s and wrap t texture parameters. If the texture size is NPOT (non power of 2), then in can only use GL_CLAMP_TO_EDGE in GL_TEXTURE_WRAP_{S,T}. @@ -86,12 +86,12 @@ public: virtual ~TextureCube(); protected: - bool init(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z); + bool init(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z); private: std::vector _imgPath; diff --git a/cocos/renderer/backend/Device.h b/cocos/renderer/backend/Device.h index fbf8934bc5..27a498e334 100644 --- a/cocos/renderer/backend/Device.h +++ b/cocos/renderer/backend/Device.h @@ -125,7 +125,7 @@ public: * @param fragmentShader Specifes this is a fragment shader source. * @return A Program instance. */ - virtual Program* newProgram(const std::string& vertexShader, const std::string& fragmentShader) = 0; + virtual Program* newProgram(std::string_view vertexShader, std::string_view fragmentShader) = 0; /** * Get a DeviceInfo object. @@ -140,7 +140,7 @@ protected: * @param source Specifies shader source. * @return A ShaderModule object. */ - virtual ShaderModule* newShaderModule(ShaderStage stage, const std::string& source) = 0; + virtual ShaderModule* newShaderModule(ShaderStage stage, std::string_view source) = 0; DeviceInfo* _deviceInfo = nullptr; ///< Device information. diff --git a/cocos/renderer/backend/Program.cpp b/cocos/renderer/backend/Program.cpp index 4c3da6cfaa..b92ab3d0b2 100644 --- a/cocos/renderer/backend/Program.cpp +++ b/cocos/renderer/backend/Program.cpp @@ -27,7 +27,7 @@ CC_BACKEND_BEGIN -Program::Program(const std::string& vs, const std::string& fs) : _vertexShader(vs), _fragmentShader(fs) {} +Program::Program(std::string_view vs, std::string_view fs) : _vertexShader(vs), _fragmentShader(fs) {} void Program::setProgramType(uint32_t type) { diff --git a/cocos/renderer/backend/Program.h b/cocos/renderer/backend/Program.h index 3cc20bdf21..95b655820e 100644 --- a/cocos/renderer/backend/Program.h +++ b/cocos/renderer/backend/Program.h @@ -60,7 +60,7 @@ public: * @param uniform Specifies the uniform name. * @return The uniform location. */ - virtual UniformLocation getUniformLocation(const std::string& uniform) const = 0; + virtual UniformLocation getUniformLocation(std::string_view uniform) const = 0; /** * Get uniform location by engine built-in uniform enum name. @@ -74,7 +74,7 @@ public: * @param name Specifies the attribute name. * @return The attribute location. */ - virtual int getAttributeLocation(const std::string& name) const = 0; + virtual int getAttributeLocation(std::string_view name) const = 0; /** * Get attribute location by engine built-in attribute enum name. @@ -99,19 +99,19 @@ public: * Get active vertex attributes. * @return Active vertex attributes. key is active attribute name, Value is corresponding attribute info. */ - virtual const std::unordered_map getActiveAttributes() const = 0; + virtual hlookup::string_map getActiveAttributes() const = 0; /** * Get vertex shader. * @return Vertex shader. */ - const std::string& getVertexShader() const { return _vertexShader; } + std::string_view getVertexShader() const { return _vertexShader; } /** * Get fragment shader. * @ Fragment shader. */ - const std::string& getFragmentShader() const { return _fragmentShader; } + std::string_view getFragmentShader() const { return _fragmentShader; } /** * Get engine built-in program type. @@ -138,7 +138,8 @@ public: * Get all uniformInfos. * @return The uniformInfos. */ - virtual const std::unordered_map& getAllActiveUniformInfo(ShaderStage stage) const = 0; + virtual const hlookup::string_map& getAllActiveUniformInfo( + ShaderStage stage) const = 0; /** * Set engin built-in program type. @@ -151,7 +152,7 @@ protected: * @param vs Specifes the vertex shader source. * @param fs Specifes the fragment shader source. */ - Program(const std::string& vs, const std::string& fs); + Program(std::string_view vs, std::string_view fs); #if CC_ENABLE_CACHE_TEXTURE_DATA /** diff --git a/cocos/renderer/backend/ProgramState.cpp b/cocos/renderer/backend/ProgramState.cpp index 8eacbc2bb6..79e036e3e0 100644 --- a/cocos/renderer/backend/ProgramState.cpp +++ b/cocos/renderer/backend/ProgramState.cpp @@ -263,7 +263,7 @@ backend::UniformLocation ProgramState::getUniformLocation(backend::Uniform name) return _program->getUniformLocation(name); } -backend::UniformLocation ProgramState::getUniformLocation(const std::string& uniform) const +backend::UniformLocation ProgramState::getUniformLocation(std::string_view uniform) const { return _program->getUniformLocation(uniform); } @@ -514,13 +514,13 @@ void ProgramState::setTextureArray(int location, #endif } -void ProgramState::setParameterAutoBinding(const std::string& uniform, const std::string& autoBinding) +void ProgramState::setParameterAutoBinding(std::string_view uniform, std::string_view autoBinding) { _autoBindings.emplace(uniform, autoBinding); applyAutoBinding(uniform, autoBinding); } -void ProgramState::applyAutoBinding(const std::string& uniformName, const std::string& autoBinding) +void ProgramState::applyAutoBinding(std::string_view uniformName, std::string_view autoBinding) { for (const auto resolver : _customAutoBindingResolvers) { diff --git a/cocos/renderer/backend/ProgramState.h b/cocos/renderer/backend/ProgramState.h index 7a5f756e61..d1c8cb272d 100644 --- a/cocos/renderer/backend/ProgramState.h +++ b/cocos/renderer/backend/ProgramState.h @@ -124,7 +124,7 @@ public: * @return Uniform location. * @see `backend::UniformLocation getUniformLocation(backend::Uniform name) const` */ - backend::UniformLocation getUniformLocation(const std::string& uniform) const; + backend::UniformLocation getUniformLocation(std::string_view uniform) const; /** * Get uniform location in a more efficient way by the given built-in uniform name. @@ -138,15 +138,15 @@ public: * Get an attribute location by the actual attribute name. * @param name Specifies the attribute name. * @return Attribute location. - * @see `int getAttributeLocation(const std::string& name) const` + * @see `int getAttributeLocation(std::string_view name) const` */ - inline int getAttributeLocation(const std::string& name) const { return _program->getAttributeLocation(name); } + inline int getAttributeLocation(std::string_view name) const { return _program->getAttributeLocation(name); } /** * Get an attribute location by the engine built-in attribute name. * @param name Specifies the built-in attribute name. * @return Attribute location. - * @see `int getAttributeLocation(const std::string& name) const` + * @see `int getAttributeLocation(std::string_view name) const` */ inline int getAttributeLocation(Attribute name) const { return _program->getAttributeLocation(name); } @@ -279,8 +279,8 @@ public: * bound, false otherwise. */ virtual bool resolveAutoBinding(ProgramState*, - const std::string& uniformName, - const std::string& autoBinding) = 0; + std::string_view uniformName, + std::string_view autoBinding) = 0; }; /** * Sets a uniform auto-binding. @@ -292,7 +292,7 @@ public: * @param uniformName The name of the material parameter to store an auto-binding for. * @param autoBinding A string matching one of the built-in AutoBinding enum constants. */ - void setParameterAutoBinding(const std::string& uniformName, const std::string& autoBinding); + void setParameterAutoBinding(std::string_view uniformName, std::string_view autoBinding); inline std::shared_ptr getVertexLayout() const { return _vertexLayout; } @@ -379,7 +379,7 @@ protected: * @param uniformName Name of the shader uniform. * @param autoBinding Name of the auto binding. */ - void applyAutoBinding(const std::string&, const std::string&); + void applyAutoBinding(std::string_view, std::string_view); backend::Program* _program = nullptr; std::unordered_map _callbackUniforms; diff --git a/cocos/renderer/backend/ShaderCache.cpp b/cocos/renderer/backend/ShaderCache.cpp index 7d92c21ba7..149fc2fcb7 100644 --- a/cocos/renderer/backend/ShaderCache.cpp +++ b/cocos/renderer/backend/ShaderCache.cpp @@ -62,21 +62,21 @@ bool ShaderCache::init() return true; } -backend::ShaderModule* ShaderCache::newVertexShaderModule(const std::string& shaderSource) +backend::ShaderModule* ShaderCache::newVertexShaderModule(std::string_view shaderSource) { auto vertexShaderModule = newShaderModule(backend::ShaderStage::VERTEX, shaderSource); return vertexShaderModule; } -backend::ShaderModule* ShaderCache::newFragmentShaderModule(const std::string& shaderSource) +backend::ShaderModule* ShaderCache::newFragmentShaderModule(std::string_view shaderSource) { auto fragmenShaderModule = newShaderModule(backend::ShaderStage::FRAGMENT, shaderSource); return fragmenShaderModule; } -backend::ShaderModule* ShaderCache::newShaderModule(backend::ShaderStage stage, const std::string& shaderSource) +backend::ShaderModule* ShaderCache::newShaderModule(backend::ShaderStage stage, std::string_view shaderSource) { - std::size_t key = std::hash{}(shaderSource); + std::size_t key = std::hash{}(shaderSource); auto iter = _cachedShaders.find(key); if (_cachedShaders.end() != iter) return iter->second; diff --git a/cocos/renderer/backend/ShaderCache.h b/cocos/renderer/backend/ShaderCache.h index d5daf870ae..87709042f5 100644 --- a/cocos/renderer/backend/ShaderCache.h +++ b/cocos/renderer/backend/ShaderCache.h @@ -54,14 +54,14 @@ public: * If it is created before, then just return the cached shader module. * @param shaderSource The source code of the shader. */ - static backend::ShaderModule* newVertexShaderModule(const std::string& shaderSource); + static backend::ShaderModule* newVertexShaderModule(std::string_view shaderSource); /** * Create a fragment shader module. * If it is created before, then just return the cached shader module. * @param shaderSource The source code of the shader. */ - static backend::ShaderModule* newFragmentShaderModule(const std::string& shaderSource); + static backend::ShaderModule* newFragmentShaderModule(std::string_view shaderSource); /** * Remove all unused shaders. @@ -85,7 +85,7 @@ protected: * @param source Specifies shader source. * @return A ShaderModule object. */ - static backend::ShaderModule* newShaderModule(backend::ShaderStage stage, const std::string& shaderSource); + static backend::ShaderModule* newShaderModule(backend::ShaderStage stage, std::string_view shaderSource); static std::unordered_map _cachedShaders; static ShaderCache* _sharedShaderCache; diff --git a/cocos/renderer/backend/VertexLayout.cpp b/cocos/renderer/backend/VertexLayout.cpp index 044a2661c0..ad8f48ab89 100644 --- a/cocos/renderer/backend/VertexLayout.cpp +++ b/cocos/renderer/backend/VertexLayout.cpp @@ -28,7 +28,7 @@ CC_BACKEND_BEGIN -void VertexLayout::setAttribute(const std::string& name, +void VertexLayout::setAttribute(std::string_view name, std::size_t index, VertexFormat format, std::size_t offset, @@ -37,7 +37,11 @@ void VertexLayout::setAttribute(const std::string& name, if (index == -1) return; - _attributes[name] = {name, index, format, offset, needToBeNormallized}; + // FIXME 2021/12/25 TODO: store name key is enough + hlookup::set_item( + _attributes, name, + Attribute{name, index, format, offset, + needToBeNormallized}); // _attributes[name] = {name, index, format, offset, needToBeNormallized}; } void VertexLayout::setLayout(std::size_t stride) diff --git a/cocos/renderer/backend/VertexLayout.h b/cocos/renderer/backend/VertexLayout.h index e3b33746e4..3c11bf49f3 100644 --- a/cocos/renderer/backend/VertexLayout.h +++ b/cocos/renderer/backend/VertexLayout.h @@ -48,7 +48,7 @@ public: struct Attribute { Attribute() = default; - Attribute(const std::string& _name, + Attribute(std::string_view _name, std::size_t _index, VertexFormat _format, std::size_t _offset, @@ -74,7 +74,7 @@ public: * @param needToBeNormallized Specifies whether fixed-point data values should be normalized (true) or converted * directly as fixed-point values (false) when they are accessed. */ - void setAttribute(const std::string& name, + void setAttribute(std::string_view name, std::size_t index, VertexFormat format, std::size_t offset, @@ -103,7 +103,7 @@ public: * Get attribute informations * @return Atrribute informations. */ - inline const std::unordered_map& getAttributes() const { return _attributes; } + inline const hlookup::string_map& getAttributes() const { return _attributes; } /** * Check if vertex layout has been set. @@ -111,7 +111,7 @@ public: inline bool isValid() const { return _stride != 0; } private: - std::unordered_map _attributes; + hlookup::string_map _attributes; std::size_t _stride = 0; VertexStepMode _stepMode = VertexStepMode::VERTEX; }; diff --git a/cocos/renderer/backend/metal/DeviceMTL.h b/cocos/renderer/backend/metal/DeviceMTL.h index fac8be126d..10cfdd30f2 100644 --- a/cocos/renderer/backend/metal/DeviceMTL.h +++ b/cocos/renderer/backend/metal/DeviceMTL.h @@ -133,7 +133,7 @@ public: * @param fragmentShader Specifes this is a fragment shader source. * @return A Program instance. */ - virtual Program* newProgram(const std::string& vertexShader, const std::string& fragmentShader) override; + virtual Program* newProgram(std::string_view vertexShader, std::string_view fragmentShader) override; /** * Get a MTLDevice object. @@ -154,7 +154,7 @@ protected: * @param source Specifies shader source. * @return A ShaderModule object. */ - virtual ShaderModule* newShaderModule(ShaderStage stage, const std::string& source) override; + virtual ShaderModule* newShaderModule(ShaderStage stage, std::string_view source) override; private: static CAMetalLayer* _metalLayer; diff --git a/cocos/renderer/backend/metal/DeviceMTL.mm b/cocos/renderer/backend/metal/DeviceMTL.mm index 174e2807a9..e5f7feafef 100644 --- a/cocos/renderer/backend/metal/DeviceMTL.mm +++ b/cocos/renderer/backend/metal/DeviceMTL.mm @@ -131,7 +131,7 @@ RenderTarget* DeviceMTL::newRenderTarget(TargetBufferFlags rtf, return rtGL; } -ShaderModule* DeviceMTL::newShaderModule(ShaderStage stage, const std::string& source) +ShaderModule* DeviceMTL::newShaderModule(ShaderStage stage, std::string_view source) { return new ShaderModuleMTL(_mtlDevice, stage, source); } @@ -146,7 +146,7 @@ RenderPipeline* DeviceMTL::newRenderPipeline() return new RenderPipelineMTL(_mtlDevice); } -Program* DeviceMTL::newProgram(const std::string& vertexShader, const std::string& fragmentShader) +Program* DeviceMTL::newProgram(std::string_view vertexShader, std::string_view fragmentShader) { return new ProgramMTL(vertexShader, fragmentShader); } diff --git a/cocos/renderer/backend/metal/ProgramMTL.h b/cocos/renderer/backend/metal/ProgramMTL.h index 0b014941bd..014a377432 100644 --- a/cocos/renderer/backend/metal/ProgramMTL.h +++ b/cocos/renderer/backend/metal/ProgramMTL.h @@ -47,7 +47,7 @@ public: * @param vertexShader Specifes the vertex shader source. * @param fragmentShader Specifes the fragment shader source. */ - ProgramMTL(const std::string& vertexShader, const std::string& fragmentShader); + ProgramMTL(std::string_view vertexShader, std::string_view fragmentShader); virtual ~ProgramMTL(); /** @@ -55,7 +55,7 @@ public: * @param uniform Specifies the uniform name. * @return The uniform location. */ - virtual UniformLocation getUniformLocation(const std::string& uniform) const override; + virtual UniformLocation getUniformLocation(std::string_view uniform) const override; /** * Get uniform location by engine built-in uniform enum name. @@ -69,7 +69,7 @@ public: * @param name Specifies the attribute name. * @return The attribute location. */ - virtual int getAttributeLocation(const std::string& name) const override; + virtual int getAttributeLocation(std::string_view name) const override; /** * Get attribute location by engine built-in attribute enum name. diff --git a/cocos/renderer/backend/metal/ProgramMTL.mm b/cocos/renderer/backend/metal/ProgramMTL.mm index d1f2cb7a86..ebf19caa62 100644 --- a/cocos/renderer/backend/metal/ProgramMTL.mm +++ b/cocos/renderer/backend/metal/ProgramMTL.mm @@ -31,7 +31,7 @@ namespace { const std::string metalSpecificDefine = "#define METAL\n"; } -ProgramMTL::ProgramMTL(const std::string& vertexShader, const std::string& fragmentShader) +ProgramMTL::ProgramMTL(std::string_view vertexShader, std::string_view fragmentShader) : Program(vertexShader, fragmentShader) { _vertexShader = static_cast(ShaderCache::newVertexShaderModule(vertexShader)); @@ -81,7 +81,7 @@ UniformLocation ProgramMTL::getUniformLocation(backend::Uniform name) const return uniformLocation; } -UniformLocation ProgramMTL::getUniformLocation(const std::string& uniform) const +UniformLocation ProgramMTL::getUniformLocation(std::string_view uniform) const { UniformLocation uniformLocation; auto vsLocation = _vertexShader->getUniformLocation(uniform); diff --git a/cocos/renderer/backend/metal/ShaderModuleMTL.h b/cocos/renderer/backend/metal/ShaderModuleMTL.h index 1272c3b409..274bbffac2 100644 --- a/cocos/renderer/backend/metal/ShaderModuleMTL.h +++ b/cocos/renderer/backend/metal/ShaderModuleMTL.h @@ -52,7 +52,7 @@ public: * @param stage Specify what kinds of shader to be created. * @param source Specify the shader source. */ - ShaderModuleMTL(id mtlDevice, ShaderStage stage, const std::string& source); + ShaderModuleMTL(id mtlDevice, ShaderStage stage, std::string_view source); ~ShaderModuleMTL(); /** @@ -97,7 +97,7 @@ public: * @param uniform Specifies the uniform name. * @return The uniform location. */ - int getUniformLocation(const std::string& name) const; + int getUniformLocation(std::string_view name) const; /** * Get attribute location by engine built-in attribute enum name. diff --git a/cocos/renderer/backend/metal/ShaderModuleMTL.mm b/cocos/renderer/backend/metal/ShaderModuleMTL.mm index d0f8291a41..00782d8eb4 100644 --- a/cocos/renderer/backend/metal/ShaderModuleMTL.mm +++ b/cocos/renderer/backend/metal/ShaderModuleMTL.mm @@ -29,7 +29,7 @@ CC_BACKEND_BEGIN -ShaderModuleMTL::ShaderModuleMTL(id mtlDevice, ShaderStage stage, const std::string& source) +ShaderModuleMTL::ShaderModuleMTL(id mtlDevice, ShaderStage stage, std::string_view source) : ShaderModule(stage) { // Convert GLSL shader to metal shader @@ -159,7 +159,7 @@ int ShaderModuleMTL::getUniformLocation(Uniform name) const return _uniformLocation[name]; } -int ShaderModuleMTL::getUniformLocation(const std::string& name) const +int ShaderModuleMTL::getUniformLocation(std::string_view name) const { const auto& iter = _uniformInfos.find(name); if(iter != _uniformInfos.end()) diff --git a/cocos/renderer/backend/opengl/DeviceGL.cpp b/cocos/renderer/backend/opengl/DeviceGL.cpp index 0be7eab52c..6f7b8b07b6 100644 --- a/cocos/renderer/backend/opengl/DeviceGL.cpp +++ b/cocos/renderer/backend/opengl/DeviceGL.cpp @@ -112,7 +112,7 @@ RenderTarget* DeviceGL::newRenderTarget(TargetBufferFlags rtf, return rtGL; } -ShaderModule* DeviceGL::newShaderModule(ShaderStage stage, const std::string& source) +ShaderModule* DeviceGL::newShaderModule(ShaderStage stage, std::string_view source) { return new ShaderModuleGL(stage, source); } @@ -127,7 +127,7 @@ RenderPipeline* DeviceGL::newRenderPipeline() return new RenderPipelineGL(); } -Program* DeviceGL::newProgram(const std::string& vertexShader, const std::string& fragmentShader) +Program* DeviceGL::newProgram(std::string_view vertexShader, std::string_view fragmentShader) { return new ProgramGL(vertexShader, fragmentShader); } diff --git a/cocos/renderer/backend/opengl/DeviceGL.h b/cocos/renderer/backend/opengl/DeviceGL.h index edf20369c9..80ea348350 100644 --- a/cocos/renderer/backend/opengl/DeviceGL.h +++ b/cocos/renderer/backend/opengl/DeviceGL.h @@ -92,7 +92,7 @@ public: * @param fragmentShader Specifes this is a fragment shader source. * @return A Program instance. */ - virtual Program* newProgram(const std::string& vertexShader, const std::string& fragmentShader) override; + virtual Program* newProgram(std::string_view vertexShader, std::string_view fragmentShader) override; protected: /** @@ -101,7 +101,7 @@ protected: * @param source Specifies shader source. * @return A ShaderModule object. */ - virtual ShaderModule* newShaderModule(ShaderStage stage, const std::string& source) override; + virtual ShaderModule* newShaderModule(ShaderStage stage, std::string_view source) override; GLint _defaultFBO = 0; // The value gets from glGetIntegerv, so need to use GLint }; diff --git a/cocos/renderer/backend/opengl/DeviceInfoGL.cpp b/cocos/renderer/backend/opengl/DeviceInfoGL.cpp index 1c2e5b89c1..1c68c04c6f 100644 --- a/cocos/renderer/backend/opengl/DeviceInfoGL.cpp +++ b/cocos/renderer/backend/opengl/DeviceInfoGL.cpp @@ -169,7 +169,7 @@ bool DeviceInfoGL::checkForFeatureSupported(FeatureType feature) return featureSupported; } -bool DeviceInfoGL::checkForGLExtension(const std::string& searchName) const +bool DeviceInfoGL::checkForGLExtension(std::string_view searchName) const { return _glExtensions.find(searchName) != std::string::npos; } diff --git a/cocos/renderer/backend/opengl/DeviceInfoGL.h b/cocos/renderer/backend/opengl/DeviceInfoGL.h index 23c56727bc..ec11777c48 100644 --- a/cocos/renderer/backend/opengl/DeviceInfoGL.h +++ b/cocos/renderer/backend/opengl/DeviceInfoGL.h @@ -79,7 +79,7 @@ public: virtual bool checkForFeatureSupported(FeatureType feature) override; private: - bool checkForGLExtension(const std::string& searchName) const; + bool checkForGLExtension(std::string_view searchName) const; static bool checkSupportsCompressedFormat(int compressedFormat); diff --git a/cocos/renderer/backend/opengl/ProgramGL.cpp b/cocos/renderer/backend/opengl/ProgramGL.cpp index e1908f2ad0..7a8702a93e 100644 --- a/cocos/renderer/backend/opengl/ProgramGL.cpp +++ b/cocos/renderer/backend/opengl/ProgramGL.cpp @@ -39,7 +39,7 @@ namespace static const std::string SHADER_PREDEFINE = "#version 100\n precision highp float;\n precision highp int;\n"; } -ProgramGL::ProgramGL(const std::string& vertexShader, const std::string& fragmentShader) +ProgramGL::ProgramGL(std::string_view vertexShader, std::string_view fragmentShader) : Program(vertexShader, fragmentShader) { #if defined(CC_USE_GLES) @@ -197,12 +197,12 @@ void ProgramGL::computeLocations() _builtinUniformLocation[Uniform::TEXTURE1].location[0] = location; } -bool ProgramGL::getAttributeLocation(const std::string& attributeName, unsigned int& location) const +bool ProgramGL::getAttributeLocation(std::string_view attributeName, unsigned int& location) const { - GLint loc = glGetAttribLocation(_program, attributeName.c_str()); + GLint loc = glGetAttribLocation(_program, attributeName.data()); if (-1 == loc) { - CCLOG("Cocos2d: %s: can not find vertex attribute of %s", __FUNCTION__, attributeName.c_str()); + CCLOG("Cocos2d: %s: can not find vertex attribute of %s", __FUNCTION__, attributeName.data()); return false; } @@ -210,9 +210,9 @@ bool ProgramGL::getAttributeLocation(const std::string& attributeName, unsigned return true; } -const std::unordered_map ProgramGL::getActiveAttributes() const +hlookup::string_map ProgramGL::getActiveAttributes() const { - std::unordered_map attributes; + hlookup::string_map attributes; if (!_program) return attributes; @@ -293,9 +293,9 @@ int ProgramGL::getAttributeLocation(Attribute name) const return _builtinAttributeLocation[name]; } -int ProgramGL::getAttributeLocation(const std::string& name) const +int ProgramGL::getAttributeLocation(std::string_view name) const { - return glGetAttribLocation(_program, name.c_str()); + return glGetAttribLocation(_program, name.data()); } UniformLocation ProgramGL::getUniformLocation(backend::Uniform name) const @@ -303,7 +303,7 @@ UniformLocation ProgramGL::getUniformLocation(backend::Uniform name) const return _builtinUniformLocation[name]; } -UniformLocation ProgramGL::getUniformLocation(const std::string& uniform) const +UniformLocation ProgramGL::getUniformLocation(std::string_view uniform) const { UniformLocation uniformLocation; if (_activeUniformInfos.find(uniform) != _activeUniformInfos.end()) @@ -352,7 +352,7 @@ const UniformInfo& ProgramGL::getActiveUniformInfo(ShaderStage stage, int locati return s_emptyInfo; } -const std::unordered_map& ProgramGL::getAllActiveUniformInfo(ShaderStage stage) const +const hlookup::string_map& ProgramGL::getAllActiveUniformInfo(ShaderStage stage) const { return _activeUniformInfos; } diff --git a/cocos/renderer/backend/opengl/ProgramGL.h b/cocos/renderer/backend/opengl/ProgramGL.h index 25be64d6f5..62e13b5c86 100644 --- a/cocos/renderer/backend/opengl/ProgramGL.h +++ b/cocos/renderer/backend/opengl/ProgramGL.h @@ -68,7 +68,7 @@ public: * @param vertexShader Specifes the vertex shader source. * @param fragmentShader Specifes the fragment shader source. */ - ProgramGL(const std::string& vertexShader, const std::string& fragmentShader); + ProgramGL(std::string_view vertexShader, std::string_view fragmentShader); ~ProgramGL(); @@ -89,7 +89,7 @@ public: * @param uniform Specifies the uniform name. * @return The uniform location. */ - virtual UniformLocation getUniformLocation(const std::string& uniform) const override; + virtual UniformLocation getUniformLocation(std::string_view uniform) const override; /** * Get uniform location by engine built-in uniform enum name. @@ -103,7 +103,7 @@ public: * @param name Specifies the attribute name. * @return The attribute location. */ - virtual int getAttributeLocation(const std::string& name) const override; + virtual int getAttributeLocation(std::string_view name) const override; /** * Get attribute location by engine built-in attribute enum name. @@ -128,7 +128,7 @@ public: * Get active vertex attributes. * @return Active vertex attributes. key is active attribute name, Value is corresponding attribute info. */ - virtual const std::unordered_map getActiveAttributes() const override; + virtual hlookup::string_map getActiveAttributes() const override; /** * Get uniform buffer size in bytes that can hold all the uniforms. @@ -149,12 +149,12 @@ public: * Get all uniformInfos. * @return The uniformInfos. */ - virtual const std::unordered_map& getAllActiveUniformInfo( + virtual const hlookup::string_map& getAllActiveUniformInfo( ShaderStage stage) const override; private: void compileProgram(); - bool getAttributeLocation(const std::string& attributeName, unsigned int& location) const; + bool getAttributeLocation(std::string_view attributeName, unsigned int& location) const; void computeUniformInfos(); void computeLocations(); #if CC_ENABLE_CACHE_TEXTURE_DATA @@ -172,7 +172,7 @@ private: ShaderModuleGL* _fragmentShaderModule = nullptr; std::vector _attributeInfos; - std::unordered_map _activeUniformInfos; + hlookup::string_map _activeUniformInfos; #if CC_ENABLE_CACHE_TEXTURE_DATA std::unordered_map _originalUniformLocations; ///< record the uniform location when shader was first created. diff --git a/cocos/renderer/backend/opengl/ShaderModuleGL.cpp b/cocos/renderer/backend/opengl/ShaderModuleGL.cpp index 23c1a1629b..3b6f49e6dd 100644 --- a/cocos/renderer/backend/opengl/ShaderModuleGL.cpp +++ b/cocos/renderer/backend/opengl/ShaderModuleGL.cpp @@ -31,7 +31,7 @@ CC_BACKEND_BEGIN -ShaderModuleGL::ShaderModuleGL(ShaderStage stage, const std::string& source) : ShaderModule(stage) +ShaderModuleGL::ShaderModuleGL(ShaderStage stage, std::string_view source) : ShaderModule(stage) { compileShader(stage, source); } @@ -41,10 +41,10 @@ ShaderModuleGL::~ShaderModuleGL() deleteShader(); } -void ShaderModuleGL::compileShader(ShaderStage stage, const std::string& source) +void ShaderModuleGL::compileShader(ShaderStage stage, std::string_view source) { GLenum shaderType = stage == ShaderStage::VERTEX ? GL_VERTEX_SHADER : GL_FRAGMENT_SHADER; - const GLchar* sourcePtr = reinterpret_cast(source.c_str()); + const GLchar* sourcePtr = reinterpret_cast(source.data()); _shader = glCreateShader(shaderType); if (!_shader) return; @@ -64,7 +64,7 @@ void ShaderModuleGL::compileShader(ShaderStage stage, const std::string& source) cocos2d::Data errorLog{}; glGetShaderInfoLog(_shader, logLength, nullptr, (GLchar*)errorLog.resize(logLength)); cocos2d::log("cocos2d: ERROR: Failed to compile shader, detail: %s\n%s", errorLog.getBytes(), - source.c_str()); + source.data()); } else { diff --git a/cocos/renderer/backend/opengl/ShaderModuleGL.h b/cocos/renderer/backend/opengl/ShaderModuleGL.h index 5bae6962bb..81ea52691a 100644 --- a/cocos/renderer/backend/opengl/ShaderModuleGL.h +++ b/cocos/renderer/backend/opengl/ShaderModuleGL.h @@ -44,7 +44,7 @@ public: * @param stage Specifies whether is vertex shader or fragment shader. * @param source Specifies shader source. */ - ShaderModuleGL(ShaderStage stage, const std::string& source); + ShaderModuleGL(ShaderStage stage, std::string_view source); ~ShaderModuleGL(); /** @@ -54,7 +54,7 @@ public: inline GLuint getShader() const { return _shader; } private: - void compileShader(ShaderStage stage, const std::string& source); + void compileShader(ShaderStage stage, std::string_view source); void deleteShader(); GLuint _shader = 0; diff --git a/cocos/ui/UIAbstractCheckButton.cpp b/cocos/ui/UIAbstractCheckButton.cpp index aec8a369de..412a33b46b 100644 --- a/cocos/ui/UIAbstractCheckButton.cpp +++ b/cocos/ui/UIAbstractCheckButton.cpp @@ -73,11 +73,11 @@ AbstractCheckButton::AbstractCheckButton() AbstractCheckButton::~AbstractCheckButton() {} -bool AbstractCheckButton::init(const std::string& backGround, - const std::string& backGroundSelected, - const std::string& cross, - const std::string& backGroundDisabled, - const std::string& frontCrossDisabled, +bool AbstractCheckButton::init(std::string_view backGround, + std::string_view backGroundSelected, + std::string_view cross, + std::string_view backGroundDisabled, + std::string_view frontCrossDisabled, TextureResType texType) { bool ret = true; @@ -120,11 +120,11 @@ void AbstractCheckButton::initRenderer() addProtectedChild(_frontCrossDisabledRenderer, FRONTCROSSDISABLED_RENDERER_Z, -1); } -void AbstractCheckButton::loadTextures(const std::string& backGround, - const std::string& backGroundSelected, - const std::string& cross, - const std::string& backGroundDisabled, - const std::string& frontCrossDisabled, +void AbstractCheckButton::loadTextures(std::string_view backGround, + std::string_view backGroundSelected, + std::string_view cross, + std::string_view backGroundDisabled, + std::string_view frontCrossDisabled, TextureResType texType) { loadTextureBackGround(backGround, texType); @@ -134,7 +134,7 @@ void AbstractCheckButton::loadTextures(const std::string& backGround, loadTextureFrontCrossDisabled(frontCrossDisabled, texType); } -void AbstractCheckButton::loadTextureBackGround(const std::string& backGround, TextureResType texType) +void AbstractCheckButton::loadTextureBackGround(std::string_view backGround, TextureResType texType) { _backGroundFileName = backGround; @@ -169,7 +169,7 @@ void AbstractCheckButton::loadTextureBackGround(SpriteFrame* spriteFrame) this->setupBackgroundTexture(); } -void AbstractCheckButton::loadTextureBackGroundSelected(const std::string& backGroundSelected, TextureResType texType) +void AbstractCheckButton::loadTextureBackGroundSelected(std::string_view backGroundSelected, TextureResType texType) { _backGroundSelectedFileName = backGroundSelected; _isBackgroundSelectedTextureLoaded = !backGroundSelected.empty(); @@ -203,7 +203,7 @@ void AbstractCheckButton::setupBackgroundSelectedTexture() _backGroundSelectedBoxRendererAdaptDirty = true; } -void AbstractCheckButton::loadTextureFrontCross(const std::string& cross, TextureResType texType) +void AbstractCheckButton::loadTextureFrontCross(std::string_view cross, TextureResType texType) { _frontCrossFileName = cross; @@ -234,7 +234,7 @@ void AbstractCheckButton::setupFrontCrossTexture() _frontCrossRendererAdaptDirty = true; } -void AbstractCheckButton::loadTextureBackGroundDisabled(const std::string& backGroundDisabled, TextureResType texType) +void AbstractCheckButton::loadTextureBackGroundDisabled(std::string_view backGroundDisabled, TextureResType texType) { _backGroundDisabledFileName = backGroundDisabled; _isBackgroundDisabledTextureLoaded = !backGroundDisabled.empty(); @@ -269,7 +269,7 @@ void AbstractCheckButton::setupBackgroundDisable() _backGroundBoxDisabledRendererAdaptDirty = true; } -void AbstractCheckButton::loadTextureFrontCrossDisabled(const std::string& frontCrossDisabled, TextureResType texType) +void AbstractCheckButton::loadTextureFrontCrossDisabled(std::string_view frontCrossDisabled, TextureResType texType) { _frontCrossDisabledFileName = frontCrossDisabled; _isFrontCrossDisabledTextureLoaded = !frontCrossDisabled.empty(); diff --git a/cocos/ui/UIAbstractCheckButton.h b/cocos/ui/UIAbstractCheckButton.h index 38f97b046a..7d801dba76 100644 --- a/cocos/ui/UIAbstractCheckButton.h +++ b/cocos/ui/UIAbstractCheckButton.h @@ -57,11 +57,11 @@ public: * @param frontCrossDisabled The front cross disabled state image name. * @param texType @see `Widget::TextureResType` */ - void loadTextures(const std::string& background, - const std::string& backgroundSelected, - const std::string& cross, - const std::string& backgroundDisabled, - const std::string& frontCrossDisabled, + void loadTextures(std::string_view background, + std::string_view backgroundSelected, + std::string_view cross, + std::string_view backgroundDisabled, + std::string_view frontCrossDisabled, TextureResType texType = TextureResType::LOCAL); /** @@ -70,7 +70,7 @@ public: * @param backGround The background image name. * @param type @see `Widget::TextureResType` */ - void loadTextureBackGround(const std::string& backGround, TextureResType type = TextureResType::LOCAL); + void loadTextureBackGround(std::string_view backGround, TextureResType type = TextureResType::LOCAL); /** * Load background selected state texture for check button. @@ -78,7 +78,7 @@ public: * @param backGroundSelected The background selected state image name. * @param texType @see `Widget::TextureResType` */ - void loadTextureBackGroundSelected(const std::string& backGroundSelected, + void loadTextureBackGroundSelected(std::string_view backGroundSelected, TextureResType texType = TextureResType::LOCAL); /** @@ -87,7 +87,7 @@ public: * @param crossTextureName The cross texture name. * @param texType @see `Widget::TextureResType` */ - void loadTextureFrontCross(const std::string& crossTextureName, TextureResType texType = TextureResType::LOCAL); + void loadTextureFrontCross(std::string_view crossTextureName, TextureResType texType = TextureResType::LOCAL); /** * Load background disabled state texture for checkbox. @@ -96,7 +96,7 @@ public: * * @param texType @see `Widget::TextureResType` */ - void loadTextureBackGroundDisabled(const std::string& backGroundDisabled, + void loadTextureBackGroundDisabled(std::string_view backGroundDisabled, TextureResType texType = TextureResType::LOCAL); /** @@ -105,7 +105,7 @@ public: * @param frontCrossDisabled The front cross disabled state texture name. * @param texType @see `Widget::TextureResType` */ - void loadTextureFrontCrossDisabled(const std::string& frontCrossDisabled, + void loadTextureFrontCrossDisabled(std::string_view frontCrossDisabled, TextureResType texType = TextureResType::LOCAL); /** @@ -174,11 +174,11 @@ public: ResourceData getCrossDisabledFile(); CC_CONSTRUCTOR_ACCESS : virtual bool init() override; - virtual bool init(const std::string& backGround, - const std::string& backGroundSelected, - const std::string& cross, - const std::string& backGroundDisabled, - const std::string& frontCrossDisabled, + virtual bool init(std::string_view backGround, + std::string_view backGroundSelected, + std::string_view cross, + std::string_view backGroundDisabled, + std::string_view frontCrossDisabled, TextureResType texType = TextureResType::LOCAL); protected: diff --git a/cocos/ui/UIButton.cpp b/cocos/ui/UIButton.cpp index 8b2025a1a7..195bdde8eb 100644 --- a/cocos/ui/UIButton.cpp +++ b/cocos/ui/UIButton.cpp @@ -92,9 +92,9 @@ Button* Button::create() return nullptr; } -Button* Button::create(const std::string& normalImage, - const std::string& selectedImage, - const std::string& disableImage, +Button* Button::create(std::string_view normalImage, + std::string_view selectedImage, + std::string_view disableImage, TextureResType texType) { Button* btn = new Button; @@ -107,9 +107,9 @@ Button* Button::create(const std::string& normalImage, return nullptr; } -bool Button::init(const std::string& normalImage, - const std::string& selectedImage, - const std::string& disableImage, +bool Button::init(std::string_view normalImage, + std::string_view selectedImage, + std::string_view disableImage, TextureResType texType) { @@ -250,9 +250,9 @@ void Button::ignoreContentAdaptWithSize(bool ignore) } } -void Button::loadTextures(const std::string& normal, - const std::string& selected, - const std::string& disabled, +void Button::loadTextures(std::string_view normal, + std::string_view selected, + std::string_view disabled, TextureResType texType) { loadTextureNormal(normal, texType); @@ -260,7 +260,7 @@ void Button::loadTextures(const std::string& normal, loadTextureDisabled(disabled, texType); } -void Button::loadTextureNormal(const std::string& normal, TextureResType texType) +void Button::loadTextureNormal(std::string_view normal, TextureResType texType) { _normalFileName = normal; _normalTexType = texType; @@ -319,7 +319,7 @@ void Button::loadTextureNormal(SpriteFrame* normalSpriteFrame) this->setupNormalTexture(nullptr != normalSpriteFrame); } -void Button::loadTexturePressed(const std::string& selected, TextureResType texType) +void Button::loadTexturePressed(std::string_view selected, TextureResType texType) { _clickedFileName = selected; _pressedTexType = texType; @@ -362,7 +362,7 @@ void Button::loadTexturePressed(SpriteFrame* pressedSpriteFrame) this->setupPressedTexture(nullptr != pressedSpriteFrame); } -void Button::loadTextureDisabled(const std::string& disabled, TextureResType texType) +void Button::loadTextureDisabled(std::string_view disabled, TextureResType texType) { _disabledFileName = disabled; _disabledTexType = texType; @@ -718,7 +718,7 @@ void Button::setTitleAlignment(TextHAlignment hAlignment, TextVAlignment vAlignm _titleRenderer->setAlignment(hAlignment, vAlignment); } -void Button::setTitleText(const std::string& text) +void Button::setTitleText(std::string_view text) { if (text.compare(getTitleText()) == 0) { @@ -737,7 +737,7 @@ void Button::setTitleText(const std::string& text) updateTitleLocation(); } -std::string Button::getTitleText() const +std::string_view Button::getTitleText() const { if (!_titleRenderer) { @@ -806,13 +806,13 @@ float Button::getZoomScale() const return _zoomScale; } -void Button::setTitleFontName(const std::string& fontName) +void Button::setTitleFontName(std::string_view fontName) { createTitleRendererIfNull(); if (FileUtils::getInstance()->isFileExist(fontName)) { - std::string lowerCasedFontName = fontName; + std::string lowerCasedFontName{fontName}; std::transform(lowerCasedFontName.begin(), lowerCasedFontName.end(), lowerCasedFontName.begin(), ::tolower); if (lowerCasedFontName.find(".fnt") != std::string::npos) { @@ -838,7 +838,7 @@ Label* Button::getTitleRenderer() const return _titleRenderer; } -std::string Button::getTitleFontName() const +std::string_view Button::getTitleFontName() const { if (_titleRenderer) { @@ -857,7 +857,7 @@ std::string Button::getTitleFontName() const } } - return ""; + return ""sv; } std::string Button::getDescription() const diff --git a/cocos/ui/UIButton.h b/cocos/ui/UIButton.h index 3db6e5c123..5405d43719 100644 --- a/cocos/ui/UIButton.h +++ b/cocos/ui/UIButton.h @@ -80,9 +80,9 @@ public: * @param texType @see `TextureResType` * @return a Button instance. */ - static Button* create(const std::string& normalImage, - const std::string& selectedImage = "", - const std::string& disableImage = "", + static Button* create(std::string_view normalImage, + std::string_view selectedImage = "", + std::string_view disableImage = "", TextureResType texType = TextureResType::LOCAL); /** @@ -93,9 +93,9 @@ public: * @param disabled disabled state texture name. * @param texType @see `TextureResType` */ - void loadTextures(const std::string& normal, - const std::string& selected, - const std::string& disabled = "", + void loadTextures(std::string_view normal, + std::string_view selected, + std::string_view disabled = "", TextureResType texType = TextureResType::LOCAL); /** @@ -104,7 +104,7 @@ public: * @param normal normal state texture. * @param texType @see `TextureResType` */ - void loadTextureNormal(const std::string& normal, TextureResType texType = TextureResType::LOCAL); + void loadTextureNormal(std::string_view normal, TextureResType texType = TextureResType::LOCAL); /** * Load selected state texture for button. @@ -112,7 +112,7 @@ public: * @param selected selected state texture. * @param texType @see `TextureResType` */ - void loadTexturePressed(const std::string& selected, TextureResType texType = TextureResType::LOCAL); + void loadTexturePressed(std::string_view selected, TextureResType texType = TextureResType::LOCAL); /** * Load disabled state texture for button. @@ -120,7 +120,7 @@ public: * @param disabled dark state texture. * @param texType @see `TextureResType` */ - void loadTextureDisabled(const std::string& disabled, TextureResType texType = TextureResType::LOCAL); + void loadTextureDisabled(std::string_view disabled, TextureResType texType = TextureResType::LOCAL); /** * Sets capInsets for button. @@ -206,13 +206,13 @@ public: * Change the content of button's title. *@param text The title in std::string. */ - void setTitleText(const std::string& text); + void setTitleText(std::string_view text); /** * Query the button title content. *@return Get the button's title content. */ - std::string getTitleText() const; + std::string_view getTitleText() const; /** * Change the color of button's title. @@ -242,13 +242,13 @@ public: * Change the font name of button's title *@param fontName a font name string. */ - void setTitleFontName(const std::string& fontName); + void setTitleFontName(std::string_view fontName); /** * Query the font name of button's title *@return font name in std::string */ - std::string getTitleFontName() const; + std::string_view getTitleFontName() const; /** * Sets the title's text horizontal alignment. @@ -314,9 +314,9 @@ public: ResourceData getDisabledFile(); CC_CONSTRUCTOR_ACCESS : virtual bool init() override; - virtual bool init(const std::string& normalImage, - const std::string& selectedImage = "", - const std::string& disableImage = "", + virtual bool init(std::string_view normalImage, + std::string_view selectedImage = "", + std::string_view disableImage = "", TextureResType texType = TextureResType::LOCAL); virtual Vec2 getNormalTextureSize() const; diff --git a/cocos/ui/UICheckBox.cpp b/cocos/ui/UICheckBox.cpp index 6cce622d6f..c98813b251 100644 --- a/cocos/ui/UICheckBox.cpp +++ b/cocos/ui/UICheckBox.cpp @@ -48,11 +48,11 @@ CheckBox* CheckBox::create() return nullptr; } -CheckBox* CheckBox::create(const std::string& backGround, - const std::string& backGroundSelected, - const std::string& cross, - const std::string& backGroundDisabled, - const std::string& frontCrossDisabled, +CheckBox* CheckBox::create(std::string_view backGround, + std::string_view backGroundSelected, + std::string_view cross, + std::string_view backGroundDisabled, + std::string_view frontCrossDisabled, TextureResType texType) { CheckBox* pWidget = new CheckBox; @@ -65,7 +65,7 @@ CheckBox* CheckBox::create(const std::string& backGround, return nullptr; } -CheckBox* CheckBox::create(const std::string& backGround, const std::string& cross, TextureResType texType) +CheckBox* CheckBox::create(std::string_view backGround, std::string_view cross, TextureResType texType) { CheckBox* pWidget = new CheckBox; if (pWidget->init(backGround, "", cross, "", "", texType)) diff --git a/cocos/ui/UICheckBox.h b/cocos/ui/UICheckBox.h index ec29f433b1..5d3d43d02c 100644 --- a/cocos/ui/UICheckBox.h +++ b/cocos/ui/UICheckBox.h @@ -93,11 +93,11 @@ public: * * @return A CheckBox instance pointer. */ - static CheckBox* create(const std::string& backGround, - const std::string& backGroundSelected, - const std::string& cross, - const std::string& backGroundDisabled, - const std::string& frontCrossDisabled, + static CheckBox* create(std::string_view backGround, + std::string_view backGroundSelected, + std::string_view cross, + std::string_view backGroundDisabled, + std::string_view frontCrossDisabled, TextureResType texType = TextureResType::LOCAL); /** @@ -108,8 +108,8 @@ public: * @param texType The texture's resource type in `Widget::TextureResType`. * @return A CheckBox instance pointer */ - static CheckBox* create(const std::string& backGround, - const std::string& cross, + static CheckBox* create(std::string_view backGround, + std::string_view cross, TextureResType texType = TextureResType::LOCAL); /** diff --git a/cocos/ui/UIEditBox/UIEditBox.cpp b/cocos/ui/UIEditBox/UIEditBox.cpp index 78c7eb1c04..fefa1cdcb3 100644 --- a/cocos/ui/UIEditBox/UIEditBox.cpp +++ b/cocos/ui/UIEditBox/UIEditBox.cpp @@ -56,15 +56,15 @@ void EditBox::openKeyboard() const _editBoxImpl->openKeyboard(); } -EditBox* EditBox::create(const Vec2& size, const std::string& normalImage, TextureResType texType) +EditBox* EditBox::create(const Vec2& size, std::string_view normalImage, TextureResType texType) { return EditBox::create(size, normalImage, "", "", texType); } EditBox* EditBox::create(const Vec2& size, - const std::string& normalImage, - const std::string& pressedImage /* = "" */, - const std::string& disabledImage /* = "" */, + std::string_view normalImage, + std::string_view pressedImage /* = "" */, + std::string_view disabledImage /* = "" */, TextureResType texType /* = TextureResType::LOCAL */) { EditBox* pRet = new EditBox(); @@ -136,16 +136,16 @@ bool EditBox::initWithSizeAndBackgroundSprite(const Vec2& size, } bool EditBox::initWithSizeAndBackgroundSprite(const Vec2& size, - const std::string& pNormal9SpriteBg, + std::string_view pNormal9SpriteBg, TextureResType texType) { return initWithSizeAndTexture(size, pNormal9SpriteBg, "", "", texType); } bool EditBox::initWithSizeAndTexture(const Vec2& size, - const std::string& normalImage, - const std::string& pressedImage /* = "" */, - const std::string& disabledImage /* = "" */, + std::string_view normalImage, + std::string_view pressedImage /* = "" */, + std::string_view disabledImage /* = "" */, TextureResType texType /* = TextureResType::LOCAL */) { if (Widget::init()) @@ -178,9 +178,9 @@ void EditBox::initRenderer() addProtectedChild(_disabledRenderer, DISABLED_RENDERER_Z, -1); } -void EditBox::loadTextures(const std::string& normal, - const std::string& pressed, - const std::string& disabled, +void EditBox::loadTextures(std::string_view normal, + std::string_view pressed, + std::string_view disabled, TextureResType texType) { loadTextureNormal(normal, texType); @@ -188,7 +188,7 @@ void EditBox::loadTextures(const std::string& normal, loadTextureDisabled(disabled, texType); } -void EditBox::loadTextureNormal(const std::string& normal, TextureResType texType) +void EditBox::loadTextureNormal(std::string_view normal, TextureResType texType) { _normalFileName = normal; _normalTexType = texType; @@ -236,7 +236,7 @@ void EditBox::loadTextureNormal(SpriteFrame* normalSpriteFrame) this->setupNormalTexture(nullptr != normalSpriteFrame); } -void EditBox::loadTexturePressed(const std::string& pressed, TextureResType texType) +void EditBox::loadTexturePressed(std::string_view pressed, TextureResType texType) { _pressedFileName = pressed; _pressedTexType = texType; @@ -279,7 +279,7 @@ void EditBox::loadTexturePressed(SpriteFrame* pressedSpriteFrame) this->setupPressedTexture(nullptr != pressedSpriteFrame); } -void EditBox::loadTextureDisabled(const std::string& disabled, TextureResType texType) +void EditBox::loadTextureDisabled(std::string_view disabled, TextureResType texType) { _disabledFileName = disabled; _disabledTexType = texType; diff --git a/cocos/ui/UIEditBox/UIEditBox.h b/cocos/ui/UIEditBox/UIEditBox.h index 9d76b3bf78..2ecb082d62 100644 --- a/cocos/ui/UIEditBox/UIEditBox.h +++ b/cocos/ui/UIEditBox/UIEditBox.h @@ -78,7 +78,7 @@ public: * @param editBox The edit box object that generated the event. * @param text The new text. */ - virtual void editBoxTextChanged(EditBox* /*editBox*/, const std::string& /*text*/) {} + virtual void editBoxTextChanged(EditBox* /*editBox*/, std::string_view /*text*/) {} /** * This method is called when the return button was pressed or the outside area of keyboard was touched. @@ -214,16 +214,16 @@ public: * create a edit box with size. * @return An autorelease pointer of EditBox, you don't need to release it only if you retain it again. */ - static EditBox* create(const Size& size, const std::string& normalImage, TextureResType texType); + static EditBox* create(const Size& size, std::string_view normalImage, TextureResType texType); /** * create a edit box with size. * @return An autorelease pointer of EditBox, you don't need to release it only if you retain it again. */ static EditBox* create(const Size& size, - const std::string& normalImage, - const std::string& pressedImage = "", - const std::string& disabledImage = "", + std::string_view normalImage, + std::string_view pressedImage = "", + std::string_view disabledImage = "", TextureResType texType = TextureResType::LOCAL); /** @@ -248,7 +248,7 @@ public: * @return Whether initialization is successfully or not. */ bool initWithSizeAndBackgroundSprite(const Size& size, - const std::string& normal9SpriteBg, + std::string_view normal9SpriteBg, TextureResType texType = TextureResType::LOCAL); /** @@ -281,9 +281,9 @@ public: * @return Whether initialization is successfully or not. */ bool initWithSizeAndTexture(const Size& size, - const std::string& normalImage, - const std::string& pressedImage = "", - const std::string& disabledImage = "", + std::string_view normalImage, + std::string_view pressedImage = "", + std::string_view disabledImage = "", TextureResType texType = TextureResType::LOCAL); /** @@ -294,9 +294,9 @@ public: * @param disabled disabled state texture name. * @param texType @see `TextureResType` */ - void loadTextures(const std::string& normal, - const std::string& pressed, - const std::string& disabled = "", + void loadTextures(std::string_view normal, + std::string_view pressed, + std::string_view disabled = "", TextureResType texType = TextureResType::LOCAL); /** @@ -305,7 +305,7 @@ public: * @param normal normal state texture. * @param texType @see `TextureResType` */ - void loadTextureNormal(const std::string& normal, TextureResType texType = TextureResType::LOCAL); + void loadTextureNormal(std::string_view normal, TextureResType texType = TextureResType::LOCAL); /** * Load pressed state texture for edit box. @@ -313,7 +313,7 @@ public: * @param pressed pressed state texture. * @param texType @see `TextureResType` */ - void loadTexturePressed(const std::string& pressed, TextureResType texType = TextureResType::LOCAL); + void loadTexturePressed(std::string_view pressed, TextureResType texType = TextureResType::LOCAL); /** * Load disabled state texture for edit box. @@ -321,7 +321,7 @@ public: * @param disabled dark state texture. * @param texType @see `TextureResType` */ - void loadTextureDisabled(const std::string& disabled, TextureResType texType = TextureResType::LOCAL); + void loadTextureDisabled(std::string_view disabled, TextureResType texType = TextureResType::LOCAL); /** * Sets capInsets for edit box. diff --git a/cocos/ui/UIEditBox/UIEditBoxImpl-android.cpp b/cocos/ui/UIEditBox/UIEditBoxImpl-android.cpp index f23a4345c0..367231058a 100644 --- a/cocos/ui/UIEditBox/UIEditBoxImpl-android.cpp +++ b/cocos/ui/UIEditBox/UIEditBoxImpl-android.cpp @@ -50,8 +50,8 @@ namespace ui # define LOGD(...) __android_log_print(ANDROID_LOG_ERROR, "", __VA_ARGS__) static void editBoxEditingDidBegin(int index); -static void editBoxEditingDidChanged(int index, const std::string& text); -static void editBoxEditingDidEnd(int index, const std::string& text, int action); +static void editBoxEditingDidChanged(int index, std::string_view text); +static void editBoxEditingDidEnd(int index, std::string_view text, int action); extern "C" { JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxEditBoxHelper_editBoxEditingDidBegin(JNIEnv*, jclass, jint index) { @@ -221,7 +221,7 @@ void editBoxEditingDidBegin(int index) s_allEditBoxes[index]->editBoxEditingDidBegin(); } } -void editBoxEditingDidChanged(int index, const std::string& text) +void editBoxEditingDidChanged(int index, std::string_view text) { auto it = s_allEditBoxes.find(index); if (it != s_allEditBoxes.end()) @@ -230,7 +230,7 @@ void editBoxEditingDidChanged(int index, const std::string& text) } } -void editBoxEditingDidEnd(int index, const std::string& text, int action) +void editBoxEditingDidEnd(int index, std::string_view text, int action) { auto it = s_allEditBoxes.find(index); if (it != s_allEditBoxes.end()) diff --git a/cocos/ui/UIEditBox/UIEditBoxImpl-common.cpp b/cocos/ui/UIEditBox/UIEditBoxImpl-common.cpp index bf99aa2f5d..bd3fe9ba63 100644 --- a/cocos/ui/UIEditBox/UIEditBoxImpl-common.cpp +++ b/cocos/ui/UIEditBox/UIEditBoxImpl-common.cpp @@ -346,7 +346,7 @@ void EditBoxImplCommon::closeKeyboard() _editingMode = false; } -void EditBoxImplCommon::onEndEditing(const std::string& /*text*/) +void EditBoxImplCommon::onEndEditing(std::string_view /*text*/) { _editBox->setBrightStyle(Widget::BrightStyle::NORMAL); _editingMode = false; @@ -374,7 +374,7 @@ void EditBoxImplCommon::editBoxEditingDidBegin() #endif } -void EditBoxImplCommon::editBoxEditingDidEnd(const std::string& text, EditBoxDelegate::EditBoxEndAction action) +void EditBoxImplCommon::editBoxEditingDidEnd(std::string_view text, EditBoxDelegate::EditBoxEndAction action) { // LOGD("textFieldShouldEndEditing..."); _text = text; @@ -405,7 +405,7 @@ void EditBoxImplCommon::editBoxEditingDidEnd(const std::string& text, EditBoxDel } } -void EditBoxImplCommon::editBoxEditingChanged(const std::string& text) +void EditBoxImplCommon::editBoxEditingChanged(std::string_view text) { // LOGD("editBoxTextChanged..."); cocos2d::ui::EditBoxDelegate* pDelegate = _editBox->getDelegate(); diff --git a/cocos/ui/UIEditBox/UIEditBoxImpl-common.h b/cocos/ui/UIEditBox/UIEditBoxImpl-common.h index 419ce7a0c9..b14e41fe6b 100644 --- a/cocos/ui/UIEditBox/UIEditBoxImpl-common.h +++ b/cocos/ui/UIEditBox/UIEditBoxImpl-common.h @@ -107,11 +107,11 @@ public: virtual void openKeyboard() override; virtual void closeKeyboard() override; - virtual void onEndEditing(const std::string& text); + virtual void onEndEditing(std::string_view text); void editBoxEditingDidBegin(); - void editBoxEditingChanged(const std::string& text); - void editBoxEditingDidEnd(const std::string& text, + void editBoxEditingChanged(std::string_view text); + void editBoxEditingDidEnd(std::string_view text, EditBoxDelegate::EditBoxEndAction action = EditBoxDelegate::EditBoxEndAction::UNKNOWN); virtual bool isEditing() override = 0; diff --git a/cocos/ui/UIHelper.cpp b/cocos/ui/UIHelper.cpp index 60f3a98ebb..eaa645c707 100644 --- a/cocos/ui/UIHelper.cpp +++ b/cocos/ui/UIHelper.cpp @@ -63,7 +63,7 @@ Widget* Helper::seekWidgetByTag(Widget* root, int tag) return nullptr; } -Widget* Helper::seekWidgetByName(Widget* root, const std::string& name) +Widget* Helper::seekWidgetByName(Widget* root, std::string_view name) { if (!root) { @@ -116,25 +116,25 @@ Widget* Helper::seekActionWidgetByActionTag(Widget* root, int tag) return nullptr; } -std::string Helper::getSubStringOfUTF8String(const std::string& str, +std::string Helper::getSubStringOfUTF8String(std::string_view str, std::string::size_type start, std::string::size_type length) { std::u32string utf32; if (!StringUtils::UTF8ToUTF32(str, utf32)) { - CCLOGERROR("Can't convert string to UTF-32: %s", str.c_str()); + CCLOGERROR("Can't convert string to UTF-32: %s", str.data()); return ""; } if (utf32.size() < start) { - CCLOGERROR("'start' is out of range: %d, %s", static_cast(start), str.c_str()); + CCLOGERROR("'start' is out of range: %d, %s", static_cast(start), str.data()); return ""; } std::string result; if (!StringUtils::UTF32ToUTF8(utf32.substr(start, length), result)) { - CCLOGERROR("Can't convert internal UTF-32 string to UTF-8: %s", str.c_str()); + CCLOGERROR("Can't convert internal UTF-32 string to UTF-8: %s", str.data()); return ""; } return result; diff --git a/cocos/ui/UIHelper.h b/cocos/ui/UIHelper.h index 9f833bef18..9d49b129c7 100644 --- a/cocos/ui/UIHelper.h +++ b/cocos/ui/UIHelper.h @@ -66,7 +66,7 @@ public: * @param name The widget name. * @return Widget instance pointer. */ - static Widget* seekWidgetByName(Widget* root, const std::string& name); + static Widget* seekWidgetByName(Widget* root, std::string_view name); /** * Find a widget with a specific action tag from root widget @@ -87,7 +87,7 @@ public: * @return a UTF8 substring * @js NA */ - static std::string getSubStringOfUTF8String(const std::string& str, + static std::string getSubStringOfUTF8String(std::string_view str, std::string::size_type start, std::string::size_type length); diff --git a/cocos/ui/UIImageView.cpp b/cocos/ui/UIImageView.cpp index da9ed8c515..ffa0391536 100644 --- a/cocos/ui/UIImageView.cpp +++ b/cocos/ui/UIImageView.cpp @@ -50,7 +50,7 @@ ImageView::ImageView() ImageView::~ImageView() {} -ImageView* ImageView::create(const std::string& imageFileName, TextureResType texType) +ImageView* ImageView::create(std::string_view imageFileName, TextureResType texType) { ImageView* widget = new ImageView(); if (widget->init(imageFileName, texType)) @@ -89,7 +89,7 @@ bool ImageView::init() return ret; } -bool ImageView::init(const std::string& imageFileName, TextureResType texType) +bool ImageView::init(std::string_view imageFileName, TextureResType texType) { bool bRet = true; do @@ -113,7 +113,7 @@ void ImageView::initRenderer() addProtectedChild(_imageRenderer, IMAGE_RENDERER_Z, -1); } -void ImageView::loadTexture(const std::string& fileName, TextureResType texType) +void ImageView::loadTexture(std::string_view fileName, TextureResType texType) { if (fileName.empty()) { diff --git a/cocos/ui/UIImageView.h b/cocos/ui/UIImageView.h index 525cdd2195..5fbb2cbde5 100644 --- a/cocos/ui/UIImageView.h +++ b/cocos/ui/UIImageView.h @@ -75,7 +75,7 @@ public: * @param texType @see `Widget::TextureResType` * @return A ImageView instance. */ - static ImageView* create(const std::string& imageFileName, TextureResType texType = TextureResType::LOCAL); + static ImageView* create(std::string_view imageFileName, TextureResType texType = TextureResType::LOCAL); /** * Load texture for imageview. @@ -83,7 +83,7 @@ public: * @param fileName file name of texture. * @param texType @see `Widget::TextureResType` */ - void loadTexture(const std::string& fileName, TextureResType texType = TextureResType::LOCAL); + void loadTexture(std::string_view fileName, TextureResType texType = TextureResType::LOCAL); /** * Updates the texture rect of the ImageView in points. @@ -150,7 +150,7 @@ public: // initializes state of widget. virtual bool init() override; - virtual bool init(const std::string& imageFileName, TextureResType texType = TextureResType::LOCAL); + virtual bool init(std::string_view imageFileName, TextureResType texType = TextureResType::LOCAL); protected: virtual void initRenderer() override; diff --git a/cocos/ui/UILayout.cpp b/cocos/ui/UILayout.cpp index d3c914d1eb..a8444a5d64 100644 --- a/cocos/ui/UILayout.cpp +++ b/cocos/ui/UILayout.cpp @@ -166,7 +166,7 @@ void Layout::addChild(Node* child, int zOrder, int tag) _doLayoutDirty = true; } -void Layout::addChild(Node* child, int zOrder, const std::string& name) +void Layout::addChild(Node* child, int zOrder, std::string_view name) { if (dynamic_cast(child)) { @@ -566,7 +566,7 @@ bool Layout::isBackGroundImageScale9Enabled() const return _backGroundScale9Enabled; } -void Layout::setBackGroundImage(const std::string& fileName, TextureResType texType) +void Layout::setBackGroundImage(std::string_view fileName, TextureResType texType) { if (fileName.empty()) { diff --git a/cocos/ui/UILayout.h b/cocos/ui/UILayout.h index 33c8903a3d..d1dba4fbce 100644 --- a/cocos/ui/UILayout.h +++ b/cocos/ui/UILayout.h @@ -171,7 +171,7 @@ public: * @param fileName image file path. * @param texType @see TextureResType. */ - void setBackGroundImage(const std::string& fileName, TextureResType texType = TextureResType::LOCAL); + void setBackGroundImage(std::string_view fileName, TextureResType texType = TextureResType::LOCAL); /** * Sets a background image capinsets for layout, it only affects the scale9 enabled background image @@ -371,7 +371,7 @@ public: * @param tag A integer to identify the node easily. Please refer to setTag(int) */ virtual void addChild(Node* child, int localZOrder, int tag) override; - virtual void addChild(Node* child, int localZOrder, const std::string& name) override; + virtual void addChild(Node* child, int localZOrder, std::string_view name) override; virtual void visit(Renderer* renderer, const Mat4& parentTransform, uint32_t parentFlags) override; diff --git a/cocos/ui/UILayoutManager.cpp b/cocos/ui/UILayoutManager.cpp index 6c40796bae..20c3cabce3 100644 --- a/cocos/ui/UILayoutManager.cpp +++ b/cocos/ui/UILayoutManager.cpp @@ -236,7 +236,7 @@ Widget* RelativeLayoutManager::getRelativeWidget(Widget* widget) { Widget* relativeWidget = nullptr; RelativeLayoutParameter* layoutParameter = dynamic_cast(widget->getLayoutParameter()); - const std::string relativeName = layoutParameter->getRelativeToWidgetName(); + auto relativeName = layoutParameter->getRelativeToWidgetName(); if (!relativeName.empty()) { diff --git a/cocos/ui/UILayoutParameter.cpp b/cocos/ui/UILayoutParameter.cpp index 0bf409a4dc..d80d751a16 100644 --- a/cocos/ui/UILayoutParameter.cpp +++ b/cocos/ui/UILayoutParameter.cpp @@ -146,22 +146,22 @@ RelativeLayoutParameter::RelativeAlign RelativeLayoutParameter::getAlign() const return _relativeAlign; } -void RelativeLayoutParameter::setRelativeToWidgetName(const std::string& name) +void RelativeLayoutParameter::setRelativeToWidgetName(std::string_view name) { _relativeWidgetName = name; } -const std::string& RelativeLayoutParameter::getRelativeToWidgetName() const +std::string_view RelativeLayoutParameter::getRelativeToWidgetName() const { return _relativeWidgetName; } -void RelativeLayoutParameter::setRelativeName(const std::string& name) +void RelativeLayoutParameter::setRelativeName(std::string_view name) { _relativeLayoutName = name; } -const std::string& RelativeLayoutParameter::getRelativeName() const +std::string_view RelativeLayoutParameter::getRelativeName() const { return _relativeLayoutName; } diff --git a/cocos/ui/UILayoutParameter.h b/cocos/ui/UILayoutParameter.h index 1a2615da8f..9e6b92a5d8 100644 --- a/cocos/ui/UILayoutParameter.h +++ b/cocos/ui/UILayoutParameter.h @@ -363,27 +363,27 @@ public: * * @param name Relative widget name. */ - void setRelativeToWidgetName(const std::string& name); + void setRelativeToWidgetName(std::string_view name); /** * Get the relative widget name. * @return name A relative widget name in string. */ - const std::string& getRelativeToWidgetName() const; + std::string_view getRelativeToWidgetName() const; /** * Set a name for LayoutParameter in Relative Layout. * * @param name A string name. */ - void setRelativeName(const std::string& name); + void setRelativeName(std::string_view name); /** * Get a name of LayoutParameter in Relative Layout. * * @return name Relative name in string. */ - const std::string& getRelativeName() const; + std::string_view getRelativeName() const; // override functions. virtual LayoutParameter* createCloneInstance() override; diff --git a/cocos/ui/UIListView.cpp b/cocos/ui/UIListView.cpp index 32616f2bb5..68b62f2c17 100644 --- a/cocos/ui/UIListView.cpp +++ b/cocos/ui/UIListView.cpp @@ -292,7 +292,7 @@ void ListView::addChild(cocos2d::Node* child, int zOrder) ListView::addChild(child, zOrder, child->getName()); } -void ListView::addChild(Node* child, int zOrder, const std::string& name) +void ListView::addChild(Node* child, int zOrder, std::string_view name) { ScrollView::addChild(child, zOrder, name); diff --git a/cocos/ui/UIListView.h b/cocos/ui/UIListView.h index b1b54b8e56..2b961b2a9b 100644 --- a/cocos/ui/UIListView.h +++ b/cocos/ui/UIListView.h @@ -309,7 +309,7 @@ public: virtual void addChild(Node* child) override; virtual void addChild(Node* child, int localZOrder) override; virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, const std::string& name) override; + virtual void addChild(Node* child, int zOrder, std::string_view name) override; virtual void removeAllChildren() override; virtual void removeAllChildrenWithCleanup(bool cleanup) override; virtual void removeChild(Node* child, bool cleanup = true) override; diff --git a/cocos/ui/UILoadingBar.cpp b/cocos/ui/UILoadingBar.cpp index e1a9e518df..b3518941ce 100644 --- a/cocos/ui/UILoadingBar.cpp +++ b/cocos/ui/UILoadingBar.cpp @@ -71,12 +71,12 @@ LoadingBar* LoadingBar::create() return nullptr; } -LoadingBar* LoadingBar::create(const std::string& textureName, float percentage) +LoadingBar* LoadingBar::create(std::string_view textureName, float percentage) { return LoadingBar::create(textureName, TextureResType::LOCAL, percentage); } -LoadingBar* LoadingBar::create(const std::string& textureName, TextureResType texType, float percentage) +LoadingBar* LoadingBar::create(std::string_view textureName, TextureResType texType, float percentage) { LoadingBar* widget = new LoadingBar; if (widget->init()) @@ -125,7 +125,7 @@ LoadingBar::Direction LoadingBar::getDirection() const return _direction; } -void LoadingBar::loadTexture(const std::string& texture, TextureResType texType) +void LoadingBar::loadTexture(std::string_view texture, TextureResType texType) { if (texture.empty()) { diff --git a/cocos/ui/UILoadingBar.h b/cocos/ui/UILoadingBar.h index b83b298db6..6206bf32f1 100644 --- a/cocos/ui/UILoadingBar.h +++ b/cocos/ui/UILoadingBar.h @@ -88,7 +88,7 @@ public: * @param percentage A percentage in float. * @return A LoadingBar instance. */ - static LoadingBar* create(const std::string& textureName, float percentage = 0); + static LoadingBar* create(std::string_view textureName, float percentage = 0); /** * @brief Create a LoadingBar with a texture name along with its texture type and a predefined progress value. @@ -98,7 +98,7 @@ public: * @param percentage A percentage in float, default value is 0. * @return A LoadingBar instance. */ - static LoadingBar* create(const std::string& textureName, TextureResType texType, float percentage = 0); + static LoadingBar* create(std::string_view textureName, TextureResType texType, float percentage = 0); /** * Change the progress direction of LoadingBar. @@ -122,7 +122,7 @@ public: * @param texture File name of texture. * @param texType Texture resource type,@see TextureResType. */ - void loadTexture(const std::string& texture, TextureResType texType = TextureResType::LOCAL); + void loadTexture(std::string_view texture, TextureResType texType = TextureResType::LOCAL); /** * Changes the progress value of LoadingBar. diff --git a/cocos/ui/UIPageView.cpp b/cocos/ui/UIPageView.cpp index 06a56f3258..b92f56a7b6 100644 --- a/cocos/ui/UIPageView.cpp +++ b/cocos/ui/UIPageView.cpp @@ -465,7 +465,7 @@ float PageView::getIndicatorIndexNodesScale() const return _indicator->getIndexNodesScale(); } -void PageView::setIndicatorIndexNodesTexture(const std::string& texName, Widget::TextureResType texType) +void PageView::setIndicatorIndexNodesTexture(std::string_view texName, Widget::TextureResType texType) { if (_indicator != nullptr) { diff --git a/cocos/ui/UIPageView.h b/cocos/ui/UIPageView.h index 97d8320ddf..6325e9561c 100644 --- a/cocos/ui/UIPageView.h +++ b/cocos/ui/UIPageView.h @@ -314,7 +314,7 @@ public: * @param fileName File name of texture. * @param resType @see TextureResType . */ - void setIndicatorIndexNodesTexture(const std::string& texName, + void setIndicatorIndexNodesTexture(std::string_view texName, Widget::TextureResType texType = Widget::TextureResType::LOCAL); /** diff --git a/cocos/ui/UIPageViewIndicator.cpp b/cocos/ui/UIPageViewIndicator.cpp index 530df5a82c..94590ced01 100644 --- a/cocos/ui/UIPageViewIndicator.cpp +++ b/cocos/ui/UIPageViewIndicator.cpp @@ -195,7 +195,7 @@ void PageViewIndicator::setIndexNodesScale(float indexNodesScale) rearrange(); } -void PageViewIndicator::setIndexNodesTexture(const std::string& texName, Widget::TextureResType texType) +void PageViewIndicator::setIndexNodesTexture(std::string_view texName, Widget::TextureResType texType) { _useDefaultTexture = false; _indexNodesTextureFile = texName; diff --git a/cocos/ui/UIPageViewIndicator.h b/cocos/ui/UIPageViewIndicator.h index d498c4cdfd..97649861e1 100644 --- a/cocos/ui/UIPageViewIndicator.h +++ b/cocos/ui/UIPageViewIndicator.h @@ -74,7 +74,7 @@ public: * @param fileName File name of texture. * @param resType @see TextureResType . */ - void setIndexNodesTexture(const std::string& texName, + void setIndexNodesTexture(std::string_view texName, Widget::TextureResType texType = Widget::TextureResType::LOCAL); protected: diff --git a/cocos/ui/UIRadioButton.cpp b/cocos/ui/UIRadioButton.cpp index 14d9e639d9..ff1ad49f1d 100644 --- a/cocos/ui/UIRadioButton.cpp +++ b/cocos/ui/UIRadioButton.cpp @@ -52,11 +52,11 @@ RadioButton* RadioButton::create() return nullptr; } -RadioButton* RadioButton::create(const std::string& backGround, - const std::string& backGroundSelected, - const std::string& cross, - const std::string& backGroundDisabled, - const std::string& frontCrossDisabled, +RadioButton* RadioButton::create(std::string_view backGround, + std::string_view backGroundSelected, + std::string_view cross, + std::string_view backGroundDisabled, + std::string_view frontCrossDisabled, TextureResType texType) { RadioButton* pWidget = new RadioButton(); @@ -69,7 +69,7 @@ RadioButton* RadioButton::create(const std::string& backGround, return nullptr; } -RadioButton* RadioButton::create(const std::string& backGround, const std::string& cross, TextureResType texType) +RadioButton* RadioButton::create(std::string_view backGround, std::string_view cross, TextureResType texType) { RadioButton* pWidget = new RadioButton(); if (pWidget->init(backGround, "", cross, "", "", texType)) diff --git a/cocos/ui/UIRadioButton.h b/cocos/ui/UIRadioButton.h index 9adb3c8357..43deb3b92e 100644 --- a/cocos/ui/UIRadioButton.h +++ b/cocos/ui/UIRadioButton.h @@ -98,11 +98,11 @@ public: * * @return A RadioButton instance pointer. */ - static RadioButton* create(const std::string& backGround, - const std::string& backGroundSelected, - const std::string& cross, - const std::string& backGroundDisabled, - const std::string& frontCrossDisabled, + static RadioButton* create(std::string_view backGround, + std::string_view backGroundSelected, + std::string_view cross, + std::string_view backGroundDisabled, + std::string_view frontCrossDisabled, TextureResType texType = TextureResType::LOCAL); /** @@ -113,8 +113,8 @@ public: * @param texType The texture's resource type in `Widget::TextureResType`. * @return A RadioButton instance pointer */ - static RadioButton* create(const std::string& backGround, - const std::string& cross, + static RadioButton* create(std::string_view backGround, + std::string_view cross, TextureResType texType = TextureResType::LOCAL); /** diff --git a/cocos/ui/UIRichText.cpp b/cocos/ui/UIRichText.cpp index e46456085b..b2650303e4 100644 --- a/cocos/ui/UIRichText.cpp +++ b/cocos/ui/UIRichText.cpp @@ -51,7 +51,7 @@ public: static const std::string COMPONENT_NAME; /*!< component name */ static ListenerComponent* create(Node* parent, - const std::string& url, + std::string_view url, const RichText::OpenUrlHandler handleOpenUrl = nullptr) { auto component = new ListenerComponent(parent, url, std::move(handleOpenUrl)); @@ -59,7 +59,7 @@ public: return component; } - explicit ListenerComponent(Node* parent, const std::string& url, const RichText::OpenUrlHandler handleOpenUrl) + explicit ListenerComponent(Node* parent, std::string_view url, const RichText::OpenUrlHandler handleOpenUrl) : _parent(parent), _url(url), _handleOpenUrl(std::move(handleOpenUrl)) { setName(ListenerComponent::COMPONENT_NAME); @@ -124,11 +124,11 @@ void RichElement::setColor(const Color3B& color) RichElementText* RichElementText::create(int tag, const Color3B& color, uint8_t opacity, - const std::string& text, - const std::string& fontName, + std::string_view text, + std::string_view fontName, float fontSize, uint32_t flags, - const std::string& url, + std::string_view url, const Color3B& outlineColor, int outlineSize, const Color3B& shadowColor, @@ -150,11 +150,11 @@ RichElementText* RichElementText::create(int tag, bool RichElementText::init(int tag, const Color3B& color, uint8_t opacity, - const std::string& text, - const std::string& fontName, + std::string_view text, + std::string_view fontName, float fontSize, uint32_t flags, - const std::string& url, + std::string_view url, const Color3B& outlineColor, int outlineSize, const Color3B& shadowColor, @@ -183,8 +183,8 @@ bool RichElementText::init(int tag, RichElementImage* RichElementImage::create(int tag, const Color3B& color, uint8_t opacity, - const std::string& filePath, - const std::string& url, + std::string_view filePath, + std::string_view url, Widget::TextureResType texType) { RichElementImage* element = new RichElementImage(); @@ -200,8 +200,8 @@ RichElementImage* RichElementImage::create(int tag, bool RichElementImage::init(int tag, const Color3B& color, uint8_t opacity, - const std::string& filePath, - const std::string& url, + std::string_view filePath, + std::string_view url, Widget::TextureResType texType) { if (RichElement::init(tag, color, opacity)) @@ -226,7 +226,7 @@ void RichElementImage::setHeight(int height) _height = height; } -void RichElementImage::setUrl(const std::string& url) +void RichElementImage::setUrl(std::string_view url) { _url = url; } @@ -334,7 +334,7 @@ private: bool isFontElement; RichText::VisitEnterHandler handleVisitEnter; }; - typedef std::unordered_map TagTables; + typedef hlookup::string_map TagTables; static TagTables _tagTables; @@ -376,11 +376,11 @@ public: void pushBackElement(RichElement* element); - static void setTagDescription(const std::string& tag, + static void setTagDescription(std::string_view tag, bool isFontElement, RichText::VisitEnterHandler&& handleVisitEnter); - static void removeTagDescription(const std::string& tag); + static void removeTagDescription(std::string_view tag); private: ValueMap tagAttrMapWithXMLElement(const char** attrs); @@ -907,14 +907,19 @@ void MyXMLVisitor::pushBackElement(RichElement* element) _richText->pushBackElement(element); } -void MyXMLVisitor::setTagDescription(const std::string& tag, +void MyXMLVisitor::setTagDescription(std::string_view tag, bool isFontElement, RichText::VisitEnterHandler&& handleVisitEnter) { - MyXMLVisitor::_tagTables[tag] = {isFontElement, std::move(handleVisitEnter)}; + hlookup::set_item( + MyXMLVisitor::_tagTables, tag, + TagBehavior{ + isFontElement, + std::move( + handleVisitEnter)}); // MyXMLVisitor::_tagTables[tag] = {isFontElement, std::move(handleVisitEnter)}; } -void MyXMLVisitor::removeTagDescription(const std::string& tag) +void MyXMLVisitor::removeTagDescription(std::string_view tag) { MyXMLVisitor::_tagTables.erase(tag); } @@ -1004,7 +1009,7 @@ RichText* RichText::create() return nullptr; } -RichText* RichText::createWithXML(const std::string& xml, const ValueMap& defaults, const OpenUrlHandler& handleOpenUrl) +RichText* RichText::createWithXML(std::string_view xml, const ValueMap& defaults, const OpenUrlHandler& handleOpenUrl) { RichText* widget = new RichText(); if (widget->initWithXML(xml, defaults, handleOpenUrl)) @@ -1025,7 +1030,7 @@ bool RichText::init() return false; } -bool RichText::initWithXML(const std::string& origxml, const ValueMap& defaults, const OpenUrlHandler& handleOpenUrl) +bool RichText::initWithXML(std::string_view origxml, const ValueMap& defaults, const OpenUrlHandler& handleOpenUrl) { static std::function startTagFont = [](RichText* richText) { std::string fontFace = richText->getFontFace(); @@ -1109,7 +1114,7 @@ void RichText::setHorizontalAlignment(cocos2d::ui::RichText::HorizontalAlignment } } -void RichText::setFontColor(const std::string& color) +void RichText::setFontColor(std::string_view color) { _defaults[KEY_FONT_COLOR_STRING] = color; } @@ -1134,7 +1139,7 @@ float RichText::getFontSize() return _defaults.at(KEY_FONT_SIZE).asFloat(); } -void RichText::setFontFace(const std::string& face) +void RichText::setFontFace(std::string_view face) { _defaults[KEY_FONT_FACE] = face; } @@ -1144,7 +1149,7 @@ std::string RichText::getFontFace() return _defaults.at(KEY_FONT_FACE).asString(); } -void RichText::setAnchorFontColor(const std::string& color) +void RichText::setAnchorFontColor(std::string_view color) { _defaults[KEY_ANCHOR_FONT_COLOR_STRING] = color; } @@ -1393,12 +1398,12 @@ ValueMap RichText::getDefaults() const return defaults; } -cocos2d::Color3B RichText::color3BWithString(const std::string& color) +cocos2d::Color3B RichText::color3BWithString(std::string_view color) { if (color.length() == 4) { int r, g, b; - sscanf(color.c_str(), "%*c%1x%1x%1x", &r, &g, &b); + sscanf(color.data(), "%*c%1x%1x%1x", &r, &g, &b); r += r * 16; g += g * 16; b += b * 16; @@ -1407,13 +1412,13 @@ cocos2d::Color3B RichText::color3BWithString(const std::string& color) else if (color.length() == 7) { int r, g, b; - sscanf(color.c_str(), "%*c%2x%2x%2x", &r, &g, &b); + sscanf(color.data(), "%*c%2x%2x%2x", &r, &g, &b); return Color3B(r, g, b); } else if (color.length() == 9) { int r, g, b, a; - sscanf(color.c_str(), "%*c%2x%2x%2x%2x", &r, &g, &b, &a); + sscanf(color.data(), "%*c%2x%2x%2x%2x", &r, &g, &b, &a); return Color3B(r, g, b); } return Color3B::WHITE; @@ -1440,17 +1445,17 @@ std::string RichText::stringWithColor4B(const cocos2d::Color4B& color4b) return std::string(buf, 9); } -void RichText::setTagDescription(const std::string& tag, bool isFontElement, VisitEnterHandler handleVisitEnter) +void RichText::setTagDescription(std::string_view tag, bool isFontElement, VisitEnterHandler handleVisitEnter) { MyXMLVisitor::setTagDescription(tag, isFontElement, std::move(handleVisitEnter)); } -void RichText::removeTagDescription(const std::string& tag) +void RichText::removeTagDescription(std::string_view tag) { MyXMLVisitor::removeTagDescription(tag); } -void RichText::openUrl(const std::string& url) +void RichText::openUrl(std::string_view url) { if (_handleOpenUrl) { @@ -1767,13 +1772,13 @@ int findSplitPositionForChar(Label* label, } } // namespace -void RichText::handleTextRenderer(const std::string& text, - const std::string& fontName, +void RichText::handleTextRenderer(std::string_view text, + std::string_view fontName, float fontSize, const Color3B& color, uint8_t opacity, uint32_t flags, - const std::string& url, + std::string_view url, const Color3B& outlineColor, int outlineSize, const Color3B& shadowColor, @@ -1785,7 +1790,8 @@ void RichText::handleTextRenderer(const std::string& text, RichText::WrapMode wrapMode = static_cast(_defaults.at(KEY_WRAP_MODE).asInt()); // split text by \n - std::stringstream ss(text); + std::stringstream ss; + ss << text; std::string currentText; size_t realLines = 0; while (std::getline(ss, currentText, '\n')) @@ -1877,13 +1883,13 @@ void RichText::handleTextRenderer(const std::string& text, } } -void RichText::handleImageRenderer(const std::string& filePath, +void RichText::handleImageRenderer(std::string_view filePath, Widget::TextureResType textureType, const Color3B& /*color*/, uint8_t /*opacity*/, int width, int height, - const std::string& url) + std::string_view url) { Sprite* imageRenderer; if (textureType == Widget::TextureResType::LOCAL) @@ -2062,10 +2068,9 @@ bool isWhitespace(char c) { return std::isspace(c, std::locale()); } -std::string rtrim(std::string s) +void rtrim(std::string& s) { s.erase(std::find_if_not(s.rbegin(), s.rend(), isWhitespace).base(), s.end()); - return s; } } // namespace @@ -2076,7 +2081,8 @@ float RichText::stripTrailingWhitespace(const Vector& row) if (auto label = dynamic_cast(row.back())) { const auto width = label->getContentSize().width; - const auto trimmedString = rtrim(label->getString()); + std::string trimmedString{label->getString()}; + rtrim(trimmedString); if (label->getString() != trimmedString) { label->setString(trimmedString); diff --git a/cocos/ui/UIRichText.h b/cocos/ui/UIRichText.h index 4c694c8af9..932ddd29cc 100644 --- a/cocos/ui/UIRichText.h +++ b/cocos/ui/UIRichText.h @@ -148,11 +148,11 @@ public: bool init(int tag, const Color3B& color, uint8_t opacity, - const std::string& text, - const std::string& fontName, + std::string_view text, + std::string_view fontName, float fontSize, uint32_t flags, - const std::string& url, + std::string_view url, const Color3B& outlineColor = Color3B::WHITE, int outlineSize = -1, const Color3B& shadowColor = Color3B::BLACK, @@ -182,11 +182,11 @@ public: static RichElementText* create(int tag, const Color3B& color, uint8_t opacity, - const std::string& text, - const std::string& fontName, + std::string_view text, + std::string_view fontName, float fontSize, uint32_t flags = 0, - const std::string& url = "", + std::string_view url = "", const Color3B& outlineColor = Color3B::WHITE, int outlineSize = -1, const Color3B& shadowColor = Color3B::BLACK, @@ -244,8 +244,8 @@ public: bool init(int tag, const Color3B& color, uint8_t opacity, - const std::string& filePath, - const std::string& url = "", + std::string_view filePath, + std::string_view url = "", Widget::TextureResType texType = Widget::TextureResType::LOCAL); /** @@ -262,13 +262,13 @@ public: static RichElementImage* create(int tag, const Color3B& color, uint8_t opacity, - const std::string& filePath, - const std::string& url = "", + std::string_view filePath, + std::string_view url = "", Widget::TextureResType texType = Widget::TextureResType::LOCAL); void setWidth(int width); void setHeight(int height); - void setUrl(const std::string& url); + void setUrl(std::string_view url); protected: std::string _filePath; @@ -386,7 +386,7 @@ public: * @brief call to open a resource specified by a URL * @param url a URL */ - typedef std::function OpenUrlHandler; + typedef std::function OpenUrlHandler; /** * @brief called on the specified tag @@ -461,7 +461,7 @@ public: * * @return RichText instance. */ - static RichText* createWithXML(const std::string& xml, + static RichText* createWithXML(std::string_view xml, const ValueMap& defaults = ValueMap(), const OpenUrlHandler& handleOpenUrl = nullptr); @@ -517,14 +517,14 @@ public: HorizontalAlignment a); /*!< sets the horizontal alignment mode: LEFT, CENTER, or RIGHT */ HorizontalAlignment getHorizontalAlignment() const; /*!< returns the current horizontal alignment mode */ void setFontColor( - const std::string& color); /*!< Set the font color. @param color the #RRGGBB hexadecimal notation. */ + std::string_view color); /*!< Set the font color. @param color the #RRGGBB hexadecimal notation. */ std::string getFontColor(); /*!< return the current font color */ Color3B getFontColor3B(); /*!< return the current font color */ void setFontSize(float size); /*!< Set the font size. @param size the font size. */ float getFontSize(); /*!< return the current font size */ - void setFontFace(const std::string& face); /*!< Set the font face. @param face the font face. */ + void setFontFace(std::string_view face); /*!< Set the font face. @param face the font face. */ std::string getFontFace(); /*!< return the current font face */ - void setAnchorFontColor(const std::string& color); /*!< Set the font color of a-tag. @param face the font color. */ + void setAnchorFontColor(std::string_view color); /*!< Set the font color of a-tag. @param face the font color. */ std::string getAnchorFontColor(); /*!< return the current font color of a-tag */ cocos2d::Color3B getAnchorFontColor3B(); /*!< return the current font color of a-tag */ void setAnchorTextBold(bool enable); /*!< enable bold text of a-tag */ @@ -555,7 +555,7 @@ public: void setDefaults(const ValueMap& defaults); /*!< set the default values */ ValueMap getDefaults() const; /*!< returns the default values */ - cocos2d::Color3B color3BWithString(const std::string& color); /*!< convert a color string into a Color3B. */ + cocos2d::Color3B color3BWithString(std::string_view color); /*!< convert a color string into a Color3B. */ std::string stringWithColor3B(const cocos2d::Color3B& color3b); /*!< convert a Color3B into a color string. */ std::string stringWithColor4B(const cocos2d::Color4B& color4b); /*!< convert a Color4B into a color string. */ @@ -565,15 +565,15 @@ public: * @param isFontElement use attributes of text tag * @param handleVisitEnter callback */ - static void setTagDescription(const std::string& tag, bool isFontElement, VisitEnterHandler handleVisitEnter); + static void setTagDescription(std::string_view tag, bool isFontElement, VisitEnterHandler handleVisitEnter); /** * @brief remove a callback to own tag. * @param tag tag's name */ - static void removeTagDescription(const std::string& tag); + static void removeTagDescription(std::string_view tag); - void openUrl(const std::string& url); + void openUrl(std::string_view url); /** * @brief Asks the callback to open a resource specified by a URL. @@ -584,7 +584,7 @@ public: CC_CONSTRUCTOR_ACCESS : virtual bool init() override; - bool initWithXML(const std::string& xml, + bool initWithXML(std::string_view xml, const ValueMap& defaults = ValueMap(), const OpenUrlHandler& handleOpenUrl = nullptr); @@ -593,26 +593,26 @@ protected: virtual void initRenderer() override; void pushToContainer(Node* renderer); - void handleTextRenderer(const std::string& text, - const std::string& fontName, + void handleTextRenderer(std::string_view text, + std::string_view fontName, float fontSize, const Color3B& color, uint8_t opacity, uint32_t flags, - const std::string& url = "", + std::string_view url = "", const Color3B& outlineColor = Color3B::WHITE, int outlineSize = -1, const Color3B& shadowColor = Color3B::BLACK, const Vec2& shadowOffset = Vec2(2.0, -2.0), int shadowBlurRadius = 0, const Color3B& glowColor = Color3B::WHITE); - void handleImageRenderer(const std::string& filePath, + void handleImageRenderer(std::string_view filePath, Widget::TextureResType textureType, const Color3B& color, uint8_t opacity, int width, int height, - const std::string& url); + std::string_view url); void handleCustomRenderer(Node* renderer); void formatRenderers(); void addNewLine(); diff --git a/cocos/ui/UIScale9Sprite.cpp b/cocos/ui/UIScale9Sprite.cpp index dba22480e4..eedb3152d4 100644 --- a/cocos/ui/UIScale9Sprite.cpp +++ b/cocos/ui/UIScale9Sprite.cpp @@ -53,7 +53,7 @@ Scale9Sprite* Scale9Sprite::create() return nullptr; } -Scale9Sprite* Scale9Sprite::create(const std::string& filename, const Rect& rect, const Rect& capInsets) +Scale9Sprite* Scale9Sprite::create(std::string_view filename, const Rect& rect, const Rect& capInsets) { Scale9Sprite* ret = new Scale9Sprite(); if (ret->initWithFile(filename, rect, capInsets)) @@ -65,12 +65,12 @@ Scale9Sprite* Scale9Sprite::create(const std::string& filename, const Rect& rect return nullptr; } -Scale9Sprite* Scale9Sprite::create(const std::string& filename, const Rect& rect) +Scale9Sprite* Scale9Sprite::create(std::string_view filename, const Rect& rect) { return create(filename, rect, Rect::ZERO); } -Scale9Sprite* Scale9Sprite::create(const Rect& capInsets, const std::string& file) +Scale9Sprite* Scale9Sprite::create(const Rect& capInsets, std::string_view file) { Scale9Sprite* ret = new Scale9Sprite(); if (ret->initWithFile(capInsets, file)) @@ -82,7 +82,7 @@ Scale9Sprite* Scale9Sprite::create(const Rect& capInsets, const std::string& fil return nullptr; } -Scale9Sprite* Scale9Sprite::create(const std::string& fileaname) +Scale9Sprite* Scale9Sprite::create(std::string_view fileaname) { return create(Rect::ZERO, fileaname); } @@ -104,7 +104,7 @@ Scale9Sprite* Scale9Sprite::createWithSpriteFrame(SpriteFrame* spriteFrame) return createWithSpriteFrame(spriteFrame, Rect::ZERO); } -Scale9Sprite* Scale9Sprite::createWithSpriteFrameName(const std::string& spriteFrameName, const Rect& capInsets) +Scale9Sprite* Scale9Sprite::createWithSpriteFrameName(std::string_view spriteFrameName, const Rect& capInsets) { Scale9Sprite* ret = new Scale9Sprite(); if (ret->initWithSpriteFrameName(spriteFrameName, capInsets)) @@ -116,7 +116,7 @@ Scale9Sprite* Scale9Sprite::createWithSpriteFrameName(const std::string& spriteF return nullptr; } -Scale9Sprite* Scale9Sprite::createWithSpriteFrameName(const std::string& spriteFrameName) +Scale9Sprite* Scale9Sprite::createWithSpriteFrameName(std::string_view spriteFrameName) { Scale9Sprite* ret = new Scale9Sprite(); if (ret->initWithSpriteFrameName(spriteFrameName, Rect::ZERO)) @@ -142,7 +142,7 @@ Scale9Sprite::Scale9Sprite() Scale9Sprite::~Scale9Sprite() {} -bool Scale9Sprite::initWithFile(const Rect& capInsets, const std::string& file) +bool Scale9Sprite::initWithFile(const Rect& capInsets, std::string_view file) { // calls super bool ret = Sprite::initWithFile(file); @@ -150,7 +150,7 @@ bool Scale9Sprite::initWithFile(const Rect& capInsets, const std::string& file) return ret; } -bool Scale9Sprite::initWithFile(const std::string& filename) +bool Scale9Sprite::initWithFile(std::string_view filename) { // calls super auto originalCapInsets = this->getCapInsets(); @@ -159,7 +159,7 @@ bool Scale9Sprite::initWithFile(const std::string& filename) return ret; } -bool Scale9Sprite::initWithFile(const std::string& filename, const Rect& rect) +bool Scale9Sprite::initWithFile(std::string_view filename, const Rect& rect) { // calls super auto originalCapInsets = this->getCapInsets(); @@ -176,7 +176,7 @@ bool Scale9Sprite::initWithSpriteFrame(SpriteFrame* spriteFrame, const Rect& cap return ret; } -bool Scale9Sprite::initWithSpriteFrameName(const std::string& spriteFrameName, const Rect& capInsets) +bool Scale9Sprite::initWithSpriteFrameName(std::string_view spriteFrameName, const Rect& capInsets) { // calls super bool ret = Sprite::initWithSpriteFrameName(spriteFrameName); @@ -184,7 +184,7 @@ bool Scale9Sprite::initWithSpriteFrameName(const std::string& spriteFrameName, c return ret; } -bool Scale9Sprite::initWithSpriteFrameName(const std::string& spriteFrameName) +bool Scale9Sprite::initWithSpriteFrameName(std::string_view spriteFrameName) { // calls super auto originalCapInsets = this->getCapInsets(); @@ -242,7 +242,7 @@ bool Scale9Sprite::init(Sprite* sprite, return ret; } -bool Scale9Sprite::initWithFile(const std::string& filename, const Rect& rect, const Rect& capInsets) +bool Scale9Sprite::initWithFile(std::string_view filename, const Rect& rect, const Rect& capInsets) { // calls super bool ret = false; diff --git a/cocos/ui/UIScale9Sprite.h b/cocos/ui/UIScale9Sprite.h index 94c4226d58..3e11d0743c 100644 --- a/cocos/ui/UIScale9Sprite.h +++ b/cocos/ui/UIScale9Sprite.h @@ -108,7 +108,7 @@ public: * @param capInsets A specified cap insets. * @return A Scale9Sprite instance. */ - static Scale9Sprite* create(const std::string& file, const Rect& rect, const Rect& capInsets); + static Scale9Sprite* create(std::string_view file, const Rect& rect, const Rect& capInsets); /** * Creates a 9-slice sprite with a texture file. The whole texture will be @@ -119,7 +119,7 @@ public: * @param file A texture file name. * @return A Scale9Sprite instance. */ - static Scale9Sprite* create(const Rect& capInsets, const std::string& file); + static Scale9Sprite* create(const Rect& capInsets, std::string_view file); /** * Creates a 9-slice sprite with a texture file and a delimitation zone. The @@ -130,7 +130,7 @@ public: * @param rect A delimitation zone. * @return A Scale9Sprite instance. */ - static Scale9Sprite* create(const std::string& file, const Rect& rect); + static Scale9Sprite* create(std::string_view file, const Rect& rect); /** * Creates a 9-slice sprite with a texture file. The whole texture will be @@ -140,7 +140,7 @@ public: * @param file A texture file name. * @return A Scale9Sprite instance. */ - static Scale9Sprite* create(const std::string& file); + static Scale9Sprite* create(std::string_view file); /** * Creates a 9-slice sprite with an sprite frame. @@ -177,7 +177,7 @@ public: * @param spriteFrameName A sprite frame name. * @return A Scale9Sprite instance. */ - static Scale9Sprite* createWithSpriteFrameName(const std::string& spriteFrameName); + static Scale9Sprite* createWithSpriteFrameName(std::string_view spriteFrameName); /** * Creates a 9-slice sprite with an sprite frame name and the centre of its zone. @@ -190,7 +190,7 @@ public: * @param capInsets A delimitation zone. * @return A Scale9Sprite instance. */ - static Scale9Sprite* createWithSpriteFrameName(const std::string& spriteFrameName, const Rect& capInsets); + static Scale9Sprite* createWithSpriteFrameName(std::string_view spriteFrameName, const Rect& capInsets); // overridden methods that takes different parameters using Sprite::initWithFile; @@ -212,7 +212,7 @@ public: * @param capInsets The values to use for the cap insets. * @return True if initialize success, false otherwise. */ - virtual bool initWithFile(const std::string& file, const Rect& rect, const Rect& capInsets); + virtual bool initWithFile(std::string_view file, const Rect& rect, const Rect& capInsets); /** * Initializes a 9-slice sprite with a texture file and with the specified cap @@ -225,7 +225,7 @@ public: * @param capInsets The values to use for the cap insets. * @return True if initializes success, false otherwise. */ - virtual bool initWithFile(const Rect& capInsets, const std::string& file); + virtual bool initWithFile(const Rect& capInsets, std::string_view file); /** * Initializes a 9-slice sprite with an sprite frame and with the specified @@ -251,7 +251,7 @@ public: * @param capInsets The values to use for the cap insets. * @return True if initializes success, false otherwise. */ - virtual bool initWithSpriteFrameName(const std::string& spriteFrameName, const Rect& capInsets); + virtual bool initWithSpriteFrameName(std::string_view spriteFrameName, const Rect& capInsets); // override function @@ -268,7 +268,7 @@ public: * texture's full rect. * @return True if initializes success, false otherwise. */ - virtual bool initWithFile(const std::string& file, const Rect& rect) override; + virtual bool initWithFile(std::string_view file, const Rect& rect) override; /** * Initializes a 9-slice sprite with a texture file. The whole texture will be @@ -280,7 +280,7 @@ public: * @param file The name of the texture file. * @return True if initializes success, false otherwise. */ - virtual bool initWithFile(const std::string& file) override; + virtual bool initWithFile(std::string_view file) override; /** * Initializes a 9-slice sprite with an sprite frame name. @@ -291,7 +291,7 @@ public: * @param spriteFrameName The sprite frame name. * @return True if initializes success, false otherwise. */ - virtual bool initWithSpriteFrameName(const std::string& spriteFrameName) override; + virtual bool initWithSpriteFrameName(std::string_view spriteFrameName) override; virtual bool init() override; diff --git a/cocos/ui/UIScrollView.cpp b/cocos/ui/UIScrollView.cpp index ae12b010d5..b0df2ffd9e 100644 --- a/cocos/ui/UIScrollView.cpp +++ b/cocos/ui/UIScrollView.cpp @@ -287,7 +287,7 @@ void ScrollView::addChild(Node* child, int zOrder, int tag) _innerContainer->addChild(child, zOrder, tag); } -void ScrollView::addChild(Node* child, int zOrder, const std::string& name) +void ScrollView::addChild(Node* child, int zOrder, std::string_view name) { child->setGlobalZOrder(_globalZOrder); _innerContainer->addChild(child, zOrder, name); @@ -328,7 +328,7 @@ Node* ScrollView::getChildByTag(int tag) const return _innerContainer->getChildByTag(tag); } -Node* ScrollView::getChildByName(const std::string& name) const +Node* ScrollView::getChildByName(std::string_view name) const { return _innerContainer->getChildByName(name); } diff --git a/cocos/ui/UIScrollView.h b/cocos/ui/UIScrollView.h index 96d9949a77..c1cbe9ba8c 100644 --- a/cocos/ui/UIScrollView.h +++ b/cocos/ui/UIScrollView.h @@ -343,7 +343,7 @@ public: virtual void addChild(Node* child) override; virtual void addChild(Node* child, int localZOrder) override; virtual void addChild(Node* child, int localZOrder, int tag) override; - virtual void addChild(Node* child, int localZOrder, const std::string& name) override; + virtual void addChild(Node* child, int localZOrder, std::string_view name) override; virtual void removeAllChildren() override; virtual void removeAllChildrenWithCleanup(bool cleanup) override; virtual void removeChild(Node* child, bool cleanup = true) override; @@ -351,7 +351,7 @@ public: virtual const Vector& getChildren() const override; virtual ssize_t getChildrenCount() const override; virtual Node* getChildByTag(int tag) const override; - virtual Node* getChildByName(const std::string& name) const override; + virtual Node* getChildByName(std::string_view name) const override; // touch event callback virtual bool onTouchBegan(Touch* touch, Event* unusedEvent) override; virtual void onTouchMoved(Touch* touch, Event* unusedEvent) override; diff --git a/cocos/ui/UISlider.cpp b/cocos/ui/UISlider.cpp index c28cfbbca5..f1c9919ef2 100644 --- a/cocos/ui/UISlider.cpp +++ b/cocos/ui/UISlider.cpp @@ -103,8 +103,8 @@ Slider* Slider::create() return nullptr; } -Slider* Slider::create(const std::string& barTextureName, - const std::string& normalBallTextureName, +Slider* Slider::create(std::string_view barTextureName, + std::string_view normalBallTextureName, TextureResType resType) { Slider* widget = new Slider(); @@ -157,7 +157,7 @@ void Slider::initRenderer() addProtectedChild(_slidBallRenderer, SLIDBALL_RENDERER_Z, -1); } -void Slider::loadBarTexture(const std::string& fileName, TextureResType texType) +void Slider::loadBarTexture(std::string_view fileName, TextureResType texType) { _textureFile = fileName; _barTexType = texType; @@ -202,7 +202,7 @@ void Slider::setupBarTexture() _originalBarRect = _barRenderer->getTextureRect(); } -void Slider::loadProgressBarTexture(const std::string& fileName, TextureResType texType) +void Slider::loadProgressBarTexture(std::string_view fileName, TextureResType texType) { _progressBarTextureFile = fileName; _progressBarTexType = texType; @@ -330,9 +330,9 @@ const Rect& Slider::getCapInsetsProgressBarRenderer() const return _capInsetsProgressBarRenderer; } -void Slider::loadSlidBallTextures(const std::string& normal, - const std::string& pressed, - const std::string& disabled, +void Slider::loadSlidBallTextures(std::string_view normal, + std::string_view pressed, + std::string_view disabled, TextureResType texType) { loadSlidBallTextureNormal(normal, texType); @@ -340,7 +340,7 @@ void Slider::loadSlidBallTextures(const std::string& normal, loadSlidBallTextureDisabled(disabled, texType); } -void Slider::loadSlidBallTextureNormal(const std::string& normal, TextureResType texType) +void Slider::loadSlidBallTextureNormal(std::string_view normal, TextureResType texType) { _slidBallNormalTextureFile = normal; _ballNTexType = texType; @@ -370,7 +370,7 @@ void Slider::loadSlidBallTextureNormal(SpriteFrame* spriteframe) this->updateChildrenDisplayedRGBA(); } -void Slider::loadSlidBallTexturePressed(const std::string& pressed, TextureResType texType) +void Slider::loadSlidBallTexturePressed(std::string_view pressed, TextureResType texType) { _slidBallPressedTextureFile = pressed; _isSliderBallPressedTextureLoaded = !pressed.empty(); @@ -402,7 +402,7 @@ void Slider::loadSlidBallTexturePressed(SpriteFrame* spriteframe) this->updateChildrenDisplayedRGBA(); } -void Slider::loadSlidBallTextureDisabled(const std::string& disabled, TextureResType texType) +void Slider::loadSlidBallTextureDisabled(std::string_view disabled, TextureResType texType) { _slidBallDisabledTextureFile = disabled; _isSliderBallDisabledTexturedLoaded = !disabled.empty(); diff --git a/cocos/ui/UISlider.h b/cocos/ui/UISlider.h index b0b30ad0c9..d774b40795 100644 --- a/cocos/ui/UISlider.h +++ b/cocos/ui/UISlider.h @@ -98,8 +98,8 @@ public: * @param resType Texture resource type. * @return An autoreleased Slider object. */ - static Slider* create(const std::string& barTextureName, - const std::string& normalBallTextureName, + static Slider* create(std::string_view barTextureName, + std::string_view normalBallTextureName, TextureResType resType = TextureResType::LOCAL); /** @@ -108,7 +108,7 @@ public: * @param fileName File name of texture. * @param resType @see TextureResType . */ - void loadBarTexture(const std::string& fileName, TextureResType resType = TextureResType::LOCAL); + void loadBarTexture(std::string_view fileName, TextureResType resType = TextureResType::LOCAL); /** * Sets if slider is using scale9 renderer. @@ -162,9 +162,9 @@ public: * @param disabled Disabled state texture. * @param texType @see TextureResType . */ - void loadSlidBallTextures(const std::string& normal, - const std::string& pressed = "", - const std::string& disabled = "", + void loadSlidBallTextures(std::string_view normal, + std::string_view pressed = "", + std::string_view disabled = "", TextureResType texType = TextureResType::LOCAL); /** @@ -173,7 +173,7 @@ public: * @param normal Normal state texture. * @param resType @see TextureResType . */ - void loadSlidBallTextureNormal(const std::string& normal, TextureResType resType = TextureResType::LOCAL); + void loadSlidBallTextureNormal(std::string_view normal, TextureResType resType = TextureResType::LOCAL); /** * Load pressed state texture for slider ball. @@ -181,7 +181,7 @@ public: * @param pressed Pressed state texture. * @param resType @see TextureResType . */ - void loadSlidBallTexturePressed(const std::string& pressed, TextureResType resType = TextureResType::LOCAL); + void loadSlidBallTexturePressed(std::string_view pressed, TextureResType resType = TextureResType::LOCAL); /** * Load disabled state texture for slider ball. @@ -189,7 +189,7 @@ public: * @param disabled Disabled state texture. * @param resType @see TextureResType . */ - void loadSlidBallTextureDisabled(const std::string& disabled, TextureResType resType = TextureResType::LOCAL); + void loadSlidBallTextureDisabled(std::string_view disabled, TextureResType resType = TextureResType::LOCAL); /** * Load dark state texture for slider progress bar. @@ -197,7 +197,7 @@ public: * @param fileName File path of texture. * @param resType @see TextureResType . */ - void loadProgressBarTexture(const std::string& fileName, TextureResType resType = TextureResType::LOCAL); + void loadProgressBarTexture(std::string_view fileName, TextureResType resType = TextureResType::LOCAL); /** * Changes the progress direction of slider. diff --git a/cocos/ui/UITabControl.cpp b/cocos/ui/UITabControl.cpp index 65c9b54f9a..37e9c39614 100644 --- a/cocos/ui/UITabControl.cpp +++ b/cocos/ui/UITabControl.cpp @@ -487,9 +487,9 @@ TabHeader* TabHeader::create() return nullptr; } -TabHeader* TabHeader::create(const std::string& titleStr, - const std::string& backGround, - const std::string& cross, +TabHeader* TabHeader::create(std::string_view titleStr, + std::string_view backGround, + std::string_view cross, TextureResType texType) { TabHeader* tabcell = new TabHeader; @@ -505,12 +505,12 @@ TabHeader* TabHeader::create(const std::string& titleStr, return nullptr; } -TabHeader* TabHeader::create(const std::string& titleStr, - const std::string& backGround, - const std::string& backGroundSelected, - const std::string& cross, - const std::string& backGroundDisabled, - const std::string& frontCrossDisabled, +TabHeader* TabHeader::create(std::string_view titleStr, + std::string_view backGround, + std::string_view backGroundSelected, + std::string_view cross, + std::string_view backGroundDisabled, + std::string_view frontCrossDisabled, TextureResType texType /*= TextureResType::LOCAL*/) { TabHeader* tabcell = new TabHeader; @@ -543,7 +543,7 @@ void TabHeader::initRenderer() addProtectedChild(_tabLabelRender, -1, -1); } -void TabHeader::setTitleText(const std::string& text) +void TabHeader::setTitleText(std::string_view text) { if (text == getTitleText()) { @@ -555,11 +555,11 @@ void TabHeader::setTitleText(const std::string& text) _tabLabelRender->setPosition(_contentSize * 0.5f); } -std::string TabHeader::getTitleText() const +std::string_view TabHeader::getTitleText() const { if (nullptr == _tabLabelRender) { - return ""; + return ""sv; } return _tabLabelRender->getString(); } @@ -609,11 +609,11 @@ void TabHeader::updateContentSize() onSizeChanged(); } -void TabHeader::setTitleFontName(const std::string& fontName) +void TabHeader::setTitleFontName(std::string_view fontName) { if (FileUtils::getInstance()->isFileExist(fontName)) { - std::string lowerCasedFontName = fontName; + std::string lowerCasedFontName{fontName}; std::transform(lowerCasedFontName.begin(), lowerCasedFontName.end(), lowerCasedFontName.begin(), ::tolower); if (lowerCasedFontName.find(".fnt") != std::string::npos) { @@ -647,7 +647,7 @@ Label* TabHeader::getTitleRenderer() const return _tabLabelRender; } -std::string TabHeader::getTitleFontName() const +std::string_view TabHeader::getTitleFontName() const { if (this->_fontType == FontType::SYSTEM) { @@ -661,7 +661,7 @@ std::string TabHeader::getTitleFontName() const { return _tabLabelRender->getBMFontFilePath(); } - return ""; + return ""sv; } void TabHeader::onSizeChanged() diff --git a/cocos/ui/UITabControl.h b/cocos/ui/UITabControl.h index 7da800751d..98765bdde4 100644 --- a/cocos/ui/UITabControl.h +++ b/cocos/ui/UITabControl.h @@ -70,9 +70,9 @@ public: * @param texType The texture's resource type in `Widget::TextureResType`. * @return A TabHeader instance pointer */ - static TabHeader* create(const std::string& titleStr, - const std::string& backGround, - const std::string& cross, + static TabHeader* create(std::string_view titleStr, + std::string_view backGround, + std::string_view cross, TextureResType texType = TextureResType::LOCAL); /** @@ -87,12 +87,12 @@ public: * * @return A TabHeader instance pointer. */ - static TabHeader* create(const std::string& titleStr, - const std::string& backGround, - const std::string& backGroundSelected, - const std::string& cross, - const std::string& backGroundDisabled, - const std::string& frontCrossDisabled, + static TabHeader* create(std::string_view titleStr, + std::string_view backGround, + std::string_view backGroundSelected, + std::string_view cross, + std::string_view backGroundDisabled, + std::string_view frontCrossDisabled, TextureResType texType = TextureResType::LOCAL); /** * Return the inner Label renderer of TabHeader. @@ -104,13 +104,13 @@ public: * Change the content of Header's text. *@param text The Header's text. */ - void setTitleText(const std::string& text); + void setTitleText(std::string_view text); /** * get the TabHeader text *@return he TabHeader text */ - std::string getTitleText() const; + std::string_view getTitleText() const; /** * Change the color of he TabHeader text @@ -140,13 +140,13 @@ public: * Change the font name of TabHeader text *@param fontName a font name string. */ - void setTitleFontName(const std::string& fontName); + void setTitleFontName(std::string_view fontName); /** * get the font name of TabHeader text *@return font name in std::string */ - std::string getTitleFontName() const; + std::string_view getTitleFontName() const; /** * get the index this header in the TabControl diff --git a/cocos/ui/UIText.cpp b/cocos/ui/UIText.cpp index db2457e216..554e024292 100644 --- a/cocos/ui/UIText.cpp +++ b/cocos/ui/UIText.cpp @@ -71,7 +71,7 @@ bool Text::init() return false; } -Text* Text::create(const std::string& textContent, const std::string& fontName, float fontSize) +Text* Text::create(std::string_view textContent, std::string_view fontName, float fontSize) { Text* text = new Text(); if (text->init(textContent, fontName, fontSize)) @@ -83,7 +83,7 @@ Text* Text::create(const std::string& textContent, const std::string& fontName, return nullptr; } -bool Text::init(const std::string& textContent, const std::string& fontName, float fontSize) +bool Text::init(std::string_view textContent, std::string_view fontName, float fontSize) { bool ret = true; do @@ -117,7 +117,7 @@ void Text::setString(std::string_view text) _labelRendererAdaptDirty = true; } -const std::string& Text::getString() const +std::string_view Text::getString() const { return _labelRenderer->getString(); } @@ -149,7 +149,7 @@ float Text::getFontSize() const return _fontSize; } -void Text::setFontName(const std::string& name) +void Text::setFontName(std::string_view name) { if (FileUtils::getInstance()->isFileExist(name)) { @@ -173,7 +173,7 @@ void Text::setFontName(const std::string& name) _labelRendererAdaptDirty = true; } -const std::string& Text::getFontName() const +std::string_view Text::getFontName() const { return _fontName; } diff --git a/cocos/ui/UIText.h b/cocos/ui/UIText.h index 39721ef697..10b980a381 100644 --- a/cocos/ui/UIText.h +++ b/cocos/ui/UIText.h @@ -96,7 +96,7 @@ public: * @param fontSize A given font size. * @return An autoreleased Text object. */ - static Text* create(const std::string& textContent, const std::string& fontName, float fontSize); + static Text* create(std::string_view textContent, std::string_view fontName, float fontSize); /** * Changes the string value of label. @@ -110,7 +110,7 @@ public: * * @return String value. */ - const std::string& getString() const; + std::string_view getString() const; /** * Gets the string length of the label. @@ -151,13 +151,13 @@ public: * @endcode * @param name Font name. */ - void setFontName(const std::string& name); + void setFontName(std::string_view name); /** Gets the font name. * * @return Font name. */ - const std::string& getFontName() const; + std::string_view getFontName() const; /** Gets the font type. * @return The font type. @@ -342,7 +342,7 @@ public: virtual const BlendFunc& getBlendFunc() const override; CC_CONSTRUCTOR_ACCESS : virtual bool init() override; - virtual bool init(const std::string& textContent, const std::string& fontName, float fontSize); + virtual bool init(std::string_view textContent, std::string_view fontName, float fontSize); protected: virtual void initRenderer() override; diff --git a/cocos/ui/UITextAtlas.cpp b/cocos/ui/UITextAtlas.cpp index 98eb85c0e8..e6ab8300fe 100644 --- a/cocos/ui/UITextAtlas.cpp +++ b/cocos/ui/UITextAtlas.cpp @@ -66,11 +66,11 @@ void TextAtlas::initRenderer() addProtectedChild(_labelAtlasRenderer, LABELATLAS_RENDERER_Z, -1); } -TextAtlas* TextAtlas::create(const std::string& stringValue, - const std::string& charMapFile, +TextAtlas* TextAtlas::create(std::string_view stringValue, + std::string_view charMapFile, int itemWidth, int itemHeight, - const std::string& startCharMap) + std::string_view startCharMap) { TextAtlas* widget = new TextAtlas(); if (widget->init()) @@ -83,11 +83,11 @@ TextAtlas* TextAtlas::create(const std::string& stringValue, return nullptr; } -void TextAtlas::setProperty(const std::string& stringValue, - const std::string& charMapFile, +void TextAtlas::setProperty(std::string_view stringValue, + std::string_view charMapFile, int itemWidth, int itemHeight, - const std::string& startCharMap) + std::string_view startCharMap) { _stringValue = stringValue; _charMapFileName = charMapFile; @@ -116,7 +116,7 @@ void TextAtlas::setString(std::string_view value) // CCLOG("cssss w %f, h %f", _contentSize.width, _contentSize.height); } -const std::string& TextAtlas::getString() const +std::string_view TextAtlas::getString() const { return _labelAtlasRenderer->getString(); } diff --git a/cocos/ui/UITextAtlas.h b/cocos/ui/UITextAtlas.h index f84739ada0..25b9817f57 100644 --- a/cocos/ui/UITextAtlas.h +++ b/cocos/ui/UITextAtlas.h @@ -82,11 +82,11 @@ public: * @param startCharMap The starting char of the atlas. * @return An autoreleased TextAtlas object. */ - static TextAtlas* create(const std::string& stringValue, - const std::string& charMapFile, + static TextAtlas* create(std::string_view stringValue, + std::string_view charMapFile, int itemWidth, int itemHeight, - const std::string& startCharMap); + std::string_view startCharMap); /** Initializes the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and * the starting char of the atlas. @@ -98,11 +98,11 @@ public: * @param startCharMap The starting char of the atlas. */ - void setProperty(const std::string& stringValue, - const std::string& charMapFile, + void setProperty(std::string_view stringValue, + std::string_view charMapFile, int itemWidth, int itemHeight, - const std::string& startCharMap); + std::string_view startCharMap); /**Set string value for labelatlas. * @@ -114,7 +114,7 @@ public: * * @return The string value of TextAtlas. */ - const std::string& getString() const; + std::string_view getString() const; /** * Gets the string length of the label. diff --git a/cocos/ui/UITextBMFont.cpp b/cocos/ui/UITextBMFont.cpp index 125f921598..28de90891b 100644 --- a/cocos/ui/UITextBMFont.cpp +++ b/cocos/ui/UITextBMFont.cpp @@ -53,7 +53,7 @@ TextBMFont* TextBMFont::create() return nullptr; } -TextBMFont* TextBMFont::create(const std::string& text, const std::string& filename) +TextBMFont* TextBMFont::create(std::string_view text, std::string_view filename) { TextBMFont* widget = new TextBMFont(); if (widget->init()) @@ -73,7 +73,7 @@ void TextBMFont::initRenderer() addProtectedChild(_labelBMFontRenderer, LABELBMFONT_RENDERER_Z, -1); } -void TextBMFont::setFntFile(const std::string& fileName) +void TextBMFont::setFntFile(std::string_view fileName) { if (fileName.empty()) { @@ -86,7 +86,7 @@ void TextBMFont::setFntFile(const std::string& fileName) _labelBMFontRendererAdaptDirty = true; } -void TextBMFont::setString(const std::string& value) +void TextBMFont::setString(std::string_view value) { if (value == _labelBMFontRenderer->getString()) { @@ -98,7 +98,7 @@ void TextBMFont::setString(const std::string& value) _labelBMFontRendererAdaptDirty = true; } -const std::string& TextBMFont::getString() const +std::string_view TextBMFont::getString() const { return _stringValue; } diff --git a/cocos/ui/UITextBMFont.h b/cocos/ui/UITextBMFont.h index 70fb5564d1..eb3f16fc67 100644 --- a/cocos/ui/UITextBMFont.h +++ b/cocos/ui/UITextBMFont.h @@ -69,16 +69,16 @@ public: */ static TextBMFont* create(); - static TextBMFont* create(const std::string& text, const std::string& filename); + static TextBMFont* create(std::string_view text, std::string_view filename); /** init a bitmap font atlas with an initial string and the FNT file */ - void setFntFile(const std::string& fileName); + void setFntFile(std::string_view fileName); /** set string value for labelbmfont*/ - void setString(const std::string& value); + void setString(std::string_view value); /** get string value for labelbmfont*/ - const std::string& getString() const; + std::string_view getString() const; /** * Gets the string length of the label. diff --git a/cocos/ui/UITextField.cpp b/cocos/ui/UITextField.cpp index 25b75a61e2..8e16b2a83a 100644 --- a/cocos/ui/UITextField.cpp +++ b/cocos/ui/UITextField.cpp @@ -52,7 +52,7 @@ UICCTextField::UICCTextField() UICCTextField::~UICCTextField() {} -UICCTextField* UICCTextField::create(const std::string& placeholder, const std::string& fontName, float fontSize) +UICCTextField* UICCTextField::create(std::string_view placeholder, std::string_view fontName, float fontSize) { UICCTextField* pRet = new UICCTextField(); @@ -191,12 +191,12 @@ bool UICCTextField::isPasswordEnabled() const return this->isSecureTextEntry(); } -void UICCTextField::setPasswordStyleText(const std::string& styleText) +void UICCTextField::setPasswordStyleText(std::string_view styleText) { this->setPasswordTextStyle(styleText); } -void UICCTextField::setPasswordText(const std::string& text) +void UICCTextField::setPasswordText(std::string_view text) { std::string tempStr = ""; int32_t text_count = StringUtils::getCharacterCountInUTF8String(text); @@ -292,7 +292,7 @@ TextField* TextField::create() return nullptr; } -TextField* TextField::create(const std::string& placeholder, const std::string& fontName, int fontSize) +TextField* TextField::create(std::string_view placeholder, std::string_view fontName, int fontSize) { TextField* widget = new TextField(); if (widget->init()) @@ -358,7 +358,7 @@ Vec2 TextField::getTouchSize() const return Vec2(_touchWidth, _touchHeight); } -void TextField::setString(const std::string& text) +void TextField::setString(std::string_view text) { std::string strText(text); @@ -386,14 +386,14 @@ void TextField::setString(const std::string& text) updateContentSizeWithTextureSize(_textFieldRenderer->getContentSize()); } -void TextField::setPlaceHolder(const std::string& value) +void TextField::setPlaceHolder(std::string_view value) { _textFieldRenderer->setPlaceHolder(value); _textFieldRendererAdaptDirty = true; updateContentSizeWithTextureSize(_textFieldRenderer->getContentSize()); } -const std::string& TextField::getPlaceHolder() const +std::string_view TextField::getPlaceHolder() const { return _textFieldRenderer->getPlaceHolder(); } @@ -449,11 +449,11 @@ int TextField::getFontSize() const return _fontSize; } -void TextField::setFontName(const std::string& name) +void TextField::setFontName(std::string_view name) { if (FileUtils::getInstance()->isFileExist(name)) { - std::string lcName = name; + std::string lcName{name}; std::transform(lcName.begin(), lcName.end(), lcName.begin(), ::tolower); if (lcName.substr(lcName.length() - 4) == ".fnt") { @@ -483,7 +483,7 @@ void TextField::setFontName(const std::string& name) updateContentSizeWithTextureSize(_textFieldRenderer->getContentSize()); } -const std::string& TextField::getFontName() const +std::string_view TextField::getFontName() const { return _fontName; } @@ -493,7 +493,7 @@ void TextField::didNotSelectSelf() _textFieldRenderer->detachWithIME(); } -const std::string& TextField::getString() const +std::string_view TextField::getString() const { return _textFieldRenderer->getString(); } @@ -563,7 +563,7 @@ void TextField::setPasswordStyleText(const char* styleText) const char* TextField::getPasswordStyleText() const { - return _textFieldRenderer->getPasswordTextStyle().c_str(); + return _textFieldRenderer->getPasswordTextStyle().data(); } void TextField::update(float /*dt*/) diff --git a/cocos/ui/UITextField.h b/cocos/ui/UITextField.h index 2e9c8a8362..c39bcc410b 100644 --- a/cocos/ui/UITextField.h +++ b/cocos/ui/UITextField.h @@ -74,7 +74,7 @@ public: *@param fontSize Font size in float. *@return A UICCTextField instance. */ - static UICCTextField* create(const std::string& placeholder, const std::string& fontName, float fontSize); + static UICCTextField* create(std::string_view placeholder, std::string_view fontName, float fontSize); // override functions virtual bool onTextFieldAttachWithIME(TextFieldTTF* pSender) override; @@ -142,14 +142,14 @@ public: * * @param styleText The styleText for password mask, the default value is "*". */ - void setPasswordStyleText(const std::string& styleText); + void setPasswordStyleText(std::string_view styleText); /** * @brief Set the password text content. * * @param text The content of password. */ - void setPasswordText(const std::string& text); + void setPasswordText(std::string_view text); /** * @brief Toggle attach with IME. @@ -270,7 +270,7 @@ public: * @param fontSize The font size. * @return A TextField instance. */ - static TextField* create(const std::string& placeholder, const std::string& fontName, int fontSize); + static TextField* create(std::string_view placeholder, std::string_view fontName, int fontSize); /** * @brief Set the touch size @@ -300,14 +300,14 @@ public: * * @param value The string value of placeholder. */ - void setPlaceHolder(const std::string& value); + void setPlaceHolder(std::string_view value); /** * @brief Get the placeholder of TextField. * * @return A placeholder string. */ - const std::string& getPlaceHolder() const; + std::string_view getPlaceHolder() const; /** * @brief Query the placeholder string color. @@ -363,14 +363,14 @@ public: * * @param name The font name string. */ - void setFontName(const std::string& name); + void setFontName(std::string_view name); /** * @brief Query the TextField's font name. * * @return The font name string. */ - const std::string& getFontName() const; + std::string_view getFontName() const; /** * @brief Detach the IME. @@ -381,13 +381,13 @@ public: *Change content of TextField. *@param text A string content. */ - void setString(const std::string& text); + void setString(std::string_view text); /** *Query the content of TextField. *@return The string value of TextField. */ - const std::string& getString() const; + std::string_view getString() const; virtual bool onTouchBegan(Touch* touch, Event* unusedEvent) override; diff --git a/cocos/ui/UITextFieldEx.cpp b/cocos/ui/UITextFieldEx.cpp index 90e45b4a28..a14258c1b8 100644 --- a/cocos/ui/UITextFieldEx.cpp +++ b/cocos/ui/UITextFieldEx.cpp @@ -28,8 +28,8 @@ NS_CC_BEGIN # define nxbeep(t) #endif -static Label* createLabel(const std::string& text, - const std::string& font, +static Label* createLabel(std::string_view text, + std::string_view font, float fontSize, const Vec2& dimensions = Vec2::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT, @@ -161,7 +161,7 @@ static int _truncateUTF8String(const char* text, int limit, int& nb) return n; } -static void internalSetLableFont(Label* l, const std::string& fontName, float fontSize) +static void internalSetLableFont(Label* l, std::string_view fontName, float fontSize) { if (FileUtils::getInstance()->isFileExist(fontName)) { @@ -178,7 +178,7 @@ static void internalSetLableFont(Label* l, const std::string& fontName, float fo } } -static float internalCalcStringWidth(std::string_view s, const std::string& fontName, float fontSize) +static float internalCalcStringWidth(std::string_view s, std::string_view fontName, float fontSize) { auto label = createLabel(std::string{s}, fontName, fontSize); return label->getContentSize().width; @@ -269,8 +269,8 @@ TextFieldEx::~TextFieldEx() ////////////////////////////////////////////////////////////////////////// // static constructor ////////////////////////////////////////////////////////////////////////// -TextFieldEx* TextFieldEx::create(const std::string& placeholder, - const std::string& fontName, +TextFieldEx* TextFieldEx::create(std::string_view placeholder, + std::string_view fontName, float fontSize, float cursorWidth, const Color4B& cursorColor) @@ -292,8 +292,8 @@ TextFieldEx* TextFieldEx::create(const std::string& placeholder, ////////////////////////////////////////////////////////////////////////// // initialize ////////////////////////////////////////////////////////////////////////// -bool TextFieldEx::initWithPlaceHolder(const std::string& placeholder, - const std::string& fontName, +bool TextFieldEx::initWithPlaceHolder(std::string_view placeholder, + std::string_view fontName, float fontSize, float cursorWidth, const Color4B& cursorColor) @@ -316,12 +316,12 @@ bool TextFieldEx::initWithPlaceHolder(const std::string& placeholder, return true; } -const std::string& TextFieldEx::getTextFontName() const +std::string_view TextFieldEx::getTextFontName() const { return this->fontName; } -void TextFieldEx::setTextFontName(const std::string& fontName) +void TextFieldEx::setTextFontName(std::string_view fontName) { if (FileUtils::getInstance()->isFileExist(fontName)) { @@ -740,7 +740,7 @@ void TextFieldEx::handleDeleteKeyEvent() this->onTextModify(); } -const std::string& TextFieldEx::getContentText() +std::string_view TextFieldEx::getContentText() { return inputText; } @@ -784,7 +784,7 @@ void TextFieldEx::setPlaceholderColor(const Color4B& color) ////////////////////////////////////////////////////////////////////////// // input text property -void TextFieldEx::setString(const std::string& text) +void TextFieldEx::setString(std::string_view text) { static char bulletString[] = {(char)0xe2, (char)0x80, (char)0xa2, (char)0x00}; @@ -838,13 +838,13 @@ void TextFieldEx::updateContentSize(void) this->setContentSize(renderLabel->getContentSize()); } -const std::string& TextFieldEx::getString() const +std::string_view TextFieldEx::getString() const { return inputText; } // place holder text property -void TextFieldEx::setPlaceholderText(const std::string& text) +void TextFieldEx::setPlaceholderText(std::string_view text) { placeHolder = text; if (inputText.empty()) @@ -854,7 +854,7 @@ void TextFieldEx::setPlaceholderText(const std::string& text) } } -const std::string& TextFieldEx::getPlaceholderText() const +std::string_view TextFieldEx::getPlaceholderText() const { return placeHolder; } diff --git a/cocos/ui/UITextFieldEx.h b/cocos/ui/UITextFieldEx.h index b94a7c7a2b..a337388c0f 100644 --- a/cocos/ui/UITextFieldEx.h +++ b/cocos/ui/UITextFieldEx.h @@ -29,14 +29,14 @@ public: */ virtual ~TextFieldEx(); - static TextFieldEx* create(const std::string& placeholder, - const std::string& fontName, + static TextFieldEx* create(std::string_view placeholder, + std::string_view fontName, float fontSize, float cursorWidth = 2, const Color4B& color = Color4B::WHITE); - bool initWithPlaceHolder(const std::string& placeholder, - const std::string& fontName, + bool initWithPlaceHolder(std::string_view placeholder, + std::string_view fontName, float fontSize, float cursorWidth = 2, const Color4B& color = Color4B::WHITE); @@ -58,8 +58,8 @@ public: const Color3B& getCursorColor(void) const; // input text property - virtual void setString(const std::string& text); - virtual const std::string& getString() const; + virtual void setString(std::string_view text); + virtual std::string_view getString() const; // Continuous touch event trigger support. void setContinuousTouchDelayTime(float delay) { _continuousTouchDelayTime = delay; } @@ -71,8 +71,8 @@ public: // place holder text property // place holder text displayed when there is no text in the text field. - virtual void setPlaceholderText(const std::string& text); - virtual const std::string& getPlaceholderText(void) const; + virtual void setPlaceholderText(std::string_view text); + virtual std::string_view getPlaceholderText(void) const; virtual void setPasswordEnabled(bool value); virtual bool isPasswordEnabled() const; @@ -97,8 +97,8 @@ public: /// fonts void setTextFontSize(float size); float getTextFontSize() const; - void setTextFontName(const std::string& fontName); - const std::string& getTextFontName() const; + void setTextFontName(std::string_view fontName); + std::string_view getTextFontName() const; CC_SYNTHESIZE(size_t, charLimit, CharLimit); @@ -122,7 +122,7 @@ protected: virtual bool canDetachWithIME() override; virtual void deleteBackward() override; - virtual const std::string& getContentText() override; + virtual std::string_view getContentText() override; void handleDeleteKeyEvent(); diff --git a/cocos/ui/UIVideoPlayer-android.cpp b/cocos/ui/UIVideoPlayer-android.cpp index dab2aafc7b..b43537e4f0 100644 --- a/cocos/ui/UIVideoPlayer-android.cpp +++ b/cocos/ui/UIVideoPlayer-android.cpp @@ -124,7 +124,7 @@ VideoPlayer::~VideoPlayer() JniHelper::callStaticVoidMethod(videoHelperClassName, "removeVideoWidget", _videoPlayerIndex); } -void VideoPlayer::setFileName(const std::string& fileName) +void VideoPlayer::setFileName(std::string_view fileName) { _videoURL = FileUtils::getInstance()->fullPathForFilename(fileName); _videoSource = VideoPlayer::Source::FILENAME; @@ -132,7 +132,7 @@ void VideoPlayer::setFileName(const std::string& fileName) _videoURL); } -void VideoPlayer::setURL(const std::string& videoUrl) +void VideoPlayer::setURL(std::string_view videoUrl) { _videoURL = videoUrl; _videoSource = VideoPlayer::Source::URL; diff --git a/cocos/ui/UIVideoPlayer-ios.mm b/cocos/ui/UIVideoPlayer-ios.mm index f41d63a57f..24f925c2a7 100644 --- a/cocos/ui/UIVideoPlayer-ios.mm +++ b/cocos/ui/UIVideoPlayer-ios.mm @@ -290,14 +290,14 @@ VideoPlayer::~VideoPlayer() } } -void VideoPlayer::setFileName(const std::string& fileName) +void VideoPlayer::setFileName(std::string_view fileName) { _videoURL = FileUtils::getInstance()->fullPathForFilename(fileName); _videoSource = VideoPlayer::Source::FILENAME; [((UIVideoViewWrapperIos*)_videoView) setURL:(int)_videoSource :_videoURL]; } -void VideoPlayer::setURL(const std::string& videoUrl) +void VideoPlayer::setURL(std::string_view videoUrl) { _videoURL = videoUrl; _videoSource = VideoPlayer::Source::URL; diff --git a/cocos/ui/UIVideoPlayer.h b/cocos/ui/UIVideoPlayer.h index c97d5c3b7b..76e82663f2 100644 --- a/cocos/ui/UIVideoPlayer.h +++ b/cocos/ui/UIVideoPlayer.h @@ -86,26 +86,26 @@ public: /** * Sets a file path as a video source for VideoPlayer. */ - virtual void setFileName(const std::string& videoPath); + virtual void setFileName(std::string_view videoPath); /** * @brief Get the local video file name. * * @return The video file name. */ - virtual const std::string& getFileName() const { return _videoURL; } + virtual std::string_view getFileName() const { return _videoURL; } /** * Sets a URL as a video source for VideoPlayer. */ - virtual void setURL(const std::string& _videoURL); + virtual void setURL(std::string_view _videoURL); /** * @brief Get the URL of remoting video source. * * @return A remoting URL address. */ - virtual const std::string& getURL() const { return _videoURL; } + virtual std::string_view getURL() const { return _videoURL; } /** * @brief Set if playback is done in loop mode diff --git a/cocos/ui/UIWebView/UIWebView-inl.h b/cocos/ui/UIWebView/UIWebView-inl.h index 586aecc8e5..8f510b0177 100644 --- a/cocos/ui/UIWebView/UIWebView-inl.h +++ b/cocos/ui/UIWebView/UIWebView-inl.h @@ -53,35 +53,35 @@ WebView* WebView::create() return nullptr; } -void WebView::setJavascriptInterfaceScheme(const std::string& scheme) +void WebView::setJavascriptInterfaceScheme(std::string_view scheme) { _impl->setJavascriptInterfaceScheme(scheme); } void WebView::loadData(const cocos2d::Data& data, - const std::string& MIMEType, - const std::string& encoding, - const std::string& baseURL) + std::string_view MIMEType, + std::string_view encoding, + std::string_view baseURL) { _impl->loadData(data, MIMEType, encoding, baseURL); } -void WebView::loadHTMLString(const std::string& string, const std::string& baseURL) +void WebView::loadHTMLString(std::string_view string, std::string_view baseURL) { _impl->loadHTMLString(string, baseURL); } -void WebView::loadURL(const std::string& url) +void WebView::loadURL(std::string_view url) { this->loadURL(url, false); } -void WebView::loadURL(const std::string& url, bool cleanCachedData) +void WebView::loadURL(std::string_view url, bool cleanCachedData) { _impl->loadURL(url, cleanCachedData); } -void WebView::loadFile(const std::string& fileName) +void WebView::loadFile(std::string_view fileName) { _impl->loadFile(fileName); } @@ -116,7 +116,7 @@ void WebView::goForward() _impl->goForward(); } -void WebView::evaluateJS(const std::string& js) +void WebView::evaluateJS(std::string_view js) { _impl->evaluateJS(js); } @@ -204,7 +204,7 @@ void WebView::setOnDidFinishLoading(const ccWebViewCallback& callback) _onDidFinishLoading = callback; } -void WebView::setOnShouldStartLoading(const std::function& callback) +void WebView::setOnShouldStartLoading(const std::function& callback) { _onShouldStartLoading = callback; } @@ -214,7 +214,7 @@ void WebView::setOnJSCallback(const ccWebViewCallback& callback) _onJSCallback = callback; } -std::function WebView::getOnShouldStartLoading() const +std::function WebView::getOnShouldStartLoading() const { return _onShouldStartLoading; } diff --git a/cocos/ui/UIWebView/UIWebView.h b/cocos/ui/UIWebView/UIWebView.h index bc37e130d2..e881dc7cdf 100644 --- a/cocos/ui/UIWebView/UIWebView.h +++ b/cocos/ui/UIWebView/UIWebView.h @@ -59,7 +59,7 @@ public: * * @see WebView::setOnJSCallback() */ - void setJavascriptInterfaceScheme(const std::string& scheme); + void setJavascriptInterfaceScheme(std::string_view scheme); /** * Sets the main page contents, MIME type, content encoding, and base URL. @@ -70,9 +70,9 @@ public: * @param baseURL The base URL for the content. */ void loadData(const cocos2d::Data& data, - const std::string& MIMEType, - const std::string& encoding, - const std::string& baseURL); + std::string_view MIMEType, + std::string_view encoding, + std::string_view baseURL); /** * Sets the main page content and base URL. @@ -80,28 +80,28 @@ public: * @param string The content for the main page. * @param baseURL The base URL for the content. */ - void loadHTMLString(const std::string& string, const std::string& baseURL = ""); + void loadHTMLString(std::string_view string, std::string_view baseURL = ""); /** * Loads the given URL. It doesn't clean cached data. * * @param url Content URL. */ - void loadURL(const std::string& url); + void loadURL(std::string_view url); /** * Loads the given URL with cleaning cached data or not. * @param url Content URL. * @cleanCachedData Whether to clean cached data. */ - void loadURL(const std::string& url, bool cleanCachedData); + void loadURL(std::string_view url, bool cleanCachedData); /** * Loads the given fileName. * * @param fileName Content fileName. */ - void loadFile(const std::string& fileName); + void loadFile(std::string_view fileName); /** * Stops the current load. @@ -140,7 +140,7 @@ public: /** * Evaluates JavaScript in the context of the currently displayed page. */ - void evaluateJS(const std::string& js); + void evaluateJS(std::string_view js); /** * Set WebView should support zooming. The default value is false. @@ -153,12 +153,12 @@ public: * @param callback The web view that is about to load new content. * @return YES if the web view should begin loading content; otherwise, NO. */ - void setOnShouldStartLoading(const std::function& callback); + void setOnShouldStartLoading(const std::function& callback); /** * A callback which will be called when a WebView event happens. */ - typedef std::function ccWebViewCallback; + typedef std::function ccWebViewCallback; /** * Call after a web view finishes loading. @@ -182,7 +182,7 @@ public: /** * Get the callback when WebView is about to start. */ - std::function getOnShouldStartLoading() const; + std::function getOnShouldStartLoading() const; /** * Get the callback when WebView has finished loading. @@ -231,7 +231,7 @@ protected: virtual cocos2d::ui::Widget* createCloneInstance() override; virtual void copySpecialProperties(Widget* model) override; - std::function _onShouldStartLoading = nullptr; + std::function _onShouldStartLoading = nullptr; ccWebViewCallback _onDidFinishLoading = nullptr; ccWebViewCallback _onDidFailLoading = nullptr; ccWebViewCallback _onJSCallback = nullptr; diff --git a/cocos/ui/UIWebView/UIWebViewImpl-android.cpp b/cocos/ui/UIWebView/UIWebViewImpl-android.cpp index cd61a73d6e..d713947e31 100644 --- a/cocos/ui/UIWebView/UIWebViewImpl-android.cpp +++ b/cocos/ui/UIWebView/UIWebViewImpl-android.cpp @@ -44,7 +44,7 @@ static const std::string className = "org.cocos2dx.lib.Cocos2dxWebViewHelper"; static const std::string s_defaultBaseUrl = "file:///android_asset/"; static const std::string s_sdRootBaseUrl = "file://"; -static std::string getFixedBaseUrl(const std::string& baseUrl) +static std::string getFixedBaseUrl(std::string_view baseUrl) { std::string fixedBaseUrl; if (baseUrl.empty()) @@ -165,7 +165,7 @@ int createWebViewJNI() return -1; } -std::string getUrlStringByFileName(const std::string& fileName) +std::string getUrlStringByFileName(std::string_view fileName) { // LOGD("error: %s,%d",__func__,__LINE__); const std::string basePath("file:///android_asset/"); @@ -214,31 +214,31 @@ WebViewImpl::~WebViewImpl() } void WebViewImpl::loadData(const Data& data, - const std::string& MIMEType, - const std::string& encoding, - const std::string& baseURL) + std::string_view MIMEType, + std::string_view encoding, + std::string_view baseURL) { std::string dataString(reinterpret_cast(data.getBytes()), static_cast(data.getSize())); JniHelper::callStaticVoidMethod(className, "setJavascriptInterfaceScheme", _viewTag, dataString, MIMEType, encoding, baseURL); } -void WebViewImpl::loadHTMLString(const std::string& string, const std::string& baseURL) +void WebViewImpl::loadHTMLString(std::string_view string, std::string_view baseURL) { JniHelper::callStaticVoidMethod(className, "loadHTMLString", _viewTag, string, getFixedBaseUrl(baseURL)); } -void WebViewImpl::loadURL(const std::string& url) +void WebViewImpl::loadURL(std::string_view url) { this->loadURL(url, false); } -void WebViewImpl::loadURL(const std::string& url, bool cleanCachedData) +void WebViewImpl::loadURL(std::string_view url, bool cleanCachedData) { JniHelper::callStaticVoidMethod(className, "loadUrl", _viewTag, url, cleanCachedData); } -void WebViewImpl::loadFile(const std::string& fileName) +void WebViewImpl::loadFile(std::string_view fileName) { auto fullPath = getUrlStringByFileName(fileName); JniHelper::callStaticVoidMethod(className, "loadFile", _viewTag, fullPath); @@ -274,12 +274,12 @@ void WebViewImpl::goForward() JniHelper::callStaticVoidMethod(className, "goForward", _viewTag); } -void WebViewImpl::setJavascriptInterfaceScheme(const std::string& scheme) +void WebViewImpl::setJavascriptInterfaceScheme(std::string_view scheme) { JniHelper::callStaticVoidMethod(className, "setJavascriptInterfaceScheme", _viewTag, scheme); } -void WebViewImpl::evaluateJS(const std::string& js) +void WebViewImpl::evaluateJS(std::string_view js) { JniHelper::callStaticVoidMethod(className, "evaluateJS", _viewTag, js); } @@ -289,7 +289,7 @@ void WebViewImpl::setScalesPageToFit(const bool scalesPageToFit) JniHelper::callStaticVoidMethod(className, "setScalesPageToFit", _viewTag, scalesPageToFit); } -bool WebViewImpl::shouldStartLoading(const int viewTag, const std::string& url) +bool WebViewImpl::shouldStartLoading(const int viewTag, std::string_view url) { bool allowLoad = true; auto it = s_WebViewImpls.find(viewTag); @@ -304,7 +304,7 @@ bool WebViewImpl::shouldStartLoading(const int viewTag, const std::string& url) return allowLoad; } -void WebViewImpl::didFinishLoading(const int viewTag, const std::string& url) +void WebViewImpl::didFinishLoading(const int viewTag, std::string_view url) { auto it = s_WebViewImpls.find(viewTag); if (it != s_WebViewImpls.end()) @@ -317,7 +317,7 @@ void WebViewImpl::didFinishLoading(const int viewTag, const std::string& url) } } -void WebViewImpl::didFailLoading(const int viewTag, const std::string& url) +void WebViewImpl::didFailLoading(const int viewTag, std::string_view url) { auto it = s_WebViewImpls.find(viewTag); if (it != s_WebViewImpls.end()) @@ -330,7 +330,7 @@ void WebViewImpl::didFailLoading(const int viewTag, const std::string& url) } } -void WebViewImpl::onJsCallback(const int viewTag, const std::string& message) +void WebViewImpl::onJsCallback(const int viewTag, std::string_view message) { auto it = s_WebViewImpls.find(viewTag); if (it != s_WebViewImpls.end()) diff --git a/cocos/ui/UIWebView/UIWebViewImpl-android.h b/cocos/ui/UIWebView/UIWebViewImpl-android.h index 653078cc28..7bebb3ba75 100644 --- a/cocos/ui/UIWebView/UIWebViewImpl-android.h +++ b/cocos/ui/UIWebView/UIWebViewImpl-android.h @@ -53,19 +53,19 @@ public: virtual ~WebViewImpl(); - void setJavascriptInterfaceScheme(const std::string& scheme); + void setJavascriptInterfaceScheme(std::string_view scheme); void loadData(const cocos2d::Data& data, - const std::string& MIMEType, - const std::string& encoding, - const std::string& baseURL); + std::string_view MIMEType, + std::string_view encoding, + std::string_view baseURL); - void loadHTMLString(const std::string& string, const std::string& baseURL); + void loadHTMLString(std::string_view string, std::string_view baseURL); - void loadURL(const std::string& url); - void loadURL(const std::string& url, bool cleanCachedData); + void loadURL(std::string_view url); + void loadURL(std::string_view url, bool cleanCachedData); - void loadFile(const std::string& fileName); + void loadFile(std::string_view fileName); void stopLoading(); @@ -79,7 +79,7 @@ public: void goForward(); - void evaluateJS(const std::string& js); + void evaluateJS(std::string_view js); void setScalesPageToFit(const bool scalesPageToFit); @@ -95,10 +95,10 @@ public: void setBackgroundTransparent(); - static bool shouldStartLoading(const int viewTag, const std::string& url); - static void didFinishLoading(const int viewTag, const std::string& url); - static void didFailLoading(const int viewTag, const std::string& url); - static void onJsCallback(const int viewTag, const std::string& message); + static bool shouldStartLoading(const int viewTag, std::string_view url); + static void didFinishLoading(const int viewTag, std::string_view url); + static void didFailLoading(const int viewTag, std::string_view url); + static void onJsCallback(const int viewTag, std::string_view message); private: int _viewTag; diff --git a/cocos/ui/UIWebView/UIWebViewImpl-ios.h b/cocos/ui/UIWebView/UIWebViewImpl-ios.h index 03fe18cc86..4e55c87f4a 100644 --- a/cocos/ui/UIWebView/UIWebViewImpl-ios.h +++ b/cocos/ui/UIWebView/UIWebViewImpl-ios.h @@ -49,19 +49,19 @@ public: virtual ~WebViewImpl(); - void setJavascriptInterfaceScheme(const std::string& scheme); + void setJavascriptInterfaceScheme(std::string_view scheme); void loadData(const cocos2d::Data& data, - const std::string& MIMEType, - const std::string& encoding, - const std::string& baseURL); + std::string_view MIMEType, + std::string_view encoding, + std::string_view baseURL); - void loadHTMLString(const std::string& string, const std::string& baseURL); + void loadHTMLString(std::string_view string, std::string_view baseURL); - void loadURL(const std::string& url); - void loadURL(const std::string& url, bool cleanCachedData); + void loadURL(std::string_view url); + void loadURL(std::string_view url, bool cleanCachedData); - void loadFile(const std::string& fileName); + void loadFile(std::string_view fileName); void stopLoading(); @@ -75,7 +75,7 @@ public: void goForward(); - void evaluateJS(const std::string& js); + void evaluateJS(std::string_view js); void setScalesPageToFit(const bool scalesPageToFit); diff --git a/cocos/ui/UIWebView/UIWebViewImpl-win32.cpp b/cocos/ui/UIWebView/UIWebViewImpl-win32.cpp index 89ecd6d052..aea7857f45 100644 --- a/cocos/ui/UIWebView/UIWebViewImpl-win32.cpp +++ b/cocos/ui/UIWebView/UIWebViewImpl-win32.cpp @@ -57,9 +57,9 @@ USING_NS_CC; using namespace rapidjson; -using msg_cb_t = std::function; +using msg_cb_t = std::function; -inline std::string htmlFromUri(const std::string& s) +inline std::string htmlFromUri(std::string_view s) { if (s.substr(0, 15) == "data:text/html,") { @@ -139,14 +139,14 @@ inline int jsonUnescape(const char* s, size_t n, char* out) // The following is a special case, where the exact json string is not returned due // to how rapidjson re-creates the nested object, original: "{"bar": 1}", parsed result: "{"bar":1}" // assert(jsonParse(R"({"foo": {"bar": 1}})", "foo", -1) == R"({"bar":1})"); -inline std::string jsonParse(const std::string& s, const std::string& key, const int index) +inline std::string jsonParse(std::string_view s, std::string_view key, const int index) { const char* value = nullptr; size_t value_sz{}; StringBuffer sb; Writer writer(sb); Document d; - d.Parse(s.c_str()); + d.Parse(s.data()); if (key.empty() && index > -1) { if (d.IsArray()) @@ -162,7 +162,7 @@ inline std::string jsonParse(const std::string& s, const std::string& key, const } else { - auto&& fieldItr = d.FindMember(key.c_str()); + auto&& fieldItr = d.FindMember(key.data()); if (fieldItr != d.MemberEnd()) { auto&& jsonValue = fieldItr->value; @@ -214,12 +214,12 @@ static std::string getUriStringFromArgs(ArgType* args) return {}; } -static std::string getDataURI(const std::string& data, const std::string& mime_type) +static std::string getDataURI(std::string_view data, std::string_view mime_type) { char* encodedData; cocos2d::base64Encode(reinterpret_cast(data.data()), static_cast(data.size()), &encodedData); - return "data:" + mime_type + ";base64," + utils::urlEncode(encodedData); + return std::string{"data:"}.append(mime_type).append(";base64,").append(utils::urlEncode(encodedData)); } static double getDeviceScaleFactor() @@ -250,24 +250,24 @@ class Win32WebControl public: Win32WebControl(); - bool createWebView(const std::function& shouldStartLoading, - const std::function& didFinishLoading, - const std::function& didFailLoading, - const std::function& onJsCallback); + bool createWebView(const std::function& shouldStartLoading, + const std::function& didFinishLoading, + const std::function& didFailLoading, + const std::function& onJsCallback); void removeWebView(); void setWebViewRect(const int left, const int top, const int width, const int height); - void setJavascriptInterfaceScheme(const std::string& scheme); - void loadHTMLString(const std::string& html, const std::string& baseURL); - void loadURL(const std::string& url, bool cleanCachedData); - void loadFile(const std::string& filePath); + void setJavascriptInterfaceScheme(std::string_view scheme); + void loadHTMLString(std::string_view html, std::string_view baseURL); + void loadURL(std::string_view url, bool cleanCachedData); + void loadFile(std::string_view filePath); void stopLoading(); void reload() const; bool canGoBack() const; bool canGoForward() const; void goBack() const; void goForward() const; - void evaluateJS(const std::string& js); + void evaluateJS(std::string_view js); void setScalesPageToFit(const bool scalesPageToFit); void setWebViewVisible(const bool visible) const; void setBounces(bool bounces); @@ -286,19 +286,19 @@ private: std::string m_jsScheme; bool _scalesPageToFit{}; - std::function _shouldStartLoading; - std::function _didFinishLoading; - std::function _didFailLoading; - std::function _onJsCallback; + std::function _shouldStartLoading; + std::function _didFinishLoading; + std::function _didFailLoading; + std::function _onJsCallback; static bool s_isInitialized; static void lazyInit(); - static LPWSTR to_lpwstr(const std::string s) + static LPWSTR to_lpwstr(std::string_view s) { - const int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, NULL, 0); + const int n = MultiByteToWideChar(CP_UTF8, 0, s.data(), -1, NULL, 0); auto* ws = new wchar_t[n]; - MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, ws, n); + MultiByteToWideChar(CP_UTF8, 0, s.data(), -1, ws, n); return ws; } @@ -325,7 +325,7 @@ private: m_webview->AddRef(); flag.clear(); }, - [this](const std::string& url) -> bool { + [this](std::string_view url) -> bool { const auto scheme = url.substr(0, url.find_first_of(':')); if (scheme == m_jsScheme) { @@ -358,7 +358,7 @@ private: if (_didFailLoading) _didFailLoading(result); }, - [this](const std::string& url) { loadURL(url, false); })); + [this](std::string_view url) { loadURL(url, false); })); if (res != S_OK) { @@ -386,28 +386,28 @@ private: m_controller->put_Bounds(bounds); } - void navigate(const std::string url) + void navigate(std::string_view url) { auto wurl = to_lpwstr(url); m_webview->Navigate(wurl); delete[] wurl; } - void init(const std::string js) + void init(std::string_view js) { LPCWSTR wjs = to_lpwstr(js); m_webview->AddScriptToExecuteOnDocumentCreated(wjs, nullptr); delete[] wjs; } - void eval(const std::string js) + void eval(std::string_view js) { LPCWSTR wjs = to_lpwstr(js); m_webview->ExecuteScript(wjs, nullptr); delete[] wjs; } - void on_message(const std::string msg) + void on_message(std::string_view msg) { const auto seq = jsonParse(msg, "id", 0); const auto name = jsonParse(msg, "method", 0); @@ -440,10 +440,10 @@ private: webview2_com_handler(HWND hwnd, msg_cb_t msgCb, webview2_com_handler_cb_t cb, - std::function navStartingCallback, + std::function navStartingCallback, std::function navCompleteCallback, std::function navErrorCallback, - std::function loadUrlCallback) + std::function loadUrlCallback) : m_window(hwnd) , m_msgCb(std::move(msgCb)) , m_cb(std::move(cb)) @@ -587,10 +587,10 @@ private: HWND m_window; msg_cb_t m_msgCb; webview2_com_handler_cb_t m_cb; - std::function m_navStartingCallback; + std::function m_navStartingCallback; std::function m_navCompleteCallback; std::function m_navErrorCallback; - std::function m_loadUrlCallback; + std::function m_loadUrlCallback; }; }; @@ -607,7 +607,7 @@ WebViewImpl::WebViewImpl(WebView* webView) : _createSucceeded(false), _systemWeb } _createSucceeded = _systemWebControl->createWebView( - [this](const std::string& url) -> bool { + [this](std::string_view url) -> bool { const auto shouldStartLoading = _webView->getOnShouldStartLoading(); if (shouldStartLoading != nullptr) { @@ -615,21 +615,21 @@ WebViewImpl::WebViewImpl(WebView* webView) : _createSucceeded(false), _systemWeb } return true; }, - [this](const std::string& url) { + [this](std::string_view url) { WebView::ccWebViewCallback didFinishLoading = _webView->getOnDidFinishLoading(); if (didFinishLoading != nullptr) { didFinishLoading(_webView, url); } }, - [this](const std::string& url) { + [this](std::string_view url) { WebView::ccWebViewCallback didFailLoading = _webView->getOnDidFailLoading(); if (didFailLoading != nullptr) { didFailLoading(_webView, url); } }, - [this](const std::string& url) { + [this](std::string_view url) { WebView::ccWebViewCallback onJsCallback = _webView->getOnJSCallback(); if (onJsCallback != nullptr) { @@ -649,9 +649,9 @@ WebViewImpl::~WebViewImpl() } void WebViewImpl::loadData(const Data& data, - const std::string& MIMEType, - const std::string& encoding, - const std::string& baseURL) + std::string_view MIMEType, + std::string_view encoding, + std::string_view baseURL) { if (_createSucceeded) { @@ -662,7 +662,7 @@ void WebViewImpl::loadData(const Data& data, } } -void WebViewImpl::loadHTMLString(const std::string& string, const std::string& baseURL) +void WebViewImpl::loadHTMLString(std::string_view string, std::string_view baseURL) { if (_createSucceeded) { @@ -684,7 +684,7 @@ void WebViewImpl::loadHTMLString(const std::string& string, const std::string& b } } -void WebViewImpl::loadURL(const std::string& url, bool cleanCachedData) +void WebViewImpl::loadURL(std::string_view url, bool cleanCachedData) { if (_createSucceeded) { @@ -692,7 +692,7 @@ void WebViewImpl::loadURL(const std::string& url, bool cleanCachedData) } } -void WebViewImpl::loadFile(const std::string& fileName) +void WebViewImpl::loadFile(std::string_view fileName) { if (_createSucceeded) { @@ -751,7 +751,7 @@ void WebViewImpl::goForward() } } -void WebViewImpl::setJavascriptInterfaceScheme(const std::string& scheme) +void WebViewImpl::setJavascriptInterfaceScheme(std::string_view scheme) { if (_createSucceeded) { @@ -759,7 +759,7 @@ void WebViewImpl::setJavascriptInterfaceScheme(const std::string& scheme) } } -void WebViewImpl::evaluateJS(const std::string& js) +void WebViewImpl::evaluateJS(std::string_view js) { if (_createSucceeded) { @@ -838,10 +838,10 @@ Win32WebControl::Win32WebControl() : _shouldStartLoading(nullptr), _didFinishLoa } } -bool Win32WebControl::createWebView(const std::function& shouldStartLoading, - const std::function& didFinishLoading, - const std::function& didFailLoading, - const std::function& onJsCallback) +bool Win32WebControl::createWebView(const std::function& shouldStartLoading, + const std::function& didFinishLoading, + const std::function& didFailLoading, + const std::function& onJsCallback) { bool ret = false; do @@ -905,7 +905,7 @@ bool Win32WebControl::createWebView(const std::functionput_ZoomFactor(_scalesPageToFit ? getDeviceScaleFactor() : 1.0); } -void Win32WebControl::setJavascriptInterfaceScheme(const std::string& scheme) +void Win32WebControl::setJavascriptInterfaceScheme(std::string_view scheme) { m_jsScheme = scheme; } -void Win32WebControl::loadHTMLString(const std::string& html, const std::string& baseURL) +void Win32WebControl::loadHTMLString(std::string_view html, std::string_view baseURL) { if (!html.empty()) { @@ -971,7 +971,7 @@ void Win32WebControl::loadHTMLString(const std::string& html, const std::string& } } -void Win32WebControl::loadURL(const std::string& url, bool cleanCachedData) +void Win32WebControl::loadURL(std::string_view url, bool cleanCachedData) { if (cleanCachedData) { @@ -980,7 +980,7 @@ void Win32WebControl::loadURL(const std::string& url, bool cleanCachedData) navigate(url); } -void Win32WebControl::loadFile(const std::string& filePath) +void Win32WebControl::loadFile(std::string_view filePath) { auto fullPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(filePath); if (fullPath.find("file:///") != 0) @@ -1029,7 +1029,7 @@ void Win32WebControl::goForward() const m_webview->GoForward(); } -void Win32WebControl::evaluateJS(const std::string& js) +void Win32WebControl::evaluateJS(std::string_view js) { eval(js); } diff --git a/cocos/ui/UIWebView/UIWebViewImpl-win32.h b/cocos/ui/UIWebView/UIWebViewImpl-win32.h index b963ba4a86..5dca559a57 100644 --- a/cocos/ui/UIWebView/UIWebViewImpl-win32.h +++ b/cocos/ui/UIWebView/UIWebViewImpl-win32.h @@ -58,21 +58,21 @@ public: WebViewImpl(cocos2d::ui::WebView* webView); virtual ~WebViewImpl(); - void setJavascriptInterfaceScheme(const std::string& scheme); + void setJavascriptInterfaceScheme(std::string_view scheme); void loadData(const cocos2d::Data& data, - const std::string& MIMEType, - const std::string& encoding, - const std::string& baseURL); - void loadHTMLString(const std::string& string, const std::string& baseURL); - void loadURL(const std::string& url, bool cleanCachedData); - void loadFile(const std::string& fileName); + std::string_view MIMEType, + std::string_view encoding, + std::string_view baseURL); + void loadHTMLString(std::string_view string, std::string_view baseURL); + void loadURL(std::string_view url, bool cleanCachedData); + void loadFile(std::string_view fileName); void stopLoading(); void reload(); bool canGoBack(); bool canGoForward(); void goBack(); void goForward(); - void evaluateJS(const std::string& js); + void evaluateJS(std::string_view js); void setScalesPageToFit(const bool scalesPageToFit); virtual void draw(cocos2d::Renderer* renderer, cocos2d::Mat4 const& transform, uint32_t flags); diff --git a/cocos/ui/UIWidget.h b/cocos/ui/UIWidget.h index 98e841c538..29c9a3786f 100644 --- a/cocos/ui/UIWidget.h +++ b/cocos/ui/UIWidget.h @@ -684,25 +684,25 @@ public: * Set callback name. *@param callbackName A string representation of callback name. */ - void setCallbackName(const std::string& callbackName) { _callbackName = callbackName; } + void setCallbackName(std::string_view callbackName) { _callbackName = callbackName; } /** * Query callback name. *@return The callback name. */ - const std::string& getCallbackName() const { return _callbackName; } + std::string_view getCallbackName() const { return _callbackName; } /** * Set callback type. * @param callbackType A string representation of callback type. */ - void setCallbackType(const std::string& callbackType) { _callbackType = callbackType; } + void setCallbackType(std::string_view callbackType) { _callbackType = callbackType; } /** * Query callback type. *@return Callback type string. */ - const std::string& getCallbackType() const { return _callbackType; } + std::string_view getCallbackType() const { return _callbackType; } /** * Toggle layout component enable. diff --git a/extensions/DragonBones/CCArmatureDisplay.cpp b/extensions/DragonBones/CCArmatureDisplay.cpp index 5f11f16381..1801334dae 100644 --- a/extensions/DragonBones/CCArmatureDisplay.cpp +++ b/extensions/DragonBones/CCArmatureDisplay.cpp @@ -1,4 +1,4 @@ -#include "CCArmatureDisplay.h" +#include "CCArmatureDisplay.h" #include "CCSlot.h" DRAGONBONES_NAMESPACE_BEGIN @@ -56,7 +56,7 @@ void CCArmatureDisplay::dbUpdate() } } -void CCArmatureDisplay::addDBEventListener(const std::string& type, const std::function& callback) +void CCArmatureDisplay::addDBEventListener(std::string_view type, const std::function& callback) { auto lambda = [callback](cocos2d::EventCustom* event) -> void { callback(static_cast(event->getUserData())); @@ -64,12 +64,12 @@ void CCArmatureDisplay::addDBEventListener(const std::string& type, const std::f _dispatcher->addCustomEventListener(type, lambda); } -void CCArmatureDisplay::dispatchDBEvent(const std::string& type, EventObject* value) +void CCArmatureDisplay::dispatchDBEvent(std::string_view type, EventObject* value) { _dispatcher->dispatchCustomEvent(type, value); } -void CCArmatureDisplay::removeDBEventListener(const std::string& type, +void CCArmatureDisplay::removeDBEventListener(std::string_view type, const std::function& callback) { // TODO diff --git a/extensions/DragonBones/CCArmatureDisplay.h b/extensions/DragonBones/CCArmatureDisplay.h index 2e594a566c..0c6092f3d9 100644 --- a/extensions/DragonBones/CCArmatureDisplay.h +++ b/extensions/DragonBones/CCArmatureDisplay.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -83,20 +83,20 @@ public: /** * @inheritDoc */ - inline virtual bool hasDBEventListener(const std::string& type) const override { return _dispatcher->isEnabled(); } + inline virtual bool hasDBEventListener(std::string_view type) const override { return _dispatcher->isEnabled(); } /** * @inheritDoc */ - virtual void dispatchDBEvent(const std::string& type, EventObject* value) override; + virtual void dispatchDBEvent(std::string_view type, EventObject* value) override; /** * @inheritDoc */ - virtual void addDBEventListener(const std::string& type, + virtual void addDBEventListener(std::string_view type, const std::function& listener) override; /** * @inheritDoc */ - virtual void removeDBEventListener(const std::string& type, + virtual void removeDBEventListener(std::string_view type, const std::function& listener) override; /** * @inheritDoc diff --git a/extensions/DragonBones/CCFactory.cpp b/extensions/DragonBones/CCFactory.cpp index 85c8565d04..ee24fc555c 100644 --- a/extensions/DragonBones/CCFactory.cpp +++ b/extensions/DragonBones/CCFactory.cpp @@ -1,4 +1,4 @@ -#include "CCFactory.h" +#include "CCFactory.h" #include "CCTextureAtlasData.h" #include "CCArmatureDisplay.h" #include "CCSlot.h" @@ -144,7 +144,7 @@ Slot* CCFactory::_buildSlot(const BuildArmaturePackage& dataPackage, const SlotD return slot; } -DragonBonesData* CCFactory::loadDragonBonesData(const std::string& filePath, const std::string& name, float scale) +DragonBonesData* CCFactory::loadDragonBonesData(std::string_view filePath, std::string_view name, float scale) { if (!name.empty()) { @@ -185,7 +185,7 @@ DragonBonesData* CCFactory::loadDragonBonesData(const std::string& filePath, con return nullptr; } -TextureAtlasData* CCFactory::loadTextureAtlasData(const std::string& filePath, const std::string& name, float scale) +TextureAtlasData* CCFactory::loadTextureAtlasData(std::string_view filePath, std::string_view name, float scale) { _prevPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(filePath); const auto data = cocos2d::FileUtils::getInstance()->getStringFromFile(_prevPath); @@ -197,10 +197,10 @@ TextureAtlasData* CCFactory::loadTextureAtlasData(const std::string& filePath, c return static_cast(BaseFactory::parseTextureAtlasData(data.c_str(), nullptr, name, scale)); } -CCArmatureDisplay* CCFactory::buildArmatureDisplay(const std::string& armatureName, - const std::string& dragonBonesName, - const std::string& skinName, - const std::string& textureAtlasName) const +CCArmatureDisplay* CCFactory::buildArmatureDisplay(std::string_view armatureName, + std::string_view dragonBonesName, + std::string_view skinName, + std::string_view textureAtlasName) const { const auto armature = buildArmature(armatureName, dragonBonesName, skinName, textureAtlasName); if (armature != nullptr) @@ -213,7 +213,7 @@ CCArmatureDisplay* CCFactory::buildArmatureDisplay(const std::string& armatureNa return nullptr; } -cocos2d::Sprite* CCFactory::getTextureDisplay(const std::string& textureName, const std::string& dragonBonesName) const +cocos2d::Sprite* CCFactory::getTextureDisplay(std::string_view textureName, std::string_view dragonBonesName) const { const auto textureData = static_cast(_getTextureData(dragonBonesName, textureName)); if (textureData != nullptr && textureData->spriteFrame != nullptr) diff --git a/extensions/DragonBones/CCFactory.h b/extensions/DragonBones/CCFactory.h index 4ffa184008..435f745ae5 100644 --- a/extensions/DragonBones/CCFactory.h +++ b/extensions/DragonBones/CCFactory.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -102,8 +102,8 @@ protected: Armature* armature) const override; public: - virtual DragonBonesData* loadDragonBonesData(const std::string& filePath, - const std::string& name = "", + virtual DragonBonesData* loadDragonBonesData(std::string_view filePath, + std::string_view name = "", float scale = 1.0f); /** * - Load and parse a texture atlas data and texture from the local and cache them to the factory. @@ -132,8 +132,8 @@ public: * * @language zh_CN */ - virtual TextureAtlasData* loadTextureAtlasData(const std::string& filePath, - const std::string& name = "", + virtual TextureAtlasData* loadTextureAtlasData(std::string_view filePath, + std::string_view name = "", float scale = 1.0f); /** * - Create a armature from cached DragonBonesData instances and TextureAtlasData instances, then use the {@link @@ -168,10 +168,10 @@ public: * * @language zh_CN */ - virtual CCArmatureDisplay* buildArmatureDisplay(const std::string& armatureName, - const std::string& dragonBonesName = "", - const std::string& skinName = "", - const std::string& textureAtlasName = "") const; + virtual CCArmatureDisplay* buildArmatureDisplay(std::string_view armatureName, + std::string_view dragonBonesName = "", + std::string_view skinName = "", + std::string_view textureAtlasName = "") const; /** * - Create the display object with the specified texture. * @param textureName - The texture data name. @@ -186,8 +186,8 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - virtual cocos2d::Sprite* getTextureDisplay(const std::string& textureName, - const std::string& dragonBonesName = "") const; + virtual cocos2d::Sprite* getTextureDisplay(std::string_view textureName, + std::string_view dragonBonesName = "") const; /** * - A global sound event manager. * Sound events can be listened to uniformly from the manager. diff --git a/extensions/DragonBones/animation/Animation.cpp b/extensions/DragonBones/animation/Animation.cpp index 56de838922..77ae02d80c 100644 --- a/extensions/DragonBones/animation/Animation.cpp +++ b/extensions/DragonBones/animation/Animation.cpp @@ -1,4 +1,4 @@ -#include "Animation.h" +#include "Animation.h" #include "../model/DisplayData.h" #include "../model/AnimationConfig.h" #include "../model/AnimationData.h" @@ -216,7 +216,7 @@ void Animation::reset() _lastAnimationState = nullptr; } -void Animation::stop(const std::string& animationName) +void Animation::stop(std::string_view animationName) { if (!animationName.empty()) { @@ -384,7 +384,7 @@ AnimationState* Animation::playConfig(AnimationConfig* animationConfig) return animationState; } -AnimationState* Animation::play(const std::string& animationName, int playTimes) +AnimationState* Animation::play(std::string_view animationName, int playTimes) { _animationConfig->clear(); _animationConfig->resetToPose = true; @@ -418,18 +418,18 @@ AnimationState* Animation::play(const std::string& animationName, int playTimes) return _lastAnimationState; } #ifdef EGRET_WASM -AnimationState* Animation::fadeIn(const std::string& animationName, +AnimationState* Animation::fadeIn(std::string_view animationName, float fadeInTime, int playTimes, int layer, - const std::string& group, + std::string_view group, int fadeOutMode /*AnimationFadeOutMode*/ #else -AnimationState* Animation::fadeIn(const std::string& animationName, +AnimationState* Animation::fadeIn(std::string_view animationName, float fadeInTime, int playTimes, int layer, - const std::string& group, + std::string_view group, AnimationFadeOutMode fadeOutMode #endif // EGRET_WASM ) @@ -445,7 +445,7 @@ AnimationState* Animation::fadeIn(const std::string& animationName, return playConfig(_animationConfig); } -AnimationState* Animation::gotoAndPlayByTime(const std::string& animationName, float time, int playTimes) +AnimationState* Animation::gotoAndPlayByTime(std::string_view animationName, float time, int playTimes) { _animationConfig->clear(); _animationConfig->resetToPose = true; @@ -457,7 +457,7 @@ AnimationState* Animation::gotoAndPlayByTime(const std::string& animationName, f return playConfig(_animationConfig); } -AnimationState* Animation::gotoAndPlayByFrame(const std::string& animationName, unsigned frame, int playTimes) +AnimationState* Animation::gotoAndPlayByFrame(std::string_view animationName, unsigned frame, int playTimes) { _animationConfig->clear(); _animationConfig->resetToPose = true; @@ -474,7 +474,7 @@ AnimationState* Animation::gotoAndPlayByFrame(const std::string& animationName, return playConfig(_animationConfig); } -AnimationState* Animation::gotoAndPlayByProgress(const std::string& animationName, float progress, int playTimes) +AnimationState* Animation::gotoAndPlayByProgress(std::string_view animationName, float progress, int playTimes) { _animationConfig->clear(); _animationConfig->resetToPose = true; @@ -491,7 +491,7 @@ AnimationState* Animation::gotoAndPlayByProgress(const std::string& animationNam return playConfig(_animationConfig); } -AnimationState* Animation::gotoAndStopByTime(const std::string& animationName, float time) +AnimationState* Animation::gotoAndStopByTime(std::string_view animationName, float time) { const auto animationState = gotoAndPlayByTime(animationName, time, 1); if (animationState != nullptr) @@ -502,7 +502,7 @@ AnimationState* Animation::gotoAndStopByTime(const std::string& animationName, f return animationState; } -AnimationState* Animation::gotoAndStopByFrame(const std::string& animationName, unsigned frame) +AnimationState* Animation::gotoAndStopByFrame(std::string_view animationName, unsigned frame) { const auto animationState = gotoAndPlayByFrame(animationName, frame, 1); if (animationState != nullptr) @@ -513,7 +513,7 @@ AnimationState* Animation::gotoAndStopByFrame(const std::string& animationName, return animationState; } -AnimationState* Animation::gotoAndStopByProgress(const std::string& animationName, float progress) +AnimationState* Animation::gotoAndStopByProgress(std::string_view animationName, float progress) { const auto animationState = gotoAndPlayByProgress(animationName, progress, 1); if (animationState != nullptr) @@ -524,7 +524,7 @@ AnimationState* Animation::gotoAndStopByProgress(const std::string& animationNam return animationState; } -AnimationState* Animation::getState(const std::string& animationName) const +AnimationState* Animation::getState(std::string_view animationName) const { int i = _animationStates.size(); while (i--) @@ -539,7 +539,7 @@ AnimationState* Animation::getState(const std::string& animationName) const return nullptr; } -bool Animation::hasAnimation(const std::string& animationName) const +bool Animation::hasAnimation(std::string_view animationName) const { return _animations.find(animationName) != _animations.end(); } @@ -570,7 +570,7 @@ bool Animation::isCompleted() const return !_animationStates.empty(); } -const std::string& Animation::getLastAnimationName() const +std::string_view Animation::getLastAnimationName() const { if (_lastAnimationState != nullptr) { diff --git a/extensions/DragonBones/animation/Animation.h b/extensions/DragonBones/animation/Animation.h index 33927b75ab..e5e2d74fa9 100644 --- a/extensions/DragonBones/animation/Animation.h +++ b/extensions/DragonBones/animation/Animation.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -115,7 +115,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - void stop(const std::string& animationName); + void stop(std::string_view animationName); /** * - Play animation with a specific animation config. * The API is still in the experimental phase and may encounter bugs or stability or compatibility issues when used. @@ -166,7 +166,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - AnimationState* play(const std::string& animationName = "", int playTimes = -1); + AnimationState* play(std::string_view animationName = "", int playTimes = -1); /** * - Fade in a specific animation. * @param animationName - The name of animation data. @@ -211,11 +211,11 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* fadeIn(const std::string& animationName, + AnimationState* fadeIn(std::string_view animationName, float fadeInTime = -1.f, int playTimes = -1, int layer = 0, - const std::string& group = "", + std::string_view group = "", AnimationFadeOutMode fadeOutMode = AnimationFadeOutMode::SameLayerAndGroup); /** * - Play a specific animation from the specific time. @@ -236,7 +236,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* gotoAndPlayByTime(const std::string& animationName, float time = 0.f, int playTimes = -1); + AnimationState* gotoAndPlayByTime(std::string_view animationName, float time = 0.f, int playTimes = -1); /** * - Play a specific animation from the specific frame. * @param animationName - The name of animation data. @@ -256,7 +256,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* gotoAndPlayByFrame(const std::string& animationName, unsigned frame = 0, int playTimes = -1); + AnimationState* gotoAndPlayByFrame(std::string_view animationName, unsigned frame = 0, int playTimes = -1); /** * - Play a specific animation from the specific progress. * @param animationName - The name of animation data. @@ -276,7 +276,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* gotoAndPlayByProgress(const std::string& animationName, float progress = 0.f, int playTimes = -1); + AnimationState* gotoAndPlayByProgress(std::string_view animationName, float progress = 0.f, int playTimes = -1); /** * - Stop a specific animation at the specific time. * @param animationName - The name of animation data. @@ -293,7 +293,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* gotoAndStopByTime(const std::string& animationName, float time = 0.f); + AnimationState* gotoAndStopByTime(std::string_view animationName, float time = 0.f); /** * - Stop a specific animation at the specific frame. * @param animationName - The name of animation data. @@ -310,7 +310,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* gotoAndStopByFrame(const std::string& animationName, unsigned frame = 0); + AnimationState* gotoAndStopByFrame(std::string_view animationName, unsigned frame = 0); /** * - Stop a specific animation at the specific progress. * @param animationName - The name of animation data. @@ -327,7 +327,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* gotoAndStopByProgress(const std::string& animationName, float progress = 0.f); + AnimationState* gotoAndStopByProgress(std::string_view animationName, float progress = 0.f); /** * - Get a specific animation state. * @param animationName - The name of animation state. @@ -354,7 +354,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - AnimationState* getState(const std::string& animationName) const; + AnimationState* getState(std::string_view animationName) const; /** * - Check whether a specific animation data is included. * @param animationName - The name of animation data. @@ -369,7 +369,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - bool hasAnimation(const std::string& animationName) const; + bool hasAnimation(std::string_view animationName) const; /** * - Get all the animation states. * @version DragonBones 5.1 @@ -419,7 +419,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - const std::string& getLastAnimationName() const; + std::string_view getLastAnimationName() const; /** * - The name of all animation data * @version DragonBones 4.5 diff --git a/extensions/DragonBones/animation/AnimationState.cpp b/extensions/DragonBones/animation/AnimationState.cpp index 48274df194..2e9503f9a6 100644 --- a/extensions/DragonBones/animation/AnimationState.cpp +++ b/extensions/DragonBones/animation/AnimationState.cpp @@ -1,4 +1,4 @@ -#include "AnimationState.h" +#include "AnimationState.h" #include "WorldClock.h" #include "../model/DisplayData.h" #include "../model/AnimationConfig.h" @@ -745,12 +745,12 @@ void AnimationState::fadeOut(float fadeOutTime, bool pausePlayhead) _fadeTime = fadeTotalTime * (1.0f - _fadeProgress); } -bool AnimationState::containsBoneMask(const std::string& boneName) const +bool AnimationState::containsBoneMask(std::string_view boneName) const { return _boneMask.empty() || std::find(_boneMask.cbegin(), _boneMask.cend(), boneName) != _boneMask.cend(); } -void AnimationState::addBoneMask(const std::string& boneName, bool recursive) +void AnimationState::addBoneMask(std::string_view boneName, bool recursive) { const auto currentBone = _armature->getBone(boneName); if (currentBone == nullptr) @@ -778,7 +778,7 @@ void AnimationState::addBoneMask(const std::string& boneName, bool recursive) _timelineDirty = 1; } -void AnimationState::removeBoneMask(const std::string& boneName, bool recursive) +void AnimationState::removeBoneMask(std::string_view boneName, bool recursive) { { auto iterator = std::find(_boneMask.begin(), _boneMask.end(), boneName); diff --git a/extensions/DragonBones/animation/AnimationState.h b/extensions/DragonBones/animation/AnimationState.h index a99da36f0e..8536ad2577 100644 --- a/extensions/DragonBones/animation/AnimationState.h +++ b/extensions/DragonBones/animation/AnimationState.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -325,7 +325,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - bool containsBoneMask(const std::string& boneName) const; + bool containsBoneMask(std::string_view boneName) const; /** * - Add a specific bone mask. * @param boneName - The bone name. @@ -340,7 +340,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - void addBoneMask(const std::string& boneName, bool recursive = true); + void addBoneMask(std::string_view boneName, bool recursive = true); /** * - Remove the mask of a specific bone. * @param boneName - The bone name. @@ -355,7 +355,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - void removeBoneMask(const std::string& boneName, bool recursive = true); + void removeBoneMask(std::string_view boneName, bool recursive = true); /** * - Remove all bone masks. * @version DragonBones 3.0 @@ -456,7 +456,7 @@ public: */ float getCurrentTime() const; void setCurrentTime(float value); - inline const std::string& getName() const { return name; } + inline std::string_view getName() const { return name; } /** * - The animation data. diff --git a/extensions/DragonBones/armature/Armature.cpp b/extensions/DragonBones/armature/Armature.cpp index 7e6cc57b95..e4aabc2763 100644 --- a/extensions/DragonBones/armature/Armature.cpp +++ b/extensions/DragonBones/armature/Armature.cpp @@ -1,4 +1,4 @@ -#include "Armature.h" +#include "Armature.h" #include "../model/TextureAtlasData.h" #include "../model/UserData.h" #include "../animation/WorldClock.h" @@ -275,7 +275,7 @@ void Armature::advanceTime(float passedTime) _proxy->dbUpdate(); } -void Armature::invalidUpdate(const std::string& boneName, bool updateSlot) +void Armature::invalidUpdate(std::string_view boneName, bool updateSlot) { if (!boneName.empty()) { @@ -431,7 +431,7 @@ Slot* Armature::intersectsSegment(float xA, return intSlotA; } -Bone* Armature::getBone(const std::string& name) const +Bone* Armature::getBone(std::string_view name) const { for (const auto& bone : _bones) { @@ -451,7 +451,7 @@ Bone* Armature::getBoneByDisplay(void* display) const return slot != nullptr ? slot->getParent() : nullptr; } -Slot* Armature::getSlot(const std::string& name) const +Slot* Armature::getSlot(std::string_view name) const { for (const auto slot : _slots) { diff --git a/extensions/DragonBones/armature/Armature.h b/extensions/DragonBones/armature/Armature.h index 6f6f5f7bbe..c78d0fe9a2 100644 --- a/extensions/DragonBones/armature/Armature.h +++ b/extensions/DragonBones/armature/Armature.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -201,7 +201,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - void invalidUpdate(const std::string& boneName = "", bool updateSlot = false); + void invalidUpdate(std::string_view boneName = "", bool updateSlot = false); /** * - Check whether a specific point is inside a custom bounding box in a slot. * The coordinate system of the point is the inner coordinate system of the armature. @@ -278,7 +278,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - Bone* getBone(const std::string& name) const; + Bone* getBone(std::string_view name) const; /** * - Get a specific bone by the display. * @param display - The display object. @@ -308,7 +308,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - Slot* getSlot(const std::string& name) const; + Slot* getSlot(std::string_view name) const; /** * - Get a specific slot by the display. * @param display - The display object. @@ -426,7 +426,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline const std::string& getName() const { return _armatureData->name; } + inline std::string_view getName() const { return _armatureData->name; } /** * - The armature data. * @see dragonBones.ArmatureData diff --git a/extensions/DragonBones/armature/Bone.h b/extensions/DragonBones/armature/Bone.h index cba7c2d650..3541143b0b 100644 --- a/extensions/DragonBones/armature/Bone.h +++ b/extensions/DragonBones/armature/Bone.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -198,7 +198,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline const std::string& getName() const { return _boneData->name; } + inline std::string_view getName() const { return _boneData->name; } /** * - The parent bone to which it belongs. * @version DragonBones 3.0 diff --git a/extensions/DragonBones/armature/Constraint.h b/extensions/DragonBones/armature/Constraint.h index 92ba6e9f50..99d38b15ec 100644 --- a/extensions/DragonBones/armature/Constraint.h +++ b/extensions/DragonBones/armature/Constraint.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -75,7 +75,7 @@ public: virtual void update() = 0; virtual void invalidUpdate() = 0; - inline const std::string& getName() { return _constraintData->name; } + inline std::string_view getName() { return _constraintData->name; } }; /** * @internal diff --git a/extensions/DragonBones/armature/Slot.h b/extensions/DragonBones/armature/Slot.h index 234e2f79c6..6700737b08 100644 --- a/extensions/DragonBones/armature/Slot.h +++ b/extensions/DragonBones/armature/Slot.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -343,7 +343,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline const std::string& getName() const { return _slotData->name; } + inline std::string_view getName() const { return _slotData->name; } /** * - Contains a display list of display objects or child armatures. * @version DragonBones 3.0 diff --git a/extensions/DragonBones/core/DragonBones.h b/extensions/DragonBones/core/DragonBones.h index 9ddab3b97a..68d8d4abc6 100644 --- a/extensions/DragonBones/core/DragonBones.h +++ b/extensions/DragonBones/core/DragonBones.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -360,14 +360,14 @@ inline int indexOf(const std::vector& vector, const T& value) } template -inline T* mapFind(const std::map& map, const std::string& key) +inline T* mapFind(const std::map& map, std::string_view key) { auto iterator = map.find(key); return (iterator != map.end()) ? iterator->second : nullptr; } template -inline T* mapFindB(std::map& map, const std::string& key) +inline T* mapFindB(std::map& map, std::string_view key) { auto iterator = map.find(key); return (iterator != map.end()) ? &iterator->second : nullptr; diff --git a/extensions/DragonBones/event/IEventDispatcher.h b/extensions/DragonBones/event/IEventDispatcher.h index ded91d92db..26476941ee 100644 --- a/extensions/DragonBones/event/IEventDispatcher.h +++ b/extensions/DragonBones/event/IEventDispatcher.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -56,7 +56,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - virtual bool hasDBEventListener(const std::string& type) const = 0; + virtual bool hasDBEventListener(std::string_view type) const = 0; /** * - Dispatches an event into the event flow. * @param type - Event type. @@ -73,7 +73,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - virtual void dispatchDBEvent(const std::string& type, EventObject* value) = 0; + virtual void dispatchDBEvent(std::string_view type, EventObject* value) = 0; /** * - Add an event listener object so that the listener receives notification of an event. * @param type - Event type. @@ -90,7 +90,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - virtual void addDBEventListener(const std::string& type, const std::function& listener) = 0; + virtual void addDBEventListener(std::string_view type, const std::function& listener) = 0; /** * - Removes a listener from the object. * @param type - Event type. @@ -107,7 +107,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - virtual void removeDBEventListener(const std::string& type, const std::function& listener) = 0; + virtual void removeDBEventListener(std::string_view type, const std::function& listener) = 0; }; DRAGONBONES_NAMESPACE_END diff --git a/extensions/DragonBones/factory/BaseFactory.cpp b/extensions/DragonBones/factory/BaseFactory.cpp index c7eb5242e2..a3f5f623ca 100644 --- a/extensions/DragonBones/factory/BaseFactory.cpp +++ b/extensions/DragonBones/factory/BaseFactory.cpp @@ -1,11 +1,11 @@ -#include "BaseFactory.h" +#include "BaseFactory.h" DRAGONBONES_NAMESPACE_BEGIN JSONDataParser BaseFactory::_jsonParser; BinaryDataParser BaseFactory::_binaryParser; -TextureData* BaseFactory::_getTextureData(const std::string& textureAtlasName, const std::string& textureName) const +TextureData* BaseFactory::_getTextureData(std::string_view textureAtlasName, std::string_view textureName) const { const auto iterator = _textureAtlasDataMap.find(textureAtlasName); if (iterator != _textureAtlasDataMap.end()) @@ -42,10 +42,10 @@ TextureData* BaseFactory::_getTextureData(const std::string& textureAtlasName, c } bool BaseFactory::_fillBuildArmaturePackage(BuildArmaturePackage& dataPackage, - const std::string& dragonBonesName, - const std::string& armatureName, - const std::string& skinName, - const std::string& textureAtlasName) const + std::string_view dragonBonesName, + std::string_view armatureName, + std::string_view skinName, + std::string_view textureAtlasName) const { std::string mapName = dragonBonesName; DragonBonesData* dragonBonesData = nullptr; @@ -309,7 +309,7 @@ std::pair BaseFactory::_getSlotDisplay(const BuildArmaturePa return display; } -DragonBonesData* BaseFactory::parseDragonBonesData(const char* rawData, const std::string& name, float scale) +DragonBonesData* BaseFactory::parseDragonBonesData(const char* rawData, std::string_view name, float scale) { DRAGONBONES_ASSERT(rawData != nullptr, ""); @@ -350,7 +350,7 @@ DragonBonesData* BaseFactory::parseDragonBonesData(const char* rawData, const st TextureAtlasData* BaseFactory::parseTextureAtlasData(const char* rawData, void* textureAtlas, - const std::string& name, + std::string_view name, float scale) { const auto textureAtlasData = _buildTextureAtlasData(nullptr, nullptr); @@ -361,7 +361,7 @@ TextureAtlasData* BaseFactory::parseTextureAtlasData(const char* rawData, return textureAtlasData; } -void BaseFactory::addDragonBonesData(DragonBonesData* data, const std::string& name) +void BaseFactory::addDragonBonesData(DragonBonesData* data, std::string_view name) { const auto& mapName = !name.empty() ? name : data->name; if (_dragonBonesDataMap.find(mapName) != _dragonBonesDataMap.cend()) @@ -378,7 +378,7 @@ void BaseFactory::addDragonBonesData(DragonBonesData* data, const std::string& n _dragonBonesDataMap[mapName] = data; } -void BaseFactory::removeDragonBonesData(const std::string& name, bool disposeData) +void BaseFactory::removeDragonBonesData(std::string_view name, bool disposeData) { const auto iterator = _dragonBonesDataMap.find(name); if (iterator != _dragonBonesDataMap.cend()) @@ -392,7 +392,7 @@ void BaseFactory::removeDragonBonesData(const std::string& name, bool disposeDat } } -void BaseFactory::addTextureAtlasData(TextureAtlasData* data, const std::string& name) +void BaseFactory::addTextureAtlasData(TextureAtlasData* data, std::string_view name) { const auto& mapName = !name.empty() ? name : data->name; auto& textureAtlasList = _textureAtlasDataMap[mapName]; @@ -402,7 +402,7 @@ void BaseFactory::addTextureAtlasData(TextureAtlasData* data, const std::string& } } -void BaseFactory::removeTextureAtlasData(const std::string& name, bool disposeData) +void BaseFactory::removeTextureAtlasData(std::string_view name, bool disposeData) { const auto iterator = _textureAtlasDataMap.find(name); if (iterator != _textureAtlasDataMap.end()) @@ -419,7 +419,7 @@ void BaseFactory::removeTextureAtlasData(const std::string& name, bool disposeDa } } -ArmatureData* BaseFactory::getArmatureData(const std::string& name, const std::string& dragonBonesName) const +ArmatureData* BaseFactory::getArmatureData(std::string_view name, std::string_view dragonBonesName) const { BuildArmaturePackage dataPackage; if (!_fillBuildArmaturePackage(dataPackage, dragonBonesName, name, "", "")) @@ -452,10 +452,10 @@ void BaseFactory::clear(bool disposeData) _textureAtlasDataMap.clear(); } -Armature* BaseFactory::buildArmature(const std::string& armatureName, - const std::string& dragonBonesName, - const std::string& skinName, - const std::string& textureAtlasName) const +Armature* BaseFactory::buildArmature(std::string_view armatureName, + std::string_view dragonBonesName, + std::string_view skinName, + std::string_view textureAtlasName) const { BuildArmaturePackage dataPackage; if (!_fillBuildArmaturePackage(dataPackage, dragonBonesName, armatureName, skinName, textureAtlasName)) @@ -512,10 +512,10 @@ void BaseFactory::replaceDisplay(Slot* slot, DisplayData* displayData, int displ slot->setDisplayList(displayList); } -bool BaseFactory::replaceSlotDisplay(const std::string& dragonBonesName, - const std::string& armatureName, - const std::string& slotName, - const std::string& displayName, +bool BaseFactory::replaceSlotDisplay(std::string_view dragonBonesName, + std::string_view armatureName, + std::string_view slotName, + std::string_view displayName, Slot* slot, int displayIndex) const { @@ -538,9 +538,9 @@ bool BaseFactory::replaceSlotDisplay(const std::string& dragonBonesName, return true; } -bool BaseFactory::replaceSlotDisplayList(const std::string& dragonBonesName, - const std::string& armatureName, - const std::string& slotName, +bool BaseFactory::replaceSlotDisplayList(std::string_view dragonBonesName, + std::string_view armatureName, + std::string_view slotName, Slot* slot) const { DRAGONBONES_ASSERT(slot, "Arguments error."); diff --git a/extensions/DragonBones/factory/BaseFactory.h b/extensions/DragonBones/factory/BaseFactory.h index 8d9329d579..9142a316e2 100644 --- a/extensions/DragonBones/factory/BaseFactory.h +++ b/extensions/DragonBones/factory/BaseFactory.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -99,12 +99,12 @@ public: protected: virtual inline bool _isSupportMesh() const { return true; } - virtual TextureData* _getTextureData(const std::string& textureAtlasName, const std::string& textureName) const; + virtual TextureData* _getTextureData(std::string_view textureAtlasName, std::string_view textureName) const; virtual bool _fillBuildArmaturePackage(BuildArmaturePackage& dataPackage, - const std::string& dragonBonesName, - const std::string& armatureName, - const std::string& skinName, - const std::string& textureAtlasName) const; + std::string_view dragonBonesName, + std::string_view armatureName, + std::string_view skinName, + std::string_view textureAtlasName) const; virtual void _buildBones(const BuildArmaturePackage& dataPackage, Armature* armature) const; /** * @private @@ -152,7 +152,7 @@ public: * @language zh_CN */ virtual DragonBonesData* parseDragonBonesData(const char* rawData, - const std::string& name = "", + std::string_view name = "", float scale = 1.0f); /** * - Parse the raw texture atlas data and the texture atlas object to a TextureAtlasData instance and cache it to @@ -186,7 +186,7 @@ public: */ virtual TextureAtlasData* parseTextureAtlasData(const char* rawData, void* textureAtlas, - const std::string& name = "", + std::string_view name = "", float scale = 1.0f); /** * - Get a specific DragonBonesData instance. @@ -210,7 +210,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline DragonBonesData* getDragonBonesData(const std::string& name) const + inline DragonBonesData* getDragonBonesData(std::string_view name) const { return mapFind(_dragonBonesDataMap, name); } @@ -237,7 +237,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - virtual void addDragonBonesData(DragonBonesData* data, const std::string& name = ""); + virtual void addDragonBonesData(DragonBonesData* data, std::string_view name = ""); /** * - Remove a DragonBonesData instance. * @param name - The DragonBonesData instance cache name. @@ -260,7 +260,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - virtual void removeDragonBonesData(const std::string& name, bool disposeData = true); + virtual void removeDragonBonesData(std::string_view name, bool disposeData = true); /** * - Get a list of specific TextureAtlasData instances. * @param name - The TextureAtlasData cahce name. @@ -281,7 +281,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline std::vector* getTextureAtlasData(const std::string& name) + inline std::vector* getTextureAtlasData(std::string_view name) { return mapFindB(_textureAtlasDataMap, name); } @@ -308,7 +308,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - virtual void addTextureAtlasData(TextureAtlasData* data, const std::string& name = ""); + virtual void addTextureAtlasData(TextureAtlasData* data, std::string_view name = ""); /** * - Remove a TextureAtlasData instance. * @param name - The TextureAtlasData instance cache name. @@ -331,7 +331,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - virtual void removeTextureAtlasData(const std::string& name, bool disposeData = true); + virtual void removeTextureAtlasData(std::string_view name, bool disposeData = true); /** * - Get a specific armature data. * @param name - The armature data name. @@ -348,7 +348,7 @@ public: * @version DragonBones 5.1 * @language zh_CN */ - virtual ArmatureData* getArmatureData(const std::string& name, const std::string& dragonBonesName = "") const; + virtual ArmatureData* getArmatureData(std::string_view name, std::string_view dragonBonesName = "") const; /** * - Clear all cached DragonBonesData instances and TextureAtlasData instances. * @param disposeData - Whether to dispose data. @@ -403,10 +403,10 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - virtual Armature* buildArmature(const std::string& armatureName, - const std::string& dragonBonesName = "", - const std::string& skinName = "", - const std::string& textureAtlasName = "") const; + virtual Armature* buildArmature(std::string_view armatureName, + std::string_view dragonBonesName = "", + std::string_view skinName = "", + std::string_view textureAtlasName = "") const; /** * @private */ @@ -448,18 +448,18 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - virtual bool replaceSlotDisplay(const std::string& dragonBonesName, - const std::string& armatureName, - const std::string& slotName, - const std::string& displayName, + virtual bool replaceSlotDisplay(std::string_view dragonBonesName, + std::string_view armatureName, + std::string_view slotName, + std::string_view displayName, Slot* slot, int displayIndex = -1) const; /** * @private */ - virtual bool replaceSlotDisplayList(const std::string& dragonBonesName, - const std::string& armatureName, - const std::string& slotName, + virtual bool replaceSlotDisplayList(std::string_view dragonBonesName, + std::string_view armatureName, + std::string_view slotName, Slot* slot) const; /** * - Share specific skin data with specific armature. diff --git a/extensions/DragonBones/model/AnimationConfig.cpp b/extensions/DragonBones/model/AnimationConfig.cpp index 26d198f630..6e012bc6be 100644 --- a/extensions/DragonBones/model/AnimationConfig.cpp +++ b/extensions/DragonBones/model/AnimationConfig.cpp @@ -1,4 +1,4 @@ -#include "AnimationConfig.h" +#include "AnimationConfig.h" #include "../armature/Armature.h" #include "../armature/Bone.h" @@ -63,12 +63,12 @@ void AnimationConfig::copyFrom(AnimationConfig* value) boneMask = value->boneMask; } -bool AnimationConfig::containsBoneMask(const std::string& boneName) const +bool AnimationConfig::containsBoneMask(std::string_view boneName) const { return boneMask.empty() || std::find(boneMask.cbegin(), boneMask.cend(), boneName) != boneMask.cend(); } -void AnimationConfig::addBoneMask(Armature* armature, const std::string& boneName, bool recursive) +void AnimationConfig::addBoneMask(Armature* armature, std::string_view boneName, bool recursive) { const auto currentBone = armature->getBone(boneName); if (currentBone == nullptr) @@ -94,7 +94,7 @@ void AnimationConfig::addBoneMask(Armature* armature, const std::string& boneNam } } -void AnimationConfig::removeBoneMask(Armature* armature, const std::string& boneName, bool recursive) +void AnimationConfig::removeBoneMask(Armature* armature, std::string_view boneName, bool recursive) { { auto iterator = std::find(boneMask.begin(), boneMask.end(), boneName); diff --git a/extensions/DragonBones/model/AnimationConfig.h b/extensions/DragonBones/model/AnimationConfig.h index c53fe730c1..dd90b4e7c8 100644 --- a/extensions/DragonBones/model/AnimationConfig.h +++ b/extensions/DragonBones/model/AnimationConfig.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -296,15 +296,15 @@ public: /** * @private */ - bool containsBoneMask(const std::string& boneName) const; + bool containsBoneMask(std::string_view boneName) const; /** * @private */ - void addBoneMask(Armature* armature, const std::string& boneName, bool recursive); + void addBoneMask(Armature* armature, std::string_view boneName, bool recursive); /** * @private */ - void removeBoneMask(Armature* armature, const std::string& boneName, bool recursive); + void removeBoneMask(Armature* armature, std::string_view boneName, bool recursive); public: // For WebAssembly. int getFadeOutMode() const { return (int)fadeOutMode; } diff --git a/extensions/DragonBones/model/AnimationData.h b/extensions/DragonBones/model/AnimationData.h index 8d7a37708e..9a4879c068 100644 --- a/extensions/DragonBones/model/AnimationData.h +++ b/extensions/DragonBones/model/AnimationData.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -181,35 +181,35 @@ public: /** * @private */ - std::vector* getBoneTimelines(const std::string& timelineName) + std::vector* getBoneTimelines(std::string_view timelineName) { return mapFindB(boneTimelines, timelineName); } /** * @private */ - inline std::vector* getSlotTimelines(const std::string& timelineName) + inline std::vector* getSlotTimelines(std::string_view timelineName) { return mapFindB(slotTimelines, timelineName); } /** * @private */ - inline std::vector* getConstraintTimelines(const std::string& timelineName) + inline std::vector* getConstraintTimelines(std::string_view timelineName) { return mapFindB(constraintTimelines, timelineName); } /** * @private */ - inline std::vector* getBoneCachedFrameIndices(const std::string& boneName) + inline std::vector* getBoneCachedFrameIndices(std::string_view boneName) { return mapFindB(boneCachedFrameIndices, boneName); } /** * @private */ - inline std::vector* getSlotCachedFrameIndices(const std::string& slotName) + inline std::vector* getSlotCachedFrameIndices(std::string_view slotName) { return mapFindB(slotCachedFrameIndices, slotName); } diff --git a/extensions/DragonBones/model/ArmatureData.cpp b/extensions/DragonBones/model/ArmatureData.cpp index 9cc86af721..66f9dfca75 100644 --- a/extensions/DragonBones/model/ArmatureData.cpp +++ b/extensions/DragonBones/model/ArmatureData.cpp @@ -1,4 +1,4 @@ -#include "ArmatureData.h" +#include "ArmatureData.h" #include "UserData.h" #include "DragonBonesData.h" #include "ConstraintData.h" @@ -264,9 +264,9 @@ void ArmatureData::addAction(ActionData* value, bool isDefault) } } -MeshDisplayData* ArmatureData::getMesh(const std::string& skinName, - const std::string& slotName, - const std::string& meshName) const +MeshDisplayData* ArmatureData::getMesh(std::string_view skinName, + std::string_view slotName, + std::string_view meshName) const { const auto skin = getSkin(skinName); if (skin == nullptr) diff --git a/extensions/DragonBones/model/ArmatureData.h b/extensions/DragonBones/model/ArmatureData.h index 838df4adb7..d8f24547d0 100644 --- a/extensions/DragonBones/model/ArmatureData.h +++ b/extensions/DragonBones/model/ArmatureData.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -223,7 +223,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline BoneData* getBone(const std::string& boneName) const { return mapFind(bones, boneName); } + inline BoneData* getBone(std::string_view boneName) const { return mapFind(bones, boneName); } /** * - Get a specific slot data. * @param slotName - The slot name. @@ -236,11 +236,11 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline SlotData* getSlot(const std::string& slotName) const { return mapFind(slots, slotName); } + inline SlotData* getSlot(std::string_view slotName) const { return mapFind(slots, slotName); } /** * @private */ - inline ConstraintData* getConstraint(const std::string& constraintName) const + inline ConstraintData* getConstraint(std::string_view constraintName) const { return mapFind(constraints, constraintName); } @@ -256,13 +256,13 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline SkinData* getSkin(const std::string& skinName) const { return mapFind(skins, skinName); } + inline SkinData* getSkin(std::string_view skinName) const { return mapFind(skins, skinName); } /** * @private */ - MeshDisplayData* getMesh(const std::string& skinName, - const std::string& slotName, - const std::string& meshName) const; + MeshDisplayData* getMesh(std::string_view skinName, + std::string_view slotName, + std::string_view meshName) const; /** * - Get a specific animation data. * @param animationName - The animation animationName. @@ -275,7 +275,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline AnimationData* getAnimation(const std::string& animationName) const + inline AnimationData* getAnimation(std::string_view animationName) const { return mapFind(animations, animationName); } diff --git a/extensions/DragonBones/model/DragonBonesData.h b/extensions/DragonBones/model/DragonBonesData.h index eef82b2b87..982f75c66d 100644 --- a/extensions/DragonBones/model/DragonBonesData.h +++ b/extensions/DragonBones/model/DragonBonesData.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -158,7 +158,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline ArmatureData* getArmature(const std::string& armatureName) const + inline ArmatureData* getArmature(std::string_view armatureName) const { return mapFind(armatures, armatureName); } diff --git a/extensions/DragonBones/model/SkinData.cpp b/extensions/DragonBones/model/SkinData.cpp index 7e6fe25011..7f53de7acf 100644 --- a/extensions/DragonBones/model/SkinData.cpp +++ b/extensions/DragonBones/model/SkinData.cpp @@ -1,4 +1,4 @@ -#include "SkinData.h" +#include "SkinData.h" #include "DisplayData.h" DRAGONBONES_NAMESPACE_BEGIN @@ -21,7 +21,7 @@ void SkinData::_onClear() parent = nullptr; } -void SkinData::addDisplay(const std::string& slotName, DisplayData* value) +void SkinData::addDisplay(std::string_view slotName, DisplayData* value) { if (value != nullptr) { @@ -31,7 +31,7 @@ void SkinData::addDisplay(const std::string& slotName, DisplayData* value) displays[slotName].push_back(value); // TODO clear prev } -DisplayData* SkinData::getDisplay(const std::string& slotName, const std::string& displayName) +DisplayData* SkinData::getDisplay(std::string_view slotName, std::string_view displayName) { const auto slotDisplays = getDisplays(slotName); if (slotDisplays != nullptr) diff --git a/extensions/DragonBones/model/SkinData.h b/extensions/DragonBones/model/SkinData.h index e054e9f96c..7228dfd8fd 100644 --- a/extensions/DragonBones/model/SkinData.h +++ b/extensions/DragonBones/model/SkinData.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -24,6 +24,7 @@ #define DRAGONBONES_SKIN_DATA_H #include "../core/BaseObject.h" +#include "base/hlookup.h" DRAGONBONES_NAMESPACE_BEGIN /** @@ -55,7 +56,7 @@ public: /** * @private */ - std::map> displays; + hlookup::string_map> displays; /** * @private */ @@ -68,15 +69,15 @@ public: /** * @internal */ - void addDisplay(const std::string& slotName, DisplayData* value); + void addDisplay(std::string_view slotName, DisplayData* value); /** * @private */ - DisplayData* getDisplay(const std::string& slotName, const std::string& displayName); + DisplayData* getDisplay(std::string_view slotName, std::string_view displayName); /** * @private */ - std::vector* getDisplays(const std::string& slotName) { return mapFindB(displays, slotName); } + std::vector* getDisplays(std::string_view slotName) { return mapFindB(displays, slotName); } public: // For WebAssembly. TODO parent const std::map>& getSlotDisplays() const { return displays; } diff --git a/extensions/DragonBones/model/TextureAtlasData.h b/extensions/DragonBones/model/TextureAtlasData.h index ad5bcb504b..b10d5eeaf6 100644 --- a/extensions/DragonBones/model/TextureAtlasData.h +++ b/extensions/DragonBones/model/TextureAtlasData.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -100,7 +100,7 @@ public: /** * @private */ - inline TextureData* getTexture(const std::string& textureName) const { return mapFind(textures, textureName); } + inline TextureData* getTexture(std::string_view textureName) const { return mapFind(textures, textureName); } protected: virtual void _onClear() override; diff --git a/extensions/DragonBones/parser/DataParser.cpp b/extensions/DragonBones/parser/DataParser.cpp index 684d192e25..699628894e 100644 --- a/extensions/DragonBones/parser/DataParser.cpp +++ b/extensions/DragonBones/parser/DataParser.cpp @@ -1,4 +1,4 @@ -#include "DataParser.h" +#include "DataParser.h" DRAGONBONES_NAMESPACE_BEGIN @@ -125,7 +125,7 @@ const char* DataParser::GOTO_AND_PLAY = "gotoAndPlay"; const char* DataParser::DEFAULT_NAME = "default"; -TextureFormat DataParser::_getTextureFormat(const std::string& value) +TextureFormat DataParser::_getTextureFormat(std::string_view value) { auto lower = value; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); @@ -158,7 +158,7 @@ TextureFormat DataParser::_getTextureFormat(const std::string& value) return TextureFormat::DEFAULT; } -ArmatureType DataParser::_getArmatureType(const std::string& value) +ArmatureType DataParser::_getArmatureType(std::string_view value) { auto lower = value; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); @@ -179,7 +179,7 @@ ArmatureType DataParser::_getArmatureType(const std::string& value) return ArmatureType::Armature; } -DisplayType DataParser::_getDisplayType(const std::string& value) +DisplayType DataParser::_getDisplayType(std::string_view value) { auto lower = value; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); @@ -204,7 +204,7 @@ DisplayType DataParser::_getDisplayType(const std::string& value) return DisplayType::Image; } -BoundingBoxType DataParser::_getBoundingBoxType(const std::string& value) +BoundingBoxType DataParser::_getBoundingBoxType(std::string_view value) { auto lower = value; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); @@ -225,7 +225,7 @@ BoundingBoxType DataParser::_getBoundingBoxType(const std::string& value) return BoundingBoxType::Rectangle; } -ActionType DataParser::_getActionType(const std::string& value) +ActionType DataParser::_getActionType(std::string_view value) { auto lower = value; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); @@ -246,7 +246,7 @@ ActionType DataParser::_getActionType(const std::string& value) return ActionType::Play; } -BlendMode DataParser::_getBlendMode(const std::string& value) +BlendMode DataParser::_getBlendMode(std::string_view value) { auto lower = value; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); diff --git a/extensions/DragonBones/parser/DataParser.h b/extensions/DragonBones/parser/DataParser.h index 08328ccd5f..ccad44049d 100644 --- a/extensions/DragonBones/parser/DataParser.h +++ b/extensions/DragonBones/parser/DataParser.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -166,12 +166,12 @@ protected: static const char* DEFAULT_NAME; - static TextureFormat _getTextureFormat(const std::string& value); - static ArmatureType _getArmatureType(const std::string& value); - static DisplayType _getDisplayType(const std::string& value); - static BoundingBoxType _getBoundingBoxType(const std::string& value); - static ActionType _getActionType(const std::string& value); - static BlendMode _getBlendMode(const std::string& value); + static TextureFormat _getTextureFormat(std::string_view value); + static ArmatureType _getArmatureType(std::string_view value); + static DisplayType _getDisplayType(std::string_view value); + static BoundingBoxType _getBoundingBoxType(std::string_view value); + static ActionType _getActionType(std::string_view value); + static BlendMode _getBlendMode(std::string_view value); public: virtual DragonBonesData* parseDragonBonesData(const char* rawData, float scale = 1.0f) = 0; diff --git a/extensions/DragonBones/parser/JSONDataParser.h b/extensions/DragonBones/parser/JSONDataParser.h index afa6e045d4..a80b510c37 100644 --- a/extensions/DragonBones/parser/JSONDataParser.h +++ b/extensions/DragonBones/parser/JSONDataParser.h @@ -1,4 +1,4 @@ -#ifndef DRAGONBONES_JSON_DATA_PARSER_H +#ifndef DRAGONBONES_JSON_DATA_PARSER_H #define DRAGONBONES_JSON_DATA_PARSER_H #include "DataParser.h" @@ -81,7 +81,7 @@ protected: inline static std::string _getString(const rapidjson::Value& rawData, const char* key, - const std::string& defaultValue) + std::string_view defaultValue) { if (rawData.HasMember(key)) { @@ -118,7 +118,7 @@ protected: inline static std::string _getParameter(const rapidjson::Value& rawData, std::size_t index, - const std::string& defaultValue) + std::string_view defaultValue) { if (rawData.Size() > index) { diff --git a/extensions/GUI/CCControlExtension/CCControlButton.cpp b/extensions/GUI/CCControlExtension/CCControlButton.cpp index ba95b0ed8e..1d9ea36046 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.cpp +++ b/extensions/GUI/CCControlExtension/CCControlButton.cpp @@ -141,15 +141,15 @@ ControlButton* ControlButton::create(Node* label, return pRet; } -bool ControlButton::initWithTitleAndFontNameAndFontSize(const std::string& title, - const std::string& fontName, +bool ControlButton::initWithTitleAndFontNameAndFontSize(std::string_view title, + std::string_view fontName, float fontSize) { return initWithLabelAndBackgroundSprite(Label::createWithSystemFont(title, fontName, fontSize), cocos2d::ui::Scale9Sprite::create(), true); } -ControlButton* ControlButton::create(const std::string& title, const std::string& fontName, float fontSize) +ControlButton* ControlButton::create(std::string_view title, std::string_view fontName, float fontSize) { ControlButton* pRet = new ControlButton(); pRet->initWithTitleAndFontNameAndFontSize(title, fontName, fontSize); @@ -291,7 +291,7 @@ std::string ControlButton::getTitleForState(State state) return iter != _titleDispatchTable.end() ? iter->second : ""; } -void ControlButton::setTitleForState(const std::string& title, State state) +void ControlButton::setTitleForState(std::string_view title, State state) { _titleDispatchTable.erase((int)state); @@ -371,12 +371,12 @@ void ControlButton::setTitleLabelForState(Node* titleLabel, State state) } } -void ControlButton::setTitleTTFForState(const std::string& fontName, State state) +void ControlButton::setTitleTTFForState(std::string_view fontName, State state) { this->setTitleLabelForState(Label::createWithSystemFont(getTitleForState(state), fontName, 12), state); } -const std::string& ControlButton::getTitleTTFForState(State state) +std::string_view ControlButton::getTitleTTFForState(State state) { LabelProtocol* label = dynamic_cast(this->getTitleLabelForState(state)); Label* labelTTF = dynamic_cast(label); @@ -416,13 +416,13 @@ float ControlButton::getTitleTTFSizeForState(State state) } } -void ControlButton::setTitleBMFontForState(const std::string& fntFile, State state) +void ControlButton::setTitleBMFontForState(std::string_view fntFile, State state) { std::string title = this->getTitleForState(state); this->setTitleLabelForState(Label::createWithBMFont(fntFile, title), state); } -const std::string& ControlButton::getTitleBMFontForState(State state) +std::string_view ControlButton::getTitleBMFontForState(State state) { LabelProtocol* label = dynamic_cast(this->getTitleLabelForState(state)); auto labelBMFont = dynamic_cast(label); diff --git a/extensions/GUI/CCControlExtension/CCControlButton.h b/extensions/GUI/CCControlExtension/CCControlButton.h index 51a8fcac34..c28624cc4e 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.h +++ b/extensions/GUI/CCControlExtension/CCControlButton.h @@ -57,7 +57,7 @@ public: static ControlButton* create(); static ControlButton* create(cocos2d::ui::Scale9Sprite* sprite); static ControlButton* create(Node* label, cocos2d::ui::Scale9Sprite* backgroundSprite); - static ControlButton* create(const std::string& title, const std::string& fontName, float fontSize); + static ControlButton* create(std::string_view title, std::string_view fontName, float fontSize); static ControlButton* create(Node* label, cocos2d::ui::Scale9Sprite* backgroundSprite, bool adjustBackGroundSize); virtual void needsLayout() override; @@ -87,7 +87,7 @@ public: * @param state The state that uses the specified title. The values are described * in "CCControlState". */ - virtual void setTitleForState(const std::string& title, State state); + virtual void setTitleForState(std::string_view title, State state); /** * Returns the title color used for a state. @@ -128,8 +128,8 @@ public: */ virtual void setTitleLabelForState(Node* label, State state); - virtual void setTitleTTFForState(const std::string& fntFile, State state); - virtual const std::string& getTitleTTFForState(State state); + virtual void setTitleTTFForState(std::string_view fntFile, State state); + virtual std::string_view getTitleTTFForState(State state); virtual void setTitleTTFSizeForState(float size, State state); virtual float getTitleTTFSizeForState(State state); @@ -140,8 +140,8 @@ public: * @param state The state that uses the specified fntFile. The values are described * in "CCControlState". */ - virtual void setTitleBMFontForState(const std::string& fntFile, State state); - virtual const std::string& getTitleBMFontForState(State state); + virtual void setTitleBMFontForState(std::string_view fntFile, State state); + virtual std::string_view getTitleBMFontForState(State state); /** * Returns the background sprite used for a state. @@ -188,7 +188,7 @@ public: virtual void setColor(const Color3B&) override; virtual void updateDisplayedColor(const Color3B& parentColor) override; - const std::string& getCurrentTitle() const { return _currentTitle; }; + std::string_view getCurrentTitle() const { return _currentTitle; }; std::string getCurrentTitle() { return _currentTitle; }; CC_CONSTRUCTOR_ACCESS : @@ -207,8 +207,8 @@ public: cocos2d::ui::Scale9Sprite* backgroundSprite, bool adjustBackGroundSize); virtual bool initWithBackgroundSprite(cocos2d::ui::Scale9Sprite* sprite); - virtual bool initWithTitleAndFontNameAndFontSize(const std::string& title, - const std::string& fontName, + virtual bool initWithTitleAndFontNameAndFontSize(std::string_view title, + std::string_view fontName, float fontSize); protected: diff --git a/extensions/GUI/CCControlExtension/CCControlSwitch.cpp b/extensions/GUI/CCControlExtension/CCControlSwitch.cpp index 09d14b6e6a..431b465a6c 100644 --- a/extensions/GUI/CCControlExtension/CCControlSwitch.cpp +++ b/extensions/GUI/CCControlExtension/CCControlSwitch.cpp @@ -78,7 +78,7 @@ public: * @js NA * @lua NA */ - virtual void updateTweenAction(float value, const std::string& key) override; + virtual void updateTweenAction(float value, std::string_view key) override; /** Contains the position (in x-axis) of the slider inside the receiver. */ float _sliderXPosition; @@ -214,7 +214,7 @@ bool ControlSwitchSprite::initWithMaskSprite(Sprite* maskSprite, return false; } -void ControlSwitchSprite::updateTweenAction(float value, const std::string& key) +void ControlSwitchSprite::updateTweenAction(float value, std::string_view key) { CCLOGINFO("key = %s, value = %f", key.c_str(), value); setSliderXPosition(value); diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index 6bf9f47288..bfa2cf5e12 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -327,7 +327,7 @@ void ScrollView::setZoomScaleInDuration(float s, float dt) } } -void ScrollView::updateTweenAction(float value, const std::string& /*key*/) +void ScrollView::updateTweenAction(float value, std::string_view /*key*/) { this->setZoomScale(value); } @@ -551,7 +551,7 @@ void ScrollView::removeAllChildren() removeAllChildrenWithCleanup(true); } -void ScrollView::addChild(Node* child, int zOrder, const std::string& name) +void ScrollView::addChild(Node* child, int zOrder, std::string_view name) { if (_container != child) { diff --git a/extensions/GUI/CCScrollView/CCScrollView.h b/extensions/GUI/CCScrollView/CCScrollView.h index 304f4cab75..9aef265af4 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.h +++ b/extensions/GUI/CCScrollView/CCScrollView.h @@ -251,7 +251,7 @@ public: using Node::addChild; virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, const std::string& name) override; + virtual void addChild(Node* child, int zOrder, std::string_view name) override; virtual void removeAllChildren() override; virtual void removeAllChildrenWithCleanup(bool cleanup) override; @@ -259,7 +259,7 @@ public: /** * CCActionTweenDelegate */ - void updateTweenAction(float value, const std::string& key) override; + void updateTweenAction(float value, std::string_view key) override; bool hasVisibleParents() const; diff --git a/extensions/ImGuiEXT/CCImGuiEXT.cpp b/extensions/ImGuiEXT/CCImGuiEXT.cpp index b3b801a33e..000806050e 100644 --- a/extensions/ImGuiEXT/CCImGuiEXT.cpp +++ b/extensions/ImGuiEXT/CCImGuiEXT.cpp @@ -5,12 +5,12 @@ NS_CC_EXT_BEGIN -static uint32_t fourccValue(const std::string& str) +static uint32_t fourccValue(std::string_view str) { if (str.empty() || str[0] != '#') return (uint32_t)-1; uint32_t value = 0; - memcpy(&value, str.c_str() + 1, std::min(sizeof(value), str.size() - 1)); + memcpy(&value, str.data() + 1, std::min(sizeof(value), str.size() - 1)); return value; } @@ -246,7 +246,7 @@ float ImGuiEXT::scaleAllByDPI(float userScale) return zoomFactor; } -void ImGuiEXT::addFont(const std::string& fontFile, float fontSize, CHS_GLYPH_RANGE glyphRange) +void ImGuiEXT::addFont(std::string_view fontFile, float fontSize, CHS_GLYPH_RANGE glyphRange) { if (FileUtils::getInstance()->isFileExistInternal(fontFile)) { @@ -255,7 +255,7 @@ void ImGuiEXT::addFont(const std::string& fontFile, float fontSize, CHS_GLYPH_RA } } -void ImGuiEXT::removeFont(const std::string& fontFile) +void ImGuiEXT::removeFont(std::string_view fontFile) { auto count = _fontsInfoMap.size(); _fontsInfoMap.erase(fontFile); @@ -339,7 +339,7 @@ void ImGuiEXT::update() // commands will be processed after update } -bool ImGuiEXT::addRenderLoop(const std::string& id, std::function func, Scene* target) +bool ImGuiEXT::addRenderLoop(std::string_view id, std::function func, Scene* target) { // TODO: check whether exist auto fourccId = fourccValue(id); @@ -362,7 +362,7 @@ bool ImGuiEXT::addRenderLoop(const std::string& id, std::function func, return false; } -void ImGuiEXT::removeRenderLoop(const std::string& id) +void ImGuiEXT::removeRenderLoop(std::string_view id) { auto fourccId = fourccValue(id); const auto iter = _renderPiplines.find(fourccId); @@ -603,16 +603,16 @@ void ImGuiEXT::setLabelColor(Label* label, ImGuiCol col) setLabelColor(label, ImGui::GetStyleColorVec4(col)); } -ImWchar* ImGuiEXT::addGlyphRanges(const std::string& key, const std::vector& ranges) +ImWchar* ImGuiEXT::addGlyphRanges(std::string_view key, const std::vector& ranges) { auto it = glyphRanges.find(key); // the pointer must be persistant, do not replace if (it != glyphRanges.end()) return it->second.data(); - glyphRanges[key] = ranges; + it = glyphRanges.emplace(key, ranges).first; // glyphRanges[key] = ranges; if (ranges.empty()) - glyphRanges[key].push_back(0); - return glyphRanges[key].data(); + it->second.push_back(0); + return it->second.data(); } void ImGuiEXT::mergeFontGlyphs(ImFont* dst, ImFont* src, ImWchar start, ImWchar end) @@ -712,13 +712,13 @@ void ImGuiEXT::setMarkdownFont(int index, ImFont* font, bool seperator, float sc ImGuiMarkdownConfig.headingScales[index] = scale; } -void ImGuiEXT::setMarkdownLinkIcon(const std::string& icon) +void ImGuiEXT::setMarkdownLinkIcon(std::string_view icon) { ImGuiMarkdownLinkIcon = icon; ImGuiMarkdownConfig.linkIcon = ImGuiMarkdownLinkIcon.c_str(); } -void ImGuiEXT::markdown(const std::string& content) +void ImGuiEXT::markdown(std::string_view content) { ImGui::Markdown(content.c_str(), content.size(), ImGuiMarkdownConfig); } diff --git a/extensions/ImGuiEXT/CCImGuiEXT.h b/extensions/ImGuiEXT/CCImGuiEXT.h index 7c80b711c7..c03cddc0c2 100644 --- a/extensions/ImGuiEXT/CCImGuiEXT.h +++ b/extensions/ImGuiEXT/CCImGuiEXT.h @@ -50,10 +50,10 @@ public: /// /// /// - void addFont(const std::string& fontFile, + void addFont(std::string_view fontFile, float fontSize = DEFAULT_FONT_SIZE, CHS_GLYPH_RANGE glyphRange = CHS_GLYPH_RANGE::NONE); - void removeFont(const std::string& fontFile); + void removeFont(std::string_view fontFile); void clearFonts(); /// @@ -62,13 +62,13 @@ public: /// The FOURCC id of render loop, starts with '#', such as "#abcd" /// the ImGui render loop /// The target scene to track event, nullptr for global, useful for global GM tools - bool addRenderLoop(const std::string& id, std::function func, Scene* target); + bool addRenderLoop(std::string_view id, std::function func, Scene* target); /// /// Remove ImGui render loop /// /// FOURCC starts with '#', such as "#abcd" - void removeRenderLoop(const std::string& id); + void removeRenderLoop(std::string_view id); void end(); @@ -112,7 +112,7 @@ public: static void setLabelColor(Label* label, bool disabled = false); static void setLabelColor(Label* label, ImGuiCol col); - ImWchar* addGlyphRanges(const std::string& key, const std::vector& ranges); + ImWchar* addGlyphRanges(std::string_view key, const std::vector& ranges); static void mergeFontGlyphs(ImFont* dst, ImFont* src, ImWchar start, ImWchar end); int getCCRefId(Ref* p); @@ -126,8 +126,8 @@ public: void setMarkdownLinkCallback(const MdLinkCallback& f); void setMarkdownImageCallback(const MdImageCallback& f); void setMarkdownFont(int index, ImFont* font, bool seperator, float scale = 1.f); - void setMarkdownLinkIcon(const std::string& icon); - void markdown(const std::string& content); + void setMarkdownLinkIcon(std::string_view icon); + void markdown(std::string_view content); #endif private: @@ -154,7 +154,7 @@ private: std::unordered_map usedCCRefIdMap; // cocos objects should be retained until next frame Vector usedCCRef; - std::unordered_map> glyphRanges; + hlookup::string_map> glyphRanges; float _contentZoomFactor = 1.0f; @@ -168,7 +168,7 @@ private: CHS_GLYPH_RANGE glyphRange; }; - std::unordered_map _fontsInfoMap; + hlookup::string_map _fontsInfoMap; bool _purgeNextLoop = false; }; diff --git a/extensions/Particle3D/CCParticle3DRender.cpp b/extensions/Particle3D/CCParticle3DRender.cpp index 58b022430e..d2907930af 100644 --- a/extensions/Particle3D/CCParticle3DRender.cpp +++ b/extensions/Particle3D/CCParticle3DRender.cpp @@ -51,7 +51,7 @@ Particle3DQuadRender::~Particle3DQuadRender() CC_SAFE_RELEASE(_indexBuffer); } -Particle3DQuadRender* Particle3DQuadRender::create(const std::string& texFile) +Particle3DQuadRender* Particle3DQuadRender::create(std::string_view texFile) { auto ret = new Particle3DQuadRender(); if (ret->initQuadRender(texFile)) @@ -185,7 +185,7 @@ void Particle3DQuadRender::render(Renderer* renderer, const Mat4& transform, Par renderer->addCommand(&_afterCommand); } -bool Particle3DQuadRender::initQuadRender(const std::string& texFile) +bool Particle3DQuadRender::initQuadRender(std::string_view texFile) { CC_SAFE_RELEASE_NULL(_programState); @@ -285,7 +285,7 @@ Particle3DModelRender::~Particle3DModelRender() } } -Particle3DModelRender* Particle3DModelRender::create(const std::string& modelFile, const std::string& texFile) +Particle3DModelRender* Particle3DModelRender::create(std::string_view modelFile, std::string_view texFile) { auto ret = new Particle3DModelRender(); ret->_modelFile = modelFile; diff --git a/extensions/Particle3D/CCParticle3DRender.h b/extensions/Particle3D/CCParticle3DRender.h index aaa0d70104..0d2d0b0188 100644 --- a/extensions/Particle3D/CCParticle3DRender.h +++ b/extensions/Particle3D/CCParticle3DRender.h @@ -95,7 +95,7 @@ protected: class CC_EX_DLL Particle3DQuadRender : public Particle3DRender { public: - static Particle3DQuadRender* create(const std::string& texFile = ""); + static Particle3DQuadRender* create(std::string_view texFile = ""); virtual void render(Renderer* renderer, const Mat4& transform, ParticleSystem3D* particleSystem) override; @@ -104,7 +104,7 @@ public: virtual ~Particle3DQuadRender(); protected: - bool initQuadRender(const std::string& texFile); + bool initQuadRender(std::string_view texFile); void onBeforeDraw(); void onAfterDraw(); @@ -145,7 +145,7 @@ protected: class CC_EX_DLL Particle3DModelRender : public Particle3DRender { public: - static Particle3DModelRender* create(const std::string& modelFile, const std::string& texFile = ""); + static Particle3DModelRender* create(std::string_view modelFile, std::string_view texFile = ""); virtual void render(Renderer* renderer, const Mat4& transform, ParticleSystem3D* particleSystem) override; diff --git a/extensions/Particle3D/PU/CCPUAffector.cpp b/extensions/Particle3D/PU/CCPUAffector.cpp index 7f0ea5bbdd..80323f4562 100644 --- a/extensions/Particle3D/PU/CCPUAffector.cpp +++ b/extensions/Particle3D/PU/CCPUAffector.cpp @@ -161,16 +161,16 @@ void PUAffector::copyAttributesTo(PUAffector* affector) affector->_excludedEmitters = _excludedEmitters; } -void PUAffector::addEmitterToExclude(const std::string& emitterName) +void PUAffector::addEmitterToExclude(std::string_view emitterName) { auto iter = std::find(_excludedEmitters.begin(), _excludedEmitters.end(), emitterName); if (iter == _excludedEmitters.end()) { - _excludedEmitters.push_back(emitterName); + _excludedEmitters.push_back(std::string{emitterName}); } } -void PUAffector::removeEmitterToExclude(const std::string& emitterName) +void PUAffector::removeEmitterToExclude(std::string_view emitterName) { auto iter = std::find(_excludedEmitters.begin(), _excludedEmitters.end(), emitterName); if (iter != _excludedEmitters.end()) @@ -189,7 +189,7 @@ void PUAffector::process(PUParticle3D* particle, float delta, bool firstParticle if (!_excludedEmitters.empty() && particle->parentEmitter) { // Return if the emitter which emits this particle is part of the vector - std::string emitterName = particle->parentEmitter->getName(); + auto emitterName = particle->parentEmitter->getName(); auto iter = std::find(_excludedEmitters.begin(), _excludedEmitters.end(), emitterName); if (iter != _excludedEmitters.end()) { diff --git a/extensions/Particle3D/PU/CCPUAffector.h b/extensions/Particle3D/PU/CCPUAffector.h index 219d620568..255401c9a6 100644 --- a/extensions/Particle3D/PU/CCPUAffector.h +++ b/extensions/Particle3D/PU/CCPUAffector.h @@ -91,22 +91,22 @@ public: /** Todo */ - const std::string& getAffectorType() const { return _affectorType; }; - void setAffectorType(const std::string& affectorType) { _affectorType = affectorType; }; + std::string_view getAffectorType() const { return _affectorType; }; + void setAffectorType(std::string_view affectorType) { _affectorType = affectorType; }; /** Add a ParticleEmitter name that excludes Particles emitted by this ParticleEmitter from being affected. */ - void addEmitterToExclude(const std::string& emitterName); + void addEmitterToExclude(std::string_view emitterName); /** Remove a ParticleEmitter name that excludes Particles emitted by this ParticleEmitter. */ - void removeEmitterToExclude(const std::string& emitterName); + void removeEmitterToExclude(std::string_view emitterName); /** Todo */ - const std::string& getName() const { return _name; }; - void setName(const std::string& name) { _name = name; }; + std::string_view getName() const { return _name; }; + void setName(std::string_view name) { _name = name; }; virtual void copyAttributesTo(PUAffector* affector); diff --git a/extensions/Particle3D/PU/CCPUAffectorManager.cpp b/extensions/Particle3D/PU/CCPUAffectorManager.cpp index e9b4e5e00f..c5be72d24d 100644 --- a/extensions/Particle3D/PU/CCPUAffectorManager.cpp +++ b/extensions/Particle3D/PU/CCPUAffectorManager.cpp @@ -63,7 +63,7 @@ PUAffectorManager* PUAffectorManager::Instance() return &pam; } -PUScriptTranslator* PUAffectorManager::getTranslator(const std::string& type) +PUScriptTranslator* PUAffectorManager::getTranslator(std::string_view type) { if (type == "Align") { @@ -172,7 +172,7 @@ PUScriptTranslator* PUAffectorManager::getTranslator(const std::string& type) return nullptr; } -PUAffector* PUAffectorManager::createAffector(const std::string& type) +PUAffector* PUAffectorManager::createAffector(std::string_view type) { if (type == "Align") { diff --git a/extensions/Particle3D/PU/CCPUAffectorManager.h b/extensions/Particle3D/PU/CCPUAffectorManager.h index 8fe439c10f..9a768d52fe 100644 --- a/extensions/Particle3D/PU/CCPUAffectorManager.h +++ b/extensions/Particle3D/PU/CCPUAffectorManager.h @@ -66,8 +66,8 @@ public: /** */ - PUScriptTranslator* getTranslator(const std::string& type); - PUAffector* createAffector(const std::string& type); + PUScriptTranslator* getTranslator(std::string_view type); + PUAffector* createAffector(std::string_view type); CC_CONSTRUCTOR_ACCESS : PUAffectorManager(); ~PUAffectorManager(); diff --git a/extensions/Particle3D/PU/CCPUBeamRender.cpp b/extensions/Particle3D/PU/CCPUBeamRender.cpp index c68c2f603e..d278f52dc8 100644 --- a/extensions/Particle3D/PU/CCPUBeamRender.cpp +++ b/extensions/Particle3D/PU/CCPUBeamRender.cpp @@ -49,7 +49,7 @@ const float PUBeamRender::DEFAULT_DEVIATION const size_t PUBeamRender::DEFAULT_NUMBER_OF_SEGMENTS = 2; const PUBillboardChain::TexCoordDirection PUBeamRender::DEFAULT_TEXTURE_DIRECTION = PUBillboardChain::TCD_V; -PUBeamRender* PUBeamRender::create(const std::string& texFile) +PUBeamRender* PUBeamRender::create(std::string_view texFile) { auto br = new PUBeamRender(); br->autorelease(); diff --git a/extensions/Particle3D/PU/CCPUBeamRender.h b/extensions/Particle3D/PU/CCPUBeamRender.h index 0d0ccc8ed6..6d6e270295 100644 --- a/extensions/Particle3D/PU/CCPUBeamRender.h +++ b/extensions/Particle3D/PU/CCPUBeamRender.h @@ -87,7 +87,7 @@ public: static const size_t DEFAULT_NUMBER_OF_SEGMENTS; static const PUBillboardChain::TexCoordDirection DEFAULT_TEXTURE_DIRECTION; - static PUBeamRender* create(const std::string& texFile = ""); + static PUBeamRender* create(std::string_view texFile = ""); virtual void prepare() override; virtual void unPrepare() override; diff --git a/extensions/Particle3D/PU/CCPUBehaviour.h b/extensions/Particle3D/PU/CCPUBehaviour.h index 15d098d439..745cfb669a 100644 --- a/extensions/Particle3D/PU/CCPUBehaviour.h +++ b/extensions/Particle3D/PU/CCPUBehaviour.h @@ -45,8 +45,8 @@ class CC_EX_DLL PUBehaviour : public Ref public: /** Todo */ - const std::string& getBehaviourType() const { return _behaviourType; }; - void setBehaviourType(const std::string& behaviourType) { _behaviourType = behaviourType; }; + std::string_view getBehaviourType() const { return _behaviourType; }; + void setBehaviourType(std::string_view behaviourType) { _behaviourType = behaviourType; }; /** Notify that the Behaviour is rescaled. */ diff --git a/extensions/Particle3D/PU/CCPUBehaviourManager.cpp b/extensions/Particle3D/PU/CCPUBehaviourManager.cpp index 6ff319f616..2ce24c156a 100644 --- a/extensions/Particle3D/PU/CCPUBehaviourManager.cpp +++ b/extensions/Particle3D/PU/CCPUBehaviourManager.cpp @@ -38,7 +38,7 @@ PUBehaviourManager* PUBehaviourManager::Instance() return &pam; } -PUScriptTranslator* PUBehaviourManager::getTranslator(const std::string& type) +PUScriptTranslator* PUBehaviourManager::getTranslator(std::string_view type) { if (type == "Slave") { @@ -47,7 +47,7 @@ PUScriptTranslator* PUBehaviourManager::getTranslator(const std::string& type) return nullptr; } -PUBehaviour* PUBehaviourManager::createBehaviour(const std::string& type) +PUBehaviour* PUBehaviourManager::createBehaviour(std::string_view type) { if (type == "Slave") { diff --git a/extensions/Particle3D/PU/CCPUBehaviourManager.h b/extensions/Particle3D/PU/CCPUBehaviourManager.h index 91dfffb450..7f468f173a 100644 --- a/extensions/Particle3D/PU/CCPUBehaviourManager.h +++ b/extensions/Particle3D/PU/CCPUBehaviourManager.h @@ -41,8 +41,8 @@ public: /** */ - PUScriptTranslator* getTranslator(const std::string& type); - PUBehaviour* createBehaviour(const std::string& type); + PUScriptTranslator* getTranslator(std::string_view type); + PUBehaviour* createBehaviour(std::string_view type); CC_CONSTRUCTOR_ACCESS : PUBehaviourManager(); ~PUBehaviourManager(); diff --git a/extensions/Particle3D/PU/CCPUBillboardChain.cpp b/extensions/Particle3D/PU/CCPUBillboardChain.cpp index b83a9dcb4e..f0646533e2 100644 --- a/extensions/Particle3D/PU/CCPUBillboardChain.cpp +++ b/extensions/Particle3D/PU/CCPUBillboardChain.cpp @@ -48,8 +48,8 @@ PUBillboardChain::Element::Element(const Vec3& pos, float w, float tex, const Ve : position(pos), width(w), texCoord(tex), color(col), orientation(ori) {} //----------------------------------------------------------------------- -PUBillboardChain::PUBillboardChain(const std::string& /*name*/, - const std::string& texFile, +PUBillboardChain::PUBillboardChain(std::string_view /*name*/, + std::string_view texFile, size_t maxElements, size_t numberOfChains, bool useTextureCoords, @@ -627,7 +627,7 @@ void PUBillboardChain::updateIndexBuffer() } } //----------------------------------------------------------------------- -void PUBillboardChain::init(const std::string& texFile) +void PUBillboardChain::init(std::string_view texFile) { CC_SAFE_RELEASE_NULL(_programState); diff --git a/extensions/Particle3D/PU/CCPUBillboardChain.h b/extensions/Particle3D/PU/CCPUBillboardChain.h index 329029d2ac..12825a0f1c 100644 --- a/extensions/Particle3D/PU/CCPUBillboardChain.h +++ b/extensions/Particle3D/PU/CCPUBillboardChain.h @@ -77,8 +77,8 @@ public: @param useVertexColours If true, use vertex colours from the chain elements @param dynamic If true, buffers are created with the intention of being updated */ - PUBillboardChain(const std::string& name, - const std::string& texFile = "", + PUBillboardChain(std::string_view name, + std::string_view texFile = "", size_t maxElements = 20, size_t numberOfChains = 1, bool useTextureCoords = true, @@ -245,7 +245,7 @@ protected: /// Update the contents of the index buffer virtual void updateIndexBuffer(); - void init(const std::string& texFile); + void init(std::string_view texFile); private: void onBeforeDraw(); diff --git a/extensions/Particle3D/PU/CCPUDoAffectorEventHandler.h b/extensions/Particle3D/PU/CCPUDoAffectorEventHandler.h index 3c2985c3d1..b4425d880c 100644 --- a/extensions/Particle3D/PU/CCPUDoAffectorEventHandler.h +++ b/extensions/Particle3D/PU/CCPUDoAffectorEventHandler.h @@ -57,11 +57,11 @@ public: /** Get the name of the affector that must be enabled or disabled. */ - const std::string& getAffectorName() const { return _affectorName; }; + std::string_view getAffectorName() const { return _affectorName; }; /** Set the name of the affector. */ - void setAffectorName(const std::string& affectorName) { _affectorName = affectorName; }; + void setAffectorName(std::string_view affectorName) { _affectorName = affectorName; }; /** If the _handle() function of this class is invoked (by an Observer), it searches the ParticleAffector defined by the its name. diff --git a/extensions/Particle3D/PU/CCPUDoEnableComponentEventHandler.h b/extensions/Particle3D/PU/CCPUDoEnableComponentEventHandler.h index 9c9ff4c0fd..94e56865f2 100644 --- a/extensions/Particle3D/PU/CCPUDoEnableComponentEventHandler.h +++ b/extensions/Particle3D/PU/CCPUDoEnableComponentEventHandler.h @@ -47,11 +47,11 @@ public: /** Get the name of the component that must be enabled or disabled. */ - const std::string& getComponentName() const { return _componentName; }; + std::string_view getComponentName() const { return _componentName; }; /** Set the name of the component that must be enabled or disables. */ - void setComponentName(const std::string& componentName) { _componentName = componentName; }; + void setComponentName(std::string_view componentName) { _componentName = componentName; }; /** Get the value that identifies whether the component must be enabled or disabled. */ diff --git a/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.cpp b/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.cpp index f70ba179ff..d572be1118 100644 --- a/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.cpp +++ b/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.cpp @@ -241,7 +241,7 @@ void PUDoPlacementParticleEventHandler::particleExpired(PUParticleSystem3D* /*pa {} //----------------------------------------------------------------------- -void PUDoPlacementParticleEventHandler::setForceEmitterName(const std::string& forceEmitterName) +void PUDoPlacementParticleEventHandler::setForceEmitterName(std::string_view forceEmitterName) { _forceEmitterName = forceEmitterName; } diff --git a/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.h b/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.h index cb33bb8cbd..3304e73094 100644 --- a/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.h +++ b/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.h @@ -78,11 +78,11 @@ public: /** Get the name of the emitter that is used to emit its particles. */ - const std::string& getForceEmitterName() const { return _forceEmitterName; }; + std::string_view getForceEmitterName() const { return _forceEmitterName; }; /** Set the name of the emitter that is used to emit its particles. */ - void setForceEmitterName(const std::string& forceEmitterName); + void setForceEmitterName(std::string_view forceEmitterName); /** Returns a pointer to the emitter that is used as a force emitter. */ diff --git a/extensions/Particle3D/PU/CCPUEmitter.cpp b/extensions/Particle3D/PU/CCPUEmitter.cpp index fdf3ac0487..2914895a70 100644 --- a/extensions/Particle3D/PU/CCPUEmitter.cpp +++ b/extensions/Particle3D/PU/CCPUEmitter.cpp @@ -497,7 +497,7 @@ void PUEmitter::setParticleTextureCoordsRangeEnd(const unsigned short& particleT } //----------------------------------------------------------------------- -void PUEmitter::setEmitsName(const std::string& emitsName) +void PUEmitter::setEmitsName(std::string_view emitsName) { _emitsName = emitsName; _emitsEntity = nullptr; diff --git a/extensions/Particle3D/PU/CCPUEmitter.h b/extensions/Particle3D/PU/CCPUEmitter.h index 4aa3c3a163..bccc699bdf 100644 --- a/extensions/Particle3D/PU/CCPUEmitter.h +++ b/extensions/Particle3D/PU/CCPUEmitter.h @@ -112,13 +112,13 @@ public: /** Todo */ - const std::string& getEmitterType() const { return _emitterType; } - void setEmitterType(const std::string& emitterType) { _emitterType = emitterType; }; + std::string_view getEmitterType() const { return _emitterType; } + void setEmitterType(std::string_view emitterType) { _emitterType = emitterType; }; /** Todo */ - const std::string& getName() const { return _name; } - void setName(const std::string& name) { _name = name; }; + std::string_view getName() const { return _name; } + void setName(std::string_view name) { _name = name; }; /** Todo */ @@ -188,8 +188,8 @@ public: /** Todo */ - const std::string& getEmitsName() const { return _emitsName; } - void setEmitsName(const std::string& emitsName); + std::string_view getEmitsName() const { return _emitsName; } + void setEmitsName(std::string_view emitsName); PUParticle3D::ParticleType getEmitsType() const { return _emitsType; } void setEmitsType(PUParticle3D::ParticleType type) { _emitsType = type; }; Ref* getEmitsEntityPtr() const; diff --git a/extensions/Particle3D/PU/CCPUEmitterManager.cpp b/extensions/Particle3D/PU/CCPUEmitterManager.cpp index f18566fc94..4c587b04aa 100644 --- a/extensions/Particle3D/PU/CCPUEmitterManager.cpp +++ b/extensions/Particle3D/PU/CCPUEmitterManager.cpp @@ -45,7 +45,7 @@ PUEmitterManager* PUEmitterManager::Instance() return &ptm; } -PUScriptTranslator* PUEmitterManager::getTranslator(const std::string& type) +PUScriptTranslator* PUEmitterManager::getTranslator(std::string_view type) { if (type == "Box") { @@ -86,7 +86,7 @@ PUScriptTranslator* PUEmitterManager::getTranslator(const std::string& type) return nullptr; } -PUEmitter* PUEmitterManager::createEmitter(const std::string& type) +PUEmitter* PUEmitterManager::createEmitter(std::string_view type) { if (type == "Box") { diff --git a/extensions/Particle3D/PU/CCPUEmitterManager.h b/extensions/Particle3D/PU/CCPUEmitterManager.h index 00ee4c33ae..5affa49ef8 100644 --- a/extensions/Particle3D/PU/CCPUEmitterManager.h +++ b/extensions/Particle3D/PU/CCPUEmitterManager.h @@ -48,8 +48,8 @@ public: /** */ - PUScriptTranslator* getTranslator(const std::string& type); - PUEmitter* createEmitter(const std::string& type); + PUScriptTranslator* getTranslator(std::string_view type); + PUEmitter* createEmitter(std::string_view type); CC_CONSTRUCTOR_ACCESS : PUEmitterManager(); ~PUEmitterManager(); diff --git a/extensions/Particle3D/PU/CCPUEventHandler.h b/extensions/Particle3D/PU/CCPUEventHandler.h index 771252122f..a9f4582b77 100644 --- a/extensions/Particle3D/PU/CCPUEventHandler.h +++ b/extensions/Particle3D/PU/CCPUEventHandler.h @@ -44,8 +44,8 @@ class CC_EX_DLL PUEventHandler : public Ref public: /** Todo */ - const std::string& getName() const { return _name; }; - void setName(const std::string& name) { _name = name; }; + std::string_view getName() const { return _name; }; + void setName(std::string_view name) { _name = name; }; /** Todo */ @@ -54,8 +54,8 @@ public: /** Todo */ - const std::string& getEventHandlerType() const { return _eventHandlerType; }; - void setEventHandlerType(const std::string& eventHandlerType) { _eventHandlerType = eventHandlerType; }; + std::string_view getEventHandlerType() const { return _eventHandlerType; }; + void setEventHandlerType(std::string_view eventHandlerType) { _eventHandlerType = eventHandlerType; }; /** Notify that the event handler is rescaled. */ diff --git a/extensions/Particle3D/PU/CCPUEventHandlerManager.cpp b/extensions/Particle3D/PU/CCPUEventHandlerManager.cpp index df3803a8f4..06206b7b99 100644 --- a/extensions/Particle3D/PU/CCPUEventHandlerManager.cpp +++ b/extensions/Particle3D/PU/CCPUEventHandlerManager.cpp @@ -44,7 +44,7 @@ PUEventHandlerManager* PUEventHandlerManager::Instance() return &pem; } -PUScriptTranslator* PUEventHandlerManager::getTranslator(const std::string& type) +PUScriptTranslator* PUEventHandlerManager::getTranslator(std::string_view type) { if (type == "DoAffector") { @@ -77,7 +77,7 @@ PUScriptTranslator* PUEventHandlerManager::getTranslator(const std::string& type return nullptr; } -PUEventHandler* PUEventHandlerManager::createEventHandler(const std::string& type) +PUEventHandler* PUEventHandlerManager::createEventHandler(std::string_view type) { if (type == "DoAffector") { diff --git a/extensions/Particle3D/PU/CCPUEventHandlerManager.h b/extensions/Particle3D/PU/CCPUEventHandlerManager.h index 2cc470c60b..bd09e1487c 100644 --- a/extensions/Particle3D/PU/CCPUEventHandlerManager.h +++ b/extensions/Particle3D/PU/CCPUEventHandlerManager.h @@ -45,8 +45,8 @@ public: /** */ - PUScriptTranslator* getTranslator(const std::string& type); - PUEventHandler* createEventHandler(const std::string& type); + PUScriptTranslator* getTranslator(std::string_view type); + PUEventHandler* createEventHandler(std::string_view type); CC_CONSTRUCTOR_ACCESS : diff --git a/extensions/Particle3D/PU/CCPUMaterialManager.cpp b/extensions/Particle3D/PU/CCPUMaterialManager.cpp index 05aa70292c..867b664462 100644 --- a/extensions/Particle3D/PU/CCPUMaterialManager.cpp +++ b/extensions/Particle3D/PU/CCPUMaterialManager.cpp @@ -77,7 +77,7 @@ PUMaterialCache* PUMaterialCache::Instance() return &pmm; } -PUMaterial* PUMaterialCache::getMaterial(const std::string& name) +PUMaterial* PUMaterialCache::getMaterial(std::string_view name) { for (auto iter : _materialMap) { @@ -87,7 +87,7 @@ PUMaterial* PUMaterialCache::getMaterial(const std::string& name) return nullptr; } -bool PUMaterialCache::loadMaterials(const std::string& file) +bool PUMaterialCache::loadMaterials(std::string_view file) { bool isFirstCompile = true; auto list = PUScriptCompiler::Instance()->compile(file, isFirstCompile); @@ -128,18 +128,23 @@ int iterPath(const char* fpath, const struct stat* /*sb*/, int typeflag) } #endif -bool PUMaterialCache::loadMaterialsFromSearchPaths(const std::string& fileFolder) +bool PUMaterialCache::loadMaterialsFromSearchPaths(std::string_view fileFolder) { bool state = false; #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) std::string seg("/"); - std::string fullPath = fileFolder + seg + std::string("*.material"); + std::string fullPath{fileFolder}; + fullPath += seg; + fullPath += std::string("*.material"); _finddata_t data; intptr_t handle = _findfirst(fullPath.c_str(), &data); int done = 0; while ((handle != -1) && (done == 0)) { - loadMaterials(fileFolder + seg + std::string(data.name)); + fullPath = fileFolder; + fullPath += seg; + fullPath += data.name; + loadMaterials(fullPath); done = _findnext(handle, &data); state = true; } diff --git a/extensions/Particle3D/PU/CCPUMaterialManager.h b/extensions/Particle3D/PU/CCPUMaterialManager.h index 54543ce349..a5cbac8934 100644 --- a/extensions/Particle3D/PU/CCPUMaterialManager.h +++ b/extensions/Particle3D/PU/CCPUMaterialManager.h @@ -63,9 +63,9 @@ public: static PUMaterialCache* Instance(); - bool loadMaterials(const std::string& file); - bool loadMaterialsFromSearchPaths(const std::string& fileFolder); - PUMaterial* getMaterial(const std::string& name); + bool loadMaterials(std::string_view file); + bool loadMaterialsFromSearchPaths(std::string_view fileFolder); + PUMaterial* getMaterial(std::string_view name); void addMaterial(PUMaterial* material); protected: diff --git a/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.cpp b/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.cpp index b453dc4126..2ee1f24f7d 100644 --- a/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.cpp +++ b/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.cpp @@ -162,7 +162,7 @@ const PUTriangle::PositionAndNormal PUTriangle::getRandomVertexAndNormal() //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- -MeshInfo::MeshInfo(const std::string& /*meshName*/, +MeshInfo::MeshInfo(std::string_view /*meshName*/, MeshSurfaceDistribution distribution, const Quaternion& /*orientation*/, const Vec3& /*scale*/) @@ -527,12 +527,12 @@ void PUMeshSurfaceEmitter::initParticleDirection(PUParticle3D* particle) } } //----------------------------------------------------------------------- -const std::string& PUMeshSurfaceEmitter::getMeshName() const +std::string_view PUMeshSurfaceEmitter::getMeshName() const { return _meshName; } //----------------------------------------------------------------------- -void PUMeshSurfaceEmitter::setMeshName(const std::string& meshName, bool doBuild) +void PUMeshSurfaceEmitter::setMeshName(std::string_view meshName, bool doBuild) { _meshName = meshName; diff --git a/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.h b/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.h index 9f1cd8389f..553d101176 100644 --- a/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.h +++ b/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.h @@ -119,7 +119,7 @@ public: }; /** Constructor **/ - MeshInfo(const std::string& meshName, + MeshInfo(std::string_view meshName, const MeshSurfaceDistribution distribution = MSD_HOMOGENEOUS, const Quaternion& orientation = Quaternion(), const Vec3& scale = Vec3::ZERO); @@ -173,11 +173,11 @@ public: /** Returns the mesh name. */ - const std::string& getMeshName() const; + std::string_view getMeshName() const; /** Sets the mesh name. */ - void setMeshName(const std::string& meshName, bool doBuild = true); + void setMeshName(std::string_view meshName, bool doBuild = true); /** Returns true if normals are used for the particle direction. */ diff --git a/extensions/Particle3D/PU/CCPUObserver.cpp b/extensions/Particle3D/PU/CCPUObserver.cpp index 6b93991b2a..edfc370560 100644 --- a/extensions/Particle3D/PU/CCPUObserver.cpp +++ b/extensions/Particle3D/PU/CCPUObserver.cpp @@ -130,7 +130,7 @@ void PUObserver::notifyRescaled(const Vec3& scale) } } //----------------------------------------------------------------------- -PUEventHandler* PUObserver::createEventHandler(const std::string& eventHandlerType) +PUEventHandler* PUObserver::createEventHandler(std::string_view eventHandlerType) { PUEventHandler* eventHandler = PUEventHandlerManager::Instance()->createEventHandler(eventHandlerType); addEventHandler(eventHandler); @@ -168,7 +168,7 @@ PUEventHandler* PUObserver::getEventHandler(size_t index) const return _eventHandlers[index]; } //----------------------------------------------------------------------- -PUEventHandler* PUObserver::getEventHandler(const std::string& eventHandlerName) const +PUEventHandler* PUObserver::getEventHandler(std::string_view eventHandlerName) const { if (eventHandlerName.empty()) return nullptr; diff --git a/extensions/Particle3D/PU/CCPUObserver.h b/extensions/Particle3D/PU/CCPUObserver.h index c2455aa036..dcb354bc02 100644 --- a/extensions/Particle3D/PU/CCPUObserver.h +++ b/extensions/Particle3D/PU/CCPUObserver.h @@ -63,8 +63,8 @@ public: /** Todo */ - const std::string& getObserverType() const { return _observerType; }; - void setObserverType(const std::string& observerType) { _observerType = observerType; }; + std::string_view getObserverType() const { return _observerType; }; + void setObserverType(std::string_view observerType) { _observerType = observerType; }; /** Todo */ @@ -93,8 +93,8 @@ public: /** Todo */ - const std::string& getName() const { return _name; }; - void setName(const std::string& name) { _name = name; }; + std::string_view getName() const { return _name; }; + void setName(std::string_view name) { _name = name; }; /** Todo */ @@ -115,7 +115,7 @@ public: /** Todo */ - PUEventHandler* createEventHandler(const std::string& eventHandlerType); + PUEventHandler* createEventHandler(std::string_view eventHandlerType); /** Todo */ @@ -131,7 +131,7 @@ public: /** Todo */ - PUEventHandler* getEventHandler(const std::string& eventHandlerName) const; + PUEventHandler* getEventHandler(std::string_view eventHandlerName) const; /** Todo */ diff --git a/extensions/Particle3D/PU/CCPUObserverManager.cpp b/extensions/Particle3D/PU/CCPUObserverManager.cpp index 3ac7859ed6..a90e2fdb09 100644 --- a/extensions/Particle3D/PU/CCPUObserverManager.cpp +++ b/extensions/Particle3D/PU/CCPUObserverManager.cpp @@ -48,7 +48,7 @@ PUObserverManager* PUObserverManager::Instance() return &pem; } -PUScriptTranslator* PUObserverManager::getTranslator(const std::string& type) +PUScriptTranslator* PUObserverManager::getTranslator(std::string_view type) { if (type == "OnClear") { @@ -97,7 +97,7 @@ PUScriptTranslator* PUObserverManager::getTranslator(const std::string& type) return nullptr; } -PUObserver* PUObserverManager::createObserver(const std::string& type) +PUObserver* PUObserverManager::createObserver(std::string_view type) { if (type == "OnClear") { diff --git a/extensions/Particle3D/PU/CCPUObserverManager.h b/extensions/Particle3D/PU/CCPUObserverManager.h index cd1a69dac8..8134843e1b 100644 --- a/extensions/Particle3D/PU/CCPUObserverManager.h +++ b/extensions/Particle3D/PU/CCPUObserverManager.h @@ -50,8 +50,8 @@ public: /** */ - PUScriptTranslator* getTranslator(const std::string& type); - PUObserver* createObserver(const std::string& type); + PUScriptTranslator* getTranslator(std::string_view type); + PUObserver* createObserver(std::string_view type); CC_CONSTRUCTOR_ACCESS : diff --git a/extensions/Particle3D/PU/CCPUParticleSystem3D.cpp b/extensions/Particle3D/PU/CCPUParticleSystem3D.cpp index e9818e3a25..6fabe49b9b 100644 --- a/extensions/Particle3D/PU/CCPUParticleSystem3D.cpp +++ b/extensions/Particle3D/PU/CCPUParticleSystem3D.cpp @@ -259,7 +259,7 @@ PUParticleSystem3D* PUParticleSystem3D::create() return pups; } -PUParticleSystem3D* PUParticleSystem3D::create(const std::string& filePath, const std::string& materialPath) +PUParticleSystem3D* PUParticleSystem3D::create(std::string_view filePath, std::string_view materialPath) { PUParticleSystem3D* ret = new PUParticleSystem3D(); if (ret->initWithFilePathAndMaterialPath(filePath, materialPath)) @@ -274,7 +274,7 @@ PUParticleSystem3D* PUParticleSystem3D::create(const std::string& filePath, cons } } -PUParticleSystem3D* PUParticleSystem3D::create(const std::string& filePath) +PUParticleSystem3D* PUParticleSystem3D::create(std::string_view filePath) { PUParticleSystem3D* ret = new PUParticleSystem3D(); if (ret->initWithFilePath(filePath)) @@ -289,7 +289,7 @@ PUParticleSystem3D* PUParticleSystem3D::create(const std::string& filePath) } } -bool PUParticleSystem3D::initWithFilePath(const std::string& filePath) +bool PUParticleSystem3D::initWithFilePath(std::string_view filePath) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); convertToUnixStylePath(fullPath); @@ -318,7 +318,7 @@ bool PUParticleSystem3D::initWithFilePath(const std::string& filePath) return true; } -bool PUParticleSystem3D::initWithFilePathAndMaterialPath(const std::string& filePath, const std::string& materialPath) +bool PUParticleSystem3D::initWithFilePathAndMaterialPath(std::string_view filePath, std::string_view materialPath) { std::string matfullPath = FileUtils::getInstance()->fullPathForFilename(materialPath); convertToUnixStylePath(matfullPath); @@ -629,24 +629,24 @@ void PUParticleSystem3D::unPrepared() _particlePool.lockAllDatas(); for (auto& iter : _emittedEmitterParticlePool) { - PUParticle3D* particle = static_cast(iter.second.getFirst()); + PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->unPrepare(); - particle = static_cast(iter.second.getNext()); + particle = static_cast(const_cast(iter.second).getNext()); } - iter.second.lockAllDatas(); + const_cast(iter.second).lockAllDatas(); } for (auto& iter : _emittedSystemParticlePool) { - PUParticle3D* particle = static_cast(iter.second.getFirst()); + PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->unPrepared(); - particle = static_cast(iter.second.getNext()); + particle = static_cast(const_cast(iter.second).getNext()); } - iter.second.lockAllDatas(); + const_cast(iter.second).lockAllDatas(); } _prepared = false; } @@ -692,21 +692,21 @@ void PUParticleSystem3D::preUpdator(float elapsedTime) for (auto& iter : _emittedEmitterParticlePool) { - PUParticle3D* particle = static_cast(iter.second.getFirst()); + PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->preUpdateEmitter(elapsedTime); - particle = static_cast(iter.second.getNext()); + particle = static_cast(const_cast(iter.second).getNext()); } } for (auto& iter : _emittedSystemParticlePool) { - PUParticle3D* particle = static_cast(iter.second.getFirst()); + PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->preUpdator(elapsedTime); - particle = static_cast(iter.second.getNext()); + particle = static_cast(const_cast(iter.second).getNext()); } } } @@ -719,12 +719,12 @@ void PUParticleSystem3D::updator(float elapsedTime) for (auto& iter : _emittedEmitterParticlePool) { - processParticle(iter.second, firstActiveParticle, firstParticle, elapsedTime); + processParticle(const_cast(iter.second), firstActiveParticle, firstParticle, elapsedTime); } for (auto& iter : _emittedSystemParticlePool) { - processParticle(iter.second, firstActiveParticle, firstParticle, elapsedTime); + processParticle(const_cast(iter.second), firstActiveParticle, firstParticle, elapsedTime); } } @@ -763,21 +763,21 @@ void PUParticleSystem3D::postUpdator(float elapsedTime) for (auto& iter : _emittedEmitterParticlePool) { - PUParticle3D* particle = static_cast(iter.second.getFirst()); + PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->postUpdateEmitter(elapsedTime); - particle = static_cast(iter.second.getNext()); + particle = static_cast(const_cast(iter.second).getNext()); } } for (auto& iter : _emittedSystemParticlePool) { - PUParticle3D* particle = static_cast(iter.second.getFirst()); + PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->postUpdator(elapsedTime); - particle = static_cast(iter.second.getNext()); + particle = static_cast(const_cast(iter.second).getNext()); } } } @@ -901,7 +901,7 @@ void PUParticleSystem3D::setMaxVelocity(float maxVelocity) _maxVelocitySet = true; } -bool PUParticleSystem3D::initSystem(const std::string& filePath) +bool PUParticleSystem3D::initSystem(std::string_view filePath) { bool isFirstCompile = true; auto list = PUScriptCompiler::Instance()->compile(filePath, isFirstCompile); @@ -922,7 +922,7 @@ void PUParticleSystem3D::addEmitter(PUEmitter* emitter) } } -PUAffector* PUParticleSystem3D::getAffector(const std::string& name) +PUAffector* PUParticleSystem3D::getAffector(std::string_view name) { for (auto iter : _affectors) { @@ -934,7 +934,7 @@ PUAffector* PUParticleSystem3D::getAffector(const std::string& name) return nullptr; } -PUEmitter* PUParticleSystem3D::getEmitter(const std::string& name) +PUEmitter* PUParticleSystem3D::getEmitter(std::string_view name) { for (auto iter : _emitters) { @@ -1040,7 +1040,7 @@ void PUParticleSystem3D::addObserver(PUObserver* observer) } } -PUObserver* PUParticleSystem3D::getObserver(const std::string& name) +PUObserver* PUParticleSystem3D::getObserver(std::string_view name) { for (auto iter : _observers) { @@ -1074,21 +1074,21 @@ void PUParticleSystem3D::notifyRescaled(const Vec3& scl) for (auto& iter : _emittedEmitterParticlePool) { - PUParticle3D* particle = static_cast(iter.second.getFirst()); + PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->notifyRescaled(scl); - particle = static_cast(iter.second.getNext()); + particle = static_cast(const_cast(iter.second).getNext()); } } for (auto& iter : _emittedSystemParticlePool) { - PUParticle3D* particle = static_cast(iter.second.getFirst()); + PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->notifyRescaled(scl); - particle = static_cast(iter.second.getNext()); + particle = static_cast(const_cast(iter.second).getNext()); } } } @@ -1164,12 +1164,12 @@ void PUParticleSystem3D::clearAllParticles() _particlePool.lockAllDatas(); for (auto& iter : _emittedEmitterParticlePool) { - iter.second.lockAllDatas(); + const_cast(iter.second).lockAllDatas(); } for (auto& iter : _emittedSystemParticlePool) { - iter.second.lockAllDatas(); + const_cast(iter.second).lockAllDatas(); } } @@ -1303,11 +1303,11 @@ void PUParticleSystem3D::draw(Renderer* renderer, const Mat4& transform, uint32_ { for (auto& iter : _emittedSystemParticlePool) { - PUParticle3D* particle = static_cast(iter.second.getFirst()); + PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->draw(renderer, transform, flags); - particle = static_cast(iter.second.getNext()); + particle = static_cast(const_cast(iter.second).getNext()); } } } diff --git a/extensions/Particle3D/PU/CCPUParticleSystem3D.h b/extensions/Particle3D/PU/CCPUParticleSystem3D.h index 4b73e26c1d..d7773d9892 100644 --- a/extensions/Particle3D/PU/CCPUParticleSystem3D.h +++ b/extensions/Particle3D/PU/CCPUParticleSystem3D.h @@ -207,7 +207,7 @@ struct CC_EX_DLL PUParticle3D : public Particle3D class CC_EX_DLL PUParticleSystem3D : public ParticleSystem3D { public: - typedef std::unordered_map ParticlePoolMap; + typedef hlookup::string_map ParticlePoolMap; static const float DEFAULT_WIDTH; static const float DEFAULT_HEIGHT; @@ -218,8 +218,8 @@ public: static const float DEFAULT_MAX_VELOCITY; static PUParticleSystem3D* create(); - static PUParticleSystem3D* create(const std::string& filePath); - static PUParticleSystem3D* create(const std::string& filePath, const std::string& materialPath); + static PUParticleSystem3D* create(std::string_view filePath); + static PUParticleSystem3D* create(std::string_view filePath, std::string_view materialPath); virtual void draw(Renderer* renderer, const Mat4& transform, uint32_t flags) override; @@ -296,8 +296,8 @@ public: */ void setMaxVelocity(float maxVelocity); - void setMaterialName(const std::string& name) { _matName = name; }; - const std::string& getMaterialName() const { return _matName; }; + void setMaterialName(std::string_view name) { _matName = name; }; + std::string_view getMaterialName() const { return _matName; }; /** Forces emission of particles. * @remarks The number of requested particles are the exact number that are emitted. No down-scaling is applied. @@ -309,8 +309,8 @@ public: */ void addEmitter(PUEmitter* emitter); - PUAffector* getAffector(const std::string& name); - PUEmitter* getEmitter(const std::string& name); + PUAffector* getAffector(std::string_view name); + PUEmitter* getEmitter(std::string_view name); void removeAllEmitter(); void addListener(PUListener* listener); @@ -318,7 +318,7 @@ public: void removeAllListener(); void addObserver(PUObserver* observer); - PUObserver* getObserver(const std::string& name); + PUObserver* getObserver(std::string_view name); void removerAllObserver(); void addBehaviourTemplate(PUBehaviour* behaviour); @@ -346,13 +346,13 @@ public: virtual PUParticleSystem3D* clone(); virtual void copyAttributesTo(PUParticleSystem3D* system); - bool initSystem(const std::string& filePath); + bool initSystem(std::string_view filePath); CC_CONSTRUCTOR_ACCESS : PUParticleSystem3D(); virtual ~PUParticleSystem3D(); - bool initWithFilePath(const std::string& filePath); - bool initWithFilePathAndMaterialPath(const std::string& filePath, const std::string& materialPath); + bool initWithFilePath(std::string_view filePath); + bool initWithFilePathAndMaterialPath(std::string_view filePath, std::string_view materialPath); protected: void prepared(); diff --git a/extensions/Particle3D/PU/CCPURender.cpp b/extensions/Particle3D/PU/CCPURender.cpp index d22e2c977f..cccefce1bd 100644 --- a/extensions/Particle3D/PU/CCPURender.cpp +++ b/extensions/Particle3D/PU/CCPURender.cpp @@ -56,7 +56,7 @@ void PURender::copyAttributesTo(PURender* render) // return left->depthInView > right->depthInView; // } -PUParticle3DQuadRender* PUParticle3DQuadRender::create(const std::string& texFile) +PUParticle3DQuadRender* PUParticle3DQuadRender::create(std::string_view texFile) { auto ret = new PUParticle3DQuadRender(); if (ret->initRender(texFile)) @@ -488,8 +488,8 @@ PUParticle3DQuadRender* PUParticle3DQuadRender::clone() return render; } -PUParticle3DModelRender* PUParticle3DModelRender::create(const std::string& modelFile, - const std::string& texFile /*= ""*/) +PUParticle3DModelRender* PUParticle3DModelRender::create(std::string_view modelFile, + std::string_view texFile /*= ""*/) { auto ret = new PUParticle3DModelRender(); ret->_modelFile = modelFile; @@ -614,7 +614,7 @@ PUParticle3DEntityRender::~PUParticle3DEntityRender() CC_SAFE_RELEASE(_indexBuffer); } -bool PUParticle3DEntityRender::initRender(const std::string& texFile) +bool PUParticle3DEntityRender::initRender(std::string_view texFile) { CC_SAFE_RELEASE_NULL(_programState); if (!texFile.empty()) @@ -693,7 +693,7 @@ PUParticle3DBoxRender::PUParticle3DBoxRender() PUParticle3DBoxRender::~PUParticle3DBoxRender() {} -PUParticle3DBoxRender* PUParticle3DBoxRender::create(const std::string& texFile) +PUParticle3DBoxRender* PUParticle3DBoxRender::create(std::string_view texFile) { auto ret = new PUParticle3DBoxRender(); if (ret->initRender(texFile)) @@ -883,7 +883,7 @@ PUParticle3DBoxRender* PUParticle3DBoxRender::clone() return render; } -PUSphereRender* PUSphereRender::create(const std::string& texFile) +PUSphereRender* PUSphereRender::create(std::string_view texFile) { auto ret = new PUSphereRender(); if (ret->initRender(texFile)) diff --git a/extensions/Particle3D/PU/CCPURender.h b/extensions/Particle3D/PU/CCPURender.h index e4076c6565..002f333daf 100644 --- a/extensions/Particle3D/PU/CCPURender.h +++ b/extensions/Particle3D/PU/CCPURender.h @@ -47,8 +47,8 @@ public: virtual void unPrepare(){}; virtual void updateRender(PUParticle3D* particle, float deltaTime, bool firstParticle); - const std::string& getRenderType() const { return _renderType; }; - void setRenderType(const std::string& observerType) { _renderType = observerType; }; + std::string_view getRenderType() const { return _renderType; }; + void setRenderType(std::string_view observerType) { _renderType = observerType; }; virtual PURender* clone() = 0; void copyAttributesTo(PURender* render); @@ -70,7 +70,7 @@ public: virtual ~PUParticle3DEntityRender(); protected: - bool initRender(const std::string& texFile); + bool initRender(std::string_view texFile); void onBeforeDraw(); @@ -141,7 +141,7 @@ public: VERTEX }; - static PUParticle3DQuadRender* create(const std::string& texFile = ""); + static PUParticle3DQuadRender* create(std::string_view texFile = ""); void setType(Type type); Type getType() const { return _type; } @@ -191,7 +191,7 @@ protected: class CC_EX_DLL PUParticle3DModelRender : public PURender { public: - static PUParticle3DModelRender* create(const std::string& modelFile, const std::string& texFile = ""); + static PUParticle3DModelRender* create(std::string_view modelFile, std::string_view texFile = ""); virtual void render(Renderer* renderer, const Mat4& transform, ParticleSystem3D* particleSystem) override; @@ -212,7 +212,7 @@ protected: class CC_EX_DLL PUParticle3DBoxRender : public PUParticle3DEntityRender { public: - static PUParticle3DBoxRender* create(const std::string& texFile = ""); + static PUParticle3DBoxRender* create(std::string_view texFile = ""); virtual void render(Renderer* renderer, const Mat4& transform, ParticleSystem3D* particleSystem) override; @@ -228,7 +228,7 @@ protected: class CC_EX_DLL PUSphereRender : public PUParticle3DEntityRender { public: - static PUSphereRender* create(const std::string& texFile = ""); + static PUSphereRender* create(std::string_view texFile = ""); virtual void render(Renderer* renderer, const Mat4& transform, ParticleSystem3D* particleSystem) override; diff --git a/extensions/Particle3D/PU/CCPURibbonTrail.cpp b/extensions/Particle3D/PU/CCPURibbonTrail.cpp index b5bc2fc10b..fe05c38977 100644 --- a/extensions/Particle3D/PU/CCPURibbonTrail.cpp +++ b/extensions/Particle3D/PU/CCPURibbonTrail.cpp @@ -36,8 +36,8 @@ NS_CC_BEGIN -PURibbonTrail::PURibbonTrail(const std::string& name, - const std::string& texFile, +PURibbonTrail::PURibbonTrail(std::string_view name, + std::string_view texFile, size_t maxElements, size_t numberOfChains, bool useTextureCoords, diff --git a/extensions/Particle3D/PU/CCPURibbonTrail.h b/extensions/Particle3D/PU/CCPURibbonTrail.h index e57ccf58e6..9b32587969 100644 --- a/extensions/Particle3D/PU/CCPURibbonTrail.h +++ b/extensions/Particle3D/PU/CCPURibbonTrail.h @@ -48,8 +48,8 @@ public: @param useVertexColors If true, use vertex colors from the chain elements (must be true if you intend to use fading) */ - PURibbonTrail(const std::string& name, - const std::string& texFile = "", + PURibbonTrail(std::string_view name, + std::string_view texFile = "", size_t maxElements = 20, size_t numberOfChains = 1, bool useTextureCoords = true, diff --git a/extensions/Particle3D/PU/CCPURibbonTrailRender.cpp b/extensions/Particle3D/PU/CCPURibbonTrailRender.cpp index 8a924a9c4b..9d9d89a2bb 100644 --- a/extensions/Particle3D/PU/CCPURibbonTrailRender.cpp +++ b/extensions/Particle3D/PU/CCPURibbonTrailRender.cpp @@ -48,7 +48,7 @@ const bool PURibbonTrailRender::DEFAULT_RANDOM_INITIAL_COLOUR = true; const Vec4 PURibbonTrailRender::DEFAULT_INITIAL_COLOUR(1, 1, 1, 1); const Vec4 PURibbonTrailRender::DEFAULT_COLOUR_CHANGE(0.5, 0.5, 0.5, 0.5); -PURibbonTrailRender* PURibbonTrailRender::create(const std::string& texFile) +PURibbonTrailRender* PURibbonTrailRender::create(std::string_view texFile) { auto br = new PURibbonTrailRender(); br->autorelease(); diff --git a/extensions/Particle3D/PU/CCPURibbonTrailRender.h b/extensions/Particle3D/PU/CCPURibbonTrailRender.h index 54ac52539b..ec3bb38705 100644 --- a/extensions/Particle3D/PU/CCPURibbonTrailRender.h +++ b/extensions/Particle3D/PU/CCPURibbonTrailRender.h @@ -83,7 +83,7 @@ public: static const Vec4 DEFAULT_INITIAL_COLOUR; static const Vec4 DEFAULT_COLOUR_CHANGE; - static PURibbonTrailRender* create(const std::string& texFile = ""); + static PURibbonTrailRender* create(std::string_view texFile = ""); virtual void notifyRescaled(const Vec3& scale) override; virtual void prepare() override; diff --git a/extensions/Particle3D/PU/CCPUScriptCompiler.cpp b/extensions/Particle3D/PU/CCPUScriptCompiler.cpp index c4b55f4abb..9b31dc5fc5 100644 --- a/extensions/Particle3D/PU/CCPUScriptCompiler.cpp +++ b/extensions/Particle3D/PU/CCPUScriptCompiler.cpp @@ -67,19 +67,20 @@ std::string PUObjectAbstractNode::getValue() const return cls; } -void PUObjectAbstractNode::addVariable(const std::string& inName) +void PUObjectAbstractNode::addVariable(std::string_view inName) { _env.emplace(inName, ""); } -void PUObjectAbstractNode::setVariable(const std::string& inName, const std::string& value) +void PUObjectAbstractNode::setVariable(std::string_view inName, std::string_view value) { - _env[inName] = value; + // _env[inName] = value; + hlookup::set_item(_env, inName, value); } -std::pair PUObjectAbstractNode::getVariable(const std::string& inName) const +std::pair PUObjectAbstractNode::getVariable(std::string_view inName) const { - std::unordered_map::const_iterator i = _env.find(inName); + auto i = _env.find(inName); if (i != _env.end()) return std::make_pair(true, i->second); @@ -94,7 +95,7 @@ std::pair PUObjectAbstractNode::getVariable(const std::string return std::make_pair(false, ""); } -const std::unordered_map& PUObjectAbstractNode::getVariables() const +const hlookup::string_map& PUObjectAbstractNode::getVariables() const { return _env; } @@ -187,15 +188,16 @@ PUScriptCompiler::~PUScriptCompiler() _compiledScripts.clear(); } -bool PUScriptCompiler::compile(const PUConcreteNodeList& nodes, const std::string& file) +hlookup::string_map::iterator PUScriptCompiler::compile(const PUConcreteNodeList& nodes, + std::string_view file) { if (nodes.empty()) - return false; + return _compiledScripts.end(); PUAbstractNodeList aNodes; convertToAST(nodes, aNodes); - _compiledScripts[file] = aNodes; + return hlookup::set_item(_compiledScripts, file, aNodes); // _compiledScripts[file] = aNodes; // for(PUAbstractNodeList::iterator i = aNodes.begin(); i != aNodes.end(); ++i) //{ // PUScriptTranslator *translator = PUTranslateManager::Instance()->getTranslator(*i); @@ -212,10 +214,10 @@ bool PUScriptCompiler::compile(const PUConcreteNodeList& nodes, const std::strin // for (auto iter : aNodes){ // delete iter; // } - return true; + // return true; } -const PUAbstractNodeList* PUScriptCompiler::compile(const std::string& file, bool& isFirstCompile) +const PUAbstractNodeList* PUScriptCompiler::compile(std::string_view file, bool& isFirstCompile) { auto iter = _compiledScripts.find(file); if (iter != _compiledScripts.end()) @@ -231,7 +233,7 @@ const PUAbstractNodeList* PUScriptCompiler::compile(const std::string& file, boo PUConcreteNodeList creteNodeList; lexer.openLexer(data, file, tokenList); parser.parse(creteNodeList, tokenList); - bool state = compile(creteNodeList, file); + auto it = compile(creteNodeList, file); for (auto iter1 : creteNodeList) { @@ -244,9 +246,9 @@ const PUAbstractNodeList* PUScriptCompiler::compile(const std::string& file, boo } isFirstCompile = true; - if (state) + if (it != _compiledScripts.end()) { - return &_compiledScripts[file]; + return &it->second; } return nullptr; } diff --git a/extensions/Particle3D/PU/CCPUScriptCompiler.h b/extensions/Particle3D/PU/CCPUScriptCompiler.h index 4834595f59..e5bc4cc7b8 100644 --- a/extensions/Particle3D/PU/CCPUScriptCompiler.h +++ b/extensions/Particle3D/PU/CCPUScriptCompiler.h @@ -72,7 +72,7 @@ public: class CC_EX_DLL PUObjectAbstractNode : public PUAbstractNode { private: - std::unordered_map _env; + hlookup::string_map _env; public: std::string name, cls; @@ -88,10 +88,10 @@ public: PUAbstractNode* clone() const; std::string getValue() const; - void addVariable(const std::string& name); - void setVariable(const std::string& name, const std::string& value); - std::pair getVariable(const std::string& name) const; - const std::unordered_map& getVariables() const; + void addVariable(std::string_view name); + void setVariable(std::string_view name, std::string_view value); + std::pair getVariable(std::string_view name) const; + const hlookup::string_map& getVariables() const; }; /** This abstract node represents a script property */ @@ -130,9 +130,9 @@ class CC_EX_DLL PUScriptCompiler { private: - bool compile(const PUConcreteNodeList& nodes, const std::string& file); + hlookup::string_map::iterator compile(const PUConcreteNodeList& nodes, std::string_view file); // is it excluded?// - bool isNameExcluded(const std::string& cls, PUAbstractNode* parent); + bool isNameExcluded(std::string_view cls, PUAbstractNode* parent); public: typedef std::unordered_map IdMap; @@ -141,7 +141,7 @@ public: void setParticleSystem3D(PUParticleSystem3D* pu); - const PUAbstractNodeList* compile(const std::string& file, bool& isFirstCompile); + const PUAbstractNodeList* compile(std::string_view file, bool& isFirstCompile); void convertToAST(const PUConcreteNodeList& nodes, PUAbstractNodeList& aNodes); @@ -155,7 +155,7 @@ private: void visit(PUConcreteNode* node); private: - std::unordered_map _compiledScripts; + hlookup::string_map _compiledScripts; PUAbstractNode* _current; PUAbstractNodeList* _nodes; PUParticleSystem3D* _PUParticleSystem3D; diff --git a/extensions/Particle3D/PU/CCPUScriptLexer.cpp b/extensions/Particle3D/PU/CCPUScriptLexer.cpp index a8720fca0f..75aca400f7 100644 --- a/extensions/Particle3D/PU/CCPUScriptLexer.cpp +++ b/extensions/Particle3D/PU/CCPUScriptLexer.cpp @@ -31,7 +31,7 @@ PUScriptLexer::PUScriptLexer() {} PUScriptLexer::~PUScriptLexer() {} -void PUScriptLexer::openLexer(const std::string& str, const std::string& source, PUScriptTokenList& tokens) +void PUScriptLexer::openLexer(std::string_view str, std::string_view source, PUScriptTokenList& tokens) { enum { @@ -55,7 +55,7 @@ void PUScriptLexer::openLexer(const std::string& str, const std::string& source, // // Iterate over the input - std::string::const_iterator i = str.begin(), end = str.end(); + std::string_view::const_iterator i = str.begin(), end = str.end(); while (i != end) { lastc = c; @@ -233,7 +233,7 @@ void PUScriptLexer::openLexer(const std::string& str, const std::string& source, } } -void PUScriptLexer::setToken(const std::string& lexeme, int line, const std::string& source, PUScriptTokenList* tokens) +void PUScriptLexer::setToken(std::string_view lexeme, int line, std::string_view source, PUScriptTokenList* tokens) { const char openBracket = '{', closeBracket = '}', colon = ':', quote = '\"', var = '$'; diff --git a/extensions/Particle3D/PU/CCPUScriptLexer.h b/extensions/Particle3D/PU/CCPUScriptLexer.h index e5133cf323..907ef09a7b 100644 --- a/extensions/Particle3D/PU/CCPUScriptLexer.h +++ b/extensions/Particle3D/PU/CCPUScriptLexer.h @@ -67,12 +67,12 @@ public: PUScriptLexer(); ~PUScriptLexer(); - void openLexer(const std::string& str, const std::string& source, PUScriptTokenList& tokenList); + void openLexer(std::string_view str, std::string_view source, PUScriptTokenList& tokenList); /** Tokenizes the given input and returns the list of tokens found */ // tokenize(const std::string &str, const std::string &source); private: // Private utility operations - void setToken(const std::string& lexeme, int line, const std::string& source, PUScriptTokenList* tokens); + void setToken(std::string_view lexeme, int line, std::string_view source, PUScriptTokenList* tokens); bool isWhitespace(char c) const; bool isNewline(char c) const; }; diff --git a/extensions/Particle3D/PU/CCPUScriptTranslator.cpp b/extensions/Particle3D/PU/CCPUScriptTranslator.cpp index a73539e24a..3eeb334127 100644 --- a/extensions/Particle3D/PU/CCPUScriptTranslator.cpp +++ b/extensions/Particle3D/PU/CCPUScriptTranslator.cpp @@ -517,7 +517,7 @@ bool PUScriptTranslator::getQuaternion(PUAbstractNodeList::const_iterator i, //------------------------------------------------------------------------- bool PUScriptTranslator::passValidateProperty(PUScriptCompiler* compiler, PUPropertyAbstractNode* prop, - const std::string& token2, + std::string_view token2, ValidationType validationType) { if (!passValidatePropertyNoValues(compiler, prop, token2)) @@ -594,7 +594,7 @@ bool PUScriptTranslator::passValidateProperty(PUScriptCompiler* compiler, //------------------------------------------------------------------------- bool PUScriptTranslator::passValidatePropertyNoValues(PUScriptCompiler* /*compiler*/, PUPropertyAbstractNode* prop, - const std::string& /*token2*/) + std::string_view /*token2*/) { if (prop->values.empty()) { @@ -607,7 +607,7 @@ bool PUScriptTranslator::passValidatePropertyNoValues(PUScriptCompiler* /*compil //------------------------------------------------------------------------- bool PUScriptTranslator::passValidatePropertyNumberOfValues(PUScriptCompiler* /*compiler*/, PUPropertyAbstractNode* prop, - const std::string& /*token2*/, + std::string_view /*token2*/, unsigned short numberOfValues) { if (prop->values.size() > numberOfValues) @@ -619,7 +619,7 @@ bool PUScriptTranslator::passValidatePropertyNumberOfValues(PUScriptCompiler* /* //------------------------------------------------------------------------- bool PUScriptTranslator::passValidatePropertyNumberOfValuesRange(PUScriptCompiler* /*compiler*/, PUPropertyAbstractNode* prop, - const std::string& /*token2*/, + std::string_view /*token2*/, unsigned short minNumberOfValues, unsigned short maxNumberOfValues) { diff --git a/extensions/Particle3D/PU/CCPUScriptTranslator.h b/extensions/Particle3D/PU/CCPUScriptTranslator.h index 0e9af6d757..c57b7664a1 100644 --- a/extensions/Particle3D/PU/CCPUScriptTranslator.h +++ b/extensions/Particle3D/PU/CCPUScriptTranslator.h @@ -679,27 +679,27 @@ public: */ bool passValidateProperty(PUScriptCompiler* compiler, PUPropertyAbstractNode* prop, - const std::string& token, + std::string_view token, ValidationType validationType); /** Validate whether a property has values. */ bool passValidatePropertyNoValues(PUScriptCompiler* compiler, PUPropertyAbstractNode* prop, - const std::string& token); + std::string_view token); /** Validate whether the number of values is correct. */ bool passValidatePropertyNumberOfValues(PUScriptCompiler* compiler, PUPropertyAbstractNode* prop, - const std::string& token, + std::string_view token, unsigned short numberOfValues); /** Validate whether the number of values is between a range. */ bool passValidatePropertyNumberOfValuesRange(PUScriptCompiler* compiler, PUPropertyAbstractNode* prop, - const std::string& token, + std::string_view token, unsigned short minNumberOfValues, unsigned short maxNumberOfValues); diff --git a/extensions/Particle3D/PU/CCPUSlaveEmitter.cpp b/extensions/Particle3D/PU/CCPUSlaveEmitter.cpp index 904cab168e..e5880b2f9c 100644 --- a/extensions/Particle3D/PU/CCPUSlaveEmitter.cpp +++ b/extensions/Particle3D/PU/CCPUSlaveEmitter.cpp @@ -39,22 +39,22 @@ PUSlaveEmitter::PUSlaveEmitter() , _masterEmitterNameSet(false) {} //----------------------------------------------------------------------- -const std::string& PUSlaveEmitter::getMasterTechniqueName() const +std::string_view PUSlaveEmitter::getMasterTechniqueName() const { return _masterTechniqueName; } //----------------------------------------------------------------------- -void PUSlaveEmitter::setMasterTechniqueName(const std::string& masterTechniqueName) +void PUSlaveEmitter::setMasterTechniqueName(std::string_view masterTechniqueName) { _masterTechniqueName = masterTechniqueName; } //----------------------------------------------------------------------- -const std::string& PUSlaveEmitter::getMasterEmitterName() const +std::string_view PUSlaveEmitter::getMasterEmitterName() const { return _masterEmitterName; } //----------------------------------------------------------------------- -void PUSlaveEmitter::setMasterEmitterName(const std::string& masterEmitterName) +void PUSlaveEmitter::setMasterEmitterName(std::string_view masterEmitterName) { _masterEmitterName = masterEmitterName; _masterEmitterNameSet = true; diff --git a/extensions/Particle3D/PU/CCPUSlaveEmitter.h b/extensions/Particle3D/PU/CCPUSlaveEmitter.h index 32ab26c3c0..c260cf59e4 100644 --- a/extensions/Particle3D/PU/CCPUSlaveEmitter.h +++ b/extensions/Particle3D/PU/CCPUSlaveEmitter.h @@ -39,15 +39,15 @@ public: /** */ - const std::string& getMasterTechniqueName() const; + std::string_view getMasterTechniqueName() const; /** */ - void setMasterTechniqueName(const std::string& masterTechniqueName); + void setMasterTechniqueName(std::string_view masterTechniqueName); /** */ - const std::string& getMasterEmitterName() const; + std::string_view getMasterEmitterName() const; /** See ParticleEmitter. */ @@ -79,7 +79,7 @@ public: /** */ - void setMasterEmitterName(const std::string& masterEmitterName); + void setMasterEmitterName(std::string_view masterEmitterName); virtual PUSlaveEmitter* clone() override; virtual void copyAttributesTo(PUEmitter* emitter) override; diff --git a/extensions/Particle3D/PU/CCPUVertexEmitter.cpp b/extensions/Particle3D/PU/CCPUVertexEmitter.cpp index c7fcbb0276..ffbf9934d3 100644 --- a/extensions/Particle3D/PU/CCPUVertexEmitter.cpp +++ b/extensions/Particle3D/PU/CCPUVertexEmitter.cpp @@ -84,12 +84,12 @@ NS_CC_BEGIN // mStep = step; // } ////----------------------------------------------------------------------- -// const std::string& Particle3DVertexEmitter::getMeshName() const +// std::string_view Particle3DVertexEmitter::getMeshName() const //{ // return mMeshName; // } ////----------------------------------------------------------------------- -// void Particle3DVertexEmitter::setMeshName(const std::string& meshName) +// void Particle3DVertexEmitter::setMeshName(std::string_view meshName) //{ // _setDefaults(); // Triggers loading the new mesh // mMeshName = meshName; diff --git a/extensions/Particle3D/PU/CCPUVertexEmitter.h b/extensions/Particle3D/PU/CCPUVertexEmitter.h index 7db52020dd..b808d43acd 100644 --- a/extensions/Particle3D/PU/CCPUVertexEmitter.h +++ b/extensions/Particle3D/PU/CCPUVertexEmitter.h @@ -148,7 +148,7 @@ NS_CC_BEGIN // // /** // */ -// const std::string& getMeshName() const; +// std::string_view getMeshName() const; // // /** // */ @@ -156,7 +156,7 @@ NS_CC_BEGIN // // /** // */ -// void setMeshName(const std::string& meshName); +// void setMeshName(std::string_view meshName); // // /** // */ diff --git a/extensions/assets-manager/AssetsManager.cpp b/extensions/assets-manager/AssetsManager.cpp index 2566e7b0c2..8b9b571df1 100644 --- a/extensions/assets-manager/AssetsManager.cpp +++ b/extensions/assets-manager/AssetsManager.cpp @@ -182,7 +182,7 @@ AssetsManager::AssetsManager(const char* packageUrl /* =nullptr */, checkStoragePath(); // convert downloader error code to AssetsManager::ErrorCode _downloader->onTaskError = [this](const DownloadTask& /*task*/, int errorCode, int /*errorCodeInternal*/, - const std::string& /*errorStr*/) { + std::string_view /*errorStr*/) { _isDownloading = false; if (nullptr == _delegate) @@ -278,10 +278,10 @@ void AssetsManager::checkStoragePath() } // Multiple key names -static std::string keyWithHash(const char* prefix, const std::string& url) +static std::string keyWithHash(const char* prefix, std::string_view url) { char buf[256]; - sprintf(buf, "%s%zd", prefix, std::hash()(url)); + sprintf(buf, "%s%zd", prefix, std::hash()(url)); return buf; } @@ -565,9 +565,9 @@ void AssetsManager::setVersionFileUrl(const char* versionFileUrl) _versionFileUrl = versionFileUrl; } -string AssetsManager::getVersion() +std::string_view AssetsManager::getVersion() { - return UserDefault::getInstance()->getStringForKey(keyOfVersion().c_str()); + return UserDefault::getInstance()->getStringForKey(keyOfVersion().data()); } void AssetsManager::deleteVersion() diff --git a/extensions/assets-manager/AssetsManager.h b/extensions/assets-manager/AssetsManager.h index 34a1fb8125..b6587157a1 100644 --- a/extensions/assets-manager/AssetsManager.h +++ b/extensions/assets-manager/AssetsManager.h @@ -137,7 +137,7 @@ public: /* @brief Gets current version code. */ - std::string getVersion(); + std::string_view getVersion(); /* @brief Deletes recorded version code. */ diff --git a/extensions/assets-manager/AssetsManagerEx.cpp b/extensions/assets-manager/AssetsManagerEx.cpp index 10f555c1ce..8636f4523e 100644 --- a/extensions/assets-manager/AssetsManagerEx.cpp +++ b/extensions/assets-manager/AssetsManagerEx.cpp @@ -168,8 +168,7 @@ int AssetManagerEx_error_file_func(voidpf opaque, voidpf stream) // Implementation of AssetsManagerEx -AssetsManagerEx::AssetsManagerEx(const std::string& manifestUrl, const std::string& storagePath) - : _manifestUrl(manifestUrl) +AssetsManagerEx::AssetsManagerEx(std::string_view manifestUrl, std::string_view storagePath) : _manifestUrl(manifestUrl) { // Init variables _eventDispatcher = Director::getInstance()->getEventDispatcher(); @@ -208,14 +207,14 @@ AssetsManagerEx::~AssetsManagerEx() CC_SAFE_RELEASE(_remoteManifest); } -AssetsManagerEx* AssetsManagerEx::create(const std::string& manifestUrl, const std::string& storagePath) +AssetsManagerEx* AssetsManagerEx::create(std::string_view manifestUrl, std::string_view storagePath) { AssetsManagerEx* ret = new AssetsManagerEx(manifestUrl, storagePath); ret->autorelease(); return ret; } -void AssetsManagerEx::initManifests(const std::string& manifestUrl) +void AssetsManagerEx::initManifests(std::string_view manifestUrl) { _inited = true; // Init and load local manifest @@ -260,7 +259,7 @@ void AssetsManagerEx::prepareLocalManifest() _localManifest->prependSearchPaths(); } -void AssetsManagerEx::loadLocalManifest(const std::string& /*manifestUrl*/) +void AssetsManagerEx::loadLocalManifest(std::string_view /*manifestUrl*/) { Manifest* cachedManifest = nullptr; // Find the cached manifest file @@ -329,7 +328,7 @@ void AssetsManagerEx::loadLocalManifest(const std::string& /*manifestUrl*/) } } -std::string AssetsManagerEx::basename(const std::string& path) const +std::string_view AssetsManagerEx::basename(std::string_view path) const { size_t found = path.find_last_of("/\\"); @@ -343,7 +342,7 @@ std::string AssetsManagerEx::basename(const std::string& path) const } } -std::string AssetsManagerEx::get(const std::string& key) const +std::string AssetsManagerEx::get(std::string_view key) const { auto it = _assets->find(key); if (it != _assets->cend()) @@ -364,12 +363,12 @@ const Manifest* AssetsManagerEx::getRemoteManifest() const return _remoteManifest; } -const std::string& AssetsManagerEx::getStoragePath() const +std::string_view AssetsManagerEx::getStoragePath() const { return _storagePath; } -void AssetsManagerEx::setStoragePath(const std::string& storagePath) +void AssetsManagerEx::setStoragePath(std::string_view storagePath) { _storagePath = storagePath; adjustPath(_storagePath); @@ -389,16 +388,16 @@ void AssetsManagerEx::adjustPath(std::string& path) } } -bool AssetsManagerEx::decompress(const std::string& zip) +bool AssetsManagerEx::decompress(std::string_view zip) { // Find root path for zip file size_t pos = zip.find_last_of("/\\"); if (pos == std::string::npos) { - CCLOG("AssetsManagerEx : no root path specified for zip file %s\n", zip.c_str()); + CCLOG("AssetsManagerEx : no root path specified for zip file %s\n", zip.data()); return false; } - const std::string rootPath = zip.substr(0, pos + 1); + const std::string_view rootPath = zip.substr(0, pos + 1); zlib_filefunc_def_s zipFunctionOverrides; fillZipFunctionOverrides(zipFunctionOverrides); @@ -409,10 +408,10 @@ bool AssetsManagerEx::decompress(const std::string& zip) zipFunctionOverrides.opaque = &zipFileInfo; // Open the zip file - unzFile zipfile = unzOpen2(zip.c_str(), &zipFunctionOverrides); + unzFile zipfile = unzOpen2(zip.data(), &zipFunctionOverrides); if (!zipfile) { - CCLOG("AssetsManagerEx : can not open downloaded zip file %s\n", zip.c_str()); + CCLOG("AssetsManagerEx : can not open downloaded zip file %s\n", zip.data()); return false; } @@ -420,7 +419,7 @@ bool AssetsManagerEx::decompress(const std::string& zip) unz_global_info global_info; if (unzGetGlobalInfo(zipfile, &global_info) != UNZ_OK) { - CCLOG("AssetsManagerEx : can not read file global info of %s\n", zip.c_str()); + CCLOG("AssetsManagerEx : can not read file global info of %s\n", zip.data()); unzClose(zipfile); return false; } @@ -440,7 +439,8 @@ bool AssetsManagerEx::decompress(const std::string& zip) unzClose(zipfile); return false; } - const std::string fullPath = rootPath + fileName; + std::string fullPath{rootPath}; + fullPath += fileName; // Check if this entry is a directory or a file. const size_t filenameLength = strlen(fileName); @@ -459,7 +459,7 @@ bool AssetsManagerEx::decompress(const std::string& zip) else { // Create all directories in advance to avoid issue - std::string dir = basename(fullPath); + std::string_view dir = basename(fullPath); if (!_fileUtils->isDirectoryExist(dir)) { if (!_fileUtils->createDirectory(dir)) @@ -531,7 +531,7 @@ bool AssetsManagerEx::decompress(const std::string& zip) return true; } -void AssetsManagerEx::decompressDownloadedZip(const std::string& customId, const std::string& storagePath) +void AssetsManagerEx::decompressDownloadedZip(std::string_view customId, std::string_view storagePath) { struct AsyncData { @@ -573,8 +573,8 @@ void AssetsManagerEx::decompressDownloadedZip(const std::string& customId, const } void AssetsManagerEx::dispatchUpdateEvent(EventAssetsManagerEx::EventCode code, - const std::string& assetId /* = ""*/, - const std::string& message /* = ""*/, + std::string_view assetId /* = ""*/, + std::string_view message /* = ""*/, int curle_code /* = CURLE_OK*/, int curlm_code /* = CURLM_OK*/) { @@ -619,7 +619,7 @@ void AssetsManagerEx::downloadVersion() if (_updateState > State::PREDOWNLOAD_VERSION) return; - std::string versionUrl = _localManifest->getVersionFileUrl(); + std::string_view versionUrl = _localManifest->getVersionFileUrl(); if (!versionUrl.empty()) { @@ -786,7 +786,7 @@ void AssetsManagerEx::startUpdate() _tempManifest = _remoteManifest; // Check difference between local manifest and remote manifest - std::unordered_map diff_map = _localManifest->genDiff(_remoteManifest); + hlookup::string_map diff_map = _localManifest->genDiff(_remoteManifest); if (diff_map.empty()) { updateSucceed(); @@ -794,7 +794,7 @@ void AssetsManagerEx::startUpdate() else { // Generate download units for all assets that need to be updated or added - std::string packageUrl = _remoteManifest->getPackageUrl(); + std::string_view packageUrl = _remoteManifest->getPackageUrl(); // Save current download manifest information for resuming _tempManifest->saveToFile(_tempManifestPath); // Preprocessing local files in previous version and creating download folders @@ -803,10 +803,11 @@ void AssetsManagerEx::startUpdate() Manifest::AssetDiff diff = it->second; if (diff.type != Manifest::DiffType::DELETED) { - std::string path = diff.asset.path; + const std::string& path = diff.asset.path; DownloadUnit unit; - unit.customId = it->first; - unit.srcUrl = packageUrl + path; + unit.customId = it->first; + unit.srcUrl = packageUrl; + unit.srcUrl += path; unit.storagePath = _tempStoragePath + path; unit.size = diff.asset.size; _downloadUnits.emplace(unit.customId, unit); @@ -1034,8 +1035,8 @@ void AssetsManagerEx::downloadFailedAssets() updateAssets(_failedUnits); } -void AssetsManagerEx::fileError(const std::string& identifier, - const std::string& errorStr, +void AssetsManagerEx::fileError(std::string_view identifier, + std::string_view errorStr, int errorCode, int errorCodeInternal) { @@ -1056,7 +1057,7 @@ void AssetsManagerEx::fileError(const std::string& identifier, queueDowload(); } -void AssetsManagerEx::fileSuccess(const std::string& customId, const std::string& storagePath) +void AssetsManagerEx::fileSuccess(std::string_view customId, std::string_view storagePath) { // Set download state to SUCCESSED _tempManifest->setAssetDownloadState(customId, Manifest::DownloadState::SUCCESSED); @@ -1089,7 +1090,7 @@ void AssetsManagerEx::fileSuccess(const std::string& customId, const std::string void AssetsManagerEx::onError(const network::DownloadTask& task, int errorCode, int errorCodeInternal, - const std::string& errorStr) + std::string_view errorStr) { // Skip version error occurred if (task.identifier == VERSION_ID) @@ -1110,10 +1111,7 @@ void AssetsManagerEx::onError(const network::DownloadTask& task, } } -void AssetsManagerEx::onProgress(double total, - double downloaded, - const std::string& /*url*/, - const std::string& customId) +void AssetsManagerEx::onProgress(double total, double downloaded, std::string_view /*url*/, std::string_view customId) { if (customId == VERSION_ID || customId == MANIFEST_ID) { @@ -1170,9 +1168,7 @@ void AssetsManagerEx::onProgress(double total, } } -void AssetsManagerEx::onSuccess(const std::string& /*srcUrl*/, - const std::string& storagePath, - const std::string& customId) +void AssetsManagerEx::onSuccess(std::string_view /*srcUrl*/, std::string_view storagePath, std::string_view customId) { if (customId == VERSION_ID) { diff --git a/extensions/assets-manager/AssetsManagerEx.h b/extensions/assets-manager/AssetsManagerEx.h index 7180323d2d..7a77db5b44 100644 --- a/extensions/assets-manager/AssetsManagerEx.h +++ b/extensions/assets-manager/AssetsManagerEx.h @@ -77,7 +77,7 @@ public: @warning The cached manifest in your storage path have higher priority and will be searched first, only if it doesn't exist, AssetsManagerEx will use the given manifestUrl. */ - static AssetsManagerEx* create(const std::string& manifestUrl, const std::string& storagePath); + static AssetsManagerEx* create(std::string_view manifestUrl, std::string_view storagePath); /** @brief Check out if there is a new version of manifest. * You may use this method before updating, then let user determine whether @@ -99,7 +99,7 @@ public: /** @brief Gets storage path. */ - const std::string& getStoragePath() const; + std::string_view getStoragePath() const; /** @brief Function for retrieving the local manifest object */ @@ -120,8 +120,7 @@ public: /** @brief Set the handle function for comparing manifests versions * @param handle The compare function */ - void setVersionCompareHandle( - const std::function& handle) + void setVersionCompareHandle(const std::function& handle) { _versionCompareHandle = handle; }; @@ -130,37 +129,37 @@ public: * verification * @param callback The verify callback function */ - void setVerifyCallback(const std::function& callback) + void setVerifyCallback(const std::function& callback) { _verifyCallback = callback; }; CC_CONSTRUCTOR_ACCESS : - AssetsManagerEx(const std::string& manifestUrl, const std::string& storagePath); + AssetsManagerEx(std::string_view manifestUrl, std::string_view storagePath); virtual ~AssetsManagerEx(); protected: - std::string basename(const std::string& path) const; + std::string_view basename(std::string_view path) const; - std::string get(const std::string& key) const; + std::string get(std::string_view key) const; - void initManifests(const std::string& manifestUrl); + void initManifests(std::string_view manifestUrl); - void loadLocalManifest(const std::string& manifestUrl); + void loadLocalManifest(std::string_view manifestUrl); void prepareLocalManifest(); - void setStoragePath(const std::string& storagePath); + void setStoragePath(std::string_view storagePath); void adjustPath(std::string& path); void dispatchUpdateEvent(EventAssetsManagerEx::EventCode code, - const std::string& message = "", - const std::string& assetId = "", - int curle_code = 0, - int curlm_code = 0); + std::string_view message = "", + std::string_view assetId = "", + int curle_code = 0, + int curlm_code = 0); void downloadVersion(); void parseVersion(); @@ -168,8 +167,8 @@ protected: void parseManifest(); void startUpdate(); void updateSucceed(); - bool decompress(const std::string& filename); - void decompressDownloadedZip(const std::string& customId, const std::string& storagePath); + bool decompress(std::string_view filename); + void decompressDownloadedZip(std::string_view customId, std::string_view storagePath); /** @brief Update a list of assets under the current AssetsManagerEx context */ @@ -187,12 +186,12 @@ protected: */ void queueDowload(); - void fileError(const std::string& identifier, - const std::string& errorStr, + void fileError(std::string_view identifier, + std::string_view errorStr, int errorCode = 0, int errorCodeInternal = 0); - void fileSuccess(const std::string& customId, const std::string& storagePath); + void fileSuccess(std::string_view customId, std::string_view storagePath); /** @brief Call back function for error handling, the error will then be reported to user's listener registed in addUpdateEventListener @@ -204,7 +203,7 @@ protected: virtual void onError(const network::DownloadTask& task, int errorCode, int errorCodeInternal, - const std::string& errorStr); + std::string_view errorStr); /** @brief Call back function for recording downloading percent of the current asset, the progression will then be reported to user's listener registed in addUpdateProgressEventListener @@ -216,7 +215,7 @@ protected: * @js NA * @lua NA */ - virtual void onProgress(double total, double downloaded, const std::string& url, const std::string& customId); + virtual void onProgress(double total, double downloaded, std::string_view url, std::string_view customId); /** @brief Call back function for success of the current asset the success event will then be send to user's listener registed in addUpdateEventListener @@ -226,7 +225,7 @@ protected: * @js NA * @lua NA */ - virtual void onSuccess(const std::string& srcUrl, const std::string& storagePath, const std::string& customId); + virtual void onSuccess(std::string_view srcUrl, std::string_view storagePath, std::string_view customId); private: void batchDownload(); @@ -250,7 +249,7 @@ private: std::shared_ptr _downloader; //! The reference to the local assets - const std::unordered_map* _assets = nullptr; + const hlookup::string_map* _assets = nullptr; //! The path to store successfully downloaded version. std::string _storagePath; @@ -320,7 +319,7 @@ private: double _totalSize; //! Downloaded size for each file - std::unordered_map _downloadedSize; + hlookup::string_map _downloadedSize; //! Total number of assets to download int _totalToDownload = 0; @@ -330,10 +329,10 @@ private: float _nextSavePoint = 0.f; //! Handle function to compare versions between different manifests - std::function _versionCompareHandle = nullptr; + std::function _versionCompareHandle = nullptr; //! Callback function to verify the downloaded assets - std::function _verifyCallback = nullptr; + std::function _verifyCallback = nullptr; //! Marker for whether the assets manager is inited bool _inited = false; diff --git a/extensions/assets-manager/CCEventAssetsManagerEx.cpp b/extensions/assets-manager/CCEventAssetsManagerEx.cpp index 183daae660..e14a7eed30 100644 --- a/extensions/assets-manager/CCEventAssetsManagerEx.cpp +++ b/extensions/assets-manager/CCEventAssetsManagerEx.cpp @@ -30,13 +30,13 @@ NS_CC_EXT_BEGIN -EventAssetsManagerEx::EventAssetsManagerEx(const std::string& eventName, +EventAssetsManagerEx::EventAssetsManagerEx(std::string_view eventName, cocos2d::extension::AssetsManagerEx* manager, const EventCode& code, float percent /* = 0 */, float percentByFile /* = 0*/, - const std::string& assetId /* = "" */, - const std::string& message /* = "" */, + std::string_view assetId /* = "" */, + std::string_view message /* = "" */, int curle_code /* = CURLE_OK*/, int curlm_code /* = CURLM_OK*/) : EventCustom(eventName) diff --git a/extensions/assets-manager/CCEventAssetsManagerEx.h b/extensions/assets-manager/CCEventAssetsManagerEx.h index 0d261ac5b9..cf205840bf 100644 --- a/extensions/assets-manager/CCEventAssetsManagerEx.h +++ b/extensions/assets-manager/CCEventAssetsManagerEx.h @@ -74,13 +74,13 @@ public: CC_CONSTRUCTOR_ACCESS : /** Constructor */ - EventAssetsManagerEx(const std::string& eventName, + EventAssetsManagerEx(std::string_view eventName, cocos2d::extension::AssetsManagerEx* manager, const EventCode& code, float percent = 0, float percentByFile = 0, - const std::string& assetId = "", - const std::string& message = "", + std::string_view assetId = "", + std::string_view message = "", int curle_code = 0, int curlm_code = 0); diff --git a/extensions/assets-manager/Manifest.cpp b/extensions/assets-manager/Manifest.cpp index 43dc418e19..4e64bc8eae 100644 --- a/extensions/assets-manager/Manifest.cpp +++ b/extensions/assets-manager/Manifest.cpp @@ -50,16 +50,16 @@ NS_CC_EXT_BEGIN -static int cmpVersion(const std::string& v1, const std::string& v2) +static int cmpVersion(std::string_view v1, std::string_view v2) { int i; int oct_v1[4] = {0}, oct_v2[4] = {0}; - int filled1 = std::sscanf(v1.c_str(), "%d.%d.%d.%d", &oct_v1[0], &oct_v1[1], &oct_v1[2], &oct_v1[3]); - int filled2 = std::sscanf(v2.c_str(), "%d.%d.%d.%d", &oct_v2[0], &oct_v2[1], &oct_v2[2], &oct_v2[3]); + int filled1 = std::sscanf(v1.data(), "%d.%d.%d.%d", &oct_v1[0], &oct_v1[1], &oct_v1[2], &oct_v1[3]); + int filled2 = std::sscanf(v2.data(), "%d.%d.%d.%d", &oct_v2[0], &oct_v2[1], &oct_v2[2], &oct_v2[3]); if (filled1 == 0 || filled2 == 0) { - return strcmp(v1.c_str(), v2.c_str()); + return v1 != v2; // strcmp(v1.data(), v2.data()); } for (i = 0; i < 4; i++) { @@ -71,7 +71,7 @@ static int cmpVersion(const std::string& v1, const std::string& v2) return 0; } -Manifest::Manifest(const std::string& manifestUrl /* = ""*/) +Manifest::Manifest(std::string_view manifestUrl /* = ""*/) : _versionLoaded(false) , _loaded(false) , _manifestRoot("") @@ -86,7 +86,7 @@ Manifest::Manifest(const std::string& manifestUrl /* = ""*/) parse(manifestUrl); } -void Manifest::loadJson(const std::string& url) +void Manifest::loadJson(std::string_view url) { clear(); std::string content; @@ -97,7 +97,7 @@ void Manifest::loadJson(const std::string& url) if (content.empty()) { - CCLOG("Fail to retrieve local file content: %s\n", url.c_str()); + CCLOG("Fail to retrieve local file content: %s\n", url.data()); } else { @@ -116,7 +116,7 @@ void Manifest::loadJson(const std::string& url) } } -void Manifest::parseVersion(const std::string& versionUrl) +void Manifest::parseVersion(std::string_view versionUrl) { loadJson(versionUrl); @@ -126,7 +126,7 @@ void Manifest::parseVersion(const std::string& versionUrl) } } -void Manifest::parse(const std::string& manifestUrl) +void Manifest::parse(std::string_view manifestUrl) { loadJson(manifestUrl); @@ -162,7 +162,7 @@ bool Manifest::versionEquals(const Manifest* b) const else { std::vector bGroups = b->getGroups(); - std::unordered_map bGroupVer = b->getGroupVerions(); + auto& bGroupVer = b->getGroupVerions(); // Check group size if (bGroups.size() != _groups.size()) return false; @@ -184,10 +184,10 @@ bool Manifest::versionEquals(const Manifest* b) const bool Manifest::versionGreater( const Manifest* b, - const std::function& handle) const + const std::function& handle) const { - std::string localVersion = getVersion(); - const std::string& bVersion = b->getVersion(); + std::string_view localVersion = getVersion(); + std::string_view bVersion = b->getVersion(); bool greater; if (handle) { @@ -200,16 +200,16 @@ bool Manifest::versionGreater( return greater; } -std::unordered_map Manifest::genDiff(const Manifest* b) const +hlookup::string_map Manifest::genDiff(const Manifest* b) const { - std::unordered_map diff_map; - const std::unordered_map& bAssets = b->getAssets(); + hlookup::string_map diff_map; + auto& bAssets = b->getAssets(); std::string key; Asset valueA; Asset valueB; - std::unordered_map::const_iterator valueIt, it; + hlookup::string_map::const_iterator valueIt, it; for (it = _assets.begin(); it != _assets.end(); ++it) { key = it->first; @@ -317,22 +317,22 @@ void Manifest::prependSearchPaths() } } -const std::string& Manifest::getPackageUrl() const +std::string_view Manifest::getPackageUrl() const { return _packageUrl; } -const std::string& Manifest::getManifestFileUrl() const +std::string_view Manifest::getManifestFileUrl() const { return _remoteManifestUrl; } -const std::string& Manifest::getVersionFileUrl() const +std::string_view Manifest::getVersionFileUrl() const { return _remoteVersionUrl; } -const std::string& Manifest::getVersion() const +std::string_view Manifest::getVersion() const { return _version; } @@ -342,22 +342,22 @@ const std::vector& Manifest::getGroups() const return _groups; } -const std::unordered_map& Manifest::getGroupVerions() const +const hlookup::string_map& Manifest::getGroupVerions() const { return _groupVer; } -const std::string& Manifest::getGroupVersion(const std::string& group) const +std::string_view Manifest::getGroupVersion(std::string_view group) const { return _groupVer.at(group); } -const std::unordered_map& Manifest::getAssets() const +const hlookup::string_map& Manifest::getAssets() const { return _assets; } -void Manifest::setAssetDownloadState(const std::string& key, const Manifest::DownloadState& state) +void Manifest::setAssetDownloadState(std::string_view key, const Manifest::DownloadState& state) { auto valueIt = _assets.find(key); if (valueIt != _assets.end()) @@ -372,9 +372,9 @@ void Manifest::setAssetDownloadState(const std::string& key, const Manifest::Dow rapidjson::Value& assets = _json[KEY_ASSETS]; if (assets.IsObject()) { - if (assets.HasMember(key.c_str())) + if (assets.HasMember(key.data())) { - rapidjson::Value& entry = assets[key.c_str()]; + rapidjson::Value& entry = assets[key.data()]; if (entry.HasMember(KEY_DOWNLOAD_STATE) && entry[KEY_DOWNLOAD_STATE].IsInt()) { entry[KEY_DOWNLOAD_STATE].SetInt((int)state); @@ -413,7 +413,7 @@ void Manifest::clear() } } -Manifest::Asset Manifest::parseAsset(const std::string& path, const rapidjson::Value& json) +Manifest::Asset Manifest::parseAsset(std::string_view path, const rapidjson::Value& json) { Asset asset; asset.path = path; @@ -553,7 +553,7 @@ void Manifest::loadManifest(const rapidjson::Document& json) _loaded = true; } -void Manifest::saveToFile(const std::string& filepath) +void Manifest::saveToFile(std::string_view filepath) { rapidjson::StringBuffer buffer; rapidjson::PrettyWriter writer(buffer); diff --git a/extensions/assets-manager/Manifest.h b/extensions/assets-manager/Manifest.h index 695cbe55c7..92edcb4dd2 100644 --- a/extensions/assets-manager/Manifest.h +++ b/extensions/assets-manager/Manifest.h @@ -56,7 +56,7 @@ struct ManifestAsset int downloadState; }; -typedef std::unordered_map DownloadUnits; +typedef hlookup::string_map DownloadUnits; class CC_EX_DLL Manifest : public Ref { @@ -99,19 +99,19 @@ public: /** @brief Gets remote package url. */ - const std::string& getPackageUrl() const; + std::string_view getPackageUrl() const; /** @brief Gets remote manifest file url. */ - const std::string& getManifestFileUrl() const; + std::string_view getManifestFileUrl() const; /** @brief Gets remote version file url. */ - const std::string& getVersionFileUrl() const; + std::string_view getVersionFileUrl() const; /** @brief Gets manifest version. */ - const std::string& getVersion() const; + std::string_view getVersion() const; /** @brief Get the search paths list related to the Manifest. */ @@ -121,22 +121,22 @@ protected: /** @brief Constructor for Manifest class * @param manifestUrl Url of the local manifest */ - Manifest(const std::string& manifestUrl = ""); + Manifest(std::string_view manifestUrl = ""); /** @brief Load the json file into local json object * @param url Url of the json file */ - void loadJson(const std::string& url); + void loadJson(std::string_view url); /** @brief Parse the version file information into this manifest * @param versionUrl Url of the local version file */ - void parseVersion(const std::string& versionUrl); + void parseVersion(std::string_view versionUrl); /** @brief Parse the manifest file information into this manifest * @param manifestUrl Url of the local manifest */ - void parse(const std::string& manifestUrl); + void parse(std::string_view manifestUrl); /** @brief Check whether the version of this manifest equals to another. * @param b The other manifest @@ -151,12 +151,12 @@ protected: */ bool versionGreater( const Manifest* b, - const std::function& handle) const; + const std::function& handle) const; /** @brief Generate difference between this Manifest and another. * @param b The other manifest */ - std::unordered_map genDiff(const Manifest* b) const; + hlookup::string_map genDiff(const Manifest* b) const; /** @brief Generate resuming download assets list * @param units The download units reference to be modified by the generation result @@ -171,9 +171,9 @@ protected: void loadManifest(const rapidjson::Document& json); - void saveToFile(const std::string& filepath); + void saveToFile(std::string_view filepath); - Asset parseAsset(const std::string& path, const rapidjson::Value& json); + Asset parseAsset(std::string_view path, const rapidjson::Value& json); void clear(); @@ -183,26 +183,26 @@ protected: /** @brief Gets all groups version. */ - const std::unordered_map& getGroupVerions() const; + const hlookup::string_map& getGroupVerions() const; /** @brief Gets version for the given group. * @param group Key of the requested group */ - const std::string& getGroupVersion(const std::string& group) const; + std::string_view getGroupVersion(std::string_view group) const; /** * @brief Gets assets. * @lua NA */ - const std::unordered_map& getAssets() const; + const hlookup::string_map& getAssets() const; /** @brief Set the download state for an asset * @param key Key of the asset to set * @param state The current download state of the asset */ - void setAssetDownloadState(const std::string& key, const DownloadState& state); + void setAssetDownloadState(std::string_view key, const DownloadState& state); - void setManifestRoot(const std::string& root) { _manifestRoot = root; }; + void setManifestRoot(std::string_view root) { _manifestRoot = root; }; private: //! Indicate whether the version informations have been fully loaded @@ -233,13 +233,13 @@ private: std::vector _groups; //! The versions of all local group [Optional] - std::unordered_map _groupVer; + hlookup::string_map _groupVer; //! The version of local engine std::string _engineVer; //! Full assets list - std::unordered_map _assets; + hlookup::string_map _assets; //! All search paths std::vector _searchPaths; diff --git a/extensions/cocostudio/ActionTimeline/CCActionTimeline.cpp b/extensions/cocostudio/ActionTimeline/CCActionTimeline.cpp index bf4dd8ac18..6edbb87073 100644 --- a/extensions/cocostudio/ActionTimeline/CCActionTimeline.cpp +++ b/extensions/cocostudio/ActionTimeline/CCActionTimeline.cpp @@ -319,12 +319,12 @@ void ActionTimeline::removeAnimationInfo(std::string animationName) _animationInfos.erase(animationName); } -bool ActionTimeline::IsAnimationInfoExists(const std::string& animationName) +bool ActionTimeline::IsAnimationInfoExists(std::string_view animationName) { return _animationInfos.find(animationName) != _animationInfos.end(); } -const AnimationInfo& ActionTimeline::getAnimationInfo(const std::string& animationName) +const AnimationInfo& ActionTimeline::getAnimationInfo(std::string_view animationName) { return _animationInfos.find(animationName)->second; } @@ -369,7 +369,7 @@ void ActionTimeline::emitFrameEvent(Frame* frame) } } -void ActionTimeline::addFrameEndCallFunc(int frameIndex, const std::string& funcKey, std::function func) +void ActionTimeline::addFrameEndCallFunc(int frameIndex, std::string_view funcKey, std::function func) { if (func != nullptr) { @@ -377,7 +377,7 @@ void ActionTimeline::addFrameEndCallFunc(int frameIndex, const std::string& func } } -void ActionTimeline::removeFrameEndCallFunc(int frameIndex, const std::string& funcKey) +void ActionTimeline::removeFrameEndCallFunc(int frameIndex, std::string_view funcKey) { auto endClipCallsIter = _frameEndCallFuncs.find(frameIndex); if (endClipCallsIter != _frameEndCallFuncs.end()) diff --git a/extensions/cocostudio/ActionTimeline/CCActionTimeline.h b/extensions/cocostudio/ActionTimeline/CCActionTimeline.h index 6437359ff4..5e9e1053c6 100644 --- a/extensions/cocostudio/ActionTimeline/CCActionTimeline.h +++ b/extensions/cocostudio/ActionTimeline/CCActionTimeline.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013 cocos2d-x.org http://www.cocos2d-x.org @@ -37,7 +37,7 @@ typedef struct AnimationInfo { AnimationInfo() : startIndex(0), endIndex(0) {} - AnimationInfo(const std::string& otherName, int otherStartIndex, int otherEndIndex) + AnimationInfo(std::string_view otherName, int otherStartIndex, int otherEndIndex) : name(otherName), startIndex(otherStartIndex), endIndex(otherEndIndex) {} @@ -150,8 +150,8 @@ public: /** AnimationInfo*/ virtual void addAnimationInfo(const AnimationInfo& animationInfo); virtual void removeAnimationInfo(std::string animationName); - virtual bool IsAnimationInfoExists(const std::string& animationName); - virtual const AnimationInfo& getAnimationInfo(const std::string& animationName); + virtual bool IsAnimationInfoExists(std::string_view animationName); + virtual const AnimationInfo& getAnimationInfo(std::string_view animationName); /**add a frame end call back to animation's end frame * @param animationName @addFrameEndCallFunc, make the animationName as funcKey * @param func the callback function @@ -171,9 +171,9 @@ public: * @param funcKey for identity the callback function * @param func the callback function */ - virtual void addFrameEndCallFunc(int frameIndex, const std::string& funcKey, std::function func); + virtual void addFrameEndCallFunc(int frameIndex, std::string_view funcKey, std::function func); // remove callback function after frameIndex which identified with funcKey - virtual void removeFrameEndCallFunc(int frameIndex, const std::string& funcKey); + virtual void removeFrameEndCallFunc(int frameIndex, std::string_view funcKey); // clear callback functions after frameIndex virtual void removeFrameEndCallFuncs(int frameIndex); // clear all the callback functions after frameIndexs in this actiontimeline diff --git a/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.cpp b/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.cpp index 44af85a5c5..946ad6b2e3 100644 --- a/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.cpp +++ b/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.cpp @@ -126,7 +126,7 @@ void ActionTimelineCache::init() */ } -void ActionTimelineCache::removeAction(const std::string& fileName) +void ActionTimelineCache::removeAction(std::string_view fileName) { if (_animationActions.find(fileName) != _animationActions.end()) { @@ -134,7 +134,7 @@ void ActionTimelineCache::removeAction(const std::string& fileName) } } -ActionTimeline* ActionTimelineCache::createAction(const std::string& filename) +ActionTimeline* ActionTimelineCache::createAction(std::string_view filename) { std::string path = filename; size_t pos = path.find_last_of('.'); @@ -154,7 +154,7 @@ ActionTimeline* ActionTimelineCache::createAction(const std::string& filename) return nullptr; } -ActionTimeline* ActionTimelineCache::createActionFromJson(const std::string& fileName) +ActionTimeline* ActionTimelineCache::createActionFromJson(std::string_view fileName) { ActionTimeline* action = _animationActions.at(fileName); if (action == nullptr) @@ -164,7 +164,7 @@ ActionTimeline* ActionTimelineCache::createActionFromJson(const std::string& fil return action->clone(); } -ActionTimeline* ActionTimelineCache::createActionFromContent(const std::string& fileName, const std::string& content) +ActionTimeline* ActionTimelineCache::createActionFromContent(std::string_view fileName, std::string_view content) { ActionTimeline* action = _animationActions.at(fileName); if (action == nullptr) @@ -174,7 +174,7 @@ ActionTimeline* ActionTimelineCache::createActionFromContent(const std::string& return action->clone(); } -ActionTimeline* ActionTimelineCache::loadAnimationActionWithFile(const std::string& fileName) +ActionTimeline* ActionTimelineCache::loadAnimationActionWithFile(std::string_view fileName) { // Read content from file std::string fullPath = FileUtils::getInstance()->fullPathForFilename(fileName); @@ -183,8 +183,8 @@ ActionTimeline* ActionTimelineCache::loadAnimationActionWithFile(const std::stri return loadAnimationActionWithContent(fileName, contentStr); } -ActionTimeline* ActionTimelineCache::loadAnimationActionWithContent(const std::string& fileName, - const std::string& content) +ActionTimeline* ActionTimelineCache::loadAnimationActionWithContent(std::string_view fileName, + std::string_view content) { // if already exists an action with filename, then return this action ActionTimeline* action = _animationActions.at(fileName); @@ -415,7 +415,7 @@ Frame* ActionTimelineCache::loadZOrderFrame(const rapidjson::Value& json) return frame; } -ActionTimeline* ActionTimelineCache::createActionWithFlatBuffersFile(const std::string& fileName) +ActionTimeline* ActionTimelineCache::createActionWithFlatBuffersFile(std::string_view fileName) { ActionTimeline* action = _animationActions.at(fileName); if (action == NULL) @@ -425,7 +425,7 @@ ActionTimeline* ActionTimelineCache::createActionWithFlatBuffersFile(const std:: return action->clone(); } -ActionTimeline* ActionTimelineCache::createActionWithDataBuffer(Data data, const std::string& fileName) +ActionTimeline* ActionTimelineCache::createActionWithDataBuffer(Data data, std::string_view fileName) { ActionTimeline* action = _animationActions.at(fileName); if (action == NULL) @@ -435,7 +435,7 @@ ActionTimeline* ActionTimelineCache::createActionWithDataBuffer(Data data, const return action->clone(); } -ActionTimeline* ActionTimelineCache::loadAnimationActionWithFlatBuffersFile(const std::string& fileName) +ActionTimeline* ActionTimelineCache::loadAnimationActionWithFlatBuffersFile(std::string_view fileName) { // if already exists an action with filename, then return this action ActionTimeline* action = _animationActions.at(fileName); @@ -455,7 +455,7 @@ ActionTimeline* ActionTimelineCache::loadAnimationActionWithFlatBuffersFile(cons return action; } -ActionTimeline* ActionTimelineCache::loadAnimationWithDataBuffer(const cocos2d::Data& data, const std::string& fileName) +ActionTimeline* ActionTimelineCache::loadAnimationWithDataBuffer(const cocos2d::Data& data, std::string_view fileName) { // if already exists an action with filename, then return this action ActionTimeline* action = _animationActions.at(fileName); @@ -953,7 +953,7 @@ void ActionTimelineCache::loadEasingDataWithFlatBuffers(cocostudio::timeline::Fr } } -ActionTimeline* ActionTimelineCache::createActionWithFlatBuffersForSimulator(const std::string& fileName) +ActionTimeline* ActionTimelineCache::createActionWithFlatBuffersForSimulator(std::string_view fileName) { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); fbs->_isSimulator = true; diff --git a/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.h b/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.h index 052280d164..eb74ea3d58 100644 --- a/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.h +++ b/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013 cocos2d-x.org http://www.cocos2d-x.org @@ -71,24 +71,24 @@ public: void init(); /** Remove action with filename, and also remove other resource relate with this file */ - void removeAction(const std::string& fileName); + void removeAction(std::string_view fileName); - static ActionTimeline* createAction(const std::string& fileName); + static ActionTimeline* createAction(std::string_view fileName); /** Clone a action with the specified name from the container. */ - ActionTimeline* createActionFromJson(const std::string& fileName); - ActionTimeline* createActionFromContent(const std::string& fileName, const std::string& content); + ActionTimeline* createActionFromJson(std::string_view fileName); + ActionTimeline* createActionFromContent(std::string_view fileName, std::string_view content); - ActionTimeline* loadAnimationActionWithFile(const std::string& fileName); - ActionTimeline* loadAnimationActionWithContent(const std::string& fileName, const std::string& content); + ActionTimeline* loadAnimationActionWithFile(std::string_view fileName); + ActionTimeline* loadAnimationActionWithContent(std::string_view fileName, std::string_view content); - ActionTimeline* createActionWithFlatBuffersFile(const std::string& fileName); - ActionTimeline* createActionWithDataBuffer(cocos2d::Data data, const std::string& fileName); + ActionTimeline* createActionWithFlatBuffersFile(std::string_view fileName); + ActionTimeline* createActionWithDataBuffer(cocos2d::Data data, std::string_view fileName); - ActionTimeline* loadAnimationActionWithFlatBuffersFile(const std::string& fileName); - ActionTimeline* loadAnimationWithDataBuffer(const cocos2d::Data& data, const std::string& fileName); + ActionTimeline* loadAnimationActionWithFlatBuffersFile(std::string_view fileName); + ActionTimeline* loadAnimationWithDataBuffer(const cocos2d::Data& data, std::string_view fileName); - ActionTimeline* createActionWithFlatBuffersForSimulator(const std::string& fileName); + ActionTimeline* createActionWithFlatBuffersForSimulator(std::string_view fileName); protected: Timeline* loadTimeline(const rapidjson::Value& json); diff --git a/extensions/cocostudio/ActionTimeline/CCBoneNode.cpp b/extensions/cocostudio/ActionTimeline/CCBoneNode.cpp index de7d55ca31..11b6ed2d4d 100644 --- a/extensions/cocostudio/ActionTimeline/CCBoneNode.cpp +++ b/extensions/cocostudio/ActionTimeline/CCBoneNode.cpp @@ -108,7 +108,7 @@ void BoneNode::addChild(cocos2d::Node* child, int localZOrder, int tag) Node::addChild(child, localZOrder, tag); } -void BoneNode::addChild(Node* child, int localZOrder, const std::string& name) +void BoneNode::addChild(Node* child, int localZOrder, std::string_view name) { addToChildrenListHelper(child); Node::addChild(child, localZOrder, name); @@ -240,7 +240,7 @@ void BoneNode::displaySkin(SkinNode* skin, bool hideOthers) } } -void BoneNode::displaySkin(const std::string& skinName, bool hideOthers) +void BoneNode::displaySkin(std::string_view skinName, bool hideOthers) { for (auto& skin : _boneSkins) { @@ -661,7 +661,7 @@ void BoneNode::setLocalZOrder(int localZOrder) _rootSkeleton->_subBonesOrderDirty = true; } -void BoneNode::setName(const std::string& name) +void BoneNode::setName(std::string_view name) { auto oldname = getName(); Node::setName(name); diff --git a/extensions/cocostudio/ActionTimeline/CCBoneNode.h b/extensions/cocostudio/ActionTimeline/CCBoneNode.h index 02003d3ce7..60450caa79 100644 --- a/extensions/cocostudio/ActionTimeline/CCBoneNode.h +++ b/extensions/cocostudio/ActionTimeline/CCBoneNode.h @@ -52,7 +52,7 @@ public: using Node::addChild; // add child, and add child to bone list and skeleton's sub bone map or add it to skin list - virtual void addChild(cocos2d::Node* child, int localZOrder, const std::string& name) override; + virtual void addChild(cocos2d::Node* child, int localZOrder, std::string_view name) override; virtual void addChild(cocos2d::Node* child, int localZOrder, int tag) override; // remove child, and remove child from bone list and skeleton's sub bone map or remove it from skin list @@ -94,7 +94,7 @@ public: * prefer to use display(SkinNode* skin, bool hideOthers = false) * @param: hideOthers, set other skins invisible */ - virtual void displaySkin(const std::string& skinName, bool hideOthers); + virtual void displaySkin(std::string_view skinName, bool hideOthers); // get the skins which is visible (displaying skins) virtual cocos2d::Vector getVisibleSkins() const; @@ -146,7 +146,7 @@ public: virtual void setLocalZOrder(int localZOrder) override; // set name, and replace the subbone map in skeleton - virtual void setName(const std::string& name) override; + virtual void setName(std::string_view name) override; // set visible, and dirty the debugdraw to make debugdraw's render layer right virtual void setVisible(bool visible) override; diff --git a/extensions/cocostudio/ActionTimeline/CCFrame.cpp b/extensions/cocostudio/ActionTimeline/CCFrame.cpp index 2b410c5f27..fff31a344d 100644 --- a/extensions/cocostudio/ActionTimeline/CCFrame.cpp +++ b/extensions/cocostudio/ActionTimeline/CCFrame.cpp @@ -548,7 +548,7 @@ void InnerActionFrame::setEndFrameIndex(int frameIndex) _endFrameIndex = frameIndex; } -void InnerActionFrame::setAnimationName(const std::string& animationName) +void InnerActionFrame::setAnimationName(std::string_view animationName) { if (!_enterWithName) { diff --git a/extensions/cocostudio/ActionTimeline/CCFrame.h b/extensions/cocostudio/ActionTimeline/CCFrame.h index f9c0ccd37c..0c6d450b84 100644 --- a/extensions/cocostudio/ActionTimeline/CCFrame.h +++ b/extensions/cocostudio/ActionTimeline/CCFrame.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013 cocos2d-x.org http://www.cocos2d-x.org @@ -293,7 +293,7 @@ public: void setEndFrameIndex(int frameIndex); inline int getEndFrameIndex() const { return _endFrameIndex; } - void setAnimationName(const std::string& animationNamed); + void setAnimationName(std::string_view animationNamed); inline void setSingleFrameIndex(int frameIndex) { _singleFrameIndex = frameIndex; } inline int getSingleFrameIndex() const { return _singleFrameIndex; } diff --git a/extensions/cocostudio/ActionTimeline/CCSkeletonNode.cpp b/extensions/cocostudio/ActionTimeline/CCSkeletonNode.cpp index 69417e6a47..c2f8dbc7a1 100644 --- a/extensions/cocostudio/ActionTimeline/CCSkeletonNode.cpp +++ b/extensions/cocostudio/ActionTimeline/CCSkeletonNode.cpp @@ -308,7 +308,7 @@ void SkeletonNode::changeSkins(const std::map& boneSki } } -void SkeletonNode::changeSkins(const std::string& skinGroupName) +void SkeletonNode::changeSkins(std::string_view skinGroupName) { auto suit = _skinGroupMap.find(skinGroupName); if (suit != _skinGroupMap.end()) @@ -317,7 +317,7 @@ void SkeletonNode::changeSkins(const std::string& skinGroupName) } } -BoneNode* SkeletonNode::getBoneNode(const std::string& boneName) +BoneNode* SkeletonNode::getBoneNode(std::string_view boneName) { auto iter = _subBonesMap.find(boneName); if (iter != _subBonesMap.end()) diff --git a/extensions/cocostudio/ActionTimeline/CCSkeletonNode.h b/extensions/cocostudio/ActionTimeline/CCSkeletonNode.h index e6117bdcb9..05d65bf973 100644 --- a/extensions/cocostudio/ActionTimeline/CCSkeletonNode.h +++ b/extensions/cocostudio/ActionTimeline/CCSkeletonNode.h @@ -44,7 +44,7 @@ public: /** *get bonenode in skeleton node by bone name */ - BoneNode* getBoneNode(const std::string& boneName); + BoneNode* getBoneNode(std::string_view boneName); /** *get All bones in this skeleton, @@ -61,7 +61,7 @@ public: *@brief: change displays *@param: skinGroupName have */ - void changeSkins(const std::string& skinGroupName); + void changeSkins(std::string_view skinGroupName); /** *@brief: add a boneSkinNameMap as a SkinGroup named groupName diff --git a/extensions/cocostudio/ActionTimeline/CSLoader.cpp b/extensions/cocostudio/ActionTimeline/CSLoader.cpp index fcb10cc04e..61012e3c36 100644 --- a/extensions/cocostudio/ActionTimeline/CSLoader.cpp +++ b/extensions/cocostudio/ActionTimeline/CSLoader.cpp @@ -280,7 +280,7 @@ void CSLoader::init() _componentFuncs.insert(ComponentPair(ClassName_ComAudio, std::bind(&CSLoader::loadComAudio, this, _1))); } -Node* CSLoader::createNode(const std::string& filename) +Node* CSLoader::createNode(std::string_view filename) { std::string path = filename; size_t pos = path.find_last_of('.'); @@ -300,7 +300,7 @@ Node* CSLoader::createNode(const std::string& filename) return nullptr; } -Node* CSLoader::createNode(const std::string& filename, const ccNodeLoadCallback& callback) +Node* CSLoader::createNode(std::string_view filename, const ccNodeLoadCallback& callback) { std::string path = filename; size_t pos = path.find_last_of('.'); @@ -316,7 +316,7 @@ Node* CSLoader::createNode(const std::string& filename, const ccNodeLoadCallback return nullptr; } -Node* CSLoader::createNodeWithVisibleSize(const std::string& filename) +Node* CSLoader::createNodeWithVisibleSize(std::string_view filename) { auto node = createNode(filename); if (node != nullptr) @@ -328,7 +328,7 @@ Node* CSLoader::createNodeWithVisibleSize(const std::string& filename) return node; } -Node* CSLoader::createNodeWithVisibleSize(const std::string& filename, const ccNodeLoadCallback& callback) +Node* CSLoader::createNodeWithVisibleSize(std::string_view filename, const ccNodeLoadCallback& callback) { auto node = createNode(filename, callback); if (node != nullptr) @@ -340,7 +340,7 @@ Node* CSLoader::createNodeWithVisibleSize(const std::string& filename, const ccN return node; } -std::string CSLoader::getExtentionName(const std::string& name) +std::string CSLoader::getExtentionName(std::string_view name) { std::string path = name; size_t pos = path.find_last_of('.'); @@ -349,7 +349,7 @@ std::string CSLoader::getExtentionName(const std::string& name) return result; } -ActionTimeline* CSLoader::createTimeline(const std::string& filename) +ActionTimeline* CSLoader::createTimeline(std::string_view filename) { std::string suffix = getExtentionName(filename); @@ -367,7 +367,7 @@ ActionTimeline* CSLoader::createTimeline(const std::string& filename) return nullptr; } -ActionTimeline* CSLoader::createTimeline(const Data& data, const std::string& filename) +ActionTimeline* CSLoader::createTimeline(const Data& data, std::string_view filename) { std::string suffix = getExtentionName(filename); @@ -387,7 +387,7 @@ ActionTimeline* CSLoader::createTimeline(const Data& data, const std::string& fi } /* -ActionTimelineNode* CSLoader::createActionTimelineNode(const std::string& filename) +ActionTimelineNode* CSLoader::createActionTimelineNode(std::string_view filename) { Node* root = createNode(filename); ActionTimeline* action = createTimeline(filename); @@ -401,7 +401,7 @@ ActionTimelineNode* CSLoader::createActionTimelineNode(const std::string& filena ActionTimelineNode* node = ActionTimelineNode::create(root, action); return node; } -ActionTimelineNode* CSLoader::createActionTimelineNode(const std::string& filename, int startIndex, int endIndex, bool +ActionTimelineNode* CSLoader::createActionTimelineNode(std::string_view filename, int startIndex, int endIndex, bool loop) { ActionTimelineNode* node = createActionTimelineNode(filename); @@ -413,7 +413,7 @@ loop) } */ -Node* CSLoader::createNodeFromJson(const std::string& filename) +Node* CSLoader::createNodeFromJson(std::string_view filename) { if (_recordJsonPath) { @@ -432,7 +432,7 @@ Node* CSLoader::createNodeFromJson(const std::string& filename) return node; } -Node* CSLoader::loadNodeWithFile(const std::string& fileName) +Node* CSLoader::loadNodeWithFile(std::string_view fileName) { // Read content from file std::string contentStr = FileUtils::getInstance()->getStringFromFile(fileName); @@ -445,7 +445,7 @@ Node* CSLoader::loadNodeWithFile(const std::string& fileName) return node; } -Node* CSLoader::loadNodeWithContent(const std::string& content) +Node* CSLoader::loadNodeWithContent(std::string_view content) { rapidjson::Document doc; doc.Parse<0>(content.c_str()); @@ -961,12 +961,12 @@ Node* CSLoader::createNode(const Data& data, const ccNodeLoadCallback& callback) return node; } -Node* CSLoader::createNodeWithFlatBuffersFile(const std::string& filename) +Node* CSLoader::createNodeWithFlatBuffersFile(std::string_view filename) { return createNodeWithFlatBuffersFile(filename, nullptr); } -Node* CSLoader::createNodeWithFlatBuffersFile(const std::string& filename, const ccNodeLoadCallback& callback) +Node* CSLoader::createNodeWithFlatBuffersFile(std::string_view filename, const ccNodeLoadCallback& callback) { Node* node = nodeWithFlatBuffersFile(filename, callback); @@ -995,12 +995,12 @@ inline void CSLoader::reconstructNestNode(cocos2d::Node* node) } } -Node* CSLoader::nodeWithFlatBuffersFile(const std::string& fileName) +Node* CSLoader::nodeWithFlatBuffersFile(std::string_view fileName) { return nodeWithFlatBuffersFile(fileName, nullptr); } -Node* CSLoader::nodeWithFlatBuffersFile(const std::string& fileName, const ccNodeLoadCallback& callback) +Node* CSLoader::nodeWithFlatBuffersFile(std::string_view fileName, const ccNodeLoadCallback& callback) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(fileName); @@ -1248,8 +1248,8 @@ Node* CSLoader::nodeWithFlatBuffers(const flatbuffers::NodeTree* nodetree, const } } -bool CSLoader::bindCallback(const std::string& callbackName, - const std::string& callbackType, +bool CSLoader::bindCallback(std::string_view callbackName, + std::string_view callbackType, cocos2d::ui::Widget* sender, cocos2d::Node* handler) { @@ -1293,7 +1293,7 @@ bool CSLoader::bindCallback(const std::string& callbackName, return false; } -bool CSLoader::isWidget(const std::string& type) +bool CSLoader::isWidget(std::string_view type) { return (type == ClassName_Panel || type == ClassName_Button || type == ClassName_CheckBox || type == ClassName_ImageView || type == ClassName_TextAtlas || type == ClassName_LabelAtlas || @@ -1303,7 +1303,7 @@ bool CSLoader::isWidget(const std::string& type) type == ClassName_PageView || type == ClassName_Widget || type == ClassName_Label); } -bool CSLoader::isCustomWidget(const std::string& type) +bool CSLoader::isCustomWidget(std::string_view type) { Widget* widget = dynamic_cast(ObjectFactory::getInstance()->createObject(type)); if (widget) @@ -1315,7 +1315,7 @@ bool CSLoader::isCustomWidget(const std::string& type) return false; } -std::string CSLoader::getGUIClassName(const std::string& name) +std::string CSLoader::getGUIClassName(std::string_view name) { std::string convertedClassName = name; if (name == "Panel") @@ -1412,7 +1412,7 @@ std::string CSLoader::getWidgetReaderClassName(Widget* widget) return readerName; } -void CSLoader::registReaderObject(const std::string& className, ObjectFactory::Instance ins) +void CSLoader::registReaderObject(std::string_view className, ObjectFactory::Instance ins) { ObjectFactory::TInfo t; t._class = className; @@ -1421,7 +1421,7 @@ void CSLoader::registReaderObject(const std::string& className, ObjectFactory::I ObjectFactory::getInstance()->registerType(t); } -Node* CSLoader::createNodeWithFlatBuffersForSimulator(const std::string& filename) +Node* CSLoader::createNodeWithFlatBuffersForSimulator(std::string_view filename) { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); fbs->_isSimulator = true; diff --git a/extensions/cocostudio/ActionTimeline/CSLoader.h b/extensions/cocostudio/ActionTimeline/CSLoader.h index afcd41f583..903e7b31fa 100644 --- a/extensions/cocostudio/ActionTimeline/CSLoader.h +++ b/extensions/cocostudio/ActionTimeline/CSLoader.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013 cocos2d-x.org http://www.cocos2d-x.org @@ -79,25 +79,25 @@ public: void init(); - static cocos2d::Node* createNode(const std::string& filename); - static cocos2d::Node* createNode(const std::string& filename, const ccNodeLoadCallback& callback); + static cocos2d::Node* createNode(std::string_view filename); + static cocos2d::Node* createNode(std::string_view filename, const ccNodeLoadCallback& callback); static cocos2d::Node* createNode(const Data& data); static cocos2d::Node* createNode(const Data& data, const ccNodeLoadCallback& callback); - static cocos2d::Node* createNodeWithVisibleSize(const std::string& filename); - static cocos2d::Node* createNodeWithVisibleSize(const std::string& filename, const ccNodeLoadCallback& callback); + static cocos2d::Node* createNodeWithVisibleSize(std::string_view filename); + static cocos2d::Node* createNodeWithVisibleSize(std::string_view filename, const ccNodeLoadCallback& callback); - static cocostudio::timeline::ActionTimeline* createTimeline(const std::string& filename); - static cocostudio::timeline::ActionTimeline* createTimeline(const Data& data, const std::string& filename); + static cocostudio::timeline::ActionTimeline* createTimeline(std::string_view filename); + static cocostudio::timeline::ActionTimeline* createTimeline(const Data& data, std::string_view filename); /* - static cocostudio::timeline::ActionTimelineNode* createActionTimelineNode(const std::string& filename); - static cocostudio::timeline::ActionTimelineNode* createActionTimelineNode(const std::string& filename, int + static cocostudio::timeline::ActionTimelineNode* createActionTimelineNode(std::string_view filename); + static cocostudio::timeline::ActionTimelineNode* createActionTimelineNode(std::string_view filename, int startIndex, int endIndex, bool loop); */ - cocos2d::Node* createNodeFromJson(const std::string& filename); - cocos2d::Node* loadNodeWithFile(const std::string& fileName); - cocos2d::Node* loadNodeWithContent(const std::string& content); + cocos2d::Node* createNodeFromJson(std::string_view filename); + cocos2d::Node* loadNodeWithFile(std::string_view fileName); + cocos2d::Node* loadNodeWithContent(std::string_view content); void setRecordJsonPath(bool record) { _recordJsonPath = record; } bool isRecordJsonPath() const { return _recordJsonPath; } @@ -105,23 +105,23 @@ public: void setJsonPath(std::string jsonPath) { _jsonPath = jsonPath; } std::string getJsonPath() const { return _jsonPath; } - cocos2d::Node* createNodeWithFlatBuffersFile(const std::string& filename); - cocos2d::Node* nodeWithFlatBuffersFile(const std::string& fileName); + cocos2d::Node* createNodeWithFlatBuffersFile(std::string_view filename); + cocos2d::Node* nodeWithFlatBuffersFile(std::string_view fileName); cocos2d::Node* nodeWithFlatBuffers(const flatbuffers::NodeTree* nodetree); - bool bindCallback(const std::string& callbackName, - const std::string& callbackType, + bool bindCallback(std::string_view callbackName, + std::string_view callbackType, cocos2d::ui::Widget* sender, cocos2d::Node* handler); - void registReaderObject(const std::string& className, ObjectFactory::Instance ins); + void registReaderObject(std::string_view className, ObjectFactory::Instance ins); - cocos2d::Node* createNodeWithFlatBuffersForSimulator(const std::string& filename); + cocos2d::Node* createNodeWithFlatBuffersForSimulator(std::string_view filename); cocos2d::Node* nodeWithFlatBuffersForSimulator(const flatbuffers::NodeTree* nodetree); protected: - cocos2d::Node* createNodeWithFlatBuffersFile(const std::string& filename, const ccNodeLoadCallback& callback); - cocos2d::Node* nodeWithFlatBuffersFile(const std::string& fileName, const ccNodeLoadCallback& callback); + cocos2d::Node* createNodeWithFlatBuffersFile(std::string_view filename, const ccNodeLoadCallback& callback); + cocos2d::Node* nodeWithFlatBuffersFile(std::string_view fileName, const ccNodeLoadCallback& callback); cocos2d::Node* nodeWithFlatBuffers(const flatbuffers::NodeTree* nodetree, const ccNodeLoadCallback& callback); cocos2d::Node* loadNode(const rapidjson::Value& json); @@ -144,14 +144,14 @@ protected: cocos2d::Component* loadComponent(const rapidjson::Value& json); cocos2d::Component* loadComAudio(const rapidjson::Value& json); - bool isWidget(const std::string& type); - bool isCustomWidget(const std::string& type); + bool isWidget(std::string_view type); + bool isCustomWidget(std::string_view type); - std::string getGUIClassName(const std::string& name); + std::string getGUIClassName(std::string_view name); std::string getWidgetReaderClassName(cocos2d::ui::Widget* widget); inline void reconstructNestNode(cocos2d::Node* node); - static inline std::string getExtentionName(const std::string& name); + static inline std::string getExtentionName(std::string_view name); typedef std::function NodeCreateFunc; typedef std::pair Pair; diff --git a/extensions/cocostudio/CCActionNode.cpp b/extensions/cocostudio/CCActionNode.cpp index 88ffc8b5ed..7bb4b3b322 100644 --- a/extensions/cocostudio/CCActionNode.cpp +++ b/extensions/cocostudio/CCActionNode.cpp @@ -188,11 +188,11 @@ void ActionNode::initWithDictionary(const rapidjson::Value& dic, Ref* root) initActionNodeFromRoot(root); } -int ActionNode::valueToInt(const std::string& value) +int ActionNode::valueToInt(std::string_view value) { return atoi(value.c_str()); } -bool ActionNode::valueToBool(const std::string& value) +bool ActionNode::valueToBool(std::string_view value) { int intValue = valueToInt(value); if (1 == intValue) @@ -204,7 +204,7 @@ bool ActionNode::valueToBool(const std::string& value) return false; } } -float ActionNode::valueToFloat(const std::string& value) +float ActionNode::valueToFloat(std::string_view value) { return utils::atof(value.c_str()); } diff --git a/extensions/cocostudio/CCActionNode.h b/extensions/cocostudio/CCActionNode.h index 17c29ba996..ec1a6554c7 100644 --- a/extensions/cocostudio/CCActionNode.h +++ b/extensions/cocostudio/CCActionNode.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -162,9 +162,9 @@ public: virtual bool isActionDoneOnce(); protected: - int valueToInt(const std::string& value); - bool valueToBool(const std::string& value); - float valueToFloat(const std::string& value); + int valueToInt(std::string_view value); + bool valueToBool(std::string_view value); + float valueToFloat(std::string_view value); int _currentFrameIndex; int _destFrameIndex; diff --git a/extensions/cocostudio/CCActionObject.cpp b/extensions/cocostudio/CCActionObject.cpp index badd9c4852..8143324837 100644 --- a/extensions/cocostudio/CCActionObject.cpp +++ b/extensions/cocostudio/CCActionObject.cpp @@ -184,11 +184,11 @@ void ActionObject::initWithBinary(CocoLoader* cocoLoader, stExpCocoNode* cocoNod } } -int ActionObject::valueToInt(const std::string& value) +int ActionObject::valueToInt(std::string_view value) { return atoi(value.c_str()); } -bool ActionObject::valueToBool(const std::string& value) +bool ActionObject::valueToBool(std::string_view value) { int intValue = valueToInt(value); if (1 == intValue) @@ -200,7 +200,7 @@ bool ActionObject::valueToBool(const std::string& value) return false; } } -float ActionObject::valueToFloat(const std::string& value) +float ActionObject::valueToFloat(std::string_view value) { return utils::atof(value.c_str()); } diff --git a/extensions/cocostudio/CCActionObject.h b/extensions/cocostudio/CCActionObject.h index 195c741d5b..b151631ed4 100644 --- a/extensions/cocostudio/CCActionObject.h +++ b/extensions/cocostudio/CCActionObject.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -171,9 +171,9 @@ public: void simulationActionUpdate(float dt); protected: - int valueToInt(const std::string& value); - bool valueToBool(const std::string& value); - float valueToFloat(const std::string& value); + int valueToInt(std::string_view value); + bool valueToBool(std::string_view value); + float valueToFloat(std::string_view value); cocos2d::Vector _actionNodeList; std::string _name; diff --git a/extensions/cocostudio/CCArmature.cpp b/extensions/cocostudio/CCArmature.cpp index 985d3aec43..2a1f6402eb 100644 --- a/extensions/cocostudio/CCArmature.cpp +++ b/extensions/cocostudio/CCArmature.cpp @@ -57,7 +57,7 @@ Armature* Armature::create() return nullptr; } -Armature* Armature::create(const std::string& name) +Armature* Armature::create(std::string_view name) { Armature* armature = new Armature(); if (armature->init(name)) @@ -69,7 +69,7 @@ Armature* Armature::create(const std::string& name) return nullptr; } -Armature* Armature::create(const std::string& name, Bone* parentBone) +Armature* Armature::create(std::string_view name, Bone* parentBone) { Armature* armature = new Armature(); if (armature->init(name, parentBone)) @@ -102,7 +102,7 @@ bool Armature::init() return init(""); } -bool Armature::init(const std::string& name) +bool Armature::init(std::string_view name) { bool bRet = false; do @@ -182,13 +182,13 @@ bool Armature::init(const std::string& name) return bRet; } -bool Armature::init(const std::string& name, Bone* parentBone) +bool Armature::init(std::string_view name, Bone* parentBone) { _parentBone = parentBone; return init(name); } -Bone* Armature::createBone(const std::string& boneName) +Bone* Armature::createBone(std::string_view boneName) { Bone* existedBone = getBone(boneName); if (existedBone != nullptr) @@ -217,7 +217,7 @@ Bone* Armature::createBone(const std::string& boneName) return bone; } -void Armature::addBone(Bone* bone, const std::string& parentName) +void Armature::addBone(Bone* bone, std::string_view parentName) { CCASSERT(bone != nullptr, "Argument must be non-nil"); CCASSERT(_boneDic.at(bone->getName()) == nullptr, "bone already added. It can't be added again"); @@ -260,12 +260,12 @@ void Armature::removeBone(Bone* bone, bool recursion) removeChild(bone, true); } -Bone* Armature::getBone(const std::string& name) const +Bone* Armature::getBone(std::string_view name) const { return _boneDic.at(name); } -void Armature::changeBoneParent(Bone* bone, const std::string& parentName) +void Armature::changeBoneParent(Bone* bone, std::string_view parentName) { CCASSERT(bone != nullptr, "bone must be added to the bone dictionary!"); diff --git a/extensions/cocostudio/CCArmature.h b/extensions/cocostudio/CCArmature.h index d207940d85..415018cd6e 100644 --- a/extensions/cocostudio/CCArmature.h +++ b/extensions/cocostudio/CCArmature.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -85,9 +85,9 @@ public: * @param name Armature will use the name to find the ArmatureData to initializes it. * @return A initialized armature which is marked as "autorelease". */ - static Armature* create(const std::string& name); + static Armature* create(std::string_view name); - static Armature* create(const std::string& name, Bone* parentBone); + static Armature* create(std::string_view name, Bone* parentBone); public: /** @@ -109,29 +109,29 @@ public: * Init an armature with specified name * @param name Armature name */ - virtual bool init(const std::string& name); + virtual bool init(std::string_view name); - virtual bool init(const std::string& name, Bone* parentBone); + virtual bool init(std::string_view name, Bone* parentBone); /** * Add a Bone to this Armature, * * @param bone The Bone you want to add to Armature * @param parentName The parent Bone's name you want to add to . If it's nullptr, then set Armature to its parent */ - virtual void addBone(Bone* bone, const std::string& parentName); + virtual void addBone(Bone* bone, std::string_view parentName); /** * Get a bone with the specified name * * @param name The bone's name you want to get */ - virtual Bone* getBone(const std::string& name) const; + virtual Bone* getBone(std::string_view name) const; /** * Change a bone's parent with the specified parent name. * * @param bone The bone you want to change parent * @param parentName The new parent's name. */ - virtual void changeBoneParent(Bone* bone, const std::string& parentName); + virtual void changeBoneParent(Bone* bone, std::string_view parentName); /** * Remove a bone with the specified name. If recursion it will also remove child Bone recursionly. * @@ -246,7 +246,7 @@ protected: * @js NA * @lua NA */ - Bone* createBone(const std::string& boneName); + Bone* createBone(std::string_view boneName); protected: ArmatureData* _armatureData; diff --git a/extensions/cocostudio/CCArmatureAnimation.cpp b/extensions/cocostudio/CCArmatureAnimation.cpp index 5f02e393e1..7b7258234a 100644 --- a/extensions/cocostudio/CCArmatureAnimation.cpp +++ b/extensions/cocostudio/CCArmatureAnimation.cpp @@ -156,7 +156,7 @@ float ArmatureAnimation::getSpeedScale() const return _speedScale; } -void ArmatureAnimation::play(const std::string& animationName, int durationTo, int loop) +void ArmatureAnimation::play(std::string_view animationName, int durationTo, int loop) { if (animationName.empty()) { @@ -469,12 +469,12 @@ void ArmatureAnimation::setFrameEventCallFunc(Ref* target, SEL_FrameEventCallFun } void ArmatureAnimation::setMovementEventCallFunc( - std::function listener) + std::function listener) { _movementEventListener = listener; } void ArmatureAnimation::setFrameEventCallFunc( - std::function + std::function listener) { _frameEventListener = listener; @@ -488,7 +488,7 @@ void ArmatureAnimation::setUserObject(Ref* pUserObject) } void ArmatureAnimation::frameEvent(Bone* bone, - const std::string& frameEventName, + std::string_view frameEventName, int originFrameIndex, int currentFrameIndex) { @@ -504,7 +504,7 @@ void ArmatureAnimation::frameEvent(Bone* bone, } } -void ArmatureAnimation::movementEvent(Armature* armature, MovementEventType movementType, const std::string& movementID) +void ArmatureAnimation::movementEvent(Armature* armature, MovementEventType movementType, std::string_view movementID) { if ((_movementEventTarget && _movementEventCallFunc) || _movementEventListener) { diff --git a/extensions/cocostudio/CCArmatureAnimation.h b/extensions/cocostudio/CCArmatureAnimation.h index 77eb5984a0..c855e3b844 100644 --- a/extensions/cocostudio/CCArmatureAnimation.h +++ b/extensions/cocostudio/CCArmatureAnimation.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -123,7 +123,7 @@ public: * loop = 0 : this animation is not loop * loop > 0 : this animation is loop */ - virtual void play(const std::string& animationName, int durationTo = -1, int loop = -1); + virtual void play(std::string_view animationName, int durationTo = -1, int loop = -1); /** * Play animation by index, the other param is the same to play. @@ -192,10 +192,10 @@ public: CC_DEPRECATED_ATTRIBUTE void setFrameEventCallFunc(cocos2d::Ref* target, SEL_FrameEventCallFunc callFunc); void setMovementEventCallFunc( - std::function + std::function listener); void setFrameEventCallFunc( - std::function + std::function listener); virtual void setAnimationData(AnimationData* data) @@ -257,12 +257,12 @@ protected: * @js NA * @lua NA */ - void frameEvent(Bone* bone, const std::string& frameEventName, int originFrameIndex, int currentFrameIndex); + void frameEvent(Bone* bone, std::string_view frameEventName, int originFrameIndex, int currentFrameIndex); /** * Emit a movement event */ - void movementEvent(Armature* armature, MovementEventType movementType, const std::string& movementID); + void movementEvent(Armature* armature, MovementEventType movementType, std::string_view movementID); void updateMovementList(); @@ -322,9 +322,9 @@ protected: cocos2d::Ref* _movementEventTarget; cocos2d::Ref* _frameEventTarget; - std::function + std::function _movementEventListener; - std::function + std::function _frameEventListener; }; diff --git a/extensions/cocostudio/CCArmatureDataManager.cpp b/extensions/cocostudio/CCArmatureDataManager.cpp index 20f716f0e3..c0e39d227b 100644 --- a/extensions/cocostudio/CCArmatureDataManager.cpp +++ b/extensions/cocostudio/CCArmatureDataManager.cpp @@ -87,7 +87,7 @@ bool ArmatureDataManager::init() return bRet; } -void ArmatureDataManager::removeArmatureFileInfo(const std::string& configFilePath) +void ArmatureDataManager::removeArmatureFileInfo(std::string_view configFilePath) { if (RelativeData* data = getRelativeData(configFilePath)) { @@ -116,9 +116,9 @@ void ArmatureDataManager::removeArmatureFileInfo(const std::string& configFilePa } } -void ArmatureDataManager::addArmatureData(const std::string& id, +void ArmatureDataManager::addArmatureData(std::string_view id, ArmatureData* armatureData, - const std::string& configFilePath) + std::string_view configFilePath) { if (RelativeData* data = getRelativeData(configFilePath)) { @@ -128,19 +128,19 @@ void ArmatureDataManager::addArmatureData(const std::string& id, _armarureDatas.insert(id, armatureData); } -ArmatureData* ArmatureDataManager::getArmatureData(const std::string& id) +ArmatureData* ArmatureDataManager::getArmatureData(std::string_view id) { return dynamic_cast(_armarureDatas.at(id)); } -void ArmatureDataManager::removeArmatureData(const std::string& id) +void ArmatureDataManager::removeArmatureData(std::string_view id) { _armarureDatas.erase(id); } -void ArmatureDataManager::addAnimationData(const std::string& id, +void ArmatureDataManager::addAnimationData(std::string_view id, AnimationData* animationData, - const std::string& configFilePath) + std::string_view configFilePath) { if (RelativeData* data = getRelativeData(configFilePath)) { @@ -150,19 +150,19 @@ void ArmatureDataManager::addAnimationData(const std::string& id, _animationDatas.insert(id, animationData); } -AnimationData* ArmatureDataManager::getAnimationData(const std::string& id) +AnimationData* ArmatureDataManager::getAnimationData(std::string_view id) { return dynamic_cast(_animationDatas.at(id)); } -void ArmatureDataManager::removeAnimationData(const std::string& id) +void ArmatureDataManager::removeAnimationData(std::string_view id) { _animationDatas.erase(id); } -void ArmatureDataManager::addTextureData(const std::string& id, +void ArmatureDataManager::addTextureData(std::string_view id, TextureData* textureData, - const std::string& configFilePath) + std::string_view configFilePath) { if (RelativeData* data = getRelativeData(configFilePath)) { @@ -172,17 +172,17 @@ void ArmatureDataManager::addTextureData(const std::string& id, _textureDatas.insert(id, textureData); } -TextureData* ArmatureDataManager::getTextureData(const std::string& id) +TextureData* ArmatureDataManager::getTextureData(std::string_view id) { return dynamic_cast(_textureDatas.at(id)); } -void ArmatureDataManager::removeTextureData(const std::string& id) +void ArmatureDataManager::removeTextureData(std::string_view id) { _textureDatas.erase(id); } -void ArmatureDataManager::addArmatureFileInfo(const std::string& configFilePath) +void ArmatureDataManager::addArmatureFileInfo(std::string_view configFilePath) { addRelativeData(configFilePath); @@ -190,7 +190,7 @@ void ArmatureDataManager::addArmatureFileInfo(const std::string& configFilePath) DataReaderHelper::getInstance()->addDataFromFile(configFilePath); } -void ArmatureDataManager::addArmatureFileInfoAsync(const std::string& configFilePath, +void ArmatureDataManager::addArmatureFileInfoAsync(std::string_view configFilePath, Ref* target, SEL_SCHEDULE selector) { @@ -200,9 +200,9 @@ void ArmatureDataManager::addArmatureFileInfoAsync(const std::string& configFile DataReaderHelper::getInstance()->addDataFromFileAsync("", "", configFilePath, target, selector); } -void ArmatureDataManager::addArmatureFileInfo(const std::string& imagePath, - const std::string& plistPath, - const std::string& configFilePath) +void ArmatureDataManager::addArmatureFileInfo(std::string_view imagePath, + std::string_view plistPath, + std::string_view configFilePath) { addRelativeData(configFilePath); @@ -211,9 +211,9 @@ void ArmatureDataManager::addArmatureFileInfo(const std::string& imagePath, addSpriteFrameFromFile(plistPath, imagePath, configFilePath); } -void ArmatureDataManager::addArmatureFileInfoAsync(const std::string& imagePath, - const std::string& plistPath, - const std::string& configFilePath, +void ArmatureDataManager::addArmatureFileInfoAsync(std::string_view imagePath, + std::string_view plistPath, + std::string_view configFilePath, Ref* target, SEL_SCHEDULE selector) { @@ -224,9 +224,9 @@ void ArmatureDataManager::addArmatureFileInfoAsync(const std::string& imagePath, addSpriteFrameFromFile(plistPath, imagePath, configFilePath); } -void ArmatureDataManager::addSpriteFrameFromFile(const std::string& plistPath, - const std::string& imagePath, - const std::string& configFilePath) +void ArmatureDataManager::addSpriteFrameFromFile(std::string_view plistPath, + std::string_view imagePath, + std::string_view configFilePath) { if (RelativeData* data = getRelativeData(configFilePath)) { @@ -253,7 +253,7 @@ const cocos2d::Map& ArmatureDataManager::getTextureDa return _textureDatas; } -void ArmatureDataManager::addRelativeData(const std::string& configFilePath) +void ArmatureDataManager::addRelativeData(std::string_view configFilePath) { if (_relativeDatas.find(configFilePath) == _relativeDatas.end()) { @@ -261,7 +261,7 @@ void ArmatureDataManager::addRelativeData(const std::string& configFilePath) } } -RelativeData* ArmatureDataManager::getRelativeData(const std::string& configFilePath) +RelativeData* ArmatureDataManager::getRelativeData(std::string_view configFilePath) { return &_relativeDatas[configFilePath]; } diff --git a/extensions/cocostudio/CCArmatureDataManager.h b/extensions/cocostudio/CCArmatureDataManager.h index d7e9f5dd97..8b89ddb7a5 100644 --- a/extensions/cocostudio/CCArmatureDataManager.h +++ b/extensions/cocostudio/CCArmatureDataManager.h @@ -80,99 +80,99 @@ public: * @param id The id of the armature data * @param armatureData ArmatureData * */ - void addArmatureData(const std::string& id, ArmatureData* armatureData, const std::string& configFilePath = ""); + void addArmatureData(std::string_view id, ArmatureData* armatureData, std::string_view configFilePath = ""); /** * @brief get armature data * @param id the id of the armature data you want to get * @return ArmatureData * */ - ArmatureData* getArmatureData(const std::string& id); + ArmatureData* getArmatureData(std::string_view id); /** * @brief remove armature data * @param id the id of the armature data you want to get */ - void removeArmatureData(const std::string& id); + void removeArmatureData(std::string_view id); /** * @brief add animation data * @param id the id of the animation data * @return AnimationData * */ - void addAnimationData(const std::string& id, AnimationData* animationData, const std::string& configFilePath = ""); + void addAnimationData(std::string_view id, AnimationData* animationData, std::string_view configFilePath = ""); /** * @brief get animation data from _animationDatas(Dictionary) * @param id the id of the animation data you want to get * @return AnimationData * */ - AnimationData* getAnimationData(const std::string& id); + AnimationData* getAnimationData(std::string_view id); /** * @brief remove animation data * @param id the id of the animation data */ - void removeAnimationData(const std::string& id); + void removeAnimationData(std::string_view id); /** * @brief add texture data * @param id the id of the texture data * @return TextureData * */ - void addTextureData(const std::string& id, TextureData* textureData, const std::string& configFilePath = ""); + void addTextureData(std::string_view id, TextureData* textureData, std::string_view configFilePath = ""); /** * @brief get texture data * @param id the id of the texture data you want to get * @return TextureData * */ - TextureData* getTextureData(const std::string& id); + TextureData* getTextureData(std::string_view id); /** * @brief remove texture data * @param id the id of the texture data you want to get */ - void removeTextureData(const std::string& id); + void removeTextureData(std::string_view id); /** * @brief Add ArmatureFileInfo, it is managed by ArmatureDataManager. */ - void addArmatureFileInfo(const std::string& configFilePath); + void addArmatureFileInfo(std::string_view configFilePath); /** * @brief Add ArmatureFileInfo, it is managed by ArmatureDataManager. * It will load data in a new thread */ - void addArmatureFileInfoAsync(const std::string& configFilePath, + void addArmatureFileInfoAsync(std::string_view configFilePath, cocos2d::Ref* target, cocos2d::SEL_SCHEDULE selector); /** * @brief Add ArmatureFileInfo, it is managed by ArmatureDataManager. */ - void addArmatureFileInfo(const std::string& imagePath, - const std::string& plistPath, - const std::string& configFilePath); + void addArmatureFileInfo(std::string_view imagePath, + std::string_view plistPath, + std::string_view configFilePath); /** * @brief Add ArmatureFileInfo, it is managed by ArmatureDataManager. * It will load data in a new thread */ - void addArmatureFileInfoAsync(const std::string& imagePath, - const std::string& plistPath, - const std::string& configFilePath, + void addArmatureFileInfoAsync(std::string_view imagePath, + std::string_view plistPath, + std::string_view configFilePath, cocos2d::Ref* target, cocos2d::SEL_SCHEDULE selector); /** * @brief Add sprite frame to CCSpriteFrameCache, it will save display name and it's relative image name */ - void addSpriteFrameFromFile(const std::string& plistPath, - const std::string& imagePath, - const std::string& configFilePath = ""); + void addSpriteFrameFromFile(std::string_view plistPath, + std::string_view imagePath, + std::string_view configFilePath = ""); - virtual void removeArmatureFileInfo(const std::string& configFilePath); + virtual void removeArmatureFileInfo(std::string_view configFilePath); /** * @brief Judge whether or not need auto load sprite file @@ -184,8 +184,8 @@ public: const cocos2d::Map& getTextureDatas() const; public: - void addRelativeData(const std::string& configFilePath); - RelativeData* getRelativeData(const std::string& configFilePath); + void addRelativeData(std::string_view configFilePath); + RelativeData* getRelativeData(std::string_view configFilePath); private: /** diff --git a/extensions/cocostudio/CCBatchNode.cpp b/extensions/cocostudio/CCBatchNode.cpp index f7ec04f519..4344dea841 100644 --- a/extensions/cocostudio/CCBatchNode.cpp +++ b/extensions/cocostudio/CCBatchNode.cpp @@ -69,7 +69,7 @@ void BatchNode::addChild(Node* child, int zOrder, int tag) } } -void BatchNode::addChild(cocos2d::Node* child, int zOrder, const std::string& name) +void BatchNode::addChild(cocos2d::Node* child, int zOrder, std::string_view name) { Node::addChild(child, zOrder, name); Armature* armature = dynamic_cast(child); diff --git a/extensions/cocostudio/CCBatchNode.h b/extensions/cocostudio/CCBatchNode.h index 88a3983451..7269f6dcbb 100644 --- a/extensions/cocostudio/CCBatchNode.h +++ b/extensions/cocostudio/CCBatchNode.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -58,7 +58,7 @@ public: virtual bool init() override; using Node::addChild; virtual void addChild(cocos2d::Node* pChild, int zOrder, int tag) override; - virtual void addChild(cocos2d::Node* pChild, int zOrder, const std::string& name) override; + virtual void addChild(cocos2d::Node* pChild, int zOrder, std::string_view name) override; virtual void removeChild(cocos2d::Node* child, bool cleanup) override; virtual void visit(cocos2d::Renderer* renderer, const cocos2d::Mat4& parentTransform, diff --git a/extensions/cocostudio/CCBone.cpp b/extensions/cocostudio/CCBone.cpp index bbe38bb390..1fe824b92f 100644 --- a/extensions/cocostudio/CCBone.cpp +++ b/extensions/cocostudio/CCBone.cpp @@ -47,7 +47,7 @@ Bone* Bone::create() return nullptr; } -Bone* Bone::create(const std::string& name) +Bone* Bone::create(std::string_view name) { Bone* pBone = new Bone(); @@ -95,7 +95,7 @@ bool Bone::init() return Bone::init(nullptr); } -bool Bone::init(const std::string& name) +bool Bone::init(std::string_view name) { bool bRet = false; do @@ -416,7 +416,7 @@ void Bone::changeDisplayByIndex(int index, bool force) changeDisplayWithIndex(index, force); } -void Bone::changeDisplayByName(const std::string& name, bool force) +void Bone::changeDisplayByName(std::string_view name, bool force) { changeDisplayWithName(name, force); } @@ -426,7 +426,7 @@ void Bone::changeDisplayWithIndex(int index, bool force) _displayManager->changeDisplayWithIndex(index, force); } -void Bone::changeDisplayWithName(const std::string& name, bool force) +void Bone::changeDisplayWithName(std::string_view name, bool force) { _displayManager->changeDisplayWithName(name, force); } diff --git a/extensions/cocostudio/CCBone.h b/extensions/cocostudio/CCBone.h index bea21a95df..409a0a381e 100644 --- a/extensions/cocostudio/CCBone.h +++ b/extensions/cocostudio/CCBone.h @@ -53,7 +53,7 @@ public: * @param name If name is not null, then set name to the bone's name * @return A initialized bone which is marked as "autorelease". */ - static Bone* create(const std::string& name); + static Bone* create(std::string_view name); public: /** @@ -75,7 +75,7 @@ public: * Initializes a Bone with the specified name * @param name Bone's name. */ - virtual bool init(const std::string& name); + virtual bool init(std::string_view name); /** * Add display and use displayData to init the display. @@ -95,10 +95,10 @@ public: void removeDisplay(int index); CC_DEPRECATED_ATTRIBUTE void changeDisplayByIndex(int index, bool force); - CC_DEPRECATED_ATTRIBUTE void changeDisplayByName(const std::string& name, bool force); + CC_DEPRECATED_ATTRIBUTE void changeDisplayByName(std::string_view name, bool force); void changeDisplayWithIndex(int index, bool force); - void changeDisplayWithName(const std::string& name, bool force); + void changeDisplayWithName(std::string_view name, bool force); /** * Add a child to this bone, and it will let this child call setParent(Bone *parent) function to set self to it's diff --git a/extensions/cocostudio/CCComAttribute.cpp b/extensions/cocostudio/CCComAttribute.cpp index 57cf1b0767..2993266d56 100644 --- a/extensions/cocostudio/CCComAttribute.cpp +++ b/extensions/cocostudio/CCComAttribute.cpp @@ -49,27 +49,27 @@ bool ComAttribute::init() return true; } -void ComAttribute::setInt(const std::string& key, int value) +void ComAttribute::setInt(std::string_view key, int value) { _dict[key] = cocos2d::Value(value); } -void ComAttribute::setFloat(const std::string& key, float value) +void ComAttribute::setFloat(std::string_view key, float value) { _dict[key] = cocos2d::Value(value); } -void ComAttribute::setBool(const std::string& key, bool value) +void ComAttribute::setBool(std::string_view key, bool value) { _dict[key] = cocos2d::Value(value); } -void ComAttribute::setString(const std::string& key, const std::string& value) +void ComAttribute::setString(std::string_view key, std::string_view value) { _dict[key] = cocos2d::Value(value); } -int ComAttribute::getInt(const std::string& key, int def) const +int ComAttribute::getInt(std::string_view key, int def) const { if (_dict.find(key) != _dict.end()) { @@ -85,7 +85,7 @@ int ComAttribute::getInt(const std::string& key, int def) const return DICTOOL->getIntValue_json(_doc, key.c_str()); } -float ComAttribute::getFloat(const std::string& key, float def) const +float ComAttribute::getFloat(std::string_view key, float def) const { if (_dict.find(key) != _dict.end()) { @@ -100,7 +100,7 @@ float ComAttribute::getFloat(const std::string& key, float def) const return DICTOOL->getFloatValue_json(_doc, key.c_str()); } -bool ComAttribute::getBool(const std::string& key, bool def) const +bool ComAttribute::getBool(std::string_view key, bool def) const { if (_dict.find(key) != _dict.end()) { @@ -116,7 +116,7 @@ bool ComAttribute::getBool(const std::string& key, bool def) const return DICTOOL->getBooleanValue_json(_doc, key.c_str()); } -std::string ComAttribute::getString(const std::string& key, const std::string& def) const +std::string ComAttribute::getString(std::string_view key, std::string_view def) const { if (_dict.find(key) != _dict.end()) { @@ -206,7 +206,7 @@ bool ComAttribute::serialize(void* r) return ret; } -bool ComAttribute::parse(const std::string& jsonFile) +bool ComAttribute::parse(std::string_view jsonFile) { bool ret = false; do diff --git a/extensions/cocostudio/CCComAttribute.h b/extensions/cocostudio/CCComAttribute.h index 1a47ff8d05..df368b8c46 100644 --- a/extensions/cocostudio/CCComAttribute.h +++ b/extensions/cocostudio/CCComAttribute.h @@ -54,15 +54,15 @@ public: virtual bool init() override; virtual bool serialize(void* r) override; - void setInt(const std::string& key, int value); - void setFloat(const std::string& key, float value); - void setBool(const std::string& key, bool value); - void setString(const std::string& key, const std::string& value); - int getInt(const std::string& key, int def = 0) const; - float getFloat(const std::string& key, float def = 0.0f) const; - bool getBool(const std::string& key, bool def = false) const; - std::string getString(const std::string& key, const std::string& def = "") const; - bool parse(const std::string& jsonFile); + void setInt(std::string_view key, int value); + void setFloat(std::string_view key, float value); + void setBool(std::string_view key, bool value); + void setString(std::string_view key, std::string_view value); + int getInt(std::string_view key, int def = 0) const; + float getFloat(std::string_view key, float def = 0.0f) const; + bool getBool(std::string_view key, bool def = false) const; + std::string getString(std::string_view key, std::string_view def = "") const; + bool parse(std::string_view jsonFile); private: cocos2d::ValueMap _dict; diff --git a/extensions/cocostudio/CCComExtensionData.h b/extensions/cocostudio/CCComExtensionData.h index 0c5dcb7de0..9735491506 100644 --- a/extensions/cocostudio/CCComExtensionData.h +++ b/extensions/cocostudio/CCComExtensionData.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2015 cocos2d-x.org http://www.cocos2d-x.org @@ -69,7 +69,7 @@ public: static ComExtensionData* create(); virtual bool init() override; - virtual void setCustomProperty(const std::string& customProperty) { _customProperty = customProperty; } + virtual void setCustomProperty(std::string_view customProperty) { _customProperty = customProperty; } virtual std::string getCustomProperty() const { return _customProperty; }; virtual void setActionTag(int actionTag); diff --git a/extensions/cocostudio/CCComRender.cpp b/extensions/cocostudio/CCComRender.cpp index ad2262cf8d..74cf487a8b 100644 --- a/extensions/cocostudio/CCComRender.cpp +++ b/extensions/cocostudio/CCComRender.cpp @@ -383,7 +383,7 @@ ComRender* ComRender::create(cocos2d::Node* node, const char* comName) return ret; } -bool ComRender::readJson(const std::string& fileName, rapidjson::Document& doc) +bool ComRender::readJson(std::string_view fileName, rapidjson::Document& doc) { bool ret = false; do diff --git a/extensions/cocostudio/CCComRender.h b/extensions/cocostudio/CCComRender.h index 83bc28e58f..de0aaeebb1 100644 --- a/extensions/cocostudio/CCComRender.h +++ b/extensions/cocostudio/CCComRender.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -79,7 +79,7 @@ public: virtual ~ComRender(); private: - bool readJson(const std::string& fileName, rapidjson::Document& doc); + bool readJson(std::string_view fileName, rapidjson::Document& doc); cocos2d::Node* _render; }; diff --git a/extensions/cocostudio/CCDataReaderHelper.cpp b/extensions/cocostudio/CCDataReaderHelper.cpp index 7cd5acea54..9dee7de590 100644 --- a/extensions/cocostudio/CCDataReaderHelper.cpp +++ b/extensions/cocostudio/CCDataReaderHelper.cpp @@ -133,7 +133,7 @@ static const char* COLOR_INFO = "color"; static const char* CONFIG_FILE_PATH = "config_file_path"; static const char* CONTENT_SCALE = "content_scale"; -static std::string readFileContent(const std::string& filename, bool binary) +static std::string readFileContent(std::string_view filename, bool binary) { auto fs = FileUtils::getInstance(); std::string s; @@ -264,7 +264,7 @@ DataReaderHelper::~DataReaderHelper() _dataReaderHelper = nullptr; } -void DataReaderHelper::addDataFromFile(const std::string& filePath) +void DataReaderHelper::addDataFromFile(std::string_view filePath) { /* * Check if file is already added to ArmatureDataManager, if then return. @@ -319,9 +319,9 @@ void DataReaderHelper::addDataFromFile(const std::string& filePath) } } -void DataReaderHelper::addDataFromFileAsync(const std::string& imagePath, - const std::string& plistPath, - const std::string& filePath, +void DataReaderHelper::addDataFromFileAsync(std::string_view imagePath, + std::string_view plistPath, + std::string_view filePath, Ref* target, SEL_SCHEDULE selector) { @@ -490,7 +490,7 @@ void DataReaderHelper::addDataAsyncCallBack(float /*dt*/) } } -void DataReaderHelper::removeConfigFile(const std::string& configFile) +void DataReaderHelper::removeConfigFile(std::string_view configFile) { auto it_end = _configFileList.end(); for (auto it = _configFileList.begin(); it != it_end; ++it) @@ -503,7 +503,7 @@ void DataReaderHelper::removeConfigFile(const std::string& configFile) } } -void DataReaderHelper::addDataFromCache(const std::string& pFileContent, DataInfo* dataInfo) +void DataReaderHelper::addDataFromCache(std::string_view pFileContent, DataInfo* dataInfo) { pugi::xml_document document; document.load_string(pFileContent.c_str()); @@ -1116,7 +1116,7 @@ ContourData* DataReaderHelper::decodeContour(pugi::xml_node& contourXML, DataInf return contourData; } -void DataReaderHelper::addDataFromJsonCache(const std::string& fileContent, DataInfo* dataInfo) +void DataReaderHelper::addDataFromJsonCache(std::string_view fileContent, DataInfo* dataInfo) { rapidjson::Document json; rapidjson::StringStream stream(fileContent.c_str()); diff --git a/extensions/cocostudio/CCDataReaderHelper.h b/extensions/cocostudio/CCDataReaderHelper.h index aa511c27ab..b3437f7cb6 100644 --- a/extensions/cocostudio/CCDataReaderHelper.h +++ b/extensions/cocostudio/CCDataReaderHelper.h @@ -114,16 +114,16 @@ public: */ ~DataReaderHelper(); - void addDataFromFile(const std::string& filePath); - void addDataFromFileAsync(const std::string& imagePath, - const std::string& plistPath, - const std::string& filePath, + void addDataFromFile(std::string_view filePath); + void addDataFromFileAsync(std::string_view imagePath, + std::string_view plistPath, + std::string_view filePath, cocos2d::Ref* target, cocos2d::SEL_SCHEDULE selector); void addDataAsyncCallBack(float dt); - void removeConfigFile(const std::string& configFile); + void removeConfigFile(std::string_view configFile); public: /** @@ -132,7 +132,7 @@ public: * * @param xmlPath The cache of the xml */ - static void addDataFromCache(const std::string& pFileContent, DataInfo* dataInfo = nullptr); + static void addDataFromCache(std::string_view pFileContent, DataInfo* dataInfo = nullptr); /** * Decode Armature Datas from xml export from Dragon Bone flash tool @@ -166,7 +166,7 @@ public: static ContourData* decodeContour(pugi::xml_node& contourXML, DataInfo* dataInfo); public: - static void addDataFromJsonCache(const std::string& fileContent, DataInfo* dataInfo = nullptr); + static void addDataFromJsonCache(std::string_view fileContent, DataInfo* dataInfo = nullptr); static ArmatureData* decodeArmature(const rapidjson::Value& json, DataInfo* dataInfo); static BoneData* decodeBone(const rapidjson::Value& json, DataInfo* dataInfo); diff --git a/extensions/cocostudio/CCDatas.cpp b/extensions/cocostudio/CCDatas.cpp index ff8d44569d..65b5cada2e 100644 --- a/extensions/cocostudio/CCDatas.cpp +++ b/extensions/cocostudio/CCDatas.cpp @@ -136,7 +136,7 @@ Color4B BaseData::getColor() return Color4B(r, g, b, a); } -std::string DisplayData::changeDisplayToTexture(const std::string& displayName) +std::string DisplayData::changeDisplayToTexture(std::string_view displayName) { // remove .xxx std::string textureName = displayName; @@ -216,7 +216,7 @@ void ArmatureData::addBoneData(BoneData* boneData) boneDataDic.insert(boneData->name, boneData); } -BoneData* ArmatureData::getBoneData(const std::string& boneName) +BoneData* ArmatureData::getBoneData(std::string_view boneName) { return static_cast(boneDataDic.at(boneName)); } @@ -305,7 +305,7 @@ void MovementData::addMovementBoneData(MovementBoneData* movBoneData) movBoneDataDic.insert(movBoneData->name, movBoneData); } -MovementBoneData* MovementData::getMovementBoneData(const std::string& boneName) +MovementBoneData* MovementData::getMovementBoneData(std::string_view boneName) { return movBoneDataDic.at(boneName); } @@ -320,7 +320,7 @@ void AnimationData::addMovement(MovementData* movData) movementNames.push_back(movData->name); } -MovementData* AnimationData::getMovement(const std::string& movementName) +MovementData* AnimationData::getMovement(std::string_view movementName) { return movementDataDic.at(movementName); } diff --git a/extensions/cocostudio/CCDatas.h b/extensions/cocostudio/CCDatas.h index 08985516ec..e0ed53be05 100644 --- a/extensions/cocostudio/CCDatas.h +++ b/extensions/cocostudio/CCDatas.h @@ -140,7 +140,7 @@ class CCS_DLL DisplayData : public cocos2d::Ref public: CC_CREATE_NO_PARAM_NO_INIT(DisplayData) - static std::string changeDisplayToTexture(const std::string& displayName); + static std::string changeDisplayToTexture(std::string_view displayName); public: /** @@ -282,7 +282,7 @@ public: bool init(); void addBoneData(BoneData* boneData); - BoneData* getBoneData(const std::string& boneName); + BoneData* getBoneData(std::string_view boneName); public: std::string name; @@ -409,7 +409,7 @@ public: ~MovementData(void); void addMovementBoneData(MovementBoneData* movBoneData); - MovementBoneData* getMovementBoneData(const std::string& boneName); + MovementBoneData* getMovementBoneData(std::string_view boneName); public: std::string name; @@ -443,7 +443,7 @@ public: /** * @brief save movement bone data - * @key const std::string& + * @key std::string_view * @value MovementBoneData * */ cocos2d::Map movBoneDataDic; @@ -472,7 +472,7 @@ public: ~AnimationData(void); void addMovement(MovementData* movData); - MovementData* getMovement(const std::string& movementName); + MovementData* getMovement(std::string_view movementName); ssize_t getMovementCount(); public: diff --git a/extensions/cocostudio/CCDisplayManager.cpp b/extensions/cocostudio/CCDisplayManager.cpp index f5a4377d04..7fdd2bc7ab 100644 --- a/extensions/cocostudio/CCDisplayManager.cpp +++ b/extensions/cocostudio/CCDisplayManager.cpp @@ -239,7 +239,7 @@ void DisplayManager::changeDisplayWithIndex(int index, bool force) setCurrentDecorativeDisplay(decoDisplay); } -void DisplayManager::changeDisplayWithName(const std::string& name, bool force) +void DisplayManager::changeDisplayWithName(std::string_view name, bool force) { for (int i = 0; i < _decoDisplayList.size(); i++) { diff --git a/extensions/cocostudio/CCDisplayManager.h b/extensions/cocostudio/CCDisplayManager.h index 1e32d8f7a7..f43fb13e56 100644 --- a/extensions/cocostudio/CCDisplayManager.h +++ b/extensions/cocostudio/CCDisplayManager.h @@ -80,7 +80,7 @@ public: * @deprecated, please use changeDisplayWithIndex and changeDisplayWithName */ CC_DEPRECATED_ATTRIBUTE void changeDisplayByIndex(int index, bool force); - CC_DEPRECATED_ATTRIBUTE void changeDisplayByName(const std::string& name, bool force); + CC_DEPRECATED_ATTRIBUTE void changeDisplayByName(std::string_view name, bool force); /** * Change display by index. You can just use this method to change display in the display list. @@ -93,7 +93,7 @@ public: * index edit in the flash every key frame. */ void changeDisplayWithIndex(int index, bool force); - void changeDisplayWithName(const std::string& name, bool force); + void changeDisplayWithName(std::string_view name, bool force); cocos2d::Node* getDisplayRenderNode() const; DisplayType getDisplayRenderNodeType() const; diff --git a/extensions/cocostudio/CCSGUIReader.cpp b/extensions/cocostudio/CCSGUIReader.cpp index 0855bb102a..f2a0845df6 100644 --- a/extensions/cocostudio/CCSGUIReader.cpp +++ b/extensions/cocostudio/CCSGUIReader.cpp @@ -160,7 +160,7 @@ cocos2d::Size GUIReader::getFileDesignSize(const char* fileName) const return Size(w, h); } -void GUIReader::registerTypeAndCallBack(const std::string& classType, +void GUIReader::registerTypeAndCallBack(std::string_view classType, ObjectFactory::Instance ins, Ref* object, SEL_ParseEvent callBack) @@ -181,7 +181,7 @@ void GUIReader::registerTypeAndCallBack(const std::string& classType, } } -void GUIReader::registerTypeAndCallBack(const std::string& classType, +void GUIReader::registerTypeAndCallBack(std::string_view classType, ObjectFactory::InstanceFunc ins, Ref* object, SEL_ParseEvent callBack) @@ -309,7 +309,7 @@ std::string WidgetPropertiesReader::getWidgetReaderClassName(Widget* widget) return readerName; } -std::string WidgetPropertiesReader::getGUIClassName(const std::string& name) +std::string WidgetPropertiesReader::getGUIClassName(std::string_view name) { std::string convertedClassName = name; if (name == "Panel") @@ -340,7 +340,7 @@ std::string WidgetPropertiesReader::getGUIClassName(const std::string& name) return convertedClassName; } -cocos2d::ui::Widget* WidgetPropertiesReader::createGUI(const std::string& classname) +cocos2d::ui::Widget* WidgetPropertiesReader::createGUI(std::string_view classname) { std::string name = this->getGUIClassName(classname); @@ -349,7 +349,7 @@ cocos2d::ui::Widget* WidgetPropertiesReader::createGUI(const std::string& classn return dynamic_cast(object); } -WidgetReaderProtocol* WidgetPropertiesReader::createWidgetReaderProtocol(const std::string& classname) +WidgetReaderProtocol* WidgetPropertiesReader::createWidgetReaderProtocol(std::string_view classname) { Ref* object = ObjectFactory::getInstance()->createObject(classname); @@ -426,7 +426,7 @@ Widget* GUIReader::widgetFromBinaryFile(const char* fileName) return widget; } -std::string WidgetPropertiesReader::getWidgetReaderClassName(const std::string& classname) +std::string WidgetPropertiesReader::getWidgetReaderClassName(std::string_view classname) { // create widget reader to parse properties of widget std::string readerName = classname; @@ -1240,7 +1240,7 @@ void WidgetPropertiesReader0250::setPropsForAllWidgetFromJsonDictionary(WidgetRe const rapidjson::Value& /*options*/) {} -void WidgetPropertiesReader0250::setPropsForAllCustomWidgetFromJsonDictionary(const std::string& /*classType*/, +void WidgetPropertiesReader0250::setPropsForAllCustomWidgetFromJsonDictionary(std::string_view /*classType*/, cocos2d::ui::Widget* /*widget*/, const rapidjson::Value& /*customOptions*/) {} @@ -1542,7 +1542,7 @@ void WidgetPropertiesReader0300::setPropsForAllWidgetFromBinary(WidgetReaderProt reader->setPropsFromBinary(widget, cocoLoader, cocoNode); } -void WidgetPropertiesReader0300::setPropsForAllCustomWidgetFromBinary(const std::string& /*classType*/, +void WidgetPropertiesReader0300::setPropsForAllCustomWidgetFromBinary(std::string_view /*classType*/, cocos2d::ui::Widget* /*widget*/, CocoLoader* /*cocoLoader*/, stExpCocoNode* /*pCocoNode*/) @@ -1637,7 +1637,7 @@ void WidgetPropertiesReader0300::setPropsForAllWidgetFromJsonDictionary(WidgetRe reader->setPropsFromJsonDictionary(widget, options); } -void WidgetPropertiesReader0300::setPropsForAllCustomWidgetFromJsonDictionary(const std::string& classType, +void WidgetPropertiesReader0300::setPropsForAllCustomWidgetFromJsonDictionary(std::string_view classType, cocos2d::ui::Widget* widget, const rapidjson::Value& customOptions) { diff --git a/extensions/cocostudio/CCSGUIReader.h b/extensions/cocostudio/CCSGUIReader.h index 5c277866cc..1de130dd4d 100644 --- a/extensions/cocostudio/CCSGUIReader.h +++ b/extensions/cocostudio/CCSGUIReader.h @@ -76,15 +76,15 @@ public: */ cocos2d::Size getFileDesignSize(const char* fileName) const; - void setFilePath(const std::string& strFilePath) { m_strFilePath = strFilePath; } - const std::string& getFilePath() const { return m_strFilePath; } + void setFilePath(std::string_view strFilePath) { m_strFilePath = strFilePath; } + std::string_view getFilePath() const { return m_strFilePath; } - void registerTypeAndCallBack(const std::string& classType, + void registerTypeAndCallBack(std::string_view classType, cocos2d::ObjectFactory::Instance ins, Ref* object, SEL_ParseEvent callBack); - void registerTypeAndCallBack(const std::string& classType, + void registerTypeAndCallBack(std::string_view classType, cocos2d::ObjectFactory::InstanceFunc ins, Ref* object, SEL_ParseEvent callBack); @@ -118,7 +118,7 @@ public: cocos2d::ui::Widget* widget, const rapidjson::Value& options) = 0; - virtual void setPropsForAllCustomWidgetFromJsonDictionary(const std::string& classType, + virtual void setPropsForAllCustomWidgetFromJsonDictionary(std::string_view classType, cocos2d::ui::Widget* widget, const rapidjson::Value& customOptions) = 0; @@ -134,12 +134,12 @@ public: protected: void setAnchorPointForWidget(cocos2d::ui::Widget* widget, const rapidjson::Value& options); - std::string getWidgetReaderClassName(const std::string& classname); + std::string getWidgetReaderClassName(std::string_view classname); std::string getWidgetReaderClassName(cocos2d::ui::Widget* widget); - std::string getGUIClassName(const std::string& name); - cocos2d::ui::Widget* createGUI(const std::string& classname); - WidgetReaderProtocol* createWidgetReaderProtocol(const std::string& classname); + std::string getGUIClassName(std::string_view name); + cocos2d::ui::Widget* createGUI(std::string_view classname); + WidgetReaderProtocol* createWidgetReaderProtocol(std::string_view classname); protected: std::string m_strFilePath; @@ -189,7 +189,7 @@ public: virtual void setPropsForAllWidgetFromJsonDictionary(WidgetReaderProtocol* reader, cocos2d::ui::Widget* widget, const rapidjson::Value& options) override; - virtual void setPropsForAllCustomWidgetFromJsonDictionary(const std::string& classType, + virtual void setPropsForAllCustomWidgetFromJsonDictionary(std::string_view classType, cocos2d::ui::Widget* widget, const rapidjson::Value& customOptions) override; }; @@ -217,7 +217,7 @@ public: CocoLoader* cocoLoader, stExpCocoNode* pCocoNode) override; - virtual void setPropsForAllCustomWidgetFromBinary(const std::string& classType, + virtual void setPropsForAllCustomWidgetFromBinary(std::string_view classType, cocos2d::ui::Widget* widget, CocoLoader* cocoLoader, stExpCocoNode* pCocoNode); @@ -228,7 +228,7 @@ public: cocos2d::ui::Widget* widget, const rapidjson::Value& options) override; - virtual void setPropsForAllCustomWidgetFromJsonDictionary(const std::string& classType, + virtual void setPropsForAllCustomWidgetFromJsonDictionary(std::string_view classType, cocos2d::ui::Widget* widget, const rapidjson::Value& customOptions) override; }; diff --git a/extensions/cocostudio/CCSSceneReader.cpp b/extensions/cocostudio/CCSSceneReader.cpp index 477341309d..f69c5e05dd 100644 --- a/extensions/cocostudio/CCSSceneReader.cpp +++ b/extensions/cocostudio/CCSSceneReader.cpp @@ -54,7 +54,7 @@ const char* SceneReader::sceneReaderVersion() } cocos2d::Node* SceneReader::createNodeWithSceneFile( - const std::string& fileName, + std::string_view fileName, AttachComponentType attachComponent /*= AttachComponentType::EMPTY_NODE*/) { std::string fileExtension = cocos2d::FileUtils::getInstance()->getFileExtension(fileName); @@ -166,7 +166,7 @@ cocos2d::Node* SceneReader::createNodeWithSceneFile( return nullptr; } -bool SceneReader::readJson(const std::string& fileName, rapidjson::Document& doc) +bool SceneReader::readJson(std::string_view fileName, rapidjson::Document& doc) { bool ret = false; do @@ -210,14 +210,14 @@ Node* SceneReader::nodeByTag(Node* parent, int tag) return _retNode; } -cocos2d::Component* SceneReader::createComponent(const std::string& classname) +cocos2d::Component* SceneReader::createComponent(std::string_view classname) { std::string name = this->getComponentClassName(classname); Ref* object = ObjectFactory::getInstance()->createObject(name); return dynamic_cast(object); } -std::string SceneReader::getComponentClassName(const std::string& name) +std::string SceneReader::getComponentClassName(std::string_view name) { std::string comName; if (name == "CCSprite" || name == "CCTMXTiledMap" || name == "CCParticleSystemQuad" || name == "CCArmature" || diff --git a/extensions/cocostudio/CCSSceneReader.h b/extensions/cocostudio/CCSSceneReader.h index 90163ac7e5..4cb2e599b2 100644 --- a/extensions/cocostudio/CCSSceneReader.h +++ b/extensions/cocostudio/CCSSceneReader.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. Copyright (c) 2021 Bytedance Inc. @@ -61,7 +61,7 @@ public: */ static void destroyInstance(); static const char* sceneReaderVersion(); - cocos2d::Node* createNodeWithSceneFile(const std::string& fileName, + cocos2d::Node* createNodeWithSceneFile(std::string_view fileName, AttachComponentType attachComponent = AttachComponentType::EMPTY_NODE); void setTarget(const std::function& selector); cocos2d::Node* getNodeByTag(int nTag); @@ -70,15 +70,15 @@ public: virtual ~SceneReader(); private: - std::string getComponentClassName(const std::string& name); + std::string getComponentClassName(std::string_view name); - cocos2d::Component* createComponent(const std::string& classname); + cocos2d::Component* createComponent(std::string_view classname); cocos2d::Node* createObject(const rapidjson::Value& dict, cocos2d::Node* parent, AttachComponentType attachComponent); void setPropertyFromJsonDict(const rapidjson::Value& dict, cocos2d::Node* node); - bool readJson(const std::string& fileName, rapidjson::Document& doc); + bool readJson(std::string_view fileName, rapidjson::Document& doc); cocos2d::Node* createObject(CocoLoader* cocoLoader, stExpCocoNode* cocoNode, diff --git a/extensions/cocostudio/CCSkin.cpp b/extensions/cocostudio/CCSkin.cpp index 253354a235..8287a412bf 100644 --- a/extensions/cocostudio/CCSkin.cpp +++ b/extensions/cocostudio/CCSkin.cpp @@ -55,7 +55,7 @@ Skin* Skin::create() return nullptr; } -Skin* Skin::createWithSpriteFrameName(const std::string& pszSpriteFrameName) +Skin* Skin::createWithSpriteFrameName(std::string_view pszSpriteFrameName) { Skin* skin = new Skin(); if (skin->initWithSpriteFrameName(pszSpriteFrameName)) @@ -67,7 +67,7 @@ Skin* Skin::createWithSpriteFrameName(const std::string& pszSpriteFrameName) return nullptr; } -Skin* Skin::create(const std::string& pszFileName) +Skin* Skin::create(std::string_view pszFileName) { Skin* skin = new Skin(); if (skin->initWithFile(pszFileName)) @@ -81,7 +81,7 @@ Skin* Skin::create(const std::string& pszFileName) Skin::Skin() : _bone(nullptr), _armature(nullptr), _displayName(), _skinTransform(Mat4::IDENTITY) {} -bool Skin::initWithSpriteFrameName(const std::string& spriteFrameName) +bool Skin::initWithSpriteFrameName(std::string_view spriteFrameName) { CCAssert(spriteFrameName != "", ""); @@ -103,7 +103,7 @@ bool Skin::initWithSpriteFrameName(const std::string& spriteFrameName) return ret; } -bool Skin::initWithFile(const std::string& filename) +bool Skin::initWithFile(std::string_view filename) { bool ret = Sprite::initWithFile(filename); diff --git a/extensions/cocostudio/CCSkin.h b/extensions/cocostudio/CCSkin.h index 74046b428a..f1b0fc40b1 100644 --- a/extensions/cocostudio/CCSkin.h +++ b/extensions/cocostudio/CCSkin.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -39,8 +39,8 @@ class CCS_DLL Skin : public cocos2d::Sprite { public: static Skin* create(); - static Skin* createWithSpriteFrameName(const std::string& pszSpriteFrameName); - static Skin* create(const std::string& pszFileName); + static Skin* createWithSpriteFrameName(std::string_view pszSpriteFrameName); + static Skin* create(std::string_view pszFileName); public: /** @@ -48,8 +48,8 @@ public: */ Skin(); - virtual bool initWithSpriteFrameName(const std::string& spriteFrameName) override; - virtual bool initWithFile(const std::string& filename) override; + virtual bool initWithSpriteFrameName(std::string_view spriteFrameName) override; + virtual bool initWithFile(std::string_view filename) override; void updateArmatureTransform(); void updateTransform() override; @@ -73,7 +73,7 @@ public: virtual void setBone(Bone* bone); virtual Bone* getBone() const; - virtual const std::string& getDisplayName() const { return _displayName; } + virtual std::string_view getDisplayName() const { return _displayName; } protected: BaseData _skinData; diff --git a/extensions/cocostudio/CCSpriteFrameCacheHelper.cpp b/extensions/cocostudio/CCSpriteFrameCacheHelper.cpp index ffa14bbaff..66f70f7552 100644 --- a/extensions/cocostudio/CCSpriteFrameCacheHelper.cpp +++ b/extensions/cocostudio/CCSpriteFrameCacheHelper.cpp @@ -50,7 +50,7 @@ void SpriteFrameCacheHelper::purge() _spriteFrameCacheHelper = nullptr; } -void SpriteFrameCacheHelper::retainSpriteFrames(const std::string& plistPath) +void SpriteFrameCacheHelper::retainSpriteFrames(std::string_view plistPath) { auto it = _usingSpriteFrames.find(plistPath); if (it != _usingSpriteFrames.end()) @@ -72,7 +72,7 @@ void SpriteFrameCacheHelper::retainSpriteFrames(const std::string& plistPath) _usingSpriteFrames[plistPath] = vec; } -void SpriteFrameCacheHelper::releaseSpriteFrames(const std::string& plistPath) +void SpriteFrameCacheHelper::releaseSpriteFrames(std::string_view plistPath) { auto it = _usingSpriteFrames.find(plistPath); if (it == _usingSpriteFrames.end()) @@ -89,13 +89,13 @@ void SpriteFrameCacheHelper::releaseSpriteFrames(const std::string& plistPath) _usingSpriteFrames.erase(it); } -void SpriteFrameCacheHelper::removeSpriteFrameFromFile(const std::string& plistPath) +void SpriteFrameCacheHelper::removeSpriteFrameFromFile(std::string_view plistPath) { SpriteFrameCache::getInstance()->removeSpriteFramesFromFile(plistPath); releaseSpriteFrames(plistPath); } -void SpriteFrameCacheHelper::addSpriteFrameFromFile(const std::string& plistPath, const std::string& imagePath) +void SpriteFrameCacheHelper::addSpriteFrameFromFile(std::string_view plistPath, std::string_view imagePath) { SpriteFrameCache::getInstance()->addSpriteFramesWithFile(plistPath, imagePath); retainSpriteFrames(plistPath); diff --git a/extensions/cocostudio/CCSpriteFrameCacheHelper.h b/extensions/cocostudio/CCSpriteFrameCacheHelper.h index a24be27049..0c84294e68 100644 --- a/extensions/cocostudio/CCSpriteFrameCacheHelper.h +++ b/extensions/cocostudio/CCSpriteFrameCacheHelper.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -60,12 +60,12 @@ public: /** * @brief Add sprite frame to CCSpriteFrameCache, it will save display name and it's relative image name */ - void addSpriteFrameFromFile(const std::string& plistPath, const std::string& imagePath); - void removeSpriteFrameFromFile(const std::string& plistPath); + void addSpriteFrameFromFile(std::string_view plistPath, std::string_view imagePath); + void removeSpriteFrameFromFile(std::string_view plistPath); private: - void retainSpriteFrames(const std::string& plistPath); - void releaseSpriteFrames(const std::string& plistPath); + void retainSpriteFrames(std::string_view plistPath); + void releaseSpriteFrames(std::string_view plistPath); SpriteFrameCacheHelper(); ~SpriteFrameCacheHelper(); diff --git a/extensions/cocostudio/FlatBuffersSerialize.cpp b/extensions/cocostudio/FlatBuffersSerialize.cpp index 1ca0006455..8d064ea849 100644 --- a/extensions/cocostudio/FlatBuffersSerialize.cpp +++ b/extensions/cocostudio/FlatBuffersSerialize.cpp @@ -141,8 +141,8 @@ void FlatBuffersSerialize::deleteFlatBufferBuilder() } } -std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFile(const std::string& xmlFileName, - const std::string& flatbuffersFileName) +std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFile(std::string_view xmlFileName, + std::string_view flatbuffersFileName) { std::string inFullpath = FileUtils::getInstance()->fullPathForFilename(xmlFileName).c_str(); @@ -157,7 +157,7 @@ std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFile(const std::str } std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLBuffer(std::string& xmlBuffer, - const std::string& flatbuffersFileName) + std::string_view flatbuffersFileName) { // xml parse pugi::xml_document document; @@ -168,7 +168,7 @@ std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLBuffer(std::string& return ""; } -std::string FlatBuffersSerialize::serializeFlatBuffersWithOpaque(void* opaque, const std::string& flatbuffersFileName) +std::string FlatBuffersSerialize::serializeFlatBuffersWithOpaque(void* opaque, std::string_view flatbuffersFileName) { auto thiz = FlatBuffersSerialize::getInstance(); @@ -451,7 +451,7 @@ int FlatBuffersSerialize::getResourceType(std::string key) return 1; } -std::string FlatBuffersSerialize::getGUIClassName(const std::string& name) +std::string FlatBuffersSerialize::getGUIClassName(std::string_view name) { std::string convertedClassName = name; if (name == "Panel") @@ -1231,7 +1231,7 @@ flatbuffers::Offset FlatBuffersSerialize::createEasingD } /* create flat buffers with XML */ -FlatBufferBuilder* FlatBuffersSerialize::createFlatBuffersWithXMLFileForSimulator(const std::string& xmlFileName) +FlatBufferBuilder* FlatBuffersSerialize::createFlatBuffersWithXMLFileForSimulator(std::string_view xmlFileName) { std::string inFullpath = FileUtils::getInstance()->fullPathForFilename(xmlFileName); @@ -1520,9 +1520,9 @@ Offset FlatBuffersSerialize::createProjectNodeOptionsForSimu } /* Serialize language XML file to Flat Buffers file. */ -std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFileForLanguageData(const std::string& xmlFilePath, - const std::string& flatBuffersFilePath, - const std::string& languageName) +std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFileForLanguageData(std::string_view xmlFilePath, + std::string_view flatBuffersFilePath, + std::string_view languageName) { // Read and parse XML data file. if (!FileUtils::getInstance()->isFileExist(xmlFilePath)) diff --git a/extensions/cocostudio/FlatBuffersSerialize.h b/extensions/cocostudio/FlatBuffersSerialize.h index 21582b2c62..6a09988396 100644 --- a/extensions/cocostudio/FlatBuffersSerialize.h +++ b/extensions/cocostudio/FlatBuffersSerialize.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013 cocos2d-x.org http://www.cocos2d-x.org @@ -105,15 +105,15 @@ public: void deleteFlatBufferBuilder(); - std::string test(const std::string& xmlFileName, const std::string& flatbuffersFileName); + std::string test(std::string_view xmlFileName, std::string_view flatbuffersFileName); /* serialize flat buffers with XML */ - static std::string serializeFlatBuffersWithXMLFile(const std::string& xmlFileName, - const std::string& flatbuffersFileName); + static std::string serializeFlatBuffersWithXMLFile(std::string_view xmlFileName, + std::string_view flatbuffersFileName); /* x-studio spec: serialize flat buffers with XML buffer */ static std::string serializeFlatBuffersWithXMLBuffer(std::string& xmlBuffer, - const std::string& flatbuffersFileName); - static std::string serializeFlatBuffersWithOpaque(void* opaque, const std::string& flatbuffersFileName); + std::string_view flatbuffersFileName); + static std::string serializeFlatBuffersWithOpaque(void* opaque, std::string_view flatbuffersFileName); // NodeTree flatbuffers::Offset createNodeTree(pugi::xml_node objectData, std::string classType); @@ -138,11 +138,11 @@ public: /**/ int getResourceType(std::string key); - std::string getGUIClassName(const std::string& name); + std::string getGUIClassName(std::string_view name); std::string getWidgetReaderClassName(cocos2d::ui::Widget* widget); /* create flat buffers with XML */ - flatbuffers::FlatBufferBuilder* createFlatBuffersWithXMLFileForSimulator(const std::string& xmlFileName); + flatbuffers::FlatBufferBuilder* createFlatBuffersWithXMLFileForSimulator(std::string_view xmlFileName); flatbuffers::Offset createNodeTreeForSimulator(pugi::xml_node objectData, std::string classType); flatbuffers::Offset createProjectNodeOptionsForSimulator( @@ -151,9 +151,9 @@ public: std::string getCsdVersion() { return _csdVersion; } /* Serialize language XML file to Flat Buffers file. */ - std::string serializeFlatBuffersWithXMLFileForLanguageData(const std::string& xmlFilePath, - const std::string& flatBuffersFilePath, - const std::string& languageName); + std::string serializeFlatBuffersWithXMLFileForLanguageData(std::string_view xmlFilePath, + std::string_view flatBuffersFilePath, + std::string_view languageName); public: std::vector> _textures; diff --git a/extensions/cocostudio/TriggerMng.cpp b/extensions/cocostudio/TriggerMng.cpp index 0ac9a3181d..39ccd44571 100644 --- a/extensions/cocostudio/TriggerMng.cpp +++ b/extensions/cocostudio/TriggerMng.cpp @@ -505,7 +505,7 @@ ArmatureMovementDispatcher::~ArmatureMovementDispatcher(void) void ArmatureMovementDispatcher::animationEvent(Armature* armature, MovementEventType movementType, - const std::string& movementID) + std::string_view movementID) { for (auto iter = _mapEventAnimation->begin(); iter != _mapEventAnimation->end(); ++iter) { diff --git a/extensions/cocostudio/TriggerMng.h b/extensions/cocostudio/TriggerMng.h index 30474d2a02..1830a67fe9 100644 --- a/extensions/cocostudio/TriggerMng.h +++ b/extensions/cocostudio/TriggerMng.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -46,7 +46,7 @@ public: public: void addAnimationEventCallBack(cocos2d::Ref* pTarget, SEL_MovementEventCallFunc mecf); void removeAnnimationEventCallBack(cocos2d::Ref* pTarget, SEL_MovementEventCallFunc mecf); - void animationEvent(Armature* armature, MovementEventType movementType, const std::string& movementID); + void animationEvent(Armature* armature, MovementEventType movementType, std::string_view movementID); private: std::unordered_map* _mapEventAnimation; diff --git a/extensions/cocostudio/WidgetCallBackHandlerProtocol.h b/extensions/cocostudio/WidgetCallBackHandlerProtocol.h index aae843e00e..dd423e63ba 100644 --- a/extensions/cocostudio/WidgetCallBackHandlerProtocol.h +++ b/extensions/cocostudio/WidgetCallBackHandlerProtocol.h @@ -36,9 +36,9 @@ class CCS_DLL WidgetCallBackHandlerProtocol public: virtual ~WidgetCallBackHandlerProtocol(); - virtual cocos2d::ui::Widget::ccWidgetTouchCallback onLocateTouchCallback(const std::string& callBackName); - virtual cocos2d::ui::Widget::ccWidgetClickCallback onLocateClickCallback(const std::string& callBackName); - virtual cocos2d::ui::Widget::ccWidgetEventCallback onLocateEventCallback(const std::string& callBackName); + virtual cocos2d::ui::Widget::ccWidgetTouchCallback onLocateTouchCallback(std::string_view callBackName); + virtual cocos2d::ui::Widget::ccWidgetClickCallback onLocateClickCallback(std::string_view callBackName); + virtual cocos2d::ui::Widget::ccWidgetEventCallback onLocateEventCallback(std::string_view callBackName); }; } // namespace cocostudio diff --git a/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.cpp b/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.cpp index 00861efbd7..2a4a68060a 100644 --- a/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.cpp +++ b/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.cpp @@ -230,7 +230,7 @@ cocos2d::Node* ArmatureNodeReader::createNodeWithFlatBuffers(const flatbuffers:: return node; } -std::string ArmatureNodeReader::getArmatureName(const std::string& exporJsonPath) +std::string ArmatureNodeReader::getArmatureName(std::string_view exporJsonPath) { // FileUtils.getFileData(exporJsonPath, "r", size) // need read armature name in exportJsonPath size_t end = exporJsonPath.find_last_of("."); diff --git a/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.h b/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.h index 3f7ae420b0..d37f2652ba 100644 --- a/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.h +++ b/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2014 cocos2d-x.org http://www.cocos2d-x.org @@ -59,7 +59,7 @@ public: cocos2d::Node* createNodeWithFlatBuffers(const flatbuffers::Table* nodeOptions) override; private: - std::string getArmatureName(const std::string& exporJsonPath); + std::string getArmatureName(std::string_view exporJsonPath); }; #endif /* defined(__ARMATURENODEREADER_H_) */ diff --git a/extensions/cocostudio/WidgetReader/ImageViewReader/ImageViewReader.cpp b/extensions/cocostudio/WidgetReader/ImageViewReader/ImageViewReader.cpp index 6e417fcca6..866d8d76c6 100644 --- a/extensions/cocostudio/WidgetReader/ImageViewReader/ImageViewReader.cpp +++ b/extensions/cocostudio/WidgetReader/ImageViewReader/ImageViewReader.cpp @@ -111,7 +111,7 @@ void ImageViewReader::setPropsFromJsonDictionary(Widget* widget, const rapidjson const rapidjson::Value& imageFileNameDic = DICTOOL->getSubDictionary_json(options, P_FileNameData); int imageFileNameType = DICTOOL->getIntValue_json(imageFileNameDic, P_ResourceType); - const std::string& imageFilePath = DICTOOL->getStringValue_json(imageFileNameDic, P_Path); + std::string_view imageFilePath = DICTOOL->getStringValue_json(imageFileNameDic, P_Path); if (!imageFilePath.empty()) { diff --git a/extensions/cocostudio/WidgetReader/NodeReaderProtocol.cpp b/extensions/cocostudio/WidgetReader/NodeReaderProtocol.cpp index 24997d4a98..31bcc5732a 100644 --- a/extensions/cocostudio/WidgetReader/NodeReaderProtocol.cpp +++ b/extensions/cocostudio/WidgetReader/NodeReaderProtocol.cpp @@ -30,7 +30,7 @@ static cocos2d::Node* createArmatureNode() return cocostudio::Armature::create(); } -static cocos2d::ParticleSystemQuad* createParticleSystemQuad(const std::string& path) +static cocos2d::ParticleSystemQuad* createParticleSystemQuad(std::string_view path) { return cocos2d::ParticleSystemQuad::create(path); } @@ -61,8 +61,8 @@ bool (*onAfterLoadObjectAsset)(cocos2d::Node*, cocos2d::ResourceData& assets, int index /*= 0*/) = &onLoadObjectAssetDummy; void (*onLoadSpriteFramesWithFile)(std::string& file) = nullptr; -void (*onNestingNodeLoading)(const std::string& filePath) = nullptr; -void (*onNestingNodeLoaded)(cocos2d::Node*, const std::string& filePath) = nullptr; +void (*onNestingNodeLoading)(std::string_view filePath) = nullptr; +void (*onNestingNodeLoaded)(cocos2d::Node*, std::string_view filePath) = nullptr; cocos2d::Node* (*aNode)(); cocos2d::ui::Widget* (*aWidget)(); cocos2d::Sprite* (*aSprite)(); @@ -137,7 +137,7 @@ cocos2d::ResourceData cocos2d::wext::makeResourceData(const flatbuffers::Resourc return fileData; } -cocos2d::ResourceData cocos2d::wext::makeResourceData(const std::string& path, int type) +cocos2d::ResourceData cocos2d::wext::makeResourceData(std::string_view path, int type) { cocos2d::ResourceData fileData; fileData.file = path; diff --git a/extensions/cocostudio/WidgetReader/NodeReaderProtocol.h b/extensions/cocostudio/WidgetReader/NodeReaderProtocol.h index 7276307498..a92a24135f 100644 --- a/extensions/cocostudio/WidgetReader/NodeReaderProtocol.h +++ b/extensions/cocostudio/WidgetReader/NodeReaderProtocol.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2014 cocos2d-x.org http://www.cocos2d-x.org @@ -141,7 +141,7 @@ CC_DLL extern APP_LOGERROR_FUNC getAppErrorLogFunc(); CCS_DLL extern void (*onLoadSpriteFramesWithFile)(std::string& file); CCS_DLL extern cocos2d::ResourceData makeResourceData(const flatbuffers::ResourceData* data); -CCS_DLL extern cocos2d::ResourceData makeResourceData(const std::string& path, int type = 0); +CCS_DLL extern cocos2d::ResourceData makeResourceData(std::string_view path, int type = 0); CCS_DLL extern cocos2d::ResourceData makeResourceData(std::string&& path, int type = 0); CCS_DLL extern void resetReaderAllHooks(); diff --git a/extensions/cocostudio/WidgetReader/WidgetReader.cpp b/extensions/cocostudio/WidgetReader/WidgetReader.cpp index e30e04d1c2..c9cbce0976 100644 --- a/extensions/cocostudio/WidgetReader/WidgetReader.cpp +++ b/extensions/cocostudio/WidgetReader/WidgetReader.cpp @@ -98,9 +98,9 @@ WidgetReader::WidgetReader() , _opacity(255) , _isAdaptScreen(false) { - valueToInt = [=](const std::string& str) -> int { return atoi(str.c_str()); }; + valueToInt = [=](std::string_view str) -> int { return atoi(str.c_str()); }; - valueToBool = [=](const std::string& str) -> bool { + valueToBool = [=](std::string_view str) -> bool { int intValue = valueToInt(str); if (1 == intValue) { @@ -112,7 +112,7 @@ WidgetReader::WidgetReader() } }; - valueToFloat = [=](const std::string& str) -> float { return utils::atof(str.c_str()); }; + valueToFloat = [=](std::string_view str) -> float { return utils::atof(str.c_str()); }; } WidgetReader::~WidgetReader() {} @@ -303,7 +303,7 @@ void WidgetReader::endSetBasicProperties(Widget* widget) } std::string WidgetReader::getResourcePath(const rapidjson::Value& dict, - const std::string& key, + std::string_view key, cocos2d::ui::Widget::TextureResType texType) { std::string jsonPath = GUIReader::getInstance()->getFilePath(); @@ -940,7 +940,7 @@ Node* WidgetReader::createNodeWithFlatBuffers(const flatbuffers::Table* widgetOp return widget; } -std::string WidgetReader::getResourcePath(const std::string& path, cocos2d::ui::Widget::TextureResType texType) +std::string WidgetReader::getResourcePath(std::string_view path, cocos2d::ui::Widget::TextureResType texType) { std::string filePath = GUIReader::getInstance()->getFilePath(); const char* imageFileName = path.c_str(); diff --git a/extensions/cocostudio/WidgetReader/WidgetReader.h b/extensions/cocostudio/WidgetReader/WidgetReader.h index fb5e60d3d9..e7641cdc39 100644 --- a/extensions/cocostudio/WidgetReader/WidgetReader.h +++ b/extensions/cocostudio/WidgetReader/WidgetReader.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2014 cocos2d-x.org http://www.cocos2d-x.org @@ -66,7 +66,7 @@ public: protected: std::string getResourcePath(const rapidjson::Value& dict, - const std::string& key, + std::string_view key, cocos2d::ui::Widget::TextureResType texType); void setAnchorPointForWidget(cocos2d::ui::Widget* widget, const rapidjson::Value& options); @@ -74,7 +74,7 @@ protected: stExpCocoNode* pCocoNode, cocos2d::ui::Widget::TextureResType texType); - std::string getResourcePath(const std::string& path, cocos2d::ui::Widget::TextureResType texType); + std::string getResourcePath(std::string_view path, cocos2d::ui::Widget::TextureResType texType); void beginSetBasicProperties(cocos2d::ui::Widget* widget); void endSetBasicProperties(cocos2d::ui::Widget* widget); diff --git a/extensions/scripting/lua-bindings/manual/CCComponentLua.cpp b/extensions/scripting/lua-bindings/manual/CCComponentLua.cpp index 1118e57d2d..5ff34e083b 100644 --- a/extensions/scripting/lua-bindings/manual/CCComponentLua.cpp +++ b/extensions/scripting/lua-bindings/manual/CCComponentLua.cpp @@ -63,7 +63,7 @@ void adjustScriptFileName(std::string& scriptFileName) int ComponentLua::_index = 0; -ComponentLua* ComponentLua::create(const std::string& scriptFileName) +ComponentLua* ComponentLua::create(std::string_view scriptFileName) { CC_ASSERT(!scriptFileName.empty()); @@ -79,7 +79,7 @@ ComponentLua* ComponentLua::create(const std::string& scriptFileName) return componentLua; } -ComponentLua::ComponentLua(const std::string& scriptFileName) +ComponentLua::ComponentLua(std::string_view scriptFileName) : _scriptFileName(scriptFileName), _table(nullptr), _strIndex("") { _succeedLoadingScript = loadAndExecuteScript(); @@ -134,7 +134,7 @@ void ComponentLua::onExit() } } -bool ComponentLua::getLuaFunction(const std::string& functionName) +bool ComponentLua::getLuaFunction(std::string_view functionName) { lua_State* l = LuaEngine::getInstance()->getLuaStack()->getLuaState(); diff --git a/extensions/scripting/lua-bindings/manual/CCComponentLua.h b/extensions/scripting/lua-bindings/manual/CCComponentLua.h index 4a2425987b..5f17a086d3 100644 --- a/extensions/scripting/lua-bindings/manual/CCComponentLua.h +++ b/extensions/scripting/lua-bindings/manual/CCComponentLua.h @@ -34,9 +34,9 @@ NS_CC_BEGIN class ComponentLua : public Component { public: - static ComponentLua* create(const std::string& scriptFileName); + static ComponentLua* create(std::string_view scriptFileName); - ComponentLua(const std::string& scriptFileName); + ComponentLua(std::string_view scriptFileName); /** * This function is used to be invoked from lua side to get the corresponding script object of this component. */ @@ -52,7 +52,7 @@ private: bool loadAndExecuteScript(); void getUserData(); void storeLuaTable(); - bool getLuaFunction(const std::string& functionName); + bool getLuaFunction(std::string_view functionName); void removeLuaTable(); static void initClass(); diff --git a/extensions/scripting/lua-bindings/manual/CCLuaEngine.cpp b/extensions/scripting/lua-bindings/manual/CCLuaEngine.cpp index c474533f3c..4c50e1489f 100644 --- a/extensions/scripting/lua-bindings/manual/CCLuaEngine.cpp +++ b/extensions/scripting/lua-bindings/manual/CCLuaEngine.cpp @@ -174,7 +174,7 @@ int LuaEngine::reallocateScriptHandler(int nHandler) return nRet; } -bool LuaEngine::parseConfig(ConfigType type, const std::string& str) +bool LuaEngine::parseConfig(ConfigType type, std::string_view str) { lua_getglobal(_stack->getLuaState(), "__onParseConfig"); if (!lua_isfunction(_stack->getLuaState(), -1)) diff --git a/extensions/scripting/lua-bindings/manual/CCLuaEngine.h b/extensions/scripting/lua-bindings/manual/CCLuaEngine.h index dbaf44d04c..233543b72f 100644 --- a/extensions/scripting/lua-bindings/manual/CCLuaEngine.h +++ b/extensions/scripting/lua-bindings/manual/CCLuaEngine.h @@ -188,7 +188,7 @@ public: * @return if __onParseConfig function exist in the Lua, it return the value that _stack->executeFunction returns * otherwise return false. */ - virtual bool parseConfig(ConfigType type, const std::string& str) override; + virtual bool parseConfig(ConfigType type, std::string_view str) override; /** * When some events triggered in the c++ also needs to pass on to lua to handle, we could call this function to send diff --git a/extensions/scripting/lua-bindings/manual/CCLuaValue.cpp b/extensions/scripting/lua-bindings/manual/CCLuaValue.cpp index 6bb23e16e1..06081839b8 100644 --- a/extensions/scripting/lua-bindings/manual/CCLuaValue.cpp +++ b/extensions/scripting/lua-bindings/manual/CCLuaValue.cpp @@ -60,7 +60,7 @@ const LuaValue LuaValue::stringValue(const char* stringValue) return value; } -const LuaValue LuaValue::stringValue(const std::string& stringValue) +const LuaValue LuaValue::stringValue(std::string_view stringValue) { LuaValue value; value._type = LuaValueTypeString; @@ -94,7 +94,7 @@ const LuaValue LuaValue::ccobjectValue(Ref* ccobjectValue, const char* objectTyp return value; } -const LuaValue LuaValue::ccobjectValue(Ref* ccobjectValue, const std::string& objectTypename) +const LuaValue LuaValue::ccobjectValue(Ref* ccobjectValue, std::string_view objectTypename) { return LuaValue::ccobjectValue(ccobjectValue, objectTypename.c_str()); } diff --git a/extensions/scripting/lua-bindings/manual/CCLuaValue.h b/extensions/scripting/lua-bindings/manual/CCLuaValue.h index 0997bdbf43..8b918263e1 100644 --- a/extensions/scripting/lua-bindings/manual/CCLuaValue.h +++ b/extensions/scripting/lua-bindings/manual/CCLuaValue.h @@ -135,7 +135,7 @@ public: * @param stringValue a std::string object. * @return a LuaValue object. */ - static const LuaValue stringValue(const std::string& stringValue); + static const LuaValue stringValue(std::string_view stringValue); /** * Construct a LuaValue object by a LuaValueDict value. @@ -169,7 +169,7 @@ public: * @param objectTypename a std::string object represent the typename of object. * @return a LuaValue object. */ - static const LuaValue ccobjectValue(Ref* ccobjectValue, const std::string& objectTypename); + static const LuaValue ccobjectValue(Ref* ccobjectValue, std::string_view objectTypename); /** * Default constructor of LuaValue. @@ -204,7 +204,7 @@ public: * * @return the reference of _ccobjectType. */ - const std::string& getObjectTypename() const { return *_ccobjectType; } + std::string_view getObjectTypename() const { return *_ccobjectType; } /** * Get the int value of LuaValue object. @@ -232,7 +232,7 @@ public: * * @return the reference about string value. */ - const std::string& stringValue() const { return *_field.stringValue; } + std::string_view stringValue() const { return *_field.stringValue; } /** * Get the LuaValueDict value of LuaValue object. diff --git a/extensions/scripting/lua-bindings/manual/LuaBasicConversions.cpp b/extensions/scripting/lua-bindings/manual/LuaBasicConversions.cpp index eba25e98e1..1103d3f2fe 100644 --- a/extensions/scripting/lua-bindings/manual/LuaBasicConversions.cpp +++ b/extensions/scripting/lua-bindings/manual/LuaBasicConversions.cpp @@ -2725,7 +2725,7 @@ void ccvector_std_string_to_luaval(lua_State* L, const std::vector& int index = 1; - for (const std::string& value : inValue) + for (std::string_view value : inValue) { lua_pushnumber(L, (lua_Number)index); lua_pushstring(L, value.c_str()); diff --git a/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.cpp b/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.cpp index 963f1d2e15..da74a5ef6c 100644 --- a/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.cpp +++ b/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.cpp @@ -4546,7 +4546,7 @@ EventListenerAcceleration* LuaEventListenerAcceleration::create() return eventAcceleration; } -EventListenerCustom* LuaEventListenerCustom::create(const std::string& eventName) +EventListenerCustom* LuaEventListenerCustom::create(std::string_view eventName) { EventListenerCustom* eventCustom = new EventListenerCustom(); if (eventCustom->init(eventName, [=](EventCustom* event) { @@ -6109,7 +6109,7 @@ static int lua_cocos2dx_Console_addCommand(lua_State* tolua_S) handler = (toluafix_ref_function(tolua_S, 3, 0)); ScriptHandlerMgr::getInstance()->addCustomHandler((void*)cobj, handler); - Console::Command outValue = {name, help, [=](int fd, const std::string& args) { + Console::Command outValue = {name, help, [=](int fd, std::string_view args) { auto stack = LuaEngine::getInstance()->getLuaStack(); auto Ls = stack->getLuaState(); // lua-callback, the third param; @@ -7430,7 +7430,7 @@ static int tolua_cocos2d_utils_captureScreen(lua_State* tolua_S) LUA_FUNCTION handler = toluafix_ref_function(tolua_S, 2, 0); std::string fileName = tolua_tocppstring(tolua_S, 3, ""); cocos2d::utils::captureScreen( - [=](bool succeed, const std::string& name) { + [=](bool succeed, std::string_view name) { auto stack = LuaEngine::getInstance()->getLuaStack(); auto Ls = stack->getLuaState(); tolua_pushboolean(Ls, succeed); diff --git a/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.hpp b/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.hpp index ffca5eacff..d8ab149f92 100644 --- a/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.hpp +++ b/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.hpp @@ -44,7 +44,7 @@ NS_CC_BEGIN class LuaEventListenerCustom { public: - static EventListenerCustom* create(const std::string& eventName); + static EventListenerCustom* create(std::string_view eventName); }; class LuaEventListenerAcceleration diff --git a/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.cpp b/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.cpp index be047e4b4b..67a6425864 100644 --- a/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.cpp +++ b/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.cpp @@ -85,7 +85,7 @@ void CustomGUIReader::init(std::string& className, int createFunc, int setPropsF (*callbackMap)[className] = parseselector(CustomGUIReader::setCustomProps); } -void CustomGUIReader::setCustomProps(const std::string& classType, +void CustomGUIReader::setCustomProps(std::string_view classType, cocos2d::Ref* widget, const rapidjson::Value& customOptions) { diff --git a/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.h b/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.h index 79c4ab3ec7..9c331a16fd 100644 --- a/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.h +++ b/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.h @@ -43,7 +43,7 @@ public: Ref* createInstance(); - void setCustomProps(const std::string& classType, cocos2d::Ref* widget, const rapidjson::Value& customOptions); + void setCustomProps(std::string_view classType, cocos2d::Ref* widget, const rapidjson::Value& customOptions); private: std::string _className; diff --git a/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.cpp b/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.cpp index d063179bed..2bad612b73 100644 --- a/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.cpp +++ b/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.cpp @@ -112,7 +112,7 @@ static int lua_cocos2dx_ArmatureAnimation_setMovementEventCallFunc(lua_State* L) ScriptHandlerMgr::HandlerType::ARMATURE_EVENT); self->setMovementEventCallFunc( - [=](Armature* armature, MovementEventType movementType, const std::string& movementID) { + [=](Armature* armature, MovementEventType movementType, std::string_view movementID) { if (0 != handler) { std::string strMovementID = movementID; @@ -188,7 +188,7 @@ static int lua_cocos2dx_ArmatureAnimation_setFrameEventCallFunc(lua_State* L) ScriptHandlerMgr::getInstance()->addObjectHandler((void*)wrapper, handler, ScriptHandlerMgr::HandlerType::ARMATURE_EVENT); - self->setFrameEventCallFunc([=](cocostudio::Bone* bone, const std::string& frameEventName, int originFrameIndex, + self->setFrameEventCallFunc([=](cocostudio::Bone* bone, std::string_view frameEventName, int originFrameIndex, int currentFrameIndex) { if (0 != handler) { diff --git a/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.hpp b/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.hpp index afd08dc0e5..422d717d84 100644 --- a/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.hpp +++ b/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.hpp @@ -78,7 +78,7 @@ struct LuaArmatureMovementEventData int movementType; std::string movementID; - LuaArmatureMovementEventData(cocos2d::Ref* _objTarget, int _movementType,const std::string& _movementID):objTarget(_objTarget),movementType(_movementType),movementID(_movementID) + LuaArmatureMovementEventData(cocos2d::Ref* _objTarget, int _movementType,std::string_view _movementID):objTarget(_objTarget),movementType(_movementType),movementID(_movementID) { } }; @@ -90,7 +90,7 @@ struct LuaArmatureFrameEventData int originFrameIndex; int currentFrameIndex; - LuaArmatureFrameEventData( cocos2d::Ref* _objTarget, const std::string& _frameEventName, int _originFrameIndex, int _currentFrameIndex):objTarget(_objTarget), frameEventName(_frameEventName),originFrameIndex(_originFrameIndex), currentFrameIndex(_currentFrameIndex) + LuaArmatureFrameEventData( cocos2d::Ref* _objTarget, std::string_view _frameEventName, int _originFrameIndex, int _currentFrameIndex):objTarget(_objTarget), frameEventName(_frameEventName),originFrameIndex(_originFrameIndex), currentFrameIndex(_currentFrameIndex) { } }; diff --git a/extensions/scripting/lua-bindings/manual/network/lua_downloader.cpp b/extensions/scripting/lua-bindings/manual/network/lua_downloader.cpp index 179eb45bf0..500db96f54 100644 --- a/extensions/scripting/lua-bindings/manual/network/lua_downloader.cpp +++ b/extensions/scripting/lua-bindings/manual/network/lua_downloader.cpp @@ -271,7 +271,7 @@ static int lua_downloader_setOnTaskError(lua_State* L) saveCallback(L, d, "setOnTaskError"); d->setOnTaskError( - [d, L](const DownloadTask& task, int errorCode, int errorCodeInternal, const std::string& errorSt) { + [d, L](const DownloadTask& task, int errorCode, int errorCodeInternal, std::string_view errorSt) { int ret = getCallback(L, d, "setOnTaskError"); // stack callbackfn if (ret) { diff --git a/extensions/scripting/lua-bindings/manual/network/lua_xml_http_request.cpp b/extensions/scripting/lua-bindings/manual/network/lua_xml_http_request.cpp index b6b942c6e7..a72bc5e4fb 100644 --- a/extensions/scripting/lua-bindings/manual/network/lua_xml_http_request.cpp +++ b/extensions/scripting/lua-bindings/manual/network/lua_xml_http_request.cpp @@ -76,16 +76,16 @@ public: inline int getReadyState() const { return _readyState; } inline cocos2d::network::HttpRequest* getHttpRequest() const { return _httpRequest; } - inline const std::string& getStatusText() const { return _statusText; } + inline std::string_view getStatusText() const { return _statusText; } inline void setStatus(int status) { _status = status; } inline int getStatus() { return _status; } - inline const std::string& getUrl() { return _url; } - inline void setUrl(const std::string& url) { _url = url; } + inline std::string_view getUrl() { return _url; } + inline void setUrl(std::string_view url) { _url = url; } - inline const std::string& getMethod() const { return _meth; } - inline void setMethod(const std::string& meth) { _meth = meth; } + inline std::string_view getMethod() const { return _meth; } + inline void setMethod(std::string_view meth) { _meth = meth; } inline void setAsync(bool isAsync) { _isAsync = isAsync; } inline void setIsNetWork(bool isNetWork) { _isNetwork = isNetWork; } diff --git a/extensions/scripting/lua-bindings/manual/ui/lua_cocos2dx_webview_manual.cpp b/extensions/scripting/lua-bindings/manual/ui/lua_cocos2dx_webview_manual.cpp index a9d616e842..34b5ca82ef 100644 --- a/extensions/scripting/lua-bindings/manual/ui/lua_cocos2dx_webview_manual.cpp +++ b/extensions/scripting/lua-bindings/manual/ui/lua_cocos2dx_webview_manual.cpp @@ -63,8 +63,8 @@ static int lua_cocos2dx_WebView_setOnShouldStartLoading(lua_State* L) #endif LUA_FUNCTION handler = (toluafix_ref_function(L, 2, 0)); - std::function callback = - [L, handler](ui::WebView* sender, const std::string& url) -> bool { + std::function callback = + [L, handler](ui::WebView* sender, std::string_view url) -> bool { toluafix_pushusertype_ccobject(L, sender->_ID, &(sender->_luaID), (void*)sender, "ccui.WebView"); tolua_pushcppstring(L, url); return LuaEngine::getInstance()->getLuaStack()->executeFunctionByHandler(handler, 2); @@ -119,8 +119,8 @@ static int lua_cocos2dx_WebView_setOnDidFinishLoading(lua_State* L) #endif LUA_FUNCTION handler = (toluafix_ref_function(L, 2, 0)); - std::function callback = - [L, handler](ui::WebView* sender, const std::string& url) { + std::function callback = + [L, handler](ui::WebView* sender, std::string_view url) { toluafix_pushusertype_ccobject(L, sender->_ID, &(sender->_luaID), (void*)sender, "ccui.WebView"); tolua_pushcppstring(L, url); LuaEngine::getInstance()->getLuaStack()->executeFunctionByHandler(handler, 2); @@ -174,8 +174,8 @@ static int lua_cocos2dx_WebView_setOnDidFailLoading(lua_State* L) #endif LUA_FUNCTION handler = (toluafix_ref_function(L, 2, 0)); - std::function callback = - [L, handler](ui::WebView* sender, const std::string& url) { + std::function callback = + [L, handler](ui::WebView* sender, std::string_view url) { toluafix_pushusertype_ccobject(L, sender->_ID, &(sender->_luaID), (void*)sender, "ccui.WebView"); tolua_pushcppstring(L, url); LuaEngine::getInstance()->getLuaStack()->executeFunctionByHandler(handler, 2);