Merge remote-tracking branch 'upstream/develop' into develop

Conflicts:
	cocos/scripting/auto-generated
	tools/bindings-generator
This commit is contained in:
bmanGH 2014-01-20 12:18:36 +08:00
commit 7513e8d643
271 changed files with 5778 additions and 1592 deletions

View File

@ -94,6 +94,7 @@ Developers:
use tinyxml2 to replace libxml2
Added Mingw-crt Support without breaking VS SDK
CMake support for windows.
Added support for x64 target of windows.
mchinen
fix emulator issue for OpenGL ES 2.0 on Android
@ -718,6 +719,12 @@ Developers:
Pisces000221
Corrected a few mistakes in the README file of project-creator.
hbbalfred
Fixed a bug that crash if file doesn't exist when using FileUtils::getStringFromFile.
liang8305
Use multiple processes according the number of cores to build android project
Retired Core Developers:
WenSheng Yang
Author of windows port, CCTextField,

View File

@ -1,11 +1,37 @@
cocos2d-x-3.0final ?.? ?
cocos2d-x-3.0beta2 ?.? ?
[All]
[FIX] Crash was triggered if there is not `textureFileName`section in particle plist file.
[NEW] Adds performance test for Containers(Vector<>, Array, Map<K,V>, Dictionary).
[NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier.
[NEW] Console: added the 'textures', 'fileutils dump' and 'config' commands
[NEW] GLCache: glActiveTexture() is cached with GL::activeTexture(). All code MUST call the cached version in order to work correctly
[NEW] Label: Uses a struct of TTF configuration for Label::createWithTTF to reduce parameters and make this interface more easily to use.
[NEW] Label: Integrates LabelAtlas into new Label.
[NEW] Node: Added `setGlobalZOrder()`. Useful to change the Node's render order. Node::setZOrder() -> Node::setLocalZOrder()
[NEW] Renderer: Added BatchCommand. This command is not "batchable" with other commands, but improves performance in about 10%
[NEW] LuaBindings: Bindings-generator supports to bind namespace for lua.
[FIX] CocoStudio: TestColliderDetector in ArmatureTest can't work.
[FIX] Crash if file doesn't exist when using FileUtils::getStringFromFile.
[FIX] If setting a shorter string than before while using LabelAtlas, the effect will be wrong.
[FIX] Label: Crash when using unknown characters.
[FIX] Console: log(format, va_args) is private to prevent possible resolution errors
[FIX] Configuration: dumpInfo() -> getInfo()
[FIX] ControlSlider doesn't support to set selected thumb sprite.
[FIX] ControlButton doesn't support to set scale ratio of touchdown state.
[FIX] Particles: Crash was triggered if there is not `textureFileName`section in particle plist file.
[FIX] Renderer: Uses a float as key with only the depth. Viewport, opaque are not needed now
[FIX] Renderer Performance Fix: QuadCommand::init() does not copy the Quads, it only store a reference making the code faster
[FIX] Renderer Performance Fix: Sprite and SpriteBatchNode (and subclasses) has much better performance
[FIX] Renderer Performance Fix: When note using VAO, call glBufferData() instead of glBufferSubData().
[FIX] Renderer Performance Fix: Doesn't sort z=0 elements. It also uses sort() instead of stable_sort() for z!=0.
[FIX] Sprite: removed _hasChildren optimization. It uses !_children.empty() now which is super fast as well
[FIX] Tests: TestCpp works with CMake on Windows.
[FIX] Tests: Sprites Performance Test has 4 new tests
[FIX] TextureCache: getTextureForKey and removeTextureForKey work as expected
[FIX] TextureCache: dumpCachedTextureInfo() -> getCachedTextureInfo()
[FIX] Websocket doesn't support send/receive data which larger than 4096 bytes.
[NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier.
[FIX] TestCpp works by using CMake on Windows.
[FIX] Windows: There will be some compilation errors when using x64 target on Windows.
cocos2d-x-3.0beta Jan.7 2014
[All]
[NEW] New label: shadow, outline, glow support

View File

@ -12,6 +12,16 @@ LUA_SAMPLES = ['hellolua', 'testlua']
JSB_SAMPLES = ['cocosdragon', 'crystalcraze', 'moonwarriors', 'testjavascript', 'watermelonwithme']
ALL_SAMPLES = CPP_SAMPLES + LUA_SAMPLES + JSB_SAMPLES
def get_num_of_cpu():
''' The build process can be accelerated by running multiple concurrent job processes using the -j-option.
'''
try:
from numpy.distutils import cpuinfo
return cpuinfo.cpu._getNCPUs()
except Exception:
print "Can't know cpuinfo, use default 1 cpu"
return 1
def check_environment_variables():
''' Checking the environment NDK_ROOT, which will be used for building
'''
@ -94,10 +104,12 @@ def do_build(cocos_root, ndk_root, app_android_root, ndk_build_param,sdk_root,an
else:
ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root)
num_of_cpu = get_num_of_cpu()
if ndk_build_param == None:
command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path)
command = '%s -j%d -C %s %s' % (ndk_path, num_of_cpu, app_android_root, ndk_module_path)
else:
command = '%s -C %s %s %s' % (ndk_path, app_android_root, ndk_build_param, ndk_module_path)
command = '%s -j%d -C %s %s %s' % (ndk_path, num_of_cpu, app_android_root, ndk_build_param, ndk_module_path)
print command
if os.system(command) != 0:
raise Exception("Build dynamic library for project [ " + app_android_root + " ] fails!")
elif android_platform is not None:

View File

@ -1 +1 @@
3d6ada05d55194dd8e4c10ed8316add7c0d8705c
63e6598ea5798bf42bbd22c2295e65f7c739695a

View File

@ -1 +1 @@
2efefc01ff97bda1498d1d4a850ea1881f751f7c
447e7ba37294e6da0df2e02f5a62f30fb15e3272

View File

@ -47,6 +47,7 @@ CCEventListenerTouch.cpp \
CCEventMouse.cpp \
CCEventTouch.cpp \
CCFont.cpp \
CCFontCharMap.cpp \
CCFontAtlas.cpp \
CCFontAtlasCache.cpp \
CCFontAtlasFactory.cpp \
@ -122,6 +123,7 @@ renderer/CCFrustum.cpp \
renderer/CCGroupCommand.cpp \
renderer/CCMaterialManager.cpp \
renderer/CCQuadCommand.cpp \
renderer/CCBatchCommand.cpp \
renderer/CCRenderCommand.cpp \
renderer/CCRenderer.cpp \
renderer/CCRenderMaterial.cpp \

View File

@ -34,7 +34,7 @@ THE SOFTWARE.
#include "ccGLStateCache.h"
#include "CCDirector.h"
#include "TransformUtils.h"
#include "CCRenderer.h"
#include "renderer/CCRenderer.h"
#include "renderer/CCQuadCommand.h"
// external
@ -152,13 +152,13 @@ void AtlasNode::draw(void)
auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP);
_quadCommand.init(0,
_vertexZ,
_quadCommand.init(
_globalZOrder,
_textureAtlas->getTexture()->getName(),
shader,
_blendFunc,
_textureAtlas->getQuads(),
_textureAtlas->getTotalQuads(),
_quadsToDraw,
_modelViewTransform);
Director::getInstance()->getRenderer()->addCommand(&_quadCommand);

View File

@ -31,9 +31,10 @@
#include "CCShaderCache.h"
#include "CCDirector.h"
#include "CCDrawingPrimitives.h"
#include "CCRenderer.h"
#include "CCGroupCommand.h"
#include "CCCustomCommand.h"
#include "renderer/CCRenderer.h"
#include "renderer/CCGroupCommand.h"
#include "renderer/CCCustomCommand.h"
NS_CC_BEGIN
@ -209,12 +210,12 @@ void ClippingNode::visit()
Renderer* renderer = Director::getInstance()->getRenderer();
_groupCommand.init(0,_vertexZ);
_groupCommand.init(_globalZOrder);
renderer->addCommand(&_groupCommand);
renderer->pushGroup(_groupCommand.getRenderQueueID());
_beforeVisitCmd.init(0,_vertexZ);
_beforeVisitCmd.init(_globalZOrder);
_beforeVisitCmd.func = CC_CALLBACK_0(ClippingNode::onBeforeVisit, this);
renderer->addCommand(&_beforeVisitCmd);
if (_alphaThreshold < 1)
@ -237,7 +238,7 @@ void ClippingNode::visit()
}
_stencil->visit();
_afterDrawStencilCmd.init(0,_vertexZ);
_afterDrawStencilCmd.init(_globalZOrder);
_afterDrawStencilCmd.func = CC_CALLBACK_0(ClippingNode::onAfterDrawStencil, this);
renderer->addCommand(&_afterDrawStencilCmd);
@ -267,7 +268,7 @@ void ClippingNode::visit()
this->draw();
}
_afterVisitCmd.init(0,_vertexZ);
_afterVisitCmd.init(_globalZOrder);
_afterVisitCmd.func = CC_CALLBACK_0(ClippingNode::onAfterVisit, this);
renderer->addCommand(&_afterVisitCmd);

View File

@ -31,13 +31,13 @@ THE SOFTWARE.
#include "CCDictionary.h"
#include "CCInteger.h"
#include "CCBool.h"
#include "cocos2d.h"
#include "platform/CCFileUtils.h"
using namespace std;
NS_CC_BEGIN
extern const char* cocos2dVersion();
Configuration* Configuration::s_sharedConfiguration = nullptr;
@ -88,24 +88,20 @@ Configuration::~Configuration()
{
}
void Configuration::dumpInfo() const
std::string Configuration::getInfo() const
{
// Dump
Value forDump = Value(_valueDict);
CCLOG("%s", forDump.getDescription().c_str());
// And Dump some warnings as well
#if CC_ENABLE_PROFILERS
CCLOG("cocos2d: **** WARNING **** CC_ENABLE_PROFILERS is defined. Disable it when you finish profiling (from ccConfig.h)");
printf("\n");
CCLOG("cocos2d: **** WARNING **** CC_ENABLE_PROFILERS is defined. Disable it when you finish profiling (from ccConfig.h)\n");
#endif
#if CC_ENABLE_GL_STATE_CACHE == 0
CCLOG("");
CCLOG("cocos2d: **** WARNING **** CC_ENABLE_GL_STATE_CACHE is disabled. To improve performance, enable it (from ccConfig.h)");
printf("\n");
CCLOG("cocos2d: **** WARNING **** CC_ENABLE_GL_STATE_CACHE is disabled. To improve performance, enable it (from ccConfig.h)\n");
#endif
// Dump
Value forDump = Value(_valueDict);
return forDump.getDescription();
}
void Configuration::gatherGPUInfo()

View File

@ -122,8 +122,8 @@ public:
/** sets a new key/value pair in the configuration dictionary */
void setValue(const std::string& key, const Value& value);
/** dumps the current configuration on the console */
void dumpInfo() const;
/** returns the Configuration info */
std::string getInfo() const;
/** gathers OpenGL / GPU information */
void gatherGPUInfo();

View File

@ -60,9 +60,10 @@ THE SOFTWARE.
#include "CCEventDispatcher.h"
#include "CCEventCustom.h"
#include "CCFontFreeType.h"
#include "CCRenderer.h"
#include "CCConsole.h"
#include "renderer/CCRenderer.h"
#include "renderer/CCFrustum.h"
#include "CCConsole.h"
/**
Position of the FPS
@ -377,7 +378,7 @@ void Director::setOpenGLView(EGLView *openGLView)
// Configuration. Gather GPU info
Configuration *conf = Configuration::getInstance();
conf->gatherGPUInfo();
conf->dumpInfo();
CCLOG("%s\n",conf->getInfo().c_str());
// EAGLView is not a Object
delete _openGLView; // [openGLView_ release]

View File

@ -26,9 +26,9 @@
#include "CCGL.h"
#include "CCEventType.h"
#include "CCConfiguration.h"
#include "CCCustomCommand.h"
#include "renderer/CCCustomCommand.h"
#include "renderer/CCRenderer.h"
#include "CCDirector.h"
#include "CCRenderer.h"
#include "CCEventListenerCustom.h"
#include "CCEventDispatcher.h"
@ -241,7 +241,7 @@ void DrawNode::render()
void DrawNode::draw()
{
_customCommand.init(0, _vertexZ);
_customCommand.init(_globalZOrder);
_customCommand.func = CC_CALLBACK_0(DrawNode::onDraw, this);
Director::getInstance()->getRenderer()->addCommand(&_customCommand);
}

View File

@ -28,6 +28,7 @@
#include "CCFontFNT.h"
#include "CCFontFreeType.h"
#include "CCFontCharMap.h"
#include "edtaa3func.h"
NS_CC_BEGIN
@ -116,6 +117,21 @@ Font* Font::createWithFNT(const std::string& fntFilePath)
return FontFNT::create(fntFilePath);
}
Font* Font::createWithCharMap(const std::string& plistFile)
{
return FontCharMap::create(plistFile);
}
Font* Font::createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap)
{
return FontCharMap::create(texture,itemWidth,itemHeight,startCharMap);
}
Font* Font::createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
{
return FontCharMap::create(charMapFile,itemWidth,itemHeight,startCharMap);
}
unsigned char * Font::makeDistanceMap( unsigned char *img, unsigned int width, unsigned int height)
{
unsigned int pixelAmount = (width + 2 * DistanceMapSpread) * (height + 2 * DistanceMapSpread);

View File

@ -28,7 +28,6 @@
#include <string>
#include "cocos2d.h"
#include "CCLabel.h"
NS_CC_BEGIN
@ -46,6 +45,10 @@ public:
static Font* createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs);
static Font* createWithFNT(const std::string& fntFilePath);
static Font * createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap);
static Font * createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap);
static Font * createWithCharMap(const std::string& plistFile);
static unsigned char * makeDistanceMap(unsigned char *img, unsigned int width, unsigned int height);
void setDistanceFieldEnabled(bool distanceFieldEnabled);
bool isDistanceFieldEnabled() const { return _distanceFieldEnabled;}

View File

@ -22,10 +22,12 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "cocos2d.h"
#include "CCFontAtlas.h"
#include "CCFont.h"
#include "CCFontFreeType.h"
#include "ccUTF8.h"
#include "CCDirector.h"
#define PAGE_WIDTH 1024
#define PAGE_HEIGHT 1024
@ -100,6 +102,7 @@ bool FontAtlas::getLetterDefinitionForChar(unsigned short letteCharUTF16, FontL
}
else
{
outDefinition.validDefinition = false;
return false;
}
}
@ -128,7 +131,6 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
Rect tempRect;
FontLetterDefinition tempDef;
tempDef.offsetX = 0;
tempDef.anchorX = 0.0f;
tempDef.anchorY = 1.0f;
@ -141,6 +143,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
tempDef.height = 0;
tempDef.U = 0;
tempDef.V = 0;
tempDef.offsetX = 0;
tempDef.offsetY = 0;
tempDef.textureID = 0;
}
@ -150,6 +153,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
tempDef.letteCharUTF16 = utf16String[i];
tempDef.width = tempRect.size.width + _letterPadding;
tempDef.height = _currentPageLineHeight - 1;
tempDef.offsetX = tempRect.origin.x;
tempDef.offsetY = tempRect.origin.y;
tempDef.commonLineHeight = _currentPageLineHeight;

View File

@ -26,11 +26,14 @@
#define _CCFontAtlas_h_
#include <unordered_map>
#include "CCPlatformMacros.h"
#include "CCObject.h"
NS_CC_BEGIN
//fwd
class Font;
class Texture2D;
struct FontLetterDefinition
{

View File

@ -23,6 +23,8 @@
THE SOFTWARE.
****************************************************************************/
#include <sstream>
#include "CCFontAtlasCache.h"
#include "CCFontAtlasFactory.h"
@ -69,6 +71,65 @@ FontAtlas * FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName)
return tempAtlas;
}
FontAtlas * FontAtlasCache::getFontAtlasCharMap(const std::string& plistFile)
{
std::string atlasName = generateFontName(plistFile, 0, GlyphCollection::CUSTOM,false);
FontAtlas *tempAtlas = _atlasMap[atlasName];
if ( !tempAtlas )
{
tempAtlas = FontAtlasFactory::createAtlasFromCharMap(plistFile);
if (tempAtlas)
_atlasMap[atlasName] = tempAtlas;
}
else
{
tempAtlas->retain();
}
return tempAtlas;
}
FontAtlas * FontAtlasCache::getFontAtlasCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap)
{
char tmp[30];
sprintf(tmp,"name:%u_%d_%d_%d",texture->getName(),itemWidth,itemHeight,startCharMap);
std::string atlasName = generateFontName(tmp, 0, GlyphCollection::CUSTOM,false);
FontAtlas *tempAtlas = _atlasMap[atlasName];
if ( !tempAtlas )
{
tempAtlas = FontAtlasFactory::createAtlasFromCharMap(texture,itemWidth,itemHeight,startCharMap);
if (tempAtlas)
_atlasMap[atlasName] = tempAtlas;
}
else
{
tempAtlas->retain();
}
return tempAtlas;
}
FontAtlas * FontAtlasCache::getFontAtlasCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
{
std::string atlasName = generateFontName(charMapFile, 0, GlyphCollection::CUSTOM,false);
FontAtlas *tempAtlas = _atlasMap[atlasName];
if ( !tempAtlas )
{
tempAtlas = FontAtlasFactory::createAtlasFromCharMap(charMapFile,itemWidth,itemHeight,startCharMap);
if (tempAtlas)
_atlasMap[atlasName] = tempAtlas;
}
else
{
tempAtlas->retain();
}
return tempAtlas;
}
std::string FontAtlasCache::generateFontName(const std::string& fontFileName, int size, GlyphCollection theGlyphs, bool useDistanceField)
{
std::string tempName(fontFileName);

View File

@ -29,23 +29,24 @@
#include <iostream>
#include <unordered_map>
#include "cocos2d.h"
#include "CCFontAtlas.h"
#include "CCLabel.h"
NS_CC_BEGIN
class CC_DLL FontAtlasCache
{
public:
static FontAtlas * getFontAtlasTTF(const std::string& fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs = 0, bool useDistanceField = false);
static FontAtlas * getFontAtlasFNT(const std::string& fontFileName);
static FontAtlas * getFontAtlasCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap);
static FontAtlas * getFontAtlasCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap);
static FontAtlas * getFontAtlasCharMap(const std::string& plistFile);
static bool releaseFontAtlas(FontAtlas *atlas);
private:
static std::string generateFontName(const std::string& fontFileName, int size, GlyphCollection theGlyphs, bool useDistanceField);
static std::unordered_map<std::string, FontAtlas *> _atlasMap;
};

View File

@ -60,4 +60,46 @@ FontAtlas * FontAtlasFactory::createAtlasFromFNT(const std::string& fntFilePath)
}
}
FontAtlas * FontAtlasFactory::createAtlasFromCharMap(const std::string& plistFile)
{
Font *font = Font::createWithCharMap(plistFile);
if(font)
{
return font->createFontAtlas();
}
else
{
return nullptr;
}
}
FontAtlas * FontAtlasFactory::createAtlasFromCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap)
{
Font *font = Font::createWithCharMap(texture,itemWidth,itemHeight,startCharMap);
if(font)
{
return font->createFontAtlas();
}
else
{
return nullptr;
}
}
FontAtlas * FontAtlasFactory::createAtlasFromCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
{
Font *font = Font::createWithCharMap(charMapFile,itemWidth,itemHeight,startCharMap);
if(font)
{
return font->createFontAtlas();
}
else
{
return nullptr;
}
}
NS_CC_END

View File

@ -26,8 +26,8 @@
#ifndef _CCFontAtlasFactory_h_
#define _CCFontAtlasFactory_h_
#include "cocos2d.h"
#include "CCFontAtlas.h"
#include "CCLabel.h"
NS_CC_BEGIN
@ -40,6 +40,10 @@ public:
static FontAtlas * createAtlasFromTTF(const std::string& fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs = 0, bool useDistanceField = false);
static FontAtlas * createAtlasFromFNT(const std::string& fntFilePath);
static FontAtlas * createAtlasFromCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap);
static FontAtlas * createAtlasFromCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap);
static FontAtlas * createAtlasFromCharMap(const std::string& plistFile);
private:
};

171
cocos/2d/CCFontCharMap.cpp Normal file
View File

@ -0,0 +1,171 @@
/****************************************************************************
Copyright (c) 2013 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCFontCharMap.h"
#include "CCFontAtlas.h"
NS_CC_BEGIN
FontCharMap * FontCharMap::create(const std::string& plistFile)
{
std::string pathStr = FileUtils::getInstance()->fullPathForFilename(plistFile);
std::string relPathStr = pathStr.substr(0, pathStr.find_last_of("/"))+"/";
ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(pathStr.c_str());
CCASSERT(dict["version"].asInt() == 1, "Unsupported version. Upgrade cocos2d version");
std::string textureFilename = relPathStr + dict["textureFilename"].asString();
unsigned int width = dict["itemWidth"].asInt() / CC_CONTENT_SCALE_FACTOR();
unsigned int height = dict["itemHeight"].asInt() / CC_CONTENT_SCALE_FACTOR();
unsigned int startChar = dict["firstChar"].asInt();
Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(textureFilename);
if (!tempTexture)
{
return nullptr;
}
FontCharMap *tempFont = new FontCharMap(tempTexture,width,height,startChar);
if (!tempFont)
{
return nullptr;
}
tempFont->autorelease();
return tempFont;
}
FontCharMap* FontCharMap::create(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
{
Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(charMapFile);
if (!tempTexture)
{
return nullptr;
}
FontCharMap *tempFont = new FontCharMap(tempTexture,itemWidth,itemHeight,startCharMap);
if (!tempFont)
{
return nullptr;
}
tempFont->autorelease();
return tempFont;
}
FontCharMap* FontCharMap::create(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap)
{
FontCharMap *tempFont = new FontCharMap(texture,itemWidth,itemHeight,startCharMap);
if (!tempFont)
{
return nullptr;
}
tempFont->autorelease();
return tempFont;
}
FontCharMap::~FontCharMap()
{
}
Size * FontCharMap::getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const
{
if (!text)
return 0;
outNumLetters = cc_wcslen(text);
if (!outNumLetters)
return 0;
Size *sizes = new Size[outNumLetters];
if (!sizes)
return 0;
int advance = _itemWidth * CC_CONTENT_SCALE_FACTOR();
for (int c = 0; c < outNumLetters; ++c)
{
sizes[c].width = advance;
}
return sizes;
}
Rect FontCharMap::getRectForChar(unsigned short theChar) const
{
return _charRect;
}
FontAtlas * FontCharMap::createFontAtlas()
{
FontAtlas *tempAtlas = new FontAtlas(*this);
if (!tempAtlas)
return nullptr;
Size s = _texture->getContentSize();
int itemsPerColumn = (int)(s.height / _itemHeight);
int itemsPerRow = (int)(s.width / _itemWidth);
tempAtlas->setCommonLineHeight(_itemHeight);
FontLetterDefinition tempDefinition;
tempDefinition.textureID = 0;
tempDefinition.anchorX = 0.5f;
tempDefinition.anchorY = 0.5f;
tempDefinition.offsetX = 0.0f;
tempDefinition.offsetY = 0.0f;
tempDefinition.validDefinition = true;
tempDefinition.width = _itemWidth;
tempDefinition.height = _itemHeight;
int charId = _mapStartChar;
float itemWidthInPixels = _itemWidth * CC_CONTENT_SCALE_FACTOR();
float itemHeightInPixels = _itemHeight * CC_CONTENT_SCALE_FACTOR();
for (int row = 0; row < itemsPerColumn; ++row)
{
for (int col = 0; col < itemsPerRow; ++col)
{
tempDefinition.letteCharUTF16 = charId;
tempDefinition.U = _itemWidth * col;
tempDefinition.V = _itemHeight * row;
tempAtlas->addLetterDefinition(tempDefinition);
charId++;
}
}
tempAtlas->addTexture(*_texture,0);
return tempAtlas;
}
NS_CC_END

70
cocos/2d/CCFontCharMap.h Normal file
View File

@ -0,0 +1,70 @@
/****************************************************************************
Copyright (c) 2013 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef _CCFontCharMap_h_
#define _CCFontCharMap_h_
#include "cocos2d.h"
#include "CCFont.h"
NS_CC_BEGIN
class FontCharMap : public Font
{
public:
static FontCharMap * create(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap);
static FontCharMap * create(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap);
static FontCharMap * create(const std::string& plistFile);
virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const override;
virtual Rect getRectForChar(unsigned short theChar) const override;
virtual FontAtlas *createFontAtlas() override;
protected:
FontCharMap(Texture2D* texture,int itemWidth, int itemHeight, int startCharMap)
:_texture(texture)
,_mapStartChar(startCharMap)
,_itemWidth(itemWidth)
,_itemHeight(itemHeight)
,_charRect(0,0,itemWidth,itemHeight)
{}
/**
* @js NA
* @lua NA
*/
virtual ~FontCharMap();
private:
Texture2D* _texture;
int _mapStartChar;
int _itemWidth;
int _itemHeight;
Rect _charRect;
};
NS_CC_END
#endif /* defined(_CCFontCharMap_h_) */

View File

@ -23,8 +23,9 @@
THE SOFTWARE.
****************************************************************************/
#include "cocos2d.h"
#include "CCFontDefinition.h"
#include "CCDirector.h"
NS_CC_BEGIN
@ -221,7 +222,6 @@ FontAtlas * FontDefinitionTTF::createFontAtlas()
if ( item.second.validDefinition )
{
FontLetterDefinition tempDefinition = item.second;
tempDefinition.offsetX = 0;
tempDefinition.anchorX = 0.0f;
tempDefinition.anchorY = 1.0f;
retAtlas->addLetterDefinition(tempDefinition);

View File

@ -25,6 +25,10 @@
#include "CCFontFNT.h"
#include "CCFontAtlas.h"
#include "CCLabelBMFont.h"
#include "CCDirector.h"
#include "CCTextureCache.h"
#include "ccUTF8.h"
NS_CC_BEGIN

View File

@ -26,11 +26,12 @@
#ifndef _CCFontFNT_h_
#define _CCFontFNT_h_
#include "cocos2d.h"
#include "CCFont.h"
NS_CC_BEGIN
class CCBMFontConfiguration;
class FontFNT : public Font
{

View File

@ -31,6 +31,7 @@ THE SOFTWARE.
#include "CCTextImage.h"
#include "CCFont.h"
#include "CCFontDefinition.h"
#include "platform/CCFileUtils.h"
NS_CC_BEGIN
@ -175,7 +176,7 @@ bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect) const
return false;
// store result in the passed rectangle
outRect.origin.x = 0;
outRect.origin.x = _fontRef->glyph->metrics.horiBearingX >> 6;
outRect.origin.y = - (_fontRef->glyph->metrics.horiBearingY >> 6);
outRect.size.width = (_fontRef->glyph->metrics.width >> 6);
outRect.size.height = (_fontRef->glyph->metrics.height >> 6);
@ -267,7 +268,7 @@ Size * FontFreeType::getAdvancesForTextUTF16(unsigned short *text, int &outNumLe
int advance = 0;
int kerning = 0;
advance = getAdvanceForChar(text[c]) - getBearingXForChar(text[c]);
advance = getAdvanceForChar(text[c]);
if (c < (outNumLetters-1))
kerning = getHorizontalKerningForChars(text[c], text[c+1]);
@ -294,7 +295,7 @@ int FontFreeType::getAdvanceForChar(unsigned short theChar) const
return 0;
// get to the advance for this glyph
return (static_cast<int>(_fontRef->glyph->advance.x >> 6));
return (static_cast<int>(_fontRef->glyph->metrics.horiAdvance >> 6));
}
int FontFreeType::getBearingXForChar(unsigned short theChar) const

View File

@ -27,67 +27,85 @@
#include "CCFontDefinition.h"
#include "CCFontAtlasCache.h"
#include "CCLabelTextFormatter.h"
#include "CCSprite.h"
#include "CCShaderCache.h"
#include "ccUTF8.h"
#include "CCSpriteFrame.h"
#include "CCDirector.h"
#include "renderer/CCRenderer.h"
#define DISTANCEFIELD_ATLAS_FONTSIZE 50
NS_CC_BEGIN
Label* Label::createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize, TextHAlignment alignment, GlyphCollection glyphs, const char *customGlyphs, bool useDistanceField)
Label* Label::create()
{
FontAtlas *tmpAtlas = nullptr;
if(useDistanceField)
tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath.c_str(), DISTANCEFIELD_ATLAS_FONTSIZE, glyphs, customGlyphs,true);
else
tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath.c_str(), fontSize, glyphs, customGlyphs,false);
if (!tmpAtlas)
return nullptr;
// create the actual label
Label* templabel = Label::createWithAtlas(tmpAtlas, alignment, lineSize, useDistanceField,true);
if (templabel)
{
if(useDistanceField)
templabel->setFontSize(fontSize);
templabel->setText(label, lineSize, alignment, false);
return templabel;
}
return nullptr;
}
Label* Label::createWithBMFont(const std::string& label, const std::string& bmfontFilePath, TextHAlignment alignment, int lineSize)
{
FontAtlas *tmpAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath.c_str());
if (!tmpAtlas)
return 0;
Label* templabel = Label::createWithAtlas(tmpAtlas, alignment, lineSize);
if (templabel)
{
templabel->setText(label, lineSize, alignment, false);
return templabel;
}
else
{
return 0;
}
return 0;
}
Label* Label::createWithAtlas(FontAtlas *atlas, TextHAlignment alignment, int lineSize, bool useDistanceField,bool useA8Shader)
{
Label *ret = new Label(atlas, alignment, useDistanceField,useA8Shader);
Label *ret = new Label();
if (!ret)
return 0;
return nullptr;
if( ret->init() )
ret->autorelease();
return ret;
}
Label* Label::createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment alignment /* = TextHAlignment::CENTER */, int lineSize /* = 0 */)
{
Label *ret = new Label();
if (!ret)
return nullptr;
if (ret->setTTFConfig(ttfConfig))
{
if(ttfConfig.distanceFieldEnabled)
ret->setFontSize(ttfConfig.fontSize);
ret->setString(text,alignment,lineSize);
ret->autorelease();
return ret;
}
else
{
delete ret;
return nullptr;
}
}
Label* Label::createWithTTF(const std::string& text, const std::string& fontFilePath, int fontSize, int lineSize /* = 0 */, TextHAlignment alignment /* = TextHAlignment::CENTER */, GlyphCollection glyphs /* = GlyphCollection::NEHE */, const char *customGlyphs /* = 0 */, bool useDistanceField /* = false */)
{
TTFConfig ttfConfig(fontFilePath.c_str(),fontSize,glyphs,customGlyphs,useDistanceField);
return createWithTTF(ttfConfig,text,alignment,lineSize);
}
Label* Label::createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& alignment /* = TextHAlignment::CENTER */, int lineSize /* = 0 */)
{
Label *ret = new Label();
if (!ret)
return nullptr;
if (ret->setBMFontFilePath(bmfontFilePath))
{
ret->setString(text,alignment,lineSize);
ret->autorelease();
return ret;
}
else
{
delete ret;
return nullptr;
}
}
Label* Label::createWithCharMap(const std::string& plistFile)
{
Label *ret = new Label();
if (!ret)
return nullptr;
if (ret->setCharMap(plistFile))
{
ret->autorelease();
return ret;
@ -95,21 +113,86 @@ Label* Label::createWithAtlas(FontAtlas *atlas, TextHAlignment alignment, int li
else
{
delete ret;
return 0;
return nullptr;
}
}
return ret;
Label* Label::createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap)
{
Label *ret = new Label();
if (!ret)
return nullptr;
if (ret->setCharMap(texture,itemWidth,itemHeight,startCharMap))
{
ret->autorelease();
return ret;
}
else
{
delete ret;
return nullptr;
}
}
Label* Label::createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
{
Label *ret = new Label();
if (!ret)
return nullptr;
if (ret->setCharMap(charMapFile,itemWidth,itemHeight,startCharMap))
{
ret->autorelease();
return ret;
}
else
{
delete ret;
return nullptr;
}
}
bool Label::setCharMap(const std::string& plistFile)
{
FontAtlas *newAtlas = FontAtlasCache::getFontAtlasCharMap(plistFile);
if (!newAtlas)
return false;
return initWithFontAtlas(newAtlas);
}
bool Label::setCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap)
{
FontAtlas *newAtlas = FontAtlasCache::getFontAtlasCharMap(texture,itemWidth,itemHeight,startCharMap);
if (!newAtlas)
return false;
return initWithFontAtlas(newAtlas);
}
bool Label::setCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
{
FontAtlas *newAtlas = FontAtlasCache::getFontAtlasCharMap(charMapFile,itemWidth,itemHeight,startCharMap);
if (!newAtlas)
return false;
return initWithFontAtlas(newAtlas);
}
Label::Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField,bool useA8Shader)
: _reusedLetter(nullptr)
, _multilineEnable(true)
, _commonLineHeight(0.0f)
, _lineBreakWithoutSpaces(false)
, _width(0.0f)
, _alignment(alignment)
, _currentUTF16String(0)
, _originalUTF16String(0)
, _currentUTF16String(nullptr)
, _originalUTF16String(nullptr)
, _advances(nullptr)
, _fontAtlas(atlas)
, _isOpacityModifyRGB(true)
@ -118,6 +201,7 @@ Label::Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField,b
, _fontSize(0)
, _uniformEffectColor(0)
{
_cascadeColorEnabled = true;
}
Label::~Label()
@ -137,10 +221,13 @@ bool Label::init()
bool ret = true;
if(_fontAtlas)
{
_reusedLetter = Sprite::createWithTexture(&_fontAtlas->getTexture(0));
_reusedLetter->setOpacityModifyRGB(_isOpacityModifyRGB);
ret = SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), 30);
_reusedLetter->retain();
if (_reusedLetter == nullptr)
{
_reusedLetter = Sprite::createWithTexture(&_fontAtlas->getTexture(0));
_reusedLetter->setOpacityModifyRGB(_isOpacityModifyRGB);
_reusedLetter->retain();
}
ret = SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), 30);
}
if (_useDistanceField)
setLabelEffect(LabelEffect::NORMAL,Color3B::BLACK);
@ -148,46 +235,94 @@ bool Label::init()
setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_A8_COLOR));
else
setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
return ret;
}
void Label::setString(const std::string &stringToRender)
bool Label::initWithFontAtlas(FontAtlas* atlas,bool distanceFieldEnabled /* = false */, bool useA8Shader /* = false */)
{
_multilineEnable = true;
setText(stringToRender, _width, TextHAlignment::CENTER, false);
FontAtlas *oldAtlas = _fontAtlas;
bool oldDistanceFieldEnable = _useDistanceField;
bool oldA8ShaderEnabel = _useA8Shader;
_fontAtlas = atlas;
_useDistanceField = distanceFieldEnabled;
_useA8Shader = useA8Shader;
bool ret = Label::init();
if (oldAtlas)
{
if (ret)
{
FontAtlasCache::releaseFontAtlas(oldAtlas);
}
else
{
_fontAtlas = oldAtlas;
_useDistanceField = oldDistanceFieldEnable;
_useA8Shader = oldA8ShaderEnabel;
Label::init();
FontAtlasCache::releaseFontAtlas(atlas);
}
}
if (_fontAtlas)
{
_commonLineHeight = _fontAtlas->getCommonLineHeight();
if (_currentUTF16String)
{
alignText();
}
}
return ret;
}
void Label::setString(const std::string &stringToRender,bool multilineEnable)
bool Label::setTTFConfig(const TTFConfig& ttfConfig)
{
_multilineEnable = multilineEnable;
setText(stringToRender, _width, TextHAlignment::CENTER, false);
FontAtlas *newAtlas = nullptr;
if(ttfConfig.distanceFieldEnabled)
newAtlas = FontAtlasCache::getFontAtlasTTF(ttfConfig.fontFilePath, DISTANCEFIELD_ATLAS_FONTSIZE, ttfConfig.glyphs, ttfConfig.customGlyphs,true);
else
newAtlas = FontAtlasCache::getFontAtlasTTF(ttfConfig.fontFilePath, ttfConfig.fontSize, ttfConfig.glyphs, ttfConfig.customGlyphs,false);
if (!newAtlas)
return false;
return initWithFontAtlas(newAtlas,ttfConfig.distanceFieldEnabled,true);
}
bool Label::setText(const std::string& stringToRender, float lineWidth, TextHAlignment alignment, bool lineBreakWithoutSpaces)
bool Label::setBMFontFilePath(const std::string& bmfontFilePath)
{
if (!_fontAtlas)
FontAtlas *newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath);
if (!newAtlas)
return false;
return initWithFontAtlas(newAtlas);
}
bool Label::setString(const std::string& text, const TextHAlignment& alignment /* = TextHAlignment::CENTER */, float lineWidth /* = -1 */, bool lineBreakWithoutSpaces /* = false */)
{
if (!_fontAtlas || _commonLineHeight <= 0)
return false;
// carloX
// reset the string
resetCurrentString();
_width = lineWidth;
if(lineWidth >= 0)
{
_width = lineWidth;
}
_alignment = alignment;
_lineBreakWithoutSpaces = lineBreakWithoutSpaces;
// store locally common line height
_commonLineHeight = _fontAtlas->getCommonLineHeight();
if (_commonLineHeight <= 0)
return false;
// int numLetter = 0;
unsigned short* utf16String = cc_utf8_to_utf16(stringToRender.c_str());
unsigned short* utf16String = cc_utf8_to_utf16(text.c_str());
if(!utf16String)
return false;
_cascadeColorEnabled = true;
setCurrentString(utf16String);
setOriginalString(utf16String);
@ -299,7 +434,7 @@ void Label::alignText()
_textureAtlas->removeAllQuads();
_fontAtlas->prepareLetterDefinitions(_currentUTF16String);
LabelTextFormatter::createStringSprites(this);
if(_multilineEnable && LabelTextFormatter::multilineText(this) )
if(_width > 0 && LabelTextFormatter::multilineText(this) )
LabelTextFormatter::createStringSprites(this);
LabelTextFormatter::alignText(this);
@ -531,7 +666,7 @@ void Label::onDraw()
void Label::draw()
{
_customCommand.init(0, _vertexZ);
_customCommand.init(_globalZOrder);
_customCommand.func = CC_CALLBACK_0(Label::onDraw, this);
Director::getInstance()->getRenderer()->addCommand(&_customCommand);
}

View File

@ -54,23 +54,51 @@ enum class LabelEffect {
struct FontLetterDefinition;
class FontAtlas;
typedef struct _ttfConfig
{
std::string fontFilePath;
int fontSize;
GlyphCollection glyphs;
const char *customGlyphs;
bool distanceFieldEnabled;
_ttfConfig(const char* filePath,int size = 36, const GlyphCollection& glyphCollection = GlyphCollection::NEHE,
const char *customGlyphCollection = nullptr,bool useDistanceField = false)
:fontFilePath(filePath)
,fontSize(size)
,glyphs(glyphCollection)
,customGlyphs(customGlyphCollection)
,distanceFieldEnabled(useDistanceField)
{}
}TTFConfig;
class CC_DLL Label : public SpriteBatchNode, public LabelProtocol, public LabelTextFormatProtocol
class CC_DLL Label : public SpriteBatchNode, public LabelTextFormatProtocol
{
public:
static Label* create();
// static create
static Label* createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize = 0, TextHAlignment alignment = TextHAlignment::CENTER, GlyphCollection glyphs = GlyphCollection::NEHE, const char *customGlyphs = 0, bool useDistanceField = false);
CC_DEPRECATED_ATTRIBUTE static Label* createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize = 0, TextHAlignment alignment = TextHAlignment::CENTER, GlyphCollection glyphs = GlyphCollection::NEHE, const char *customGlyphs = 0, bool useDistanceField = false);
static Label* createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment alignment = TextHAlignment::CENTER, int lineWidth = 0);
static Label* createWithBMFont(const std::string& label, const std::string& bmfontFilePath, TextHAlignment alignment = TextHAlignment::CENTER, int lineSize = 0);
static Label* createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& alignment = TextHAlignment::CENTER, int lineWidth = 0);
bool setText(const std::string& stringToRender, float lineWidth, TextHAlignment alignment = TextHAlignment::LEFT, bool lineBreakWithoutSpaces = false);
static Label * createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap);
static Label * createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap);
static Label * createWithCharMap(const std::string& plistFile);
bool setTTFConfig(const TTFConfig& ttfConfig);
bool setBMFontFilePath(const std::string& bmfontFilePath);
bool setCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap);
bool setCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap);
bool setCharMap(const std::string& plistFile);
bool setString(const std::string& text, const TextHAlignment& alignment = TextHAlignment::CENTER, float lineWidth = -1, bool lineBreakWithoutSpaces = false);
//only support for TTF
void setLabelEffect(LabelEffect effect,const Color3B& effectColor);
virtual void setString(const std::string &stringToRender) override;
void setString(const std::string &stringToRender,bool multilineEnable);
virtual void setAlignment(TextHAlignment alignment);
virtual void setWidth(float width);
virtual void setLineBreakWithoutSpace(bool breakWithoutSpace);
@ -116,7 +144,7 @@ public:
virtual void setLabelContentSize(const Size &newSize) override;
// carloX
virtual const std::string& getString() const override { static std::string _ret("not implemented"); return _ret; }
virtual const std::string& getString() const { static std::string _ret("not implemented"); return _ret; }
void addChild(Node * child, int zOrder=0, int tag=0) override;
virtual std::string getDescription() const override;
@ -127,14 +155,14 @@ private:
/**
* @js NA
*/
Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField = false,bool useA8Shader = false);
Label(FontAtlas *atlas = nullptr, TextHAlignment alignment = TextHAlignment::CENTER, bool useDistanceField = false,bool useA8Shader = false);
/**
* @js NA
* @lua NA
*/
~Label();
static Label* createWithAtlas(FontAtlas *atlas, TextHAlignment alignment = TextHAlignment::LEFT, int lineSize = 0, bool useDistanceField = false,bool useA8Shader = false);
bool initWithFontAtlas(FontAtlas* atlas,bool distanceFieldEnabled = false, bool useA8Shader = false);
void setFontSize(int fontSize);
@ -151,32 +179,30 @@ private:
virtual void updateColor() override;
//! used for optimization
Sprite *_reusedLetter;
std::vector<LetterInfo> _lettersInfo;
Sprite *_reusedLetter;
std::vector<LetterInfo> _lettersInfo;
bool _multilineEnable;
float _commonLineHeight;
bool _lineBreakWithoutSpaces;
float _width;
TextHAlignment _alignment;
unsigned short int * _currentUTF16String;
unsigned short int * _originalUTF16String;
Size * _advances;
FontAtlas * _fontAtlas;
bool _isOpacityModifyRGB;
float _commonLineHeight;
bool _lineBreakWithoutSpaces;
float _width;
TextHAlignment _alignment;
unsigned short int * _currentUTF16String;
unsigned short int * _originalUTF16String;
Size * _advances;
FontAtlas * _fontAtlas;
bool _isOpacityModifyRGB;
bool _useDistanceField;
bool _useA8Shader;
int _fontSize;
bool _useDistanceField;
bool _useA8Shader;
int _fontSize;
LabelEffect _currLabelEffect;
Color3B _effectColor;
LabelEffect _currLabelEffect;
Color3B _effectColor;
GLuint _uniformEffectColor;
GLuint _uniformEffectColor;
CustomCommand _customCommand;
CustomCommand _customCommand;
};

View File

@ -275,8 +275,7 @@ std::set<unsigned int>* CCBMFontConfiguration::parseBinaryConfigFile(unsigned ch
unsigned long remains = size;
unsigned char version = pData[3];
CCASSERT(version == 3, "Only version 3 is supported");
CCASSERT(pData[3] == 3, "Only version 3 is supported");
pData += 4; remains -= 4;
@ -343,8 +342,7 @@ std::set<unsigned int>* CCBMFontConfiguration::parseBinaryConfigFile(unsigned ch
*/
const char *value = (const char *)pData;
size_t len = strlen(value);
CCASSERT(len < blockSize, "Block size should be less then string");
CCASSERT(strlen(value) < blockSize, "Block size should be less then string");
_atlasName = FileUtils::getInstance()->fullPathFromRelativeFile(value, controlFile);
}

View File

@ -25,11 +25,16 @@
#ifndef _CCLabelTextFormatProtocol_h_
#define _CCLabelTextFormatProtocol_h_
#include "CCFontAtlas.h"
#include <vector>
#include "CCFontAtlas.h"
#include "CCGeometry.h"
#include "ccTypes.h"
NS_CC_BEGIN
class Sprite;
struct LetterInfo
{
@ -46,13 +51,13 @@ public:
virtual ~LabelTextFormatProtocol() {}
virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex) = 0;
virtual bool recordLetterInfo(const Point& point,unsigned short int theChar, int spriteIndex) = 0;
virtual bool recordPlaceholderInfo(int spriteIndex) = 0;
virtual std::vector<LetterInfo> *getLettersInfo() = 0;
virtual float getLetterPosXLeft(int index) const = 0;
virtual float getLetterPosXRight(int index) const = 0;
// sprite related stuff
virtual cocos2d::Sprite *getLetter(int ID) = 0;
virtual Sprite *getLetter(int ID) = 0;
// font related stuff
virtual int getCommonLineHeight() const = 0;
@ -60,7 +65,7 @@ public:
virtual int getXOffsetForChar(unsigned short c) const = 0;
virtual int getYOffsetForChar(unsigned short c) const = 0;
virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const = 0;
virtual cocos2d::Rect getRectForChar(unsigned short c) const = 0;
virtual Rect getRectForChar(unsigned short c) const = 0;
// string related stuff
virtual int getStringNumLines() const = 0;
@ -68,7 +73,7 @@ public:
virtual unsigned short getCharAtStringPosition(int position) const = 0;
virtual unsigned short * getUTF8String() const = 0;
virtual void assignNewUTF8String(unsigned short *newString) = 0;
virtual TextHAlignment getTextAlignment() const = 0;
virtual TextHAlignment getTextAlignment() const = 0;
// label related stuff
virtual float getMaxLineWidth() const = 0;

View File

@ -25,9 +25,9 @@
#include <vector>
#include "cocos2d.h"
#include "ccUTF8.h"
#include "CCLabelTextFormatter.h"
#include "CCDirector.h"
using namespace std;
@ -68,15 +68,19 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel)
while (info->def.validDefinition == false)
{
justSkipped++;
info = &leterInfo->at( j+skip+justSkipped );
tIndex = j+skip+justSkipped;
if(tIndex < strLen)
info = &leterInfo->at( tIndex );
else
break;
}
skip += justSkipped;
tIndex = j + skip;
if (i >= stringLength)
if (tIndex >= stringLength)
break;
unsigned short character = strWhole[i];
unsigned short character = strWhole[tIndex];
if (!isStartOfWord)
{
@ -241,8 +245,6 @@ bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel)
continue;
}
int index = static_cast<int>(i + lineLength - 1 + lineNumber);
if(currentChar == 0)
index -= 1;
if (index < 0) continue;
LetterInfo* info = &leterInfo->at( index );
@ -351,7 +353,7 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel)
Point fontPos = Point((float)nextFontPositionX + charXOffset + charRect.size.width * 0.5f + kerningAmount,
(float)nextFontPositionY + yOffset - charRect.size.height * 0.5f);
(float)nextFontPositionY + yOffset - charRect.size.height * 0.5f);
if( theLabel->recordLetterInfo(CC_POINT_PIXELS_TO_POINTS(fontPos),c,i) == false)
{

View File

@ -44,8 +44,8 @@ THE SOFTWARE.
#include "CCEventListenerAcceleration.h"
#include "platform/CCDevice.h"
#include "CCScene.h"
#include "CCCustomCommand.h"
#include "CCRenderer.h"
#include "renderer/CCCustomCommand.h"
#include "renderer/CCRenderer.h"
NS_CC_BEGIN
@ -565,7 +565,7 @@ void LayerColor::updateColor()
void LayerColor::draw()
{
_customCommand.init(0, _vertexZ);
_customCommand.init(_globalZOrder);
_customCommand.func = CC_CALLBACK_0(LayerColor::onDraw, this);
Director::getInstance()->getRenderer()->addCommand(&_customCommand);

View File

@ -31,8 +31,8 @@ THE SOFTWARE.
#include "ccMacros.h"
#include "CCDirector.h"
#include "CCVertex.h"
#include "CCCustomCommand.h"
#include "CCRenderer.h"
#include "renderer/CCCustomCommand.h"
#include "renderer/CCRenderer.h"
NS_CC_BEGIN
@ -359,7 +359,7 @@ void MotionStreak::draw()
if(_nuPoints <= 1)
return;
kmGLGetMatrix(KM_GL_MODELVIEW,&_cachedMV);
_customCommand.init(0,_vertexZ);
_customCommand.init(_globalZOrder);
_customCommand.func = CC_CALLBACK_0(MotionStreak::onDraw, this);
Director::getInstance()->getRenderer()->addCommand(&_customCommand);

View File

@ -108,7 +108,8 @@ Node::Node(void)
, _inverseDirty(true)
// children (lazy allocs)
// lazy alloc
, _ZOrder(0)
, _localZOrder(0)
, _globalZOrder(0)
, _parent(nullptr)
// "whole screen" objects. like Scenes and Layers, should set _ignoreAnchorPointForPosition to true
, _tag(Node::INVALID_TAG)
@ -212,28 +213,21 @@ void Node::setSkewY(float newSkewY)
_transformDirty = _inverseDirty = true;
}
/// zOrder getter
int Node::getZOrder() const
{
return _ZOrder;
}
/// zOrder setter : private method
/// used internally to alter the zOrder variable. DON'T call this method manually
void Node::_setZOrder(int z)
void Node::_setLocalZOrder(int z)
{
_ZOrder = z;
_localZOrder = z;
}
void Node::setZOrder(int z)
void Node::setLocalZOrder(int z)
{
_localZOrder = z;
if (_parent)
{
_parent->reorderChild(this, z);
}
// should set "_ZOrder" after reorderChild, because the implementation of reorderChild subclass of Node, such as Sprite,
// will return when _ZOrder value is not changed
_setZOrder(z);
_eventDispatcher->setDirtyForNode(this);
}
@ -246,9 +240,10 @@ float Node::getVertexZ() const
/// vertexZ setter
void Node::setVertexZ(float var)
void Node::setVertexZ(float zOrder)
{
_vertexZ = var;
_vertexZ = zOrder;
setGlobalZOrder(zOrder);
}
@ -650,7 +645,7 @@ void Node::addChild(Node *child, int zOrder)
void Node::addChild(Node *child)
{
CCASSERT( child != nullptr, "Argument must be non-nil");
this->addChild(child, child->_ZOrder, child->_tag);
this->addChild(child, child->_localZOrder, child->_tag);
}
void Node::removeFromParent()
@ -767,7 +762,7 @@ void Node::insertChild(Node* child, int z)
{
_reorderChildDirty = true;
_children.pushBack(child);
child->_setZOrder(z);
child->_setLocalZOrder(z);
}
void Node::reorderChild(Node *child, int zOrder)
@ -775,7 +770,7 @@ void Node::reorderChild(Node *child, int zOrder)
CCASSERT( child != nullptr, "Child must be non-nil");
_reorderChildDirty = true;
child->setOrderOfArrival(s_globalOrderOfArrival++);
child->_setZOrder(zOrder);
child->_setLocalZOrder(zOrder);
}
void Node::sortAllChildren()
@ -816,7 +811,7 @@ void Node::visit()
{
auto node = _children.at(i);
if ( node && node->_ZOrder < 0 )
if ( node && node->_localZOrder < 0 )
node->visit();
else
break;

View File

@ -161,43 +161,72 @@ public:
/// @name Setters & Getters for Graphic Peroperties
/**
* Sets the Z order which stands for the drawing order, and reorder this node in its parent's children array.
*
* The Z order of node is relative to its siblings.
* It is not related to the OpenGL's z property. This one only affects the draw order of itself and its siblings.
* Lower Z order number are drawn before higher numbers.
* Please refer to `setVertexZ(float)` for the difference.
*
* @param zOrder Z order of this node.
LocalZOrder is the 'key' used to sort the node relative to its siblings.
The Node's parent will sort all its children based ont the LocalZOrder value.
If two nodes have the same LocalZOrder, then the node that was added first to the children's array will be in front of the other node in the array.
Also, the Scene Graph is traversed using the "In-Order" tree traversal algorithm ( http://en.wikipedia.org/wiki/Tree_traversal#In-order )
And Nodes that have LocalZOder values < 0 are the "left" subtree
While Nodes with LocalZOder >=0 are the "right" subtree.
@see `setGlobalZOrder`
@see `setVertexZ`
*/
virtual void setZOrder(int zOrder);
/*
* Sets the z order which stands for the drawing order
*
* This is an internal method. Don't call it outside the framework.
* The difference between setZOrder(int) and _setOrder(int) is:
* - _setZOrder(int) is a pure setter for _ZOrder memeber variable
* - setZOrder(int) firstly changes _ZOrder, then recorder this node in its parent's chilren array.
virtual void setLocalZOrder(int zOrder);
CC_DEPRECATED_ATTRIBUTE virtual void setZOrder(int zOrder) { setLocalZOrder(zOrder); }
/* Helper function used by `setLocalZOrder`. Don't use it unless you know what you are doing.
*/
virtual void _setZOrder(int z);
virtual void _setLocalZOrder(int z);
/**
* Gets the Z order of this node.
* Gets the local Z order of this node.
*
* @see `setZOrder(int)`
* @see `setLocalZOrder(int)`
*
* @return The Z order.
* @return The local (relative to its siblings) Z order.
*/
virtual int getZOrder() const;
virtual int getLocalZOrder() const { return _localZOrder; }
CC_DEPRECATED_ATTRIBUTE virtual int getZOrder() const { return getLocalZOrder(); }
/**
* Sets the real OpenGL Z vertex.
Defines the oder in which the nodes are renderer.
Nodes that have a Global Z Order lower, are renderer first.
In case two or more nodes have the same Global Z Order, the oder is not guaranteed.
The only exception if the Nodes have a Global Z Order == 0. In that case, the Scene Graph order is used.
By default, all nodes have a Global Z Order = 0. That means that by default, the Scene Graph order is used to render the nodes.
Global Z Order is useful when you need to render nodes in an order different than the Scene Graph order.
Limitations: Global Z Order can't be used used by Nodes that have SpriteBatchNode as one of their acenstors.
And if ClippingNode is one of the ancestors, then "global Z order" will be relative to the ClippingNode.
@see `setLocalZOrder()`
@see `setVertexZ()`
@since v3.0
*/
virtual void setGlobalZOrder(float zOrder) { _globalZOrder = zOrder; }
/**
* Returns the Node's Global Z Order.
*
* Differences between openGL Z vertex and cocos2d Z order:
* - OpenGL Z modifies the Z vertex, and not the Z order in the relation between parent-children
* - OpenGL Z might require to set 2D projection
* - cocos2d Z order works OK if all the nodes uses the same openGL Z vertex. eg: `vertexZ = 0`
* @see `setGlobalZOrder(int)`
*
* @warning Use it at your own risk since it might break the cocos2d parent-children z order
* @return The node's global Z order
*/
virtual float getGlobalZOrder() const { return _globalZOrder; }
/**
* Sets the 'z' value in the OpenGL Depth Buffer.
*
* The OpenGL depth buffer and depth testing are disabled by default. You need to turn them on
* in order to use this property correctly.
*
* `setVertexZ()` also sets the `setGlobalZValue()` with the vertexZ value.
*
* @see `setGlobalZValue()`
*
* @param vertexZ OpenGL Z vertex of this node.
*/
@ -1411,7 +1440,6 @@ protected:
float _scaleX; ///< scaling factor on x-axis
float _scaleY; ///< scaling factor on y-axis
float _vertexZ; ///< OpenGL real Z vertex
Point _position; ///< position of the node
@ -1433,7 +1461,11 @@ protected:
mutable bool _transformDirty; ///< transform dirty flag
mutable bool _inverseDirty; ///< inverse transform dirty flag
int _ZOrder; ///< z-order value that affects the draw order
int _localZOrder; ///< Local order (relative to its siblings) used to sort the node
float _globalZOrder; ///< Global order used to sort the node
float _vertexZ; ///< OpenGL real Z vertex
Vector<Node*> _children; ///< array of children nodes
Node *_parent; ///< weak reference to parent node

View File

@ -25,9 +25,9 @@
#include "CCNodeGrid.h"
#include "CCGrid.h"
#include "CCGroupCommand.h"
#include "CCRenderer.h"
#include "CCCustomCommand.h"
#include "renderer/CCGroupCommand.h"
#include "renderer/CCRenderer.h"
#include "renderer/CCCustomCommand.h"
NS_CC_BEGIN
@ -92,7 +92,7 @@ void NodeGrid::visit()
Renderer* renderer = Director::getInstance()->getRenderer();
_groupCommand.init(0,_vertexZ);
_groupCommand.init(_globalZOrder);
renderer->addCommand(&_groupCommand);
renderer->pushGroup(_groupCommand.getRenderQueueID());
@ -104,7 +104,7 @@ void NodeGrid::visit()
_nodeGrid->set2DProjection();
}
_gridBeginCommand.init(0,_vertexZ);
_gridBeginCommand.init(_globalZOrder);
_gridBeginCommand.func = CC_CALLBACK_0(NodeGrid::onGridBeginDraw, this);
renderer->addCommand(&_gridBeginCommand);
@ -152,7 +152,7 @@ void NodeGrid::visit()
director->setProjection(beforeProjectionType);
}
_gridEndCommand.init(0,_vertexZ);
_gridEndCommand.init(_globalZOrder);
_gridEndCommand.func = CC_CALLBACK_0(NodeGrid::onGridEndDraw, this);
renderer->addCommand(&_gridEndCommand);

View File

@ -44,7 +44,7 @@
#include "kazmath/GL/matrix.h"
#include "CCProfiling.h"
#include "renderer/CCQuadCommand.h"
#include "CCRenderer.h"
#include "renderer/CCRenderer.h"
NS_CC_BEGIN
@ -197,7 +197,7 @@ int ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag)
_children.insert(pos, child);
child->setTag(aTag);
child->_setZOrder(z);
child->_setLocalZOrder(z);
child->setParent(this);
@ -264,7 +264,7 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder)
}
}
child->_setZOrder(zOrder);
child->_setLocalZOrder(zOrder);
}
void ParticleBatchNode::getCurrentIndex(int* oldIndex, int* newIndex, Node* child, int z)
@ -382,26 +382,14 @@ void ParticleBatchNode::draw(void)
return;
}
// CC_NODE_DRAW_SETUP();
//
// GL::blendFunc( _blendFunc.src, _blendFunc.dst );
//
// _textureAtlas->drawQuads();
auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP);
kmMat4 mv;
kmGLGetMatrix(KM_GL_MODELVIEW, &mv);
_quadCommand.init(0,
_vertexZ,
_textureAtlas->getTexture()->getName(),
shader,
_blendFunc,
_textureAtlas->getQuads(),
_textureAtlas->getTotalQuads(),
mv);
Director::getInstance()->getRenderer()->addCommand(&_quadCommand);
_batchCommand.init(
_globalZOrder,
_textureAtlas->getTexture()->getName(),
_shaderProgram,
_blendFunc,
_textureAtlas,
_modelViewTransform);
Director::getInstance()->getRenderer()->addCommand(&_batchCommand);
CC_PROFILER_STOP("CCParticleBatchNode - draw");
}

View File

@ -32,7 +32,7 @@
#include "CCNode.h"
#include "CCProtocols.h"
#include "renderer/CCQuadCommand.h"
#include "renderer/CCBatchCommand.h"
NS_CC_BEGIN
@ -146,7 +146,7 @@ private:
/** the blend function used for drawing the quads */
BlendFunc _blendFunc;
// quad command
QuadCommand _quadCommand;
BatchCommand _batchCommand;
};
// end of particle_nodes group

View File

@ -38,9 +38,9 @@ THE SOFTWARE.
#include "TransformUtils.h"
#include "CCEventType.h"
#include "CCConfiguration.h"
#include "CCRenderer.h"
#include "renderer/CCRenderer.h"
#include "renderer/CCQuadCommand.h"
#include "CCCustomCommand.h"
#include "renderer/CCCustomCommand.h"
// extern
#include "kazmath/GL/matrix.h"
@ -439,7 +439,7 @@ void ParticleSystemQuad::draw()
auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP);
_quadCommand.init(0, _vertexZ, _texture->getName(), shader, _blendFunc, _quads, _particleIdx, _modelViewTransform);
_quadCommand.init(_globalZOrder, _texture->getName(), shader, _blendFunc, _quads, _particleIdx, _modelViewTransform);
Director::getInstance()->getRenderer()->addCommand(&_quadCommand);
}

View File

@ -33,8 +33,8 @@ THE SOFTWARE.
#include "CCDirector.h"
#include "TransformUtils.h"
#include "CCDrawingPrimitives.h"
#include "CCRenderer.h"
#include "CCCustomCommand.h"
#include "renderer/CCRenderer.h"
#include "renderer/CCCustomCommand.h"
// extern
#include "kazmath/GL/matrix.h"
@ -555,7 +555,7 @@ void ProgressTimer::draw()
if( ! _vertexData || ! _sprite)
return;
_customCommand.init(0, _vertexZ);
_customCommand.init(_globalZOrder);
_customCommand.func = CC_CALLBACK_0(ProgressTimer::onDraw, this);
Director::getInstance()->getRenderer()->addCommand(&_customCommand);
}

View File

@ -38,9 +38,9 @@ THE SOFTWARE.
#include "CCEventType.h"
#include "CCGrid.h"
#include "CCRenderer.h"
#include "CCGroupCommand.h"
#include "CCCustomCommand.h"
#include "renderer/CCRenderer.h"
#include "renderer/CCGroupCommand.h"
#include "renderer/CCCustomCommand.h"
// extern
#include "kazmath/GL/matrix.h"
@ -322,7 +322,7 @@ void RenderTexture::beginWithClear(float r, float g, float b, float a, float dep
this->begin();
//clear screen
_beginWithClearCommand.init(0, _vertexZ);
_beginWithClearCommand.init(_globalZOrder);
_beginWithClearCommand.func = CC_CALLBACK_0(RenderTexture::onClear, this);
Director::getInstance()->getRenderer()->addCommand(&_beginWithClearCommand);
}
@ -340,7 +340,7 @@ void RenderTexture::clearDepth(float depthValue)
this->begin();
_clearDepthCommand.init(0, _vertexZ);
_clearDepthCommand.init(_globalZOrder);
_clearDepthCommand.func = CC_CALLBACK_0(RenderTexture::onClearDepth, this);
Director::getInstance()->getRenderer()->addCommand(&_clearDepthCommand);
@ -605,7 +605,7 @@ void RenderTexture::draw()
begin();
//clear screen
_clearCommand.init(0, _vertexZ);
_clearCommand.init(_globalZOrder);
_clearCommand.func = CC_CALLBACK_0(RenderTexture::onClear, this);
Director::getInstance()->getRenderer()->addCommand(&_clearCommand);
@ -648,13 +648,13 @@ void RenderTexture::begin()
(float)-1.0 / heightRatio, (float)1.0 / heightRatio, -1,1 );
kmGLMultMatrix(&orthoMatrix);
_groupCommand.init(0, _vertexZ);
_groupCommand.init(_globalZOrder);
Renderer *renderer = Director::getInstance()->getRenderer();
renderer->addCommand(&_groupCommand);
renderer->pushGroup(_groupCommand.getRenderQueueID());
_beginCommand.init(0, _vertexZ);
_beginCommand.init(_globalZOrder);
_beginCommand.func = CC_CALLBACK_0(RenderTexture::onBegin, this);
Director::getInstance()->getRenderer()->addCommand(&_beginCommand);
@ -662,7 +662,7 @@ void RenderTexture::begin()
void RenderTexture::end()
{
_endCommand.init(0, _vertexZ);
_endCommand.init(_globalZOrder);
_endCommand.func = CC_CALLBACK_0(RenderTexture::onEnd, this);
Renderer *renderer = Director::getInstance()->getRenderer();

View File

@ -45,9 +45,9 @@ THE SOFTWARE.
#include "CCAffineTransform.h"
#include "TransformUtils.h"
#include "CCProfiling.h"
#include "CCRenderer.h"
#include "renderer/CCRenderer.h"
#include "renderer/CCQuadCommand.h"
#include "CCFrustum.h"
#include "renderer/CCFrustum.h"
// external
#include "kazmath/GL/matrix.h"
@ -243,8 +243,6 @@ bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect, bool rotated)
// zwoptex default values
_offsetPosition = Point::ZERO;
_hasChildren = false;
// clean the Quad
memset(&_quad, 0, sizeof(_quad));
@ -672,7 +670,7 @@ void Sprite::updateTransform(void)
void Sprite::draw(void)
{
//TODO implement z order
_quadCommand.init(0, _vertexZ, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, _modelViewTransform);
_quadCommand.init(_globalZOrder, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, _modelViewTransform);
// if(culling())
{
@ -767,18 +765,12 @@ void Sprite::addChild(Node *child, int zOrder, int tag)
}
//CCNode already sets isReorderChildDirty_ so this needs to be after batchNode check
Node::addChild(child, zOrder, tag);
_hasChildren = true;
}
void Sprite::reorderChild(Node *child, int zOrder)
{
CCASSERT(child != nullptr, "");
CCASSERT(_children.contains(child), "");
if (zOrder == child->getZOrder())
{
return;
}
CCASSERT(child != nullptr, "child must be non null");
CCASSERT(_children.contains(child), "child does not belong to this");
if( _batchNode && ! _reorderChildDirty)
{
@ -813,8 +805,6 @@ void Sprite::removeAllChildrenWithCleanup(bool cleanup)
}
Node::removeAllChildrenWithCleanup(cleanup);
_hasChildren = false;
}
void Sprite::sortAllChildren()
@ -882,27 +872,24 @@ void Sprite::setDirtyRecursively(bool bValue)
{
_recursiveDirty = bValue;
setDirty(bValue);
// recursively set dirty
if (_hasChildren)
{
for(const auto &child: _children) {
Sprite* sp = dynamic_cast<Sprite*>(child);
if (sp)
{
sp->setDirtyRecursively(true);
}
for(const auto &child: _children) {
Sprite* sp = dynamic_cast<Sprite*>(child);
if (sp)
{
sp->setDirtyRecursively(true);
}
}
}
// XXX HACK: optimization
#define SET_DIRTY_RECURSIVELY() { \
if (! _recursiveDirty) { \
_recursiveDirty = true; \
setDirty(true); \
if ( _hasChildren) \
setDirtyRecursively(true); \
} \
#define SET_DIRTY_RECURSIVELY() { \
if (! _recursiveDirty) { \
_recursiveDirty = true; \
setDirty(true); \
if (!_children.empty()) \
setDirtyRecursively(true); \
} \
}
void Sprite::setPosition(const Point& pos)

View File

@ -538,7 +538,6 @@ protected:
bool _dirty; /// Whether the sprite needs to be updated
bool _recursiveDirty; /// Whether all of the sprite's children needs to be updated
bool _hasChildren; /// Whether the sprite contains children
bool _shouldBeHidden; /// should not be drawn because one of the ancestors is not visible
kmMat4 _transformToBatch;

View File

@ -43,7 +43,7 @@ THE SOFTWARE.
#include "CCProfiling.h"
#include "CCLayer.h"
#include "CCScene.h"
#include "CCRenderer.h"
#include "renderer/CCRenderer.h"
#include "renderer/CCQuadCommand.h"
// external
#include "kazmath/GL/matrix.h"
@ -99,7 +99,7 @@ bool SpriteBatchNode::initWithTexture(Texture2D *tex, ssize_t capacity)
_descendants.reserve(capacity);
setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP));
setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
return true;
}
@ -356,18 +356,14 @@ void SpriteBatchNode::draw()
for(const auto &child: _children)
child->updateTransform();
kmMat4 mv;
kmGLGetMatrix(KM_GL_MODELVIEW, &mv);
_quadCommand.init(0,
_vertexZ,
_textureAtlas->getTexture()->getName(),
_shaderProgram,
_blendFunc,
_textureAtlas->getQuads(),
_textureAtlas->getTotalQuads(),
mv);
Director::getInstance()->getRenderer()->addCommand(&_quadCommand);
_batchCommand.init(
_globalZOrder,
_textureAtlas->getTexture()->getName(),
_shaderProgram,
_blendFunc,
_textureAtlas,
_modelViewTransform);
Director::getInstance()->getRenderer()->addCommand(&_batchCommand);
}
void SpriteBatchNode::increaseAtlasCapacity(void)

View File

@ -35,7 +35,7 @@ THE SOFTWARE.
#include "CCProtocols.h"
#include "CCTextureAtlas.h"
#include "ccMacros.h"
#include "renderer/CCQuadCommand.h"
#include "renderer/CCBatchCommand.h"
NS_CC_BEGIN
@ -189,7 +189,7 @@ protected:
TextureAtlas *_textureAtlas;
BlendFunc _blendFunc;
QuadCommand _quadCommand; // quad command
BatchCommand _batchCommand; // render command
// all descendants: children, grand children, etc...
// There is not need to retain/release these objects, since they are already retained by _children

View File

@ -174,7 +174,7 @@ void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo)
if (layerInfo->_visible)
{
TMXLayer *child = parseLayer(layerInfo, mapInfo);
addChild((Node*)child, idx, idx);
addChild(child, idx, idx);
// update content size with the max size
const Size& childSize = child->getContentSize();

View File

@ -28,10 +28,10 @@
#include <vector>
#include <string>
#include "cocos2d.h"
#include "CCTextImage.h"
#include "CCFontFreeType.h"
#include "CCFont.h"
#include "ccUTF8.h"
NS_CC_BEGIN
@ -295,7 +295,7 @@ bool TextImage::createPageDefinitions(unsigned short int *inText, int imageWidth
return true;
}
int TextImage::getNumGlyphsFittingInSize(std::map<unsigned short int, GlyphDef> &glyphDefs, unsigned short int *strUTF8, Font *font, Size *constrainSize, int &outNewSize)
int TextImage::getNumGlyphsFittingInSize(std::unordered_map<unsigned short int, GlyphDef> &glyphDefs, unsigned short int *strUTF8, Font *font, Size *constrainSize, int &outNewSize)
{
if (!strUTF8)
return 0;

View File

@ -23,15 +23,19 @@
THE SOFTWARE.
****************************************************************************/
#ifndef _TextImage_h_
#define _TextImage_h_
#ifndef _CCTextImage_h_
#define _CCTextImage_h_
//#include "CCFont.h"
#include <vector>
#include <unordered_map>
#include "CCPlatformMacros.h"
#include "CCGeometry.h"
NS_CC_BEGIN
class Font;
class Texture2D;
/** @brief GlyphDef defines one single glyph (character) in a text image
*
@ -43,27 +47,33 @@ class CC_DLL GlyphDef
{
public:
GlyphDef() : _validGlyph(false) { /*do nothing*/ }
GlyphDef(unsigned short int letterUTF8, const Rect &rect) { _gliphRect = rect; _uTF16Letter = letterUTF8; }
GlyphDef() : _validGlyph(false) {}
GlyphDef(unsigned short int letterUTF8, const Rect &rect) {
_gliphRect = rect;
_uTF16Letter = letterUTF8;
}
void setUTF16Letter(unsigned short int letterUTF8) { _uTF16Letter = letterUTF8; }
void setRect(const Rect & theRect) { _gliphRect = theRect; }
unsigned short int getUTF8Letter() { return _uTF16Letter; }
const Rect & getRect() const { return _gliphRect; }
void setPadding(float padding) { _padding = padding; }
float getPadding() { return _padding; }
void setCommonHeight(float commonHeight) { _commonHeight = commonHeight; }
float getCommonHeight() { return _commonHeight; }
void setValid(bool isValid) { _validGlyph = isValid; }
bool isValid() { return _validGlyph; }
void setUTF16Letter(unsigned short int letterUTF8) { _uTF16Letter = letterUTF8; }
void setRect(const Rect & theRect) { _gliphRect = theRect; }
private:
unsigned short int getUTF8Letter() const { return _uTF16Letter; }
const Rect& getRect() const { return _gliphRect; }
Rect _gliphRect;
unsigned short int _uTF16Letter;
float _padding;
float _commonHeight;
bool _validGlyph;
void setPadding(float padding) { _padding = padding; }
float getPadding() const { return _padding; }
void setCommonHeight(float commonHeight) { _commonHeight = commonHeight; }
float getCommonHeight() const { return _commonHeight; }
void setValid(bool isValid) { _validGlyph = isValid; }
bool isValid() const { return _validGlyph; }
protected:
Rect _gliphRect;
unsigned short int _uTF16Letter;
float _padding;
float _commonHeight;
bool _validGlyph;
};
@ -78,23 +88,21 @@ public:
TextLineDef(float x, float y, float width, float height);
float getX() const { return _x; }
float getY() const { return _y; }
float getWidth() const { return _width; }
float getHeight() const { return _height; }
float getX() const { return _x; }
float getY() const { return _y; }
float getWidth() const { return _width; }
float getHeight() const { return _height; }
void addGlyph(GlyphDef theGlyph) { _glyphs.push_back(theGlyph); }
int getNumGlyph() const { return static_cast<int>(_glyphs.size()); }
const GlyphDef & getGlyphAt(int index) const { return _glyphs[index]; }
private:
float _x;
float _y;
float _width;
float _height;
std::vector<GlyphDef> _glyphs;
void addGlyph(GlyphDef theGlyph) { _glyphs.push_back(theGlyph); }
int getNumGlyph() const { return static_cast<int>(_glyphs.size()); }
const GlyphDef & getGlyphAt(int index) const { return _glyphs[index]; }
protected:
float _x;
float _y;
float _width;
float _height;
std::vector<GlyphDef> _glyphs;
};
/** @brief TextPageDef defines one text image page (a TextImage can have/use more than one page)
@ -115,28 +123,26 @@ public:
*/
~TextPageDef();
void addLine(TextLineDef *theLine) { _lines.push_back(theLine); }
int getNumLines() const { return static_cast<int>(_lines.size()); }
TextLineDef * getLineAt(int index) const { return _lines[index]; }
int getWidth() const { return _width; }
int getHeight() const { return _height; }
int getPageNumber() const { return _pageNum; }
void setPageData(unsigned char *data) { _pageData = data; }
const unsigned char * getPageData() const { return _pageData; }
Texture2D *getPageTexture();
void addLine(TextLineDef *theLine) { _lines.push_back(theLine); }
int getNumLines() const { return static_cast<int>(_lines.size()); }
TextLineDef * getLineAt(int index) const { return _lines[index]; }
int getWidth() const { return _width; }
int getHeight() const { return _height; }
int getPageNumber() const { return _pageNum; }
void setPageData(unsigned char *data) { _pageData = data; }
const unsigned char * getPageData() const { return _pageData; }
Texture2D *getPageTexture();
void preparePageTexture(bool releaseRAWData = true);
private:
protected:
bool generatePageTexture(bool releasePageData = false);
int _pageNum;
int _width;
int _height;
unsigned char * _pageData;
Texture2D * _pageTexture;
std::vector<TextLineDef *> _lines;
int _pageNum;
int _width;
int _height;
unsigned char * _pageData;
Texture2D* _pageTexture;
std::vector<TextLineDef*> _lines;
};
/** @brief CCTextFontPages collection of pages (TextPageDef)
@ -156,13 +162,12 @@ public:
*/
~TextFontPagesDef();
void addPage(TextPageDef *newPage) { _pages.push_back(newPage); }
int getNumPages() const { return static_cast<int>(_pages.size()); }
TextPageDef* getPageAt(int index) const { return _pages[index]; }
void addPage(TextPageDef *newPage) { _pages.push_back(newPage); }
int getNumPages() const { return static_cast<int>(_pages.size()); }
TextPageDef* getPageAt(int index) const { return _pages[index]; }
private:
std::vector<TextPageDef *> _pages;
protected:
std::vector<TextPageDef*> _pages;
};
@ -184,28 +189,27 @@ public:
bool initWithString(const char *text, int width, int height, Font* font, bool releaseRAWData = true);
TextFontPagesDef * getPages() const { return _fontPages; }
Font * getFont() const { return _font; }
private:
TextFontPagesDef* getPages() const { return _fontPages; }
Font* getFont() const { return _font; }
protected:
bool createImageDataFromPages(TextFontPagesDef *thePages, bool releaseRAWData = true);
bool addGlyphsToLine(TextLineDef *line, const char *lineText, bool textIsUTF16 = false);
bool generateTextGlyphs(const char * text);
int getNumGlyphsFittingInSize(std::map<unsigned short int, GlyphDef> &glyphDefs, unsigned short int *strUTF8, Font *font, Size *constrainSize, int &outNewSize);
int getNumGlyphsFittingInSize(std::unordered_map<unsigned short int, GlyphDef> &glyphDefs, unsigned short int *strUTF8, Font *font, Size *constrainSize, int &outNewSize);
bool createPageDefinitions(unsigned short int *inText, int imageWidth, int imageHeight, int lineHeight);
unsigned char * preparePageGlyphData(TextPageDef *thePage);
// glyph rendering
unsigned char * renderGlyphData(TextPageDef *thePage);
std::map<unsigned short int, GlyphDef> _textGlyphs;
TextFontPagesDef * _fontPages;
Font * _font;
std::unordered_map<unsigned short int, GlyphDef> _textGlyphs;
TextFontPagesDef* _fontPages;
Font* _font;
};
NS_CC_END
#endif
#endif // _CCTextImage_h_

View File

@ -624,10 +624,10 @@ void TextureAtlas::drawNumberOfQuads(ssize_t numberOfQuads, ssize_t start)
{
glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]);
// option 1: subdata
//glBufferSubData(GL_ARRAY_BUFFER, sizeof(_quads[0])*start, sizeof(_quads[0]) * n , &_quads[start] );
// glBufferSubData(GL_ARRAY_BUFFER, sizeof(_quads[0])*start, sizeof(_quads[0]) * n , &_quads[start] );
// option 2: data
// glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * (n-start), &quads_[start], GL_DYNAMIC_DRAW);
// glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * (n-start), &quads_[start], GL_DYNAMIC_DRAW);
// option 3: orphaning + glMapBuffer
glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * (numberOfQuads-start), nullptr, GL_DYNAMIC_DRAW);

View File

@ -97,7 +97,7 @@ void TextureCache::addImageAsync(const std::string &path, std::function<void(Tex
{
Texture2D *texture = nullptr;
std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path.c_str());
std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path);
auto it = _textures.find(fullpath);
if( it != _textures.end() )
@ -290,7 +290,7 @@ Texture2D * TextureCache::addImage(const std::string &path)
// MUTEX:
// Needed since addImageAsync calls this method from a different thread
std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path.c_str());
std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path);
if (fullpath.size() == 0)
{
return nullptr;
@ -307,7 +307,7 @@ Texture2D * TextureCache::addImage(const std::string &path)
image = new Image();
CC_BREAK_IF(nullptr == image);
bool bRet = image->initWithImageFile(fullpath.c_str());
bool bRet = image->initWithImageFile(fullpath);
CC_BREAK_IF(!bRet);
texture = new Texture2D();
@ -417,16 +417,30 @@ void TextureCache::removeTexture(Texture2D* texture)
void TextureCache::removeTextureForKey(const std::string &textureKeyName)
{
auto it = _textures.find(textureKeyName);
std::string key = textureKeyName;
auto it = _textures.find(key);
if( it == _textures.end() ) {
key = FileUtils::getInstance()->fullPathForFilename(textureKeyName);
it = _textures.find(key);
}
if( it != _textures.end() ) {
(it->second)->release();
_textures.erase(it);
}
}
Texture2D* TextureCache::getTextureForKey(const std::string &key) const
Texture2D* TextureCache::getTextureForKey(const std::string &textureKeyName) const
{
std::string key = textureKeyName;
auto it = _textures.find(key);
if( it == _textures.end() ) {
key = FileUtils::getInstance()->fullPathForFilename(textureKeyName);
it = _textures.find(key);
}
if( it != _textures.end() )
return it->second;
return nullptr;
@ -448,20 +462,28 @@ void TextureCache::waitForQuit()
if (_loadingThread) _loadingThread->join();
}
void TextureCache::dumpCachedTextureInfo() const
std::string TextureCache::getCachedTextureInfo() const
{
char buffer[16386];
char buftmp[4096];
memset(buffer,0,sizeof(buffer));
unsigned int count = 0;
unsigned int totalBytes = 0;
for( auto it = _textures.begin(); it != _textures.end(); ++it ) {
memset(buftmp,0,sizeof(buftmp));
Texture2D* tex = it->second;
unsigned int bpp = tex->getBitsPerPixelForFormat();
// Each texture takes up width * height * bytesPerPixel bytes.
auto bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8;
totalBytes += bytes;
count++;
log("cocos2d: \"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB",
snprintf(buftmp,sizeof(buftmp)-1,"\"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB\n",
it->first.c_str(),
(long)tex->retainCount(),
(long)tex->getName(),
@ -469,9 +491,13 @@ void TextureCache::dumpCachedTextureInfo() const
(long)tex->getPixelsHigh(),
(long)bpp,
(long)bytes / 1024);
strcat(buffer, buftmp);
}
log("cocos2d: TextureCache dumpDebugInfo: %ld textures, for %lu KB (%.2f MB)", (long)count, (long)totalBytes / 1024, totalBytes / (1024.0f*1024.0f));
snprintf(buftmp, sizeof(buftmp)-1, "TextureCache dumpDebugInfo: %ld textures, for %lu KB (%.2f MB)\n", (long)count, (long)totalBytes / 1024, totalBytes / (1024.0f*1024.0f));
strcat(buffer, buftmp);
return std::string(buffer);
}
#if CC_ENABLE_CACHE_TEXTURE_DATA

View File

@ -163,7 +163,7 @@ public:
*
* @since v1.0
*/
void dumpCachedTextureInfo() const;
std::string getCachedTextureInfo() const;
//wait for texture cahe to quit befor destroy instance
//called by director, please do not called outside

View File

@ -98,23 +98,23 @@ void TransitionPageTurn::draw()
if( _isInSceneOnTop ) {
_outSceneProxy->visit();
_enableOffsetCmd.init(0, _vertexZ);
_enableOffsetCmd.init(_globalZOrder);
_enableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onEnablePolygonOffset, this);
Director::getInstance()->getRenderer()->addCommand(&_enableOffsetCmd);
_inSceneProxy->visit();
_disableOffsetCmd.init(0, _vertexZ);
_disableOffsetCmd.init(_globalZOrder);
_disableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onDisablePolygonOffset, this);
Director::getInstance()->getRenderer()->addCommand(&_disableOffsetCmd);
} else {
_inSceneProxy->visit();
_enableOffsetCmd.init(0, _vertexZ);
_enableOffsetCmd.init(_globalZOrder);
_enableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onEnablePolygonOffset, this);
Director::getInstance()->getRenderer()->addCommand(&_enableOffsetCmd);
_outSceneProxy->visit();
_disableOffsetCmd.init(0, _vertexZ);
_disableOffsetCmd.init(_globalZOrder);
_disableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onDisablePolygonOffset, this);
Director::getInstance()->getRenderer()->addCommand(&_disableOffsetCmd);
}

View File

@ -71,6 +71,7 @@ set(COCOS2D_SRC
CCFontDefinition.cpp
CCFontFNT.cpp
CCFontFreeType.cpp
CCFontCharMap.cpp
CCLabel.cpp
CCLabelAtlas.cpp
CCLabelBMFont.cpp
@ -144,6 +145,7 @@ set(COCOS2D_SRC
renderer/CCGroupCommand.cpp
renderer/CCMaterialManager.cpp
renderer/CCQuadCommand.cpp
renderer/CCBatchCommand.cpp
renderer/CCRenderCommand.cpp
renderer/CCRenderer.cpp
renderer/CCRenderMaterial.cpp

View File

@ -73,7 +73,7 @@ void ccArrayEnsureExtraCapacity(ccArray *arr, ssize_t extra)
{
while (arr->max < arr->num + extra)
{
CCLOG("cocos2d: ccCArray: resizing ccArray capacity from [%d] to [%d].",
CCLOGINFO("cocos2d: ccCArray: resizing ccArray capacity from [%d] to [%d].",
static_cast<int>(arr->max),
static_cast<int>(arr->max*2));

View File

@ -44,7 +44,6 @@ namespace
static bool s_vertexAttribColor = false;
static bool s_vertexAttribTexCoords = false;
#if CC_ENABLE_GL_STATE_CACHE
#define kMaxActiveTexture 16
@ -55,6 +54,8 @@ namespace
static GLenum s_blendingDest = -1;
static int s_GLServerState = 0;
static GLuint s_VAO = 0;
static GLenum s_activeTexture = -1;
#endif // CC_ENABLE_GL_STATE_CACHE
}
@ -159,7 +160,7 @@ void bindTexture2DN(GLuint textureUnit, GLuint textureId)
if (s_currentBoundTexture[textureUnit] != textureId)
{
s_currentBoundTexture[textureUnit] = textureId;
glActiveTexture(GL_TEXTURE0 + textureUnit);
activeTexture(GL_TEXTURE0 + textureUnit);
glBindTexture(GL_TEXTURE_2D, textureId);
}
#else
@ -186,6 +187,18 @@ void deleteTextureN(GLuint textureUnit, GLuint textureId)
glDeleteTextures(1, &textureId);
}
void activeTexture(GLenum texture)
{
#if CC_ENABLE_GL_STATE_CACHE
if(s_activeTexture != texture) {
s_activeTexture = texture;
glActiveTexture(s_activeTexture);
}
#else
glActiveTexture(texture);
#endif
}
void bindVAO(GLuint vaoId)
{
if (Configuration::getInstance()->supportsShareableVAO())

View File

@ -129,6 +129,12 @@ void CC_DLL deleteTexture(GLuint textureId);
*/
void CC_DLL deleteTextureN(GLuint textureUnit, GLuint textureId);
/** Select active texture unit.
If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glActiveTexture() directly.
@since v3.0
*/
void CC_DLL activeTexture(GLenum texture);
/** If the vertex array is not already bound, it binds it.
If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindVertexArray() directly.
@since v2.0.0

View File

@ -38,7 +38,7 @@ varying vec2 v_texCoord; \n\
\n\
void main() \n\
{ \n\
gl_Position = CC_PMatrix * a_position; \n\
gl_Position = CC_PMatrix * a_position; \n\
v_fragmentColor = a_color; \n\
v_texCoord = a_texCoord; \n\
} \n\

View File

@ -279,7 +279,7 @@ cc_utf8_get_char (const char * p)
unsigned short* cc_utf8_to_utf16(const char* str_old, int length/* = -1 */, int* rUtf16Size/* = nullptr */)
{
unsigned short len = cc_utf8_strlen(str_old, length);
long len = cc_utf8_strlen(str_old, length);
if (rUtf16Size != nullptr) {
*rUtf16Size = len;
}

View File

@ -25,7 +25,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "cocos2d.h"
#include "CCPlatformMacros.h"
NS_CC_BEGIN

View File

@ -248,6 +248,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClCompile Include="CCFontAtlas.cpp" />
<ClCompile Include="CCFontAtlasCache.cpp" />
<ClCompile Include="CCFontAtlasFactory.cpp" />
<ClCompile Include="CCFontCharMap.cpp" />
<ClCompile Include="CCFontDefinition.cpp" />
<ClCompile Include="CCFontFNT.cpp" />
<ClCompile Include="CCFontFreeType.cpp" />
@ -317,6 +318,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClCompile Include="platform\win32\CCFileUtilsWin32.cpp" />
<ClCompile Include="platform\win32\CCImage.cpp" />
<ClCompile Include="platform\win32\CCStdC.cpp" />
<ClCompile Include="renderer\CCBatchCommand.cpp" />
<ClCompile Include="renderer\CCCustomCommand.cpp" />
<ClCompile Include="renderer\CCFrustum.cpp" />
<ClCompile Include="renderer\CCGroupCommand.cpp" />
@ -428,6 +430,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClInclude Include="CCFontAtlas.h" />
<ClInclude Include="CCFontAtlasCache.h" />
<ClInclude Include="CCFontAtlasFactory.h" />
<ClInclude Include="CCFontCharMap.h" />
<ClInclude Include="CCFontDefinition.h" />
<ClInclude Include="CCFontFNT.h" />
<ClInclude Include="CCFontFreeType.h" />
@ -521,6 +524,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClInclude Include="platform\win32\CCGL.h" />
<ClInclude Include="platform\win32\CCPlatformDefine.h" />
<ClInclude Include="platform\win32\CCStdC.h" />
<ClInclude Include="renderer\CCBatchCommand.h" />
<ClInclude Include="renderer\CCCustomCommand.h" />
<ClInclude Include="renderer\CCFrustum.h" />
<ClInclude Include="renderer\CCGroupCommand.h" />

View File

@ -598,6 +598,12 @@
<ClCompile Include="renderer\CCRenderMaterial.cpp">
<Filter>renderer</Filter>
</ClCompile>
<ClCompile Include="renderer\CCBatchCommand.cpp">
<Filter>renderer</Filter>
</ClCompile>
<ClCompile Include="CCFontCharMap.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\physics\CCPhysicsBody.h">
@ -1207,5 +1213,11 @@
<ClInclude Include="renderer\CCRenderMaterial.h">
<Filter>renderer</Filter>
</ClInclude>
<ClInclude Include="renderer\CCBatchCommand.h">
<Filter>renderer</Filter>
</ClInclude>
<ClInclude Include="CCFontCharMap.h">
<Filter>label_nodes</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -547,6 +547,8 @@ static Data getData(const std::string& filename, bool forString)
std::string FileUtils::getStringFromFile(const std::string& filename)
{
Data data = getData(filename, true);
if (data.isNull())
return "";
std::string ret((const char*)data.getBytes());
return ret;
}

View File

@ -327,6 +327,9 @@ public:
*/
virtual ValueVector getValueVectorFromFile(const std::string& filename);
/** Returns the full path cache */
const std::unordered_map<std::string, std::string>& getFullPathCache() const { return _fullPathCache; }
protected:
/**
* The default constructor.

View File

@ -89,38 +89,43 @@ public class Cocos2dxHelper {
jobs.add(r);
}
private static boolean sInited = false;
public static void init(final Activity activity) {
final ApplicationInfo applicationInfo = activity.getApplicationInfo();
if (!sInited) {
final ApplicationInfo applicationInfo = activity.getApplicationInfo();
initListener();
initListener();
try {
// Get the lib_name from AndroidManifest.xml metadata
ActivityInfo ai =
activity.getPackageManager().getActivityInfo(activity.getIntent().getComponent(), PackageManager.GET_META_DATA);
if (null != ai.metaData) {
String lib_name = ai.metaData.getString(META_DATA_LIB_NAME);
if (null != lib_name) {
System.loadLibrary(lib_name);
} else {
System.loadLibrary(DEFAULT_LIB_NAME);
try {
// Get the lib_name from AndroidManifest.xml metadata
ActivityInfo ai =
activity.getPackageManager().getActivityInfo(activity.getIntent().getComponent(), PackageManager.GET_META_DATA);
if (null != ai.metaData) {
String lib_name = ai.metaData.getString(META_DATA_LIB_NAME);
if (null != lib_name) {
System.loadLibrary(lib_name);
} else {
System.loadLibrary(DEFAULT_LIB_NAME);
}
}
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException("Error getting activity info", e);
}
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException("Error getting activity info", e);
}
Cocos2dxHelper.sPackageName = applicationInfo.packageName;
Cocos2dxHelper.sFileDirectory = activity.getFilesDir().getAbsolutePath();
//Cocos2dxHelper.nativeSetApkPath(applicationInfo.sourceDir);
Cocos2dxHelper.sPackageName = applicationInfo.packageName;
Cocos2dxHelper.sFileDirectory = activity.getFilesDir().getAbsolutePath();
//Cocos2dxHelper.nativeSetApkPath(applicationInfo.sourceDir);
Cocos2dxHelper.sCocos2dMusic = new Cocos2dxMusic(activity);
Cocos2dxHelper.sCocos2dSound = new Cocos2dxSound(activity);
Cocos2dxHelper.sAssetManager = activity.getAssets();
Cocos2dxHelper.sCocos2dMusic = new Cocos2dxMusic(activity);
Cocos2dxHelper.sCocos2dSound = new Cocos2dxSound(activity);
Cocos2dxHelper.sAssetManager = activity.getAssets();
//Cocos2dxHelper.nativeSetAssetManager(sAssetManager);
Cocos2dxBitmap.setContext(activity);
sActivity = activity;
//Cocos2dxHelper.nativeSetAssetManager(sAssetManager);
Cocos2dxBitmap.setContext(activity);
sActivity = activity;
sInited = true;
}
}
public static void initListener() {

View File

@ -459,7 +459,7 @@ bool Image::initWithString(
{
bool bRet = false;
do
{
{
CC_BREAK_IF(! pText);
BitmapDC &dc = sharedBitmapDC();

View File

@ -0,0 +1,69 @@
/****************************************************************************
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "renderer/CCBatchCommand.h"
#include "ccGLStateCache.h"
#include "CCTextureAtlas.h"
NS_CC_BEGIN
BatchCommand::BatchCommand()
: _textureID(0)
, _blendType(BlendFunc::DISABLE)
, _textureAtlas(nullptr)
{
_type = RenderCommand::Type::BATCH_COMMAND;
_shader = nullptr;
}
void BatchCommand::init(float globalOrder, GLuint textureID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform)
{
_globalOrder = globalOrder;
_textureID = textureID;
_blendType = blendType;
_shader = shader;
_textureAtlas = textureAtlas;
_mv = modelViewTransform;
}
BatchCommand::~BatchCommand()
{
}
void BatchCommand::execute()
{
// Set material
_shader->use();
_shader->setUniformsForBuiltins(_mv);
GL::bindTexture2D(_textureID);
GL::blendFunc(_blendType.src, _blendType.dst);
// Draw
_textureAtlas->drawQuads();
}
NS_CC_END

View File

@ -0,0 +1,68 @@
/****************************************************************************
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef _CC_BATCHCOMMAND_H_
#define _CC_BATCHCOMMAND_H_
#include "CCRenderCommand.h"
#include "CCGLProgram.h"
#include "CCRenderCommandPool.h"
#include "kazmath/kazmath.h"
NS_CC_BEGIN
class TextureAtlas;
#define CC_NO_TEXTURE 0
class BatchCommand : public RenderCommand
{
public:
BatchCommand();
~BatchCommand();
void init(float depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform);
void execute();
protected:
int32_t _materialID;
//Maternal
GLuint _textureID;
GLProgram* _shader;
// GLuint _shaderID;
BlendFunc _blendType;
TextureAtlas *_textureAtlas;
// ModelView transform
kmMat4 _mv;
};
NS_CC_END
#endif //_CC_BATCHCOMMAND_H_

View File

@ -22,23 +22,19 @@
THE SOFTWARE.
****************************************************************************/
#include "CCCustomCommand.h"
#include "renderer/CCCustomCommand.h"
NS_CC_BEGIN
CustomCommand::CustomCommand()
:RenderCommand()
, func(nullptr)
, _viewport(0)
, _depth(0)
: func(nullptr)
{
_type = RenderCommand::Type::CUSTOM_COMMAND;
}
void CustomCommand::init(int viewport, int32_t depth)
void CustomCommand::init(float globalOrder)
{
_viewport = viewport;
_depth = depth;
_globalOrder = globalOrder;
}
CustomCommand::~CustomCommand()
@ -46,17 +42,6 @@ CustomCommand::~CustomCommand()
}
int64_t CustomCommand::generateID()
{
_id = 0;
_id = (int64_t)_viewport << 61
| (int64_t)1 << 60 // translucent
| (int64_t)_depth << 36;
return _id;
}
void CustomCommand::execute()
{
if(func)

View File

@ -39,14 +39,7 @@ public:
public:
void init(int viewport, int32_t depth);
// +----------+----------+-----+-----------------------------------+
// | | | | | |
// | ViewPort | Transluc | | Depth | |
// | 3 bits | 1 bit | | 24 bits | |
// +----------+----------+-----+----------------+------------------+
virtual int64_t generateID();
void init(float depth);
void execute();
@ -54,8 +47,6 @@ public:
std::function<void()> func;
protected:
int _viewport;
int32_t _depth;
};
NS_CC_END

View File

@ -22,7 +22,7 @@
THE SOFTWARE.
****************************************************************************/
#include "CCFrustum.h"
#include "renderer/CCFrustum.h"
#include "CCConsole.h"
#include <stdlib.h>

View File

@ -23,8 +23,8 @@
****************************************************************************/
#include "CCGroupCommand.h"
#include "CCRenderer.h"
#include "renderer/CCGroupCommand.h"
#include "renderer/CCRenderer.h"
#include "CCDirector.h"
NS_CC_BEGIN
@ -86,18 +86,14 @@ void GroupCommandManager::releaseGroupID(int groupID)
}
GroupCommand::GroupCommand()
:RenderCommand()
, _viewport(0)
, _depth(0)
{
_type = RenderCommand::Type::GROUP_COMMAND;
_renderQueueID = GroupCommandManager::getInstance()->getGroupID();
}
void GroupCommand::init(int viewport, int32_t depth)
void GroupCommand::init(float globalOrder)
{
_viewport = viewport;
_depth = depth;
_globalOrder = globalOrder;
GroupCommandManager::getInstance()->releaseGroupID(_renderQueueID);
_renderQueueID = GroupCommandManager::getInstance()->getGroupID();
}
@ -107,15 +103,4 @@ GroupCommand::~GroupCommand()
GroupCommandManager::getInstance()->releaseGroupID(_renderQueueID);
}
int64_t GroupCommand::generateID()
{
_id = 0;
_id = (int64_t)_viewport << 61
| (int64_t)1 << 60 // translucent
| (int64_t)_depth << 36;
return _id;
}
NS_CC_END

View File

@ -56,23 +56,11 @@ public:
GroupCommand();
~GroupCommand();
public:
void init(float depth);
void init(int viewport, int32_t depth);
// +----------+----------+-----+-----------------------------------+
// | | | | | |
// | ViewPort | Transluc | | Depth | |
// | 3 bits | 1 bit | | 24 bits | |
// +----------+----------+-----+----------------+------------------+
virtual int64_t generateID() override;
inline bool isTranslucent() {return true;}
inline int getRenderQueueID() {return _renderQueueID;}
inline int getRenderQueueID() const {return _renderQueueID;}
protected:
int _viewport;
int32_t _depth;
int _renderQueueID;
};

View File

@ -29,88 +29,36 @@
NS_CC_BEGIN
QuadCommand::QuadCommand()
:RenderCommand()
,_viewport(0)
,_depth(0)
,_textureID(0)
:_textureID(0)
,_blendType(BlendFunc::DISABLE)
,_quadCount(0)
,_capacity(0)
,_quadsCount(0)
{
_type = RenderCommand::Type::QUAD_COMMAND;
_shader = nullptr;
_quad = nullptr;
_quads = nullptr;
}
void QuadCommand::init(int viewport, int32_t depth, GLuint textureID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quad, ssize_t quadCount, const kmMat4 &mv)
void QuadCommand::init(float globalOrder, GLuint textureID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quad, ssize_t quadCount, const kmMat4 &mv)
{
_viewport = viewport;
_depth = depth;
_globalOrder = globalOrder;
_textureID = textureID;
_blendType = blendType;
_quadCount = quadCount;
_shader = shader;
if(quadCount > _capacity ) {
//TODO find a better way to manage quads, current way will result in memory be wasted
// _quad = (V3F_C4B_T2F_Quad*)malloc(sizeof(V3F_C4B_T2F_Quad) * quadCount);
_quad = (V3F_C4B_T2F_Quad*) realloc(_quad, sizeof(*quad) * quadCount );
_capacity = quadCount;
}
_quadsCount = quadCount;
_quads = quad;
_quadCount = quadCount;
memcpy(_quad, quad, sizeof(V3F_C4B_T2F_Quad) * quadCount);
_mv = mv;
for(int i=0; i<quadCount; ++i) {
V3F_C4B_T2F_Quad *q = &_quad[i];
kmVec3 vec1, out1;
vec1.x = q->bl.vertices.x;
vec1.y = q->bl.vertices.y;
vec1.z = q->bl.vertices.z;
kmVec3Transform(&out1, &vec1, &mv);
q->bl.vertices.x = out1.x;
q->bl.vertices.y = out1.y;
q->bl.vertices.z = out1.z;
kmVec3 vec2, out2;
vec2.x = q->br.vertices.x;
vec2.y = q->br.vertices.y;
vec2.z = q->br.vertices.z;
kmVec3Transform(&out2, &vec2, &mv);
q->br.vertices.x = out2.x;
q->br.vertices.y = out2.y;
q->br.vertices.z = out2.z;
kmVec3 vec3, out3;
vec3.x = q->tr.vertices.x;
vec3.y = q->tr.vertices.y;
vec3.z = q->tr.vertices.z;
kmVec3Transform(&out3, &vec3, &mv);
q->tr.vertices.x = out3.x;
q->tr.vertices.y = out3.y;
q->tr.vertices.z = out3.z;
kmVec3 vec4, out4;
vec4.x = q->tl.vertices.x;
vec4.y = q->tl.vertices.y;
vec4.z = q->tl.vertices.z;
kmVec3Transform(&out4, &vec4, &mv);
q->tl.vertices.x = out4.x;
q->tl.vertices.y = out4.y;
q->tl.vertices.z = out4.z;
}
generateMaterialID();
}
QuadCommand::~QuadCommand()
{
free(_quad);
}
int64_t QuadCommand::generateID()
void QuadCommand::generateMaterialID()
{
_id = 0;
//Generate Material ID
//TODO fix shader ID generation
CCASSERT(_shader->getProgram() < pow(2,10), "ShaderID is greater than 2^10");
@ -148,19 +96,12 @@ int64_t QuadCommand::generateID()
// | Shader ID (10 bits) | Blend ID (4 bits) | Texture ID (18 bits) |
// +---------------------+-------------------+----------------------+
_materialID = (int32_t)_shader->getProgram() << 22
| (int32_t)blendID << 18
| (int32_t)_textureID << 0;
//Generate RenderCommandID
_id = (int64_t)_viewport << 61
| (int64_t)1 << 60 //translucent
| (int64_t)_depth << 36;
return _id;
_materialID = (uint32_t)_shader->getProgram() << 22
| (uint32_t)blendID << 18
| (uint32_t)_textureID << 0;
}
void QuadCommand::useMaterial()
void QuadCommand::useMaterial() const
{
_shader->use();

View File

@ -41,41 +41,31 @@ public:
QuadCommand();
~QuadCommand();
void init(int viewport, int32_t depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quad, ssize_t quadCount,
void init(float depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quads, ssize_t quadCount,
const kmMat4& mv);
// +----------+----------+-----+-----------------------------------+
// | | | | | |
// | ViewPort | Transluc | | Depth | Material ID |
// | 3 bits | 1 bit | | 24 bits | 24 bit2 |
// +----------+----------+-----+----------------+------------------+
virtual int64_t generateID();
void useMaterial();
void useMaterial() const;
//TODO use material to decide if it is translucent
inline bool isTranslucent() const { return true; }
inline int32_t getMaterialID() const { return _materialID; }
void generateMaterialID();
inline uint32_t getMaterialID() const { return _materialID; }
inline GLuint getTextureID() const { return _textureID; }
inline V3F_C4B_T2F_Quad* getQuad() const { return _quad; }
inline V3F_C4B_T2F_Quad* getQuads() const { return _quads; }
inline ssize_t getQuadCount() const { return _quadCount; }
inline ssize_t getQuadCount() const { return _quadsCount; }
inline GLProgram* getShader() const { return _shader; }
inline BlendFunc getBlendType() const { return _blendType; }
inline const kmMat4& getModelView() const { return _mv; }
protected:
int32_t _materialID;
//Key Data
int _viewport; /// Which view port it belongs to
//TODO use material to determine if it's translucent
int32_t _depth;
uint32_t _materialID;
//Maternal
GLuint _textureID;
@ -85,9 +75,10 @@ protected:
BlendFunc _blendType;
V3F_C4B_T2F_Quad* _quad;
ssize_t _quadCount;
ssize_t _capacity;
V3F_C4B_T2F_Quad* _quads;
ssize_t _quadsCount;
kmMat4 _mv;
};
NS_CC_END

View File

@ -28,9 +28,9 @@
NS_CC_BEGIN
RenderCommand::RenderCommand()
: _type(RenderCommand::Type::UNKNOWN_COMMAND)
, _globalOrder(0)
{
_id = 0;
_type = RenderCommand::Type::UNKNOWN_COMMAND;
}
RenderCommand::~RenderCommand()
@ -57,9 +57,7 @@ void printBits(ssize_t const size, void const * const ptr)
void RenderCommand::printID()
{
printf("CommandID: ");
printBits(sizeof(_id), &_id);
printf("\n");
printf("Command Depth: %f\n", _globalOrder);
}
NS_CC_END

View File

@ -33,25 +33,27 @@
NS_CC_BEGIN
//TODO make RenderCommand inherent from Object
/** Base class of the RenderCommand hierarchy.
The Renderer knows how to render RenderCommands.
*/
class RenderCommand
{
public:
enum class Type
{
UNKNOWN_COMMAND,
QUAD_COMMAND,
CUSTOM_COMMAND,
BATCH_COMMAND,
GROUP_COMMAND,
UNKNOWN_COMMAND,
};
virtual int64_t generateID() = 0;
/** Get Render Command Id */
virtual inline int64_t getID() { return _id; }
inline float getGlobalOrder() const { return _globalOrder; }
virtual inline Type getType() { return _type; }
/** Returns the Command type */
inline Type getType() const { return _type; }
protected:
RenderCommand();
@ -59,9 +61,11 @@ protected:
void printID();
//Generated IDs
int64_t _id; /// used for sorting render commands
// Type used in order to avoid dynamic cast, faster
Type _type;
// commands are sort by depth
float _globalOrder;
};
NS_CC_END

View File

@ -22,23 +22,80 @@
THE SOFTWARE.
****************************************************************************/
#include "CCRenderer.h"
#include "renderer/CCRenderer.h"
#include "renderer/CCQuadCommand.h"
#include "renderer/CCBatchCommand.h"
#include "renderer/CCCustomCommand.h"
#include "renderer/CCGroupCommand.h"
#include "CCShaderCache.h"
#include "ccGLStateCache.h"
#include "CCCustomCommand.h"
#include "renderer/CCQuadCommand.h"
#include "CCGroupCommand.h"
#include "CCConfiguration.h"
#include "CCDirector.h"
#include "CCEventDispatcher.h"
#include "CCEventListenerCustom.h"
#include "CCEventType.h"
#include <algorithm> // for std::stable_sort
#include <algorithm>
NS_CC_BEGIN
using namespace std;
bool compareRenderCommand(RenderCommand* a, RenderCommand* b)
{
return a->getGlobalOrder() < b->getGlobalOrder();
}
void RenderQueue::push_back(RenderCommand* command)
{
float z = command->getGlobalOrder();
if(z < 0)
_queueNegZ.push_back(command);
else if(z > 0)
_queuePosZ.push_back(command);
else
_queue0.push_back(command);
}
ssize_t RenderQueue::size() const
{
return _queueNegZ.size() + _queue0.size() + _queuePosZ.size();
}
void RenderQueue::sort()
{
// Don't sort _queue0, it already comes sorted
std::sort(std::begin(_queueNegZ), std::end(_queueNegZ), compareRenderCommand);
std::sort(std::begin(_queuePosZ), std::end(_queuePosZ), compareRenderCommand);
}
RenderCommand* RenderQueue::operator[](ssize_t index) const
{
if(index < _queueNegZ.size())
return _queueNegZ[index];
index -= _queueNegZ.size();
if(index < _queue0.size())
return _queue0[index];
index -= _queue0.size();
if(index < _queuePosZ.size())
return _queuePosZ[index];
CCASSERT(false, "invalid index");
return nullptr;
}
void RenderQueue::clear()
{
_queueNegZ.clear();
_queue0.clear();
_queuePosZ.clear();
}
//
//
//
#define DEFAULT_RENDER_QUEUE 0
Renderer::Renderer()
@ -176,13 +233,14 @@ void Renderer::mapBuffers()
void Renderer::addCommand(RenderCommand* command)
{
command->generateID();
_renderGroups[_commandGroupStack.top()].push_back(command);
int renderQueue =_commandGroupStack.top();
addCommand(command, renderQueue);
}
void Renderer::addCommand(RenderCommand* command, int renderQueue)
{
command->generateID();
CCASSERT(renderQueue >=0, "Invalid render queue");
CCASSERT(command->getType() != RenderCommand::Type::UNKNOWN_COMMAND, "Invalid Command Type");
_renderGroups[renderQueue].push_back(command);
}
@ -203,11 +261,6 @@ int Renderer::createRenderQueue()
return (int)_renderGroups.size() - 1;
}
bool compareRenderCommand(RenderCommand* a, RenderCommand* b)
{
return a->getID() < b->getID();
}
void Renderer::render()
{
//Uncomment this once everything is rendered by new renderer
@ -219,9 +272,9 @@ void Renderer::render()
{
//Process render commands
//1. Sort render commands based on ID
for (auto it = _renderGroups.begin(); it != _renderGroups.end(); ++it)
for (auto &renderqueue : _renderGroups)
{
std::stable_sort((*it).begin(), (*it).end(), compareRenderCommand);
renderqueue.sort();
}
while(!_renderStack.empty())
@ -242,31 +295,41 @@ void Renderer::render()
if(commandType == RenderCommand::Type::QUAD_COMMAND)
{
QuadCommand* cmd = static_cast<QuadCommand*>(command);
auto cmd = static_cast<QuadCommand*>(command);
ssize_t cmdQuadCount = cmd->getQuadCount();
//Batch quads
if(_numQuads + cmdQuadCount > VBO_SIZE)
{
CCASSERT(cmdQuadCount < VBO_SIZE, "VBO is not big enough for quad data, please break the quad data down or use customized render command");
CCASSERT(cmdQuadCount>=0 && cmdQuadCount<VBO_SIZE, "VBO is not big enough for quad data, please break the quad data down or use customized render command");
//Draw batched quads if VBO is full
_lastCommand --;
drawBatchedQuads();
_lastCommand ++;
}
memcpy(_quads + _numQuads, cmd->getQuad(), sizeof(V3F_C4B_T2F_Quad) * cmdQuadCount);
memcpy(_quads + _numQuads, cmd->getQuads(), sizeof(V3F_C4B_T2F_Quad) * cmdQuadCount);
convertToWorldCoordiantes(_quads + _numQuads, cmdQuadCount, cmd->getModelView());
_numQuads += cmdQuadCount;
}
else if(commandType == RenderCommand::Type::CUSTOM_COMMAND)
{
flush();
CustomCommand* cmd = static_cast<CustomCommand*>(command);
auto cmd = static_cast<CustomCommand*>(command);
cmd->execute();
}
else if(commandType == RenderCommand::Type::BATCH_COMMAND)
{
flush();
auto cmd = static_cast<BatchCommand*>(command);
cmd->execute();
}
else if(commandType == RenderCommand::Type::GROUP_COMMAND)
{
flush();
GroupCommand* cmd = static_cast<GroupCommand*>(command);
auto cmd = static_cast<GroupCommand*>(command);
_renderStack.top().currentIndex = i + 1;
@ -279,6 +342,7 @@ void Renderer::render()
}
else
{
CCASSERT(true, "Invalid command");
flush();
}
}
@ -317,6 +381,29 @@ void Renderer::render()
_lastMaterialID = 0;
}
void Renderer::convertToWorldCoordiantes(V3F_C4B_T2F_Quad* quads, ssize_t quantity, const kmMat4& modelView)
{
// kmMat4 matrixP, mvp;
// kmGLGetMatrix(KM_GL_PROJECTION, &matrixP);
// kmMat4Multiply(&mvp, &matrixP, &modelView);
for(ssize_t i=0; i<quantity; ++i) {
V3F_C4B_T2F_Quad *q = &quads[i];
kmVec3 *vec1 = (kmVec3*)&q->bl.vertices;
kmVec3Transform(vec1, vec1, &modelView);
kmVec3 *vec2 = (kmVec3*)&q->br.vertices;
kmVec3Transform(vec2, vec2, &modelView);
kmVec3 *vec3 = (kmVec3*)&q->tr.vertices;
kmVec3Transform(vec3, vec3, &modelView);
kmVec3 *vec4 = (kmVec3*)&q->tl.vertices;
kmVec3Transform(vec4, vec4, &modelView);
}
}
void Renderer::drawBatchedQuads()
{
//TODO we can improve the draw performance by insert material switching command before hand.
@ -336,6 +423,13 @@ void Renderer::drawBatchedQuads()
//Set VBO data
glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]);
// option 1: subdata
// glBufferSubData(GL_ARRAY_BUFFER, sizeof(_quads[0])*start, sizeof(_quads[0]) * n , &_quads[start] );
// option 2: data
// glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * (n-start), &quads_[start], GL_DYNAMIC_DRAW);
// option 3: orphaning + glMapBuffer
glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * (_numQuads), nullptr, GL_DYNAMIC_DRAW);
void *buf = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
memcpy(buf, _quads, sizeof(_quads[0])* (_numQuads));
@ -351,7 +445,7 @@ void Renderer::drawBatchedQuads()
#define kQuadSize sizeof(_quads[0].bl)
glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(_quads[0]) * _numQuads , _quads);
glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * _numQuads , _quads, GL_DYNAMIC_DRAW);
GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX);
@ -368,12 +462,12 @@ void Renderer::drawBatchedQuads()
}
//Start drawing verties in batch
for(size_t i = _firstCommand; i <= _lastCommand; i++)
for(ssize_t i = _firstCommand; i <= _lastCommand; i++)
{
RenderCommand* command = _renderGroups[_renderStack.top().renderQueueID][i];
auto command = _renderGroups[_renderStack.top().renderQueueID][i];
if (command->getType() == RenderCommand::Type::QUAD_COMMAND)
{
QuadCommand* cmd = static_cast<QuadCommand*>(command);
auto cmd = static_cast<QuadCommand*>(command);
if(_lastMaterialID != cmd->getMaterialID())
{
//Draw quads
@ -414,7 +508,7 @@ void Renderer::drawBatchedQuads()
}
_firstCommand = _lastCommand;
_firstCommand = _lastCommand + 1;
_numQuads = 0;
}

View File

@ -37,12 +37,31 @@ NS_CC_BEGIN
class EventListenerCustom;
typedef std::vector<RenderCommand*> RenderQueue;
/** Class that knows how to sort the Commands.
Since the commands that have z==0 are "pushed back" in
the correct order, the only Commands that need to be sorted,
are the ones that have z <0 and z >0.
And that is what this class does.
*/
class RenderQueue {
public:
void push_back(RenderCommand* command);
ssize_t size() const;
void sort();
RenderCommand* operator[](ssize_t index) const;
void clear();
protected:
std::vector<RenderCommand*> _queueNegZ;
std::vector<RenderCommand*> _queue0;
std::vector<RenderCommand*> _queuePosZ;
};
struct RenderStackElement
{
int renderQueueID;
size_t currentIndex;
ssize_t currentIndex;
};
class Renderer
@ -75,18 +94,21 @@ protected:
void mapBuffers();
void drawBatchedQuads();
//Draw the previews queued quads and flush previous context
void flush();
void convertToWorldCoordiantes(V3F_C4B_T2F_Quad* quads, ssize_t quantity, const kmMat4& modelView);
std::stack<int> _commandGroupStack;
std::stack<RenderStackElement> _renderStack;
std::vector<RenderQueue> _renderGroups;
int _lastMaterialID;
uint32_t _lastMaterialID;
size_t _firstCommand;
size_t _lastCommand;
ssize_t _firstCommand;
ssize_t _lastCommand;
V3F_C4B_T2F_Quad _quads[VBO_SIZE];
GLushort _indices[6 * VBO_SIZE];

View File

@ -50,6 +50,9 @@
#include "CCScheduler.h"
#include "CCScene.h"
#include "CCPlatformConfig.h"
#include "platform/CCFileUtils.h"
#include "CCConfiguration.h"
#include "CCTextureCache.h"
NS_CC_BEGIN
@ -61,7 +64,7 @@ NS_CC_BEGIN
static ssize_t mydprintf(int sock, const char *format, ...)
{
va_list args;
char buf[1024];
char buf[16386];
va_start(args, format);
vsnprintf(buf, sizeof(buf), format, args);
@ -92,6 +95,33 @@ static void printSceneGraphBoot(int fd)
mydprintf(fd, "Total Nodes: %d\n", total);
}
static void printFileUtils(int fd)
{
FileUtils* fu = FileUtils::getInstance();
mydprintf(fd, "\nSearch Paths:\n");
auto list = fu->getSearchPaths();
for( const auto &item : list) {
mydprintf(fd, "%s\n", item.c_str());
}
mydprintf(fd, "\nResolution Order:\n");
list = fu->getSearchResolutionsOrder();
for( const auto &item : list) {
mydprintf(fd, "%s\n", item.c_str());
}
mydprintf(fd, "\nWriteble Path:\n");
mydprintf(fd, "%s\n", fu->getWritablePath().c_str());
mydprintf(fd, "\nFull Path Cache:\n");
auto cache = fu->getFullPathCache();
for( const auto &item : cache) {
mydprintf(fd, "%s -> %s\n", item.first.c_str(), item.second.c_str());
}
}
#if defined(__MINGW32__)
static const char* inet_ntop(int af, const void* src, char* dst, int cnt)
{
@ -114,24 +144,7 @@ static const char* inet_ntop(int af, const void* src, char* dst, int cnt)
// Free functions to log
//
// XXX: Deprecated
void CCLog(const char * format, ...)
{
va_list args;
va_start(args, format);
log(format, args);
va_end(args);
}
void log(const char * format, ...)
{
va_list args;
va_start(args, format);
log(format, args);
va_end(args);
}
void log(const char *format, va_list args)
static void _log(const char *format, va_list args)
{
char buf[MAX_LOG_LENGTH];
@ -159,6 +172,22 @@ void log(const char *format, va_list args)
Director::getInstance()->getConsole()->log(buf);
}
// XXX: Deprecated
void CCLog(const char * format, ...)
{
va_list args;
va_start(args, format);
_log(format, args);
va_end(args);
}
void log(const char * format, ...)
{
va_list args;
va_start(args, format);
_log(format, args);
va_end(args);
}
//
// Console code
@ -174,6 +203,7 @@ Console::Console()
{
// VS2012 doesn't support initializer list, so we create a new array and assign its elements to '_command'.
Command commands[] = {
{ "config", std::bind(&Console::commandConfig, this, std::placeholders::_1, std::placeholders::_2) },
{ "debug msg on", [&](int fd, const char* command) {
_sendDebugStrings = true;
} },
@ -181,6 +211,7 @@ Console::Console()
_sendDebugStrings = false;
} },
{ "exit", std::bind(&Console::commandExit, this, std::placeholders::_1, std::placeholders::_2) },
{ "fileutils dump", std::bind(&Console::commandFileUtilsDump, this, std::placeholders::_1, std::placeholders::_2) },
{ "fps on", [](int fd, const char* command) {
Director *dir = Director::getInstance();
Scheduler *sched = dir->getScheduler();
@ -193,6 +224,7 @@ Console::Console()
} },
{ "help", std::bind(&Console::commandHelp, this, std::placeholders::_1, std::placeholders::_2) },
{ "scene graph", std::bind(&Console::commandSceneGraph, this, std::placeholders::_1, std::placeholders::_2) },
{ "textures", std::bind(&Console::commandTextures, this, std::placeholders::_1, std::placeholders::_2) },
};
_maxCommands = sizeof(commands)/sizeof(commands[0]);
@ -340,6 +372,31 @@ void Console::commandSceneGraph(int fd, const char *command)
sched->performFunctionInCocosThread( std::bind(&printSceneGraphBoot, fd) );
}
void Console::commandFileUtilsDump(int fd, const char *command)
{
Scheduler *sched = Director::getInstance()->getScheduler();
sched->performFunctionInCocosThread( std::bind(&printFileUtils, fd) );
}
void Console::commandConfig(int fd, const char *command)
{
Scheduler *sched = Director::getInstance()->getScheduler();
sched->performFunctionInCocosThread( [&](){
mydprintf(fd, "%s", Configuration::getInstance()->getInfo().c_str());
}
);
}
void Console::commandTextures(int fd, const char *command)
{
Scheduler *sched = Director::getInstance()->getScheduler();
sched->performFunctionInCocosThread( [&](){
mydprintf(fd, "%s", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str());
}
);
}
bool Console::parseCommand(int fd)
{
auto r = readline(fd);

View File

@ -58,7 +58,6 @@ static const int MAX_LOG_LENGTH = 16*1024;
@brief Output Debug message.
*/
void CC_DLL log(const char * format, ...) CC_FORMAT_PRINTF(1, 2);
void CC_DLL log(const char * format, va_list args);
/** Console is helper class that lets the developer control the game from TCP connection.
Console will spawn a new thread that will listen to a specified TCP port.
@ -109,6 +108,9 @@ protected:
void commandHelp(int fd, const char *command);
void commandExit(int fd, const char *command);
void commandSceneGraph(int fd, const char *command);
void commandFileUtilsDump(int fd, const char *command);
void commandConfig(int fd, const char *command);
void commandTextures(int fd, const char *command);
// file descriptor: socket, console, etc.
int _listenfd;

View File

@ -25,10 +25,17 @@
#ifndef __CCMAP_H__
#define __CCMAP_H__
#define USE_STD_UNORDERED_MAP 1
#include "ccMacros.h"
#include "CCObject.h"
#include <vector>
#if USE_STD_UNORDERED_MAP
#include <unordered_map>
#else
#include <map>
#endif
NS_CC_BEGIN
@ -44,7 +51,11 @@ public:
// ------------------------------------------
// Iterators
// ------------------------------------------
#if USE_STD_UNORDERED_MAP
typedef std::unordered_map<K, V> RefMap;
#else
typedef std::map<K, V> RefMap;
#endif
typedef typename RefMap::iterator iterator;
typedef typename RefMap::const_iterator const_iterator;
@ -104,25 +115,39 @@ public:
/** Sets capacity of the map */
void reserve(ssize_t capacity)
{
#if USE_STD_UNORDERED_MAP
_data.reserve(capacity);
#endif
}
/** Returns the number of buckets in the Map container. */
ssize_t bucketCount() const
{
#if USE_STD_UNORDERED_MAP
return _data.bucket_count();
#else
return 0;
#endif
}
/** Returns the number of elements in bucket n. */
ssize_t bucketSize(ssize_t n) const
{
#if USE_STD_UNORDERED_MAP
return _data.bucket_size(n);
#else
return 0;
#endif
}
/** Returns the bucket number where the element with key k is located. */
ssize_t bucket(const K& k) const
{
#if USE_STD_UNORDERED_MAP
return _data.bucket(k);
#else
return 0;
#endif
}
/** The number of elements in the map. */
@ -147,6 +172,8 @@ public:
if (!_data.empty())
{
keys.reserve(_data.size());
for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter)
{
keys.push_back(iter->first);
@ -160,14 +187,21 @@ public:
{
std::vector<K> keys;
for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter)
if (!_data.empty())
{
if (iter->second == object)
keys.reserve(_data.size() / 10);
for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter)
{
keys.push_back(iter->first);
if (iter->second == object)
{
keys.push_back(iter->first);
}
}
}
keys.shrink_to_fit();
return keys;
}

View File

@ -1,7 +1,11 @@
#ifndef __CCB_CCBANIMATION_MANAGER_H__
#define __CCB_CCBANIMATION_MANAGER_H__
#include "cocos2d.h"
#include "CCMap.h"
#include "CCActionInterval.h"
#include "CCActionInstant.h"
#include "CCActionEase.h"
#include "extensions/ExtensionMacros.h"
#include "CCBSequence.h"
#include "CCBSequenceProperty.h"

View File

@ -1,7 +1,9 @@
#ifndef __CCB_KEYFRAME_H__
#define __CCB_KEYFRAME_H__
#include "cocos2d.h"
#include "CCObject.h"
#include "CCValue.h"
namespace cocosbuilder {

View File

@ -1,7 +1,6 @@
#ifndef _CCB_CCBMEMBERVARIABLEASSIGNER_H_
#define _CCB_CCBMEMBERVARIABLEASSIGNER_H_
#include "cocos2d.h"
namespace cocosbuilder {

View File

@ -1,7 +1,13 @@
#include "CCBReader.h"
#include <ctype.h>
#include <algorithm>
#include "CCDirector.h"
#include "platform/CCFileUtils.h"
#include "CCScene.h"
#include "CCTextureCache.h"
#include "CCSpriteFrameCache.h"
#include "CCBReader.h"
#include "CCNodeLoader.h"
#include "CCNodeLoaderLibrary.h"
#include "CCNodeLoaderListener.h"
@ -11,7 +17,7 @@
#include "CCBSequenceProperty.h"
#include "CCBKeyframe.h"
#include <ctype.h>
using namespace std;
using namespace cocos2d;

View File

@ -1,9 +1,12 @@
#ifndef _CCB_CCBREADER_H_
#define _CCB_CCBREADER_H_
#include "cocos2d.h"
#include <string>
#include <vector>
#include "CCNode.h"
#include "CCData.h"
#include "CCMap.h"
#include "CCBSequence.h"
#include "extensions/GUI/CCControlExtension/CCControl.h"

View File

@ -1,7 +1,6 @@
#ifndef _CCB_CCBSELECTORRESOLVER_H_
#define _CCB_CCBSELECTORRESOLVER_H_
#include "cocos2d.h"
#include "extensions//GUI/CCControlExtension/CCInvocation.h"

View File

@ -2,7 +2,8 @@
#define __CCB_CCSEQUENCE_H__
#include <string>
#include "cocos2d.h"
#include "CCObject.h"
#include "CCBSequenceProperty.h"
namespace cocosbuilder {

View File

@ -1,7 +1,8 @@
#ifndef __CCB_SEQUENCE_PROPERTY_H__
#define __CCB_SEQUENCE_PROPERTY_H__
#include "cocos2d.h"
#include "CCObject.h"
#include "CCVector.h"
#include "CCBKeyframe.h"
namespace cocosbuilder {

View File

@ -1,6 +1,9 @@
#ifndef _CCB_CCLABELBMFONTLOADER_H_
#define _CCB_CCLABELBMFONTLOADER_H_
#include "CCObject.h"
#include "CCLabelBMFont.h"
#include "CCNodeLoader.h"
namespace cocosbuilder {

View File

@ -1,6 +1,9 @@
#ifndef _CCB_CCLABELTTFLOADER_H_
#define _CCB_CCLABELTTFLOADER_H_
#include "CCObject.h"
#include "CCLabelTTF.h"
#include "CCNodeLoader.h"
namespace cocosbuilder {

View File

@ -1,6 +1,9 @@
#ifndef _CCB_CCMENUITEMLOADER_H_
#define _CCB_CCMENUITEMLOADER_H_
#include "CCObject.h"
#include "CCMenuItem.h"
#include "CCLayerLoader.h"
namespace cocosbuilder {

View File

@ -2,6 +2,8 @@
#define _CCB_CCMENULOADER_H_
#include "CCLayerLoader.h"
#include "CCObject.h"
#include "CCMenu.h"
namespace cocosbuilder {

View File

@ -1,7 +1,6 @@
#ifndef __CCB_CCNODE_RELATIVEPOSITIONING_H__
#define __CCB_CCNODE_RELATIVEPOSITIONING_H__
#include "cocos2d.h"
#include "CCBReader.h"
namespace cocosbuilder {

View File

@ -1,9 +1,12 @@
#include "cocos2d.h"
#include "CCNodeLoader.h"
#include "CCBSelectorResolver.h"
#include "CCBMemberVariableAssigner.h"
#include "CCBAnimationManager.h"
#include "CCNode+CCBRelativePositioning.h"
using namespace std;
using namespace cocos2d;
using namespace cocos2d::extension;

View File

@ -2,7 +2,6 @@
#define _CCB_CCNODELOADER_H_
#include "extensions/GUI/CCControlExtension/CCInvocation.h"
#include "cocos2d.h"
#include "CCBReader.h"
#include "extensions/GUI/CCControlExtension/CCControl.h"

View File

@ -1,7 +1,6 @@
#ifndef _CCB_CCNODELOADERLIBRARY_H_
#define _CCB_CCNODELOADERLIBRARY_H_
#include "cocos2d.h"
#include "CCBReader.h"
namespace cocosbuilder {

View File

@ -1,7 +1,6 @@
#ifndef _CCB_CCNODELOADERLISTENER_H_
#define _CCB_CCNODELOADERLISTENER_H_
#include "cocos2d.h"
namespace cocosbuilder {

View File

@ -1,6 +1,9 @@
#ifndef _CCB_CCPARTICLESYSTEMQUADLOADER_H_
#define _CCB_CCPARTICLESYSTEMQUADLOADER_H_
#include "CCObject.h"
#include "CCParticleSystemQuad.h"
#include "CCNodeLoader.h"
namespace cocosbuilder {

View File

@ -25,7 +25,6 @@ THE SOFTWARE.
#ifndef __ActionEaseEx_H__
#define __ActionEaseEx_H__
#include "cocos2d.h"
#include "cocostudio/CocoStudio.h"
namespace cocostudio {

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