Huge changes for all string_view

This commit is contained in:
halx99 2021-12-26 23:26:34 +08:00
parent 658fa24cb0
commit 0076283252
492 changed files with 3704 additions and 3434 deletions

View File

@ -247,7 +247,7 @@ Vec2 ShuffleTiles::getDelta(const Vec2& pos) const
pos2.x = (float)(_tilesOrder[idx] / (int)_gridSize.height); pos2.x = (float)(_tilesOrder[idx] / (int)_gridSize.height);
pos2.y = (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<float>((int)(pos2.x - pos.width)), static_cast<float>((int)(pos2.y - pos.height)));
} }
void ShuffleTiles::placeTile(const Vec2& pos, Tile* t) void ShuffleTiles::placeTile(const Vec2& pos, Tile* t)

View File

@ -29,7 +29,7 @@ THE SOFTWARE.
NS_CC_BEGIN 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(); ActionTween* ret = new ActionTween();
if (ret->initWithDuration(duration, key, from, to)) if (ret->initWithDuration(duration, key, from, to))
@ -42,7 +42,7 @@ ActionTween* ActionTween::create(float duration, const std::string& key, float f
return nullptr; 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)) if (ActionInterval::initWithDuration(duration))
{ {

View File

@ -59,7 +59,7 @@ public:
@param value The new value of the specified key. @param value The new value of the specified key.
@param key The key of property which should be updated. @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 /** ActionTween
@ -93,7 +93,7 @@ public:
* @param to The value of the specified property when the action end. * @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. * @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 // Overrides
void startWithTarget(Node* target) override; void startWithTarget(Node* target) override;
@ -111,7 +111,7 @@ public:
* @return If the initialization success, return true; otherwise, return false. * @return If the initialization success, return true; otherwise, return false.
*/ */
bool bool
initWithDuration(float duration, const std::string& key, float from, float to); initWithDuration(float duration, std::string_view key, float from, float to);
protected: protected:
std::string _key; std::string _key;

View File

@ -165,7 +165,7 @@ void Animation::addSpriteFrame(SpriteFrame* spriteFrame)
_totalDelayUnits++; _totalDelayUnits++;
} }
void Animation::addSpriteFrameWithFile(const std::string& filename) void Animation::addSpriteFrameWithFile(std::string_view filename)
{ {
Texture2D* texture = Director::getInstance()->getTextureCache()->addImage(filename); Texture2D* texture = Director::getInstance()->getTextureCache()->addImage(filename);
Rect rect = Rect::ZERO; Rect rect = Rect::ZERO;

View File

@ -199,7 +199,7 @@ public:
* Added to facilitate the migration from v0.8 to v0.9. * Added to facilitate the migration from v0.8 to v0.9.
* @param filename The path of SpriteFrame. * @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. /** 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". * The frame will be added with one "delay unit".

View File

@ -63,12 +63,12 @@ AnimationCache::~AnimationCache()
CCLOGINFO("deallocing AnimationCache: %p", this); 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()) if (name.empty())
return; return;
@ -76,7 +76,7 @@ void AnimationCache::removeAnimation(const std::string& name)
_animations.erase(name); _animations.erase(name);
} }
Animation* AnimationCache::getAnimation(const std::string& name) Animation* AnimationCache::getAnimation(std::string_view name)
{ {
return _animations.at(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"); auto anisItr = dictionary.find("animations");
if (anisItr == dictionary.end()) 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 */ /** 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"); CCASSERT(!plist.empty(), "Invalid texture file name");
if (plist.empty()) if (plist.empty())
@ -259,7 +259,7 @@ void AnimationCache::addAnimationsWithFile(const std::string& plist)
CCASSERT(!dict.empty(), "CCAnimationCache: File could not be found"); CCASSERT(!dict.empty(), "CCAnimationCache: File could not be found");
if (dict.empty()) 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); addAnimationsWithDictionary(dict, plist);

View File

@ -81,13 +81,13 @@ public:
* @param animation An animation. * @param animation An animation.
* @param name The name of 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. /** Deletes a Animation from the cache.
* *
* @param name The name of animation. * @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. /** Returns a Animation that was previously added.
* If the name is not found it will return nil. * 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. * @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. /** Adds an animation from an NSDictionary.
* Make sure that the frames were previously loaded in the SpriteFrameCache. * Make sure that the frames were previously loaded in the SpriteFrameCache.
@ -104,7 +104,7 @@ public:
* @since v1.1 * @since v1.1
@js NA @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. /** Adds an animation from a plist file.
* Make sure that the frames were previously loaded in the SpriteFrameCache. * Make sure that the frames were previously loaded in the SpriteFrameCache.
@ -113,14 +113,14 @@ public:
* @lua addAnimations * @lua addAnimations
* @param plist An animation from a plist file. * @param plist An animation from a plist file.
*/ */
void addAnimationsWithFile(const std::string& plist); void addAnimationsWithFile(std::string_view plist);
private: private:
void parseVersion1(const ValueMap& animations); void parseVersion1(const ValueMap& animations);
void parseVersion2(const ValueMap& animations); void parseVersion2(const ValueMap& animations);
private: private:
Map<std::string, Animation*> _animations; Map<std::string, Animation*, hlookup::string_hash, hlookup::equal_to> _animations;
static AnimationCache* s_sharedAnimationCache; static AnimationCache* s_sharedAnimationCache;
}; };

View File

@ -47,7 +47,7 @@ AtlasNode::~AtlasNode()
CC_SAFE_RELEASE(_textureAtlas); 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(); AtlasNode* ret = new AtlasNode();
if (ret->initWithTileFile(tile, tileWidth, tileHeight, itemsToRender)) if (ret->initWithTileFile(tile, tileWidth, tileHeight, itemsToRender))
@ -59,7 +59,7 @@ AtlasNode* AtlasNode::create(const std::string& tile, int tileWidth, int tileHei
return nullptr; 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"); CCASSERT(!tile.empty(), "file size should not be empty");
Texture2D* texture = _director->getTextureCache()->addImage(tile); Texture2D* texture = _director->getTextureCache()->addImage(tile);
@ -222,7 +222,7 @@ void AtlasNode::setIgnoreContentScaleFactor(bool ignoreContentScaleFactor)
auto label = dynamic_cast<LabelProtocol*>(this); auto label = dynamic_cast<LabelProtocol*>(this);
if (label) if (label)
{ {
Vec2 s = Vec2(label->getString().size() * _itemWidth, _itemHeight); Vec2 s = Vec2(static_cast<float>(label->getString().size() * _itemWidth), static_cast<float>(_itemHeight));
this->setContentSize(s); this->setContentSize(s);
} }
} }

View File

@ -57,7 +57,7 @@ public:
* @param tileHeight The height of the item. * @param tileHeight The height of the item.
* @param itemsToRender The quantity of items to render. * @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). /** updates the Atlas (indexed vertex array).
* Shall be overridden in subclasses. * 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 /** Initializes an AtlasNode with an Atlas file the width and height of each item and the quantity of items to
* render*/ * 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 /** Initializes an AtlasNode with a texture the width and height of each item measured in points and the quantity
* of items to render*/ * of items to render*/

View File

@ -168,7 +168,7 @@ float PolygonInfo::getArea() const
return area; 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) : _image(nullptr), _data(nullptr), _filename(""), _width(0), _height(0), _scaleFactor(0)
{ {
_filename = filename; _filename = filename;
@ -714,7 +714,7 @@ PolygonInfo AutoPolygon::generateTriangles(const Rect& rect, float epsilon, floa
return ret; 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); AutoPolygon ap(filename);
return ap.generateTriangles(rect, epsilon, threshold); return ap.generateTriangles(rect, epsilon, threshold);

View File

@ -117,8 +117,8 @@ public:
const Rect& getRect() const { return _rect; } const Rect& getRect() const { return _rect; }
void setRect(const Rect& rect) { _rect = rect; } void setRect(const Rect& rect) { _rect = rect; }
const std::string& getFilename() const { return _filename; } std::string_view getFilename() const { return _filename; }
void setFilename(const std::string& filename) { _filename = filename; } void setFilename(std::string_view filename) { _filename = filename; }
// FIXME: this should be a property, not a public ivar // FIXME: this should be a property, not a public ivar
TrianglesCommand::Triangles triangles; TrianglesCommand::Triangles triangles;
@ -147,7 +147,7 @@ public:
* @param filename a path to image file, e.g., "scene1/monster.png". * @param filename a path to image file, e.g., "scene1/monster.png".
* @return an AutoPolygon object; * @return an AutoPolygon object;
*/ */
AutoPolygon(const std::string& filename); AutoPolygon(std::string_view filename);
/** /**
* Destructor of AutoPolygon. * Destructor of AutoPolygon.
@ -254,7 +254,7 @@ public:
* auto sp = Sprite::create(AutoPolygon::generatePolygon("grossini.png")); * auto sp = Sprite::create(AutoPolygon::generatePolygon("grossini.png"));
* @endcode * @endcode
*/ */
static PolygonInfo generatePolygon(const std::string& filename, static PolygonInfo generatePolygon(std::string_view filename,
const Rect& rect = Rect::ZERO, const Rect& rect = Rect::ZERO,
float epsilon = 2.0f, float epsilon = 2.0f,
float threshold = 0.05f); float threshold = 0.05f);

View File

@ -71,12 +71,12 @@ CameraBackgroundDepthBrush* CameraBackgroundBrush::createDepthBrush(float depth)
return CameraBackgroundDepthBrush::create(depth); return CameraBackgroundDepthBrush::create(depth);
} }
CameraBackgroundSkyBoxBrush* CameraBackgroundBrush::createSkyboxBrush(const std::string& positive_x, CameraBackgroundSkyBoxBrush* CameraBackgroundBrush::createSkyboxBrush(std::string_view positive_x,
const std::string& negative_x, std::string_view negative_x,
const std::string& positive_y, std::string_view positive_y,
const std::string& negative_y, std::string_view negative_y,
const std::string& positive_z, std::string_view positive_z,
const std::string& negative_z) std::string_view negative_z)
{ {
return CameraBackgroundSkyBoxBrush::create(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z); return CameraBackgroundSkyBoxBrush::create(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z);
} }
@ -303,12 +303,12 @@ CameraBackgroundSkyBoxBrush::~CameraBackgroundSkyBoxBrush()
#endif #endif
} }
CameraBackgroundSkyBoxBrush* CameraBackgroundSkyBoxBrush::create(const std::string& positive_x, CameraBackgroundSkyBoxBrush* CameraBackgroundSkyBoxBrush::create(std::string_view positive_x,
const std::string& negative_x, std::string_view negative_x,
const std::string& positive_y, std::string_view positive_y,
const std::string& negative_y, std::string_view negative_y,
const std::string& positive_z, std::string_view positive_z,
const std::string& negative_z) std::string_view negative_z)
{ {
CameraBackgroundSkyBoxBrush* ret = nullptr; CameraBackgroundSkyBoxBrush* ret = nullptr;

View File

@ -105,12 +105,12 @@ public:
@param negative_z texture for the rear side of the texture cube face. @param negative_z texture for the rear side of the texture cube face.
@return A new brush inited with given parameters. @return A new brush inited with given parameters.
*/ */
static CameraBackgroundSkyBoxBrush* createSkyboxBrush(const std::string& positive_x, static CameraBackgroundSkyBoxBrush* createSkyboxBrush(std::string_view positive_x,
const std::string& negative_x, std::string_view negative_x,
const std::string& positive_y, std::string_view positive_y,
const std::string& negative_y, std::string_view negative_y,
const std::string& positive_z, std::string_view positive_z,
const std::string& negative_z); std::string_view negative_z);
/** /**
* draw the background * draw the background
*/ */
@ -253,12 +253,12 @@ public:
@param negative_z texture for the rear side of the texture cube face. @param negative_z texture for the rear side of the texture cube face.
@return A new brush inited with given parameters. @return A new brush inited with given parameters.
*/ */
static CameraBackgroundSkyBoxBrush* create(const std::string& positive_x, static CameraBackgroundSkyBoxBrush* create(std::string_view positive_x,
const std::string& negative_x, std::string_view negative_x,
const std::string& positive_y, std::string_view positive_y,
const std::string& negative_y, std::string_view negative_y,
const std::string& positive_z, std::string_view positive_z,
const std::string& negative_z); std::string_view negative_z);
/** Creates a Skybox brush with 6 textures. /** Creates a Skybox brush with 6 textures.
*/ */

View File

@ -60,8 +60,8 @@ public:
bool isEnabled() const { return _enabled; } bool isEnabled() const { return _enabled; }
virtual void setEnabled(bool enabled); virtual void setEnabled(bool enabled);
const std::string& getName() const { return _name; } std::string_view getName() const { return _name; }
virtual void setName(const std::string& name) { _name = name; } virtual void setName(std::string_view name) { _name = name; }
Node* getOwner() const { return _owner; } Node* getOwner() const { return _owner; }
virtual void setOwner(Node* owner); virtual void setOwner(Node* owner);

View File

@ -33,7 +33,7 @@ ComponentContainer::ComponentContainer(Node* node) : _owner(node) {}
ComponentContainer::~ComponentContainer() {} ComponentContainer::~ComponentContainer() {}
Component* ComponentContainer::get(const std::string& name) const Component* ComponentContainer::get(std::string_view name) const
{ {
Component* ret = nullptr; Component* ret = nullptr;
@ -60,7 +60,7 @@ bool ComponentContainer::add(Component* com)
CCASSERT(false, "ComponentContainer already have this kind of component"); CCASSERT(false, "ComponentContainer already have this kind of component");
break; break;
} }
_componentMap[componentName] = com; hlookup::set_item(_componentMap, componentName, com);//_componentMap[componentName] = com;
com->retain(); com->retain();
com->setOwner(_owner); com->setOwner(_owner);
com->onAdd(); com->onAdd();
@ -70,7 +70,7 @@ bool ComponentContainer::add(Component* com)
return ret; return ret;
} }
bool ComponentContainer::remove(const std::string& componentName) bool ComponentContainer::remove(std::string_view componentName)
{ {
bool ret = false; bool ret = false;
do do

View File

@ -54,10 +54,10 @@ public:
/** /**
* @js getComponent * @js getComponent
*/ */
Component* get(const std::string& name) const; Component* get(std::string_view name) const;
bool add(Component* com); bool add(Component* com);
bool remove(const std::string& name); bool remove(std::string_view name);
bool remove(Component* com); bool remove(Component* com);
void removeAll(); void removeAll();
void visit(float delta); void visit(float delta);
@ -68,7 +68,7 @@ public:
bool isEmpty() const { return _componentMap.empty(); } bool isEmpty() const { return _componentMap.empty(); }
private: private:
std::unordered_map<std::string, Component*> _componentMap; hlookup::string_map<Component*> _componentMap;
Node* _owner; Node* _owner;
friend class Node; friend class Node;

View File

@ -799,7 +799,7 @@ void FastTMXLayer::removeChild(Node* node, bool cleanup)
} }
// TMXLayer - Properties // TMXLayer - Properties
Value FastTMXLayer::getProperty(const std::string& propertyName) const Value FastTMXLayer::getProperty(std::string_view propertyName) const
{ {
auto propItr = _properties.find(propertyName); auto propItr = _properties.find(propertyName);
if (propItr != _properties.end()) if (propItr != _properties.end())

View File

@ -152,7 +152,7 @@ public:
* @param propertyName The value for the specific property name. * @param propertyName The value for the specific property name.
* @return 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. */ /** Creates the tiles. */
void setupTiles(); void setupTiles();
@ -161,13 +161,13 @@ public:
* *
* @return The tile layer name. * @return The tile layer name.
*/ */
const std::string& getLayerName() { return _layerName; } std::string_view getLayerName() { return _layerName; }
/** Set the tile layer name. /** Set the tile layer name.
* *
* @param layerName The new 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. /** Gets the size of the layer in tiles.
* *

View File

@ -33,7 +33,7 @@ NS_CC_BEGIN
// implementation FastTMXTiledMap // implementation FastTMXTiledMap
FastTMXTiledMap* FastTMXTiledMap::create(const std::string& tmxFile) FastTMXTiledMap* FastTMXTiledMap::create(std::string_view tmxFile)
{ {
FastTMXTiledMap* ret = new FastTMXTiledMap(); FastTMXTiledMap* ret = new FastTMXTiledMap();
if (ret->initWithTMXFile(tmxFile)) if (ret->initWithTMXFile(tmxFile))
@ -45,7 +45,7 @@ FastTMXTiledMap* FastTMXTiledMap::create(const std::string& tmxFile)
return nullptr; 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(); FastTMXTiledMap* ret = new FastTMXTiledMap();
if (ret->initWithXML(tmxString, resourcePath)) if (ret->initWithXML(tmxString, resourcePath))
@ -57,7 +57,7 @@ FastTMXTiledMap* FastTMXTiledMap::createWithXML(const std::string& tmxString, co
return nullptr; 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"); CCASSERT(tmxFile.size() > 0, "FastTMXTiledMap: tmx file should not be empty");
@ -77,7 +77,7 @@ bool FastTMXTiledMap::initWithTMXFile(const std::string& tmxFile)
return true; 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); setContentSize(Vec2::ZERO);
@ -194,7 +194,7 @@ void FastTMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo)
} }
// public // public
FastTMXLayer* FastTMXTiledMap::getLayer(const std::string& layerName) const FastTMXLayer* FastTMXTiledMap::getLayer(std::string_view layerName) const
{ {
CCASSERT(!layerName.empty(), "Invalid layer name!"); CCASSERT(!layerName.empty(), "Invalid layer name!");
@ -214,7 +214,7 @@ FastTMXLayer* FastTMXTiledMap::getLayer(const std::string& layerName) const
return nullptr; return nullptr;
} }
TMXObjectGroup* FastTMXTiledMap::getObjectGroup(const std::string& groupName) const TMXObjectGroup* FastTMXTiledMap::getObjectGroup(std::string_view groupName) const
{ {
CCASSERT(!groupName.empty(), "Invalid group name!"); CCASSERT(!groupName.empty(), "Invalid group name!");
@ -233,7 +233,7 @@ TMXObjectGroup* FastTMXTiledMap::getObjectGroup(const std::string& groupName) co
return nullptr; return nullptr;
} }
Value FastTMXTiledMap::getProperty(const std::string& propertyName) const Value FastTMXTiledMap::getProperty(std::string_view propertyName) const
{ {
auto propsItr = _properties.find(propertyName); auto propsItr = _properties.find(propertyName);
if (propsItr != _properties.end()) if (propsItr != _properties.end())

View File

@ -101,7 +101,7 @@ public:
* *
* @return An autorelease object. * @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. /** 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. * @param resourcePath A path to TMX resources.
* @return An autorelease object. * @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 the FastTMXLayer for the specific layer.
* *
* @return 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 the TMXObjectGroup for the specific group.
* *
* @return 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 the value for the specific property name.
* *
* @return 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. /** Return properties dictionary for tile GID.
* *
@ -207,7 +207,7 @@ public:
int getLayerCount() const { return _layerCount; } int getLayerCount() const { return _layerCount; }
const std::string& getResourceFile() const { return _tmxFile; } std::string_view getResourceFile() const { return _tmxFile; }
CC_CONSTRUCTOR_ACCESS : CC_CONSTRUCTOR_ACCESS :
/** /**
@ -221,10 +221,10 @@ public:
virtual ~FastTMXTiledMap(); virtual ~FastTMXTiledMap();
/** initializes a TMX Tiled Map with a TMX file */ /** 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 */ /** 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: protected:
FastTMXLayer* parseLayer(TMXLayerInfo* layerInfo, TMXMapInfo* mapInfo); FastTMXLayer* parseLayer(TMXLayerInfo* layerInfo, TMXMapInfo* mapInfo);

View File

@ -520,9 +520,9 @@ void FontAtlas::setLineHeight(float newHeight)
_lineHeight = 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()) if (fontName.empty())
return fontName; return fontName;
auto idx = fontName.rfind('/'); auto idx = fontName.rfind('/');

View File

@ -86,7 +86,7 @@ public:
float getLineHeight() const { return _lineHeight; } float getLineHeight() const { return _lineHeight; }
void setLineHeight(float newHeight); void setLineHeight(float newHeight);
std::string getFontName() const; std::string_view getFontName() const;
Texture2D* getTexture(int slot); Texture2D* getTexture(int slot);
const Font* getFont() const { return _font; } const Font* getFont() const { return _font; }

View File

@ -36,7 +36,7 @@
NS_CC_BEGIN NS_CC_BEGIN
std::unordered_map<std::string, FontAtlas*> FontAtlasCache::_atlasMap; hlookup::string_map<FontAtlas*> FontAtlasCache::_atlasMap;
#define ATLAS_MAP_KEY_PREFIX_BUFFER_SIZE 255 #define ATLAS_MAP_KEY_PREFIX_BUFFER_SIZE 255
void FontAtlasCache::purgeCachedData() void FontAtlasCache::purgeCachedData()
@ -91,16 +91,17 @@ FontAtlas* FontAtlasCache::getFontAtlasTTF(const _ttfConfig* config)
return nullptr; return nullptr;
} }
FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName) FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName)
{ {
return getFontAtlasFNT(fontFileName, Rect::ZERO, false); 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( const auto realFontFilename = FileUtils::getInstance()->getNewFilename(
fontFileName); // resolves real file path, to prevent storing multiple atlases for the same file. 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); const auto it = _atlasMap.find(atlasName);
if (it == _atlasMap.end()) if (it == _atlasMap.end())
@ -123,7 +124,7 @@ FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName, cons
return nullptr; 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( const auto realFontFilename = FileUtils::getInstance()->getNewFilename(
fontFileName); // resolves real file path, to prevent storing multiple atlases for the same file. 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; 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); 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); auto it = _atlasMap.find(atlasName);
if (it == _atlasMap.end()) if (it == _atlasMap.end())
@ -172,8 +173,8 @@ FontAtlas* FontAtlasCache::getFontAtlasCharMap(const std::string& plistFile)
auto tempAtlas = font->newFontAtlas(); auto tempAtlas = font->newFontAtlas();
if (tempAtlas) if (tempAtlas)
{ {
_atlasMap[atlasName] = tempAtlas; hlookup::set_item(_atlasMap, atlasName, tempAtlas); // _atlasMap[atlasName] = tempAtlas;
return _atlasMap[atlasName]; return tempAtlas;
} }
} }
} }
@ -210,7 +211,7 @@ FontAtlas* FontAtlasCache::getFontAtlasCharMap(Texture2D* texture, int itemWidth
return nullptr; return nullptr;
} }
FontAtlas* FontAtlasCache::getFontAtlasCharMap(const std::string& charMapFile, FontAtlas* FontAtlasCache::getFontAtlasCharMap(std::string_view charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
int startCharMap) int startCharMap)
@ -263,7 +264,7 @@ bool FontAtlasCache::releaseFontAtlas(FontAtlas* atlas)
return false; 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]; char keyPrefix[ATLAS_MAP_KEY_PREFIX_BUFFER_SIZE];
snprintf(keyPrefix, ATLAS_MAP_KEY_PREFIX_BUFFER_SIZE, "%.2f %.2f ", imageRect.origin.x, imageRect.origin.y); 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); 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(); auto item = _atlasMap.begin();
while (item != _atlasMap.end()) while (item != _atlasMap.end())

View File

@ -43,17 +43,17 @@ class CC_DLL FontAtlasCache
public: public:
static FontAtlas* getFontAtlasTTF(const _ttfConfig* config); static FontAtlas* getFontAtlasTTF(const _ttfConfig* config);
static FontAtlas* getFontAtlasFNT(const std::string& fontFileName); static FontAtlas* getFontAtlasFNT(std::string_view fontFileName);
static FontAtlas* getFontAtlasFNT(const std::string& fontFileName, const std::string& subTextureKey); static FontAtlas* getFontAtlasFNT(std::string_view fontFileName, std::string_view subTextureKey);
static FontAtlas* getFontAtlasFNT(const std::string& fontFileName, const Rect& imageRect, bool imageRotated); static FontAtlas* getFontAtlasFNT(std::string_view fontFileName, const Rect& imageRect, bool imageRotated);
CC_DEPRECATED_ATTRIBUTE static FontAtlas* getFontAtlasFNT(const std::string& fontFileName, const Vec2& imageOffset); 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 itemWidth,
int itemHeight, int itemHeight,
int startCharMap); int startCharMap);
static FontAtlas* getFontAtlasCharMap(Texture2D* texture, 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); 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! CAUTION : All component use this font texture should be reset font name, though the file name is same!
otherwise, it will cause program crash! 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); const Vec2& imageOffset = Vec2::ZERO);
/** Unload all texture atlas texture create by special file name. /** 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! CAUTION : All component use this font texture should be reset font name, though the file name is same!
otherwise, it will cause program crash! otherwise, it will cause program crash!
*/ */
static void unloadFontAtlasTTF(const std::string& fontFileName); static void unloadFontAtlasTTF(std::string_view fontFileName);
private: private:
static std::unordered_map<std::string, FontAtlas*> _atlasMap; static hlookup::string_map<FontAtlas*> _atlasMap;
}; };
NS_CC_END NS_CC_END

View File

@ -33,7 +33,7 @@
NS_CC_BEGIN 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 pathStr = FileUtils::getInstance()->fullPathForFilename(plistFile);
std::string relPathStr = pathStr.substr(0, pathStr.find_last_of('/')) + "/"; std::string relPathStr = pathStr.substr(0, pathStr.find_last_of('/')) + "/";
@ -64,7 +64,7 @@ FontCharMap* FontCharMap::create(const std::string& plistFile)
return tempFont; 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); Texture2D* tempTexture = Director::getInstance()->getTextureCache()->addImage(charMapFile);

View File

@ -38,9 +38,9 @@ class Texture2D;
class FontCharMap : public Font class FontCharMap : public Font
{ {
public: 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(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 int* getHorizontalKerningForTextUTF32(const std::u32string& text, int& outNumLetters) const override;
virtual FontAtlas* newFontAtlas() override; virtual FontAtlas* newFontAtlas() override;

View File

@ -56,15 +56,15 @@ struct _FontDefHashElement;
// //
// FNTConfig Cache - free functions // FNTConfig Cache - free functions
// //
static Map<std::string, BMFontConfiguration*>* s_configurations = nullptr; static StringMap<BMFontConfiguration*>* s_configurations = nullptr;
BMFontConfiguration* FNTConfigLoadFile(const std::string& fntFile) BMFontConfiguration* FNTConfigLoadFile(std::string_view fntFile)
{ {
BMFontConfiguration* ret = nullptr; BMFontConfiguration* ret = nullptr;
if (s_configurations == nullptr) if (s_configurations == nullptr)
{ {
s_configurations = new Map<std::string, BMFontConfiguration*>(); s_configurations = new StringMap<BMFontConfiguration*>();
} }
ret = s_configurations->at(fntFile); ret = s_configurations->at(fntFile);
@ -84,7 +84,7 @@ BMFontConfiguration* FNTConfigLoadFile(const std::string& fntFile)
// BitmapFontConfiguration // BitmapFontConfiguration
// //
BMFontConfiguration* BMFontConfiguration::create(const std::string& FNTfile) BMFontConfiguration* BMFontConfiguration::create(std::string_view FNTfile)
{ {
BMFontConfiguration* ret = new BMFontConfiguration(); BMFontConfiguration* ret = new BMFontConfiguration();
if (ret->initWithFNTfile(FNTfile)) if (ret->initWithFNTfile(FNTfile))
@ -96,7 +96,7 @@ BMFontConfiguration* BMFontConfiguration::create(const std::string& FNTfile)
return nullptr; return nullptr;
} }
bool BMFontConfiguration::initWithFNTfile(const std::string& FNTfile) bool BMFontConfiguration::initWithFNTfile(std::string_view FNTfile)
{ {
_characterSet = this->parseConfigFile(FNTfile); _characterSet = this->parseConfigFile(FNTfile);
@ -141,7 +141,7 @@ void BMFontConfiguration::purgeFontDefDictionary()
_fontDefDictionary.clear(); _fontDefDictionary.clear();
} }
std::set<unsigned int>* BMFontConfiguration::parseConfigFile(const std::string& controlFile) std::set<unsigned int>* BMFontConfiguration::parseConfigFile(std::string_view controlFile)
{ {
std::string data = FileUtils::getInstance()->getStringFromFile(controlFile); std::string data = FileUtils::getInstance()->getStringFromFile(controlFile);
if (data.empty()) if (data.empty())
@ -156,7 +156,7 @@ std::set<unsigned int>* BMFontConfiguration::parseConfigFile(const std::string&
} }
if (data[0] == 0) if (data[0] == 0)
{ {
CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.c_str()); CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.data());
return nullptr; return nullptr;
} }
auto contents = data.c_str(); auto contents = data.c_str();
@ -223,7 +223,7 @@ std::set<unsigned int>* BMFontConfiguration::parseConfigFile(const std::string&
std::set<unsigned int>* BMFontConfiguration::parseBinaryConfigFile(unsigned char* pData, std::set<unsigned int>* BMFontConfiguration::parseBinaryConfigFile(unsigned char* pData,
uint32_t size, 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 */ /* based on http://www.angelcode.com/products/bmfont/doc/file_format.html file format */
@ -399,7 +399,7 @@ std::set<unsigned int>* BMFontConfiguration::parseBinaryConfigFile(unsigned char
return validCharsString; 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: // line to parse:
@ -528,7 +528,7 @@ void BMFontConfiguration::parseKerningEntry(const char* line)
_kerningDictionary[key] = amount; _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); const auto newConf = FNTConfigLoadFile(fntFilePath);
if (!newConf) if (!newConf)
@ -545,7 +545,7 @@ FontFNT* FontFNT::create(const std::string& fntFilePath, const Rect& imageRect,
return tempFont; 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); const auto newConf = FNTConfigLoadFile(fntFilePath);
if (!newConf) if (!newConf)
@ -567,7 +567,7 @@ FontFNT* FontFNT::create(const std::string& fntFilePath, const std::string& subT
return tempFont; return tempFont;
} }
FontFNT* FontFNT::create(const std::string& fntFilePath) FontFNT* FontFNT::create(std::string_view fntFilePath)
{ {
const auto newConf = FNTConfigLoadFile(fntFilePath); const auto newConf = FNTConfigLoadFile(fntFilePath);
if (!newConf) if (!newConf)
@ -590,7 +590,7 @@ FontFNT* FontFNT::create(const std::string& fntFilePath)
return tempFont; 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); return create(fntFilePath, Rect(imageOffset.x, imageOffset.y, 0, 0), false);
} }
@ -762,11 +762,11 @@ FontAtlas* FontFNT::newFontAtlas()
return tempAtlas; return tempAtlas;
} }
void FontFNT::reloadBMFontResource(const std::string& fntFilePath) void FontFNT::reloadBMFontResource(std::string_view fntFilePath)
{ {
if (s_configurations == nullptr) if (s_configurations == nullptr)
{ {
s_configurations = new Map<std::string, BMFontConfiguration*>(); s_configurations = new StringMap<BMFontConfiguration*>();
} }
BMFontConfiguration* ret = s_configurations->at(fntFilePath); BMFontConfiguration* ret = s_configurations->at(fntFilePath);

View File

@ -115,27 +115,27 @@ public:
std::string description() const; std::string description() const;
/** allocates a BMFontConfiguration with a FNT file */ /** 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 */ /** 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; } std::string_view getAtlasName() { return _atlasName; }
void setAtlasName(const std::string& atlasName) { _atlasName = atlasName; } void setAtlasName(std::string_view atlasName) { _atlasName = atlasName; }
std::set<unsigned int>* getCharacterSet() const; std::set<unsigned int>* getCharacterSet() const;
protected: protected:
virtual std::set<unsigned int>* parseConfigFile(const std::string& controlFile); virtual std::set<unsigned int>* parseConfigFile(std::string_view controlFile);
virtual std::set<unsigned int>* parseBinaryConfigFile(unsigned char* pData, virtual std::set<unsigned int>* parseBinaryConfigFile(unsigned char* pData,
uint32_t size, uint32_t size,
const std::string& controlFile); std::string_view controlFile);
private: private:
unsigned int parseCharacterDefinition(const char* line); unsigned int parseCharacterDefinition(const char* line);
void parseInfoArguments(const char* line); void parseInfoArguments(const char* line);
void parseCommonArguments(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 parseKerningEntry(const char* line);
void purgeKerningDictionary(); void purgeKerningDictionary();
void purgeFontDefDictionary(); void purgeFontDefDictionary();
@ -145,11 +145,11 @@ class CC_DLL FontFNT : public Font
{ {
public: public:
static FontFNT* create(const std::string& fntFilePath, const Rect& imageRect, bool imageRotated); static FontFNT* create(std::string_view fntFilePath, const Rect& imageRect, bool imageRotated);
static FontFNT* create(const std::string& fntFilePath, const std::string& subTextureKey); static FontFNT* create(std::string_view fntFilePath, std::string_view subTextureKey);
static FontFNT* create(const std::string& fntFilePath); 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); const Vec2& imageOffset = Vec2::ZERO);
/** Purges the cached data. /** Purges the cached data.
@ -164,7 +164,7 @@ public:
int getOriginalFontSize() const; int getOriginalFontSize() const;
static void reloadBMFontResource(const std::string& fntFilePath); static void reloadBMFontResource(std::string_view fntFilePath);
protected: protected:
FontFNT(BMFontConfiguration* theContfig, const Rect& imageRect, bool imageRotated); FontFNT(BMFontConfiguration* theContfig, const Rect& imageRect, bool imageRotated);

View File

@ -653,7 +653,7 @@ std::string_view FontFreeType::getGlyphCollection() const
return glyphCollection; return glyphCollection;
} }
void FontFreeType::releaseFont(const std::string& fontName) void FontFreeType::releaseFont(std::string_view fontName)
{ {
auto item = s_cacheFontData.begin(); auto item = s_cacheFontData.begin();
while (s_cacheFontData.end() != item) while (s_cacheFontData.end() != item)

View File

@ -101,12 +101,12 @@ public:
int getFontAscender() const; int getFontAscender() const;
const char* getFontFamily() const; const char* getFontFamily() const;
const std::string& getFontName() const { return _fontName; } std::string_view getFontName() const { return _fontName; }
virtual FontAtlas* newFontAtlas() override; virtual FontAtlas* newFontAtlas() override;
virtual int getFontMaxHeight() const override { return _lineHeight; } 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(); static FT_Library getFTLibrary();

View File

@ -240,8 +240,8 @@ Label* Label::create()
return ret; return ret;
} }
Label* Label::createWithSystemFont(const std::string& text, Label* Label::createWithSystemFont(std::string_view text,
const std::string& font, std::string_view font,
float fontSize, float fontSize,
const Vec2& dimensions /* = Vec2::ZERO */, const Vec2& dimensions /* = Vec2::ZERO */,
TextHAlignment hAlignment /* = TextHAlignment::LEFT */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */,
@ -259,8 +259,8 @@ Label* Label::createWithSystemFont(const std::string& text,
return ret; return ret;
} }
Label* Label::createWithTTF(const std::string& text, Label* Label::createWithTTF(std::string_view text,
const std::string& fontFile, std::string_view fontFile,
float fontSize, float fontSize,
const Vec2& dimensions /* = Vec2::ZERO */, const Vec2& dimensions /* = Vec2::ZERO */,
TextHAlignment hAlignment /* = TextHAlignment::LEFT */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */,
@ -279,7 +279,7 @@ Label* Label::createWithTTF(const std::string& text,
} }
Label* Label::createWithTTF(const TTFConfig& ttfConfig, Label* Label::createWithTTF(const TTFConfig& ttfConfig,
const std::string& text, std::string_view text,
TextHAlignment hAlignment /* = TextHAlignment::CENTER */, TextHAlignment hAlignment /* = TextHAlignment::CENTER */,
int maxLineWidth /* = 0 */) int maxLineWidth /* = 0 */)
{ {
@ -295,8 +295,8 @@ Label* Label::createWithTTF(const TTFConfig& ttfConfig,
return nullptr; return nullptr;
} }
Label* Label::createWithBMFont(const std::string& bmfontPath, Label* Label::createWithBMFont(std::string_view bmfontPath,
const std::string& text, std::string_view text,
const TextHAlignment& hAlignment, const TextHAlignment& hAlignment,
int maxLineWidth) int maxLineWidth)
{ {
@ -315,8 +315,8 @@ Label* Label::createWithBMFont(const std::string& bmfontPath,
return nullptr; return nullptr;
} }
Label* Label::createWithBMFont(const std::string& bmfontPath, Label* Label::createWithBMFont(std::string_view bmfontPath,
const std::string& text, std::string_view text,
const TextHAlignment& hAlignment, const TextHAlignment& hAlignment,
int maxLineWidth, int maxLineWidth,
const Rect& imageRect, const Rect& imageRect,
@ -337,11 +337,11 @@ Label* Label::createWithBMFont(const std::string& bmfontPath,
return nullptr; return nullptr;
} }
Label* Label::createWithBMFont(const std::string& bmfontPath, Label* Label::createWithBMFont(std::string_view bmfontPath,
const std::string& text, std::string_view text,
const TextHAlignment& hAlignment, const TextHAlignment& hAlignment,
int maxLineWidth, int maxLineWidth,
const std::string& subTextureKey) std::string_view subTextureKey)
{ {
auto ret = new Label(hAlignment); auto ret = new Label(hAlignment);
@ -358,8 +358,8 @@ Label* Label::createWithBMFont(const std::string& bmfontPath,
return nullptr; return nullptr;
} }
Label* Label::createWithBMFont(const std::string& bmfontPath, Label* Label::createWithBMFont(std::string_view bmfontPath,
const std::string& text, std::string_view text,
const TextHAlignment& hAlignment, const TextHAlignment& hAlignment,
int maxLineWidth, int maxLineWidth,
const Vec2& imageOffset) const Vec2& imageOffset)
@ -368,7 +368,7 @@ Label* Label::createWithBMFont(const std::string& bmfontPath,
false); false);
} }
Label* Label::createWithCharMap(const std::string& plistFile) Label* Label::createWithCharMap(std::string_view plistFile)
{ {
auto ret = new Label(); auto ret = new Label();
@ -396,7 +396,7 @@ Label* Label::createWithCharMap(Texture2D* texture, int itemWidth, int itemHeigh
return nullptr; 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(); auto ret = new Label();
@ -410,7 +410,7 @@ Label* Label::createWithCharMap(const std::string& charMapFile, int itemWidth, i
return nullptr; return nullptr;
} }
bool Label::setCharMap(const std::string& plistFile) bool Label::setCharMap(std::string_view plistFile)
{ {
auto newAtlas = FontAtlasCache::getFontAtlasCharMap(plistFile); auto newAtlas = FontAtlasCache::getFontAtlasCharMap(plistFile);
@ -426,8 +426,8 @@ bool Label::setCharMap(const std::string& plistFile)
return true; return true;
} }
bool Label::initWithTTF(const std::string& text, bool Label::initWithTTF(std::string_view text,
const std::string& fontFilePath, std::string_view fontFilePath,
float fontSize, float fontSize,
const Vec2& dimensions, const Vec2& dimensions,
TextHAlignment /*hAlignment*/, TextHAlignment /*hAlignment*/,
@ -447,7 +447,7 @@ bool Label::initWithTTF(const std::string& text,
} }
bool Label::initWithTTF(const TTFConfig& ttfConfig, bool Label::initWithTTF(const TTFConfig& ttfConfig,
const std::string& text, std::string_view text,
TextHAlignment /*hAlignment*/, TextHAlignment /*hAlignment*/,
int maxLineWidth) int maxLineWidth)
{ {
@ -476,7 +476,7 @@ bool Label::setCharMap(Texture2D* texture, int itemWidth, int itemHeight, int st
return true; 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); auto newAtlas = FontAtlasCache::getFontAtlasCharMap(charMapFile, itemWidth, itemHeight, startCharMap);
@ -841,7 +841,7 @@ bool Label::setTTFConfig(const TTFConfig& ttfConfig)
return setTTFConfigInternal(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); FontAtlas* newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath);
@ -875,7 +875,7 @@ bool Label::setBMFontFilePath(const std::string& bmfontFilePath, float fontSize)
return true; return true;
} }
bool Label::setBMFontFilePath(const std::string& bmfontFilePath, bool Label::setBMFontFilePath(std::string_view bmfontFilePath,
const Rect& imageRect, const Rect& imageRect,
bool imageRotated, bool imageRotated,
float fontSize) float fontSize)
@ -914,7 +914,7 @@ bool Label::setBMFontFilePath(const std::string& bmfontFilePath,
return true; 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); FontAtlas* newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath, subTextureKey);
@ -949,7 +949,7 @@ bool Label::setBMFontFilePath(const std::string& bmfontFilePath, const std::stri
return true; 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); 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) if (systemFont != _systemFont)
{ {

View File

@ -166,8 +166,8 @@ public:
* *
* @return An automatically released Label object. * @return An automatically released Label object.
*/ */
static Label* createWithSystemFont(const std::string& text, static Label* createWithSystemFont(std::string_view text,
const std::string& font, std::string_view font,
float fontSize, float fontSize,
const Vec2& dimensions = Vec2::ZERO, const Vec2& dimensions = Vec2::ZERO,
TextHAlignment hAlignment = TextHAlignment::LEFT, TextHAlignment hAlignment = TextHAlignment::LEFT,
@ -185,8 +185,8 @@ public:
* *
* @return An automatically released Label object. * @return An automatically released Label object.
*/ */
static Label* createWithTTF(const std::string& text, static Label* createWithTTF(std::string_view text,
const std::string& fontFilePath, std::string_view fontFilePath,
float fontSize, float fontSize,
const Vec2& dimensions = Vec2::ZERO, const Vec2& dimensions = Vec2::ZERO,
TextHAlignment hAlignment = TextHAlignment::LEFT, TextHAlignment hAlignment = TextHAlignment::LEFT,
@ -204,7 +204,7 @@ public:
* @see TTFConfig setTTFConfig setMaxLineWidth * @see TTFConfig setTTFConfig setMaxLineWidth
*/ */
static Label* createWithTTF(const TTFConfig& ttfConfig, static Label* createWithTTF(const TTFConfig& ttfConfig,
const std::string& text, std::string_view text,
TextHAlignment hAlignment = TextHAlignment::LEFT, TextHAlignment hAlignment = TextHAlignment::LEFT,
int maxLineWidth = 0); int maxLineWidth = 0);
@ -219,8 +219,8 @@ public:
* @return An automatically released Label object. * @return An automatically released Label object.
* @see setBMFontFilePath setMaxLineWidth * @see setBMFontFilePath setMaxLineWidth
*/ */
static Label* createWithBMFont(const std::string& bmfontPath, static Label* createWithBMFont(std::string_view bmfontPath,
const std::string& text, std::string_view text,
const TextHAlignment& hAlignment = TextHAlignment::LEFT, const TextHAlignment& hAlignment = TextHAlignment::LEFT,
int maxLineWidth = 0); int maxLineWidth = 0);
@ -237,8 +237,8 @@ public:
* @return An automatically released Label object. * @return An automatically released Label object.
* @see setBMFontFilePath setMaxLineWidth * @see setBMFontFilePath setMaxLineWidth
*/ */
static Label* createWithBMFont(const std::string& bmfontPath, static Label* createWithBMFont(std::string_view bmfontPath,
const std::string& text, std::string_view text,
const TextHAlignment& hAlignment, const TextHAlignment& hAlignment,
int maxLineWidth, int maxLineWidth,
const Rect& imageRect, const Rect& imageRect,
@ -256,11 +256,11 @@ public:
* @return An automatically released Label object. * @return An automatically released Label object.
* @see setBMFontFilePath setMaxLineWidth * @see setBMFontFilePath setMaxLineWidth
*/ */
static Label* createWithBMFont(const std::string& bmfontPath, static Label* createWithBMFont(std::string_view bmfontPath,
const std::string& text, std::string_view text,
const TextHAlignment& hAlignment, const TextHAlignment& hAlignment,
int maxLineWidth, int maxLineWidth,
const std::string& subTextureKey); std::string_view subTextureKey);
/** /**
* Allocates and initializes a Label, with a bitmap font file. * Allocates and initializes a Label, with a bitmap font file.
@ -274,8 +274,8 @@ public:
* @return An automatically released Label object. * @return An automatically released Label object.
* @see setBMFontFilePath setMaxLineWidth * @see setBMFontFilePath setMaxLineWidth
*/ */
CC_DEPRECATED_ATTRIBUTE static Label* createWithBMFont(const std::string& bmfontPath, CC_DEPRECATED_ATTRIBUTE static Label* createWithBMFont(std::string_view bmfontPath,
const std::string& text, std::string_view text,
const TextHAlignment& hAlignment, const TextHAlignment& hAlignment,
int maxLineWidth, int maxLineWidth,
const Vec2& imageOffset); const Vec2& imageOffset);
@ -290,7 +290,7 @@ public:
* *
* @return An automatically released Label object. * @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. * Allocates and initializes a Label, with char map configuration.
@ -311,7 +311,7 @@ public:
* *
* @return An automatically released Label object. * @return An automatically released Label object.
*/ */
static Label* createWithCharMap(const std::string& plistFile); static Label* createWithCharMap(std::string_view plistFile);
// end of creators group // end of creators group
/// @} /// @}
@ -332,33 +332,33 @@ public:
virtual const TTFConfig& getTTFConfig() const { return _fontConfig; } virtual const TTFConfig& getTTFConfig() const { return _fontConfig; }
/** Sets a new bitmap font to Label */ /** 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 */ /** Sets a new bitmap font to Label */
virtual bool setBMFontFilePath(const std::string& bmfontFilePath, virtual bool setBMFontFilePath(std::string_view bmfontFilePath,
const Rect& imageRect, const Rect& imageRect,
bool imageRotated, bool imageRotated,
float fontSize = 0); float fontSize = 0);
/** Sets a new bitmap font to Label */ /** Sets a new bitmap font to Label */
virtual bool setBMFontFilePath(const std::string& bmfontFilePath, virtual bool setBMFontFilePath(std::string_view bmfontFilePath,
const std::string& subTextureKey, std::string_view subTextureKey,
float fontSize = 0); float fontSize = 0);
/** Sets a new bitmap font to Label */ /** 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, const Vec2& imageOffset,
float fontSize = 0); float fontSize = 0);
/** Returns the bitmap font used by the Label.*/ /** 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. * 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. * Sets a new char map configuration to Label.
@ -370,9 +370,9 @@ public:
/** /**
* Sets a new char map configuration to Label. * 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. * Sets a new system font to Label.
@ -380,10 +380,10 @@ public:
* @param font A font file or a font family name. * @param font A font file or a font family name.
* @warning * @warning
*/ */
virtual void setSystemFontName(const std::string& font); virtual void setSystemFontName(std::string_view font);
/** Returns the system font used by the Label.*/ /** 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.*/ /* Sets the system font size of Label.*/
virtual void setSystemFontSize(float fontSize); virtual void setSystemFontSize(float fontSize);
@ -403,7 +403,7 @@ public:
virtual void setString(std::string_view text) override; virtual void setString(std::string_view text) override;
/** Return the text the Label is currently displaying.*/ /** 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. * Return the number of lines of text.
@ -716,15 +716,15 @@ public:
*/ */
virtual ~Label(); virtual ~Label();
bool initWithTTF(const std::string& text, bool initWithTTF(std::string_view text,
const std::string& fontFilePath, std::string_view fontFilePath,
float fontSize, float fontSize,
const Vec2& dimensions = Vec2::ZERO, const Vec2& dimensions = Vec2::ZERO,
TextHAlignment hAlignment = TextHAlignment::LEFT, TextHAlignment hAlignment = TextHAlignment::LEFT,
TextVAlignment vAlignment = TextVAlignment::TOP); TextVAlignment vAlignment = TextVAlignment::TOP);
bool initWithTTF(const TTFConfig& ttfConfig, bool initWithTTF(const TTFConfig& ttfConfig,
const std::string& text, std::string_view text,
TextHAlignment hAlignment = TextHAlignment::LEFT, TextHAlignment hAlignment = TextHAlignment::LEFT,
int maxLineWidth = 0); int maxLineWidth = 0);

View File

@ -40,8 +40,8 @@ NS_CC_BEGIN
// CCLabelAtlas - Creation & Init // CCLabelAtlas - Creation & Init
LabelAtlas* LabelAtlas::create(const std::string& string, LabelAtlas* LabelAtlas::create(std::string_view string,
const std::string& charMapFile, std::string_view charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
int startCharMap) int startCharMap)
@ -56,8 +56,8 @@ LabelAtlas* LabelAtlas::create(const std::string& string,
return nullptr; return nullptr;
} }
bool LabelAtlas::initWithString(const std::string& string, bool LabelAtlas::initWithString(std::string_view string,
const std::string& charMapFile, std::string_view charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
int startCharMap) int startCharMap)
@ -66,7 +66,7 @@ bool LabelAtlas::initWithString(const std::string& string,
return initWithString(string, texture, itemWidth, itemHeight, startCharMap); return initWithString(string, texture, itemWidth, itemHeight, startCharMap);
} }
bool LabelAtlas::initWithString(const std::string& string, bool LabelAtlas::initWithString(std::string_view string,
Texture2D* texture, Texture2D* texture,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
@ -81,7 +81,7 @@ bool LabelAtlas::initWithString(const std::string& string,
return false; 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(); LabelAtlas* ret = new LabelAtlas();
@ -97,7 +97,7 @@ LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& fnt
return ret; return ret;
} }
LabelAtlas* LabelAtlas::create(const std::string& string, LabelAtlas* LabelAtlas::create(std::string_view string,
Texture2D* texture, Texture2D* texture,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
@ -117,7 +117,7 @@ LabelAtlas* LabelAtlas::create(const std::string& string,
return ret; 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 pathStr = FileUtils::getInstance()->fullPathForFilename(fntFile);
std::string relPathStr = pathStr.substr(0, pathStr.find_last_of('/')) + "/"; 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(); std::string textureFilename = relPathStr + dict["textureFilename"].asString();
unsigned int width = dict["itemWidth"].asInt() / CC_CONTENT_SCALE_FACTOR(); unsigned int width = static_cast<unsigned int>(dict["itemWidth"].asInt() / CC_CONTENT_SCALE_FACTOR());
unsigned int height = dict["itemHeight"].asInt() / CC_CONTENT_SCALE_FACTOR(); unsigned int height = static_cast<unsigned int>(dict["itemHeight"].asInt() / CC_CONTENT_SCALE_FACTOR());
unsigned int startChar = dict["firstChar"].asInt(); unsigned int startChar = dict["firstChar"].asInt();
this->initWithString(theString, textureFilename, width, height, startChar); this->initWithString(theString, textureFilename, width, height, startChar);
@ -156,8 +156,8 @@ void LabelAtlas::updateAtlasValues()
float itemHeightInPixels = _itemHeight * CC_CONTENT_SCALE_FACTOR(); float itemHeightInPixels = _itemHeight * CC_CONTENT_SCALE_FACTOR();
if (_ignoreContentScaleFactor) if (_ignoreContentScaleFactor)
{ {
itemWidthInPixels = _itemWidth; itemWidthInPixels = static_cast<float>(_itemWidth);
itemHeightInPixels = _itemHeight; itemHeightInPixels = static_cast<float>(_itemHeight);
} }
CCASSERT(n <= _textureAtlas->getCapacity(), "updateAtlasValues: Invalid String length"); CCASSERT(n <= _textureAtlas->getCapacity(), "updateAtlasValues: Invalid String length");
@ -239,7 +239,7 @@ void LabelAtlas::setString(std::string_view label)
_quadsToDraw = len; _quadsToDraw = len;
} }
const std::string& LabelAtlas::getString() const std::string_view LabelAtlas::getString() const
{ {
return _string; return _string;
} }

View File

@ -58,8 +58,8 @@ class CC_DLL LabelAtlas : public AtlasNode, public LabelProtocol
public: public:
/** Creates the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the /** 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. */ * starting char of the atlas. */
static LabelAtlas* create(const std::string& string, static LabelAtlas* create(std::string_view string,
const std::string& charMapFile, std::string_view charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
int startCharMap); int startCharMap);
@ -68,13 +68,13 @@ public:
* Creates the LabelAtlas with a string and a configuration file. * Creates the LabelAtlas with a string and a configuration file.
* @since v2.0 * @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 * Creates the LabelAtlas with a string, a texture, the width and height of each element and the starting char of
* the atlas. * the atlas.
*/ */
static LabelAtlas* create(const std::string& string, static LabelAtlas* create(std::string_view string,
Texture2D* texture, Texture2D* texture,
int itemWidth, int itemWidth,
int itemHeight, 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 /** 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. */ * the starting char of the atlas. */
bool initWithString(const std::string& string, bool initWithString(std::string_view string,
const std::string& charMapFile, std::string_view charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
int startCharMap); int startCharMap);
@ -92,14 +92,14 @@ public:
* Initializes the LabelAtlas with a string and a configuration file. * Initializes the LabelAtlas with a string and a configuration file.
* @since v2.0 * @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 /** Initializes the LabelAtlas with a string, a texture, the width and height in points of each element and the
* starting char of the atlas */ * 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 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; virtual void updateAtlasValues() override;
/** /**

View File

@ -109,7 +109,7 @@ int Label::getFirstWordLen(const std::u32string& utf32Text, int startIndex, int
break; break;
} }
nextLetterX += letterDef.xAdvance * _bmfontScale + _additionalKerning; nextLetterX += static_cast<int>(letterDef.xAdvance * _bmfontScale + _additionalKerning);
len++; len++;
} }
@ -140,7 +140,7 @@ void Label::updateBMFontScale()
if (_currentLabelType == LabelType::BMFONT) if (_currentLabelType == LabelType::BMFONT)
{ {
FontFNT* bmFont = (FontFNT*)font; FontFNT* bmFont = (FontFNT*)font;
float originalFontSize = bmFont->getOriginalFontSize(); auto originalFontSize = bmFont->getOriginalFontSize();
_bmfontScale = _bmFontSize * CC_CONTENT_SCALE_FACTOR() / originalFontSize; _bmfontScale = _bmFontSize * CC_CONTENT_SCALE_FACTOR() / originalFontSize;
} }
else else
@ -242,7 +242,7 @@ bool Label::multilineTextWrap(const std::function<int(const std::u32string&, int
{ {
float newLetterWidth = 0.f; float newLetterWidth = 0.f;
if (_horizontalKernings && letterIndex < textLen - 1) if (_horizontalKernings && letterIndex < textLen - 1)
newLetterWidth = _horizontalKernings[letterIndex + 1]; newLetterWidth = static_cast<float>(_horizontalKernings[letterIndex + 1]);
newLetterWidth += letterDef.xAdvance * _bmfontScale + _additionalKerning; newLetterWidth += letterDef.xAdvance * _bmfontScale + _additionalKerning;
nextLetterX += newLetterWidth; nextLetterX += newLetterWidth;

View File

@ -175,7 +175,7 @@ void Menu::addChild(Node* child, int zOrder, int tag)
Layer::addChild(child, zOrder, 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<MenuItem*>(child) != nullptr, "Menu only supports MenuItem objects as children"); CCASSERT(dynamic_cast<MenuItem*>(child) != nullptr, "Menu only supports MenuItem objects as children");
Layer::addChild(child, zOrder, name); Layer::addChild(child, zOrder, name);

View File

@ -148,7 +148,7 @@ public:
virtual void addChild(Node* child) override; virtual void addChild(Node* child) override;
virtual void addChild(Node* child, int zOrder) 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, 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 onEnter() override;
virtual void onExit() override; virtual void onExit() override;

View File

@ -180,13 +180,13 @@ bool MenuItemLabel::initWithLabel(Node* label, const ccMenuCallback& callback)
MenuItemLabel::~MenuItemLabel() {} MenuItemLabel::~MenuItemLabel() {}
void MenuItemLabel::setString(const std::string& label) void MenuItemLabel::setString(std::string_view label)
{ {
dynamic_cast<LabelProtocol*>(_label)->setString(label); dynamic_cast<LabelProtocol*>(_label)->setString(label);
this->setContentSize(_label->getContentSize()); this->setContentSize(_label->getContentSize());
} }
std::string MenuItemLabel::getString() const std::string_view MenuItemLabel::getString() const
{ {
auto label = dynamic_cast<LabelProtocol*>(_label); auto label = dynamic_cast<LabelProtocol*>(_label);
return label->getString(); return label->getString();
@ -259,8 +259,8 @@ void MenuItemLabel::setEnabled(bool enabled)
// CCMenuItemAtlasFont // CCMenuItemAtlasFont
// //
MenuItemAtlasFont* MenuItemAtlasFont::create(const std::string& value, MenuItemAtlasFont* MenuItemAtlasFont::create(std::string_view value,
const std::string& charMapFile, std::string_view charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
char startCharMap) char startCharMap)
@ -269,8 +269,8 @@ MenuItemAtlasFont* MenuItemAtlasFont::create(const std::string& value,
(const ccMenuCallback&)nullptr); (const ccMenuCallback&)nullptr);
} }
MenuItemAtlasFont* MenuItemAtlasFont::create(const std::string& value, MenuItemAtlasFont* MenuItemAtlasFont::create(std::string_view value,
const std::string& charMapFile, std::string_view charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
char startCharMap, char startCharMap,
@ -282,8 +282,8 @@ MenuItemAtlasFont* MenuItemAtlasFont::create(const std::string& value,
return ret; return ret;
} }
bool MenuItemAtlasFont::initWithString(const std::string& value, bool MenuItemAtlasFont::initWithString(std::string_view value,
const std::string& charMapFile, std::string_view charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
char startCharMap, char startCharMap,
@ -312,7 +312,7 @@ int MenuItemFont::getFontSize()
return _globalFontSize; return _globalFontSize;
} }
void MenuItemFont::setFontName(const std::string& name) void MenuItemFont::setFontName(std::string_view name)
{ {
if (_globalFontNameRelease) if (_globalFontNameRelease)
{ {
@ -322,12 +322,12 @@ void MenuItemFont::setFontName(const std::string& name)
_globalFontNameRelease = true; _globalFontNameRelease = true;
} }
const std::string& MenuItemFont::getFontName() std::string_view MenuItemFont::getFontName()
{ {
return _globalFontName; 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(); MenuItemFont* ret = new MenuItemFont();
ret->initWithString(value, callback); ret->initWithString(value, callback);
@ -335,7 +335,7 @@ MenuItemFont* MenuItemFont::create(const std::string& value, const ccMenuCallbac
return ret; return ret;
} }
MenuItemFont* MenuItemFont::create(const std::string& value) MenuItemFont* MenuItemFont::create(std::string_view value)
{ {
MenuItemFont* ret = new MenuItemFont(); MenuItemFont* ret = new MenuItemFont();
ret->initWithString(value, (const ccMenuCallback&)nullptr); ret->initWithString(value, (const ccMenuCallback&)nullptr);
@ -350,7 +350,7 @@ MenuItemFont::~MenuItemFont()
CCLOGINFO("In the destructor of MenuItemFont (%p).", this); 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"); CCASSERT(!value.empty(), "Value length must be greater than 0");
@ -377,14 +377,14 @@ int MenuItemFont::getFontSizeObj() const
return _fontSize; return _fontSize;
} }
void MenuItemFont::setFontNameObj(const std::string& name) void MenuItemFont::setFontNameObj(std::string_view name)
{ {
_fontName = name; _fontName = name;
dynamic_cast<Label*>(_label)->setSystemFontName(_fontName); dynamic_cast<Label*>(_label)->setSystemFontName(_fontName);
this->setContentSize(dynamic_cast<Label*>(_label)->getContentSize()); this->setContentSize(dynamic_cast<Label*>(_label)->getContentSize());
} }
const std::string& MenuItemFont::getFontNameObj() const std::string_view MenuItemFont::getFontNameObj() const
{ {
return _fontName; return _fontName;
} }
@ -600,21 +600,21 @@ bool MenuItemImage::init()
return initWithNormalImage("", "", "", (const ccMenuCallback&)nullptr); 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); return MenuItemImage::create(normalImage, selectedImage, "", (const ccMenuCallback&)nullptr);
} }
MenuItemImage* MenuItemImage::create(const std::string& normalImage, MenuItemImage* MenuItemImage::create(std::string_view normalImage,
const std::string& selectedImage, std::string_view selectedImage,
const ccMenuCallback& callback) const ccMenuCallback& callback)
{ {
return MenuItemImage::create(normalImage, selectedImage, "", callback); return MenuItemImage::create(normalImage, selectedImage, "", callback);
} }
MenuItemImage* MenuItemImage::create(const std::string& normalImage, MenuItemImage* MenuItemImage::create(std::string_view normalImage,
const std::string& selectedImage, std::string_view selectedImage,
const std::string& disabledImage, std::string_view disabledImage,
const ccMenuCallback& callback) const ccMenuCallback& callback)
{ {
MenuItemImage* ret = new MenuItemImage(); MenuItemImage* ret = new MenuItemImage();
@ -627,9 +627,9 @@ MenuItemImage* MenuItemImage::create(const std::string& normalImage,
return nullptr; return nullptr;
} }
MenuItemImage* MenuItemImage::create(const std::string& normalImage, MenuItemImage* MenuItemImage::create(std::string_view normalImage,
const std::string& selectedImage, std::string_view selectedImage,
const std::string& disabledImage) std::string_view disabledImage)
{ {
MenuItemImage* ret = new MenuItemImage(); MenuItemImage* ret = new MenuItemImage();
if (ret->initWithNormalImage(normalImage, selectedImage, disabledImage, (const ccMenuCallback&)nullptr)) if (ret->initWithNormalImage(normalImage, selectedImage, disabledImage, (const ccMenuCallback&)nullptr))
@ -641,9 +641,9 @@ MenuItemImage* MenuItemImage::create(const std::string& normalImage,
return nullptr; return nullptr;
} }
bool MenuItemImage::initWithNormalImage(const std::string& normalImage, bool MenuItemImage::initWithNormalImage(std::string_view normalImage,
const std::string& selectedImage, std::string_view selectedImage,
const std::string& disabledImage, std::string_view disabledImage,
const ccMenuCallback& callback) const ccMenuCallback& callback)
{ {
Node* normalSprite = nullptr; Node* normalSprite = nullptr;

View File

@ -137,10 +137,10 @@ public:
static MenuItemLabel* create(Node* label); static MenuItemLabel* create(Node* label);
/** Sets a new string to the inner 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. */ /** 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. */ /** Gets the color that will be used when the item is disabled. */
const Color3B& getDisabledColor() const { return _disabledColor; } const Color3B& getDisabledColor() const { return _disabledColor; }
@ -196,14 +196,14 @@ class CC_DLL MenuItemAtlasFont : public MenuItemLabel
{ {
public: public:
/** Creates a menu item from a string and atlas with a target/selector. */ /** Creates a menu item from a string and atlas with a target/selector. */
static MenuItemAtlasFont* create(const std::string& value, static MenuItemAtlasFont* create(std::string_view value,
const std::string& charMapFile, std::string_view charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
char startCharMap); char startCharMap);
/** Creates a menu item from a string and atlas. Use it with MenuItemToggle. */ /** Creates a menu item from a string and atlas. Use it with MenuItemToggle. */
static MenuItemAtlasFont* create(const std::string& value, static MenuItemAtlasFont* create(std::string_view value,
const std::string& charMapFile, std::string_view charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
char startCharMap, char startCharMap,
@ -222,8 +222,8 @@ public:
virtual ~MenuItemAtlasFont() {} virtual ~MenuItemAtlasFont() {}
/** Initializes a menu item from a string and atlas with a target/selector. */ /** Initializes a menu item from a string and atlas with a target/selector. */
bool initWithString(const std::string& value, bool initWithString(std::string_view value,
const std::string& charMapFile, std::string_view charMapFile,
int itemWidth, int itemWidth,
int itemHeight, int itemHeight,
char startCharMap, char startCharMap,
@ -240,18 +240,18 @@ class CC_DLL MenuItemFont : public MenuItemLabel
{ {
public: public:
/** Creates a menu item from a string without target/selector. To be used with MenuItemToggle. */ /** 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. */ /** 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. */ /** Set default font size. */
static void setFontSize(int size); static void setFontSize(int size);
/** Get default font size. */ /** Get default font size. */
static int getFontSize(); static int getFontSize();
/** Set the default font name. */ /** Set the default font name. */
static void setFontName(const std::string& name); static void setFontName(std::string_view name);
/** Get the default font name. */ /** Get the default font name. */
static const std::string& getFontName(); static std::string_view getFontName();
/** Set font size. /** Set font size.
* c++ can not overload static and non-static member functions with the same parameter types. * c++ can not overload static and non-static member functions with the same parameter types.
@ -274,13 +274,13 @@ public:
* @js setFontName * @js setFontName
* @js NA * @js NA
*/ */
void setFontNameObj(const std::string& name); void setFontNameObj(std::string_view name);
/** Returns the name of the Font. /** Returns the name of the Font.
* @js getFontNameObj * @js getFontNameObj
* @js NA * @js NA
*/ */
const std::string& getFontNameObj() const; std::string_view getFontNameObj() const;
CC_CONSTRUCTOR_ACCESS : CC_CONSTRUCTOR_ACCESS :
/** /**
@ -294,7 +294,7 @@ public:
virtual ~MenuItemFont(); virtual ~MenuItemFont();
/** Initializes a menu item from a string with a target/selector. */ /** 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: protected:
int _fontSize; int _fontSize;
@ -392,19 +392,19 @@ public:
/** Creates an MenuItemImage. */ /** Creates an MenuItemImage. */
static MenuItemImage* create(); static MenuItemImage* create();
/** Creates a menu item with a normal and selected image.*/ /** 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.*/ /** Creates a menu item with a normal,selected and disabled image.*/
static MenuItemImage* create(const std::string& normalImage, static MenuItemImage* create(std::string_view normalImage,
const std::string& selectedImage, std::string_view selectedImage,
const std::string& disabledImage); std::string_view disabledImage);
/** Creates a menu item with a normal and selected image with a callable object. */ /** Creates a menu item with a normal and selected image with a callable object. */
static MenuItemImage* create(const std::string& normalImage, static MenuItemImage* create(std::string_view normalImage,
const std::string& selectedImage, std::string_view selectedImage,
const ccMenuCallback& callback); const ccMenuCallback& callback);
/** Creates a menu item with a normal,selected and disabled image with a callable object. */ /** Creates a menu item with a normal,selected and disabled image with a callable object. */
static MenuItemImage* create(const std::string& normalImage, static MenuItemImage* create(std::string_view normalImage,
const std::string& selectedImage, std::string_view selectedImage,
const std::string& disabledImage, std::string_view disabledImage,
const ccMenuCallback& callback); const ccMenuCallback& callback);
/** Sets the sprite frame for the normal image. */ /** Sets the sprite frame for the normal image. */
@ -429,9 +429,9 @@ public:
bool init(); bool init();
/** Initializes a menu item with a normal, selected and disabled image with a callable object. */ /** Initializes a menu item with a normal, selected and disabled image with a callable object. */
bool initWithNormalImage(const std::string& normalImage, bool initWithNormalImage(std::string_view normalImage,
const std::string& selectedImage, std::string_view selectedImage,
const std::string& disabledImage, std::string_view disabledImage,
const ccMenuCallback& callback); const ccMenuCallback& callback);
private: private:

View File

@ -56,7 +56,7 @@ MotionStreak* MotionStreak::create(float fade,
float minSeg, float minSeg,
float stroke, float stroke,
const Color3B& color, const Color3B& color,
const std::string& path) std::string_view path)
{ {
MotionStreak* ret = new MotionStreak(); MotionStreak* ret = new MotionStreak();
if (ret->initWithFade(fade, minSeg, stroke, color, path)) if (ret->initWithFade(fade, minSeg, stroke, color, path))
@ -82,7 +82,7 @@ MotionStreak* MotionStreak::create(float fade, float minSeg, float stroke, const
return nullptr; 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"); CCASSERT(!path.empty(), "Invalid filename");

View File

@ -59,7 +59,7 @@ public:
float minSeg, float minSeg,
float strokeWidth, float strokeWidth,
const Color3B& strokeColor, 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. /** Creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture.
* *
* @param timeToFade The fade time, in seconds. * @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 /** 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 */ /** 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); bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture);

View File

@ -56,7 +56,7 @@ THE SOFTWARE.
/* /*
* 4.5x faster than std::hash in release mode * 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 NS_CC_BEGIN
@ -695,12 +695,12 @@ void Node::setTag(int tag)
_tag = tag; _tag = tag;
} }
const std::string& Node::getName() const std::string_view Node::getName() const
{ {
return _name; return _name;
} }
void Node::setName(const std::string& name) void Node::setName(std::string_view name)
{ {
updateParentChildrenIndexer(name); updateParentChildrenIndexer(name);
_name = 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); uint64_t newHash = CC_HASH_NODE_NAME(name);
auto parentChildrenIndexer = getParentChildrenIndexer(); auto parentChildrenIndexer = getParentChildrenIndexer();
@ -817,7 +817,7 @@ Node* Node::getChildByTag(int tag) const
return nullptr; return nullptr;
} }
Node* Node::getChildByName(const std::string& name) const Node* Node::getChildByName(std::string_view name) const
{ {
// CCASSERT(!name.empty(), "Invalid name"); // CCASSERT(!name.empty(), "Invalid name");
auto hash = CC_HASH_NODE_NAME(name); auto hash = CC_HASH_NODE_NAME(name);
@ -837,7 +837,7 @@ Node* Node::getChildByName(const std::string& name) const
return nullptr; return nullptr;
} }
void Node::enumerateChildren(const std::string& name, std::function<bool(Node*)> callback) const void Node::enumerateChildren(std::string_view name, std::function<bool(Node*)> callback) const
{ {
CCASSERT(!name.empty(), "Invalid name"); CCASSERT(!name.empty(), "Invalid name");
CCASSERT(callback != nullptr, "Invalid callback function"); CCASSERT(callback != nullptr, "Invalid callback function");
@ -865,7 +865,7 @@ void Node::enumerateChildren(const std::string& name, std::function<bool(Node*)>
} }
// Remove '//', '/..' if exist // Remove '//', '/..' if exist
std::string newName = name.substr(subStrStartPos, subStrlength); auto newName = name.substr(subStrStartPos, subStrlength);
const Node* target = this; const Node* target = this;
@ -886,15 +886,15 @@ void Node::enumerateChildren(const std::string& name, std::function<bool(Node*)>
else else
{ {
// name is xxx // 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<bool(Node*)> callback) const bool Node::doEnumerateRecursive(const Node* node, std::string_view name, std::function<bool(Node*)> callback) const
{ {
bool ret = false; bool ret = false;
if (node->doEnumerate(name, callback)) if (node->doEnumerate(std::string{name}, callback))
{ {
// search itself // search itself
ret = true; ret = true;
@ -966,7 +966,7 @@ void Node::addChild(Node* child, int localZOrder, int tag)
addChildHelper(child, localZOrder, tag, "", true); 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 != nullptr, "Argument must be non-nil");
CCASSERT(child->_parent == nullptr, "child already added. It can't be added again"); 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); 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 { auto assertNotSelfChild([this, child]() -> bool {
for (Node* parent(getParent()); parent != nullptr; parent = parent->getParent()) 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"); CCASSERT(!name.empty(), "Invalid name");
@ -1096,7 +1096,7 @@ void Node::removeChildByName(const std::string& name, bool cleanup)
if (child == nullptr) 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 else
{ {
@ -1490,7 +1490,7 @@ bool Node::isScheduled(SEL_SCHEDULE selector) const
return _scheduler->isScheduled(selector, this); 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); 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); _scheduler->schedule(selector, this, interval, repeat, delay, !_running);
} }
void Node::schedule(const std::function<void(float)>& callback, const std::string& key) void Node::schedule(const std::function<void(float)>& callback, std::string_view key)
{ {
_scheduler->schedule(callback, this, 0, !_running, key); _scheduler->schedule(callback, this, 0, !_running, key);
} }
void Node::schedule(const std::function<void(float)>& callback, float interval, const std::string& key) void Node::schedule(const std::function<void(float)>& callback, float interval, std::string_view key)
{ {
_scheduler->schedule(callback, this, interval, !_running, key); _scheduler->schedule(callback, this, interval, !_running, key);
} }
@ -1561,7 +1561,7 @@ void Node::schedule(const std::function<void(float)>& callback,
float interval, float interval,
unsigned int repeat, unsigned int repeat,
float delay, float delay,
const std::string& key) std::string_view key)
{ {
_scheduler->schedule(callback, this, interval, repeat, delay, !_running, 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); this->schedule(selector, 0.0f, 0, delay);
} }
void Node::scheduleOnce(const std::function<void(float)>& callback, float delay, const std::string& key) void Node::scheduleOnce(const std::function<void(float)>& callback, float delay, std::string_view key)
{ {
_scheduler->schedule(callback, this, 0, 0, delay, !_running, key); _scheduler->schedule(callback, this, 0, 0, delay, !_running, key);
} }
@ -1585,7 +1585,7 @@ void Node::unschedule(SEL_SCHEDULE selector)
_scheduler->unschedule(selector, this); _scheduler->unschedule(selector, this);
} }
void Node::unschedule(const std::string& key) void Node::unschedule(std::string_view key)
{ {
_scheduler->unschedule(key, this); _scheduler->unschedule(key, this);
} }
@ -1923,7 +1923,7 @@ void Node::updateTransform()
// MARK: components // MARK: components
Component* Node::getComponent(const std::string& name) Component* Node::getComponent(std::string_view name)
{ {
if (_componentContainer) if (_componentContainer)
return _componentContainer->get(name); return _componentContainer->get(name);
@ -1943,7 +1943,7 @@ bool Node::addComponent(Component* component)
return _componentContainer->add(component); return _componentContainer->add(component);
} }
bool Node::removeComponent(const std::string& name) bool Node::removeComponent(std::string_view name)
{ {
if (_componentContainer) if (_componentContainer)
return _componentContainer->remove(name); return _componentContainer->remove(name);

View File

@ -762,7 +762,7 @@ public:
* @param name A string to identify the node easily. Please refer to `setName(int)`. * @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. * Gets a child from the container with its tag.
* *
@ -796,7 +796,7 @@ public:
* *
* @since v3.2 * @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. * 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. * @return a Node with the given name that can be cast to Type T.
*/ */
template <typename T> template <typename T>
T getChildByName(const std::string& name) const T getChildByName(std::string_view name) const
{ {
return static_cast<T>(getChildByName(name)); return static_cast<T>(getChildByName(name));
} }
@ -835,7 +835,7 @@ public:
* *
* @since v3.2 * @since v3.2
*/ */
virtual void enumerateChildren(const std::string& name, std::function<bool(Node* node)> callback) const; virtual void enumerateChildren(std::string_view name, std::function<bool(Node* node)> callback) const;
/** /**
* Returns the array of the node's children. * Returns the array of the node's children.
* *
@ -909,7 +909,7 @@ public:
* @param name A string that identifies a child node. * @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. * @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. * Removes all children from the container with a cleanup.
* *
@ -989,13 +989,13 @@ public:
* *
* @since v3.2 * @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. /** Changes the name that is used to identify the node easily.
* @param name A string that identifies the node. * @param name A string that identifies the node.
* *
* @since v3.2 * @since v3.2
*/ */
virtual void setName(const std::string& name); virtual void setName(std::string_view name);
/** /**
* Returns a custom user data pointer. * Returns a custom user data pointer.
@ -1306,7 +1306,7 @@ public:
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
bool isScheduled(const std::string& key) const; bool isScheduled(std::string_view key) const;
/** /**
* Schedules the "update" method. * 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. * @param key The key of the lambda function. To be used if you want to unschedule it.
* @lua NA * @lua NA
*/ */
void scheduleOnce(const std::function<void(float)>& callback, float delay, const std::string& key); void scheduleOnce(const std::function<void(float)>& callback, float delay, std::string_view key);
/** /**
* Schedules a custom selector, the scheduled selector will be ticked every frame. * 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. * @param key The key of the lambda function. To be used if you want to unschedule it.
* @lua NA * @lua NA
*/ */
void schedule(const std::function<void(float)>& callback, const std::string& key); void schedule(const std::function<void(float)>& callback, std::string_view key);
/** /**
* Schedules a lambda function. The scheduled lambda function will be called every "interval" seconds * 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 * @param key The key of the lambda function. To be used if you want to unschedule it
* @lua NA * @lua NA
*/ */
void schedule(const std::function<void(float)>& callback, float interval, const std::string& key); void schedule(const std::function<void(float)>& callback, float interval, std::string_view key);
/** /**
* Schedules a lambda function. * Schedules a lambda function.
@ -1430,7 +1430,7 @@ public:
float interval, float interval,
unsigned int repeat, unsigned int repeat,
float delay, float delay,
const std::string& key); std::string_view key);
/** /**
* Unschedules a custom selector. * Unschedules a custom selector.
@ -1447,7 +1447,7 @@ public:
* @param key The key of the lambda function to be unscheduled. * @param key The key of the lambda function to be unscheduled.
* @lua NA * @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 * 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. * @param name A given name of component.
* @return The Component by name. * @return The Component by name.
*/ */
Component* getComponent(const std::string& name); Component* getComponent(std::string_view name);
/** /**
* Adds a component. * Adds a component.
@ -1649,7 +1649,7 @@ public:
* @param name A given name of component. * @param name A given name of component.
* @return True if removed success. * @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. * Removes a component by its pointer.
@ -1854,7 +1854,7 @@ protected:
virtual void updateColor() {} virtual void updateColor() {}
bool doEnumerate(std::string name, std::function<bool(Node*)> callback) const; bool doEnumerate(std::string name, std::function<bool(Node*)> callback) const;
bool doEnumerateRecursive(const Node* node, const std::string& name, std::function<bool(Node*)> callback) const; bool doEnumerateRecursive(const Node* node, std::string_view name, std::function<bool(Node*)> callback) const;
// check whether this camera mask is visible by the current visiting camera // check whether this camera mask is visible by the current visiting camera
bool isVisitableByVisitingCamera() const; bool isVisitableByVisitingCamera() const;
@ -1865,10 +1865,10 @@ protected:
void updateRotation3D(); void updateRotation3D();
void updateParentChildrenIndexer(int tag); void updateParentChildrenIndexer(int tag);
void updateParentChildrenIndexer(const std::string& name); void updateParentChildrenIndexer(std::string_view name);
private: 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(); NodeIndexerMap_t* getParentChildrenIndexer();

View File

@ -91,7 +91,7 @@ void ParallaxNode::addChild(Node* /*child*/, int /*zOrder*/, int /*tag*/)
CCASSERT(0, "ParallaxNode: use addChild:z:parallaxRatio:positionOffset instead"); 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"); CCASSERT(0, "ParallaxNode: use addChild:z:parallaxRatio:positionOffset instead");
} }

View File

@ -83,7 +83,7 @@ public:
// Overrides // Overrides
// //
virtual void addChild(Node* child, int zOrder, int tag) 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 removeChild(Node* child, bool cleanup) override; virtual void removeChild(Node* child, bool cleanup) override;
virtual void removeAllChildrenWithCleanup(bool cleanup) override; virtual void removeAllChildrenWithCleanup(bool cleanup) override;
virtual void visit(Renderer* renderer, const Mat4& parentTransform, uint32_t parentFlags) override; virtual void visit(Renderer* renderer, const Mat4& parentTransform, uint32_t parentFlags) override;

View File

@ -108,7 +108,7 @@ ParticleBatchNode* ParticleBatchNode::createWithTexture(Texture2D* tex, int capa
* creation with File Image * 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(); ParticleBatchNode* p = new ParticleBatchNode();
if (p->initWithFile(imageFile, capacity)) if (p->initWithFile(imageFile, capacity))
@ -140,7 +140,7 @@ bool ParticleBatchNode::initWithTexture(Texture2D* tex, int capacity)
/* /*
* init with FileImage * 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); Texture2D* tex = _director->getTextureCache()->addImage(fileImage);
return initWithTexture(tex, capacity); return initWithTexture(tex, capacity);
@ -193,7 +193,7 @@ void ParticleBatchNode::addChild(Node* aChild, int zOrder, int tag)
addChildByTagOrName(child, zOrder, tag, "", true); 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(aChild != nullptr, "Argument must be non-nullptr");
CCASSERT(dynamic_cast<ParticleSystem*>(aChild) != nullptr, CCASSERT(dynamic_cast<ParticleSystem*>(aChild) != nullptr,
@ -208,7 +208,7 @@ void ParticleBatchNode::addChild(Node* aChild, int zOrder, const std::string& na
void ParticleBatchNode::addChildByTagOrName(ParticleSystem* child, void ParticleBatchNode::addChildByTagOrName(ParticleSystem* child,
int zOrder, int zOrder,
int tag, int tag,
const std::string& name, std::string_view name,
bool setTag) bool setTag)
{ {
// If this is the 1st children, then copy blending function // If this is the 1st children, then copy blending function
@ -251,7 +251,7 @@ void ParticleBatchNode::addChildByTagOrName(ParticleSystem* child,
// faster // faster
// FIXME: or possibly using vertexZ for reordering, that would be fastest // 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 // 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 != nullptr, "Argument must be non-nil");
CCASSERT(child->getParent() == nullptr, "child already added. It can't be added again"); CCASSERT(child->getParent() == nullptr, "child already added. It can't be added again");

View File

@ -87,7 +87,7 @@ public:
* @param capacity A capacity of particles. * @param capacity A capacity of particles.
* @return An autoreleased ParticleBatchNode object. * @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. /** Inserts a child into the ParticleBatchNode.
* *
@ -127,7 +127,7 @@ public:
using Node::addChild; using Node::addChild;
virtual void addChild(Node* child, int zOrder, int tag) 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 removeChild(Node* child, bool cleanup) override; virtual void removeChild(Node* child, bool cleanup) override;
virtual void reorderChild(Node* child, int zOrder) override; virtual void reorderChild(Node* child, int zOrder) override;
virtual void draw(Renderer* renderer, const Mat4& transform, uint32_t flags) 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 /** 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 */ * Texture2D class), a capacity of particles */
bool initWithFile(const std::string& fileImage, int capacity); bool initWithFile(std::string_view fileImage, int capacity);
private: private:
void updateAllAtlasIndexes(); void updateAllAtlasIndexes();
void increaseAtlasCapacityTo(ssize_t quantity); void increaseAtlasCapacityTo(ssize_t quantity);
int searchNewPositionInChildrenForZ(int z); int searchNewPositionInChildrenForZ(int z);
void getCurrentIndex(int* oldIndex, int* newIndex, Node* child, 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); int addChildHelper(ParticleSystem* child, int z, int aTag, std::string_view name, bool setTag);
void addChildByTagOrName(ParticleSystem* child, int z, int tag, const std::string& name, bool setTag); void addChildByTagOrName(ParticleSystem* child, int z, int tag, std::string_view name, bool setTag);
void updateBlendFunc(); void updateBlendFunc();
void updateProgramStateTexture(); void updateProgramStateTexture();

View File

@ -191,11 +191,6 @@ void ParticleData::release()
Vector<ParticleSystem*> ParticleSystem::__allInstances; Vector<ParticleSystem*> ParticleSystem::__allInstances;
float ParticleSystem::__totalParticleCountFactor = 1.0f; 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() ParticleSystem::ParticleSystem()
: _isBlendAdditive(false) : _isBlendAdditive(false)
, _isAutoRemoveOnFinish(false) , _isAutoRemoveOnFinish(false)
@ -250,7 +245,7 @@ ParticleSystem::ParticleSystem()
} }
// implementation ParticleSystem // implementation ParticleSystem
ParticleSystem* ParticleSystem::create(const std::string& plistFile) ParticleSystem* ParticleSystem::create(std::string_view plistFile)
{ {
ParticleSystem* ret = new ParticleSystem(); ParticleSystem* ret = new ParticleSystem();
if (ret->initWithFile(plistFile)) if (ret->initWithFile(plistFile))
@ -290,7 +285,7 @@ bool ParticleSystem::init()
return initWithTotalParticles(150); return initWithTotalParticles(150);
} }
bool ParticleSystem::initWithFile(const std::string& plistFile) bool ParticleSystem::initWithFile(std::string_view plistFile)
{ {
bool ret = false; bool ret = false;
_plistFile = FileUtils::getInstance()->fullPathForFilename(plistFile); _plistFile = FileUtils::getInstance()->fullPathForFilename(plistFile);
@ -299,7 +294,7 @@ bool ParticleSystem::initWithFile(const std::string& plistFile)
CCASSERT(!dict.empty(), "Particles: file not found"); CCASSERT(!dict.empty(), "Particles: file not found");
// FIXME: compute path from a path, should define a function somewhere to do it // 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) if (listFilePath.find('/') != string::npos)
{ {
listFilePath = listFilePath.substr(0, listFilePath.rfind('/') + 1); listFilePath = listFilePath.substr(0, listFilePath.rfind('/') + 1);
@ -318,7 +313,7 @@ bool ParticleSystem::initWithDictionary(const ValueMap& dictionary)
return initWithDictionary(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; bool ret = false;
unsigned char* buffer = nullptr; unsigned char* buffer = nullptr;
@ -487,12 +482,12 @@ bool ParticleSystem::initWithDictionary(const ValueMap& dictionary, const std::s
if (!dirname.empty() && textureDir != dirname) if (!dirname.empty() && textureDir != dirname)
{ {
textureName = textureName.substr(rPos + 1); textureName = textureName.substr(rPos + 1);
textureName = dirname + textureName; textureName.insert(0, dirname); // textureName = dirname + textureName;
} }
} }
else if (!dirname.empty() && !textureName.empty()) else if (!dirname.empty() && !textureName.empty())
{ {
textureName = dirname + textureName; textureName.insert(0, dirname); // textureName = dirname + textureName;
} }
Texture2D* tex = nullptr; Texture2D* tex = nullptr;

View File

@ -237,7 +237,7 @@ public:
* @param plistFile Particle plist file name. * @param plistFile Particle plist file name.
* @return An autoreleased ParticleSystem object. * @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. /** Create a system with a fixed number of particles.
* *
@ -761,7 +761,7 @@ public:
*/ */
virtual const BlendFunc& getBlendFunc() const override; virtual const BlendFunc& getBlendFunc() const override;
const std::string& getResourceFile() const { return _plistFile; } std::string_view getResourceFile() const { return _plistFile; }
/// @{ /// @{
/// @name implement Playable Protocol /// @name implement Playable Protocol
@ -793,7 +793,7 @@ public:
http://particledesigner.71squared.com/ http://particledesigner.71squared.com/
@since v0.99.3 @since v0.99.3
*/ */
bool initWithFile(const std::string& plistFile); bool initWithFile(std::string_view plistFile);
/** initializes a QuadParticleSystem from a Dictionary. /** initializes a QuadParticleSystem from a Dictionary.
@since v0.99.3 @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 /** initializes a particle system from a NSDictionary and the path from where to load the png
@since v2.1 @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 //! Initializes a system with a fixed number of particles
virtual bool initWithTotalParticles(int numberOfParticles); virtual bool initWithTotalParticles(int numberOfParticles);

View File

@ -91,7 +91,7 @@ ParticleSystemQuad::~ParticleSystemQuad()
// implementation ParticleSystemQuad // implementation ParticleSystemQuad
ParticleSystemQuad* ParticleSystemQuad::create(const std::string& filename) ParticleSystemQuad* ParticleSystemQuad::create(std::string_view filename)
{ {
ParticleSystemQuad* ret = new ParticleSystemQuad(); ParticleSystemQuad* ret = new ParticleSystemQuad();
if (ret->initWithFile(filename)) if (ret->initWithFile(filename))

View File

@ -75,7 +75,7 @@ public:
* @param filename Particle plist file name. * @param filename Particle plist file name.
* @return An autoreleased ParticleSystemQuad object. * @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. /** Creates a Particle Emitter with a dictionary.
* *
* @param dictionary Particle dictionary. * @param dictionary Particle dictionary.

View File

@ -18,7 +18,7 @@ using namespace std;
NS_CC_BEGIN 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"); CCASSERT(!filePath.empty(), "plist filename should not be nullptr");
@ -26,7 +26,7 @@ void PlistSpriteSheetLoader::load(const std::string& filePath, SpriteFrameCache&
if (fullPath.empty()) if (fullPath.empty())
{ {
// return if plist file doesn't exist // 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; return;
} }
@ -66,7 +66,7 @@ void PlistSpriteSheetLoader::load(const std::string& filePath, SpriteFrameCache&
addSpriteFramesWithDictionary(dict, texturePath, filePath, cache); 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); const auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
@ -74,8 +74,8 @@ void PlistSpriteSheetLoader::load(const std::string& filePath, Texture2D* textur
addSpriteFramesWithDictionary(dict, texture, filePath, cache); addSpriteFramesWithDictionary(dict, texture, filePath, cache);
} }
void PlistSpriteSheetLoader::load(const std::string& filePath, void PlistSpriteSheetLoader::load(std::string_view filePath,
const std::string& textureFileName, std::string_view textureFileName,
SpriteFrameCache& cache) SpriteFrameCache& cache)
{ {
CCASSERT(!textureFileName.empty(), "texture name should not be null"); 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); 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); const auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
@ -151,7 +151,7 @@ void PlistSpriteSheetLoader::reload(const std::string& filePath, SpriteFrameCach
void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary,
Texture2D* texture, Texture2D* texture,
const std::string& plist, std::string_view plist,
SpriteFrameCache& cache) SpriteFrameCache& cache)
{ {
/* /*
@ -178,15 +178,15 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary,
Vec2 textureSize; Vec2 textureSize;
// get the format // get the format
auto metaItr = dictionary.find("metadata"); auto metaItr = dictionary.find("metadata"sv);
if (metaItr != dictionary.end()) if (metaItr != dictionary.end())
{ {
auto& metadataDict = metaItr->second.asValueMap(); 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) if (format == 0)
{ {
auto x = frameDict["x"].asFloat(); auto x = optValue(frameDict, "x"sv).asFloat();
auto y = frameDict["y"].asFloat(); auto y = optValue(frameDict, "y"sv).asFloat();
auto w = frameDict["width"].asFloat(); auto w = optValue(frameDict, "width"sv).asFloat();
auto h = frameDict["height"].asFloat(); auto h = optValue(frameDict, "height"sv).asFloat();
auto ox = frameDict["offsetX"].asFloat(); auto ox = optValue(frameDict, "offsetX"sv).asFloat();
auto oy = frameDict["offsetY"].asFloat(); auto oy = optValue(frameDict, "offsetY"sv).asFloat();
auto ow = frameDict["originalWidth"].asInt(); auto ow = optValue(frameDict, "originalWidth"sv).asInt();
auto oh = frameDict["originalHeight"].asInt(); auto oh = optValue(frameDict, "originalHeight"sv).asInt();
// check ow/oh // check ow/oh
if (!ow || !oh) if (!ow || !oh)
{ {
@ -234,17 +234,17 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary,
} }
else if (format == 1 || format == 2) else if (format == 1 || format == 2)
{ {
auto frame = RectFromString(frameDict["frame"].asString()); auto frame = RectFromString(optValue(frameDict, "frame"sv).asString());
auto rotated = false; auto rotated = false;
// rotation // rotation
if (format == 2) if (format == 2)
{ {
rotated = frameDict["rotated"].asBool(); rotated = optValue(frameDict, "rotated"sv).asBool();
} }
auto offset = PointFromString(frameDict["offset"].asString()); auto offset = PointFromString(optValue(frameDict, "offset"sv).asString());
auto sourceSize = SizeFromString(frameDict["sourceSize"].asString()); auto sourceSize = SizeFromString(optValue(frameDict, "sourceSize"sv).asString());
// create frame // create frame
spriteFrame = SpriteFrame::createWithTexture(texture, frame, rotated, offset, sourceSize); spriteFrame = SpriteFrame::createWithTexture(texture, frame, rotated, offset, sourceSize);
@ -252,14 +252,14 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary,
else if (format == 3) else if (format == 3)
{ {
// get values // get values
auto spriteSize = SizeFromString(frameDict["spriteSize"].asString()); auto spriteSize = SizeFromString(optValue(frameDict, "spriteSize"sv).asString());
auto spriteOffset = PointFromString(frameDict["spriteOffset"].asString()); auto spriteOffset = PointFromString(optValue(frameDict, "spriteOffset"sv).asString());
auto spriteSourceSize = SizeFromString(frameDict["spriteSourceSize"].asString()); auto spriteSourceSize = SizeFromString(optValue(frameDict, "spriteSourceSize"sv).asString());
auto textureRect = RectFromString(frameDict["textureRect"].asString()); auto textureRect = RectFromString(optValue(frameDict, "textureRect"sv).asString());
auto textureRotated = frameDict["textureRotated"].asBool(); auto textureRotated = optValue(frameDict, "textureRotated"sv).asBool();
// get aliases // get aliases
auto& aliases = frameDict["aliases"].asValueVector(); auto& aliases = optValue(frameDict, "aliases"sv).asValueVector();
for (const auto& value : aliases) for (const auto& value : aliases)
{ {
@ -282,9 +282,9 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary,
if (frameDict.find("vertices") != frameDict.end()) if (frameDict.find("vertices") != frameDict.end())
{ {
using cocos2d::utils::parseIntegerList; using cocos2d::utils::parseIntegerList;
auto vertices = parseIntegerList(frameDict["vertices"].asString()); auto vertices = parseIntegerList(optValue(frameDict, "vertices"sv).asString());
auto verticesUV = parseIntegerList(frameDict["verticesUV"].asString()); auto verticesUV = parseIntegerList(optValue(frameDict, "verticesUV"sv).asString());
auto indices = parseIntegerList(frameDict["triangles"].asString()); auto indices = parseIntegerList(optValue(frameDict, "triangles"sv).asString());
PolygonInfo info; PolygonInfo info;
initializePolygonInfo(textureSize, spriteSourceSize, vertices, verticesUV, indices, info); initializePolygonInfo(textureSize, spriteSourceSize, vertices, verticesUV, indices, info);
@ -292,7 +292,7 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary,
} }
if (frameDict.find("anchor") != frameDict.end()) 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, void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dict,
const std::string& texturePath, std::string_view texturePath,
const std::string& plist, std::string_view plist,
SpriteFrameCache& cache) SpriteFrameCache& cache)
{ {
std::string pixelFormatName; std::string pixelFormatName;
@ -378,7 +378,7 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dict,
void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict, void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict,
Texture2D* texture, Texture2D* texture,
const std::string& plist, std::string_view plist,
SpriteFrameCache& cache) SpriteFrameCache& cache)
{ {
auto& framesDict = dict["frames"].asValueMap(); auto& framesDict = dict["frames"].asValueMap();
@ -401,8 +401,8 @@ void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict,
for (auto& iter : framesDict) for (auto& iter : framesDict)
{ {
ValueMap& frameDict = iter.second.asValueMap(); const ValueMap& frameDict = iter.second.asValueMap();
std::string spriteFrameName = iter.first; std::string_view spriteFrameName = iter.first;
cache.eraseFrame(spriteFrameName); cache.eraseFrame(spriteFrameName);
@ -411,14 +411,14 @@ void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict,
if (format == 0) if (format == 0)
{ {
const auto x = frameDict["x"].asFloat(); const auto x = optValue(frameDict, "x"sv).asFloat();
const auto y = frameDict["y"].asFloat(); const auto y = optValue(frameDict, "y"sv).asFloat();
const auto w = frameDict["width"].asFloat(); const auto w = optValue(frameDict, "width"sv).asFloat();
const auto h = frameDict["height"].asFloat(); const auto h = optValue(frameDict, "height"sv).asFloat();
const auto ox = frameDict["offsetX"].asFloat(); const auto ox = optValue(frameDict, "offsetX"sv).asFloat();
const auto oy = frameDict["offsetY"].asFloat(); const auto oy = optValue(frameDict, "offsetY"sv).asFloat();
auto ow = frameDict["originalWidth"].asInt(); auto ow = optValue(frameDict, "originalWidth"sv).asInt();
auto oh = frameDict["originalHeight"].asInt(); auto oh = optValue(frameDict, "originalHeight"sv).asInt();
// check ow/oh // check ow/oh
if (!ow || !oh) if (!ow || !oh)
{ {
@ -435,17 +435,17 @@ void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict,
} }
else if (format == 1 || format == 2) else if (format == 1 || format == 2)
{ {
auto frame = RectFromString(frameDict["frame"].asString()); auto frame = RectFromString(optValue(frameDict, "frame"sv).asString());
auto rotated = false; auto rotated = false;
// rotation // rotation
if (format == 2) if (format == 2)
{ {
rotated = frameDict["rotated"].asBool(); rotated = optValue(frameDict, "rotated"sv).asBool();
} }
auto offset = PointFromString(frameDict["offset"].asString()); auto offset = PointFromString(optValue(frameDict, "offset"sv).asString());
auto sourceSize = SizeFromString(frameDict["sourceSize"].asString()); auto sourceSize = SizeFromString(optValue(frameDict, "sourceSize"sv).asString());
// create frame // create frame
spriteFrame = SpriteFrame::createWithTexture(texture, frame, rotated, offset, sourceSize); spriteFrame = SpriteFrame::createWithTexture(texture, frame, rotated, offset, sourceSize);
@ -453,14 +453,14 @@ void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict,
else if (format == 3) else if (format == 3)
{ {
// get values // get values
const auto spriteSize = SizeFromString(frameDict["spriteSize"].asString()); const auto spriteSize = SizeFromString(optValue(frameDict, "spriteSize"sv).asString());
auto spriteOffset = PointFromString(frameDict["spriteOffset"].asString()); auto spriteOffset = PointFromString(optValue(frameDict, "spriteOffset"sv).asString());
auto spriteSourceSize = SizeFromString(frameDict["spriteSourceSize"].asString()); auto spriteSourceSize = SizeFromString(optValue(frameDict, "spriteSourceSize"sv).asString());
const auto textureRect = RectFromString(frameDict["textureRect"].asString()); const auto textureRect = RectFromString(optValue(frameDict, "textureRect"sv).asString());
const auto textureRotated = frameDict["textureRotated"].asBool(); const auto textureRotated = optValue(frameDict, "textureRotated"sv).asBool();
// get aliases // get aliases
ValueVector& aliases = frameDict["aliases"].asValueVector(); const ValueVector& aliases = optValue(frameDict, "aliases"sv).asValueVector();
for (const auto& value : aliases) for (const auto& value : aliases)
{ {

View File

@ -14,30 +14,30 @@ public:
static constexpr uint32_t FORMAT = SpriteSheetFormat::PLIST; static constexpr uint32_t FORMAT = SpriteSheetFormat::PLIST;
uint32_t getFormat() override { return FORMAT; } uint32_t getFormat() override { return FORMAT; }
void load(const std::string& filePath, SpriteFrameCache& cache) override; void load(std::string_view filePath, SpriteFrameCache& cache) override;
void load(const std::string& filePath, Texture2D* texture, SpriteFrameCache& cache) override; void load(std::string_view 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, std::string_view textureFileName, SpriteFrameCache& cache) override;
void load(const Data& content, Texture2D* texture, 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: protected:
/*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames. /*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames.
*/ */
void addSpriteFramesWithDictionary(ValueMap& dictionary, void addSpriteFramesWithDictionary(ValueMap& dictionary,
Texture2D* texture, Texture2D* texture,
const std::string& plist, std::string_view plist,
SpriteFrameCache& cache); SpriteFrameCache& cache);
/*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames. /*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames.
*/ */
void addSpriteFramesWithDictionary(ValueMap& dict, void addSpriteFramesWithDictionary(ValueMap& dict,
const std::string& texturePath, std::string_view texturePath,
const std::string& plist, std::string_view plist,
SpriteFrameCache& cache); SpriteFrameCache& cache);
void reloadSpriteFramesWithDictionary(ValueMap& dict, void reloadSpriteFramesWithDictionary(ValueMap& dict,
Texture2D* texture, Texture2D* texture,
const std::string& plist, std::string_view plist,
SpriteFrameCache& cache); SpriteFrameCache& cache);
}; };

View File

@ -357,9 +357,7 @@ void RenderTexture::visit(Renderer* renderer, const Mat4& parentTransform, uint3
// setOrderOfArrival(0); // setOrderOfArrival(0);
} }
bool RenderTexture::saveToFileAsNonPMA(const std::string& filename, bool RenderTexture::saveToFileAsNonPMA(std::string_view filename, bool isRGBA, SaveFileCallbackType callback)
bool isRGBA,
std::function<void(RenderTexture*, const std::string&)> callback)
{ {
std::string basename(filename); std::string basename(filename);
std::transform(basename.begin(), basename.end(), basename.begin(), ::tolower); 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); return saveToFileAsNonPMA(filename, Image::Format::JPG, false, callback);
} }
bool RenderTexture::saveToFile(const std::string& filename, bool RenderTexture::saveToFile(std::string_view filename, bool isRGBA, SaveFileCallbackType callback)
bool isRGBA,
std::function<void(RenderTexture*, const std::string&)> callback)
{ {
std::string basename(filename); std::string basename(filename);
std::transform(basename.begin(), basename.end(), basename.begin(), ::tolower); 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); 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, Image::Format format,
bool isRGBA, bool isRGBA,
std::function<void(RenderTexture*, const std::string&)> callback) SaveFileCallbackType callback)
{ {
CCASSERT(format == Image::Format::JPG || format == Image::Format::PNG, CCASSERT(format == Image::Format::JPG || format == Image::Format::PNG,
"the image can only be saved as JPG or PNG format"); "the image can only be saved as JPG or PNG format");
@ -419,7 +415,7 @@ bool RenderTexture::saveToFileAsNonPMA(const std::string& fileName,
_saveFileCallback = callback; _saveFileCallback = callback;
std::string fullpath = FileUtils::getInstance()->getWritablePath() + fileName; std::string fullpath = FileUtils::getInstance()->getWritablePath().append(fileName);
_saveToFileCommand.init(_globalZOrder); _saveToFileCommand.init(_globalZOrder);
_saveToFileCommand.func = CC_CALLBACK_0(RenderTexture::onSaveToFile, this, fullpath, isRGBA, true); _saveToFileCommand.func = CC_CALLBACK_0(RenderTexture::onSaveToFile, this, fullpath, isRGBA, true);
@ -427,10 +423,10 @@ bool RenderTexture::saveToFileAsNonPMA(const std::string& fileName,
return true; return true;
} }
bool RenderTexture::saveToFile(const std::string& fileName, bool RenderTexture::saveToFile(std::string_view fileName,
Image::Format format, Image::Format format,
bool isRGBA, bool isRGBA,
std::function<void(RenderTexture*, const std::string&)> callback) std::function<void(RenderTexture*, std::string_view)> callback)
{ {
CCASSERT(format == Image::Format::JPG || format == Image::Format::PNG, CCASSERT(format == Image::Format::JPG || format == Image::Format::PNG,
"the image can only be saved as JPG or PNG format"); "the image can only be saved as JPG or PNG format");
@ -439,7 +435,7 @@ bool RenderTexture::saveToFile(const std::string& fileName,
_saveFileCallback = callback; _saveFileCallback = callback;
std::string fullpath = FileUtils::getInstance()->getWritablePath() + fileName; std::string fullpath = FileUtils::getInstance()->getWritablePath().append(fileName);
_saveToFileCommand.init(_globalZOrder); _saveToFileCommand.init(_globalZOrder);
_saveToFileCommand.func = CC_CALLBACK_0(RenderTexture::onSaveToFile, this, fullpath, isRGBA, false); _saveToFileCommand.func = CC_CALLBACK_0(RenderTexture::onSaveToFile, this, fullpath, isRGBA, false);
@ -447,7 +443,7 @@ bool RenderTexture::saveToFile(const std::string& fileName,
return true; 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> image) { auto callbackFunc = [&, filename, isRGBA, forceNonPMA](RefPtr<Image> image) {
if (image) if (image)

View File

@ -61,6 +61,7 @@ class EventCustom;
class CC_DLL RenderTexture : public Node class CC_DLL RenderTexture : public Node
{ {
public: public:
using SaveFileCallbackType = std::function<void(RenderTexture*, std::string_view)>;
/** Initializes a RenderTexture object with width and height in Points and a pixel format( only RGB and RGBA formats /** Initializes a RenderTexture object with width and height in Points and a pixel format( only RGB and RGBA formats
* are valid ) and depthStencil format. * are valid ) and depthStencil format.
* *
@ -171,9 +172,7 @@ public:
* @param callback When the file is save finished,it will callback this function. * @param callback When the file is save finished,it will callback this function.
* @return Returns true if the operation is successful. * @return Returns true if the operation is successful.
*/ */
bool saveToFileAsNonPMA(const std::string& filename, bool saveToFileAsNonPMA(std::string_view filename, bool isRGBA = true, SaveFileCallbackType = nullptr);
bool isRGBA = true,
std::function<void(RenderTexture*, const std::string&)> callback = nullptr);
/** Saves the texture into a file using JPEG format. The file will be saved in the Documents folder. /** 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. * 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. * @param callback When the file is save finished,it will callback this function.
* @return Returns true if the operation is successful. * @return Returns true if the operation is successful.
*/ */
bool saveToFile(const std::string& filename, bool saveToFile(std::string_view filename, bool isRGBA = true, SaveFileCallbackType = nullptr);
bool isRGBA = true,
std::function<void(RenderTexture*, const std::string&)> callback = nullptr);
/** saves the texture into a file in non-PMA. The format could be JPG or PNG. The file will be saved in the /** 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. 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. * @param callback When the file is save finished,it will callback this function.
* @return Returns true if the operation is successful. * @return Returns true if the operation is successful.
*/ */
bool saveToFileAsNonPMA(const std::string& fileName, bool saveToFileAsNonPMA(std::string_view fileName,
Image::Format format, Image::Format format,
bool isRGBA, bool isRGBA,
std::function<void(RenderTexture*, const std::string&)> 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. /** 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. 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. * @param callback When the file is save finished,it will callback this function.
* @return Returns true if the operation is successful. * @return Returns true if the operation is successful.
*/ */
bool saveToFile(const std::string& filename, bool saveToFile(std::string_view filename,
Image::Format format, Image::Format format,
bool isRGBA = true, bool isRGBA = true,
std::function<void(RenderTexture*, const std::string&)> callback = nullptr); SaveFileCallbackType callback = nullptr);
/** Listen "come to background" message, and save render texture. /** Listen "come to background" message, and save render texture.
* It only has effect on Android. * It only has effect on Android.
@ -367,7 +364,7 @@ protected:
void onEnd(); void onEnd();
void clearColorAttachment(); 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; bool _keepMatrix = false;
Rect _rtTextureRect; Rect _rtTextureRect;
@ -411,7 +408,7 @@ protected:
and the command and callback will be executed twice. and the command and callback will be executed twice.
*/ */
CallbackCommand _saveToFileCommand; CallbackCommand _saveToFileCommand;
std::function<void(RenderTexture*, const std::string&)> _saveFileCallback = nullptr; std::function<void(RenderTexture*, std::string_view)> _saveFileCallback = nullptr;
Mat4 _oldTransMatrix, _oldProjMatrix; Mat4 _oldTransMatrix, _oldProjMatrix;
Mat4 _transformMatrix, _projectionMatrix; Mat4 _transformMatrix, _projectionMatrix;

View File

@ -72,7 +72,7 @@ Sprite* Sprite::createWithTexture(Texture2D* texture, const Rect& rect, bool rot
return nullptr; return nullptr;
} }
Sprite* Sprite::create(const std::string& filename) Sprite* Sprite::create(std::string_view filename)
{ {
Sprite* sprite = new Sprite(); Sprite* sprite = new Sprite();
if (sprite->initWithFile(filename)) if (sprite->initWithFile(filename))
@ -96,7 +96,7 @@ Sprite* Sprite::create(const PolygonInfo& info)
return nullptr; 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(); Sprite* sprite = new Sprite();
if (sprite->initWithFile(filename, rect)) if (sprite->initWithFile(filename, rect))
@ -120,13 +120,13 @@ Sprite* Sprite::createWithSpriteFrame(SpriteFrame* spriteFrame)
return nullptr; return nullptr;
} }
Sprite* Sprite::createWithSpriteFrameName(const std::string& spriteFrameName) Sprite* Sprite::createWithSpriteFrameName(std::string_view spriteFrameName)
{ {
SpriteFrame* frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); SpriteFrame* frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName);
#if COCOS2D_DEBUG > 0 #if COCOS2D_DEBUG > 0
char msg[256] = {0}; char msg[256] = {0};
sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName.c_str()); sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName.data());
CCASSERT(frame != nullptr, msg); CCASSERT(frame != nullptr, msg);
#endif #endif
@ -167,7 +167,7 @@ bool Sprite::initWithTexture(Texture2D* texture, const Rect& rect)
return initWithTexture(texture, rect, false); return initWithTexture(texture, rect, false);
} }
bool Sprite::initWithFile(const std::string& filename) bool Sprite::initWithFile(std::string_view filename)
{ {
if (filename.empty()) if (filename.empty())
{ {
@ -191,7 +191,7 @@ bool Sprite::initWithFile(const std::string& filename)
return false; 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"); CCASSERT(!filename.empty(), "Invalid filename");
if (filename.empty()) if (filename.empty())
@ -209,7 +209,7 @@ bool Sprite::initWithFile(const std::string& filename, const Rect& rect)
return false; return false;
} }
bool Sprite::initWithSpriteFrameName(const std::string& spriteFrameName) bool Sprite::initWithSpriteFrameName(std::string_view spriteFrameName)
{ {
CCASSERT(!spriteFrameName.empty(), "Invalid spriteFrameName"); CCASSERT(!spriteFrameName.empty(), "Invalid spriteFrameName");
if (spriteFrameName.empty()) if (spriteFrameName.empty())
@ -332,7 +332,7 @@ static unsigned char cc_2x2_white_image[] = {
#define CC_2x2_WHITE_IMAGE_KEY "/cc_2x2_white_image" #define CC_2x2_WHITE_IMAGE_KEY "/cc_2x2_white_image"
// MARK: texture // MARK: texture
void Sprite::setTexture(const std::string& filename) void Sprite::setTexture(std::string_view filename)
{ {
Texture2D* texture = _director->getTextureCache()->addImage(filename); Texture2D* texture = _director->getTextureCache()->addImage(filename);
setTexture(texture); setTexture(texture);
@ -1132,7 +1132,7 @@ void Sprite::addChild(Node* child, int zOrder, int tag)
Node::addChild(child, zOrder, 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"); CCASSERT(child != nullptr, "Argument must be non-nullptr");
if (child == nullptr) if (child == nullptr)
@ -1539,7 +1539,7 @@ bool Sprite::isOpacityModifyRGB() const
// MARK: Frames // MARK: Frames
void Sprite::setSpriteFrame(const std::string& spriteFrameName) void Sprite::setSpriteFrame(std::string_view spriteFrameName)
{ {
CCASSERT(!spriteFrameName.empty(), "spriteFrameName must not be empty"); CCASSERT(!spriteFrameName.empty(), "spriteFrameName must not be empty");
if (spriteFrameName.empty()) if (spriteFrameName.empty())
@ -1590,7 +1590,7 @@ void Sprite::setSpriteFrame(SpriteFrame* spriteFrame)
setCenterRect(spriteFrame->getCenterRect()); 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"); CCASSERT(!animationName.empty(), "CCSprite#setDisplayFrameWithAnimationName. animationName must not be nullptr");
if (animationName.empty()) if (animationName.empty())

View File

@ -129,7 +129,7 @@ public:
* @param filename A path to image file, e.g., "scene1/monster.png". * @param filename A path to image file, e.g., "scene1/monster.png".
* @return An autoreleased sprite object. * @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. * Creates a polygon sprite with a polygon info.
@ -149,7 +149,7 @@ public:
* @param rect A subrect of the image file. * @param rect A subrect of the image file.
* @return An autoreleased sprite object. * @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. * Creates a sprite with a Texture2D object.
@ -191,7 +191,7 @@ public:
* @param spriteFrameName The name of sprite frame. * @param spriteFrameName The name of sprite frame.
* @return An autoreleased sprite object. * @return An autoreleased sprite object.
*/ */
static Sprite* createWithSpriteFrameName(const std::string& spriteFrameName); static Sprite* createWithSpriteFrameName(std::string_view spriteFrameName);
// end of creators group // end of creators group
/// @} /// @}
@ -233,7 +233,7 @@ public:
* @memberof Sprite * @memberof Sprite
* It will call `setTextureRect()` with the texture's content size. * 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 /** @overload
* *
@ -304,7 +304,7 @@ public:
/** @{ /** @{
* Sets a new SpriteFrame to the Sprite. * 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); virtual void setSpriteFrame(SpriteFrame* newFrame);
/** @} */ /** @} */
@ -326,7 +326,7 @@ public:
* Changes the display frame with animation name and index. * Changes the display frame with animation name and index.
* The animation name will be get from the AnimationCache. * 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; virtual void reorderChild(Node* child, int zOrder) override;
using Node::addChild; using Node::addChild;
virtual void addChild(Node* child, int zOrder, int tag) 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 sortAllChildren() override; virtual void sortAllChildren() override;
virtual void setScale(float scale) override; virtual void setScale(float scale) override;
virtual void setPositionZ(float positionZ) override; virtual void setPositionZ(float positionZ) override;
@ -513,7 +513,7 @@ public:
/// @} /// @}
int getResourceType() const { return _fileType; } int getResourceType() const { return _fileType; }
const std::string& getResourceName() const { return _fileName; } std::string_view getResourceName() const { return _fileName; }
CC_CONSTRUCTOR_ACCESS : CC_CONSTRUCTOR_ACCESS :
/** /**
@ -588,7 +588,7 @@ public:
* @param spriteFrameName A key string that can fetched a valid SpriteFrame from SpriteFrameCache. * @param spriteFrameName A key string that can fetched a valid SpriteFrame from SpriteFrameCache.
* @return True if the sprite is initialized properly, false otherwise. * @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. * Initializes a sprite with an image filename.
@ -601,7 +601,7 @@ public:
* @return True if the sprite is initialized properly, false otherwise. * @return True if the sprite is initialized properly, false otherwise.
* @lua init * @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. * 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. * @return True if the sprite is initialized properly, false otherwise.
* @lua init * @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(); virtual void setVertexLayout();

View File

@ -64,7 +64,7 @@ SpriteBatchNode* SpriteBatchNode::createWithTexture(Texture2D* tex, ssize_t capa
* creation with File Image * 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(); SpriteBatchNode* batchNode = new SpriteBatchNode();
if (batchNode->initWithFile(fileImage, capacity)) if (batchNode->initWithFile(fileImage, capacity))
@ -168,7 +168,7 @@ bool SpriteBatchNode::init()
/* /*
* init with FileImage * 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); Texture2D* texture2D = _director->getTextureCache()->addImage(fileImage);
return initWithTexture(texture2D, capacity); return initWithTexture(texture2D, capacity);
@ -236,7 +236,7 @@ void SpriteBatchNode::addChild(Node* child, int zOrder, int tag)
appendChild(sprite); 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(child != nullptr, "child should not be null");
CCASSERT(dynamic_cast<Sprite*>(child) != nullptr, "CCSpriteBatchNode only supports Sprites as children"); CCASSERT(dynamic_cast<Sprite*>(child) != nullptr, "CCSpriteBatchNode only supports Sprites as children");

View File

@ -84,7 +84,7 @@ public:
* @param capacity The capacity of children. * @param capacity The capacity of children.
* @return Return an autorelease object. * @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. /** Returns the TextureAtlas object.
* *
@ -195,7 +195,7 @@ public:
using Node::addChild; using Node::addChild;
virtual void addChild(Node* child, int zOrder, int tag) 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 reorderChild(Node* child, int zOrder) override; virtual void reorderChild(Node* child, int zOrder) override;
virtual void removeChild(Node* child, bool cleanup) override; virtual void removeChild(Node* child, bool cleanup) override;
@ -250,7 +250,7 @@ public:
* @js init * @js init
* @lua 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; bool init() override;
protected: protected:

View File

@ -35,7 +35,7 @@ NS_CC_BEGIN
// implementation of SpriteFrame // 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* spriteFrame = new SpriteFrame();
spriteFrame->initWithTextureFilename(filename, rect); spriteFrame->initWithTextureFilename(filename, rect);
@ -70,7 +70,7 @@ SpriteFrame* SpriteFrame::createWithTexture(Texture2D* texture,
return nullptr; return nullptr;
} }
SpriteFrame* SpriteFrame::create(const std::string& filename, SpriteFrame* SpriteFrame::create(std::string_view filename,
const Rect& rect, const Rect& rect,
bool rotated, bool rotated,
const Vec2& offset, const Vec2& offset,
@ -94,7 +94,7 @@ bool SpriteFrame::initWithTexture(Texture2D* texture, const Rect& rect)
return initWithTexture(texture, rectInPixels, false, Vec2::ZERO, rectInPixels.size); 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); Rect rectInPixels = CC_RECT_POINTS_TO_PIXELS(rect);
return initWithTextureFilename(filename, rectInPixels, false, Vec2::ZERO, rectInPixels.size); return initWithTextureFilename(filename, rectInPixels, false, Vec2::ZERO, rectInPixels.size);
@ -126,7 +126,7 @@ bool SpriteFrame::initWithTexture(Texture2D* texture,
return true; return true;
} }
bool SpriteFrame::initWithTextureFilename(const std::string& filename, bool SpriteFrame::initWithTextureFilename(std::string_view filename,
const Rect& rect, const Rect& rect,
bool rotated, bool rotated,
const Vec2& offset, const Vec2& offset,

View File

@ -66,7 +66,7 @@ public:
* @param rect A specified rect. * @param rect A specified rect.
* @return An autoreleased SpriteFrame object. * @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. /** 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. The originalSize is the size in pixels of the frame before being trimmed.
@ -78,7 +78,7 @@ public:
* @param originalSize A specified original size. * @param originalSize A specified original size.
* @return An autoreleased SpriteFrame object. * @return An autoreleased SpriteFrame object.
*/ */
static SpriteFrame* create(const std::string& filename, static SpriteFrame* create(std::string_view filename,
const Rect& rect, const Rect& rect,
bool rotated, bool rotated,
const Vec2& offset, const Vec2& offset,
@ -279,7 +279,7 @@ public:
/** Initializes a SpriteFrame with a texture filename, rect in points; /** Initializes a SpriteFrame with a texture filename, rect in points;
It is assumed that the frame was not trimmed. 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. /** 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. The originalSize is the size in points of the frame before being trimmed.
@ -295,7 +295,7 @@ public:
@since v1.1 @since v1.1
*/ */
bool initWithTextureFilename(const std::string& filename, bool initWithTextureFilename(std::string_view filename,
const Rect& rect, const Rect& rect,
bool rotated, bool rotated,
const Vec2& offset, const Vec2& offset,

View File

@ -75,8 +75,8 @@ bool SpriteFrameCache::init()
SpriteFrameCache::~SpriteFrameCache() {} SpriteFrameCache::~SpriteFrameCache() {}
void SpriteFrameCache::addSpriteFramesWithFile(const std::string& spriteSheetFileName, void SpriteFrameCache::addSpriteFramesWithFile(std::string_view spriteSheetFileName,
const std::string& textureFileName, std::string_view textureFileName,
uint32_t spriteSheetFormat) uint32_t spriteSheetFormat)
{ {
auto* loader = getSpriteSheetLoader(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, Texture2D* texture,
uint32_t spriteSheetFormat) 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); auto* loader = getSpriteSheetLoader(spriteSheetFormat);
if (loader) 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); 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"); 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 // explicit nil handling
if (name.empty()) if (name.empty())
@ -178,7 +178,7 @@ void SpriteFrameCache::removeSpriteFrameByName(const std::string& name)
eraseFrame(name); eraseFrame(name);
} }
void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& atlasPath) void SpriteFrameCache::removeSpriteFramesFromFile(std::string_view atlasPath)
{ {
// const auto fullPath = FileUtils::getInstance()->fullPathForFilename(plist); // const auto fullPath = FileUtils::getInstance()->fullPathForFilename(plist);
// auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); // auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
@ -193,7 +193,7 @@ void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& atlasPath)
removeSpriteSheet(atlasPath); removeSpriteSheet(atlasPath);
} }
void SpriteFrameCache::removeSpriteFramesFromFileContent(const std::string& plist_content) void SpriteFrameCache::removeSpriteFramesFromFileContent(std::string_view plist_content)
{ {
auto dict = auto dict =
FileUtils::getInstance()->getValueMapFromData(plist_content.data(), static_cast<int>(plist_content.size())); FileUtils::getInstance()->getValueMapFromData(plist_content.data(), static_cast<int>(plist_content.size()));
@ -241,17 +241,17 @@ void SpriteFrameCache::removeSpriteFramesFromTexture(Texture2D* texture)
eraseFrames(keysToRemove); eraseFrames(keysToRemove);
} }
SpriteFrame* SpriteFrameCache::getSpriteFrameByName(const std::string& name) SpriteFrame* SpriteFrameCache::getSpriteFrameByName(std::string_view name)
{ {
auto* frame = findFrame(name); auto* frame = findFrame(name);
if (!frame) 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; 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"); 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>& spriteSheet, void SpriteFrameCache::insertFrame(const std::shared_ptr<SpriteSheet>& spriteSheet,
const std::string& frameName, std::string_view frameName,
SpriteFrame* spriteFrame) SpriteFrame* spriteFrame)
{ {
spriteSheet->frames.insert(frameName); spriteSheet->frames.emplace(frameName);
_spriteFrames.insert(frameName, spriteFrame); // add SpriteFrame _spriteFrames.insert(frameName, spriteFrame); // add SpriteFrame
_spriteSheets[spriteSheet->path] = spriteSheet; _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 _spriteFrames.erase(frameName); // drop SpriteFrame
const auto itFrame = _spriteFrameToSpriteSheetMap.find(frameName); const auto itFrame = _spriteFrameToSpriteSheetMap.find(frameName);
@ -330,7 +331,7 @@ bool SpriteFrameCache::eraseFrames(const std::vector<std::string>& frames)
return ret; return ret;
} }
bool SpriteFrameCache::removeSpriteSheet(const std::string& spriteSheetFileName) bool SpriteFrameCache::removeSpriteSheet(std::string_view spriteSheetFileName)
{ {
auto it = _spriteSheets.find(spriteSheetFileName); auto it = _spriteSheets.find(spriteSheetFileName);
if (it == _spriteSheets.end()) if (it == _spriteSheets.end())
@ -356,18 +357,18 @@ void SpriteFrameCache::clear()
_spriteFrames.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(); 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); const auto spriteSheetItr = _spriteSheets.find(spriteSheetFileName);
return spriteSheetItr != _spriteSheets.end() && !spriteSheetItr->second->frames.empty(); 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); return _spriteFrames.at(frame);
} }
@ -377,7 +378,7 @@ void SpriteFrameCache::addSpriteFrameCapInset(SpriteFrame* spriteFrame, const Re
texture->addSpriteFrameCapInset(spriteFrame, capInsets); texture->addSpriteFrameCapInset(spriteFrame, capInsets);
} }
Map<std::string, SpriteFrame*>& SpriteFrameCache::getSpriteFrames() StringMap<SpriteFrame*>& SpriteFrameCache::getSpriteFrames()
{ {
return _spriteFrames; return _spriteFrames;
} }

View File

@ -117,7 +117,7 @@ public:
/** Adds multiple Sprite Frames from a plist file. /** 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. * 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. * std::string& textureFileName) method.
* @js addSpriteFrames * @js addSpriteFrames
* @lua addSpriteFrames * @lua addSpriteFrames
@ -125,7 +125,7 @@ public:
* @param spriteSheetFileName file name. * @param spriteSheetFileName file name.
* @param spriteSheetFormat * @param spriteSheetFormat
*/ */
void addSpriteFramesWithFile(const std::string& spriteSheetFileName, void addSpriteFramesWithFile(std::string_view spriteSheetFileName,
uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST); uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST);
/** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. /** 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 textureFileName Texture file name.
* @param spriteSheetFormat * @param spriteSheetFormat
*/ */
void addSpriteFramesWithFile(const std::string& spriteSheetFileName, void addSpriteFramesWithFile(std::string_view spriteSheetFileName,
const std::string& textureFileName, std::string_view textureFileName,
uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST); uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST);
/** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. /** 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 texture Texture pointer.
* @param spriteSheetFormat * @param spriteSheetFormat
*/ */
void addSpriteFramesWithFile(const std::string& spriteSheetFileName, void addSpriteFramesWithFile(std::string_view spriteSheetFileName,
Texture2D* texture, Texture2D* texture,
uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST); uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST);
@ -172,7 +172,7 @@ public:
* @param frame A certain sprite frame. * @param frame A certain sprite frame.
* @param frameName The name of the 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. /** Check if multiple Sprite Frames from a plist file have been loaded.
* @js NA * @js NA
@ -181,7 +181,7 @@ public:
* @param plist Plist file name. * @param plist Plist file name.
* @return True if the file is loaded. * @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. /** Purges the dictionary of loaded sprite frames.
* Call this method if you receive the "Memory Warning". * 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. * @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. /** Removes multiple Sprite Frames from a plist file.
* Sprite Frames stored in this file will be removed. * 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. * @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. /** Removes multiple Sprite Frames from a plist file content.
* Sprite Frames stored in this file will be removed. * 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. * @param plist_content The string of the plist content that needs to removed.
* @js NA * @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. /** Removes all Sprite Frames associated with the specified textures.
* It is convenient to call this method when a specific texture needs to be removed. * 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. * @param name A certain sprite frame name.
* @return The sprite frame. * @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 /** Record SpriteFrame with plist and frame name, add frame name
* and plist to index * and plist to index
*/ */
void insertFrame(const std::shared_ptr<SpriteSheet>& spriteSheet, void insertFrame(const std::shared_ptr<SpriteSheet>& spriteSheet,
const std::string& frameName, std::string_view frameName,
SpriteFrame* frameObj); SpriteFrame* frameObj);
/** Delete frame from cache, rebuild index /** 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); void addSpriteFrameCapInset(SpriteFrame* spriteFrame, const Rect& capInsets, Texture2D* texture);
@ -277,30 +277,35 @@ protected:
bool eraseFrames(const std::vector<std::string>& frame); bool eraseFrames(const std::vector<std::string>& frame);
/** Delete frame from index and SpriteFrame is kept. /** 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. /** Clear index and all SpriteFrames.
*/ */
void clear(); void clear();
inline bool hasFrame(const std::string& frame) const; inline bool hasFrame(std::string_view frame) const;
inline bool isSpriteSheetInUse(const std::string& spriteSheetFileName) const; inline bool isSpriteSheetInUse(std::string_view spriteSheetFileName) const;
inline Map<std::string, SpriteFrame*>& getSpriteFrames(); inline StringMap<SpriteFrame*>& 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; return it == _spriteSheets.end() ? false : it->second->full;
} }
private: private:
Map<std::string, SpriteFrame*> _spriteFrames; StringMap<SpriteFrame*> _spriteFrames;
std::unordered_map<std::string, std::shared_ptr<SpriteSheet>> _spriteSheets; hlookup::string_map<std::shared_ptr<SpriteSheet>> _spriteSheets;
std::unordered_map<std::string, std::shared_ptr<SpriteSheet>> _spriteFrameToSpriteSheetMap; hlookup::string_map<std::shared_ptr<SpriteSheet>> _spriteFrameToSpriteSheetMap;
std::map<uint32_t, std::shared_ptr<ISpriteSheetLoader>> _spriteSheetLoaders; std::map<uint32_t, std::shared_ptr<ISpriteSheetLoader>> _spriteSheetLoaders;
}; };

View File

@ -65,7 +65,7 @@ class SpriteSheet
public: public:
std::string path; std::string path;
uint32_t format; uint32_t format;
std::set<std::string> frames; hlookup::string_set frames;
bool full = false; bool full = false;
}; };
@ -74,11 +74,11 @@ class ISpriteSheetLoader
public: public:
virtual ~ISpriteSheetLoader() = default; virtual ~ISpriteSheetLoader() = default;
virtual uint32_t getFormat() = 0; virtual uint32_t getFormat() = 0;
virtual void load(const std::string& filePath, SpriteFrameCache& cache) = 0; virtual void load(std::string_view filePath, SpriteFrameCache& cache) = 0;
virtual void load(const std::string& filePath, Texture2D* texture, SpriteFrameCache& cache) = 0; virtual void load(std::string_view 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, std::string_view textureFileName, SpriteFrameCache& cache) = 0;
virtual void load(const Data& content, Texture2D* texture, 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 class SpriteSheetLoader : public ISpriteSheetLoader
@ -93,11 +93,11 @@ public:
PolygonInfo& polygonInfo); PolygonInfo& polygonInfo);
uint32_t getFormat() override = 0; uint32_t getFormat() override = 0;
void load(const std::string& filePath, SpriteFrameCache& cache) override = 0; void load(std::string_view filePath, SpriteFrameCache& cache) override = 0;
void load(const std::string& filePath, Texture2D* texture, SpriteFrameCache& cache) override = 0; void load(std::string_view 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, std::string_view textureFileName, SpriteFrameCache& cache) override = 0;
void load(const Data& content, Texture2D* texture, 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 // end of _2d group

View File

@ -40,7 +40,7 @@ TMXObjectGroup::~TMXObjectGroup()
CCLOGINFO("deallocing TMXObjectGroup: %p", this); CCLOGINFO("deallocing TMXObjectGroup: %p", this);
} }
ValueMap TMXObjectGroup::getObject(const std::string& objectName) const ValueMap TMXObjectGroup::getObject(std::string_view objectName) const
{ {
if (!_objects.empty()) if (!_objects.empty())
{ {
@ -59,7 +59,7 @@ ValueMap TMXObjectGroup::getObject(const std::string& objectName) const
return ValueMap(); return ValueMap();
} }
Value TMXObjectGroup::getProperty(const std::string& propertyName) const Value TMXObjectGroup::getProperty(std::string_view propertyName) const
{ {
if (_properties.find(propertyName) != _properties.end()) if (_properties.find(propertyName) != _properties.end())
return _properties.at(propertyName); return _properties.at(propertyName);

View File

@ -60,13 +60,13 @@ public:
* *
* @return The group name. * @return The group name.
*/ */
const std::string& getGroupName() const { return _groupName; } std::string_view getGroupName() const { return _groupName; }
/** Set the group name. /** Set the group name.
* *
* @param groupName A string,it is used to 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. /** Return the value for the specific property name.
* *
@ -74,14 +74,14 @@ public:
* @return Return the value for the specific property name. * @return Return the value for the specific property name.
* @js NA * @js NA
*/ */
Value getProperty(const std::string& propertyName) const; Value getProperty(std::string_view propertyName) const;
/** Return the dictionary for the specific object name. /** Return the dictionary for the specific object name.
* It will return the 1st object found on the array for the given name. * It will return the 1st object found on the array for the given name.
* *
* @return Return the dictionary for the specific object 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. /** Gets the offset position of child objects.
* *

View File

@ -92,7 +92,7 @@ Rect TMXTilesetInfo::getRectForGID(uint32_t gid)
// implementation TMXMapInfo // implementation TMXMapInfo
TMXMapInfo* TMXMapInfo::create(const std::string& tmxFile) TMXMapInfo* TMXMapInfo::create(std::string_view tmxFile)
{ {
TMXMapInfo* ret = new TMXMapInfo(); TMXMapInfo* ret = new TMXMapInfo();
if (ret->initWithTMXFile(tmxFile)) if (ret->initWithTMXFile(tmxFile))
@ -104,7 +104,7 @@ TMXMapInfo* TMXMapInfo::create(const std::string& tmxFile)
return nullptr; 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(); TMXMapInfo* ret = new TMXMapInfo();
if (ret->initWithXML(tmxString, resourcePath)) if (ret->initWithXML(tmxString, resourcePath))
@ -116,7 +116,7 @@ TMXMapInfo* TMXMapInfo::createWithXML(const std::string& tmxString, const std::s
return nullptr; 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()) if (!tmxFileName.empty())
{ {
@ -138,13 +138,13 @@ void TMXMapInfo::internalInit(const std::string& tmxFileName, const std::string&
_currentFirstGID = -1; _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); internalInit("", resourcePath);
return parseXMLString(tmxString); return parseXMLString(tmxString);
} }
bool TMXMapInfo::initWithTMXFile(const std::string& tmxFile) bool TMXMapInfo::initWithTMXFile(std::string_view tmxFile)
{ {
internalInit(tmxFile, ""); internalInit(tmxFile, "");
return parseXMLFile(_TMXFileName); return parseXMLFile(_TMXFileName);
@ -171,7 +171,7 @@ TMXMapInfo::~TMXMapInfo()
CCLOGINFO("deallocing TMXMapInfo: %p", this); CCLOGINFO("deallocing TMXMapInfo: %p", this);
} }
bool TMXMapInfo::parseXMLString(const std::string& xmlString) bool TMXMapInfo::parseXMLString(std::string_view xmlString)
{ {
size_t len = xmlString.size(); size_t len = xmlString.size();
if (len <= 0) if (len <= 0)
@ -186,10 +186,10 @@ bool TMXMapInfo::parseXMLString(const std::string& xmlString)
parser.setDelegator(this); 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; SAXParser parser;
@ -265,7 +265,7 @@ void TMXMapInfo::startElement(void* /*ctx*/, const char* name, const char** atts
tmxMapInfo->setStaggerIndex(TMXStaggerIndex_Even); tmxMapInfo->setStaggerIndex(TMXStaggerIndex_Even);
} }
float hexSideLength = attributeDict["hexsidelength"].asFloat(); auto hexSideLength = attributeDict["hexsidelength"].asInt();
tmxMapInfo->setHexSideLength(hexSideLength); tmxMapInfo->setHexSideLength(hexSideLength);
Vec2 s; Vec2 s;
@ -348,7 +348,7 @@ void TMXMapInfo::startElement(void* /*ctx*/, const char* name, const char** atts
TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
Vec2 layerSize = layer->_layerSize; Vec2 layerSize = layer->_layerSize;
uint32_t gid = static_cast<uint32_t>(attributeDict["gid"].asUnsignedInt()); uint32_t gid = static_cast<uint32_t>(attributeDict["gid"].asUnsignedInt());
int tilesAmount = layerSize.width * layerSize.height; int tilesAmount = static_cast<int>(layerSize.width * layerSize.height);
if (_xmlTileIndex < tilesAmount) if (_xmlTileIndex < tilesAmount)
{ {
@ -443,7 +443,7 @@ void TMXMapInfo::startElement(void* /*ctx*/, const char* name, const char** atts
TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
Vec2 layerSize = layer->_layerSize; Vec2 layerSize = layer->_layerSize;
int tilesAmount = layerSize.width * layerSize.height; int tilesAmount = static_cast<int>(layerSize.width * layerSize.height);
uint32_t* tiles = (uint32_t*)malloc(tilesAmount * sizeof(uint32_t)); uint32_t* tiles = (uint32_t*)malloc(tilesAmount * sizeof(uint32_t));
// set all value to 0 // set all value to 0
@ -688,10 +688,10 @@ void TMXMapInfo::endElement(void* /*ctx*/, const char* name)
TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
std::string currentString = tmxMapInfo->getCurrentString(); auto currentString = tmxMapInfo->getCurrentString();
unsigned char* buffer; unsigned char* buffer;
auto len = 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) if (!buffer)
{ {
CCLOG("cocos2d: TiledMap: decode data error"); CCLOG("cocos2d: TiledMap: decode data error");
@ -733,10 +733,11 @@ void TMXMapInfo::endElement(void* /*ctx*/, const char* name)
TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
tmxMapInfo->setStoringCharacters(false); tmxMapInfo->setStoringCharacters(false);
std::string currentString = tmxMapInfo->getCurrentString(); auto currentString = tmxMapInfo->getCurrentString();
vector<string> gidTokens; vector<string> gidTokens;
istringstream filestr(currentString); std::stringstream filestr;
filestr << currentString;
string sRow; string sRow;
while (getline(filestr, sRow, '\n')) while (getline(filestr, sRow, '\n'))
{ {
@ -810,7 +811,7 @@ void TMXMapInfo::textHandler(void* /*ctx*/, const char* ch, size_t len)
if (tmxMapInfo->isStoringCharacters()) if (tmxMapInfo->isStoringCharacters())
{ {
std::string currentString = tmxMapInfo->getCurrentString(); std::string currentString{tmxMapInfo->getCurrentString()};
currentString += text; currentString += text;
tmxMapInfo->setCurrentString(currentString); tmxMapInfo->setCurrentString(currentString);
} }

View File

@ -250,9 +250,9 @@ class CC_DLL TMXMapInfo : public Ref, public SAXDelegator
{ {
public: public:
/** creates a TMX Format with a tmx file */ /** 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 */ /** 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 * @js ctor
@ -265,13 +265,13 @@ public:
virtual ~TMXMapInfo(); virtual ~TMXMapInfo();
/** initializes a TMX format with a tmx file */ /** 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 */ /** 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 */ /** 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 */ /* 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; }; ValueMapIntKey& getTileProperties() { return _tileProperties; };
void setTileProperties(const ValueMapIntKey& tileProperties) { _tileProperties = tileProperties; } void setTileProperties(const ValueMapIntKey& tileProperties) { _tileProperties = tileProperties; }
@ -353,14 +353,14 @@ public:
*/ */
void textHandler(void* ctx, const char* ch, size_t len) override; void textHandler(void* ctx, const char* ch, size_t len) override;
const std::string& getCurrentString() const { return _currentString; } std::string_view getCurrentString() const { return _currentString; }
void setCurrentString(const std::string& currentString) { _currentString = currentString; } void setCurrentString(std::string_view currentString) { _currentString = currentString; }
const std::string& getTMXFileName() const { return _TMXFileName; } std::string_view getTMXFileName() const { return _TMXFileName; }
void setTMXFileName(const std::string& fileName) { _TMXFileName = fileName; } void setTMXFileName(std::string_view fileName) { _TMXFileName = fileName; }
const std::string& getExternalTilesetFileName() const { return _externalTilesetFilename; } std::string_view getExternalTilesetFileName() const { return _externalTilesetFilename; }
protected: protected:
void internalInit(const std::string& tmxFileName, const std::string& resourcePath); void internalInit(std::string_view tmxFileName, std::string_view resourcePath);
/// map orientation /// map orientation
int _orientation; int _orientation;

View File

@ -109,10 +109,10 @@ TextFieldTTF::~TextFieldTTF() {}
// static constructor // static constructor
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder, TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(std::string_view placeholder,
const Vec2& dimensions, const Vec2& dimensions,
TextHAlignment alignment, TextHAlignment alignment,
const std::string& fontName, std::string_view fontName,
float fontSize) float fontSize)
{ {
TextFieldTTF* ret = new TextFieldTTF(); TextFieldTTF* ret = new TextFieldTTF();
@ -129,8 +129,8 @@ TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(const std::string& placehol
return nullptr; return nullptr;
} }
TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder, TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(std::string_view placeholder,
const std::string& fontName, std::string_view fontName,
float fontSize) float fontSize)
{ {
TextFieldTTF* ret = new TextFieldTTF(); TextFieldTTF* ret = new TextFieldTTF();
@ -151,10 +151,10 @@ TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(const std::string& placehol
// initialize // initialize
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, bool TextFieldTTF::initWithPlaceHolder(std::string_view placeholder,
const Vec2& dimensions, const Vec2& dimensions,
TextHAlignment alignment, TextHAlignment alignment,
const std::string& fontName, std::string_view fontName,
float fontSize) float fontSize)
{ {
setDimensions(dimensions.width, dimensions.height); setDimensions(dimensions.width, dimensions.height);
@ -162,7 +162,7 @@ bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder,
return initWithPlaceHolder(placeholder, fontName, fontSize); 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; _placeHolder = placeholder;
@ -366,7 +366,7 @@ void TextFieldTTF::deleteBackward()
} }
} }
const std::string& TextFieldTTF::getContentText() std::string_view TextFieldTTF::getContentText()
{ {
return _inputText; return _inputText;
} }
@ -573,9 +573,9 @@ void TextFieldTTF::setString(std::string_view text)
_charCount = charCount; _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) 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; return _inputText;
} }
// place holder text property // place holder text property
void TextFieldTTF::setPlaceHolder(const std::string& text) void TextFieldTTF::setPlaceHolder(std::string_view text)
{ {
_placeHolder = text; _placeHolder = text;
if (_inputText.empty() && !_isAttachWithIME) 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; 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) 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; return _passwordStyleText;
} }

View File

@ -98,28 +98,28 @@ public:
/** Creates a TextFieldTTF from a fontname, alignment, dimension and font size. /** Creates a TextFieldTTF from a fontname, alignment, dimension and font size.
* @js NA * @js NA
*/ */
static TextFieldTTF* textFieldWithPlaceHolder(const std::string& placeholder, static TextFieldTTF* textFieldWithPlaceHolder(std::string_view placeholder,
const Vec2& dimensions, const Vec2& dimensions,
TextHAlignment alignment, TextHAlignment alignment,
const std::string& fontName, std::string_view fontName,
float fontSize); float fontSize);
/** Creates a TextFieldTTF from a fontname and font size. /** Creates a TextFieldTTF from a fontname and font size.
* @js NA * @js NA
*/ */
static TextFieldTTF* textFieldWithPlaceHolder(const std::string& placeholder, static TextFieldTTF* textFieldWithPlaceHolder(std::string_view placeholder,
const std::string& fontName, std::string_view fontName,
float fontSize); float fontSize);
/** Initializes the TextFieldTTF with a font name, alignment, dimension and font size. */ /** 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, const Vec2& dimensions,
TextHAlignment alignment, TextHAlignment alignment,
const std::string& fontName, std::string_view fontName,
float fontSize); float fontSize);
/** Initializes the TextFieldTTF with a font name and font size. */ /** 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. *@brief Open keyboard and receive input text.
@ -183,26 +183,26 @@ public:
* Append to input text of TextField. * Append to input text of TextField.
*@param text The append 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. * Query the input text of TextField.
*@return Get 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. * Change placeholder text.
* place holder text displayed when there is no text in the text field. * place holder text displayed when there is no text in the text field.
*@param text The placeholder string. *@param text The placeholder string.
*/ */
virtual void setPlaceHolder(const std::string& text); virtual void setPlaceHolder(std::string_view text);
/** /**
* Query the placeholder string. * Query the placeholder string.
*@return 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. * Set enable secure text entry representation.
@ -211,8 +211,8 @@ public:
* @js NA * @js NA
*/ */
virtual void setSecureTextEntry(bool value); virtual void setSecureTextEntry(bool value);
virtual void setPasswordTextStyle(const std::string& text); virtual void setPasswordTextStyle(std::string_view text);
const std::string& getPasswordTextStyle() const; std::string_view getPasswordTextStyle() const;
/** /**
* Query whether the currently display mode is secure text entry or not. * Query whether the currently display mode is secure text entry or not.
@ -260,7 +260,7 @@ protected:
virtual void didDetachWithIME() override; virtual void didDetachWithIME() override;
virtual void insertText(const char* text, size_t len) override; virtual void insertText(const char* text, size_t len) override;
virtual void deleteBackward() override; virtual void deleteBackward() override;
virtual const std::string& getContentText() override; virtual std::string_view getContentText() override;
virtual void controlKey(EventKeyboard::KeyCode keyCode) override; virtual void controlKey(EventKeyboard::KeyCode keyCode) override;
TextFieldDelegate* _delegate; TextFieldDelegate* _delegate;

View File

@ -36,7 +36,7 @@ NS_CC_BEGIN
// implementation TileMapAtlas // 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(); TileMapAtlas* ret = new TileMapAtlas();
if (ret->initWithTileFile(tile, mapFile, tileWidth, tileHeight)) if (ret->initWithTileFile(tile, mapFile, tileWidth, tileHeight))
@ -48,7 +48,7 @@ TileMapAtlas* TileMapAtlas::create(const std::string& tile, const std::string& m
return nullptr; 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->loadTGAfile(mapFile);
this->calculateItemsToRender(); 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); std::string fullPath = FileUtils::getInstance()->fullPathForFilename(file);

View File

@ -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. /** 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. 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 * @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. /** 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. 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. * Returns a tile from position x,y.
*For the moment only channel R is used *For the moment only channel R is used
@ -100,7 +100,7 @@ public:
void setTGAInfo(struct sImageTGA* TGAInfo) { _TGAInfo = TGAInfo; } void setTGAInfo(struct sImageTGA* TGAInfo) { _TGAInfo = TGAInfo; }
protected: protected:
void loadTGAfile(const std::string& file); void loadTGAfile(std::string_view file);
void calculateItemsToRender(); void calculateItemsToRender();
void updateAtlasValueAt(const Vec2& pos, const Color3B& value, int index); void updateAtlasValueAt(const Vec2& pos, const Color3B& value, int index);
void updateAtlasValues(); void updateAtlasValues();

View File

@ -128,9 +128,9 @@ Animate3D* Animate3D::reverse() const
return animate; 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) if (name == childName)
return node; return node;
@ -162,10 +162,10 @@ void Animate3D::startWithTarget(Node* target)
{ {
if (_animation) if (_animation)
{ {
const std::unordered_map<std::string, Animation3D::Curve*>& boneCurves = _animation->getBoneCurves(); auto& boneCurves = _animation->getBoneCurves();
for (const auto& iter : boneCurves) for (const auto& iter : boneCurves)
{ {
const std::string& boneName = iter.first; std::string_view boneName = iter.first;
auto skin = sprite->getSkeleton(); auto skin = sprite->getSkeleton();
if (skin) if (skin)
{ {
@ -200,10 +200,10 @@ void Animate3D::startWithTarget(Node* target)
} }
else else
{ {
const std::unordered_map<std::string, Animation3D::Curve*>& boneCurves = _animation->getBoneCurves(); auto& boneCurves = _animation->getBoneCurves();
for (const auto& iter : boneCurves) for (const auto& iter : boneCurves)
{ {
const std::string& boneName = iter.first; std::string_view boneName = iter.first;
Node* node = nullptr; Node* node = nullptr;
if (target->getName() == boneName) if (target->getName() == boneName)
node = target; node = target;

View File

@ -29,11 +29,11 @@
NS_CC_BEGIN 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 fullPath = FileUtils::getInstance()->fullPathForFilename(fileName);
std::string key = fullPath + "#" + animationName; fullPath.append("#").append(animationName);
auto animation = Animation3DCache::getInstance()->getAnimation(key); auto animation = Animation3DCache::getInstance()->getAnimation(fullPath);
if (animation != nullptr) if (animation != nullptr)
return animation; return animation;
@ -50,7 +50,7 @@ Animation3D* Animation3D::create(const std::string& fileName, const std::string&
return animation; 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); std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename);
@ -59,8 +59,8 @@ bool Animation3D::initWithFile(const std::string& filename, const std::string& a
Animation3DData animationdata; Animation3DData animationdata;
if (bundle->load(fullPath) && bundle->loadAnimationData(animationName, &animationdata) && init(animationdata)) if (bundle->load(fullPath) && bundle->loadAnimationData(animationName, &animationdata) && init(animationdata))
{ {
std::string key = fullPath + "#" + animationName; fullPath.append("#").append(animationName);
Animation3DCache::getInstance()->addAnimation(key, this); Animation3DCache::getInstance()->addAnimation(fullPath, this);
Bundle3D::destroyBundle(bundle); Bundle3D::destroyBundle(bundle);
return true; return true;
} }
@ -70,7 +70,7 @@ bool Animation3D::initWithFile(const std::string& filename, const std::string& a
return false; 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); auto it = _boneCurves.find(name);
if (it != _boneCurves.end()) if (it != _boneCurves.end())
@ -199,7 +199,7 @@ void Animation3DCache::destroyInstance()
CC_SAFE_DELETE(_cacheInstance); CC_SAFE_DELETE(_cacheInstance);
} }
Animation3D* Animation3DCache::getAnimation(const std::string& key) Animation3D* Animation3DCache::getAnimation(std::string_view key)
{ {
auto it = _animations.find(key); auto it = _animations.find(key);
if (it != _animations.end()) if (it != _animations.end())
@ -207,14 +207,14 @@ Animation3D* Animation3DCache::getAnimation(const std::string& key)
return nullptr; 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); const auto& it = _animations.find(key);
if (it != _animations.end()) if (it != _animations.end())
{ {
return; // already have this key return; // already have this key
} }
_animations[key] = animation; _animations.emplace(key, animation); //_animations[key] = animation;
animation->retain(); animation->retain();
} }

View File

@ -69,7 +69,7 @@ public:
}; };
/**read all animation or only the animation with given animationName? animationName == "" read the first.*/ /**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*/ /**get duration*/
float getDuration() const { return _duration; } float getDuration() const { return _duration; }
@ -79,10 +79,10 @@ public:
* *
* @lua NA * @lua NA
*/ */
Curve* getBoneCurveByName(const std::string& name) const; Curve* getBoneCurveByName(std::string_view name) const;
/**get the bone Curves set*/ /**get the bone Curves set*/
const std::unordered_map<std::string, Curve*>& getBoneCurves() const { return _boneCurves; } const hlookup::string_map<Curve*>& getBoneCurves() const { return _boneCurves; }
CC_CONSTRUCTOR_ACCESS : Animation3D(); CC_CONSTRUCTOR_ACCESS : Animation3D();
virtual ~Animation3D(); virtual ~Animation3D();
@ -90,10 +90,10 @@ public:
bool init(const Animation3DData& data); bool init(const Animation3DData& data);
/**init Animation3D with file name and animation name*/ /**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: protected:
std::unordered_map<std::string, Curve*> _boneCurves; // bone curves map, key bone name, value AnimationCurve hlookup::string_map<Curve*> _boneCurves; // bone curves map, key bone name, value AnimationCurve
float _duration; // animation duration float _duration; // animation duration
}; };
@ -109,10 +109,10 @@ public:
static void destroyInstance(); static void destroyInstance();
/**get animation by key*/ /**get animation by key*/
Animation3D* getAnimation(const std::string& key); Animation3D* getAnimation(std::string_view key);
/**add animation to cache*/ /**add animation to cache*/
void addAnimation(const std::string& key, Animation3D* animation); void addAnimation(std::string_view key, Animation3D* animation);
/**remove all animation*/ /**remove all animation*/
void removeAllAnimations(); void removeAllAnimations();
@ -125,7 +125,7 @@ protected:
static Animation3DCache* _cacheInstance; // cache instance static Animation3DCache* _cacheInstance; // cache instance
std::unordered_map<std::string, Animation3D*> _animations; // cached animations hlookup::string_map<Animation3D*> _animations; // cached animations
}; };
// end of 3d group // end of 3d group

View File

@ -53,7 +53,7 @@ BillBoard* BillBoard::createWithTexture(Texture2D* texture, Mode mode)
return nullptr; return nullptr;
} }
BillBoard* BillBoard::create(const std::string& filename, Mode mode) BillBoard* BillBoard::create(std::string_view filename, Mode mode)
{ {
BillBoard* billboard = new BillBoard(); BillBoard* billboard = new BillBoard();
if (billboard->initWithFile(filename)) if (billboard->initWithFile(filename))
@ -66,7 +66,7 @@ BillBoard* BillBoard::create(const std::string& filename, Mode mode)
return nullptr; 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(); BillBoard* billboard = new BillBoard();
if (billboard->initWithFile(filename, rect)) if (billboard->initWithFile(filename, rect))

View File

@ -63,7 +63,7 @@ public:
* @param filename A path to image file, e.g., "scene1/monster.png" * @param filename A path to image file, e.g., "scene1/monster.png"
* @return An autoreleased BillBoard object. * @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. * Creates a BillBoard with an image filename and a rect.
@ -72,7 +72,7 @@ public:
* @param rect A subrect of the image file * @param rect A subrect of the image file
* @return An autoreleased BillBoard object * @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. * Creates a BillBoard with a Texture2D object.

View File

@ -169,7 +169,7 @@ void Bundle3D::clear()
} }
} }
bool Bundle3D::load(const std::string& path) bool Bundle3D::load(std::string_view path)
{ {
if (path.empty()) if (path.empty())
return false; return false;
@ -193,7 +193,7 @@ bool Bundle3D::load(const std::string& path)
} }
else else
{ {
CCLOG("warning: %s is invalid file formate", path.c_str()); CCLOG("warning: %s is invalid file formate", path.data());
} }
ret ? (_path = path) : (_path = ""); ret ? (_path = path) : (_path = "");
@ -204,7 +204,7 @@ bool Bundle3D::load(const std::string& path)
bool Bundle3D::loadObj(MeshDatas& meshdatas, bool Bundle3D::loadObj(MeshDatas& meshdatas,
MaterialDatas& materialdatas, MaterialDatas& materialdatas,
NodeDatas& nodedatas, NodeDatas& nodedatas,
const std::string& fullPath, std::string_view fullPath,
const char* mtl_basepath) const char* mtl_basepath)
{ {
meshdatas.resetData(); meshdatas.resetData();
@ -219,7 +219,7 @@ bool Bundle3D::loadObj(MeshDatas& meshdatas,
std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials; std::vector<tinyobj::material_t> 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()) if (ret.empty())
{ {
// fill data // fill data
@ -329,11 +329,11 @@ bool Bundle3D::loadObj(MeshDatas& meshdatas,
return true; 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; return false;
} }
bool Bundle3D::loadSkinData(const std::string& /*id*/, SkinData* skindata) bool Bundle3D::loadSkinData(std::string_view /*id*/, SkinData* skindata)
{ {
skindata->resetData(); 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(); animationdata->resetData();
@ -1062,7 +1062,7 @@ bool Bundle3D::loadMaterialsJson(MaterialDatas& materialdatas)
} }
return true; return true;
} }
bool Bundle3D::loadJson(const std::string& path) bool Bundle3D::loadJson(std::string_view path)
{ {
clear(); clear();
@ -1084,7 +1084,7 @@ bool Bundle3D::loadJson(const std::string& path)
return true; return true;
} }
bool Bundle3D::loadBinary(const std::string& path) bool Bundle3D::loadBinary(std::string_view path)
{ {
clear(); clear();
@ -1094,7 +1094,7 @@ bool Bundle3D::loadBinary(const std::string& path)
if (_binaryBuffer.isNull()) if (_binaryBuffer.isNull())
{ {
clear(); clear();
CCLOG("warning: Failed to read file: %s", path.c_str()); CCLOG("warning: Failed to read file: %s", path.data());
return false; 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) if (_binaryReader.read(sig, 1, 4) != 4 || memcmp(sig, identifier, 4) != 0)
{ {
clear(); clear();
CCLOG("warning: Invalid identifier: %s", path.c_str()); CCLOG("warning: Invalid identifier: %s", path.data());
return false; return false;
} }
@ -1127,7 +1127,7 @@ bool Bundle3D::loadBinary(const std::string& path)
if (_binaryReader.read(&_referenceCount, 4, 1) != 1) if (_binaryReader.read(&_referenceCount, 4, 1) != 1)
{ {
clear(); 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; return false;
} }
@ -1141,7 +1141,7 @@ bool Bundle3D::loadBinary(const std::string& path)
_binaryReader.read(&_references[i].offset, 4, 1) != 1) _binaryReader.read(&_references[i].offset, 4, 1) != 1)
{ {
clear(); 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); CC_SAFE_DELETE_ARRAY(_references);
return false; return false;
} }
@ -1460,7 +1460,7 @@ bool loadMaterialDataJson_0_2(MaterialData* /*materialdata*/)
return true; return true;
} }
bool Bundle3D::loadAnimationDataJson(const std::string& id, Animation3DData* animationdata) bool Bundle3D::loadAnimationDataJson(std::string_view id, Animation3DData* animationdata)
{ {
std::string anim = ""; std::string anim = "";
if (_version == "1.2" || _version == "0.2") if (_version == "1.2" || _version == "0.2")
@ -1549,7 +1549,7 @@ bool Bundle3D::loadAnimationDataJson(const std::string& id, Animation3DData* ani
return true; 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") 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 else
{ {
// if id is not a null string, we need to add a suffix of "animation" for seeding. // if id is not a null string, we need to add a suffix of "animation" for seeding.
std::string id_ = id; std::string id_{id};
if (id != "") if (!id.empty())
id_ = id + "animation"; id_.append("animation");
if (!seekToFirstType(BUNDLE_TYPE_ANIMATIONS, id_)) if (!seekToFirstType(BUNDLE_TYPE_ANIMATIONS, id_))
return false; return false;
@ -1998,7 +1998,7 @@ NodeData* Bundle3D::parseNodesRecursivelyBinary(bool& skeleton, bool singleSprit
return nodedata; 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; backend::VertexFormat ret = backend::VertexFormat::INT;
if (str == "GL_BYTE") if (str == "GL_BYTE")
@ -2097,7 +2097,7 @@ backend::VertexFormat Bundle3D::parseGLDataType(const std::string& str, int size
return ret; return ret;
} }
backend::SamplerAddressMode Bundle3D::parseSamplerAddressMode(const std::string& str) backend::SamplerAddressMode Bundle3D::parseSamplerAddressMode(std::string_view str)
{ {
if (str == "REPEAT") 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") if (str == "AMBIENT")
{ {
@ -2163,7 +2163,7 @@ NTextureData::Usage Bundle3D::parseGLTextureType(const std::string& str)
return NTextureData::Usage::Unknown; 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") 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('/'); ssize_t index = path.find_last_of('/');
std::string fullModelPath; std::string fullModelPath;
_modelPath = path.substr(0, index + 1); _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 each Reference
for (unsigned int i = 0; i < _referenceCount; ++i) for (unsigned int i = 0; i < _referenceCount; ++i)
@ -2266,7 +2266,7 @@ Reference* Bundle3D::seekToFirstType(unsigned int type, const std::string& id)
return nullptr; return nullptr;
} }
std::vector<Vec3> Bundle3D::getTrianglesList(const std::string& path) std::vector<Vec3> Bundle3D::getTrianglesList(std::string_view path)
{ {
std::vector<Vec3> trianglesList; std::vector<Vec3> trianglesList;

View File

@ -64,32 +64,32 @@ public:
* get define data type * get define data type
* @param str The type in string * @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 * get define data type
* @param str The type in string * @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 * load a file. You must load a file first, then call loadMeshData, loadSkinData, and so on
* @param path File to be loaded * @param path File to be loaded
* @return result of load * @return result of load
*/ */
virtual bool load(const std::string& path); virtual bool load(std::string_view path);
/** /**
* load skin data from bundle * load skin data from bundle
* @param id The ID of the skin, load the first Skin in the bundle if it is empty * @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 * load material data from bundle
* @param id The ID of the animation, load the first animation in the bundle if it is empty * @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 // since 3.3, to support reskin
virtual bool loadMeshDatas(MeshDatas& meshdatas); virtual bool loadMeshDatas(MeshDatas& meshdatas);
@ -102,21 +102,21 @@ public:
* load triangle list * load triangle list
* @param path the file path to load * @param path the file path to load
*/ */
static std::vector<Vec3> getTrianglesList(const std::string& path); static std::vector<Vec3> getTrianglesList(std::string_view path);
// load .obj file // load .obj file
static bool loadObj(MeshDatas& meshdatas, static bool loadObj(MeshDatas& meshdatas,
MaterialDatas& materialdatas, MaterialDatas& materialdatas,
NodeDatas& nodedatas, NodeDatas& nodedatas,
const std::string& fullPath, std::string_view fullPath,
const char* mtl_basepath = nullptr); const char* mtl_basepath = nullptr);
// calculate aabb // calculate aabb
static AABB calculateAABB(const std::vector<float>& vertex, int stride, const std::vector<unsigned short>& index); static AABB calculateAABB(const std::vector<float>& vertex, int stride, const std::vector<unsigned short>& index);
protected: protected:
bool loadJson(const std::string& path); bool loadJson(std::string_view path);
bool loadBinary(const std::string& path); bool loadBinary(std::string_view path);
bool loadMeshDatasJson(MeshDatas& meshdatas); bool loadMeshDatasJson(MeshDatas& meshdatas);
bool loadMeshDataJson_0_1(MeshDatas& meshdatas); bool loadMeshDataJson_0_1(MeshDatas& meshdatas);
bool loadMeshDataJson_0_2(MeshDatas& meshdatas); bool loadMeshDataJson_0_2(MeshDatas& meshdatas);
@ -137,8 +137,8 @@ protected:
bool loadMaterialDataJson(MaterialData* materialdata); bool loadMaterialDataJson(MaterialData* materialdata);
bool loadMaterialDataJson_0_1(MaterialData* materialdata); bool loadMaterialDataJson_0_1(MaterialData* materialdata);
bool loadMaterialDataJson_0_2(MaterialData* materialdata); bool loadMaterialDataJson_0_2(MaterialData* materialdata);
bool loadAnimationDataJson(const std::string& id, Animation3DData* animationdata); bool loadAnimationDataJson(std::string_view id, Animation3DData* animationdata);
bool loadAnimationDataBinary(const std::string& id, Animation3DData* animationdata); bool loadAnimationDataBinary(std::string_view id, Animation3DData* animationdata);
/** /**
* load nodes of json * load nodes of json
@ -156,26 +156,26 @@ protected:
* get define data type * get define data type
* @param str The type in string * @param str The type in string
*/ */
NTextureData::Usage parseGLTextureType(const std::string& str); NTextureData::Usage parseGLTextureType(std::string_view str);
/** /**
* get vertex attribute type * get vertex attribute type
* @param str The type in string * @param str The type in string
*/ */
shaderinfos::VertexKey parseGLProgramAttribute(const std::string& str); shaderinfos::VertexKey parseGLProgramAttribute(std::string_view str);
/* /*
* get model path * get model path
* @param str Full path of model file * @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 * set the read position in buffer to the target type
* @param The data type * @param The data type
* @param The data id * @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(); CC_CONSTRUCTOR_ACCESS : Bundle3D();
virtual ~Bundle3D(); virtual ~Bundle3D();

View File

@ -220,21 +220,21 @@ struct SkinData
rootBoneIndex = -1; rootBoneIndex = -1;
} }
void addSkinBoneNames(const std::string& name) void addSkinBoneNames(std::string_view name)
{ {
auto it = std::find(skinBoneNames.begin(), skinBoneNames.end(), name); auto it = std::find(skinBoneNames.begin(), skinBoneNames.end(), name);
if (it == skinBoneNames.end()) 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); auto it = std::find(nodeBoneNames.begin(), nodeBoneNames.end(), name);
if (it == nodeBoneNames.end()) 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; int i = 0;
for (const auto& iter : skinBoneNames) for (const auto& iter : skinBoneNames)
@ -246,7 +246,7 @@ struct SkinData
return -1; return -1;
} }
int getBoneNameIndex(const std::string& name) const int getBoneNameIndex(std::string_view name) const
{ {
int i = 0; int i = 0;
for (const auto& iter : skinBoneNames) for (const auto& iter : skinBoneNames)
@ -323,7 +323,7 @@ struct MaterialDatas
{ {
std::vector<NMaterialData> materials; std::vector<NMaterialData> materials;
void resetData() { materials.clear(); } 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) for (const auto& it : materials)
{ {

View File

@ -228,7 +228,7 @@ Mesh* Mesh::create(const std::vector<float>& vertices,
return create("", indexData); 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(); auto state = new Mesh();
state->autorelease(); state->autorelease();
@ -255,7 +255,7 @@ bool Mesh::isVisible() const
return _visible; return _visible;
} }
void Mesh::setTexture(const std::string& texPath) void Mesh::setTexture(std::string_view texPath)
{ {
_texFile = texPath; _texFile = texPath;
auto tex = Director::getInstance()->getTextureCache()->addImage(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); auto tex = Director::getInstance()->getTextureCache()->addImage(texPath);
setTexture(tex, usage); setTexture(tex, usage);

View File

@ -83,7 +83,7 @@ public:
* create mesh * create mesh
* @lua NA * @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 * get vertex buffer
@ -109,7 +109,7 @@ public:
* call setTexture(texPath, NTextureData::Usage::Diffuse) * call setTexture(texPath, NTextureData::Usage::Diffuse)
* @param texPath texture path * @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 * 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) * call setTexture(texPath, NTextureData::Usage::Diffuse)
@ -128,7 +128,7 @@ public:
* @param texPath texture path * @param texPath texture path
* @param usage Usage of this texture * @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 * Get texture (diffuse), which is responsible for the main appearance. It is also means main texture, you can also
* call getTexture(NTextureData::Usage::Diffuse) * call getTexture(NTextureData::Usage::Diffuse)
@ -168,7 +168,7 @@ public:
backend::ProgramState* getProgramState() const; backend::ProgramState* getProgramState() const;
/**name getter */ /**name getter */
const std::string& getName() const { return _name; } std::string_view getName() const { return _name; }
void setBlendFunc(const BlendFunc& blendFunc); void setBlendFunc(const BlendFunc& blendFunc);
const BlendFunc& getBlendFunc() const; const BlendFunc& getBlendFunc() const;
@ -225,7 +225,7 @@ public:
/**Mesh index data setter*/ /**Mesh index data setter*/
void setMeshIndexData(MeshIndexData* indexdata); void setMeshIndexData(MeshIndexData* indexdata);
/**name setter*/ /**name setter*/
void setName(const std::string& name) { _name = name; } void setName(std::string_view name) { _name = name; }
/** /**
* calculate the AABB of the mesh * calculate the AABB of the mesh

View File

@ -75,7 +75,7 @@ Bone3D* MeshSkin::getBoneByIndex(unsigned int index) const
return nullptr; return nullptr;
} }
Bone3D* MeshSkin::getBoneByName(const std::string& id) const Bone3D* MeshSkin::getBoneByName(std::string_view id) const
{ {
// search from skin bones // search from skin bones
for (const auto& it : _skinBones) for (const auto& it : _skinBones)

View File

@ -54,7 +54,7 @@ class CC_DLL MeshSkin : public Ref
public: public:
/**create a new meshskin if do not want to share meshskin*/ /**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, static MeshSkin* create(Skeleton3D* skeleton,
const std::vector<std::string>& boneNames, const std::vector<std::string>& boneNames,
@ -65,7 +65,7 @@ public:
/**get bone*/ /**get bone*/
Bone3D* getBoneByIndex(unsigned int index) const; Bone3D* getBoneByIndex(unsigned int index) const;
Bone3D* getBoneByName(const std::string& id) const; Bone3D* getBoneByName(std::string_view id) const;
/**get bone index*/ /**get bone index*/
int getBoneIndex(Bone3D* bone) const; int getBoneIndex(Bone3D* bone) const;

View File

@ -49,7 +49,7 @@ using namespace std;
NS_CC_BEGIN NS_CC_BEGIN
///////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////
MeshIndexData* MeshIndexData::create(const std::string& id, MeshIndexData* MeshIndexData::create(std::string_view id,
MeshVertexData* vertexData, MeshVertexData* vertexData,
backend::Buffer* indexbuffer, backend::Buffer* indexbuffer,
const AABB& aabb) const AABB& aabb)
@ -160,7 +160,7 @@ MeshVertexData* MeshVertexData::create(const MeshData& meshdata)
return vertexdata; return vertexdata;
} }
MeshIndexData* MeshVertexData::getMeshIndexDataById(const std::string& id) const MeshIndexData* MeshVertexData::getMeshIndexDataById(std::string_view id) const
{ {
for (auto it : _indexs) for (auto it : _indexs)
{ {

View File

@ -55,7 +55,7 @@ class CC_DLL MeshIndexData : public Ref
{ {
public: public:
/** create */ /** create */
static MeshIndexData* create(const std::string& id, static MeshIndexData* create(std::string_view id,
MeshVertexData* vertexData, MeshVertexData* vertexData,
backend::Buffer* indexbuffer, backend::Buffer* indexbuffer,
const AABB& aabb); const AABB& aabb);
@ -74,8 +74,8 @@ public:
const AABB& getAABB() const { return _aabb; } const AABB& getAABB() const { return _aabb; }
/** id setter and getter */ /** id setter and getter */
void setId(const std::string& id) { _id = id; } void setId(std::string_view id) { _id = id; }
const std::string& getId() const { return _id; } std::string_view getId() const { return _id; }
/**primitive type setter & getter*/ /**primitive type setter & getter*/
MeshCommand::PrimitiveType getPrimitiveType() const { return _primitiveType; } MeshCommand::PrimitiveType getPrimitiveType() const { return _primitiveType; }
@ -128,7 +128,7 @@ public:
/** get index data by index */ /** get index data by index */
MeshIndexData* getMeshIndexDataByIndex(int index) const { return _indexs.at(index); } MeshIndexData* getMeshIndexDataByIndex(int index) const { return _indexs.at(index); }
/** get index data by id */ /** 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; } ssize_t getSizePerVertex() const { return _sizePerVertex; }

View File

@ -61,7 +61,7 @@ MotionStreak3D* MotionStreak3D::create(float fade,
float minSeg, float minSeg,
float stroke, float stroke,
const Color3B& color, const Color3B& color,
const std::string& path) std::string_view path)
{ {
MotionStreak3D* ret = new MotionStreak3D(); MotionStreak3D* ret = new MotionStreak3D();
if (ret && ret->initWithFade(fade, minSeg, stroke, color, path)) 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; 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"); CCASSERT(!path.empty(), "Invalid filename");

View File

@ -61,7 +61,7 @@ public:
float minSeg, float minSeg,
float stroke, float stroke,
const Color3B& color, 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. /** Creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture.
* *
* @param fade The fade time, in seconds. * @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 /** 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 */ /** 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); bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture);

View File

@ -395,7 +395,7 @@ static bool exportFaceGroupToShape(shape_t& shape,
const std::vector<float>& in_texcoords, const std::vector<float>& in_texcoords,
const std::vector<std::vector<vertex_index>>& faceGroup, const std::vector<std::vector<vertex_index>>& faceGroup,
const int material_id, const int material_id,
const std::string& name, std::string_view name,
bool clearCache) bool clearCache)
{ {
if (faceGroup.empty()) if (faceGroup.empty())
@ -517,7 +517,7 @@ std::string LoadMtl(std::map<std::string, int>& material_map,
char namebuf[TINYOBJ_SSCANF_BUFFER_SIZE]; char namebuf[TINYOBJ_SSCANF_BUFFER_SIZE];
token += 7; token += 7;
#ifdef _MSC_VER #ifdef _MSC_VER
sscanf_s(token, "%s", namebuf, _countof(namebuf)); sscanf_s(token, "%s", namebuf, static_cast<unsigned int>(_countof(namebuf)));
#else #else
sscanf(token, "%s", namebuf); sscanf(token, "%s", namebuf);
#endif #endif
@ -681,7 +681,7 @@ std::string LoadMtl(std::map<std::string, int>& material_map,
return err.str(); return err.str();
} }
std::string MaterialFileReader::operator()(const std::string& matId, std::string MaterialFileReader::operator()(std::string_view matId,
std::vector<material_t>& materials, std::vector<material_t>& materials,
std::map<std::string, int>& matMap) std::map<std::string, int>& matMap)
{ {
@ -689,7 +689,7 @@ std::string MaterialFileReader::operator()(const std::string& matId,
if (!m_mtlBasePath.empty()) if (!m_mtlBasePath.empty())
{ {
filepath = std::string(m_mtlBasePath) + matId; filepath.append(m_mtlBasePath).append(matId);
} }
else else
{ {

View File

@ -75,7 +75,7 @@ public:
MaterialReader() {} MaterialReader() {}
virtual ~MaterialReader() {} virtual ~MaterialReader() {}
virtual std::string operator()(const std::string& matId, virtual std::string operator()(std::string_view matId,
std::vector<material_t>& materials, std::vector<material_t>& materials,
std::map<std::string, int>& matMap) = 0; std::map<std::string, int>& matMap) = 0;
}; };
@ -83,9 +83,9 @@ public:
class MaterialFileReader : public MaterialReader class MaterialFileReader : public MaterialReader
{ {
public: public:
MaterialFileReader(const std::string& mtl_basepath) : m_mtlBasePath(mtl_basepath) {} MaterialFileReader(std::string_view mtl_basepath) : m_mtlBasePath(mtl_basepath) {}
virtual ~MaterialFileReader() {} virtual ~MaterialFileReader() {}
virtual std::string operator()(const std::string& matId, virtual std::string operator()(std::string_view matId,
std::vector<material_t>& materials, std::vector<material_t>& materials,
std::map<std::string, int>& matMap); std::map<std::string, int>& matMap);

View File

@ -136,7 +136,7 @@ void Bone3D::clearBoneBlendState()
/** /**
* Creates C3DBone. * Creates C3DBone.
*/ */
Bone3D* Bone3D::create(const std::string& id) Bone3D* Bone3D::create(std::string_view id)
{ {
auto bone = new Bone3D(id); auto bone = new Bone3D(id);
bone->autorelease(); bone->autorelease();
@ -185,7 +185,7 @@ void Bone3D::removeAllChildBone()
_children.clear(); _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() Bone3D::~Bone3D()
{ {
@ -279,7 +279,7 @@ Bone3D* Skeleton3D::getBoneByIndex(unsigned int index) const
return nullptr; return nullptr;
} }
Bone3D* Skeleton3D::getBoneByName(const std::string& id) const Bone3D* Skeleton3D::getBoneByName(std::string_view id) const
{ {
// search from bones // search from bones
for (auto it : _bones) for (auto it : _bones)

View File

@ -61,7 +61,7 @@ public:
const Mat4& getWorldMat(); const Mat4& getWorldMat();
/**get bone name*/ /**get bone name*/
const std::string& getName() const { return _name; } std::string_view getName() const { return _name; }
/** /**
* set animation value * set animation value
@ -78,7 +78,7 @@ public:
/** /**
* Creates C3DBone. * Creates C3DBone.
*/ */
static Bone3D* create(const std::string& id); static Bone3D* create(std::string_view id);
/** /**
* Sets the inverse bind pose matrix. * Sets the inverse bind pose matrix.
@ -139,7 +139,7 @@ protected:
/** /**
* Constructor. * Constructor.
*/ */
Bone3D(const std::string& id); Bone3D(std::string_view id);
/** /**
* Destructor. * Destructor.
@ -190,7 +190,7 @@ public:
/**get bone*/ /**get bone*/
Bone3D* getBoneByIndex(unsigned int index) const; Bone3D* getBoneByIndex(unsigned int index) const;
Bone3D* getBoneByName(const std::string& id) const; Bone3D* getBoneByName(std::string_view id) const;
/**get & set root bone*/ /**get & set root bone*/
ssize_t getRootCount() const; ssize_t getRootCount() const;

View File

@ -41,12 +41,12 @@ Skybox::~Skybox()
_texture->release(); _texture->release();
} }
Skybox* Skybox::create(const std::string& positive_x, Skybox* Skybox::create(std::string_view positive_x,
const std::string& negative_x, std::string_view negative_x,
const std::string& positive_y, std::string_view positive_y,
const std::string& negative_y, std::string_view negative_y,
const std::string& positive_z, std::string_view positive_z,
const std::string& negative_z) std::string_view negative_z)
{ {
auto ret = new Skybox(); auto ret = new Skybox();
ret->init(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z); ret->init(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z);
@ -90,12 +90,12 @@ bool Skybox::init()
return true; return true;
} }
bool Skybox::init(const std::string& positive_x, bool Skybox::init(std::string_view positive_x,
const std::string& negative_x, std::string_view negative_x,
const std::string& positive_y, std::string_view positive_y,
const std::string& negative_y, std::string_view negative_y,
const std::string& positive_z, std::string_view positive_z,
const std::string& negative_z) std::string_view negative_z)
{ {
auto texture = TextureCube::create(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z); auto texture = TextureCube::create(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z);
if (texture == nullptr) if (texture == nullptr)

View File

@ -58,12 +58,12 @@ public:
@param negative_z texture for the rear side of the texture cube face. @param negative_z texture for the rear side of the texture cube face.
@return A new skybox inited with given parameters. @return A new skybox inited with given parameters.
*/ */
static Skybox* create(const std::string& positive_x, static Skybox* create(std::string_view positive_x,
const std::string& negative_x, std::string_view negative_x,
const std::string& positive_y, std::string_view positive_y,
const std::string& negative_y, std::string_view negative_y,
const std::string& positive_z, std::string_view positive_z,
const std::string& negative_z); std::string_view negative_z);
/**texture getter and setter*/ /**texture getter and setter*/
void setTexture(TextureCube*); void setTexture(TextureCube*);
@ -93,12 +93,12 @@ public:
/** /**
* initialize with texture path * initialize with texture path
*/ */
bool init(const std::string& positive_x, bool init(std::string_view positive_x,
const std::string& negative_x, std::string_view negative_x,
const std::string& positive_y, std::string_view positive_y,
const std::string& negative_y, std::string_view negative_y,
const std::string& positive_z, std::string_view positive_z,
const std::string& negative_z); std::string_view negative_z);
protected: protected:
/** /**

View File

@ -63,7 +63,7 @@ Sprite3D* Sprite3D::create()
return nullptr; return nullptr;
} }
Sprite3D* Sprite3D::create(const std::string& modelPath) Sprite3D* Sprite3D::create(std::string_view modelPath)
{ {
CCASSERT(modelPath.length() >= 4, "invalid filename for Sprite3D"); CCASSERT(modelPath.length() >= 4, "invalid filename for Sprite3D");
@ -77,7 +77,7 @@ Sprite3D* Sprite3D::create(const std::string& modelPath)
CC_SAFE_DELETE(sprite); CC_SAFE_DELETE(sprite);
return nullptr; 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); auto sprite = create(modelPath);
if (sprite) if (sprite)
@ -88,15 +88,15 @@ Sprite3D* Sprite3D::create(const std::string& modelPath, const std::string& text
return sprite; return sprite;
} }
void Sprite3D::createAsync(const std::string& modelPath, void Sprite3D::createAsync(std::string_view modelPath,
const std::function<void(Sprite3D*, void*)>& callback, const std::function<void(Sprite3D*, void*)>& callback,
void* callbackparam) void* callbackparam)
{ {
createAsync(modelPath, "", callback, callbackparam); createAsync(modelPath, "", callback, callbackparam);
} }
void Sprite3D::createAsync(const std::string& modelPath, void Sprite3D::createAsync(std::string_view modelPath,
const std::string& texturePath, std::string_view texturePath,
const std::function<void(Sprite3D*, void*)>& callback, const std::function<void(Sprite3D*, void*)>& callback,
void* callbackparam) void* callbackparam)
{ {
@ -197,7 +197,7 @@ AABB Sprite3D::getAABBRecursivelyImp(Node* node)
return aabb; return aabb;
} }
bool Sprite3D::loadFromCache(const std::string& path) bool Sprite3D::loadFromCache(std::string_view path)
{ {
auto spritedata = Sprite3DCache::getInstance()->getSpriteData(path); auto spritedata = Sprite3DCache::getInstance()->getSpriteData(path);
if (spritedata) if (spritedata)
@ -238,7 +238,7 @@ bool Sprite3D::loadFromCache(const std::string& path)
return false; return false;
} }
bool Sprite3D::loadFromFile(const std::string& path, bool Sprite3D::loadFromFile(std::string_view path,
NodeDatas* nodedatas, NodeDatas* nodedatas,
MeshDatas* meshdatas, MeshDatas* meshdatas,
MaterialDatas* materialdatas) MaterialDatas* materialdatas)
@ -296,7 +296,7 @@ bool Sprite3D::init()
return false; return false;
} }
bool Sprite3D::initWithFile(const std::string& path) bool Sprite3D::initWithFile(std::string_view path)
{ {
_aabbDirty = true; _aabbDirty = true;
_meshes.clear(); _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) for (auto it : _meshVertexDatas)
{ {
@ -672,7 +672,7 @@ void Sprite3D::addMesh(Mesh* mesh)
_meshes.pushBack(mesh); _meshes.pushBack(mesh);
} }
void Sprite3D::setTexture(const std::string& texFile) void Sprite3D::setTexture(std::string_view texFile)
{ {
auto tex = _director->getTextureCache()->addImage(texFile); auto tex = _director->getTextureCache()->addImage(texFile);
setTexture(tex); setTexture(tex);
@ -685,7 +685,7 @@ void Sprite3D::setTexture(Texture2D* texture)
mesh->setTexture(texture); mesh->setTexture(texture);
} }
} }
AttachNode* Sprite3D::getAttachNode(const std::string& boneName) AttachNode* Sprite3D::getAttachNode(std::string_view boneName)
{ {
auto it = _attachments.find(boneName); auto it = _attachments.find(boneName);
if (it != _attachments.end()) if (it != _attachments.end())
@ -698,7 +698,7 @@ AttachNode* Sprite3D::getAttachNode(const std::string& boneName)
{ {
auto attachNode = AttachNode::create(bone); auto attachNode = AttachNode::create(bone);
addChild(attachNode); addChild(attachNode);
_attachments[boneName] = attachNode; _attachments.emplace(boneName, attachNode); // _attachments[boneName] = attachNode;
return attachNode; return attachNode;
} }
} }
@ -706,7 +706,7 @@ AttachNode* Sprite3D::getAttachNode(const std::string& boneName)
return nullptr; return nullptr;
} }
void Sprite3D::removeAttachNode(const std::string& boneName) void Sprite3D::removeAttachNode(std::string_view boneName)
{ {
auto it = _attachments.find(boneName); auto it = _attachments.find(boneName);
if (it != _attachments.end()) if (it != _attachments.end())
@ -918,7 +918,7 @@ Mesh* Sprite3D::getMeshByIndex(int index) const
} }
/**get Mesh by Name */ /**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) for (const auto& it : _meshes)
{ {
@ -928,7 +928,7 @@ Mesh* Sprite3D::getMeshByName(const std::string& name) const
return nullptr; return nullptr;
} }
std::vector<Mesh*> Sprite3D::getMeshArrayByName(const std::string& name) const std::vector<Mesh*> Sprite3D::getMeshArrayByName(std::string_view name) const
{ {
std::vector<Mesh*> meshes; std::vector<Mesh*> meshes;
for (const auto& it : _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); auto it = _spriteDatas.find(key);
if (it != _spriteDatas.end()) if (it != _spriteDatas.end())
@ -981,18 +981,18 @@ Sprite3DCache::Sprite3DData* Sprite3DCache::getSpriteData(const std::string& key
return nullptr; 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); auto it = _spriteDatas.find(key);
if (it == _spriteDatas.end()) if (it == _spriteDatas.end())
{ {
_spriteDatas[key] = spritedata; _spriteDatas.emplace(key, spritedata); // _spriteDatas[key] = spritedata;
return true; return true;
} }
return false; return false;
} }
void Sprite3DCache::removeSprite3DData(const std::string& key) void Sprite3DCache::removeSprite3DData(std::string_view key)
{ {
auto it = _spriteDatas.find(key); auto it = _spriteDatas.find(key);
if (it != _spriteDatas.end()) if (it != _spriteDatas.end())

View File

@ -62,10 +62,10 @@ public:
static Sprite3D* create(); static Sprite3D* create();
/** creates a Sprite3D*/ /** 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' // 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 /** 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. * 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 callback callback after loading
* @param callbackparam user defined parameter for the callback * @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<void(Sprite3D*, void*)>& callback, const std::function<void(Sprite3D*, void*)>& callback,
void* callbackparam); void* callbackparam);
static void createAsync(const std::string& modelPath, static void createAsync(std::string_view modelPath,
const std::string& texturePath, std::string_view texturePath,
const std::function<void(Sprite3D*, void*)>& callback, const std::function<void(Sprite3D*, void*)>& callback,
void* callbackparam); void* callbackparam);
/**set diffuse texture, set the first if multiple textures exist*/ /**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); void setTexture(Texture2D* texture);
/**get Mesh by index*/ /**get Mesh by index*/
Mesh* getMeshByIndex(int index) const; 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 */ /**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 * get mesh array by name, returns all meshes with the given name
* *
* @lua NA * @lua NA
*/ */
std::vector<Mesh*> getMeshArrayByName(const std::string& name) const; std::vector<Mesh*> getMeshArrayByName(std::string_view name) const;
/**get mesh*/ /**get mesh*/
Mesh* getMesh() const; Mesh* getMesh() const;
@ -111,10 +111,10 @@ public:
Skeleton3D* getSkeleton() const { return _skeleton; } Skeleton3D* getSkeleton() const { return _skeleton; }
/**get AttachNode by bone name, return nullptr if not exist*/ /**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*/ /**remove attach node*/
void removeAttachNode(const std::string& boneName); void removeAttachNode(std::string_view boneName);
/**remove all attach nodes*/ /**remove all attach nodes*/
void removeAllAttachNode(); void removeAllAttachNode();
@ -214,16 +214,16 @@ public:
virtual bool init() override; 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); bool initFrom(const NodeDatas& nodedatas, const MeshDatas& meshdatas, const MaterialDatas& materialdatas);
/**load sprite3d from cache, return true if succeed, false otherwise*/ /**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 /** load file and set it to meshedatas, nodedatas and materialdatas, obj file .mtl file should be at the same
* directory if exist */ * directory if exist */
bool loadFromFile(const std::string& path, bool loadFromFile(std::string_view path,
NodeDatas* nodedatas, NodeDatas* nodedatas,
MeshDatas* meshdatas, MeshDatas* meshdatas,
MaterialDatas* materialdatas); MaterialDatas* materialdatas);
@ -242,7 +242,7 @@ public:
Sprite3D* createSprite3DNode(NodeData* nodedata, ModelData* modeldata, const MaterialDatas& materialdatas); Sprite3D* createSprite3DNode(NodeData* nodedata, ModelData* modeldata, const MaterialDatas& materialdatas);
/**get MeshIndexData by Id*/ /**get MeshIndexData by Id*/
MeshIndexData* getMeshIndexData(const std::string& indexId) const; MeshIndexData* getMeshIndexData(std::string_view indexId) const;
void addMesh(Mesh* mesh); void addMesh(Mesh* mesh);
@ -257,7 +257,7 @@ protected:
Vector<MeshVertexData*> _meshVertexDatas; Vector<MeshVertexData*> _meshVertexDatas;
std::unordered_map<std::string, AttachNode*> _attachments; hlookup::string_map<AttachNode*> _attachments;
BlendFunc _blend; BlendFunc _blend;
@ -319,17 +319,17 @@ public:
* *
* @lua NA * @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 * add the SpriteData into Sprite3D by given the specified key
* *
* @lua NA * @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*/ /**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*/ /**remove all the SpriteData from Sprite3D*/
void removeAllSprite3DData(); void removeAllSprite3DData();
@ -339,7 +339,7 @@ public:
protected: protected:
static Sprite3DCache* _cacheInstance; static Sprite3DCache* _cacheInstance;
std::unordered_map<std::string, Sprite3DData*> _spriteDatas; // cached sprite data hlookup::string_map<Sprite3DData*> _spriteDatas; // cached sprite data
}; };
// end of 3d group // end of 3d group

View File

@ -238,7 +238,7 @@ Sprite3DMaterial* Sprite3DMaterial::createBuiltInMaterial(MaterialType type, boo
return nullptr; return nullptr;
} }
Sprite3DMaterial* Sprite3DMaterial::createWithFilename(const std::string& path) Sprite3DMaterial* Sprite3DMaterial::createWithFilename(std::string_view path)
{ {
auto validfilename = FileUtils::getInstance()->fullPathForFilename(path); auto validfilename = FileUtils::getInstance()->fullPathForFilename(path);
if (!validfilename.empty()) 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); auto itr = _materials.find(key);
if (itr == _materials.end()) if (itr == _materials.end())
{ {
CC_SAFE_RETAIN(texture); CC_SAFE_RETAIN(texture);
_materials[key] = texture; _materials.emplace(key, texture);
return true; return true;
} }
return false; return false;
} }
Texture2D* Sprite3DMaterialCache::getSprite3DMaterial(const std::string& key) Texture2D* Sprite3DMaterialCache::getSprite3DMaterial(std::string_view key)
{ {
auto itr = _materials.find(key); auto itr = _materials.find(key);
if (itr != _materials.end()) if (itr != _materials.end())
@ -337,7 +337,7 @@ void Sprite3DMaterialCache::removeAllSprite3DMaterial()
{ {
for (auto& itr : _materials) for (auto& itr : _materials)
{ {
CC_SAFE_RELEASE_NULL(itr.second); CC_SAFE_RELEASE_NULL(const_cast<Texture2D*>(itr.second));
} }
_materials.clear(); _materials.clear();
} }

View File

@ -87,7 +87,7 @@ public:
* @param path Path of material file * @param path Path of material file
* @return Created material * @return Created material
*/ */
static Sprite3DMaterial* createWithFilename(const std::string& path); static Sprite3DMaterial* createWithFilename(std::string_view path);
/** /**
* Create material with GLProgramState * Create material with GLProgramState
@ -162,10 +162,10 @@ public:
static void destroyInstance(); static void destroyInstance();
/**add to cache*/ /**add to cache*/
bool addSprite3DMaterial(const std::string& key, Texture2D* tex); bool addSprite3DMaterial(std::string_view key, Texture2D* tex);
/**get material from cache*/ /**get material from cache*/
Texture2D* getSprite3DMaterial(const std::string& key); Texture2D* getSprite3DMaterial(std::string_view key);
/**remove all spritematerial*/ /**remove all spritematerial*/
void removeAllSprite3DMaterial(); void removeAllSprite3DMaterial();
@ -179,7 +179,7 @@ public:
protected: protected:
static Sprite3DMaterialCache* _cacheInstance; // instance static Sprite3DMaterialCache* _cacheInstance; // instance
std::unordered_map<std::string, Texture2D*> _materials; // cached material hlookup::string_map<Texture2D*> _materials; // cached material
}; };
// end of 3d group // end of 3d group

View File

@ -83,7 +83,7 @@ bool Terrain::initWithTerrainData(TerrainData& parameter, CrackFixedType fixedTy
return initResult; return initResult;
} }
void cocos2d::Terrain::setLightMap(const std::string& fileName) void cocos2d::Terrain::setLightMap(std::string_view fileName)
{ {
CC_SAFE_RELEASE(_lightMap); CC_SAFE_RELEASE(_lightMap);
auto image = new Image(); 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 = new Image();
_heightMapImage->initWithImageFile(heightMap); _heightMapImage->initWithImageFile(heightMap);
@ -611,7 +611,7 @@ cocos2d::Vec2 Terrain::convertToTerrainSpace(const Vec2& worldSpaceXZ) const
return Vec2(image_x, image_y); return Vec2(image_x, image_y);
} }
void Terrain::resetHeightMap(const std::string& heightMap) void Terrain::resetHeightMap(std::string_view heightMap)
{ {
_heightMapImage->release(); _heightMapImage->release();
_vertices.clear(); _vertices.clear();
@ -1154,8 +1154,8 @@ void Terrain::Chunk::updateIndicesLOD()
} }
memcpy(_neighborOldLOD, currentNeighborLOD, sizeof(currentNeighborLOD)); memcpy(_neighborOldLOD, currentNeighborLOD, sizeof(currentNeighborLOD));
_oldLod = _currentLod; _oldLod = _currentLod;
int gridY = _size.height; int gridY = static_cast<int>(_size.height);
int gridX = _size.width; int gridX = static_cast<int>(_size.width);
int step = 1 << _currentLod; int step = 1 << _currentLod;
if ((_left && _left->_currentLod > _currentLod) || (_right && _right->_currentLod > _currentLod) || if ((_left && _left->_currentLod > _currentLod) || (_right && _right->_currentLod > _currentLod) ||
@ -1644,8 +1644,8 @@ Terrain::QuadTree::~QuadTree()
delete _br; delete _br;
} }
Terrain::TerrainData::TerrainData(const std::string& heightMapsrc, Terrain::TerrainData::TerrainData(std::string_view heightMapsrc,
const std::string& textureSrc, std::string_view textureSrc,
const Vec2& chunksize, const Vec2& chunksize,
float height, float height,
float scale) float scale)
@ -1659,8 +1659,8 @@ Terrain::TerrainData::TerrainData(const std::string& heightMapsrc,
_skirtHeightRatio = 1; _skirtHeightRatio = 1;
} }
Terrain::TerrainData::TerrainData(const std::string& heightMapsrc, Terrain::TerrainData::TerrainData(std::string_view heightMapsrc,
const std::string& alphamap, std::string_view alphamap,
const DetailMap& detail1, const DetailMap& detail1,
const DetailMap& detail2, const DetailMap& detail2,
const DetailMap& detail3, const DetailMap& detail3,
@ -1682,8 +1682,8 @@ Terrain::TerrainData::TerrainData(const std::string& heightMapsrc,
_skirtHeightRatio = 1; _skirtHeightRatio = 1;
} }
Terrain::TerrainData::TerrainData(const std::string& heightMapsrc, Terrain::TerrainData::TerrainData(std::string_view heightMapsrc,
const std::string& alphamap, std::string_view alphamap,
const DetailMap& detail1, const DetailMap& detail1,
const DetailMap& detail2, const DetailMap& detail2,
const DetailMap& detail3, const DetailMap& detail3,
@ -1729,7 +1729,7 @@ Terrain::ChunkIndices::~ChunkIndices()
CC_SAFE_RELEASE_NULL(_indexBuffer); 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->_detailMapSrc = detailMapPath;
this->_detailMapSize = size; this->_detailMapSize = size;

View File

@ -108,7 +108,7 @@ public:
{ {
/*Constructors*/ /*Constructors*/
DetailMap(); DetailMap();
DetailMap(const std::string& detailMapSrc, float size = 35); DetailMap(std::string_view detailMapSrc, float size = 35);
/*detail Image source file path*/ /*detail Image source file path*/
std::string _detailMapSrc; std::string _detailMapSrc;
/*detailMapSize determine how many tiles that Terrain represent*/ /*detailMapSize determine how many tiles that Terrain represent*/
@ -136,14 +136,14 @@ public:
/**empty constructor*/ /**empty constructor*/
TerrainData(); TerrainData();
/**constructor, this constructor construct a simple terrain which only have 1 detailmap*/ /**constructor, this constructor construct a simple terrain which only have 1 detailmap*/
TerrainData(const std::string& heightMapsrc, TerrainData(std::string_view heightMapsrc,
const std::string& textureSrc, std::string_view textureSrc,
const Vec2& chunksize = Vec2(32, 32), const Vec2& chunksize = Vec2(32, 32),
float mapHeight = 2, float mapHeight = 2,
float mapScale = 0.1); float mapScale = 0.1);
/**constructor, this constructor construct a terrain which have 4 detailmaps, 1 alpha map*/ /**constructor, this constructor construct a terrain which have 4 detailmaps, 1 alpha map*/
TerrainData(const std::string& heightMapsrc, TerrainData(std::string_view heightMapsrc,
const std::string& alphamap, std::string_view alphamap,
const DetailMap& detail1, const DetailMap& detail1,
const DetailMap& detail2, const DetailMap& detail2,
const DetailMap& detail3, const DetailMap& detail3,
@ -152,8 +152,8 @@ public:
float mapHeight = 2, float mapHeight = 2,
float mapScale = 0.1); float mapScale = 0.1);
/**constructor, this constructor construct a terrain which have 3 detailmaps, 1 alpha map*/ /**constructor, this constructor construct a terrain which have 3 detailmaps, 1 alpha map*/
TerrainData(const std::string& heightMapsrc, TerrainData(std::string_view heightMapsrc,
const std::string& alphamap, std::string_view alphamap,
const DetailMap& detail1, const DetailMap& detail1,
const DetailMap& detail2, const DetailMap& detail2,
const DetailMap& detail3, const DetailMap& detail3,
@ -337,7 +337,7 @@ private:
public: public:
/** set light map texture */ /** set light map texture */
void setLightMap(const std::string& fileName); void setLightMap(std::string_view fileName);
/** /**
set directional light for the terrain set directional light for the terrain
@ -349,7 +349,7 @@ public:
/**initialize all Properties which terrain need */ /**initialize all Properties which terrain need */
bool initProperties(); bool initProperties();
/**initialize heightMap data */ /**initialize heightMap data */
bool initHeightMap(const std::string& heightMap); bool initHeightMap(std::string_view heightMap);
/**initialize alphaMap ,detailMaps textures*/ /**initialize alphaMap ,detailMaps textures*/
bool initTextures(); bool initTextures();
/**create entry*/ /**create entry*/
@ -429,7 +429,7 @@ public:
/** /**
* reset the heightmap data. * reset the heightmap data.
*/ */
void resetHeightMap(const std::string& heightMap); void resetHeightMap(std::string_view heightMap);
/** /**
* get the terrain's minimal height. * get the terrain's minimal height.

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