Merge pull request #2 from cocos2d/develop

update cc2dx/develop
This commit is contained in:
hbb 2014-02-08 19:08:36 +08:00
commit 2738fc4cc1
1783 changed files with 40242 additions and 50659 deletions

1
.gitignore vendored
View File

@ -60,7 +60,6 @@ build_*_vc10/
*.mode*v* *.mode*v*
*.pbxuser *.pbxuser
*.xcbkptlist *.xcbkptlist
*.xcscheme
*.xcworkspacedata *.xcworkspacedata
*.xcuserstate *.xcuserstate
*.xccheckout *.xccheckout

6
.gitmodules vendored
View File

@ -4,12 +4,12 @@
[submodule "cocos/scripting/auto-generated"] [submodule "cocos/scripting/auto-generated"]
path = cocos/scripting/auto-generated path = cocos/scripting/auto-generated
url = git://github.com/cocos2d-x/bindings-auto-generated.git url = git://github.com/cocos2d-x/bindings-auto-generated.git
[submodule "samples/Javascript/Shared"]
path = samples/Javascript/Shared
url = git://github.com/cocos2d/cocos2d-js-tests.git
[submodule "tools/cocos2d-console"] [submodule "tools/cocos2d-console"]
path = tools/cocos2d-console path = tools/cocos2d-console
url = git://github.com/cocos2d/cocos2d-console.git url = git://github.com/cocos2d/cocos2d-console.git
[submodule "plugin"] [submodule "plugin"]
path = plugin path = plugin
url = https://github.com/cocos2d-x/plugin-x.git url = https://github.com/cocos2d-x/plugin-x.git
[submodule "tests/test-javascript/tests"]
path = tests/test-javascript/tests
url = git://github.com/cocos2d/cocos2d-js-tests.git

16
AUTHORS
View File

@ -95,6 +95,7 @@ Developers:
Added Mingw-crt Support without breaking VS SDK Added Mingw-crt Support without breaking VS SDK
CMake support for windows. CMake support for windows.
Added support for x64 target of windows. Added support for x64 target of windows.
Added Dutch Language support.
mchinen mchinen
fix emulator issue for OpenGL ES 2.0 on Android fix emulator issue for OpenGL ES 2.0 on Android
@ -510,6 +511,8 @@ Developers:
Lee, Jae-Hong (pyrasis) Lee, Jae-Hong (pyrasis)
Maintainer of tizen port. Maintainer of tizen port.
localStorageGetItem crashes when column text is NULL.
fix image bug on Android
lumendes lumendes
Updating spine-runtime to EsotericSoftware/spine-runtimes@5f90386. Updating spine-runtime to EsotericSoftware/spine-runtimes@5f90386.
@ -718,6 +721,19 @@ Developers:
Pisces000221 Pisces000221
Corrected a few mistakes in the README file of project-creator. Corrected a few mistakes in the README file of project-creator.
Corrected a mistake in README.
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
pandamicro
Exposed SAXParser to JS, it is used for parsing XML in JS.
hanjukim
Fixed a bug that color and opacity settings were not applied when invoking Label::alignText.
Retired Core Developers: Retired Core Developers:
WenSheng Yang WenSheng Yang

View File

@ -1,17 +1,85 @@
cocos2d-x-3.0final ?.? ? cocos2d-x-3.0rc0 Feb.?? 2014
[All] [All]
[NEW] Console: added the 'textures', 'fileutils dump' and 'config' commands [NEW] Adds Dutch Language support.
[FIX] EGLView improvements: renamed to GLView, no longer a singleton, easier to customize
[FIX] Removes samples except testcpp|testjavascript|testlua. Moves sample games to `cocos2d/samples` repo.
cocos2d-x-3.0beta2 Jan.24 2014
[All]
[NEW] Full screen support for desktop platforms.
[NEW] Adds performance test for EventDispatcher.
[NEW] Adds performance test for Containers(Vector<>, Array, Map<K,V>, Dictionary).
[NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier. [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%
[FIX] event->stopPropagation can't work for EventListenerTouchAllAtOnce.
[FIX] Uses unified `desktop/CCEGLView.h/cpp` for desktop platforms (windows, mac, linux).
[FIX] Bindings-generator supports Windows again and remove dependency of LLVM since we only need binary(libclang.so/dll).
[FIX] Removes unused files for MAC platform after using glfw3 to create opengl context.
[FIX] Wrong arithmetic of child's position in ParallaxNode::addChild()
[FIX] CocoStudio: TestColliderDetector in ArmatureTest can't work.
[FIX] CocoStudio: The order of transform calculation in Skin::getNodeToWorldTransform() is incorrect.
[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: Memory leak in FontFreeType::createFontAtlas().
[FIX] Label: Crash when using unknown characters.
[FIX] Label: Missing line breaks and wrong alignment.
[FIX] Label: Corrupt looking characters and incorrect spacing between characters
[FIX] Label: Label:color and opacity settings are invalid afeter these these properties changed: 1)text content changed 2)align style changed 3)max line width limited
[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] Configuration: dumpInfo() -> getInfo()
[FIX] ControlSlider doesn't support to set selected thumb sprite. [FIX] ControlSlider doesn't support to set selected thumb sprite.
[FIX] ControlButton doesn't support to set scale ratio of touchdown state. [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] Particles: Crash was triggered if there is not `textureFileName`section in particle plist file.
[FIX] Tests: TestCpp works with CMake on Windows. [FIX] Renderer: Uses a float as key with only the depth. Viewport, opaque are not needed now
[FIX] Tests: Sprites Performance Test has 3 new tests [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: Sprites Performance Test has 4 new tests
[FIX] TextureCache: getTextureForKey and removeTextureForKey work as expected [FIX] TextureCache: getTextureForKey and removeTextureForKey work as expected
[FIX] TextureCache: dumpCachedTextureInfo() -> getCachedTextureInfo() [FIX] TextureCache: dumpCachedTextureInfo() -> getCachedTextureInfo()
[FIX] Websocket doesn't support send/receive data which larger than 4096 bytes. [FIX] Websocket doesn't support send/receive data which larger than 4096 bytes.
[FIX] Windows: There will be some compilation errors when using x64 target on Windows. [FIX] Object: Remove _retainCount
[FIX] ParallaxNode: Coordinate of Sprite may be wrong after being added into ParallaxNode
[FIX] Crash if there is not `textureFileName`section in particle plist file
[FIX] Websocket cannot send/receive more than 4096 bytes data
[FIX] TextureCache::addImageAsync can't load first image
[FIX] ControlSlider: Can not set "selected thumb sprite"
[FIX] ControlSlider: Can not set "scale ratio"
[FIX] Crash when loading tga format image
[FIX] Keyboard pressed events are being repeatedly fired before keyboard is released
[Android]
[FIX] Background music can't be resumed when back from foreground
[FIX] ANR (Application Not Responding) appears on android 2.3 when pressing hardware button.
[lua binding]
[NEW] Can bind classes that have the same class names but different namesapces
[FIX] Use EventDispatcher to update some test cases
[FIX] sp.SkeletonAnimation:registerScriptHandler should not override cc.Node:registerScriptHandler
[javascript binding]
[NEW] Bind SAXParser
[FIX] Pure JS class that wants to inherite from cc.Class will trigger an irrelevant log
[FIX] Mac and iOS Simulator should also use SpiderMonkey which was built in RELEASE mode
[FIX] Crash when running JSB projects on iOS device in DEBUG mode
[FIX] Crash when Firefox connects to JSB application on Mac platform.
[Desktop]
[NEW] Support fullscreen
[Linux]
[FIX] "Testing empty labels" in LabelTest crashes.
[Mac]
[FIX] Removes unused files after using glfw3 to create opengl context
[Win32]
[FIX] Compiling error when using x64 target
[FIX] Tests: TestCpp works with CMake
[FIX] Bindings-generator supports Windows again and remove dependency of LLVM since it only needs binary of libclang
cocos2d-x-3.0beta Jan.7 2014 cocos2d-x-3.0beta Jan.7 2014
[All] [All]
@ -758,7 +826,7 @@ cocos2d-2.0-x-2.0.2 @Aug.30 2012
Refactor #1399: adjust directory structure Refactor #1399: adjust directory structure
Refactor #1402: improve static creator function names to avoid confusion Refactor #1402: improve static creator function names to avoid confusion
Refactor #1413: improve CCTouch::getLocation(), getDelta() which returns OpenGL coordinates directly Refactor #1413: improve CCTouch::getLocation(), getDelta() which returns OpenGL coordinates directly
Refactor #1437: change the return type of CCApplication::sharedApplication() and CCEGLView::sharedOpenGLView() to a pointer Refactor #1437: change the return type of CCApplication::sharedApplication() and CCGLView::sharedOpenGLView() to a pointer
Refactor #1441: put hd and iPad resources of TestCpp into separate directories Refactor #1441: put hd and iPad resources of TestCpp into separate directories
Refactor #1442: use CREATE_FUNC to replace LAYER_CREATE_FUNC and SCENE_CREATE_FUNC Refactor #1442: use CREATE_FUNC to replace LAYER_CREATE_FUNC and SCENE_CREATE_FUNC
[iOS] [iOS]
@ -792,7 +860,7 @@ cocos2d-2.0-rc2-x-2.0.1 @Jun.28 2012
Bug #1293: fix a bug that CCDirector::getFrames() returns wrong value Bug #1293: fix a bug that CCDirector::getFrames() returns wrong value
Bug #1296: fix a logical error in CCTMXTiledMap::tilesetForLayer() Bug #1296: fix a logical error in CCTMXTiledMap::tilesetForLayer()
Bug #1300: fix a typo of CC_ENABLE_CACHE_TEXTTURE_DATA Bug #1300: fix a typo of CC_ENABLE_CACHE_TEXTTURE_DATA
Bug #1301: apply scissor with points in CCEGLView::sharedOpenGLView().setScissorInPoints() Bug #1301: apply scissor with points in CCGLView::sharedOpenGLView().setScissorInPoints()
Bug #1302: change the parameter type of CCMenu::setHandlerPriority to signed int Bug #1302: change the parameter type of CCMenu::setHandlerPriority to signed int
Bug #1308: fix a logical bug in CCTouchDispatcher Bug #1308: fix a logical bug in CCTouchDispatcher
Bug #1326: fix a bug that the compilation of HelloLua and testjs project was broken after synchronizing to rc2 Bug #1326: fix a bug that the compilation of HelloLua and testjs project was broken after synchronizing to rc2

View File

@ -45,9 +45,7 @@ option(BUILD_EDITOR_SPINE "Build editor support for spine" ON)
option(BUILD_EDITOR_COCOSTUDIO "Build editor support for cocostudio" ON) option(BUILD_EDITOR_COCOSTUDIO "Build editor support for cocostudio" ON)
option(BUILD_EDITOR_COCOSBUILDER "Build editor support for cocosbuilder" ON) option(BUILD_EDITOR_COCOSBUILDER "Build editor support for cocosbuilder" ON)
option(BUILD_HelloCpp "Only build HelloCpp sample" ON)
option(BUILD_TestCpp "Only build TestCpp sample" ON) option(BUILD_TestCpp "Only build TestCpp sample" ON)
option(BUILD_HelloLua "Only build HelloLua sample" OFF)
option(BUILD_TestLua "Only build TestLua sample" OFF) option(BUILD_TestLua "Only build TestLua sample" OFF)
else()#temp else()#temp
@ -63,10 +61,7 @@ option(BUILD_EDITOR_SPINE "Build editor support for spine" ON)
option(BUILD_EDITOR_COCOSTUDIO "Build editor support for cocostudio" ON) option(BUILD_EDITOR_COCOSTUDIO "Build editor support for cocostudio" ON)
option(BUILD_EDITOR_COCOSBUILDER "Build editor support for cocosbuilder" ON) option(BUILD_EDITOR_COCOSBUILDER "Build editor support for cocosbuilder" ON)
option(BUILD_HelloCpp "Only build HelloCpp sample" ON)
option(BUILD_TestCpp "Only build TestCpp sample" ON) option(BUILD_TestCpp "Only build TestCpp sample" ON)
option(BUILD_HelloLua "Only build HelloLua sample" ON)
option(BUILD_TestLua "Only build TestLua sample" ON) option(BUILD_TestLua "Only build TestLua sample" ON)
endif()#temp endif()#temp
@ -155,6 +150,7 @@ include_directories(
${CMAKE_CURRENT_SOURCE_DIR}/external/unzip ${CMAKE_CURRENT_SOURCE_DIR}/external/unzip
${CMAKE_CURRENT_SOURCE_DIR}/external/edtaa3func ${CMAKE_CURRENT_SOURCE_DIR}/external/edtaa3func
${CMAKE_CURRENT_SOURCE_DIR}/external/chipmunk/include/chipmunk ${CMAKE_CURRENT_SOURCE_DIR}/external/chipmunk/include/chipmunk
${CMAKE_CURRENT_SOURCE_DIR}/cocos/2d/platform/desktop
${CMAKE_CURRENT_SOURCE_DIR}/cocos/2d/platform/${PLATFORM_FOLDER} ${CMAKE_CURRENT_SOURCE_DIR}/cocos/2d/platform/${PLATFORM_FOLDER}
${CMAKE_CURRENT_SOURCE_DIR}/external/jpeg/include/${PLATFORM_FOLDER} ${CMAKE_CURRENT_SOURCE_DIR}/external/jpeg/include/${PLATFORM_FOLDER}
${CMAKE_CURRENT_SOURCE_DIR}/external/png/include/${PLATFORM_FOLDER} ${CMAKE_CURRENT_SOURCE_DIR}/external/png/include/${PLATFORM_FOLDER}
@ -169,7 +165,7 @@ if(WIN32)
${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/gles/include/OGLES ${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/gles/include/OGLES
${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/icon/include ${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/icon/include
${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/zlib/include ${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/zlib/include
external/curl/include/${PLATFORM_FOLDER} external/curl/include/${PLATFORM_FOLDER}
) )
elseif(APPLE) elseif(APPLE)
include_directories( include_directories(
@ -177,8 +173,9 @@ elseif(APPLE)
) )
else() else()
include_directories( include_directories(
/usr/include
/usr/local/include/GLFW
${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/fmod/include/${ARCH_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/fmod/include/${ARCH_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/external/curl/include/${PLATFORM_FOLDER}/${ARCH_DIR}
) )
endif() endif()
@ -192,8 +189,8 @@ if(WIN32)
${CMAKE_CURRENT_SOURCE_DIR}/external/png/prebuilt/${PLATFORM_FOLDER} ${CMAKE_CURRENT_SOURCE_DIR}/external/png/prebuilt/${PLATFORM_FOLDER}
${CMAKE_CURRENT_SOURCE_DIR}/external/freetype2/prebuilt/${PLATFORM_FOLDER} ${CMAKE_CURRENT_SOURCE_DIR}/external/freetype2/prebuilt/${PLATFORM_FOLDER}
${CMAKE_CURRENT_SOURCE_DIR}/external/curl/prebuilt/${PLATFORM_FOLDER} ${CMAKE_CURRENT_SOURCE_DIR}/external/curl/prebuilt/${PLATFORM_FOLDER}
${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/icon/prebuilt ${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/icon/prebuilt
${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/zlib/prebuilt ${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/zlib/prebuilt
) )
endif() endif()
@ -208,7 +205,6 @@ else()
${CMAKE_CURRENT_SOURCE_DIR}/external/webp/prebuilt/${PLATFORM_FOLDER}/${ARCH_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/external/webp/prebuilt/${PLATFORM_FOLDER}/${ARCH_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/external/png/prebuilt/${PLATFORM_FOLDER}/${ARCH_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/external/png/prebuilt/${PLATFORM_FOLDER}/${ARCH_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/external/freetype2/prebuilt/${PLATFORM_FOLDER}/${ARCH_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/external/freetype2/prebuilt/${PLATFORM_FOLDER}/${ARCH_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/external/curl/prebuilt/${PLATFORM_FOLDER}/${ARCH_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/fmod/prebuilt/${ARCH_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/fmod/prebuilt/${ARCH_DIR}
) )
@ -283,20 +279,13 @@ add_subdirectory(external/lua/tolua)
add_subdirectory(cocos/scripting) add_subdirectory(cocos/scripting)
endif(BUILD_LIBS_LUA) endif(BUILD_LIBS_LUA)
# build samples # build tests
if(BUILD_HelloCpp)
add_subdirectory(samples/Cpp/HelloCpp)
endif(BUILD_HelloCpp)
if(BUILD_TestCpp) if(BUILD_TestCpp)
add_subdirectory(samples/Cpp/TestCpp) add_subdirectory(tests/test-cpp)
endif(BUILD_TestCpp) endif(BUILD_TestCpp)
if(BUILD_HelloLua)
add_subdirectory(samples/Lua/HelloLua)
endif(BUILD_HelloLua)
if(BUILD_TestLua) if(BUILD_TestLua)
add_subdirectory(samples/Lua/TestLua) add_subdirectory(tests/test-lua)
endif(BUILD_TestLua) endif(BUILD_TestLua)

View File

@ -24,12 +24,12 @@ How to start a new game
1. Download the code from [cocos2d download site][4] 1. Download the code from [cocos2d download site][4]
2. Enter `tools/project-creator` 2. Enter `tools/project-creator`
3. Run the `create-projects.py` script 3. Run the `create_project.py` script
Example: Example:
$ cd cocos2d-x/tools/project-creator $ cd cocos2d-x/tools/project-creator
$ ./project-creator.py -n mygame -k com.your_company.mygame -l cpp -p /home/mygame $ ./create_project.py -n mygame -k com.your_company.mygame -l cpp -p /home/mygame
$ cd /home/mygame $ cd /home/mygame
### Build new project for android ### ### Build new project for android ###

View File

@ -1,17 +1,34 @@
#!/usr/bin/python #!/usr/bin/python
# android-build.py # android-build.py
# Build android samples # Build android
import sys import sys
import os, os.path import os, os.path
import shutil import shutil
from optparse import OptionParser from optparse import OptionParser
CPP_SAMPLES = ['hellocpp', 'testcpp', 'simplegame', 'assetsmanager'] CPP_SAMPLES = ['testcpp']
LUA_SAMPLES = ['hellolua', 'testlua'] LUA_SAMPLES = ['testlua']
JSB_SAMPLES = ['cocosdragon', 'crystalcraze', 'moonwarriors', 'testjavascript', 'watermelonwithme'] JSB_SAMPLES = ['testjavascript']
ALL_SAMPLES = CPP_SAMPLES + LUA_SAMPLES + JSB_SAMPLES 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:
platform = sys.platform
if platform == 'win32':
if 'NUMBER_OF_PROCESSORS' in os.environ:
return int(os.environ['NUMBER_OF_PROCESSORS'])
else:
return 1
else:
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(): def check_environment_variables():
''' Checking the environment NDK_ROOT, which will be used for building ''' Checking the environment NDK_ROOT, which will be used for building
''' '''
@ -57,9 +74,9 @@ def select_toolchain_version():
def caculate_built_samples(args): def caculate_built_samples(args):
''' Compute the sampels to be built ''' Compute the sampels to be built
'cpp' for short of all cpp samples 'cpp' for short of all cpp tests
'lua' for short of all lua smpleas 'lua' for short of all lua tests
'jsb' for short of all javascript samples 'jsb' for short of all javascript tests
''' '''
if 'all' in args: if 'all' in args:
@ -94,10 +111,12 @@ def do_build(cocos_root, ndk_root, app_android_root, ndk_build_param,sdk_root,an
else: else:
ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root) 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: 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: 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: if os.system(command) != 0:
raise Exception("Build dynamic library for project [ " + app_android_root + " ] fails!") raise Exception("Build dynamic library for project [ " + app_android_root + " ] fails!")
elif android_platform is not None: elif android_platform is not None:
@ -140,47 +159,23 @@ def copy_resources(target, app_android_root):
# jsb samples should copy javascript files and resources(shared with cocos2d-html5) # jsb samples should copy javascript files and resources(shared with cocos2d-html5)
if target in JSB_SAMPLES: if target in JSB_SAMPLES:
resources_dir = os.path.join(app_android_root, "../../../../cocos/scripting/javascript/script") resources_dir = os.path.join(app_android_root, "../../../cocos/scripting/javascript/script")
copy_files(resources_dir, assets_dir) copy_files(resources_dir, assets_dir)
if target == "cocosdragon":
resources_dir = os.path.join(app_android_root, "../../Shared/games/CocosDragonJS/Published files Android")
if target == "crystalcraze":
resources_dir = os.path.join(app_android_root, "../../Shared/games/CrystalCraze/Published-Android")
if target == "testjavascript": if target == "testjavascript":
resources_dir = os.path.join(app_android_root, "../../Shared/tests/") resources_dir = os.path.join(app_android_root, "../tests/")
if target == "watermelonwithme":
resources_dir = os.path.join(app_android_root, "../../Shared/games/WatermelonWithMe")
if target != "moonwarriors":
copy_files(resources_dir, assets_dir)
else:
resources_dir = os.path.join(app_android_root, "../../Shared/games/MoonWarriors/res")
dst_dir = os.path.join(assets_dir, "res")
os.mkdir(dst_dir)
copy_files(resources_dir, dst_dir)
resources_dir = os.path.join(app_android_root, "../../Shared/games/MoonWarriors/src")
dst_dir = os.path.join(assets_dir, "src")
os.mkdir(dst_dir)
copy_files(resources_dir, dst_dir)
resources_dir = os.path.join(app_android_root, "../../Shared/games/MoonWarriors")
for item in os.listdir(resources_dir):
path = os.path.join(resources_dir, item)
if item.endswith('.js') and os.path.isfile(path):
shutil.copy(path, assets_dir)
# AssetsManager test should also copy javascript files
if target == "assetsmanager":
resources_dir = os.path.join(app_android_root, "../../../../cocos/scripting/javascript/script")
copy_files(resources_dir, assets_dir) copy_files(resources_dir, assets_dir)
# lua samples should copy lua script # lua samples should copy lua script
if target in LUA_SAMPLES: if target in LUA_SAMPLES:
resources_dir = os.path.join(app_android_root, "../../../../cocos/scripting/lua/script") resources_dir = os.path.join(app_android_root, "../../../cocos/scripting/lua/script")
copy_files(resources_dir, assets_dir) copy_files(resources_dir, assets_dir)
# TestLua shared resources with TestCpp # TestLua shared resources with TestCpp
if target == "testlua": if target == "testlua":
resources_dir = os.path.join(app_android_root, "../../../Cpp/TestCpp/Resources") resources_dir = os.path.join(app_android_root, "../../test-cpp/Resources")
copy_files(resources_dir, assets_dir) copy_files(resources_dir, assets_dir)
def build_samples(target,ndk_build_param,android_platform,build_mode): def build_samples(target,ndk_build_param,android_platform,build_mode):
@ -194,12 +189,12 @@ def build_samples(target,ndk_build_param,android_platform,build_mode):
cocos_root = os.path.join(current_dir, "..") cocos_root = os.path.join(current_dir, "..")
if android_platform is not None: if android_platform is not None:
sdk_root = check_environment_variables_sdk() sdk_root = check_environment_variables_sdk()
if android_platform.isdigit(): if android_platform.isdigit():
android_platform = 'android-'+android_platform android_platform = 'android-'+android_platform
else: else:
print 'please use vaild android platform' print 'please use vaild android platform'
exit(1) exit(1)
if build_mode is None: if build_mode is None:
build_mode = 'debug' build_mode = 'debug'
@ -208,28 +203,12 @@ def build_samples(target,ndk_build_param,android_platform,build_mode):
app_android_root = '' app_android_root = ''
for target in build_targets: for target in build_targets:
if target == 'hellocpp': if target == 'testcpp':
app_android_root = os.path.join(cocos_root, 'samples/Cpp/HelloCpp/proj.android') app_android_root = os.path.join(cocos_root, 'tests/test-cpp/proj.android')
elif target == 'testcpp':
app_android_root = os.path.join(cocos_root, 'samples/Cpp/TestCpp/proj.android')
elif target == 'simplegame':
app_android_root = os.path.join(cocos_root, 'samples/Cpp/SimpleGame/proj.android')
elif target == 'assetsmanager':
app_android_root = os.path.join(cocos_root, 'samples/Cpp/AssetsManagerTest/proj.android')
elif target == 'hellolua':
app_android_root = os.path.join(cocos_root, 'samples/Lua/HelloLua/proj.android')
elif target == 'testlua': elif target == 'testlua':
app_android_root = os.path.join(cocos_root, 'samples/Lua/TestLua/proj.android') app_android_root = os.path.join(cocos_root, 'tests/test-lua/proj.android')
elif target == 'cocosdragon':
app_android_root = os.path.join(cocos_root, 'samples/Javascript/CocosDragonJS/proj.android')
elif target == 'crystalcraze':
app_android_root = os.path.join(cocos_root, 'samples/Javascript/CrystalCraze/proj.android')
elif target == 'moonwarriors':
app_android_root = os.path.join(cocos_root, 'samples/Javascript/MoonWarriors/proj.android')
elif target == 'testjavascript': elif target == 'testjavascript':
app_android_root = os.path.join(cocos_root, 'samples/Javascript/TestJavascript/proj.android') app_android_root = os.path.join(cocos_root, 'tests/test-javascript/proj.android')
elif target == 'watermelonwithme':
app_android_root = os.path.join(cocos_root, 'samples/Javascript/WatermelonWithMe/proj.android')
else: else:
print 'unknown target: %s' % target print 'unknown target: %s' % target
continue continue
@ -241,19 +220,40 @@ def build_samples(target,ndk_build_param,android_platform,build_mode):
if __name__ == '__main__': if __name__ == '__main__':
#parse the params #parse the params
usage = """usage: %prog [options] target usage = """
This script is mainy used for building tests built-in with cocos2d-x.
Valid targets are: [hellocpp|testcpp|simplegame|assetsmanager|hellolua|testlua|cocosdragon|crystalcraze|moonwarriors|testjavascript|watermelonwithme] Usage: %prog [options] target
You can use [all|cpp|lua|jsb], to build all, or all the C++, or all the Lua, or all the JavaScript samples respectevely.""" Valid targets are: [testcpp|testlua|testjavascript]. You can combine them arbitrarily with a whitespace among two valid targets.
You can use [all|cpp|lua|jsb], to build all the tests, or all the c++ tests, or all the Lua tests, or all the JavaScript tests respectevely.
cpp = ['testcpp']
lua = ['testlua']
jsb = ['testjavascript']
all = cpp + lua + jsb // be careful with the all target, it may took a very long time to compile all the projects, do it under your own risk.
If you are new to cocos2d-x, I recommend you start with testcpp, testlua or testjavascript.
You can combine these targets like this:
//1. to build simplegame and assetsmanager
python android-build.py -p 10 testcpp testlua
//2. to build testlua and all the jsb tests
python android-build.py -p 19 testlua jsb
Note: You should install ant to generate apk while building the andriod tests. But it is optional. You can generate apk with eclipse.
"""
parser = OptionParser(usage=usage) parser = OptionParser(usage=usage)
parser.add_option("-n", "--ndk", dest="ndk_build_param", parser.add_option("-n", "--ndk", dest="ndk_build_param",
help='parameter for ndk-build') help='Parameter for ndk-build')
parser.add_option("-p", "--platform", dest="android_platform", parser.add_option("-p", "--platform", dest="android_platform",
help='parameter for android-update.Without the parameter,the script just build dynamic library for project. Valid android-platform are:[10|11|12|13|14|15|16|17|18|19]') help='Parameter for android-update. Without the parameter,the script just build dynamic library for the projects. Valid android-platform are:[10|11|12|13|14|15|16|17|18|19]')
parser.add_option("-b", "--build", dest="build_mode", parser.add_option("-b", "--build", dest="build_mode",
help='the build mode for java project,debug[default] or release.Get more information,please refer to http://developer.android.com/tools/building/building-cmdline.html') help='The build mode for java project,debug[default] or release. Get more information,please refer to http://developer.android.com/tools/building/building-cmdline.html')
(opts, args) = parser.parse_args() (opts, args) = parser.parse_args()
if len(args) == 0: if len(args) == 0:

View File

@ -5,15 +5,13 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libAudio", "..\cocos\audio\
EndProject EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d", "..\cocos\2d\cocos2d.vcxproj", "{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d", "..\cocos\2d\cocos2d.vcxproj", "{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}"
EndProject EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloCpp", "..\samples\Cpp\HelloCpp\proj.win32\HelloCpp.vcxproj", "{B8BF9E81-35FD-4582-BA1C-B85FA365BABB}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libBox2D", "..\external\Box2D\proj.win32\Box2D.vcxproj", "{929480E7-23C0-4DF6-8456-096D71547116}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libBox2D", "..\external\Box2D\proj.win32\Box2D.vcxproj", "{929480E7-23C0-4DF6-8456-096D71547116}"
EndProject EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libchipmunk", "..\external\chipmunk\proj.win32\chipmunk.vcxproj", "{207BC7A9-CCF1-4F2F-A04D-45F72242AE25}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libchipmunk", "..\external\chipmunk\proj.win32\chipmunk.vcxproj", "{207BC7A9-CCF1-4F2F-A04D-45F72242AE25}"
EndProject EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libExtensions", "..\extensions\proj.win32\libExtensions.vcxproj", "{21B2C324-891F-48EA-AD1A-5AE13DE12E28}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libExtensions", "..\extensions\proj.win32\libExtensions.vcxproj", "{21B2C324-891F-48EA-AD1A-5AE13DE12E28}"
EndProject EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestCpp", "..\samples\Cpp\TestCpp\proj.win32\TestCpp.vcxproj", "{76A39BB2-9B84-4C65-98A5-654D86B86F2A}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestCpp", "..\tests\test-cpp\proj.win32\TestCpp.vcxproj", "{76A39BB2-9B84-4C65-98A5-654D86B86F2A}"
EndProject EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libCocosBuilder", "..\cocos\editor-support\cocosbuilder\proj.win32\libCocosBuilder.vcxproj", "{811C0DAB-7B96-4BD3-A154-B7572B58E4AB}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libCocosBuilder", "..\cocos\editor-support\cocosbuilder\proj.win32\libCocosBuilder.vcxproj", "{811C0DAB-7B96-4BD3-A154-B7572B58E4AB}"
EndProject EndProject
@ -25,29 +23,15 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libNetwork", "..\cocos\netw
EndProject EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libSpine", "..\cocos\editor-support\spine\proj.win32\libSpine.vcxproj", "{B7C2A162-DEC9-4418-972E-240AB3CBFCAE}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libSpine", "..\cocos\editor-support\spine\proj.win32\libSpine.vcxproj", "{B7C2A162-DEC9-4418-972E-240AB3CBFCAE}"
EndProject EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AssetsManagerTest", "..\samples\Cpp\AssetsManagerTest\proj.win32\AssetsManagerTest.vcxproj", "{6D37505F-A890-441D-BD3F-A61E2C0469CE}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBinding", "..\cocos\scripting\javascript\bindings\proj.win32\libJSBinding.vcxproj", "{39379840-825A-45A0-B363-C09FFEF864BD}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBinding", "..\cocos\scripting\javascript\bindings\proj.win32\libJSBinding.vcxproj", "{39379840-825A-45A0-B363-C09FFEF864BD}"
EndProject EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestJavascript", "..\samples\Javascript\TestJavascript\proj.win32\TestJavascript.vcxproj", "{D0F06A44-A245-4D13-A498-0120C203B539}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestJavascript", "..\tests\test-javascript\proj.win32\TestJavascript.vcxproj", "{D0F06A44-A245-4D13-A498-0120C203B539}"
EndProject EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libLocalStorage", "..\cocos\storage\local-storage\proj.win32\libLocalStorage.vcxproj", "{632A8F38-D0F0-4D22-86B3-D69F5E6BF63A}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libLocalStorage", "..\cocos\storage\local-storage\proj.win32\libLocalStorage.vcxproj", "{632A8F38-D0F0-4D22-86B3-D69F5E6BF63A}"
EndProject EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CocosDragonJS", "..\samples\Javascript\CocosDragonJS\proj.win32\CocosDragonJS.vcxproj", "{68ED0B4E-2BCA-45D2-9648-CEABEBD3B9D7}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CrystalCraze", "..\samples\Javascript\CrystalCraze\proj.win32\CrystalCraze.vcxproj", "{9A17D9A4-4B11-4E32-94F6-895FF4909EC5}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MoonWarriors", "..\samples\Javascript\MoonWarriors\proj.win32\MoonWarriors.vcxproj", "{1DB7C0FC-46FF-4A1B-82E0-C6244EEEC4C2}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WatermelonWithMe", "..\samples\Javascript\WatermelonWithMe\proj.win32\WatermelonWithMe.vcxproj", "{BE092D9E-95AE-4F86-84CE-F4519E4F3F15}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblua", "..\cocos\scripting\lua\bindings\liblua.vcxproj", "{DDC3E27F-004D-4DD4-9DD3-931A013D2159}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblua", "..\cocos\scripting\lua\bindings\liblua.vcxproj", "{DDC3E27F-004D-4DD4-9DD3-931A013D2159}"
EndProject EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloLua", "..\samples\Lua\HelloLua\proj.win32\HelloLua.vcxproj", "{13E55395-94A2-4CD9-BFC2-1A051F80C17D}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestLua", "..\tests\test-lua\proj.win32\TestLua.win32.vcxproj", "{4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestLua", "..\samples\Lua\TestLua\proj.win32\TestLua.win32.vcxproj", "{4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SimpleGame", "..\samples\Cpp\SimpleGame\proj.win32\SimpleGame.vcxproj", "{E0E282F4-8487-452C-BFAB-CB960EB4D22F}"
EndProject EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBindingForBuilder", "..\cocos\scripting\javascript\bindings\cocosbuilder\libJSBindingForBuilder.vcxproj", "{F9DA0FC1-651B-457B-962E-A4D61CEBF5FD}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBindingForBuilder", "..\cocos\scripting\javascript\bindings\cocosbuilder\libJSBindingForBuilder.vcxproj", "{F9DA0FC1-651B-457B-962E-A4D61CEBF5FD}"
EndProject EndProject

View File

@ -1 +1 @@
3d6ada05d55194dd8e4c10ed8316add7c0d8705c caae58ff83f2655d5ea4c19e00a2be17259f8559

View File

@ -1 +0,0 @@
2efefc01ff97bda1498d1d4a850ea1881f751f7c

View File

@ -0,0 +1 @@
88d35147fd70ffbc353388aa9424bd2f0645ac95

View File

@ -0,0 +1,86 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0500"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A035A5441782290400987F6C"
BuildableName = "Test JavaScript Mac.app"
BlueprintName = "Test JavaScript Mac"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A035A5441782290400987F6C"
BuildableName = "Test JavaScript Mac.app"
BlueprintName = "Test JavaScript Mac"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</MacroExpansion>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
<BuildableProductRunnable>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A035A5441782290400987F6C"
BuildableName = "Test JavaScript Mac.app"
BlueprintName = "Test JavaScript Mac"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
<BuildableProductRunnable>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A035A5441782290400987F6C"
BuildableName = "Test JavaScript Mac.app"
BlueprintName = "Test JavaScript Mac"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@ -0,0 +1,86 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0500"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A01E16C01784C06E00B0CA4A"
BuildableName = "Test JavaScript iOS.app"
BlueprintName = "Test JavaScript iOS"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A01E16C01784C06E00B0CA4A"
BuildableName = "Test JavaScript iOS.app"
BlueprintName = "Test JavaScript iOS"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</MacroExpansion>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
<BuildableProductRunnable>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A01E16C01784C06E00B0CA4A"
BuildableName = "Test JavaScript iOS.app"
BlueprintName = "Test JavaScript iOS"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
<BuildableProductRunnable>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A01E16C01784C06E00B0CA4A"
BuildableName = "Test JavaScript iOS.app"
BlueprintName = "Test JavaScript iOS"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@ -0,0 +1,86 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0500"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "1D6058900D05DD3D006BFB54"
BuildableName = "Test cpp Mac.app"
BlueprintName = "Test cpp Mac"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "1D6058900D05DD3D006BFB54"
BuildableName = "Test cpp Mac.app"
BlueprintName = "Test cpp Mac"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</MacroExpansion>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
<BuildableProductRunnable>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "1D6058900D05DD3D006BFB54"
BuildableName = "Test cpp Mac.app"
BlueprintName = "Test cpp Mac"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
<BuildableProductRunnable>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "1D6058900D05DD3D006BFB54"
BuildableName = "Test cpp Mac.app"
BlueprintName = "Test cpp Mac"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@ -0,0 +1,86 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0500"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A07A517F1783A1D20073F6A7"
BuildableName = "Test cpp iOS.app"
BlueprintName = "Test cpp iOS"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A07A517F1783A1D20073F6A7"
BuildableName = "Test cpp iOS.app"
BlueprintName = "Test cpp iOS"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</MacroExpansion>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
<BuildableProductRunnable>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A07A517F1783A1D20073F6A7"
BuildableName = "Test cpp iOS.app"
BlueprintName = "Test cpp iOS"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
<BuildableProductRunnable>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A07A517F1783A1D20073F6A7"
BuildableName = "Test cpp iOS.app"
BlueprintName = "Test cpp iOS"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@ -0,0 +1,86 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0500"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "1A6FB7821785614200CDF010"
BuildableName = "Test lua Mac.app"
BlueprintName = "Test lua Mac"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "1A6FB7821785614200CDF010"
BuildableName = "Test lua Mac.app"
BlueprintName = "Test lua Mac"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</MacroExpansion>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
<BuildableProductRunnable>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "1A6FB7821785614200CDF010"
BuildableName = "Test lua Mac.app"
BlueprintName = "Test lua Mac"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
<BuildableProductRunnable>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "1A6FB7821785614200CDF010"
BuildableName = "Test lua Mac.app"
BlueprintName = "Test lua Mac"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@ -0,0 +1,86 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0500"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "1A11982D178538E400D62A44"
BuildableName = "Test lua iOS.app"
BlueprintName = "Test lua iOS"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "1A11982D178538E400D62A44"
BuildableName = "Test lua iOS.app"
BlueprintName = "Test lua iOS"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</MacroExpansion>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
<BuildableProductRunnable>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "1A11982D178538E400D62A44"
BuildableName = "Test lua iOS.app"
BlueprintName = "Test lua iOS"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
<BuildableProductRunnable>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "1A11982D178538E400D62A44"
BuildableName = "Test lua iOS.app"
BlueprintName = "Test lua iOS"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0500"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A035ACBB1782469700987F6C"
BuildableName = "build-all-tests Mac"
BlueprintName = "build-all-tests Mac"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
</Testables>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0500"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A07A517B1783A1CC0073F6A7"
BuildableName = "build-all-tests iOS"
BlueprintName = "build-all-tests iOS"
ReferencedContainer = "container:cocos2d_tests.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
</Testables>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@ -1,8 +0,0 @@
@echo off
SETLOCAL
:start
mkdir win32-msvc-vs2010-x86
cd win32-msvc-vs2010-x86
cmake -G "Visual Studio 10" ../..
pause

View File

@ -47,10 +47,9 @@ CCEventListenerTouch.cpp \
CCEventMouse.cpp \ CCEventMouse.cpp \
CCEventTouch.cpp \ CCEventTouch.cpp \
CCFont.cpp \ CCFont.cpp \
CCFontCharMap.cpp \
CCFontAtlas.cpp \ CCFontAtlas.cpp \
CCFontAtlasCache.cpp \ CCFontAtlasCache.cpp \
CCFontAtlasFactory.cpp \
CCFontDefinition.cpp \
CCFontFNT.cpp \ CCFontFNT.cpp \
CCFontFreeType.cpp \ CCFontFreeType.cpp \
ccFPSImages.c \ ccFPSImages.c \
@ -90,7 +89,6 @@ CCSpriteBatchNode.cpp \
CCSpriteFrame.cpp \ CCSpriteFrame.cpp \
CCSpriteFrameCache.cpp \ CCSpriteFrameCache.cpp \
CCTextFieldTTF.cpp \ CCTextFieldTTF.cpp \
CCTextImage.cpp \
CCTexture2D.cpp \ CCTexture2D.cpp \
CCTextureAtlas.cpp \ CCTextureAtlas.cpp \
CCTextureCache.cpp \ CCTextureCache.cpp \
@ -113,7 +111,7 @@ cocos2d.cpp \
TGAlib.cpp \ TGAlib.cpp \
TransformUtils.cpp \ TransformUtils.cpp \
ZipUtils.cpp \ ZipUtils.cpp \
platform/CCEGLViewProtocol.cpp \ platform/CCGLViewProtocol.cpp \
platform/CCFileUtils.cpp \ platform/CCFileUtils.cpp \
platform/CCSAXParser.cpp \ platform/CCSAXParser.cpp \
platform/CCThread.cpp \ platform/CCThread.cpp \
@ -122,6 +120,7 @@ renderer/CCFrustum.cpp \
renderer/CCGroupCommand.cpp \ renderer/CCGroupCommand.cpp \
renderer/CCMaterialManager.cpp \ renderer/CCMaterialManager.cpp \
renderer/CCQuadCommand.cpp \ renderer/CCQuadCommand.cpp \
renderer/CCBatchCommand.cpp \
renderer/CCRenderCommand.cpp \ renderer/CCRenderCommand.cpp \
renderer/CCRenderer.cpp \ renderer/CCRenderer.cpp \
renderer/CCRenderMaterial.cpp \ renderer/CCRenderMaterial.cpp \

View File

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

View File

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

View File

@ -31,13 +31,13 @@ THE SOFTWARE.
#include "CCDictionary.h" #include "CCDictionary.h"
#include "CCInteger.h" #include "CCInteger.h"
#include "CCBool.h" #include "CCBool.h"
#include "cocos2d.h"
#include "platform/CCFileUtils.h" #include "platform/CCFileUtils.h"
using namespace std; using namespace std;
NS_CC_BEGIN NS_CC_BEGIN
extern const char* cocos2dVersion();
Configuration* Configuration::s_sharedConfiguration = nullptr; Configuration* Configuration::s_sharedConfiguration = nullptr;
@ -75,7 +75,7 @@ bool Configuration::init()
_valueDict["cocos2d.x.compiled_with_gl_state_cache"] = Value(true); _valueDict["cocos2d.x.compiled_with_gl_state_cache"] = Value(true);
#endif #endif
#ifdef DEBUG #if COCOS2D_DEBUG
_valueDict["cocos2d.x.build_type"] = Value("DEBUG"); _valueDict["cocos2d.x.build_type"] = Value("DEBUG");
#else #else
_valueDict["cocos2d.x.build_type"] = Value("RELEASE"); _valueDict["cocos2d.x.build_type"] = Value("RELEASE");
@ -146,7 +146,7 @@ void Configuration::gatherGPUInfo()
_supportsShareableVAO = checkForGLExtension("vertex_array_object"); _supportsShareableVAO = checkForGLExtension("vertex_array_object");
_valueDict["gl.supports_vertex_array_object"] = Value(_supportsShareableVAO); _valueDict["gl.supports_vertex_array_object"] = Value(_supportsShareableVAO);
CHECK_GL_ERROR_DEBUG(); CHECK_GL_ERROR_DEBUG();
} }

View File

@ -764,7 +764,7 @@ CC_DEPRECATED_ATTRIBUTE typedef TMXTiledMap CCTMXTiledMap;
CC_DEPRECATED_ATTRIBUTE typedef TileMapAtlas CCTileMapAtlas; CC_DEPRECATED_ATTRIBUTE typedef TileMapAtlas CCTileMapAtlas;
CC_DEPRECATED_ATTRIBUTE typedef Timer CCTimer; CC_DEPRECATED_ATTRIBUTE typedef Timer CCTimer;
CC_DEPRECATED_ATTRIBUTE typedef Scheduler CCScheduler; CC_DEPRECATED_ATTRIBUTE typedef Scheduler CCScheduler;
CC_DEPRECATED_ATTRIBUTE typedef EGLView CCEGLView; CC_DEPRECATED_ATTRIBUTE typedef GLView CCEGLView;
CC_DEPRECATED_ATTRIBUTE typedef Component CCComponent; CC_DEPRECATED_ATTRIBUTE typedef Component CCComponent;
CC_DEPRECATED_ATTRIBUTE typedef AffineTransform CCAffineTransform; CC_DEPRECATED_ATTRIBUTE typedef AffineTransform CCAffineTransform;
@ -840,7 +840,7 @@ CC_DEPRECATED_ATTRIBUTE extern const char* kCCAttributeNameColor;
CC_DEPRECATED_ATTRIBUTE extern const char* kCCAttributeNamePosition; CC_DEPRECATED_ATTRIBUTE extern const char* kCCAttributeNamePosition;
CC_DEPRECATED_ATTRIBUTE extern const char* kCCAttributeNameTexCoord; CC_DEPRECATED_ATTRIBUTE extern const char* kCCAttributeNameTexCoord;
CC_DEPRECATED_ATTRIBUTE const int kCCVertexAttribFlag_None = GL::VERTEX_ATTRIB_FLAT_NONE; CC_DEPRECATED_ATTRIBUTE const int kCCVertexAttribFlag_None = GL::VERTEX_ATTRIB_FLAG_NONE;
CC_DEPRECATED_ATTRIBUTE const int kCCVertexAttribFlag_Position = GL::VERTEX_ATTRIB_FLAG_POSITION; CC_DEPRECATED_ATTRIBUTE const int kCCVertexAttribFlag_Position = GL::VERTEX_ATTRIB_FLAG_POSITION;
CC_DEPRECATED_ATTRIBUTE const int kCCVertexAttribFlag_Color = GL::VERTEX_ATTRIB_FLAG_COLOR; CC_DEPRECATED_ATTRIBUTE const int kCCVertexAttribFlag_Color = GL::VERTEX_ATTRIB_FLAG_COLOR;
CC_DEPRECATED_ATTRIBUTE const int kCCVertexAttribFlag_TexCoords = GL::VERTEX_ATTRIB_FLAG_TEX_COORDS; CC_DEPRECATED_ATTRIBUTE const int kCCVertexAttribFlag_TexCoords = GL::VERTEX_ATTRIB_FLAG_TEX_COORDS;

View File

@ -55,14 +55,15 @@ THE SOFTWARE.
#include "kazmath/GL/matrix.h" #include "kazmath/GL/matrix.h"
#include "CCProfiling.h" #include "CCProfiling.h"
#include "platform/CCImage.h" #include "platform/CCImage.h"
#include "CCEGLView.h" #include "CCGLView.h"
#include "CCConfiguration.h" #include "CCConfiguration.h"
#include "CCEventDispatcher.h" #include "CCEventDispatcher.h"
#include "CCEventCustom.h" #include "CCEventCustom.h"
#include "CCFontFreeType.h" #include "CCFontFreeType.h"
#include "CCRenderer.h" #include "renderer/CCRenderer.h"
#include "CCConsole.h"
#include "renderer/CCFrustum.h" #include "renderer/CCFrustum.h"
#include "CCConsole.h"
/** /**
Position of the FPS Position of the FPS
@ -164,9 +165,6 @@ bool Director::init(void)
_renderer = new Renderer; _renderer = new Renderer;
_console = new Console; _console = new Console;
// create autorelease pool
PoolManager::sharedPoolManager()->push();
return true; return true;
} }
@ -192,9 +190,8 @@ Director::~Director(void)
delete _renderer; delete _renderer;
delete _console; delete _console;
// pop the autorelease pool // clean auto release pool
PoolManager::sharedPoolManager()->pop(); PoolManager::destroyInstance();
PoolManager::purgePoolManager();
// delete _lastUpdate // delete _lastUpdate
CC_SAFE_DELETE(_lastUpdate); CC_SAFE_DELETE(_lastUpdate);
@ -354,7 +351,7 @@ void Director::calculateDeltaTime()
_deltaTime = MAX(0, _deltaTime); _deltaTime = MAX(0, _deltaTime);
} }
#ifdef DEBUG #if COCOS2D_DEBUG
// If we are debugging our code, prevent big delta time // If we are debugging our code, prevent big delta time
if (_deltaTime > 0.2f) if (_deltaTime > 0.2f)
{ {
@ -368,7 +365,7 @@ float Director::getDeltaTime() const
{ {
return _deltaTime; return _deltaTime;
} }
void Director::setOpenGLView(EGLView *openGLView) void Director::setOpenGLView(GLView *openGLView)
{ {
CCASSERT(openGLView, "opengl view should not be null"); CCASSERT(openGLView, "opengl view should not be null");
@ -379,9 +376,10 @@ void Director::setOpenGLView(EGLView *openGLView)
conf->gatherGPUInfo(); conf->gatherGPUInfo();
CCLOG("%s\n",conf->getInfo().c_str()); CCLOG("%s\n",conf->getInfo().c_str());
// EAGLView is not a Object if(_openGLView)
delete _openGLView; // [openGLView_ release] _openGLView->release();
_openGLView = openGLView; _openGLView = openGLView;
_openGLView->retain();
// set size // set size
_winSizeInPoints = _openGLView->getDesignResolutionSize(); _winSizeInPoints = _openGLView->getDesignResolutionSize();
@ -944,7 +942,8 @@ void Director::createStatsLabel()
Secondly, the size of this image is 480*320, to display the FPS label with correct size, Secondly, the size of this image is 480*320, to display the FPS label with correct size,
a factor of design resolution ratio of 480x320 is also needed. a factor of design resolution ratio of 480x320 is also needed.
*/ */
float factor = EGLView::getInstance()->getDesignResolutionSize().height / 320.0f; auto glview = Director::getInstance()->getOpenGLView();
float factor = glview->getDesignResolutionSize().height / 320.0f;
_FPSLabel = LabelAtlas::create(); _FPSLabel = LabelAtlas::create();
_FPSLabel->retain(); _FPSLabel->retain();
@ -1048,7 +1047,7 @@ void DisplayLinkDirector::mainLoop()
drawScene(); drawScene();
// release the objects // release the objects
PoolManager::sharedPoolManager()->pop(); PoolManager::getInstance()->getCurrentPool()->clear();
} }
} }

View File

@ -49,7 +49,7 @@ NS_CC_BEGIN
/* Forward declarations. */ /* Forward declarations. */
class LabelAtlas; class LabelAtlas;
class Scene; class Scene;
class EGLView; class GLView;
class DirectorDelegate; class DirectorDelegate;
class Node; class Node;
class Scheduler; class Scheduler;
@ -143,12 +143,12 @@ public:
/** seconds per frame */ /** seconds per frame */
inline float getSecondsPerFrame() { return _secondsPerFrame; } inline float getSecondsPerFrame() { return _secondsPerFrame; }
/** Get the EGLView, where everything is rendered /** Get the GLView, where everything is rendered
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
inline EGLView* getOpenGLView() { return _openGLView; } inline GLView* getOpenGLView() { return _openGLView; }
void setOpenGLView(EGLView *openGLView); void setOpenGLView(GLView *openGLView);
TextureCache* getTextureCache() const; TextureCache* getTextureCache() const;
@ -202,7 +202,7 @@ public:
/** returns visible size of the OpenGL view in points. /** returns visible size of the OpenGL view in points.
* the value is equal to getWinSize if don't invoke * the value is equal to getWinSize if don't invoke
* EGLView::setDesignResolutionSize() * GLView::setDesignResolutionSize()
*/ */
Size getVisibleSize() const; Size getVisibleSize() const;
@ -422,8 +422,8 @@ protected:
/* delta time since last tick to main loop */ /* delta time since last tick to main loop */
float _deltaTime; float _deltaTime;
/* The EGLView, where everything is rendered */ /* The GLView, where everything is rendered */
EGLView *_openGLView; GLView *_openGLView;
//texture cache belongs to this director //texture cache belongs to this director
TextureCache *_textureCache; TextureCache *_textureCache;
@ -492,8 +492,8 @@ protected:
/* Console for the director */ /* Console for the director */
Console *_console; Console *_console;
// EGLViewProtocol will recreate stats labels to fit visible rect // GLViewProtocol will recreate stats labels to fit visible rect
friend class EGLViewProtocol; friend class GLViewProtocol;
}; };
/** /**

View File

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

View File

@ -191,7 +191,7 @@ EventDispatcher::~EventDispatcher()
removeAllEventListeners(); removeAllEventListeners();
} }
void EventDispatcher::visitTarget(Node* node) void EventDispatcher::visitTarget(Node* node, bool isRootNode)
{ {
int i = 0; int i = 0;
auto& children = node->getChildren(); auto& children = node->getChildren();
@ -206,24 +206,55 @@ void EventDispatcher::visitTarget(Node* node)
{ {
child = children.at(i); child = children.at(i);
if ( child && child->getZOrder() < 0 ) if ( child && child->getLocalZOrder() < 0 )
visitTarget(child); visitTarget(child, false);
else else
break; break;
} }
_nodePriorityMap.insert(std::make_pair(node, ++_nodePriorityIndex)); if (_nodeListenersMap.find(node) != _nodeListenersMap.end())
{
_globalZOrderNodeMap[node->getGlobalZOrder()].push_back(node);
}
for( ; i < childrenCount; i++ ) for( ; i < childrenCount; i++ )
{ {
child = children.at(i); child = children.at(i);
if (child) if (child)
visitTarget(child); visitTarget(child, false);
} }
} }
else else
{ {
_nodePriorityMap.insert(std::make_pair(node, ++_nodePriorityIndex)); if (_nodeListenersMap.find(node) != _nodeListenersMap.end())
{
_globalZOrderNodeMap[node->getGlobalZOrder()].push_back(node);
}
}
if (isRootNode)
{
std::vector<float> globalZOrders;
globalZOrders.reserve(_globalZOrderNodeMap.size());
for (const auto& e : _globalZOrderNodeMap)
{
globalZOrders.push_back(e.first);
}
std::sort(globalZOrders.begin(), globalZOrders.end(), [](const float a, const float b){
return a < b;
});
for (const auto& globalZ : globalZOrders)
{
for (const auto& n : _globalZOrderNodeMap[globalZ])
{
_nodePriorityMap[n] = ++_nodePriorityIndex;
}
}
_globalZOrderNodeMap.clear();
} }
} }
@ -354,7 +385,7 @@ void EventDispatcher::forceAddEventListener(EventListener* listener)
} }
else else
{ {
setDirty(listenerID, DirtyFlag::FIXED_PRITORY); setDirty(listenerID, DirtyFlag::FIXED_PRIORITY);
} }
} }
@ -496,7 +527,7 @@ void EventDispatcher::setPriority(EventListener* listener, int fixedPriority)
if (listener->getFixedPriority() != fixedPriority) if (listener->getFixedPriority() != fixedPriority)
{ {
listener->setFixedPriority(fixedPriority); listener->setFixedPriority(fixedPriority);
setDirty(listener->getListenerID(), DirtyFlag::FIXED_PRITORY); setDirty(listener->getListenerID(), DirtyFlag::FIXED_PRIORITY);
} }
return; return;
} }
@ -784,7 +815,7 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event)
if (event->isStopped()) if (event->isStopped())
{ {
updateListeners(event); updateListeners(event);
return false; return true;
} }
return false; return false;
@ -921,7 +952,7 @@ void EventDispatcher::sortEventListeners(const EventListener::ListenerID& listen
if (dirtyFlag != DirtyFlag::NONE) if (dirtyFlag != DirtyFlag::NONE)
{ {
if ((int)dirtyFlag & (int)DirtyFlag::FIXED_PRITORY) if ((int)dirtyFlag & (int)DirtyFlag::FIXED_PRIORITY)
{ {
sortEventListenersOfFixedPriority(listenerID); sortEventListenersOfFixedPriority(listenerID);
} }
@ -947,7 +978,7 @@ void EventDispatcher::sortEventListenersOfSceneGraphPriority(const EventListener
_nodePriorityIndex = 0; _nodePriorityIndex = 0;
_nodePriorityMap.clear(); _nodePriorityMap.clear();
visitTarget(rootNode); visitTarget(rootNode, true);
// After sort: priority < 0, > 0 // After sort: priority < 0, > 0
auto sceneGraphlisteners = listeners->getSceneGraphPriorityListeners(); auto sceneGraphlisteners = listeners->getSceneGraphPriorityListeners();
@ -1135,7 +1166,7 @@ bool EventDispatcher::isEnabled() const
void EventDispatcher::setDirtyForNode(Node* node) void EventDispatcher::setDirtyForNode(Node* node)
{ {
// Mark the node dirty only when there was an eventlistener associates with it. // Mark the node dirty only when there is an eventlistener associated with it.
if (_nodeListenersMap.find(node) != _nodeListenersMap.end()) if (_nodeListenersMap.find(node) != _nodeListenersMap.end())
{ {
_dirtyNodes.insert(node); _dirtyNodes.insert(node);

View File

@ -207,16 +207,16 @@ protected:
enum class DirtyFlag enum class DirtyFlag
{ {
NONE = 0, NONE = 0,
FIXED_PRITORY = 1 << 0, FIXED_PRIORITY = 1 << 0,
SCENE_GRAPH_PRIORITY = 1 << 1, SCENE_GRAPH_PRIORITY = 1 << 1,
ALL = FIXED_PRITORY | SCENE_GRAPH_PRIORITY ALL = FIXED_PRIORITY | SCENE_GRAPH_PRIORITY
}; };
/** Sets the dirty flag for a specified listener ID */ /** Sets the dirty flag for a specified listener ID */
void setDirty(const EventListener::ListenerID& listenerID, DirtyFlag flag); void setDirty(const EventListener::ListenerID& listenerID, DirtyFlag flag);
/** Walks though scene graph to get the draw order for each node, it's called before sorting event listener with scene graph priority */ /** Walks though scene graph to get the draw order for each node, it's called before sorting event listener with scene graph priority */
void visitTarget(Node* node); void visitTarget(Node* node, bool isRootNode);
/** Listeners map */ /** Listeners map */
std::unordered_map<EventListener::ListenerID, EventListenerVector*> _listeners; std::unordered_map<EventListener::ListenerID, EventListenerVector*> _listeners;
@ -230,6 +230,9 @@ protected:
/** The map of node and its event priority */ /** The map of node and its event priority */
std::unordered_map<Node*, int> _nodePriorityMap; std::unordered_map<Node*, int> _nodePriorityMap;
/** key: Global Z Order, value: Sorted Nodes */
std::unordered_map<float, std::vector<Node*>> _globalZOrderNodeMap;
/** The listeners to be added after dispatching event */ /** The listeners to be added after dispatching event */
std::vector<EventListener*> _toAddedListeners; std::vector<EventListener*> _toAddedListeners;

View File

@ -60,7 +60,7 @@ private:
EventCode _eventCode; EventCode _eventCode;
std::vector<Touch*> _touches; std::vector<Touch*> _touches;
friend class EGLViewProtocol; friend class GLViewProtocol;
}; };

View File

@ -26,14 +26,8 @@
#include "CCFont.h" #include "CCFont.h"
#include "ccUTF8.h" #include "ccUTF8.h"
#include "CCFontFNT.h"
#include "CCFontFreeType.h"
#include "edtaa3func.h"
NS_CC_BEGIN NS_CC_BEGIN
const int Font::DistanceMapSpread = 3;
const char * Font::_glyphASCII = "\"!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ "; const char * Font::_glyphASCII = "\"!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ ";
const char * Font::_glyphNEHE = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ "; const char * Font::_glyphNEHE = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ";
@ -42,7 +36,6 @@ const char * Font::_glyphNEHE = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLM
Font::Font() : Font::Font() :
_usedGlyphs(GlyphCollection::ASCII) _usedGlyphs(GlyphCollection::ASCII)
, _customGlyphs(nullptr) , _customGlyphs(nullptr)
,_distanceFieldEnabled(false)
{ {
} }
@ -92,6 +85,7 @@ void Font::setCurrentGlyphCollection(GlyphCollection glyphs, const char *customG
break; break;
} }
_usedGlyphs = glyphs;
} }
const char * Font::getCurrentGlyphCollection() const const char * Font::getCurrentGlyphCollection() const
@ -106,175 +100,7 @@ const char * Font::getCurrentGlyphCollection() const
} }
} }
Font* Font::createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs) unsigned short* Font::getUTF16Text(const char *text, int &outNumLetters) const
{
return FontFreeType::create(fntName, fontSize, glyphs, customGlyphs);
}
Font* Font::createWithFNT(const std::string& fntFilePath)
{
return FontFNT::create(fntFilePath);
}
unsigned char * Font::makeDistanceMap( unsigned char *img, unsigned int width, unsigned int height)
{
unsigned int pixelAmount = (width + 2 * DistanceMapSpread) * (height + 2 * DistanceMapSpread);
short * xdist = (short *) malloc( pixelAmount * sizeof(short) );
short * ydist = (short *) malloc( pixelAmount * sizeof(short) );
double * gx = (double *) calloc( pixelAmount, sizeof(double) );
double * gy = (double *) calloc( pixelAmount, sizeof(double) );
double * data = (double *) calloc( pixelAmount, sizeof(double) );
double * outside = (double *) calloc( pixelAmount, sizeof(double) );
double * inside = (double *) calloc( pixelAmount, sizeof(double) );
unsigned int i,j;
// Convert img into double (data) rescale image levels between 0 and 1
unsigned int outWidth = width + 2 * DistanceMapSpread;
for (i = 0; i < width; ++i)
{
for (j = 0; j < height; ++j)
{
data[j * outWidth + DistanceMapSpread + i] = img[j * width + i] / 255.0;
}
}
width += 2 * DistanceMapSpread;
height += 2 * DistanceMapSpread;
// Transform background (outside contour, in areas of 0's)
computegradient( data, width, height, gx, gy);
edtaa3(data, gx, gy, width, height, xdist, ydist, outside);
for( i=0; i< pixelAmount; i++)
if( outside[i] < 0.0 )
outside[i] = 0.0;
// Transform foreground (inside contour, in areas of 1's)
for( i=0; i< pixelAmount; i++)
data[i] = 1 - data[i];
computegradient( data, width, height, gx, gy);
edtaa3(data, gx, gy, width, height, xdist, ydist, inside);
for( i=0; i< pixelAmount; i++)
if( inside[i] < 0.0 )
inside[i] = 0.0;
// The bipolar distance field is now outside-inside
double dist;
/* Single channel 8-bit output (bad precision and range, but simple) */
unsigned char *out = (unsigned char *) malloc( pixelAmount * sizeof(unsigned char) );
for( i=0; i < pixelAmount; i++)
{
dist = outside[i] - inside[i];
dist = 128.0 - dist*16;
if( dist < 0 ) dist = 0;
if( dist > 255 ) dist = 255;
out[i] = (unsigned char) dist;
}
/* Dual channel 16-bit output (more complicated, but good precision and range) */
/*unsigned char *out = (unsigned char *) malloc( pixelAmount * 3 * sizeof(unsigned char) );
for( i=0; i< pixelAmount; i++)
{
dist = outside[i] - inside[i];
dist = 128.0 - dist*16;
if( dist < 0.0 ) dist = 0.0;
if( dist >= 256.0 ) dist = 255.999;
// R channel is a copy of the original grayscale image
out[3*i] = img[i];
// G channel is fraction
out[3*i + 1] = (unsigned char) ( 256 - (dist - floor(dist)* 256.0 ));
// B channel is truncated integer part
out[3*i + 2] = (unsigned char)dist;
}*/
free( xdist );
free( ydist );
free( gx );
free( gy );
free( data );
free( outside );
free( inside );
return out;
}
void Font::setDistanceFieldEnabled(bool distanceFieldEnabled)
{
_distanceFieldEnabled = distanceFieldEnabled;
}
bool Font::renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize)
{
unsigned char *sourceBitmap = 0;
int sourceWidth = 0;
int sourceHeight = 0;
sourceBitmap = getGlyphBitmap(charToRender, sourceWidth, sourceHeight);
if (!sourceBitmap)
return false;
if (_distanceFieldEnabled)
{
unsigned char * out = makeDistanceMap(sourceBitmap,sourceWidth,sourceHeight);
int iX = posX;
int iY = posY;
sourceWidth += 2 * DistanceMapSpread;
sourceHeight += 2 * DistanceMapSpread;
for (int y = 0; y < sourceHeight; ++y)
{
int bitmap_y = y * sourceWidth;
for (int x = 0; x < sourceWidth; ++x)
{
/* Dual channel 16-bit output (more complicated, but good precision and range) */
/*int index = (iX + ( iY * destSize )) * 3;
int index2 = (bitmap_y + x)*3;
destMemory[index] = out[index2];
destMemory[index + 1] = out[index2 + 1];
destMemory[index + 2] = out[index2 + 2];*/
//Single channel 8-bit output
destMemory[iX + ( iY * destSize )] = out[bitmap_y + x];
iX += 1;
}
iX = posX;
iY += 1;
}
free(out);
return true;
}
int iX = posX;
int iY = posY;
for (int y = 0; y < sourceHeight; ++y)
{
int bitmap_y = y * sourceWidth;
for (int x = 0; x < sourceWidth; ++x)
{
unsigned char cTemp = sourceBitmap[bitmap_y + x];
// the final pixel
destMemory[(iX + ( iY * destSize ) )] = cTemp;
iX += 1;
}
iX = posX;
iY += 1;
}
//everything good
return true;
}
unsigned short int * Font::getUTF16Text(const char *text, int &outNumLetters) const
{ {
unsigned short* utf16String = cc_utf8_to_utf16(text); unsigned short* utf16String = cc_utf8_to_utf16(text);
@ -290,7 +116,7 @@ int Font::getUTF16TextLenght(unsigned short int *text) const
return cc_wcslen(text); return cc_wcslen(text);
} }
unsigned short int * Font::trimUTF16Text(unsigned short int *text, int newBegin, int newEnd) const unsigned short * Font::trimUTF16Text(unsigned short int *text, int newBegin, int newEnd) const
{ {
if ( newBegin < 0 || newEnd <= 0 ) if ( newBegin < 0 || newEnd <= 0 )
return 0; return 0;
@ -316,11 +142,6 @@ unsigned short int * Font::trimUTF16Text(unsigned short int *text, int newBegin
return trimmedString; return trimmedString;
} }
Rect Font::getRectForChar(unsigned short theChar) const
{
return Rect::ZERO;
}
NS_CC_END NS_CC_END

View File

@ -28,43 +28,29 @@
#include <string> #include <string>
#include "cocos2d.h"
#include "CCLabel.h" #include "CCLabel.h"
NS_CC_BEGIN NS_CC_BEGIN
// fwd // fwd
class GlyphDef;
class FontAtlas; class FontAtlas;
class CC_DLL Font : public Object class CC_DLL Font : public Object
{ {
public: public:
static const int DistanceMapSpread;
// create the font
static Font* createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs);
static Font* createWithFNT(const std::string& fntFilePath);
static unsigned char * makeDistanceMap(unsigned char *img, unsigned int width, unsigned int height);
void setDistanceFieldEnabled(bool distanceFieldEnabled);
bool isDistanceFieldEnabled() const { return _distanceFieldEnabled;}
bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize);
virtual FontAtlas *createFontAtlas() = 0; virtual FontAtlas *createFontAtlas() = 0;
virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const = 0; virtual int* getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const = 0;
virtual const char* getCurrentGlyphCollection() const; virtual const char* getCurrentGlyphCollection() const;
virtual int getLetterPadding() const { return 0; }
virtual unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const { return 0; } virtual unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const { return 0; }
virtual GlyphDef* getGlyphDefintionsForText(const char *text, int &outNumGlyphs, bool UTF16text = false) const { return 0; }
virtual int getFontMaxHeight() const { return 0; } virtual int getFontMaxHeight() const { return 0; }
virtual Rect getRectForChar(unsigned short theChar) const;
virtual int getUTF16TextLenght(unsigned short int *text) const; virtual int getUTF16TextLenght(unsigned short int *text) const;
virtual unsigned short int * getUTF16Text(const char *text, int &outNumLetters) const; virtual unsigned short * getUTF16Text(const char *text, int &outNumLetters) const;
virtual unsigned short int * trimUTF16Text(unsigned short int *text, int newBegin, int newEnd) const; virtual unsigned short * trimUTF16Text(unsigned short int *text, int newBegin, int newEnd) const;
protected: protected:
@ -82,7 +68,6 @@ protected:
char * _customGlyphs; char * _customGlyphs;
static const char * _glyphASCII; static const char * _glyphASCII;
static const char * _glyphNEHE; static const char * _glyphNEHE;
bool _distanceFieldEnabled;
}; };

View File

@ -22,10 +22,11 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "cocos2d.h"
#include "CCFontAtlas.h" #include "CCFontAtlas.h"
#include "CCFont.h"
#include "CCFontFreeType.h" #include "CCFontFreeType.h"
#include "ccUTF8.h"
#include "CCDirector.h"
#define PAGE_WIDTH 1024 #define PAGE_WIDTH 1024
#define PAGE_HEIGHT 1024 #define PAGE_HEIGHT 1024
@ -37,10 +38,9 @@ _font(&theFont),
_currentPageData(nullptr) _currentPageData(nullptr)
{ {
_font->retain(); _font->retain();
_makeDistanceMap = _font->isDistanceFieldEnabled();
FontFreeType* fontTTf = dynamic_cast<FontFreeType*>(_font); FontFreeType* fontTTf = dynamic_cast<FontFreeType*>(_font);
if (fontTTf && fontTTf->isDynamicGlyphCollection()) if (fontTTf)
{ {
_currentPageLineHeight = _font->getFontMaxHeight(); _currentPageLineHeight = _font->getFontMaxHeight();
_commonLineHeight = _currentPageLineHeight * 0.8f; _commonLineHeight = _currentPageLineHeight * 0.8f;
@ -48,24 +48,25 @@ _currentPageData(nullptr)
_currentPage = 0; _currentPage = 0;
_currentPageOrigX = 0; _currentPageOrigX = 0;
_currentPageOrigY = 0; _currentPageOrigY = 0;
_letterPadding = 5; _letterPadding = 0;
_makeDistanceMap = fontTTf->isDistanceFieldEnabled();
if(_makeDistanceMap) if(_makeDistanceMap)
{ {
_commonLineHeight += 2 * Font::DistanceMapSpread; _commonLineHeight += 2 * FontFreeType::DistanceMapSpread;
_letterPadding += 2 * Font::DistanceMapSpread; _letterPadding += 2 * FontFreeType::DistanceMapSpread;
_currentPageDataSize = (PAGE_WIDTH * PAGE_HEIGHT * 1);
}
else
{
_currentPageDataSize = (PAGE_WIDTH * PAGE_HEIGHT * 1);
} }
_currentPageDataSize = (PAGE_WIDTH * PAGE_HEIGHT * 1);
_currentPageData = new unsigned char[_currentPageDataSize]; _currentPageData = new unsigned char[_currentPageDataSize];
memset(_currentPageData, 0, _currentPageDataSize); memset(_currentPageData, 0, _currentPageDataSize);
addTexture(*tex,0); addTexture(*tex,0);
tex->release(); tex->release();
} }
else
{
_makeDistanceMap = false;
}
} }
FontAtlas::~FontAtlas() FontAtlas::~FontAtlas()
@ -100,6 +101,7 @@ bool FontAtlas::getLetterDefinitionForChar(unsigned short letteCharUTF16, FontL
} }
else else
{ {
outDefinition.validDefinition = false;
return false; return false;
} }
} }
@ -114,6 +116,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
std::unordered_map<unsigned short, FontLetterDefinition> fontDefs; std::unordered_map<unsigned short, FontLetterDefinition> fontDefs;
int length = cc_wcslen(utf16String); int length = cc_wcslen(utf16String);
float offsetAdjust = _letterPadding / 2;
//find out new letter //find out new letter
for (int i = 0; i < length; ++i) for (int i = 0; i < length; ++i)
{ {
@ -128,31 +131,28 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
Rect tempRect; Rect tempRect;
FontLetterDefinition tempDef; FontLetterDefinition tempDef;
tempDef.offsetX = 0;
tempDef.anchorX = 0.0f;
tempDef.anchorY = 1.0f;
if (!fontTTf->getBBOXFotChar(utf16String[i], tempRect)) if (!fontTTf->getBBOXFotChar(utf16String[i], tempRect,tempDef.xAdvance))
{ {
tempDef.validDefinition = false; tempDef.validDefinition = false;
tempDef.letteCharUTF16 = utf16String[i]; tempDef.letteCharUTF16 = utf16String[i];
tempDef.commonLineHeight = 0;
tempDef.width = 0; tempDef.width = 0;
tempDef.height = 0; tempDef.height = 0;
tempDef.U = 0; tempDef.U = 0;
tempDef.V = 0; tempDef.V = 0;
tempDef.offsetX = 0;
tempDef.offsetY = 0; tempDef.offsetY = 0;
tempDef.textureID = 0; tempDef.textureID = 0;
tempDef.xAdvance = 0;
} }
else else
{ {
tempDef.validDefinition = true; tempDef.validDefinition = true;
tempDef.letteCharUTF16 = utf16String[i]; tempDef.letteCharUTF16 = utf16String[i];
tempDef.width = tempRect.size.width + _letterPadding; tempDef.width = tempRect.size.width + _letterPadding;
tempDef.height = _currentPageLineHeight - 1; tempDef.height = tempRect.size.height + _letterPadding;
tempDef.offsetY = tempRect.origin.y; tempDef.offsetX = tempRect.origin.x + offsetAdjust;
tempDef.commonLineHeight = _currentPageLineHeight; tempDef.offsetY = _commonLineHeight + tempRect.origin.y - offsetAdjust;
} }
fontDefs[utf16String[i]] = tempDef; fontDefs[utf16String[i]] = tempDef;
} }
@ -161,14 +161,14 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
Size _pageContentSize = Size(PAGE_WIDTH,PAGE_HEIGHT); Size _pageContentSize = Size(PAGE_WIDTH,PAGE_HEIGHT);
float scaleFactor = CC_CONTENT_SCALE_FACTOR(); float scaleFactor = CC_CONTENT_SCALE_FACTOR();
float glyphWidth; float glyphWidth;
Texture2D::PixelFormat pixelFormat = _makeDistanceMap ? Texture2D::PixelFormat::A8 : Texture2D::PixelFormat::A8; Texture2D::PixelFormat pixelFormat = Texture2D::PixelFormat::A8;
for(auto it = fontDefs.begin(); it != fontDefs.end(); it++) for(auto it = fontDefs.begin(); it != fontDefs.end(); it++)
{ {
if(it->second.validDefinition) if(it->second.validDefinition)
{ {
_currentPageOrigX += _letterPadding; glyphWidth = it->second.width;
glyphWidth = it->second.width - _letterPadding;
if (_currentPageOrigX + glyphWidth > PAGE_WIDTH) if (_currentPageOrigX + glyphWidth > PAGE_WIDTH)
{ {
@ -190,9 +190,9 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
tex->release(); tex->release();
} }
} }
_font->renderCharAt(it->second.letteCharUTF16,_currentPageOrigX,_currentPageOrigY,_currentPageData,PAGE_WIDTH); fontTTf->renderCharAt(it->second.letteCharUTF16,_currentPageOrigX,_currentPageOrigY,_currentPageData,PAGE_WIDTH);
it->second.U = _currentPageOrigX - 1; it->second.U = _currentPageOrigX;
it->second.V = _currentPageOrigY; it->second.V = _currentPageOrigY;
it->second.textureID = _currentPage; it->second.textureID = _currentPage;
// take from pixels to points // take from pixels to points
@ -205,7 +205,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
glyphWidth = 0; glyphWidth = 0;
_fontLetterDefinitions[it->second.letteCharUTF16] = it->second; _fontLetterDefinitions[it->second.letteCharUTF16] = it->second;
_currentPageOrigX += glyphWidth; _currentPageOrigX += glyphWidth + 1;
} }
if(fontDefs.size() > 0) if(fontDefs.size() > 0)
_atlasTextures[_currentPage]->initWithData(_currentPageData, _currentPageDataSize, pixelFormat, PAGE_WIDTH, PAGE_HEIGHT, _pageContentSize ); _atlasTextures[_currentPage]->initWithData(_currentPageData, _currentPageDataSize, pixelFormat, PAGE_WIDTH, PAGE_HEIGHT, _pageContentSize );
@ -230,8 +230,6 @@ float FontAtlas::getCommonLineHeight() const
void FontAtlas::setCommonLineHeight(float newHeight) void FontAtlas::setCommonLineHeight(float newHeight)
{ {
if(_makeDistanceMap)
newHeight += 2 * Font::DistanceMapSpread;
_commonLineHeight = newHeight; _commonLineHeight = newHeight;
} }
@ -240,4 +238,4 @@ const Font * FontAtlas::getFont() const
return _font; return _font;
} }
NS_CC_END NS_CC_END

View File

@ -26,11 +26,14 @@
#define _CCFontAtlas_h_ #define _CCFontAtlas_h_
#include <unordered_map> #include <unordered_map>
#include "CCPlatformMacros.h"
#include "CCObject.h"
NS_CC_BEGIN NS_CC_BEGIN
//fwd //fwd
class Font; class Font;
class Texture2D;
struct FontLetterDefinition struct FontLetterDefinition
{ {
@ -42,10 +45,8 @@ struct FontLetterDefinition
float offsetX; float offsetX;
float offsetY; float offsetY;
int textureID; int textureID;
float commonLineHeight;
float anchorX;
float anchorY;
bool validDefinition; bool validDefinition;
int xAdvance;
}; };
class CC_DLL FontAtlas : public Object class CC_DLL FontAtlas : public Object

View File

@ -23,9 +23,13 @@
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "CCFontAtlasCache.h" #include <sstream>
#include "CCFontAtlasFactory.h"
#include "CCFontAtlasCache.h"
#include "CCFontFNT.h"
#include "CCFontFreeType.h"
#include "CCFontCharMap.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -38,15 +42,24 @@ FontAtlas * FontAtlasCache::getFontAtlasTTF(const std::string& fontFileName, int
if ( !tempAtlas ) if ( !tempAtlas )
{ {
tempAtlas = FontAtlasFactory::createAtlasFromTTF(fontFileName, size, glyphs, customGlyphs, useDistanceField); FontFreeType *font = FontFreeType::create(fontFileName, size, glyphs, customGlyphs);
if (tempAtlas) if (font)
_atlasMap[atlasName] = tempAtlas; {
font->setDistanceFieldEnabled(useDistanceField);
tempAtlas = font->createFontAtlas();
if (tempAtlas)
_atlasMap[atlasName] = tempAtlas;
}
else
{
return nullptr;
}
} }
else else
{ {
tempAtlas->retain(); tempAtlas->retain();
} }
return tempAtlas; return tempAtlas;
} }
@ -57,9 +70,18 @@ FontAtlas * FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName)
if ( !tempAtlas ) if ( !tempAtlas )
{ {
tempAtlas = FontAtlasFactory::createAtlasFromFNT(fontFileName); Font *font = FontFNT::create(fontFileName);
if (tempAtlas)
_atlasMap[atlasName] = tempAtlas; if(font)
{
tempAtlas = font->createFontAtlas();
if (tempAtlas)
_atlasMap[atlasName] = tempAtlas;
}
else
{
return nullptr;
}
} }
else else
{ {
@ -69,6 +91,92 @@ FontAtlas * FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName)
return tempAtlas; return tempAtlas;
} }
FontAtlas * FontAtlasCache::getFontAtlasCharMap(const std::string& plistFile)
{
std::string atlasName = generateFontName(plistFile, 0, GlyphCollection::CUSTOM,false);
FontAtlas *tempAtlas = _atlasMap[atlasName];
if ( !tempAtlas )
{
Font *font = FontCharMap::create(plistFile);
if(font)
{
tempAtlas = font->createFontAtlas();
if (tempAtlas)
_atlasMap[atlasName] = tempAtlas;
}
else
{
return nullptr;
}
}
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 )
{
Font *font = FontCharMap::create(texture,itemWidth,itemHeight,startCharMap);
if(font)
{
tempAtlas = font->createFontAtlas();
if (tempAtlas)
_atlasMap[atlasName] = tempAtlas;
}
else
{
return nullptr;
}
}
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 )
{
Font *font = FontCharMap::create(charMapFile,itemWidth,itemHeight,startCharMap);
if(font)
{
tempAtlas = font->createFontAtlas();
if (tempAtlas)
_atlasMap[atlasName] = tempAtlas;
}
else
{
return nullptr;
}
}
else
{
tempAtlas->retain();
}
return tempAtlas;
}
std::string FontAtlasCache::generateFontName(const std::string& fontFileName, int size, GlyphCollection theGlyphs, bool useDistanceField) std::string FontAtlasCache::generateFontName(const std::string& fontFileName, int size, GlyphCollection theGlyphs, bool useDistanceField)
{ {
std::string tempName(fontFileName); std::string tempName(fontFileName);
@ -110,7 +218,7 @@ bool FontAtlasCache::releaseFontAtlas(FontAtlas *atlas)
{ {
if ( item.second == atlas ) if ( item.second == atlas )
{ {
if( atlas->isSingleReference() ) if (atlas->getReferenceCount() == 1)
{ {
_atlasMap.erase(item.first); _atlasMap.erase(item.first);
} }

View File

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

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

@ -0,0 +1,166 @@
/****************************************************************************
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"
#include "platform/CCFileUtils.h"
#include "CCDirector.h"
#include "CCTextureCache.h"
#include "ccUTF8.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()
{
}
int * FontCharMap::getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const
{
if (!text)
return 0;
outNumLetters = cc_wcslen(text);
if (!outNumLetters)
return 0;
int *sizes = new int[outNumLetters];
if (!sizes)
return 0;
for (int c = 0; c < outNumLetters; ++c)
{
sizes[c] = 0;
}
return sizes;
}
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.offsetX = 0.0f;
tempDefinition.offsetY = 0.0f;
tempDefinition.validDefinition = true;
tempDefinition.width = _itemWidth;
tempDefinition.height = _itemHeight;
tempDefinition.xAdvance = _itemWidth * CC_CONTENT_SCALE_FACTOR();
int charId = _mapStartChar;
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

View File

@ -1,6 +1,6 @@
/**************************************************************************** /****************************************************************************
Copyright (c) 2013 Zynga Inc. Copyright (c) 2013 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc. Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org http://www.cocos2d-x.org
@ -23,48 +23,44 @@
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#ifndef _FontDefinition_h_ #ifndef _CCFontCharMap_h_
#define _FontDefinition_h_ #define _CCFontCharMap_h_
#include <unordered_map>
#include "CCTextImage.h"
#include "CCFont.h" #include "CCFont.h"
#include "CCFontAtlas.h"
NS_CC_BEGIN NS_CC_BEGIN
/** class FontCharMap : public Font
*/ {
class CC_DLL FontDefinitionTTF : public Object
{
public: 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);
static FontDefinitionTTF* create(Font *font, int textureSize = 0); virtual int* getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const override;
FontAtlas * createFontAtlas(); virtual FontAtlas *createFontAtlas() override;
private: protected:
/** FontCharMap(Texture2D* texture,int itemWidth, int itemHeight, int startCharMap)
* @js ctor :_texture(texture)
*/ ,_mapStartChar(startCharMap)
FontDefinitionTTF(); ,_itemWidth(itemWidth)
,_itemHeight(itemHeight)
{}
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
~FontDefinitionTTF(); virtual ~FontCharMap();
bool initDefinition(Font *font, const char *letters, int textureSize); private:
bool prepareLetterDefinitions(TextFontPagesDef *pageDefs); Texture2D* _texture;
void addLetterDefinition(const FontLetterDefinition &defToAdd); int _mapStartChar;
int _itemWidth;
TextImage * _textImages; int _itemHeight;
std::unordered_map<unsigned short, FontLetterDefinition> _fontLettersDefinitionUTF16;
float _commonLineHeight;
static const int DEFAUL_ATLAS_TEXTURE_SIZE;
}; };
NS_CC_END NS_CC_END
#endif #endif /* defined(_CCFontCharMap_h_) */

View File

@ -1,235 +0,0 @@
/****************************************************************************
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 "cocos2d.h"
#include "CCFontDefinition.h"
NS_CC_BEGIN
const int FontDefinitionTTF::DEFAUL_ATLAS_TEXTURE_SIZE = 1024;
FontDefinitionTTF::FontDefinitionTTF():_textImages(0), _commonLineHeight(0)
{
}
FontDefinitionTTF* FontDefinitionTTF::create(Font *font, int textureSize)
{
if (textureSize == 0)
textureSize = DEFAUL_ATLAS_TEXTURE_SIZE;
FontDefinitionTTF *ret = new FontDefinitionTTF;
if (!ret)
return 0;
const char *glyph = font->getCurrentGlyphCollection();
if (!glyph)
return nullptr;
if (ret->initDefinition(font, glyph, textureSize))
{
ret->autorelease();
return ret;
}
else
{
delete ret;
return 0;
}
}
FontDefinitionTTF::~FontDefinitionTTF()
{
if (_textImages)
{
delete _textImages;
}
}
bool FontDefinitionTTF::prepareLetterDefinitions(TextFontPagesDef *pageDefs)
{
// get all the pages
TextFontPagesDef *pages = pageDefs;
if (!pages)
return (false);
float maxLineHeight = -1;
// loops all the pages
for (int cPages = 0; cPages < pages->getNumPages(); ++cPages)
{
// loops all the lines in this page
for (int cLines = 0; cLines<pages->getPageAt(cPages)->getNumLines(); ++cLines)
{
float posXUV = 0.0;
float posYUV = pages->getPageAt(cPages)->getLineAt(cLines)->getY();
int charsCounter = 0;
for (int c = 0; c < pages->getPageAt(cPages)->getLineAt(cLines)->getNumGlyph(); ++c)
{
// the current glyph
GlyphDef currentGlyph = pages->getPageAt(cPages)->getLineAt(cLines)->getGlyphAt(c);
// letter width
float letterWidth = currentGlyph.getRect().size.width;
// letter height
float letterHeight = pages->getPageAt(cPages)->getLineAt(cLines)->getHeight();
// add this letter definition
FontLetterDefinition tempDef;
// carloX little hack (this should be done outside the loop)
if (posXUV == 0.0)
posXUV = currentGlyph.getPadding();
tempDef.validDefinition = currentGlyph.isValid();
if (tempDef.validDefinition)
{
tempDef.letteCharUTF16 = currentGlyph.getUTF8Letter();
tempDef.width = letterWidth + currentGlyph.getPadding();
tempDef.height = (letterHeight - 1);
tempDef.U = (posXUV - 1);
tempDef.V = posYUV;
tempDef.offsetX = currentGlyph.getRect().origin.x;
tempDef.offsetY = currentGlyph.getRect().origin.y;
tempDef.textureID = cPages;
tempDef.commonLineHeight = currentGlyph.getCommonHeight();
// take from pixels to points
tempDef.width = tempDef.width / CC_CONTENT_SCALE_FACTOR();
tempDef.height = tempDef.height / CC_CONTENT_SCALE_FACTOR();
tempDef.U = tempDef.U / CC_CONTENT_SCALE_FACTOR();
tempDef.V = tempDef.V / CC_CONTENT_SCALE_FACTOR();
if (tempDef.commonLineHeight>maxLineHeight)
maxLineHeight = tempDef.commonLineHeight;
}
else
{
tempDef.letteCharUTF16 = currentGlyph.getUTF8Letter();
tempDef.commonLineHeight = 0;
tempDef.width = 0;
tempDef.height = 0;
tempDef.U = 0;
tempDef.V = 0;
tempDef.offsetX = 0;
tempDef.offsetY = 0;
tempDef.textureID = 0;
}
// add this definition
addLetterDefinition(tempDef);
// move bounding box to the next letter
posXUV += letterWidth + currentGlyph.getPadding();
// next char in the string
++charsCounter;
}
}
}
// store the common line height
_commonLineHeight = maxLineHeight;
//
return true;
}
bool FontDefinitionTTF::initDefinition(cocos2d::Font *font, const char *letters, int textureSize)
{
// preare texture/image stuff
_textImages = new TextImage();
if (!_textImages)
return false;
if (!_textImages->initWithString(letters, textureSize, textureSize, font, true))
{
delete _textImages;
_textImages = 0;
return false;
}
// prepare the new letter definition
return prepareLetterDefinitions(_textImages->getPages());
}
void FontDefinitionTTF::addLetterDefinition(const FontLetterDefinition &defToAdd)
{
if (_fontLettersDefinitionUTF16.find(defToAdd.letteCharUTF16) == _fontLettersDefinitionUTF16.end())
{
_fontLettersDefinitionUTF16[defToAdd.letteCharUTF16] = defToAdd;
}
}
FontAtlas * FontDefinitionTTF::createFontAtlas()
{
int numTextures = 0;
TextFontPagesDef *pages = _textImages->getPages();
if (pages)
numTextures = pages->getNumPages();
else
return nullptr;
if (!numTextures)
return nullptr;
FontAtlas *retAtlas = new FontAtlas(*_textImages->getFont());
if (!retAtlas)
return 0;
for (int c = 0; c < numTextures; ++c)
{
TextFontPagesDef *pPages = _textImages->getPages();
retAtlas->addTexture(*(pPages->getPageAt(c)->getPageTexture()), c);
}
// set the common line height
retAtlas->setCommonLineHeight(_commonLineHeight * 0.8);
for( auto &item: _fontLettersDefinitionUTF16 )
{
if ( item.second.validDefinition )
{
FontLetterDefinition tempDefinition = item.second;
tempDefinition.offsetX = 0;
tempDefinition.anchorX = 0.0f;
tempDefinition.anchorY = 1.0f;
retAtlas->addLetterDefinition(tempDefinition);
}
}
// done here
return retAtlas;
}
NS_CC_END

View File

@ -25,6 +25,10 @@
#include "CCFontFNT.h" #include "CCFontFNT.h"
#include "CCFontAtlas.h" #include "CCFontAtlas.h"
#include "CCLabelBMFont.h"
#include "CCDirector.h"
#include "CCTextureCache.h"
#include "ccUTF8.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -58,7 +62,7 @@ FontFNT::~FontFNT()
} }
Size * FontFNT::getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const int * FontFNT::getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const
{ {
if (!text) if (!text)
return 0; return 0;
@ -68,39 +72,21 @@ Size * FontFNT::getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters
if (!outNumLetters) if (!outNumLetters)
return 0; return 0;
Size *sizes = new Size[outNumLetters]; int *sizes = new int[outNumLetters];
if (!sizes) if (!sizes)
return 0; return 0;
for (int c = 0; c < outNumLetters; ++c) for (int c = 0; c < outNumLetters; ++c)
{ {
int advance = 0;
int kerning = 0;
advance = getAdvanceForChar(text[c]);
if (c < (outNumLetters-1)) if (c < (outNumLetters-1))
kerning = getHorizontalKerningForChars(text[c], text[c+1]); sizes[c] = getHorizontalKerningForChars(text[c], text[c+1]);
else
sizes[c].width = (advance + kerning); sizes[c] = 0;
} }
return sizes; return sizes;
} }
int FontFNT::getAdvanceForChar(unsigned short theChar) const
{
tFontDefHashElement *element = nullptr;
// unichar is a short, and an int is needed on HASH_FIND_INT
unsigned int key = theChar;
HASH_FIND_INT(_configuration->_fontDefDictionary, &key, element);
if (! element)
return -1;
return element->fontDef.xAdvance;
}
int FontFNT::getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const int FontFNT::getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const
{ {
int ret = 0; int ret = 0;
@ -118,28 +104,6 @@ int FontFNT::getHorizontalKerningForChars(unsigned short firstChar, unsigned sh
return ret; return ret;
} }
Rect FontFNT::getRectForCharInternal(unsigned short theChar) const
{
Rect retRect;
ccBMFontDef fontDef;
tFontDefHashElement *element = nullptr;
unsigned int key = theChar;
HASH_FIND_INT(_configuration->_fontDefDictionary, &key, element);
if (element)
{
retRect = element->fontDef.rect;
}
return retRect;
}
Rect FontFNT::getRectForChar(unsigned short theChar) const
{
return getRectForCharInternal(theChar);
}
FontAtlas * FontFNT::createFontAtlas() FontAtlas * FontFNT::createFontAtlas()
{ {
FontAtlas *tempAtlas = new FontAtlas(*this); FontAtlas *tempAtlas = new FontAtlas(*this);
@ -190,9 +154,8 @@ FontAtlas * FontFNT::createFontAtlas()
//carloX: only one texture supported FOR NOW //carloX: only one texture supported FOR NOW
tempDefinition.textureID = 0; tempDefinition.textureID = 0;
tempDefinition.anchorX = 0.5f;
tempDefinition.anchorY = 0.5f;
tempDefinition.validDefinition = true; tempDefinition.validDefinition = true;
tempDefinition.xAdvance = fontDef.xAdvance;
// add the new definition // add the new definition
tempAtlas->addLetterDefinition(tempDefinition); tempAtlas->addLetterDefinition(tempDefinition);
} }

View File

@ -26,11 +26,12 @@
#ifndef _CCFontFNT_h_ #ifndef _CCFontFNT_h_
#define _CCFontFNT_h_ #define _CCFontFNT_h_
#include "cocos2d.h"
#include "CCFont.h" #include "CCFont.h"
NS_CC_BEGIN NS_CC_BEGIN
class CCBMFontConfiguration;
class FontFNT : public Font class FontFNT : public Font
{ {
@ -38,8 +39,7 @@ public:
static FontFNT * create(const std::string& fntFilePath); static FontFNT * create(const std::string& fntFilePath);
virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const override; virtual int* getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const override;
virtual Rect getRectForChar(unsigned short theChar) const override;
virtual FontAtlas *createFontAtlas() override; virtual FontAtlas *createFontAtlas() override;
protected: protected:
@ -54,9 +54,7 @@ protected:
private: private:
int getAdvanceForChar(unsigned short theChar) const;
int getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const; int getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const;
Rect getRectForCharInternal(unsigned short theChar) const;
CCBMFontConfiguration * _configuration; CCBMFontConfiguration * _configuration;

View File

@ -28,23 +28,19 @@ THE SOFTWARE.
#include "ccUTF8.h" #include "ccUTF8.h"
#include "CCFontFreeType.h" #include "CCFontFreeType.h"
#include "CCTextImage.h" #include "platform/CCFileUtils.h"
#include "CCFont.h" #include "edtaa3func.h"
#include "CCFontDefinition.h"
NS_CC_BEGIN NS_CC_BEGIN
FT_Library FontFreeType::_FTlibrary; FT_Library FontFreeType::_FTlibrary;
bool FontFreeType::_FTInitialized = false; bool FontFreeType::_FTInitialized = false;
const int FontFreeType::DistanceMapSpread = 3;
FontFreeType * FontFreeType::create(const std::string &fontName, int fontSize, GlyphCollection glyphs, const char *customGlyphs) FontFreeType * FontFreeType::create(const std::string &fontName, int fontSize, GlyphCollection glyphs, const char *customGlyphs)
{ {
bool dynamicGlyphCollection = false; FontFreeType *tempFont = new FontFreeType();
if(glyphs == GlyphCollection::DYNAMIC)
dynamicGlyphCollection = true;
FontFreeType *tempFont = new FontFreeType(dynamicGlyphCollection);
if (!tempFont) if (!tempFont)
return nullptr; return nullptr;
@ -88,13 +84,10 @@ FT_Library FontFreeType::getFTLibrary()
return _FTlibrary; return _FTlibrary;
} }
FontFreeType::FontFreeType(bool dynamicGlyphCollection) FontFreeType::FontFreeType()
: _fontRef(nullptr), : _fontRef(nullptr)
_letterPadding(5), ,_distanceFieldEnabled(false)
_dynamicGlyphCollection(dynamicGlyphCollection)
{ {
if(_distanceFieldEnabled)
_letterPadding += 2 * DistanceMapSpread;
} }
bool FontFreeType::createFontObject(const std::string &fontName, int fontSize) bool FontFreeType::createFontObject(const std::string &fontName, int fontSize)
@ -140,26 +133,18 @@ FontFreeType::~FontFreeType()
FontAtlas * FontFreeType::createFontAtlas() FontAtlas * FontFreeType::createFontAtlas()
{ {
if (_dynamicGlyphCollection) FontAtlas *atlas = new FontAtlas(*this);
if (_usedGlyphs != GlyphCollection::DYNAMIC)
{ {
FontAtlas *atlas = new FontAtlas(*this); unsigned short* utf16 = cc_utf8_to_utf16(getCurrentGlyphCollection());
this->release(); atlas->prepareLetterDefinitions(utf16);
return atlas; CC_SAFE_DELETE_ARRAY(utf16);
} }
else this->release();
{ return atlas;
FontDefinitionTTF *def = FontDefinitionTTF::create(this);
if (!def)
return nullptr;
FontAtlas *atlas = def->createFontAtlas();
return atlas;
}
} }
bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect) const bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect, int &xAdvance) const
{ {
if (!_fontRef) if (!_fontRef)
return false; return false;
@ -175,80 +160,17 @@ bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect) const
return false; return false;
// store result in the passed rectangle // 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.origin.y = - (_fontRef->glyph->metrics.horiBearingY >> 6);
outRect.size.width = (_fontRef->glyph->metrics.width >> 6); outRect.size.width = (_fontRef->glyph->metrics.width >> 6);
outRect.size.height = (_fontRef->glyph->metrics.height >> 6); outRect.size.height = (_fontRef->glyph->metrics.height >> 6);
xAdvance = (static_cast<int>(_fontRef->glyph->metrics.horiAdvance >> 6));
return true; return true;
} }
GlyphDef * FontFreeType::getGlyphDefintionsForText(const char *text, int &outNumGlyphs, bool UTF16text) const int * FontFreeType::getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const
{
unsigned short* utf16String = 0;
if (UTF16text)
{
utf16String = (unsigned short*) text;
}
else
{
utf16String = cc_utf8_to_utf16(text);
}
//
if (!utf16String)
return 0;
int numChar = cc_wcslen(utf16String);
if (!numChar)
return 0;
// allocate the needed Glyphs
GlyphDef *glyphs = new GlyphDef[numChar];
assert(glyphs != nullptr);
if (!glyphs)
return 0;
// sore result as CCRect
for (int c = 0; c < numChar; ++c)
{
Rect tempRect;
if (!getBBOXFotChar(utf16String[c], tempRect))
{
log("Warning: Cannot find definition for glyph: %c in font:%s", utf16String[c], _fontName.c_str());
tempRect.origin.x = 0;
tempRect.origin.y = 0;
tempRect.size.width = 0;
tempRect.size.height = 0;
glyphs[c].setRect(tempRect);
glyphs[c].setUTF16Letter(utf16String[c]);
glyphs[c].setValid(false);
glyphs[c].setPadding(_letterPadding);
}
else
{
glyphs[c].setRect(tempRect);
glyphs[c].setUTF16Letter(utf16String[c]);
glyphs[c].setPadding(_letterPadding);
glyphs[c].setValid(true);
}
}
outNumGlyphs = numChar;
// free memory
if (!UTF16text)
delete [] utf16String;
// done
return glyphs;
}
Size * FontFreeType::getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const
{ {
if (!text) if (!text)
return 0; return 0;
@ -258,64 +180,21 @@ Size * FontFreeType::getAdvancesForTextUTF16(unsigned short *text, int &outNumLe
if (!outNumLetters) if (!outNumLetters)
return 0; return 0;
Size *sizes = new Size[outNumLetters]; int *sizes = new int[outNumLetters];
if (!sizes) if (!sizes)
return 0; return 0;
for (int c = 0; c < outNumLetters; ++c) for (int c = 0; c < outNumLetters; ++c)
{ {
int advance = 0;
int kerning = 0;
advance = getAdvanceForChar(text[c]) - getBearingXForChar(text[c]);
if (c < (outNumLetters-1)) if (c < (outNumLetters-1))
kerning = getHorizontalKerningForChars(text[c], text[c+1]); sizes[c] = getHorizontalKerningForChars(text[c], text[c+1]);
else
sizes[c].width = (advance + kerning); sizes[c] = 0;
} }
return sizes; return sizes;
} }
int FontFreeType::getAdvanceForChar(unsigned short theChar) const
{
if (!_fontRef)
return 0;
// get the ID to the char we need
int glyph_index = FT_Get_Char_Index(_fontRef, theChar);
if (!glyph_index)
return 0;
// load glyph infos
if (FT_Load_Glyph(_fontRef, glyph_index, FT_LOAD_DEFAULT))
return 0;
// get to the advance for this glyph
return (static_cast<int>(_fontRef->glyph->advance.x >> 6));
}
int FontFreeType::getBearingXForChar(unsigned short theChar) const
{
if (!_fontRef)
return 0;
// get the ID to the char we need
int glyphIndex = FT_Get_Char_Index(_fontRef, theChar);
if (!glyphIndex)
return 0;
// load glyph infos
if (FT_Load_Glyph(_fontRef, glyphIndex, FT_LOAD_DEFAULT))
return 0;
return (static_cast<int>(_fontRef->glyph->metrics.horiBearingX >>6));
}
int FontFreeType::getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const int FontFreeType::getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const
{ {
if (!_fontRef) if (!_fontRef)
@ -374,9 +253,162 @@ unsigned char * FontFreeType::getGlyphBitmap(unsigned short theChar, int &outWid
return _fontRef->glyph->bitmap.buffer; return _fontRef->glyph->bitmap.buffer;
} }
int FontFreeType::getLetterPadding() const unsigned char * makeDistanceMap( unsigned char *img, unsigned int width, unsigned int height)
{ {
return _letterPadding; unsigned int pixelAmount = (width + 2 * FontFreeType::DistanceMapSpread) * (height + 2 * FontFreeType::DistanceMapSpread);
short * xdist = (short *) malloc( pixelAmount * sizeof(short) );
short * ydist = (short *) malloc( pixelAmount * sizeof(short) );
double * gx = (double *) calloc( pixelAmount, sizeof(double) );
double * gy = (double *) calloc( pixelAmount, sizeof(double) );
double * data = (double *) calloc( pixelAmount, sizeof(double) );
double * outside = (double *) calloc( pixelAmount, sizeof(double) );
double * inside = (double *) calloc( pixelAmount, sizeof(double) );
unsigned int i,j;
// Convert img into double (data) rescale image levels between 0 and 1
unsigned int outWidth = width + 2 * FontFreeType::DistanceMapSpread;
for (i = 0; i < width; ++i)
{
for (j = 0; j < height; ++j)
{
data[j * outWidth + FontFreeType::DistanceMapSpread + i] = img[j * width + i] / 255.0;
}
}
width += 2 * FontFreeType::DistanceMapSpread;
height += 2 * FontFreeType::DistanceMapSpread;
// Transform background (outside contour, in areas of 0's)
computegradient( data, width, height, gx, gy);
edtaa3(data, gx, gy, width, height, xdist, ydist, outside);
for( i=0; i< pixelAmount; i++)
if( outside[i] < 0.0 )
outside[i] = 0.0;
// Transform foreground (inside contour, in areas of 1's)
for( i=0; i< pixelAmount; i++)
data[i] = 1 - data[i];
computegradient( data, width, height, gx, gy);
edtaa3(data, gx, gy, width, height, xdist, ydist, inside);
for( i=0; i< pixelAmount; i++)
if( inside[i] < 0.0 )
inside[i] = 0.0;
// The bipolar distance field is now outside-inside
double dist;
/* Single channel 8-bit output (bad precision and range, but simple) */
unsigned char *out = (unsigned char *) malloc( pixelAmount * sizeof(unsigned char) );
for( i=0; i < pixelAmount; i++)
{
dist = outside[i] - inside[i];
dist = 128.0 - dist*16;
if( dist < 0 ) dist = 0;
if( dist > 255 ) dist = 255;
out[i] = (unsigned char) dist;
}
/* Dual channel 16-bit output (more complicated, but good precision and range) */
/*unsigned char *out = (unsigned char *) malloc( pixelAmount * 3 * sizeof(unsigned char) );
for( i=0; i< pixelAmount; i++)
{
dist = outside[i] - inside[i];
dist = 128.0 - dist*16;
if( dist < 0.0 ) dist = 0.0;
if( dist >= 256.0 ) dist = 255.999;
// R channel is a copy of the original grayscale image
out[3*i] = img[i];
// G channel is fraction
out[3*i + 1] = (unsigned char) ( 256 - (dist - floor(dist)* 256.0 ));
// B channel is truncated integer part
out[3*i + 2] = (unsigned char)dist;
}*/
free( xdist );
free( ydist );
free( gx );
free( gy );
free( data );
free( outside );
free( inside );
return out;
}
void FontFreeType::setDistanceFieldEnabled(bool distanceFieldEnabled)
{
_distanceFieldEnabled = distanceFieldEnabled;
}
bool FontFreeType::renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize)
{
unsigned char *sourceBitmap = 0;
int sourceWidth = 0;
int sourceHeight = 0;
sourceBitmap = getGlyphBitmap(charToRender, sourceWidth, sourceHeight);
if (!sourceBitmap)
return false;
if (_distanceFieldEnabled)
{
unsigned char * out = makeDistanceMap(sourceBitmap,sourceWidth,sourceHeight);
int iX = posX;
int iY = posY;
sourceWidth += 2 * DistanceMapSpread;
sourceHeight += 2 * DistanceMapSpread;
for (int y = 0; y < sourceHeight; ++y)
{
int bitmap_y = y * sourceWidth;
for (int x = 0; x < sourceWidth; ++x)
{
/* Dual channel 16-bit output (more complicated, but good precision and range) */
/*int index = (iX + ( iY * destSize )) * 3;
int index2 = (bitmap_y + x)*3;
destMemory[index] = out[index2];
destMemory[index + 1] = out[index2 + 1];
destMemory[index + 2] = out[index2 + 2];*/
//Single channel 8-bit output
destMemory[iX + ( iY * destSize )] = out[bitmap_y + x];
iX += 1;
}
iX = posX;
iY += 1;
}
free(out);
return true;
}
int iX = posX;
int iY = posY;
for (int y = 0; y < sourceHeight; ++y)
{
int bitmap_y = y * sourceWidth;
for (int x = 0; x < sourceWidth; ++x)
{
unsigned char cTemp = sourceBitmap[bitmap_y + x];
// the final pixel
destMemory[(iX + ( iY * destSize ) )] = cTemp;
iX += 1;
}
iX = posX;
iY += 1;
}
//everything good
return true;
} }
NS_CC_END NS_CC_END

View File

@ -39,25 +39,27 @@ NS_CC_BEGIN
class CC_DLL FontFreeType : public Font class CC_DLL FontFreeType : public Font
{ {
public: public:
static const int DistanceMapSpread;
static FontFreeType * create(const std::string &fontName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); static FontFreeType * create(const std::string &fontName, int fontSize, GlyphCollection glyphs, const char *customGlyphs);
static void shutdownFreeType(); static void shutdownFreeType();
void setDistanceFieldEnabled(bool distanceFieldEnabled);
bool isDistanceFieldEnabled() const { return _distanceFieldEnabled;}
bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize);
virtual FontAtlas * createFontAtlas() override; virtual FontAtlas * createFontAtlas() override;
virtual Size * getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const override; virtual int * getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const override;
virtual GlyphDef * getGlyphDefintionsForText(const char *text, int &outNumGlyphs, bool UTF16text = false) const override;
unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const override; unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const override;
virtual int getFontMaxHeight() const override; virtual int getFontMaxHeight() const override;
virtual int getLetterPadding() const override;
bool getBBOXFotChar(unsigned short theChar, Rect &outRect) const; bool getBBOXFotChar(unsigned short theChar, Rect &outRect,int &xAdvance) const;
inline bool isDynamicGlyphCollection() { return _dynamicGlyphCollection;}
protected: protected:
FontFreeType(bool dynamicGlyphCollection = false); FontFreeType();
virtual ~FontFreeType(); virtual ~FontFreeType();
bool createFontObject(const std::string &fontName, int fontSize); bool createFontObject(const std::string &fontName, int fontSize);
@ -66,17 +68,14 @@ private:
bool initFreeType(); bool initFreeType();
FT_Library getFTLibrary(); FT_Library getFTLibrary();
int getAdvanceForChar(unsigned short theChar) const;
int getBearingXForChar(unsigned short theChar) const;
int getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const; int getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const;
static FT_Library _FTlibrary; static FT_Library _FTlibrary;
static bool _FTInitialized; static bool _FTInitialized;
FT_Face _fontRef; FT_Face _fontRef;
int _letterPadding;
std::string _fontName; std::string _fontName;
Data _ttfData; Data _ttfData;
bool _dynamicGlyphCollection; bool _distanceFieldEnabled;
}; };
NS_CC_END NS_CC_END

View File

@ -24,70 +24,90 @@
****************************************************************************/ ****************************************************************************/
#include "CCLabel.h" #include "CCLabel.h"
#include "CCFontDefinition.h"
#include "CCFontAtlasCache.h" #include "CCFontAtlasCache.h"
#include "CCLabelTextFormatter.h" #include "CCLabelTextFormatter.h"
#include "CCSprite.h"
#include "CCShaderCache.h"
#include "ccUTF8.h"
#include "CCSpriteFrame.h"
#include "CCDirector.h"
#include "renderer/CCRenderer.h"
#include "CCFont.h"
#define DISTANCEFIELD_ATLAS_FONTSIZE 50 #define DISTANCEFIELD_ATLAS_FONTSIZE 50
NS_CC_BEGIN 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; Label *ret = new Label();
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);
if (!ret) 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(nullptr,alignment);
if (!ret)
return nullptr;
if (ret->setTTFConfig(ttfConfig))
{
if(ttfConfig.distanceFieldEnabled)
ret->setFontSize(ttfConfig.fontSize);
ret->setWidth(lineSize);
ret->setString(text);
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(nullptr,alignment);
if (!ret)
return nullptr;
if (ret->setBMFontFilePath(bmfontFilePath))
{
ret->setWidth(lineSize);
ret->setString(text);
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(); ret->autorelease();
return ret; return ret;
@ -95,36 +115,102 @@ Label* Label::createWithAtlas(FontAtlas *atlas, TextHAlignment alignment, int li
else else
{ {
delete ret; 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) Label::Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField,bool useA8Shader)
: _reusedLetter(nullptr) : _reusedLetter(nullptr)
, _multilineEnable(true)
, _commonLineHeight(0.0f) , _commonLineHeight(0.0f)
, _lineBreakWithoutSpaces(false) , _lineBreakWithoutSpaces(false)
, _width(0.0f) , _width(0.0f)
, _alignment(alignment) , _alignment(alignment)
, _currentUTF16String(0) , _currentUTF16String(nullptr)
, _originalUTF16String(0) , _originalUTF16String(nullptr)
, _advances(nullptr) , _horizontalKernings(nullptr)
, _fontAtlas(atlas) , _fontAtlas(atlas)
, _isOpacityModifyRGB(true) , _isOpacityModifyRGB(false)
, _useDistanceField(useDistanceField) , _useDistanceField(useDistanceField)
, _useA8Shader(useA8Shader) , _useA8Shader(useA8Shader)
, _fontSize(0) , _fontSize(0)
, _uniformEffectColor(0) , _uniformEffectColor(0)
{ {
_cascadeColorEnabled = true;
} }
Label::~Label() Label::~Label()
{ {
delete [] _currentUTF16String; delete [] _currentUTF16String;
delete [] _originalUTF16String; delete [] _originalUTF16String;
delete [] _advances; delete [] _horizontalKernings;
if (_fontAtlas) if (_fontAtlas)
FontAtlasCache::releaseFontAtlas(_fontAtlas); FontAtlasCache::releaseFontAtlas(_fontAtlas);
@ -137,10 +223,14 @@ bool Label::init()
bool ret = true; bool ret = true;
if(_fontAtlas) if(_fontAtlas)
{ {
_reusedLetter = Sprite::createWithTexture(&_fontAtlas->getTexture(0)); if (_reusedLetter == nullptr)
_reusedLetter->setOpacityModifyRGB(_isOpacityModifyRGB); {
ret = SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), 30); _reusedLetter = Sprite::createWithTexture(&_fontAtlas->getTexture(0));
_reusedLetter->retain(); _reusedLetter->setOpacityModifyRGB(_isOpacityModifyRGB);
_reusedLetter->retain();
_reusedLetter->setAnchorPoint(Point::ANCHOR_TOP_LEFT);
}
ret = SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), 30);
} }
if (_useDistanceField) if (_useDistanceField)
setLabelEffect(LabelEffect::NORMAL,Color3B::BLACK); setLabelEffect(LabelEffect::NORMAL,Color3B::BLACK);
@ -148,54 +238,89 @@ bool Label::init()
setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_A8_COLOR)); setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_A8_COLOR));
else else
setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
return ret; return ret;
} }
void Label::setString(const std::string &stringToRender) bool Label::initWithFontAtlas(FontAtlas* atlas,bool distanceFieldEnabled /* = false */, bool useA8Shader /* = false */)
{ {
_multilineEnable = true; FontAtlas *oldAtlas = _fontAtlas;
setText(stringToRender, _width, TextHAlignment::CENTER, false); 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)
{
resetCurrentString();
alignText();
}
}
return ret;
} }
void Label::setString(const std::string &stringToRender,bool multilineEnable) bool Label::setTTFConfig(const TTFConfig& ttfConfig)
{ {
_multilineEnable = multilineEnable; FontAtlas *newAtlas = nullptr;
setText(stringToRender, _width, TextHAlignment::CENTER, false); 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 false;
return initWithFontAtlas(newAtlas);
}
void Label::setString(const std::string& text)
{
if (!_fontAtlas || _commonLineHeight <= 0)
return ;
// carloX unsigned short* utf16String = cc_utf8_to_utf16(text.c_str());
// reset the string
resetCurrentString();
_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());
if(!utf16String) if(!utf16String)
return false; return ;
_originalUTF8String = text;
_cascadeColorEnabled = true;
setCurrentString(utf16String); setCurrentString(utf16String);
setOriginalString(utf16String); setOriginalString(utf16String);
// align text // align text
alignText(); alignText();
// done here
return true;
} }
void Label::setAlignment(TextHAlignment alignment) void Label::setAlignment(TextHAlignment alignment)
@ -206,11 +331,14 @@ void Label::setAlignment(TextHAlignment alignment)
// store // store
_alignment = alignment; _alignment = alignment;
// reset the string if (_currentUTF16String)
resetCurrentString(); {
// reset the string
// need to align text again resetCurrentString();
alignText();
// need to align text again
alignText();
}
} }
} }
@ -221,12 +349,14 @@ void Label::setWidth(float width)
// store // store
_width = width; _width = width;
if (_currentUTF16String)
// reset the string {
resetCurrentString(); // reset the string
resetCurrentString();
// need to align text again
alignText(); // need to align text again
alignText();
}
} }
} }
@ -238,7 +368,11 @@ void Label::setLineBreakWithoutSpace(bool breakWithoutSpace)
_lineBreakWithoutSpaces = breakWithoutSpace; _lineBreakWithoutSpaces = breakWithoutSpace;
// need to align text again // need to align text again
alignText(); if(_currentUTF16String)
{
resetCurrentString();
alignText();
}
} }
} }
@ -294,12 +428,12 @@ float Label::getScaleX() const
} }
void Label::alignText() void Label::alignText()
{ {
if(_textureAtlas) if(_textureAtlas)
_textureAtlas->removeAllQuads(); _textureAtlas->removeAllQuads();
_fontAtlas->prepareLetterDefinitions(_currentUTF16String); _fontAtlas->prepareLetterDefinitions(_currentUTF16String);
LabelTextFormatter::createStringSprites(this); LabelTextFormatter::createStringSprites(this);
if(_multilineEnable && LabelTextFormatter::multilineText(this) ) if(_width > 0 && LabelTextFormatter::multilineText(this) )
LabelTextFormatter::createStringSprites(this); LabelTextFormatter::createStringSprites(this);
LabelTextFormatter::alignText(this); LabelTextFormatter::alignText(this);
@ -337,20 +471,22 @@ void Label::alignText()
insertQuadFromSprite(_reusedLetter,vaildIndex++); insertQuadFromSprite(_reusedLetter,vaildIndex++);
} }
} }
updateColor();
} }
bool Label::computeAdvancesForString(unsigned short int *stringToRender) bool Label::computeHorizontalKernings(unsigned short int *stringToRender)
{ {
if (_advances) if (_horizontalKernings)
{ {
delete [] _advances; delete [] _horizontalKernings;
_advances = 0; _horizontalKernings = 0;
} }
int letterCount = 0; int letterCount = 0;
_advances = _fontAtlas->getFont()->getAdvancesForTextUTF16(stringToRender, letterCount); _horizontalKernings = _fontAtlas->getFont()->getHorizontalKerningForTextUTF16(stringToRender, letterCount);
if(!_advances) if(!_horizontalKernings)
return false; return false;
else else
return true; return true;
@ -384,7 +520,7 @@ bool Label::setCurrentString(unsigned short *stringToSet)
// //
_currentUTF16String = stringToSet; _currentUTF16String = stringToSet;
// compute the advances // compute the advances
return computeAdvancesForString(stringToSet); return computeHorizontalKernings(stringToSet);
} }
void Label::resetCurrentString() void Label::resetCurrentString()
@ -423,10 +559,8 @@ Sprite * Label::updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, const F
SpriteFrame *frame = SpriteFrame::createWithTexture(theTexture, uvRect); SpriteFrame *frame = SpriteFrame::createWithTexture(theTexture, uvRect);
if (frame) if (frame)
{ {
spriteToUpdate->setBatchNode(this); spriteToUpdate->setBatchNode(this);
spriteToUpdate->setTexture(theTexture); spriteToUpdate->setSpriteFrame(frame);
spriteToUpdate->setSpriteFrame(frame);
spriteToUpdate->setAnchorPoint(Point(theDefinition.anchorX, theDefinition.anchorY));
} }
return spriteToUpdate; return spriteToUpdate;
@ -531,7 +665,7 @@ void Label::onDraw()
void Label::draw() void Label::draw()
{ {
_customCommand.init(0, _vertexZ); _customCommand.init(_globalZOrder);
_customCommand.func = CC_CALLBACK_0(Label::onDraw, this); _customCommand.func = CC_CALLBACK_0(Label::onDraw, this);
Director::getInstance()->getRenderer()->addCommand(&_customCommand); Director::getInstance()->getRenderer()->addCommand(&_customCommand);
} }
@ -557,8 +691,8 @@ Sprite * Label::getLetter(int ID)
sp = Sprite::createWithTexture(&_fontAtlas->getTexture(_lettersInfo[ID].def.textureID),uvRect); sp = Sprite::createWithTexture(&_fontAtlas->getTexture(_lettersInfo[ID].def.textureID),uvRect);
sp->setBatchNode(this); sp->setBatchNode(this);
sp->setAnchorPoint(Point(_lettersInfo[ID].def.anchorX, _lettersInfo[ID].def.anchorY)); sp->setAnchorPoint(Point::ANCHOR_MIDDLE);
sp->setPosition(_lettersInfo[ID].position); sp->setPosition(Point(_lettersInfo[ID].position.x+uvRect.size.width/2,_lettersInfo[ID].position.y-uvRect.size.height/2));
sp->setOpacity(_realOpacity); sp->setOpacity(_realOpacity);
this->addSpriteWithoutQuad(sp, ID, ID); this->addSpriteWithoutQuad(sp, ID, ID);
@ -569,75 +703,19 @@ Sprite * Label::getLetter(int ID)
return nullptr; return nullptr;
} }
float Label::getLetterPosXLeft( int index ) const
{
return _lettersInfo[index].position.x * _scaleX - (_lettersInfo[index].contentSize.width * _scaleX * _lettersInfo[index].def.anchorX);
}
float Label::getLetterPosXRight( int index ) const
{
return _lettersInfo[index].position.x * _scaleX + (_lettersInfo[index].contentSize.width * _scaleX * _lettersInfo[index].def.anchorX);
}
int Label::getCommonLineHeight() const int Label::getCommonLineHeight() const
{ {
return _commonLineHeight; return _commonLineHeight;
} }
int Label::getKerningForCharsPair(unsigned short first, unsigned short second) const
{
return 0;
}
int Label::getXOffsetForChar(unsigned short c) const
{
FontLetterDefinition tempDefinition;
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition);
if (!validDefinition)
return -1;
return (tempDefinition.offsetX);
}
int Label::getYOffsetForChar(unsigned short c) const
{
FontLetterDefinition tempDefinition;
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition);
if (!validDefinition)
return -1;
return (tempDefinition.offsetY);
}
int Label::getAdvanceForChar(unsigned short c, int hintPositionInString) const
{
if (_advances)
{
// not that advance contains the X offset already
FontLetterDefinition tempDefinition;
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition);
if (!validDefinition)
return -1;
return (_advances[hintPositionInString].width);
}
else
{
return -1;
}
}
Rect Label::getRectForChar(unsigned short c) const
{
return _fontAtlas->getFont()->getRectForChar(c);
}
// string related stuff // string related stuff
int Label::getStringNumLines() const int Label::getStringNumLines() const
{ {
int quantityOfLines = 1; int quantityOfLines = 1;
unsigned int stringLen = _currentUTF16String ? cc_wcslen(_currentUTF16String) : 0; unsigned int stringLen = _currentUTF16String ? cc_wcslen(_currentUTF16String) : -1;
if (stringLen < 1)
return stringLen;
if (stringLen == 0) if (stringLen == 0)
return (-1); return (-1);
@ -659,17 +737,12 @@ int Label::getStringLenght() const
return _currentUTF16String ? cc_wcslen(_currentUTF16String) : 0; return _currentUTF16String ? cc_wcslen(_currentUTF16String) : 0;
} }
unsigned short Label::getCharAtStringPosition(int position) const unsigned short * Label::getUTF16String() const
{
return _currentUTF16String[position];
}
unsigned short * Label::getUTF8String() const
{ {
return _currentUTF16String; return _currentUTF16String;
} }
void Label::assignNewUTF8String(unsigned short *newString) void Label::assignNewUTF16String(unsigned short *newString)
{ {
setCurrentString(newString); setCurrentString(newString);
} }
@ -690,17 +763,6 @@ bool Label::breakLineWithoutSpace() const
return _lineBreakWithoutSpaces; return _lineBreakWithoutSpaces;
} }
Size Label::getLabelContentSize() const
{
return getContentSize();
}
void Label::setLabelContentSize(const Size &newSize)
{
setContentSize(newSize);
}
// RGBA protocol // RGBA protocol

View File

@ -28,9 +28,9 @@
#define _COCOS2D_CCLABEL_H_ #define _COCOS2D_CCLABEL_H_
#include "CCSpriteBatchNode.h" #include "CCSpriteBatchNode.h"
#include "CCLabelTextFormatProtocol.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "renderer/CCCustomCommand.h" #include "renderer/CCCustomCommand.h"
#include "CCFontAtlas.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -50,27 +50,59 @@ enum class LabelEffect {
GLOW GLOW
}; };
//fwd struct LetterInfo
struct FontLetterDefinition; {
class FontAtlas; FontLetterDefinition def;
Point position;
Size contentSize;
};
typedef struct _ttfConfig
{
std::string fontFilePath;
int fontSize;
GlyphCollection glyphs;
const char *customGlyphs;
bool distanceFieldEnabled;
class CC_DLL Label : public SpriteBatchNode, public LabelProtocol, public LabelTextFormatProtocol _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: 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);
static Label* createWithBMFont(const std::string& label, const std::string& bmfontFilePath, TextHAlignment alignment = TextHAlignment::CENTER, int lineSize = 0);
bool setText(const std::string& stringToRender, float lineWidth, TextHAlignment alignment = TextHAlignment::LEFT, bool lineBreakWithoutSpaces = false);
CC_DEPRECATED_ATTRIBUTE static Label* createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize = 0, TextHAlignment alignment = TextHAlignment::LEFT, GlyphCollection glyphs = GlyphCollection::NEHE, const char *customGlyphs = 0, bool useDistanceField = false);
static Label* createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment alignment = TextHAlignment::LEFT, int lineWidth = 0);
static Label* createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& alignment = TextHAlignment::LEFT, int lineWidth = 0);
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);
virtual void setString(const std::string& text) override;
//only support for TTF
void setLabelEffect(LabelEffect effect,const Color3B& effectColor); 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 setAlignment(TextHAlignment alignment);
virtual void setWidth(float width); virtual void setWidth(float width);
virtual void setLineBreakWithoutSpace(bool breakWithoutSpace); virtual void setLineBreakWithoutSpace(bool breakWithoutSpace);
@ -85,56 +117,49 @@ public:
virtual void setColor(const Color3B& color) override; virtual void setColor(const Color3B& color) override;
// CCLabelTextFormat protocol implementation // CCLabelTextFormat protocol implementation
virtual std::vector<LetterInfo> *getLettersInfo() override { return &_lettersInfo; }; virtual std::vector<LetterInfo> *getLettersInfo() { return &_lettersInfo; };
virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex) override; virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex);
virtual bool recordPlaceholderInfo(int spriteIndex) override; virtual bool recordPlaceholderInfo(int spriteIndex);
virtual float getLetterPosXLeft( int index ) const override;
virtual float getLetterPosXRight( int index ) const override;
virtual Sprite * getLetter(int ID) override; virtual Sprite * getLetter(int ID);
// font related stuff // font related stuff
virtual int getCommonLineHeight() const override; virtual int getCommonLineHeight() const;
virtual int getKerningForCharsPair(unsigned short first, unsigned short second) const override; virtual int* getKernings() const { return _horizontalKernings;}
virtual int getXOffsetForChar(unsigned short c) const override;
virtual int getYOffsetForChar(unsigned short c) const override;
virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const override;
virtual Rect getRectForChar(unsigned short c) const override;
// string related stuff // string related stuff
virtual int getStringNumLines() const override; virtual int getStringNumLines() const;
virtual int getStringLenght() const override; virtual int getStringLenght() const;
virtual unsigned short getCharAtStringPosition(int position) const override; virtual unsigned short * getUTF16String() const;
virtual unsigned short * getUTF8String() const override; virtual void assignNewUTF16String(unsigned short *newString);
virtual void assignNewUTF8String(unsigned short *newString) override; virtual TextHAlignment getTextAlignment() const;
virtual TextHAlignment getTextAlignment() const override;
// label related stuff // label related stuff
virtual float getMaxLineWidth() const override; virtual float getMaxLineWidth() const;
virtual bool breakLineWithoutSpace() const override; virtual bool breakLineWithoutSpace() const;
virtual Size getLabelContentSize() const override;
virtual void setLabelContentSize(const Size &newSize) override;
// carloX // carloX
virtual const std::string& getString() const override { static std::string _ret("not implemented"); return _ret; } virtual const std::string& getString() const override { return _originalUTF8String; }
void addChild(Node * child, int zOrder=0, int tag=0) override; void addChild(Node * child, int zOrder=0, int tag=0) override;
virtual std::string getDescription() const override; virtual std::string getDescription() const override;
virtual void draw(void) override; virtual void draw(void) override;
virtual void onDraw(); virtual void onDraw();
virtual FontAtlas* getFontAtlas() const {return _fontAtlas;}
private: private:
/** /**
* @js NA * @js NA
*/ */
Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField = false,bool useA8Shader = false); Label(FontAtlas *atlas = nullptr, TextHAlignment alignment = TextHAlignment::LEFT, bool useDistanceField = false,bool useA8Shader = false);
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
~Label(); ~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); void setFontSize(int fontSize);
@ -142,7 +167,7 @@ private:
void alignText(); void alignText();
bool computeAdvancesForString(unsigned short int *stringToRender); bool computeHorizontalKernings(unsigned short int *stringToRender);
bool setCurrentString(unsigned short *stringToSet); bool setCurrentString(unsigned short *stringToSet);
bool setOriginalString(unsigned short *stringToSet); bool setOriginalString(unsigned short *stringToSet);
void resetCurrentString(); void resetCurrentString();
@ -151,32 +176,31 @@ private:
virtual void updateColor() override; virtual void updateColor() override;
//! used for optimization //! used for optimization
Sprite *_reusedLetter; Sprite *_reusedLetter;
std::vector<LetterInfo> _lettersInfo; 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;
bool _useDistanceField; float _commonLineHeight;
bool _useA8Shader; bool _lineBreakWithoutSpaces;
int _fontSize; float _width;
TextHAlignment _alignment;
unsigned short int * _currentUTF16String;
unsigned short int * _originalUTF16String;
std::string _originalUTF8String;
int * _horizontalKernings;
FontAtlas * _fontAtlas;
bool _isOpacityModifyRGB;
LabelEffect _currLabelEffect; bool _useDistanceField;
Color3B _effectColor; bool _useA8Shader;
int _fontSize;
GLuint _uniformEffectColor; LabelEffect _currLabelEffect;
Color3B _effectColor;
CustomCommand _customCommand; GLuint _uniformEffectColor;
CustomCommand _customCommand;
}; };

View File

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

View File

@ -1,82 +0,0 @@
/****************************************************************************
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 _CCLabelTextFormatProtocol_h_
#define _CCLabelTextFormatProtocol_h_
#include "CCFontAtlas.h"
#include <vector>
NS_CC_BEGIN
struct LetterInfo
{
FontLetterDefinition def;
Point position;
Size contentSize;
bool visible;
};
class CC_DLL LabelTextFormatProtocol
{
public:
virtual ~LabelTextFormatProtocol() {}
virtual bool recordLetterInfo(const cocos2d::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;
// font related stuff
virtual int getCommonLineHeight() const = 0;
virtual int getKerningForCharsPair(unsigned short first, unsigned short second) const = 0;
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;
// string related stuff
virtual int getStringNumLines() const = 0;
virtual int getStringLenght() const = 0;
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;
// label related stuff
virtual float getMaxLineWidth() const = 0;
virtual bool breakLineWithoutSpace() const = 0;
virtual cocos2d::Size getLabelContentSize() const = 0;
virtual void setLabelContentSize(const Size &newSize) = 0;
};
NS_CC_END
#endif

View File

@ -25,76 +25,53 @@
#include <vector> #include <vector>
#include "cocos2d.h"
#include "ccUTF8.h" #include "ccUTF8.h"
#include "CCLabelTextFormatter.h" #include "CCLabelTextFormatter.h"
#include "CCDirector.h"
#include "CCLabel.h"
using namespace std; using namespace std;
NS_CC_BEGIN NS_CC_BEGIN
bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel) bool LabelTextFormatter::multilineText(Label *theLabel)
{ {
// to do if (m_fWidth > 0) int strLen = theLabel->getStringLenght();
if (theLabel->getMaxLineWidth()) auto strWhole = theLabel->getUTF16String();
{
// Step 1: Make multiline
vector<unsigned short> strWhole = cc_utf16_vec_from_utf16_str(theLabel->getUTF8String());
size_t stringLength = strWhole.size();
vector<unsigned short> multiline_string;
multiline_string.reserve( stringLength );
vector<unsigned short> last_word;
last_word.reserve( stringLength );
unsigned int line = 1, i = 0;
bool isStartOfLine = false, isStartOfWord = false;
float startOfLine = -1, startOfWord = -1;
int skip = 0;
int strLen = theLabel->getStringLenght();
std::vector<LetterInfo> *leterInfo = theLabel->getLettersInfo();
int tIndex = 0;
for (int j = 0; j+skip < strLen; j++) vector<unsigned short> multiline_string;
{ multiline_string.reserve( strLen );
LetterInfo* info = &leterInfo->at(j+skip);
unsigned int justSkipped = 0; vector<unsigned short> last_word;
last_word.reserve( strLen );
while (info->def.validDefinition == false)
{ unsigned int line = 1;
justSkipped++;
info = &leterInfo->at( j+skip+justSkipped ); bool isStartOfLine = false, isStartOfWord = false;
} float startOfLine = -1, startOfWord = -1;
skip += justSkipped;
tIndex = j + skip; int skip = 0;
if (i >= stringLength) std::vector<LetterInfo> *leterInfo = theLabel->getLettersInfo();
break; int tIndex = 0;
float scalsX = theLabel->getScaleX();
unsigned short character = strWhole[i]; float lineWidth = theLabel->getMaxLineWidth();
bool breakLineWithoutSpace = theLabel->breakLineWithoutSpace();
if (!isStartOfWord)
{ for (int j = 0; j+skip < strLen; j++)
startOfWord = theLabel->getLetterPosXLeft( tIndex ); {
isStartOfWord = true; LetterInfo* info = &leterInfo->at(j+skip);
}
unsigned int justSkipped = 0;
if (!isStartOfLine)
{ while (info->def.validDefinition == false)
startOfLine = startOfWord; {
isStartOfLine = true; justSkipped++;
} tIndex = j+skip+justSkipped;
if (strWhole[tIndex-1] == '\n')
// Newline.
if (character == '\n')
{ {
cc_utf8_trim_ws(&last_word); cc_utf8_trim_ws(&last_word);
last_word.push_back('\n'); last_word.push_back('\n');
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end()); multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
last_word.clear(); last_word.clear();
@ -102,133 +79,119 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel)
isStartOfLine = false; isStartOfLine = false;
startOfWord = -1; startOfWord = -1;
startOfLine = -1; startOfLine = -1;
i += justSkipped;
++line; ++line;
if (i >= stringLength)
break;
character = strWhole[i];
if (!startOfWord)
{
startOfWord = theLabel->getLetterPosXLeft( tIndex );
isStartOfWord = true;
}
if (!startOfLine)
{
startOfLine = startOfWord;
isStartOfLine = true;
}
} }
if(tIndex < strLen)
// Whitespace. {
if (isspace_unicode(character)) info = &leterInfo->at( tIndex );
}
else
break;
}
skip += justSkipped;
tIndex = j + skip;
if (tIndex >= strLen)
break;
unsigned short character = strWhole[tIndex];
if (!isStartOfWord)
{
startOfWord = info->position.x * scalsX;
isStartOfWord = true;
}
if (!isStartOfLine)
{
startOfLine = startOfWord;
isStartOfLine = true;
}
// Whitespace.
if (isspace_unicode(character))
{
last_word.push_back(character);
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
last_word.clear();
isStartOfWord = false;
startOfWord = -1;
continue;
}
float posRight = (info->position.x + info->contentSize.width) * scalsX;
// Out of bounds.
if (posRight - startOfLine > lineWidth)
{
if (!breakLineWithoutSpace)
{ {
last_word.push_back(character); last_word.push_back(character);
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
last_word.clear(); int found = cc_utf8_find_last_not_char(multiline_string, ' ');
isStartOfWord = false; if (found != -1)
startOfWord = -1; cc_utf8_trim_ws(&multiline_string);
++i;
continue;
}
// Out of bounds.
if (theLabel->getLetterPosXRight( tIndex ) - startOfLine > theLabel->getMaxLineWidth())
{
if (!theLabel->breakLineWithoutSpace())
{
last_word.push_back(character);
int found = cc_utf8_find_last_not_char(multiline_string, ' ');
if (found != -1)
cc_utf8_trim_ws(&multiline_string);
else
multiline_string.clear();
if (multiline_string.size() > 0)
multiline_string.push_back('\n');
++line;
isStartOfLine = false;
startOfLine = -1;
++i;
}
else else
{ multiline_string.clear();
cc_utf8_trim_ws(&last_word);
if (multiline_string.size() > 0)
last_word.push_back('\n'); multiline_string.push_back('\n');
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
last_word.clear(); ++line;
isStartOfWord = false; isStartOfLine = false;
isStartOfLine = false; startOfLine = -1;
startOfWord = -1;
startOfLine = -1;
++line;
if (i >= stringLength)
break;
if (!startOfWord)
{
startOfWord = theLabel->getLetterPosXLeft( tIndex );
isStartOfWord = true;
}
if (!startOfLine)
{
startOfLine = startOfWord;
isStartOfLine = true;
}
--j;
}
continue;
} }
else else
{ {
// Character is normal. cc_utf8_trim_ws(&last_word);
last_word.push_back(character);
++i; last_word.push_back('\n');
continue; multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
last_word.clear();
isStartOfWord = false;
isStartOfLine = false;
startOfWord = -1;
startOfLine = -1;
++line;
--j;
} }
} }
else
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
size_t size = multiline_string.size();
unsigned short* strNew = new unsigned short[size + 1];
for (size_t j = 0; j < size; ++j)
{ {
strNew[j] = multiline_string[j]; // Character is normal.
last_word.push_back(character);
} }
strNew[size] = 0;
theLabel->assignNewUTF8String(strNew);
return true;
} }
else
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
size_t size = multiline_string.size();
unsigned short* strNew = new unsigned short[size + 1];
for (size_t j = 0; j < size; ++j)
{ {
return false; strNew[j] = multiline_string[j];
} }
strNew[size] = 0;
theLabel->assignNewUTF16String(strNew);
return true;
} }
bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel) bool LabelTextFormatter::alignText(Label *theLabel)
{ {
int i = 0; int i = 0;
int lineNumber = 0; int lineNumber = 0;
int strLen = cc_wcslen(theLabel->getUTF8String()); int strLen = cc_wcslen(theLabel->getUTF16String());
vector<unsigned short> lastLine; vector<unsigned short> lastLine;
std::vector<LetterInfo> *leterInfo = theLabel->getLettersInfo(); std::vector<LetterInfo> *leterInfo = theLabel->getLettersInfo();
auto strWhole = theLabel->getUTF16String();
for (int ctr = 0; ctr <= strLen; ++ctr) for (int ctr = 0; ctr <= strLen; ++ctr)
{ {
unsigned short int currentChar = theLabel->getCharAtStringPosition(ctr); unsigned short currentChar = strWhole[ctr];
if (currentChar == '\n' || currentChar == 0) if (currentChar == '\n' || currentChar == 0)
{ {
float lineWidth = 0.0f; float lineWidth = 0.0f;
@ -241,23 +204,21 @@ bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel)
continue; continue;
} }
int index = static_cast<int>(i + lineLength - 1 + lineNumber); int index = static_cast<int>(i + lineLength - 1 + lineNumber);
if(currentChar == 0)
index -= 1;
if (index < 0) continue; if (index < 0) continue;
LetterInfo* info = &leterInfo->at( index ); LetterInfo* info = &leterInfo->at( index );
if(info->def.validDefinition == false) if(info->def.validDefinition == false)
continue; continue;
lineWidth = info->position.x + info->contentSize.width /2.0f; lineWidth = info->position.x + info->contentSize.width;
float shift = 0; float shift = 0;
switch (theLabel->getTextAlignment()) switch (theLabel->getTextAlignment())
{ {
case TextHAlignment::CENTER: case TextHAlignment::CENTER:
shift = theLabel->getLabelContentSize().width/2.0f - lineWidth/2.0f; shift = theLabel->getContentSize().width/2.0f - lineWidth/2.0f;
break; break;
case TextHAlignment::RIGHT: case TextHAlignment::RIGHT:
shift = theLabel->getLabelContentSize().width - lineWidth; shift = theLabel->getContentSize().width - lineWidth;
break; break;
default: default:
break; break;
@ -273,7 +234,7 @@ bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel)
info = &leterInfo->at( index ); info = &leterInfo->at( index );
if(info) if(info)
{ {
info->position = info->position + Point(shift, 0.0f); info->position.x += shift;
} }
} }
} }
@ -291,7 +252,7 @@ bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel)
return true; return true;
} }
bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel) bool LabelTextFormatter::createStringSprites(Label *theLabel)
{ {
// check for string // check for string
unsigned int stringLen = theLabel->getStringLenght(); unsigned int stringLen = theLabel->getStringLenght();
@ -305,37 +266,42 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel)
unsigned short prev = -1; unsigned short prev = -1;
Size tmpSize = Size::ZERO; Size tmpSize = Size::ZERO;
int longestLine = 0; int longestLine = 0;
unsigned int totalHeight = 0; unsigned int totalHeight = 0;
int quantityOfLines = theLabel->getStringNumLines(); int quantityOfLines = theLabel->getStringNumLines();
int commonLineHeight = theLabel->getCommonLineHeight(); int commonLineHeight = theLabel->getCommonLineHeight();
totalHeight = commonLineHeight * quantityOfLines; totalHeight = commonLineHeight * quantityOfLines;
nextFontPositionY = 0 - (commonLineHeight - totalHeight); nextFontPositionY = totalHeight;
Rect rect;
Rect charRect; Rect charRect;
int charXOffset = 0; int charXOffset = 0;
int charYOffset = 0; int charYOffset = 0;
int charAdvance = 0; int charAdvance = 0;
auto strWhole = theLabel->getUTF16String();
FontAtlas* fontAtlas = theLabel->getFontAtlas();
FontLetterDefinition tempDefinition;
auto kernings = theLabel->getKernings();
for (unsigned int i = 0; i < stringLen; i++) for (unsigned int i = 0; i < stringLen; i++)
{ {
// get the current character unsigned short c = strWhole[i];
unsigned short c = theLabel->getCharAtStringPosition(i); if (fontAtlas->getLetterDefinitionForChar(c, tempDefinition))
{
charXOffset = theLabel->getXOffsetForChar(c); charXOffset = tempDefinition.offsetX;
charYOffset = theLabel->getYOffsetForChar(c); charYOffset = tempDefinition.offsetY;
charAdvance = theLabel->getAdvanceForChar(c, i); charAdvance = tempDefinition.xAdvance;
charRect = theLabel->getRectForChar(c); }
else
int kerningAmount = theLabel->getKerningForCharsPair(prev, c); {
charXOffset = -1;
charYOffset = -1;
charAdvance = -1;
}
if (c == '\n') if (c == '\n')
{ {
@ -346,12 +312,8 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel)
continue; continue;
} }
// See issue 1343. cast( signed short + unsigned integer ) == unsigned integer (sign is lost!) Point fontPos = Point((float)nextFontPositionX + charXOffset + kernings[i],
int yOffset = commonLineHeight - charYOffset; (float)nextFontPositionY - charYOffset);
Point fontPos = Point((float)nextFontPositionX + charXOffset + charRect.size.width * 0.5f + kerningAmount,
(float)nextFontPositionY + yOffset - charRect.size.height * 0.5f);
if( theLabel->recordLetterInfo(CC_POINT_PIXELS_TO_POINTS(fontPos),c,i) == false) if( theLabel->recordLetterInfo(CC_POINT_PIXELS_TO_POINTS(fontPos),c,i) == false)
{ {
@ -360,7 +322,7 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel)
} }
// update kerning // update kerning
nextFontPositionX += charAdvance + kerningAmount; nextFontPositionX += charAdvance + kernings[i];
prev = c; prev = c;
if (longestLine < nextFontPositionX) if (longestLine < nextFontPositionX)
@ -369,12 +331,13 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel)
} }
} }
float lastCharWidth = tempDefinition.width * CC_CONTENT_SCALE_FACTOR();
// If the last character processed has an xAdvance which is less that the width of the characters image, then we need // If the last character processed has an xAdvance which is less that the width of the characters image, then we need
// to adjust the width of the string to take this into account, or the character will overlap the end of the bounding // to adjust the width of the string to take this into account, or the character will overlap the end of the bounding
// box // box
if (charAdvance < charRect.size.width) if(charAdvance < lastCharWidth)
{ {
tmpSize.width = longestLine + charRect.size.width - charAdvance; tmpSize.width = longestLine - charAdvance + lastCharWidth;
} }
else else
{ {
@ -382,7 +345,7 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel)
} }
tmpSize.height = totalHeight; tmpSize.height = totalHeight;
theLabel->setLabelContentSize(CC_SIZE_PIXELS_TO_POINTS(tmpSize)); theLabel->setContentSize(CC_SIZE_PIXELS_TO_POINTS(tmpSize));
return true; return true;
} }

View File

@ -26,17 +26,17 @@
#ifndef _CCLabelTextFormatter_h_ #ifndef _CCLabelTextFormatter_h_
#define _CCLabelTextFormatter_h_ #define _CCLabelTextFormatter_h_
#include "CCLabelTextFormatProtocol.h"
NS_CC_BEGIN NS_CC_BEGIN
class Label;
class CC_DLL LabelTextFormatter class CC_DLL LabelTextFormatter
{ {
public: public:
static bool multilineText(LabelTextFormatProtocol *theLabel); static bool multilineText(Label *theLabel);
static bool alignText(LabelTextFormatProtocol *theLabel); static bool alignText(Label *theLabel);
static bool createStringSprites(LabelTextFormatProtocol *theLabel); static bool createStringSprites(Label *theLabel);
}; };

View File

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

View File

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

View File

@ -64,29 +64,12 @@ THE SOFTWARE.
NS_CC_BEGIN NS_CC_BEGIN
#if CC_USE_ARRAY_VECTOR bool nodeComparisonLess(Node* n1, Node* n2)
bool nodeComparisonLess(const RCPtr<Object>& pp1, const RCPtr<Object>& pp2)
{ {
Object *p1 = static_cast<Object*>(pp1); return( n1->getLocalZOrder() < n2->getLocalZOrder() ||
Object *p2 = static_cast<Object*>(pp2); ( n1->getLocalZOrder() == n2->getLocalZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() )
Node *n1 = static_cast<Node*>(p1);
Node *n2 = static_cast<Node*>(p2);
return( n1->getZOrder() < n2->getZOrder() ||
( n1->getZOrder() == n2->getZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() )
); );
} }
#else
bool nodeComparisonLess(Object* p1, Object* p2)
{
Node *n1 = static_cast<Node*>(p1);
Node *n2 = static_cast<Node*>(p2);
return( n1->getZOrder() < n2->getZOrder() ||
( n1->getZOrder() == n2->getZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() )
);
}
#endif
// XXX: Yes, nodes might have a sort problem once every 15 days if the game runs at 60 FPS and each frame sprites are reordered. // XXX: Yes, nodes might have a sort problem once every 15 days if the game runs at 60 FPS and each frame sprites are reordered.
static int s_globalOrderOfArrival = 1; static int s_globalOrderOfArrival = 1;
@ -108,7 +91,8 @@ Node::Node(void)
, _inverseDirty(true) , _inverseDirty(true)
// children (lazy allocs) // children (lazy allocs)
// lazy alloc // lazy alloc
, _ZOrder(0) , _localZOrder(0)
, _globalZOrder(0)
, _parent(nullptr) , _parent(nullptr)
// "whole screen" objects. like Scenes and Layers, should set _ignoreAnchorPointForPosition to true // "whole screen" objects. like Scenes and Layers, should set _ignoreAnchorPointForPosition to true
, _tag(Node::INVALID_TAG) , _tag(Node::INVALID_TAG)
@ -212,32 +196,34 @@ void Node::setSkewY(float newSkewY)
_transformDirty = _inverseDirty = true; _transformDirty = _inverseDirty = true;
} }
/// zOrder getter
int Node::getZOrder() const
{
return _ZOrder;
}
/// zOrder setter : private method /// zOrder setter : private method
/// used internally to alter the zOrder variable. DON'T call this method manually /// 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) if (_parent)
{ {
_parent->reorderChild(this, z); _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); _eventDispatcher->setDirtyForNode(this);
} }
void Node::setGlobalZOrder(float globalZOrder)
{
if (_globalZOrder != globalZOrder)
{
_globalZOrder = globalZOrder;
_eventDispatcher->setDirtyForNode(this);
}
}
/// vertexZ getter /// vertexZ getter
float Node::getVertexZ() const float Node::getVertexZ() const
{ {
@ -246,9 +232,10 @@ float Node::getVertexZ() const
/// vertexZ setter /// vertexZ setter
void Node::setVertexZ(float var) void Node::setVertexZ(float zOrder)
{ {
_vertexZ = var; _vertexZ = zOrder;
setGlobalZOrder(zOrder);
} }
@ -650,7 +637,7 @@ void Node::addChild(Node *child, int zOrder)
void Node::addChild(Node *child) void Node::addChild(Node *child)
{ {
CCASSERT( child != nullptr, "Argument must be non-nil"); 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() void Node::removeFromParent()
@ -767,7 +754,7 @@ void Node::insertChild(Node* child, int z)
{ {
_reorderChildDirty = true; _reorderChildDirty = true;
_children.pushBack(child); _children.pushBack(child);
child->_setZOrder(z); child->_setLocalZOrder(z);
} }
void Node::reorderChild(Node *child, int zOrder) void Node::reorderChild(Node *child, int zOrder)
@ -775,7 +762,7 @@ void Node::reorderChild(Node *child, int zOrder)
CCASSERT( child != nullptr, "Child must be non-nil"); CCASSERT( child != nullptr, "Child must be non-nil");
_reorderChildDirty = true; _reorderChildDirty = true;
child->setOrderOfArrival(s_globalOrderOfArrival++); child->setOrderOfArrival(s_globalOrderOfArrival++);
child->_setZOrder(zOrder); child->_setLocalZOrder(zOrder);
} }
void Node::sortAllChildren() void Node::sortAllChildren()
@ -816,7 +803,7 @@ void Node::visit()
{ {
auto node = _children.at(i); auto node = _children.at(i);
if ( node && node->_ZOrder < 0 ) if ( node && node->_localZOrder < 0 )
node->visit(); node->visit();
else else
break; break;

View File

@ -1,9 +1,9 @@
/**************************************************************************** /****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2009 Valentin Milea Copyright (c) 2009 Valentin Milea
Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc. Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc. Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org http://www.cocos2d-x.org
@ -72,11 +72,7 @@ enum {
kNodeOnCleanup kNodeOnCleanup
}; };
#if CC_USE_ARRAY_VECTOR bool nodeComparisonLess(Node* n1, Node* n2);
bool nodeComparisonLess(const RCPtr<Object>& pp1, const RCPtr<Object>& pp2);
#else
bool nodeComparisonLess(Object* p1, Object* p2);
#endif
class EventListener; class EventListener;
@ -161,43 +157,72 @@ public:
/// @name Setters & Getters for Graphic Peroperties /// @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. LocalZOrder is the 'key' used to sort the node relative to its siblings.
*
* The Z order of node is relative to its siblings. The Node's parent will sort all its children based ont the LocalZOrder value.
* It is not related to the OpenGL's z property. This one only affects the draw order of itself and its siblings. 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.
* Lower Z order number are drawn before higher numbers.
* Please refer to `setVertexZ(float)` for the difference. 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
* @param zOrder Z order of this node. While Nodes with LocalZOder >=0 are the "right" subtree.
@see `setGlobalZOrder`
@see `setVertexZ`
*/ */
virtual void setZOrder(int zOrder); virtual void setLocalZOrder(int localZOrder);
/*
* Sets the z order which stands for the drawing order CC_DEPRECATED_ATTRIBUTE virtual void setZOrder(int localZOrder) { setLocalZOrder(localZOrder); }
* /* Helper function used by `setLocalZOrder`. Don't use it unless you know what you are doing.
* 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 _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 globalZOrder);
/**
* Returns the Node's Global Z Order.
* *
* Differences between openGL Z vertex and cocos2d Z order: * @see `setGlobalZOrder(int)`
* - 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`
* *
* @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. * @param vertexZ OpenGL Z vertex of this node.
*/ */
@ -506,11 +531,11 @@ public:
* A node which called addChild subsequently will take a larger arrival order, * A node which called addChild subsequently will take a larger arrival order,
* If two children have the same Z order, the child with larger arrival order will be drawn later. * If two children have the same Z order, the child with larger arrival order will be drawn later.
* *
* @warning This method is used internally for zOrder sorting, don't change this manually * @warning This method is used internally for localZOrder sorting, don't change this manually
* *
* @param orderOfArrival The arrival order. * @param orderOfArrival The arrival order.
*/ */
virtual void setOrderOfArrival(int orderOfArrival); void setOrderOfArrival(int orderOfArrival);
/** /**
* Returns the arrival order, indecates which children is added previously. * Returns the arrival order, indecates which children is added previously.
* *
@ -518,7 +543,7 @@ public:
* *
* @return The arrival order. * @return The arrival order.
*/ */
virtual int getOrderOfArrival() const; int getOrderOfArrival() const;
/** @deprecated No longer needed /** @deprecated No longer needed
@ -566,24 +591,24 @@ public:
*/ */
virtual void addChild(Node * child); virtual void addChild(Node * child);
/** /**
* Adds a child to the container with a z-order * Adds a child to the container with a local z-order
* *
* If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately.
* *
* @param child A child node * @param child A child node
* @param zOrder Z order for drawing priority. Please refer to setZOrder(int) * @param zOrder Z order for drawing priority. Please refer to `setLocalZOrder(int)`
*/ */
virtual void addChild(Node * child, int zOrder); virtual void addChild(Node * child, int localZOrder);
/** /**
* Adds a child to the container with z order and tag * Adds a child to the container with z order and tag
* *
* If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately.
* *
* @param child A child node * @param child A child node
* @param zOrder Z order for drawing priority. Please refer to setZOrder(int) * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int)
* @param tag A interger to identify the node easily. Please refer to setTag(int) * @param tag A interger to identify the node easily. Please refer to setTag(int)
*/ */
virtual void addChild(Node* child, int zOrder, int tag); virtual void addChild(Node* child, int localZOrder, int tag);
/** /**
* Gets a child from the container with its tag * Gets a child from the container with its tag
* *
@ -686,9 +711,9 @@ public:
* Reorders a child according to a new z value. * Reorders a child according to a new z value.
* *
* @param child An already added child node. It MUST be already added. * @param child An already added child node. It MUST be already added.
* @param zOrder Z order for drawing priority. Please refer to setZOrder(int) * @param localZOrder Z order for drawing priority. Please refer to setLocalZOrder(int)
*/ */
virtual void reorderChild(Node * child, int zOrder); virtual void reorderChild(Node * child, int localZOrder);
/** /**
* Sorts the children array once before drawing, instead of every time when a child is added or reordered. * Sorts the children array once before drawing, instead of every time when a child is added or reordered.
@ -1411,7 +1436,6 @@ protected:
float _scaleX; ///< scaling factor on x-axis float _scaleX; ///< scaling factor on x-axis
float _scaleY; ///< scaling factor on y-axis float _scaleY; ///< scaling factor on y-axis
float _vertexZ; ///< OpenGL real Z vertex
Point _position; ///< position of the node Point _position; ///< position of the node
@ -1433,8 +1457,12 @@ protected:
mutable bool _transformDirty; ///< transform dirty flag mutable bool _transformDirty; ///< transform dirty flag
mutable bool _inverseDirty; ///< inverse 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 Vector<Node*> _children; ///< array of children nodes
Node *_parent; ///< weak reference to parent node Node *_parent; ///< weak reference to parent node
@ -1445,7 +1473,7 @@ protected:
GLProgram *_shaderProgram; ///< OpenGL shader GLProgram *_shaderProgram; ///< OpenGL shader
int _orderOfArrival; ///< used to preserve sequence while sorting children with the same zOrder int _orderOfArrival; ///< used to preserve sequence while sorting children with the same localZOrder
Scheduler *_scheduler; ///< scheduler used to schedule timers and updates Scheduler *_scheduler; ///< scheduler used to schedule timers and updates

View File

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

View File

@ -100,9 +100,9 @@ void ParallaxNode::addChild(Node *child, int z, const Point& ratio, const Point&
obj->setChild(child); obj->setChild(child);
ccArrayAppendObjectWithResize(_parallaxArray, (Object*)obj); ccArrayAppendObjectWithResize(_parallaxArray, (Object*)obj);
Point pos = _position; Point pos = this->absolutePosition();
pos.x = pos.x * ratio.x + offset.x; pos.x = -pos.x + pos.x * ratio.x + offset.x;
pos.y = pos.y * ratio.y + offset.y; pos.y = -pos.y + pos.y * ratio.y + offset.y;
child->setPosition(pos); child->setPosition(pos);
Node::addChild(child, z, child->getTag()); Node::addChild(child, z, child->getTag());

View File

@ -44,7 +44,7 @@
#include "kazmath/GL/matrix.h" #include "kazmath/GL/matrix.h"
#include "CCProfiling.h" #include "CCProfiling.h"
#include "renderer/CCQuadCommand.h" #include "renderer/CCQuadCommand.h"
#include "CCRenderer.h" #include "renderer/CCRenderer.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -197,7 +197,7 @@ int ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag)
_children.insert(pos, child); _children.insert(pos, child);
child->setTag(aTag); child->setTag(aTag);
child->_setZOrder(z); child->_setLocalZOrder(z);
child->setParent(this); child->setParent(this);
@ -218,7 +218,7 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder)
ParticleSystem* child = static_cast<ParticleSystem*>(aChild); ParticleSystem* child = static_cast<ParticleSystem*>(aChild);
if( zOrder == child->getZOrder() ) if( zOrder == child->getLocalZOrder() )
{ {
return; return;
} }
@ -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) void ParticleBatchNode::getCurrentIndex(int* oldIndex, int* newIndex, Node* child, int z)
@ -280,7 +280,7 @@ void ParticleBatchNode::getCurrentIndex(int* oldIndex, int* newIndex, Node* chil
Node* pNode = _children.at(i); Node* pNode = _children.at(i);
// new index // new index
if( pNode->getZOrder() > z && ! foundNewIdx ) if( pNode->getLocalZOrder() > z && ! foundNewIdx )
{ {
*newIndex = i; *newIndex = i;
foundNewIdx = true; foundNewIdx = true;
@ -325,7 +325,7 @@ int ParticleBatchNode::searchNewPositionInChildrenForZ(int z)
for( int i=0; i < count; i++ ) for( int i=0; i < count; i++ )
{ {
Node *child = _children.at(i); Node *child = _children.at(i);
if (child->getZOrder() > z) if (child->getLocalZOrder() > z)
{ {
return i; return i;
} }
@ -382,26 +382,13 @@ void ParticleBatchNode::draw(void)
return; return;
} }
// CC_NODE_DRAW_SETUP(); _batchCommand.init(
// _globalZOrder,
// GL::blendFunc( _blendFunc.src, _blendFunc.dst ); _shaderProgram,
// _blendFunc,
// _textureAtlas->drawQuads(); _textureAtlas,
_modelViewTransform);
auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP); Director::getInstance()->getRenderer()->addCommand(&_batchCommand);
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);
CC_PROFILER_STOP("CCParticleBatchNode - draw"); CC_PROFILER_STOP("CCParticleBatchNode - draw");
} }

View File

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

View File

@ -38,9 +38,9 @@ THE SOFTWARE.
#include "TransformUtils.h" #include "TransformUtils.h"
#include "CCEventType.h" #include "CCEventType.h"
#include "CCConfiguration.h" #include "CCConfiguration.h"
#include "CCRenderer.h" #include "renderer/CCRenderer.h"
#include "renderer/CCQuadCommand.h" #include "renderer/CCQuadCommand.h"
#include "CCCustomCommand.h" #include "renderer/CCCustomCommand.h"
// extern // extern
#include "kazmath/GL/matrix.h" #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); 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); Director::getInstance()->getRenderer()->addCommand(&_quadCommand);
} }

View File

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

View File

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

View File

@ -290,7 +290,7 @@ void ShaderCache::loadDefaultShader(GLProgram *p, int type)
break; break;
case kShaderType_PositionTextureColorAlphaTest: case kShaderType_PositionTextureColorAlphaTest:
p->initWithVertexShaderByteArray(ccPositionTextureColor_noMVP_vert, ccPositionTextureColorAlphaTest_frag); p->initWithVertexShaderByteArray(ccPositionTextureColor_vert, ccPositionTextureColorAlphaTest_frag);
p->addAttribute(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION); p->addAttribute(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION);
p->addAttribute(GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR); p->addAttribute(GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR);

View File

@ -45,9 +45,9 @@ THE SOFTWARE.
#include "CCAffineTransform.h" #include "CCAffineTransform.h"
#include "TransformUtils.h" #include "TransformUtils.h"
#include "CCProfiling.h" #include "CCProfiling.h"
#include "CCRenderer.h" #include "renderer/CCRenderer.h"
#include "renderer/CCQuadCommand.h" #include "renderer/CCQuadCommand.h"
#include "CCFrustum.h" #include "renderer/CCFrustum.h"
// external // external
#include "kazmath/GL/matrix.h" #include "kazmath/GL/matrix.h"
@ -242,9 +242,7 @@ bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect, bool rotated)
// zwoptex default values // zwoptex default values
_offsetPosition = Point::ZERO; _offsetPosition = Point::ZERO;
_hasChildren = false;
// clean the Quad // clean the Quad
memset(&_quad, 0, sizeof(_quad)); memset(&_quad, 0, sizeof(_quad));
@ -672,7 +670,7 @@ void Sprite::updateTransform(void)
void Sprite::draw(void) void Sprite::draw(void)
{ {
//TODO implement z order //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()) // 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 //CCNode already sets isReorderChildDirty_ so this needs to be after batchNode check
Node::addChild(child, zOrder, tag); Node::addChild(child, zOrder, tag);
_hasChildren = true;
} }
void Sprite::reorderChild(Node *child, int zOrder) void Sprite::reorderChild(Node *child, int zOrder)
{ {
CCASSERT(child != nullptr, ""); CCASSERT(child != nullptr, "child must be non null");
CCASSERT(_children.contains(child), ""); CCASSERT(_children.contains(child), "child does not belong to this");
if (zOrder == child->getZOrder())
{
return;
}
if( _batchNode && ! _reorderChildDirty) if( _batchNode && ! _reorderChildDirty)
{ {
@ -813,8 +805,6 @@ void Sprite::removeAllChildrenWithCleanup(bool cleanup)
} }
Node::removeAllChildrenWithCleanup(cleanup); Node::removeAllChildrenWithCleanup(cleanup);
_hasChildren = false;
} }
void Sprite::sortAllChildren() void Sprite::sortAllChildren()
@ -832,8 +822,8 @@ void Sprite::sortAllChildren()
auto tempJ = static_cast<Node*>( _children->getObjectAtIndex(j) ); auto tempJ = static_cast<Node*>( _children->getObjectAtIndex(j) );
//continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
while(j>=0 && ( tempI->getZOrder() < tempJ->getZOrder() || while(j>=0 && ( tempI->getLocalZOrder() < tempJ->getLocalZOrder() ||
( tempI->getZOrder() == tempJ->getZOrder() && ( tempI->getLocalZOrder() == tempJ->getLocalZOrder() &&
tempI->getOrderOfArrival() < tempJ->getOrderOfArrival() ) ) ) tempI->getOrderOfArrival() < tempJ->getOrderOfArrival() ) ) )
{ {
_children->fastSetObject( tempJ, j+1 ); _children->fastSetObject( tempJ, j+1 );
@ -882,27 +872,24 @@ void Sprite::setDirtyRecursively(bool bValue)
{ {
_recursiveDirty = bValue; _recursiveDirty = bValue;
setDirty(bValue); setDirty(bValue);
// recursively set dirty
if (_hasChildren) for(const auto &child: _children) {
{ Sprite* sp = dynamic_cast<Sprite*>(child);
for(const auto &child: _children) { if (sp)
Sprite* sp = dynamic_cast<Sprite*>(child); {
if (sp) sp->setDirtyRecursively(true);
{
sp->setDirtyRecursively(true);
}
} }
} }
} }
// XXX HACK: optimization // XXX HACK: optimization
#define SET_DIRTY_RECURSIVELY() { \ #define SET_DIRTY_RECURSIVELY() { \
if (! _recursiveDirty) { \ if (! _recursiveDirty) { \
_recursiveDirty = true; \ _recursiveDirty = true; \
setDirty(true); \ setDirty(true); \
if ( _hasChildren) \ if (!_children.empty()) \
setDirtyRecursively(true); \ setDirtyRecursively(true); \
} \ } \
} }
void Sprite::setPosition(const Point& pos) void Sprite::setPosition(const Point& pos)

View File

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

View File

@ -43,7 +43,7 @@ THE SOFTWARE.
#include "CCProfiling.h" #include "CCProfiling.h"
#include "CCLayer.h" #include "CCLayer.h"
#include "CCScene.h" #include "CCScene.h"
#include "CCRenderer.h" #include "renderer/CCRenderer.h"
#include "renderer/CCQuadCommand.h" #include "renderer/CCQuadCommand.h"
// external // external
#include "kazmath/GL/matrix.h" #include "kazmath/GL/matrix.h"
@ -99,7 +99,7 @@ bool SpriteBatchNode::initWithTexture(Texture2D *tex, ssize_t capacity)
_descendants.reserve(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; return true;
} }
@ -179,7 +179,7 @@ void SpriteBatchNode::reorderChild(Node *child, int zOrder)
CCASSERT(child != nullptr, "the child should not be null"); CCASSERT(child != nullptr, "the child should not be null");
CCASSERT(_children.contains(child), "Child doesn't belong to Sprite"); CCASSERT(_children.contains(child), "Child doesn't belong to Sprite");
if (zOrder == child->getZOrder()) if (zOrder == child->getLocalZOrder())
{ {
return; return;
} }
@ -277,7 +277,7 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, ssize_t* curIndex)
{ {
bool needNewIndex=true; bool needNewIndex=true;
if (array.at(0)->getZOrder() >= 0) if (array.at(0)->getLocalZOrder() >= 0)
{ {
//all children are in front of the parent //all children are in front of the parent
oldIndex = sprite->getAtlasIndex(); oldIndex = sprite->getAtlasIndex();
@ -294,7 +294,7 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, ssize_t* curIndex)
for(const auto &child: array) { for(const auto &child: array) {
Sprite* sp = static_cast<Sprite*>(child); Sprite* sp = static_cast<Sprite*>(child);
if (needNewIndex && sp->getZOrder() >= 0) if (needNewIndex && sp->getLocalZOrder() >= 0)
{ {
oldIndex = sprite->getAtlasIndex(); oldIndex = sprite->getAtlasIndex();
sprite->setAtlasIndex(*curIndex); sprite->setAtlasIndex(*curIndex);
@ -356,18 +356,13 @@ void SpriteBatchNode::draw()
for(const auto &child: _children) for(const auto &child: _children)
child->updateTransform(); child->updateTransform();
kmMat4 mv; _batchCommand.init(
kmGLGetMatrix(KM_GL_MODELVIEW, &mv); _globalZOrder,
_shaderProgram,
_quadCommand.init(0, _blendFunc,
_vertexZ, _textureAtlas,
_textureAtlas->getTexture()->getName(), _modelViewTransform);
_shaderProgram, Director::getInstance()->getRenderer()->addCommand(&_batchCommand);
_blendFunc,
_textureAtlas->getQuads(),
_textureAtlas->getTotalQuads(),
mv);
Director::getInstance()->getRenderer()->addCommand(&_quadCommand);
} }
void SpriteBatchNode::increaseAtlasCapacity(void) void SpriteBatchNode::increaseAtlasCapacity(void)
@ -396,7 +391,7 @@ ssize_t SpriteBatchNode::rebuildIndexInOrder(Sprite *parent, ssize_t index)
auto& children = parent->getChildren(); auto& children = parent->getChildren();
for(const auto &child: children) { for(const auto &child: children) {
Sprite* sp = static_cast<Sprite*>(child); Sprite* sp = static_cast<Sprite*>(child);
if (sp && (sp->getZOrder() < 0)) if (sp && (sp->getLocalZOrder() < 0))
{ {
index = rebuildIndexInOrder(sp, index); index = rebuildIndexInOrder(sp, index);
} }
@ -411,7 +406,7 @@ ssize_t SpriteBatchNode::rebuildIndexInOrder(Sprite *parent, ssize_t index)
for(const auto &child: children) { for(const auto &child: children) {
Sprite* sp = static_cast<Sprite*>(child); Sprite* sp = static_cast<Sprite*>(child);
if (sp && (sp->getZOrder() >= 0)) if (sp && (sp->getLocalZOrder() >= 0))
{ {
index = rebuildIndexInOrder(sp, index); index = rebuildIndexInOrder(sp, index);
} }
@ -492,7 +487,7 @@ ssize_t SpriteBatchNode::atlasIndexForChild(Sprite *sprite, int nZ)
else else
{ {
// previous & sprite belong to the same branch // previous & sprite belong to the same branch
if ((prev->getZOrder() < 0 && nZ < 0) || (prev->getZOrder() >= 0 && nZ >= 0)) if ((prev->getLocalZOrder() < 0 && nZ < 0) || (prev->getLocalZOrder() >= 0 && nZ >= 0))
{ {
return highestAtlasIndexInChild(prev) + 1; return highestAtlasIndexInChild(prev) + 1;
} }

View File

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

View File

@ -293,7 +293,7 @@ void SpriteFrameCache::removeUnusedSpriteFrames()
for (auto iter = _spriteFrames.begin(); iter != _spriteFrames.end(); ++iter) for (auto iter = _spriteFrames.begin(); iter != _spriteFrames.end(); ++iter)
{ {
SpriteFrame* spriteFrame = iter->second; SpriteFrame* spriteFrame = iter->second;
if( spriteFrame->retainCount() == 1 ) if( spriteFrame->getReferenceCount() == 1 )
{ {
toRemoveFrames.push_back(iter->first); toRemoveFrames.push_back(iter->first);
CCLOG("cocos2d: SpriteFrameCache: removing unused frame: %s", iter->first.c_str()); CCLOG("cocos2d: SpriteFrameCache: removing unused frame: %s", iter->first.c_str());

View File

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

View File

@ -250,8 +250,9 @@ public:
inline void setStoringCharacters(bool storingCharacters) { _storingCharacters = storingCharacters; }; inline void setStoringCharacters(bool storingCharacters) { _storingCharacters = storingCharacters; };
/// properties /// properties
inline ValueMap getProperties() const { return _properties; }; inline const ValueMap& getProperties() const { return _properties; }
inline void setProperties(ValueMap properties) { inline ValueMap& getProperties() { return _properties; }
inline void setProperties(const ValueMap& properties) {
_properties = properties; _properties = properties;
}; };

View File

@ -26,7 +26,7 @@ THE SOFTWARE.
#include "CCTextFieldTTF.h" #include "CCTextFieldTTF.h"
#include "CCDirector.h" #include "CCDirector.h"
#include "CCEGLView.h" #include "CCGLView.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -126,7 +126,7 @@ bool TextFieldTTF::attachWithIME()
if (ret) if (ret)
{ {
// open keyboard // open keyboard
EGLView * pGlView = Director::getInstance()->getOpenGLView(); GLView * pGlView = Director::getInstance()->getOpenGLView();
if (pGlView) if (pGlView)
{ {
pGlView->setIMEKeyboardState(true); pGlView->setIMEKeyboardState(true);
@ -141,7 +141,7 @@ bool TextFieldTTF::detachWithIME()
if (ret) if (ret)
{ {
// close keyboard // close keyboard
EGLView * glView = Director::getInstance()->getOpenGLView(); GLView * glView = Director::getInstance()->getOpenGLView();
if (glView) if (glView)
{ {
glView->setIMEKeyboardState(false); glView->setIMEKeyboardState(false);

View File

@ -1,478 +0,0 @@
/****************************************************************************
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 <stdio.h>
#include <string.h>
#include <vector>
#include <string>
#include "cocos2d.h"
#include "CCTextImage.h"
#include "CCFontFreeType.h"
#include "CCFont.h"
NS_CC_BEGIN
TextLineDef::TextLineDef(float x, float y, float width, float height) :_x(x), _y(y), _width(width), _height(height)
{
}
TextPageDef::TextPageDef(int pageNum, int width, int height): _pageNum(pageNum),
_width(width),
_height(height),
_pageData(0),
_pageTexture(0)
{
}
TextPageDef::~TextPageDef()
{
size_t numLines = _lines.size();
for( size_t c = 0; c<numLines; ++c )
{
delete _lines[c];
}
_lines.clear();
if (_pageData)
{
delete [] _pageData;
}
if (_pageTexture)
{
_pageTexture->release();
}
}
bool TextPageDef::generatePageTexture(bool releasePageData)
{
if (!_pageData)
return false;
if (_pageTexture)
{
_pageTexture->release();
_pageTexture = 0;
}
Size imageSize = Size((float)(_width), (float)(_height));
if((imageSize.width <= 0) || (imageSize.height <= 0))
return false;
_pageTexture = new Texture2D();
if (!_pageTexture)
return false;
int dataLenght = (_width * _height * 1);
bool textureCreated = _pageTexture->initWithData(_pageData, dataLenght, Texture2D::PixelFormat::A8, _width, _height, imageSize);
// release the page data if requested
if (releasePageData && textureCreated)
{
delete [] _pageData;
_pageData = 0;
}
return textureCreated;
}
void TextPageDef::preparePageTexture(bool releaseRAWData)
{
generatePageTexture(releaseRAWData);
}
Texture2D *TextPageDef::getPageTexture()
{
if (!_pageTexture)
{
generatePageTexture();
}
return _pageTexture;
}
TextFontPagesDef::TextFontPagesDef()
{
}
TextFontPagesDef::~TextFontPagesDef()
{
size_t numPages = _pages.size();
for( size_t c = 0; c < numPages; ++c )
{
if (_pages[c])
delete _pages[c];
}
}
TextImage::TextImage(): _fontPages(0), _font(0)
{
}
TextImage::~TextImage()
{
if (_fontPages)
delete _fontPages;
if (_font)
_font->release();
}
bool TextImage::initWithString(const char *text, int width, int height, cocos2d::Font* font, bool releaseRAWData)
{
bool textIsUTF16 = false;
if (_font)
{
_font->release();
_font = 0;
}
// carloX
_font = font;
// generate the glyphs for the requested text (glyphs are latter's bounding boxes)
if (!generateTextGlyphs(text))
return false;
Size constrainSize;
unsigned short int *strUTF16 = 0;
int stringNumChars;
if (textIsUTF16)
{
strUTF16 = (unsigned short int *)text;
stringNumChars = cc_wcslen(strUTF16);
}
else
{
// string needs to go to unicode
strUTF16 = _font->getUTF16Text(text, stringNumChars);
}
if (!strUTF16 || !stringNumChars)
return false;
// create all the needed pages
if (!createPageDefinitions(strUTF16, width, height, _font->getFontMaxHeight()))
return false;
// release the original string if needed
if (!textIsUTF16)
delete [] strUTF16;
// actually create the needed images
return createImageDataFromPages(_fontPages, releaseRAWData);
return true;
}
bool TextImage::createPageDefinitions(unsigned short int *inText, int imageWidth, int imageHeight, int lineHeight)
{
bool needToReleaseText = false;
int delta = 0;
int currentPage = 0;
float currentY = 0.0;
//
unsigned short int *strUTF16 = inText;
if (_fontPages)
delete _fontPages;
// create pages for the font
_fontPages = new TextFontPagesDef();
if (!_fontPages)
return false;
// create the first page (ther is going to be at least one page)
TextPageDef *currentPageDef = new TextPageDef(currentPage, imageWidth, imageHeight);
if (!currentPageDef)
return false;
// add the current page
_fontPages->addPage(currentPageDef);
// work out creating pages
do {
// choose texture page
if ((currentY + lineHeight) > imageHeight)
{
currentY = 0;
currentPage += 1;
// create a new page and add
currentPageDef = new TextPageDef(currentPage, imageWidth, imageHeight);
if (!currentPageDef)
return false;
_fontPages->addPage(currentPageDef);
}
// get the new fitting string
Size tempSize;
tempSize.width = imageWidth;
tempSize.height = imageHeight;
// figure out how many glyphs fit in this line
int newLineSize = 0;
int numFittingChar = getNumGlyphsFittingInSize(_textGlyphs, strUTF16, _font, &tempSize, newLineSize);
// crete the temporary new string
unsigned short int *pTempString = 0;
pTempString = _font->trimUTF16Text(strUTF16, 0, (numFittingChar - 1));
// create the new line and add to the current page
TextLineDef *newLine = new TextLineDef(0.0, currentY, newLineSize, lineHeight);
if (!newLine)
return false;
// add all the glyphs to this line
addGlyphsToLine(newLine, (const char *)pTempString, true);
// add the line the to current page
currentPageDef->addLine(newLine);
// can now release the string
delete [] pTempString;
// create the new string
int stringLenght = _font->getUTF16TextLenght(strUTF16);
delta = (stringLenght - numFittingChar);
// there is still some leftover, need to work on it
if (delta)
{
// create the new string
unsigned short int *tempS = _font->trimUTF16Text(strUTF16, numFittingChar, (stringLenght - 1));
if (needToReleaseText)
delete [] strUTF16;
// a copy of the string has been created, so next time I'll need to release it
needToReleaseText = true;
// assign pointer
strUTF16 = tempS;
}
// go to next line
currentY += lineHeight;
} while(delta);
if (needToReleaseText)
delete [] strUTF16;
return true;
}
int TextImage::getNumGlyphsFittingInSize(std::map<unsigned short int, GlyphDef> &glyphDefs, unsigned short int *strUTF8, Font *font, Size *constrainSize, int &outNewSize)
{
if (!strUTF8)
return 0;
float widthWithBBX = 0.0f;
float lastWidth = 0.0f;
// get the string to UTF8
int numChar = cc_wcslen(strUTF8);
for (int c = 0; c < numChar; ++c)
{
widthWithBBX += (glyphDefs[strUTF8[c]].getRect().size.width + glyphDefs[strUTF8[c]].getPadding());
if (widthWithBBX >= constrainSize->width)
{
outNewSize = lastWidth;
return c;
}
lastWidth = widthWithBBX;
}
outNewSize = constrainSize->width;
return numChar;
}
bool TextImage::addGlyphsToLine(TextLineDef *line, const char *lineText, bool textIsUTF16)
{
if (!_font)
return false;
int numLetters = 0;
unsigned short int *UTF16string = 0;
if (textIsUTF16)
{
UTF16string = (unsigned short int *)lineText;
numLetters = cc_wcslen(UTF16string);
}
else
{
UTF16string = _font->getUTF16Text(lineText, numLetters);
}
for (int c = 0; c < numLetters; ++c)
{
_textGlyphs[UTF16string[c]].setCommonHeight(line->getHeight());
line->addGlyph(_textGlyphs[UTF16string[c]] );
}
if(!textIsUTF16)
delete [] UTF16string;
return true;
}
bool TextImage::generateTextGlyphs(const char * text)
{
if (!_font)
return false;
int numGlyphs = 0;
GlyphDef *newGlyphs = _font->getGlyphDefintionsForText(text, numGlyphs);
if (!newGlyphs)
return false;
if (!_textGlyphs.empty())
_textGlyphs.clear();
for (int c = 0; c < numGlyphs; ++c)
_textGlyphs[newGlyphs[c].getUTF8Letter()] = newGlyphs[c];
delete [] newGlyphs;
return true;
}
bool TextImage::createImageDataFromPages(TextFontPagesDef *thePages, bool releaseRAWData)
{
int numPages = thePages->getNumPages();
if (!numPages)
return false;
for (int c = 0; c < numPages; ++c)
{
unsigned char *pageData = 0;
pageData = preparePageGlyphData(thePages->getPageAt(c));
if (pageData)
{
// set the page data
thePages->getPageAt(c)->setPageData(pageData);
// crete page texture and relase RAW data
thePages->getPageAt(c)->preparePageTexture(releaseRAWData);
}
else
{
return false;
}
}
return true;
}
unsigned char * TextImage::preparePageGlyphData(TextPageDef *thePage)
{
return renderGlyphData(thePage);
}
unsigned char * TextImage::renderGlyphData(TextPageDef *thePage)
{
if (!thePage)
return 0;
if (!_font)
return 0;
if (thePage->getNumLines() == 0)
return nullptr;
int pageWidth = thePage->getWidth();
int pageHeight = thePage->getHeight();
// prepare memory and clean to 0
int sizeInBytes = (pageWidth * pageHeight * 1);
unsigned char* data = new unsigned char[sizeInBytes];
if (!data)
return 0;
memset(data, 0, sizeInBytes);
int numLines = thePage->getNumLines();
for (int c = 0; c < numLines; ++c)
{
TextLineDef *currentLine = thePage->getLineAt(c);
float origX = _font->getLetterPadding();
float origY = currentLine->getY();
int numGlyphToRender = currentLine->getNumGlyph();
for (int cglyph = 0; cglyph < numGlyphToRender; ++cglyph)
{
GlyphDef currGlyph = currentLine->getGlyphAt(cglyph);
_font->renderCharAt(currGlyph.getUTF8Letter(), origX, origY, data, pageWidth);
origX += (currGlyph.getRect().size.width + _font->getLetterPadding());
}
}
#ifdef _DEBUG_FONTS_
static int counter = 0;
char outFilename[512];
sprintf(outFilename,"testIMG%d", counter);
++counter;
Image *image = new Image;
image->initWithRawData(data, (pageWidth * pageWidth * 4), 1024, 1024, 8, false);
image->saveToFile(outFilename);
#endif
// we are done here
return data;
}
NS_CC_END

View File

@ -1,211 +0,0 @@
/****************************************************************************
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 _TextImage_h_
#define _TextImage_h_
//#include "CCFont.h"
#include <vector>
NS_CC_BEGIN
class Font;
/** @brief GlyphDef defines one single glyph (character) in a text image
*
* it defines the bounding box for the glyph in the texture page, the character the padding (spacing) between characters
*
*/
class CC_DLL GlyphDef
{
public:
GlyphDef() : _validGlyph(false) { /*do nothing*/ }
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; }
private:
Rect _gliphRect;
unsigned short int _uTF16Letter;
float _padding;
float _commonHeight;
bool _validGlyph;
};
/** @brief TextLineDef define a line of text in a text image texture page
*
* conllects all the GlyphDef for a text line plus line size and line position in text image space
*
*/
class CC_DLL TextLineDef
{
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; }
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;
};
/** @brief TextPageDef defines one text image page (a TextImage can have/use more than one page)
*
* collects all the TextLineDef for one page, the witdh and height of the page and the graphics (texture) for the page
*
*/
class CC_DLL TextPageDef
{
public:
/**
* @js NA
*/
TextPageDef(int pageNum, int width, int height);
/**
* @js NA
* @lua NA
*/
~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 preparePageTexture(bool releaseRAWData = true);
private:
bool generatePageTexture(bool releasePageData = false);
int _pageNum;
int _width;
int _height;
unsigned char * _pageData;
Texture2D * _pageTexture;
std::vector<TextLineDef *> _lines;
};
/** @brief CCTextFontPages collection of pages (TextPageDef)
*
* A TextImage is composed by one or more text pages. This calss collects all of those pages
*/
class CC_DLL TextFontPagesDef
{
public:
/**
* @js ctor
*/
TextFontPagesDef();
/**
* @js NA
* @lua NA
*/
~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]; }
private:
std::vector<TextPageDef *> _pages;
};
/** @brief TextImage
*
*/
class CC_DLL TextImage
{
public:
/**
* @js ctor
*/
TextImage();
/**
* @js NA
* @lua NA
*/
~TextImage();
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:
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);
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;
};
NS_CC_END
#endif

View File

@ -544,7 +544,6 @@ bool Texture2D::initWithData(const void *data, ssize_t dataLen, Texture2D::Pixel
_contentSize = contentSize; _contentSize = contentSize;
_maxS = contentSize.width / (float)(pixelsWide); _maxS = contentSize.width / (float)(pixelsWide);
_maxT = contentSize.height / (float)(pixelsHigh); _maxT = contentSize.height / (float)(pixelsHigh);
} }
bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat pixelFormat, int pixelsWide, int pixelsHigh) bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat pixelFormat, int pixelsWide, int pixelsHigh)

View File

@ -624,11 +624,11 @@ void TextureAtlas::drawNumberOfQuads(ssize_t numberOfQuads, ssize_t start)
{ {
glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]); glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]);
// option 1: subdata // 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 // 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 // option 3: orphaning + glMapBuffer
glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * (numberOfQuads-start), nullptr, GL_DYNAMIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * (numberOfQuads-start), nullptr, GL_DYNAMIC_DRAW);
void *buf = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); void *buf = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);

View File

@ -386,7 +386,7 @@ void TextureCache::removeUnusedTextures()
{ {
for( auto it=_textures.cbegin(); it!=_textures.cend(); /* nothing */) { for( auto it=_textures.cbegin(); it!=_textures.cend(); /* nothing */) {
Texture2D *tex = it->second; Texture2D *tex = it->second;
if( tex->retainCount() == 1 ) { if( tex->getReferenceCount() == 1 ) {
CCLOG("cocos2d: TextureCache: removing unused texture: %s", it->first.c_str()); CCLOG("cocos2d: TextureCache: removing unused texture: %s", it->first.c_str());
tex->release(); tex->release();
@ -485,7 +485,7 @@ std::string TextureCache::getCachedTextureInfo() const
count++; count++;
snprintf(buftmp,sizeof(buftmp)-1,"\"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB\n", snprintf(buftmp,sizeof(buftmp)-1,"\"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB\n",
it->first.c_str(), it->first.c_str(),
(long)tex->retainCount(), (long)tex->getReferenceCount(),
(long)tex->getName(), (long)tex->getName(),
(long)tex->getPixelsWide(), (long)tex->getPixelsWide(),
(long)tex->getPixelsHigh(), (long)tex->getPixelsHigh(),

View File

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

View File

@ -7,7 +7,7 @@ set(PLATFORM_SRC
platform/win32/CCFileUtilsWin32.cpp platform/win32/CCFileUtilsWin32.cpp
platform/win32/CCCommon.cpp platform/win32/CCCommon.cpp
platform/win32/CCApplication.cpp platform/win32/CCApplication.cpp
platform/win32/CCEGLView.cpp platform/win32/CCGLView.cpp
platform/win32/CCImage.cpp platform/win32/CCImage.cpp
platform/win32/CCDevice.cpp platform/win32/CCDevice.cpp
) )
@ -21,7 +21,7 @@ set(PLATFORM_SRC
platform/linux/CCFileUtilsLinux.cpp platform/linux/CCFileUtilsLinux.cpp
platform/linux/CCCommon.cpp platform/linux/CCCommon.cpp
platform/linux/CCApplication.cpp platform/linux/CCApplication.cpp
platform/linux/CCEGLView.cpp platform/desktop/CCGLView.cpp
platform/linux/CCImage.cpp platform/linux/CCImage.cpp
platform/linux/CCDevice.cpp platform/linux/CCDevice.cpp
) )
@ -67,16 +67,14 @@ set(COCOS2D_SRC
CCFont.cpp CCFont.cpp
CCFontAtlas.cpp CCFontAtlas.cpp
CCFontAtlasCache.cpp CCFontAtlasCache.cpp
CCFontAtlasFactory.cpp
CCFontDefinition.cpp
CCFontFNT.cpp CCFontFNT.cpp
CCFontFreeType.cpp CCFontFreeType.cpp
CCFontCharMap.cpp
CCLabel.cpp CCLabel.cpp
CCLabelAtlas.cpp CCLabelAtlas.cpp
CCLabelBMFont.cpp CCLabelBMFont.cpp
CCLabelTTF.cpp CCLabelTTF.cpp
CCLabelTextFormatter.cpp CCLabelTextFormatter.cpp
CCTextImage.cpp
CCLayer.cpp CCLayer.cpp
CCScene.cpp CCScene.cpp
CCTransition.cpp CCTransition.cpp
@ -136,7 +134,7 @@ set(COCOS2D_SRC
CCDeprecated.cpp CCDeprecated.cpp
platform/CCSAXParser.cpp platform/CCSAXParser.cpp
platform/CCThread.cpp platform/CCThread.cpp
platform/CCEGLViewProtocol.cpp platform/CCGLViewProtocol.cpp
platform/CCFileUtils.cpp platform/CCFileUtils.cpp
../../external/edtaa3func/edtaa3func.cpp ../../external/edtaa3func/edtaa3func.cpp
renderer/CCCustomCommand.cpp renderer/CCCustomCommand.cpp
@ -144,6 +142,7 @@ set(COCOS2D_SRC
renderer/CCGroupCommand.cpp renderer/CCGroupCommand.cpp
renderer/CCMaterialManager.cpp renderer/CCMaterialManager.cpp
renderer/CCQuadCommand.cpp renderer/CCQuadCommand.cpp
renderer/CCBatchCommand.cpp
renderer/CCRenderCommand.cpp renderer/CCRenderCommand.cpp
renderer/CCRenderer.cpp renderer/CCRenderer.cpp
renderer/CCRenderMaterial.cpp renderer/CCRenderMaterial.cpp

View File

@ -73,7 +73,7 @@ void ccArrayEnsureExtraCapacity(ccArray *arr, ssize_t extra)
{ {
while (arr->max < arr->num + 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),
static_cast<int>(arr->max*2)); static_cast<int>(arr->max*2));

View File

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

View File

@ -44,7 +44,7 @@ namespace GL {
/** vertex attrib flags */ /** vertex attrib flags */
enum { enum {
VERTEX_ATTRIB_FLAT_NONE = 0, VERTEX_ATTRIB_FLAG_NONE = 0,
VERTEX_ATTRIB_FLAG_POSITION = 1 << 0, VERTEX_ATTRIB_FLAG_POSITION = 1 << 0,
VERTEX_ATTRIB_FLAG_COLOR = 1 << 1, VERTEX_ATTRIB_FLAG_COLOR = 1 << 1,
@ -129,6 +129,12 @@ void CC_DLL deleteTexture(GLuint textureId);
*/ */
void CC_DLL deleteTextureN(GLuint textureUnit, 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 the vertex array is not already bound, it binds it.
If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindVertexArray() directly. If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindVertexArray() directly.
@since v2.0.0 @since v2.0.0

View File

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

View File

@ -107,9 +107,9 @@ Color4B::Color4B(GLubyte _r, GLubyte _g, GLubyte _b, GLubyte _a)
{} {}
Color4B::Color4B(const Color3B& color) Color4B::Color4B(const Color3B& color)
: r(color.r * 255) : r(color.r)
, g(color.g * 255) , g(color.g)
, b(color.b * 255) , b(color.b)
, a(255) , a(255)
{} {}

View File

@ -279,9 +279,9 @@ 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* 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) { if (rUtf16Size != nullptr) {
*rUtf16Size = len; *rUtf16Size = static_cast<int>(len);
} }
unsigned short* str_new = new unsigned short[len + 1]; unsigned short* str_new = new unsigned short[len + 1];

View File

@ -25,13 +25,13 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "cocos2d.h" #include "CCPlatformMacros.h"
NS_CC_BEGIN NS_CC_BEGIN
const char* cocos2dVersion() const char* cocos2dVersion()
{ {
return "3.0-beta"; return "3.0-beta2";
} }
NS_CC_END NS_CC_END

View File

@ -154,44 +154,44 @@ THE SOFTWARE.
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#include "platform/ios/CCApplication.h" #include "platform/ios/CCApplication.h"
#include "platform/ios/CCEGLView.h" #include "platform/ios/CCGLView.h"
#include "platform/ios/CCGL.h" #include "platform/ios/CCGL.h"
#include "platform/ios/CCStdC.h" #include "platform/ios/CCStdC.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_IOS #endif // CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "platform/android/CCApplication.h" #include "platform/android/CCApplication.h"
#include "platform/android/CCEGLView.h" #include "platform/android/CCGLView.h"
#include "platform/android/CCGL.h" #include "platform/android/CCGL.h"
#include "platform/android/CCStdC.h" #include "platform/android/CCStdC.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID #endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#if (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY) #if (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY)
#include "platform/blackberry/CCApplication.h" #include "platform/blackberry/CCApplication.h"
#include "platform/blackberry/CCEGLView.h" #include "platform/blackberry/CCGLView.h"
#include "platform/blackberry/CCGL.h" #include "platform/blackberry/CCGL.h"
#include "platform/blackberry/CCStdC.h" #include "platform/blackberry/CCStdC.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY #endif // CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#include "platform/win32/CCApplication.h" #include "platform/win32/CCApplication.h"
#include "platform/win32/CCEGLView.h" #include "platform/desktop/CCGLView.h"
#include "platform/win32/CCGL.h" #include "platform/win32/CCGL.h"
#include "platform/win32/CCStdC.h" #include "platform/win32/CCStdC.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 #endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
#include "platform/mac/CCApplication.h" #include "platform/mac/CCApplication.h"
#include "platform/mac/CCEGLView.h" #include "platform/desktop/CCGLView.h"
#include "platform/mac/CCGL.h" #include "platform/mac/CCGL.h"
#include "platform/mac/CCStdC.h" #include "platform/mac/CCStdC.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC #endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC
#if (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) #if (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
#include "platform/linux/CCApplication.h" #include "platform/linux/CCApplication.h"
#include "platform/linux/CCEGLView.h" #include "platform/desktop/CCGLView.h"
#include "platform/linux/CCGL.h" #include "platform/linux/CCGL.h"
#include "platform/linux/CCStdC.h" #include "platform/linux/CCStdC.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX #endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
// script_support // script_support

View File

@ -247,8 +247,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClCompile Include="CCFont.cpp" /> <ClCompile Include="CCFont.cpp" />
<ClCompile Include="CCFontAtlas.cpp" /> <ClCompile Include="CCFontAtlas.cpp" />
<ClCompile Include="CCFontAtlasCache.cpp" /> <ClCompile Include="CCFontAtlasCache.cpp" />
<ClCompile Include="CCFontAtlasFactory.cpp" /> <ClCompile Include="CCFontCharMap.cpp" />
<ClCompile Include="CCFontDefinition.cpp" />
<ClCompile Include="CCFontFNT.cpp" /> <ClCompile Include="CCFontFNT.cpp" />
<ClCompile Include="CCFontFreeType.cpp" /> <ClCompile Include="CCFontFreeType.cpp" />
<ClCompile Include="ccFPSImages.c" /> <ClCompile Include="ccFPSImages.c" />
@ -287,7 +286,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClCompile Include="CCSpriteFrame.cpp" /> <ClCompile Include="CCSpriteFrame.cpp" />
<ClCompile Include="CCSpriteFrameCache.cpp" /> <ClCompile Include="CCSpriteFrameCache.cpp" />
<ClCompile Include="CCTextFieldTTF.cpp" /> <ClCompile Include="CCTextFieldTTF.cpp" />
<ClCompile Include="CCTextImage.cpp" />
<ClCompile Include="CCTexture2D.cpp" /> <ClCompile Include="CCTexture2D.cpp" />
<ClCompile Include="CCTextureAtlas.cpp" /> <ClCompile Include="CCTextureAtlas.cpp" />
<ClCompile Include="CCTextureCache.cpp" /> <ClCompile Include="CCTextureCache.cpp" />
@ -306,17 +304,18 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClCompile Include="ccUtils.cpp" /> <ClCompile Include="ccUtils.cpp" />
<ClCompile Include="CCVertex.cpp" /> <ClCompile Include="CCVertex.cpp" />
<ClCompile Include="cocos2d.cpp" /> <ClCompile Include="cocos2d.cpp" />
<ClCompile Include="platform\CCEGLViewProtocol.cpp" /> <ClCompile Include="platform\CCGLViewProtocol.cpp" />
<ClCompile Include="platform\CCFileUtils.cpp" /> <ClCompile Include="platform\CCFileUtils.cpp" />
<ClCompile Include="platform\CCSAXParser.cpp" /> <ClCompile Include="platform\CCSAXParser.cpp" />
<ClCompile Include="platform\CCThread.cpp" /> <ClCompile Include="platform\CCThread.cpp" />
<ClCompile Include="platform\desktop\CCGLView.cpp" />
<ClCompile Include="platform\win32\CCApplication.cpp" /> <ClCompile Include="platform\win32\CCApplication.cpp" />
<ClCompile Include="platform\win32\CCCommon.cpp" /> <ClCompile Include="platform\win32\CCCommon.cpp" />
<ClCompile Include="platform\win32\CCDevice.cpp" /> <ClCompile Include="platform\win32\CCDevice.cpp" />
<ClCompile Include="platform\win32\CCEGLView.cpp" />
<ClCompile Include="platform\win32\CCFileUtilsWin32.cpp" /> <ClCompile Include="platform\win32\CCFileUtilsWin32.cpp" />
<ClCompile Include="platform\win32\CCImage.cpp" /> <ClCompile Include="platform\win32\CCImage.cpp" />
<ClCompile Include="platform\win32\CCStdC.cpp" /> <ClCompile Include="platform\win32\CCStdC.cpp" />
<ClCompile Include="renderer\CCBatchCommand.cpp" />
<ClCompile Include="renderer\CCCustomCommand.cpp" /> <ClCompile Include="renderer\CCCustomCommand.cpp" />
<ClCompile Include="renderer\CCFrustum.cpp" /> <ClCompile Include="renderer\CCFrustum.cpp" />
<ClCompile Include="renderer\CCGroupCommand.cpp" /> <ClCompile Include="renderer\CCGroupCommand.cpp" />
@ -427,8 +426,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClInclude Include="CCFont.h" /> <ClInclude Include="CCFont.h" />
<ClInclude Include="CCFontAtlas.h" /> <ClInclude Include="CCFontAtlas.h" />
<ClInclude Include="CCFontAtlasCache.h" /> <ClInclude Include="CCFontAtlasCache.h" />
<ClInclude Include="CCFontAtlasFactory.h" /> <ClInclude Include="CCFontCharMap.h" />
<ClInclude Include="CCFontDefinition.h" />
<ClInclude Include="CCFontFNT.h" /> <ClInclude Include="CCFontFNT.h" />
<ClInclude Include="CCFontFreeType.h" /> <ClInclude Include="CCFontFreeType.h" />
<ClInclude Include="ccFPSImages.h" /> <ClInclude Include="ccFPSImages.h" />
@ -442,7 +440,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClInclude Include="CCLabel.h" /> <ClInclude Include="CCLabel.h" />
<ClInclude Include="CCLabelAtlas.h" /> <ClInclude Include="CCLabelAtlas.h" />
<ClInclude Include="CCLabelBMFont.h" /> <ClInclude Include="CCLabelBMFont.h" />
<ClInclude Include="CCLabelTextFormatProtocol.h" />
<ClInclude Include="CCLabelTextFormatter.h" /> <ClInclude Include="CCLabelTextFormatter.h" />
<ClInclude Include="CCLabelTTF.h" /> <ClInclude Include="CCLabelTTF.h" />
<ClInclude Include="CCLayer.h" /> <ClInclude Include="CCLayer.h" />
@ -487,7 +484,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClInclude Include="CCSpriteFrame.h" /> <ClInclude Include="CCSpriteFrame.h" />
<ClInclude Include="CCSpriteFrameCache.h" /> <ClInclude Include="CCSpriteFrameCache.h" />
<ClInclude Include="CCTextFieldTTF.h" /> <ClInclude Include="CCTextFieldTTF.h" />
<ClInclude Include="CCTextImage.h" />
<ClInclude Include="CCTexture2D.h" /> <ClInclude Include="CCTexture2D.h" />
<ClInclude Include="CCTextureAtlas.h" /> <ClInclude Include="CCTextureAtlas.h" />
<ClInclude Include="CCTextureCache.h" /> <ClInclude Include="CCTextureCache.h" />
@ -509,18 +505,19 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClInclude Include="platform\CCApplicationProtocol.h" /> <ClInclude Include="platform\CCApplicationProtocol.h" />
<ClInclude Include="platform\CCCommon.h" /> <ClInclude Include="platform\CCCommon.h" />
<ClInclude Include="platform\CCDevice.h" /> <ClInclude Include="platform\CCDevice.h" />
<ClInclude Include="platform\CCEGLViewProtocol.h" /> <ClInclude Include="platform\CCGLViewProtocol.h" />
<ClInclude Include="platform\CCFileUtils.h" /> <ClInclude Include="platform\CCFileUtils.h" />
<ClInclude Include="platform\CCImage.h" /> <ClInclude Include="platform\CCImage.h" />
<ClInclude Include="platform\CCImageCommon_cpp.h" /> <ClInclude Include="platform\CCImageCommon_cpp.h" />
<ClInclude Include="platform\CCSAXParser.h" /> <ClInclude Include="platform\CCSAXParser.h" />
<ClInclude Include="platform\CCThread.h" /> <ClInclude Include="platform\CCThread.h" />
<ClInclude Include="platform\desktop\CCGLView.h" />
<ClInclude Include="platform\win32\CCApplication.h" /> <ClInclude Include="platform\win32\CCApplication.h" />
<ClInclude Include="platform\win32\CCEGLView.h" />
<ClInclude Include="platform\win32\CCFileUtilsWin32.h" /> <ClInclude Include="platform\win32\CCFileUtilsWin32.h" />
<ClInclude Include="platform\win32\CCGL.h" /> <ClInclude Include="platform\win32\CCGL.h" />
<ClInclude Include="platform\win32\CCPlatformDefine.h" /> <ClInclude Include="platform\win32\CCPlatformDefine.h" />
<ClInclude Include="platform\win32\CCStdC.h" /> <ClInclude Include="platform\win32\CCStdC.h" />
<ClInclude Include="renderer\CCBatchCommand.h" />
<ClInclude Include="renderer\CCCustomCommand.h" /> <ClInclude Include="renderer\CCCustomCommand.h" />
<ClInclude Include="renderer\CCFrustum.h" /> <ClInclude Include="renderer\CCFrustum.h" />
<ClInclude Include="renderer\CCGroupCommand.h" /> <ClInclude Include="renderer\CCGroupCommand.h" />
@ -539,4 +536,4 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets"> <ImportGroup Label="ExtensionTargets">
</ImportGroup> </ImportGroup>
</Project> </Project>

View File

@ -112,6 +112,9 @@
<Filter Include="renderer"> <Filter Include="renderer">
<UniqueIdentifier>{cba0f362-878c-438b-ad0f-43d287516357}</UniqueIdentifier> <UniqueIdentifier>{cba0f362-878c-438b-ad0f-43d287516357}</UniqueIdentifier>
</Filter> </Filter>
<Filter Include="platform\desktop">
<UniqueIdentifier>{32373f63-2c2d-4eab-bc4a-21745ba0b3fb}</UniqueIdentifier>
</Filter>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClCompile Include="..\physics\CCPhysicsBody.cpp"> <ClCompile Include="..\physics\CCPhysicsBody.cpp">
@ -318,12 +321,6 @@
<ClCompile Include="CCFontAtlasCache.cpp"> <ClCompile Include="CCFontAtlasCache.cpp">
<Filter>label_nodes</Filter> <Filter>label_nodes</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="CCFontAtlasFactory.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
<ClCompile Include="CCFontDefinition.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
<ClCompile Include="CCFontFNT.cpp"> <ClCompile Include="CCFontFNT.cpp">
<Filter>label_nodes</Filter> <Filter>label_nodes</Filter>
</ClCompile> </ClCompile>
@ -345,9 +342,6 @@
<ClCompile Include="CCLabelTTF.cpp"> <ClCompile Include="CCLabelTTF.cpp">
<Filter>label_nodes</Filter> <Filter>label_nodes</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="CCTextImage.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
<ClCompile Include="..\base\etc1.cpp"> <ClCompile Include="..\base\etc1.cpp">
<Filter>platform\etc</Filter> <Filter>platform\etc</Filter>
</ClCompile> </ClCompile>
@ -360,9 +354,6 @@
<ClCompile Include="platform\win32\CCDevice.cpp"> <ClCompile Include="platform\win32\CCDevice.cpp">
<Filter>platform\win32</Filter> <Filter>platform\win32</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="platform\win32\CCEGLView.cpp">
<Filter>platform\win32</Filter>
</ClCompile>
<ClCompile Include="platform\win32\CCFileUtilsWin32.cpp"> <ClCompile Include="platform\win32\CCFileUtilsWin32.cpp">
<Filter>platform\win32</Filter> <Filter>platform\win32</Filter>
</ClCompile> </ClCompile>
@ -372,7 +363,7 @@
<ClCompile Include="platform\win32\CCStdC.cpp"> <ClCompile Include="platform\win32\CCStdC.cpp">
<Filter>platform\win32</Filter> <Filter>platform\win32</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="platform\CCEGLViewProtocol.cpp"> <ClCompile Include="platform\CCGLViewProtocol.cpp">
<Filter>platform</Filter> <Filter>platform</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="platform\CCFileUtils.cpp"> <ClCompile Include="platform\CCFileUtils.cpp">
@ -598,6 +589,15 @@
<ClCompile Include="renderer\CCRenderMaterial.cpp"> <ClCompile Include="renderer\CCRenderMaterial.cpp">
<Filter>renderer</Filter> <Filter>renderer</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="renderer\CCBatchCommand.cpp">
<Filter>renderer</Filter>
</ClCompile>
<ClCompile Include="CCFontCharMap.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
<ClCompile Include="platform\desktop\CCGLView.cpp">
<Filter>platform\desktop</Filter>
</ClCompile>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="..\physics\CCPhysicsBody.h"> <ClInclude Include="..\physics\CCPhysicsBody.h">
@ -828,12 +828,6 @@
<ClInclude Include="CCFontAtlasCache.h"> <ClInclude Include="CCFontAtlasCache.h">
<Filter>label_nodes</Filter> <Filter>label_nodes</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="CCFontAtlasFactory.h">
<Filter>label_nodes</Filter>
</ClInclude>
<ClInclude Include="CCFontDefinition.h">
<Filter>label_nodes</Filter>
</ClInclude>
<ClInclude Include="CCFontFNT.h"> <ClInclude Include="CCFontFNT.h">
<Filter>label_nodes</Filter> <Filter>label_nodes</Filter>
</ClInclude> </ClInclude>
@ -849,27 +843,18 @@
<ClInclude Include="CCLabelBMFont.h"> <ClInclude Include="CCLabelBMFont.h">
<Filter>label_nodes</Filter> <Filter>label_nodes</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="CCLabelTextFormatProtocol.h">
<Filter>label_nodes</Filter>
</ClInclude>
<ClInclude Include="CCLabelTextFormatter.h"> <ClInclude Include="CCLabelTextFormatter.h">
<Filter>label_nodes</Filter> <Filter>label_nodes</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="CCLabelTTF.h"> <ClInclude Include="CCLabelTTF.h">
<Filter>label_nodes</Filter> <Filter>label_nodes</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="CCTextImage.h">
<Filter>label_nodes</Filter>
</ClInclude>
<ClInclude Include="..\base\etc1.h"> <ClInclude Include="..\base\etc1.h">
<Filter>platform\etc</Filter> <Filter>platform\etc</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="platform\win32\CCApplication.h"> <ClInclude Include="platform\win32\CCApplication.h">
<Filter>platform\win32</Filter> <Filter>platform\win32</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="platform\win32\CCEGLView.h">
<Filter>platform\win32</Filter>
</ClInclude>
<ClInclude Include="platform\win32\CCFileUtilsWin32.h"> <ClInclude Include="platform\win32\CCFileUtilsWin32.h">
<Filter>platform\win32</Filter> <Filter>platform\win32</Filter>
</ClInclude> </ClInclude>
@ -891,7 +876,7 @@
<ClInclude Include="platform\CCDevice.h"> <ClInclude Include="platform\CCDevice.h">
<Filter>platform</Filter> <Filter>platform</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="platform\CCEGLViewProtocol.h"> <ClInclude Include="platform\CCGLViewProtocol.h">
<Filter>platform</Filter> <Filter>platform</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="platform\CCFileUtils.h"> <ClInclude Include="platform\CCFileUtils.h">
@ -1207,5 +1192,14 @@
<ClInclude Include="renderer\CCRenderMaterial.h"> <ClInclude Include="renderer\CCRenderMaterial.h">
<Filter>renderer</Filter> <Filter>renderer</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="renderer\CCBatchCommand.h">
<Filter>renderer</Filter>
</ClInclude>
<ClInclude Include="CCFontCharMap.h">
<Filter>label_nodes</Filter>
</ClInclude>
<ClInclude Include="platform\desktop\CCGLView.h">
<Filter>platform\desktop</Filter>
</ClInclude>
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -7,7 +7,7 @@
<PropertyGroup /> <PropertyGroup />
<ItemDefinitionGroup> <ItemDefinitionGroup>
<ClCompile> <ClCompile>
<AdditionalIncludeDirectories>$(EngineRoot)cocos\2d;$(EngineRoot)cocos\2d\renderer;$(EngineRoot)cocos\gui;$(EngineRoot)cocos\base;$(EngineRoot)cocos\physics;$(EngineRoot)cocos\math\kazmath\include;$(EngineRoot)cocos\2d\platform\win32;$(EngineRoot)external\glfw3\include\win32;$(EngineRoot)external\win32-specific\gles\include\OGLES</AdditionalIncludeDirectories> <AdditionalIncludeDirectories>$(EngineRoot)cocos\2d;$(EngineRoot)cocos\2d\renderer;$(EngineRoot)cocos\gui;$(EngineRoot)cocos\base;$(EngineRoot)cocos\physics;$(EngineRoot)cocos\math\kazmath\include;$(EngineRoot)cocos\2d\platform\win32;$(EngineRoot)cocos\2d\platform\desktop;$(EngineRoot)external\glfw3\include\win32;$(EngineRoot)external\win32-specific\gles\include\OGLES</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_VARIADIC_MAX=10;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>_VARIADIC_MAX=10;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile> </ClCompile>
</ItemDefinitionGroup> </ItemDefinitionGroup>

View File

@ -1,149 +0,0 @@
################################################################################
#
# LINUX MAKEFILE
#
# Available options are:
# - CLANG=1 : Compiles with clang instead of gcc. Clang must be in your PATH.
# - V=1 : Enables the verbose mode.
# - DEBUG=1 : Enables the debug mode, disable compiler optimizations.
# - OPENAL=1 : Uses OpenAL instead of FMOD as sound engine.
#
################################################################################
all:
# Remove -Wall, because it enables -Wunused-function, and this warning exists in webp.h
# when enable c++11. I don't know why.
# GCC 4.6 is primary platform for cocos2d v.3, because it's default compiler for Android,
# Blackberry, some Linux distributions.It supports all important features of c++11, but have
# no flag "-std=c++11" (which was turned on in version 4.7).
CCFLAGS += -MMD -Wno-deprecated-declarations -fPIC
CXXFLAGS += -MMD -Wno-deprecated-declarations -fPIC -std=gnu++0x
ifeq ($(CLANG), 1)
CC := clang
CXX := clang++
DEFINES += -D__STRICT_ANSI__ # Allows clang 3.3 to use __float128
else
CC = gcc
CXX = g++
CCFLAGS += -Werror
CXXFLAGS += -Werror
endif
ARFLAGS = cr
DEFINES += -DLINUX -DCC_KEYBOARD_SUPPORT
ifdef USE_BOX2D
DEFINES += -DCC_ENABLE_BOX2D_INTEGRATION=1
else
DEFINES += -DCC_ENABLE_CHIPMUNK_INTEGRATION=1
endif
THIS_MAKEFILE := $(CURDIR)/$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
ifndef COCOS_ROOT
COCOS_ROOT := $(realpath $(dir $(THIS_MAKEFILE))/../..)
endif
COCOS_SRC = $(COCOS_ROOT)/cocos/2d
OBJ_DIR ?= obj
LIB_DIR = $(COCOS_ROOT)/lib/linux
BIN_DIR = bin
INCLUDES += \
-I$(COCOS_SRC)/ \
-I$(COCOS_SRC)/../math/kazmath/include \
-I$(COCOS_SRC)/platform/linux \
-I$(COCOS_SRC)/../../external/jpeg/include/linux \
-I$(COCOS_SRC)/../../external/tiff/include/linux \
-I$(COCOS_SRC)/../../external/webp/include/linux \
-I$(COCOS_SRC)/../../external/tinyxml2 \
-I$(COCOS_SRC)/../../external/unzip \
-I$(COCOS_SRC)/../../external/glfw3/include/linux \
-I$(COCOS_SRC)/../physics \
-I$(COCOS_SRC)/../base \
-I$(COCOS_SRC)/../../external/chipmunk/include/chipmunk \
-I$(COCOS_SRC)/../../external/freetype2/include/linux \
-I$(COCOS_SRC)/../.. \
-I$(COCOS_SRC)/../audio/include
LBITS := $(shell getconf LONG_BIT)
ifeq ($(DEBUG), 1)
CCFLAGS += -g3 -O0
CXXFLAGS += -g3 -O0
DEFINES += -D_DEBUG -DCOCOS2D_DEBUG=1
OBJ_DIR := $(OBJ_DIR)/debug
LIB_DIR := $(LIB_DIR)/debug
BIN_DIR := $(BIN_DIR)/debug
else
CCFLAGS += -O3
CXXFLAGS += -O3
DEFINES += -DNDEBUG
OBJ_DIR := $(OBJ_DIR)/release
LIB_DIR := $(LIB_DIR)/release
BIN_DIR := $(BIN_DIR)/release
endif
ifndef V
LOG_CC = @echo " CC $@";
LOG_CXX = @echo " CXX $@";
LOG_AR = @echo " AR $@";
LOG_LINK = @echo " LINK $@";
endif
OBJECTS := $(SOURCES:.cpp=.o)
OBJECTS := $(OBJECTS:.c=.o)
OBJECTS := $(subst ../,,$(OBJECTS))
OBJECTS := $(subst $(COCOS_ROOT)/,,$(OBJECTS))
OBJECTS := $(addprefix $(OBJ_DIR)/, $(OBJECTS))
DEPS = $(OBJECTS:.o=.d)
CORE_MAKEFILE_LIST := $(MAKEFILE_LIST)
-include $(DEPS)
STATICLIBS_DIR = $(COCOS_ROOT)/external
ifeq ($(LBITS),64)
POSTFIX = 64-bit
else
POSTFIX = 32-bit
endif
STATICLIBS = $(STATICLIBS_DIR)/freetype2/prebuilt/linux/$(POSTFIX)/libfreetype.a \
$(STATICLIBS_DIR)/jpeg/prebuilt/linux/$(POSTFIX)/libjpeg.a \
$(STATICLIBS_DIR)/tiff/prebuilt/linux/$(POSTFIX)/libtiff.a \
$(STATICLIBS_DIR)/webp/prebuilt/linux/$(POSTFIX)/libwebp.a
ifneq ($(OPENAL),1)
ifeq ($(LBITS),64)
FMOD_LIBDIR = $(COCOS_ROOT)/cocos/audio/third-party/fmod/lib64/api/lib
SHAREDLIBS += -lfmodex64
else
FMOD_LIBDIR = $(COCOS_ROOT)/cocos/audio/third-party/fmod/api/lib
SHAREDLIBS += -lfmodex
endif
endif
SHAREDLIBS += -lGLEW -lfontconfig -lpthread -lGL -lpng `pkg-config --libs glfw3`
SHAREDLIBS += -L$(FMOD_LIBDIR) -Wl,-rpath,$(abspath $(FMOD_LIBDIR))
SHAREDLIBS += -L$(LIB_DIR) -Wl,-rpath,$(abspath $(LIB_DIR))
LIBS = -lrt -lz -lX11
clean:
rm -rf $(OBJ_DIR)
rm -f $(TARGET) core
.PHONY: all clean
# If the parent Makefile defines $(EXECUTABLE) then define this as the target
# and create a 'make run' rule to run the app.
ifdef EXECUTABLE
TARGET := $(BIN_DIR)/$(EXECUTABLE)
all: $(TARGET)
run: $(TARGET)
cd $(dir $^) && ./$(notdir $^)
.PHONY: run
endif

View File

@ -33,6 +33,8 @@ NS_CC_BEGIN
* @{ * @{
*/ */
class EAGLView;
class CC_DLL ApplicationProtocol class CC_DLL ApplicationProtocol
{ {
public: public:

View File

@ -56,6 +56,7 @@ enum class LanguageType
ITALIAN, ITALIAN,
GERMAN, GERMAN,
SPANISH, SPANISH,
DUTCH,
RUSSIAN, RUSSIAN,
KOREAN, KOREAN,
JAPANESE, JAPANESE,

View File

@ -23,7 +23,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "CCEGLViewProtocol.h" #include "CCGLViewProtocol.h"
#include "CCTouch.h" #include "CCTouch.h"
#include "CCDirector.h" #include "CCDirector.h"
#include "CCSet.h" #include "CCSet.h"
@ -71,24 +71,23 @@ namespace {
} }
EGLViewProtocol::EGLViewProtocol() GLViewProtocol::GLViewProtocol()
: _delegate(nullptr) : _scaleX(1.0f)
, _scaleX(1.0f)
, _scaleY(1.0f) , _scaleY(1.0f)
, _resolutionPolicy(ResolutionPolicy::UNKNOWN) , _resolutionPolicy(ResolutionPolicy::UNKNOWN)
{ {
} }
EGLViewProtocol::~EGLViewProtocol() GLViewProtocol::~GLViewProtocol()
{ {
} }
void EGLViewProtocol::pollInputEvents() void GLViewProtocol::pollInputEvents()
{ {
} }
void EGLViewProtocol::setDesignResolutionSize(float width, float height, ResolutionPolicy resolutionPolicy) void GLViewProtocol::setDesignResolutionSize(float width, float height, ResolutionPolicy resolutionPolicy)
{ {
CCASSERT(resolutionPolicy != ResolutionPolicy::UNKNOWN, "should set resolutionPolicy"); CCASSERT(resolutionPolicy != ResolutionPolicy::UNKNOWN, "should set resolutionPolicy");
@ -107,17 +106,17 @@ void EGLViewProtocol::setDesignResolutionSize(float width, float height, Resolut
_scaleX = _scaleY = MAX(_scaleX, _scaleY); _scaleX = _scaleY = MAX(_scaleX, _scaleY);
} }
if (resolutionPolicy == ResolutionPolicy::SHOW_ALL) else if (resolutionPolicy == ResolutionPolicy::SHOW_ALL)
{ {
_scaleX = _scaleY = MIN(_scaleX, _scaleY); _scaleX = _scaleY = MIN(_scaleX, _scaleY);
} }
if ( resolutionPolicy == ResolutionPolicy::FIXED_HEIGHT) { else if ( resolutionPolicy == ResolutionPolicy::FIXED_HEIGHT) {
_scaleX = _scaleY; _scaleX = _scaleY;
_designResolutionSize.width = ceilf(_screenSize.width/_scaleX); _designResolutionSize.width = ceilf(_screenSize.width/_scaleX);
} }
if ( resolutionPolicy == ResolutionPolicy::FIXED_WIDTH) { else if ( resolutionPolicy == ResolutionPolicy::FIXED_WIDTH) {
_scaleY = _scaleX; _scaleY = _scaleX;
_designResolutionSize.height = ceilf(_screenSize.height/_scaleY); _designResolutionSize.height = ceilf(_screenSize.height/_scaleY);
} }
@ -131,27 +130,28 @@ void EGLViewProtocol::setDesignResolutionSize(float width, float height, Resolut
_resolutionPolicy = resolutionPolicy; _resolutionPolicy = resolutionPolicy;
// reset director's member variables to fit visible rect // reset director's member variables to fit visible rect
Director::getInstance()->_winSizeInPoints = getDesignResolutionSize(); auto director = Director::getInstance();
Director::getInstance()->createStatsLabel(); director->_winSizeInPoints = getDesignResolutionSize();
Director::getInstance()->setGLDefaultValues(); director->createStatsLabel();
director->setGLDefaultValues();
} }
const Size& EGLViewProtocol::getDesignResolutionSize() const const Size& GLViewProtocol::getDesignResolutionSize() const
{ {
return _designResolutionSize; return _designResolutionSize;
} }
const Size& EGLViewProtocol::getFrameSize() const const Size& GLViewProtocol::getFrameSize() const
{ {
return _screenSize; return _screenSize;
} }
void EGLViewProtocol::setFrameSize(float width, float height) void GLViewProtocol::setFrameSize(float width, float height)
{ {
_designResolutionSize = _screenSize = Size(width, height); _designResolutionSize = _screenSize = Size(width, height);
} }
Size EGLViewProtocol::getVisibleSize() const Size GLViewProtocol::getVisibleSize() const
{ {
if (_resolutionPolicy == ResolutionPolicy::NO_BORDER) if (_resolutionPolicy == ResolutionPolicy::NO_BORDER)
{ {
@ -163,7 +163,7 @@ Size EGLViewProtocol::getVisibleSize() const
} }
} }
Point EGLViewProtocol::getVisibleOrigin() const Point GLViewProtocol::getVisibleOrigin() const
{ {
if (_resolutionPolicy == ResolutionPolicy::NO_BORDER) if (_resolutionPolicy == ResolutionPolicy::NO_BORDER)
{ {
@ -176,12 +176,7 @@ Point EGLViewProtocol::getVisibleOrigin() const
} }
} }
void EGLViewProtocol::setTouchDelegate(EGLTouchDelegate * delegate) void GLViewProtocol::setViewPortInPoints(float x , float y , float w , float h)
{
_delegate = delegate;
}
void EGLViewProtocol::setViewPortInPoints(float x , float y , float w , float h)
{ {
glViewport((GLint)(x * _scaleX + _viewPortRect.origin.x), glViewport((GLint)(x * _scaleX + _viewPortRect.origin.x),
(GLint)(y * _scaleY + _viewPortRect.origin.y), (GLint)(y * _scaleY + _viewPortRect.origin.y),
@ -189,7 +184,7 @@ void EGLViewProtocol::setViewPortInPoints(float x , float y , float w , float h)
(GLsizei)(h * _scaleY)); (GLsizei)(h * _scaleY));
} }
void EGLViewProtocol::setScissorInPoints(float x , float y , float w , float h) void GLViewProtocol::setScissorInPoints(float x , float y , float w , float h)
{ {
glScissor((GLint)(x * _scaleX + _viewPortRect.origin.x), glScissor((GLint)(x * _scaleX + _viewPortRect.origin.x),
(GLint)(y * _scaleY + _viewPortRect.origin.y), (GLint)(y * _scaleY + _viewPortRect.origin.y),
@ -197,12 +192,12 @@ void EGLViewProtocol::setScissorInPoints(float x , float y , float w , float h)
(GLsizei)(h * _scaleY)); (GLsizei)(h * _scaleY));
} }
bool EGLViewProtocol::isScissorEnabled() bool GLViewProtocol::isScissorEnabled()
{ {
return (GL_FALSE == glIsEnabled(GL_SCISSOR_TEST)) ? false : true; return (GL_FALSE == glIsEnabled(GL_SCISSOR_TEST)) ? false : true;
} }
Rect EGLViewProtocol::getScissorRect() const Rect GLViewProtocol::getScissorRect() const
{ {
GLfloat params[4]; GLfloat params[4];
glGetFloatv(GL_SCISSOR_BOX, params); glGetFloatv(GL_SCISSOR_BOX, params);
@ -213,17 +208,17 @@ Rect EGLViewProtocol::getScissorRect() const
return Rect(x, y, w, h); return Rect(x, y, w, h);
} }
void EGLViewProtocol::setViewName(const std::string& viewname ) void GLViewProtocol::setViewName(const std::string& viewname )
{ {
_viewName = viewname; _viewName = viewname;
} }
const std::string& EGLViewProtocol::getViewName() const const std::string& GLViewProtocol::getViewName() const
{ {
return _viewName; return _viewName;
} }
void EGLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float ys[]) void GLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float ys[])
{ {
int id = 0; int id = 0;
float x = 0.0f; float x = 0.0f;
@ -273,7 +268,7 @@ void EGLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float y
dispatcher->dispatchEvent(&touchEvent); dispatcher->dispatchEvent(&touchEvent);
} }
void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys[]) void GLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys[])
{ {
int id = 0; int id = 0;
float x = 0.0f; float x = 0.0f;
@ -321,7 +316,7 @@ void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys
dispatcher->dispatchEvent(&touchEvent); dispatcher->dispatchEvent(&touchEvent);
} }
void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]) void GLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[])
{ {
int id = 0; int id = 0;
float x = 0.0f; float x = 0.0f;
@ -381,27 +376,27 @@ void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode
} }
} }
void EGLViewProtocol::handleTouchesEnd(int num, int ids[], float xs[], float ys[]) void GLViewProtocol::handleTouchesEnd(int num, int ids[], float xs[], float ys[])
{ {
handleTouchesOfEndOrCancel(EventTouch::EventCode::ENDED, num, ids, xs, ys); handleTouchesOfEndOrCancel(EventTouch::EventCode::ENDED, num, ids, xs, ys);
} }
void EGLViewProtocol::handleTouchesCancel(int num, int ids[], float xs[], float ys[]) void GLViewProtocol::handleTouchesCancel(int num, int ids[], float xs[], float ys[])
{ {
handleTouchesOfEndOrCancel(EventTouch::EventCode::CANCELLED, num, ids, xs, ys); handleTouchesOfEndOrCancel(EventTouch::EventCode::CANCELLED, num, ids, xs, ys);
} }
const Rect& EGLViewProtocol::getViewPortRect() const const Rect& GLViewProtocol::getViewPortRect() const
{ {
return _viewPortRect; return _viewPortRect;
} }
float EGLViewProtocol::getScaleX() const float GLViewProtocol::getScaleX() const
{ {
return _scaleX; return _scaleX;
} }
float EGLViewProtocol::getScaleY() const float GLViewProtocol::getScaleY() const
{ {
return _scaleY; return _scaleY;
} }

View File

@ -23,8 +23,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#ifndef __CCEGLVIEWPROTOCOL_H__ #ifndef __CCGLVIEWPROTOCOL_H__
#define __CCEGLVIEWPROTOCOL_H__ #define __CCGLVIEWPROTOCOL_H__
#include "ccTypes.h" #include "ccTypes.h"
#include "CCEventTouch.h" #include "CCEventTouch.h"
@ -65,30 +65,30 @@ class EGLTouchDelegate;
* @{ * @{
*/ */
class CC_DLL EGLViewProtocol class CC_DLL GLViewProtocol
{ {
public: public:
/** /**
* @js ctor * @js ctor
*/ */
EGLViewProtocol(); GLViewProtocol();
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual ~EGLViewProtocol(); virtual ~GLViewProtocol();
/** Force destroying EGL view, subclass must implement this method. */ /** Force destroying EGL view, subclass must implement this method. */
virtual void end() = 0; virtual void end() = 0;
/** Get whether opengl render system is ready, subclass must implement this method. */ /** Get whether opengl render system is ready, subclass must implement this method. */
virtual bool isOpenGLReady() = 0; virtual bool isOpenGLReady() = 0;
/** Exchanges the front and back buffers, subclass must implement this method. */ /** Exchanges the front and back buffers, subclass must implement this method. */
virtual void swapBuffers() = 0; virtual void swapBuffers() = 0;
/** Open or close IME keyboard , subclass must implement this method. */ /** Open or close IME keyboard , subclass must implement this method. */
virtual void setIMEKeyboardState(bool open) = 0; virtual void setIMEKeyboardState(bool open) = 0;
/** /**
* Polls input events. Subclass must implement methods if platform * Polls input events. Subclass must implement methods if platform
@ -133,9 +133,6 @@ public:
*/ */
virtual const Size& getDesignResolutionSize() const; virtual const Size& getDesignResolutionSize() const;
/** Set touch delegate */
virtual void setTouchDelegate(EGLTouchDelegate * delegate);
/** /**
* Set opengl view port rectangle with points. * Set opengl view port rectangle with points.
*/ */
@ -184,8 +181,6 @@ public:
protected: protected:
void handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]); void handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]);
EGLTouchDelegate* _delegate;
// real screen size // real screen size
Size _screenSize; Size _screenSize;
// resolution size, it is the size appropriate for the app resources. // resolution size, it is the size appropriate for the app resources.
@ -195,8 +190,8 @@ protected:
// the view name // the view name
std::string _viewName; std::string _viewName;
float _scaleX; float _scaleX;
float _scaleY; float _scaleY;
ResolutionPolicy _resolutionPolicy; ResolutionPolicy _resolutionPolicy;
}; };
@ -205,4 +200,4 @@ protected:
NS_CC_END NS_CC_END
#endif /* __CCEGLVIEWPROTOCOL_H__ */ #endif /* __CCGLVIEWPROTOCOL_H__ */

View File

@ -10,7 +10,7 @@ LOCAL_SRC_FILES := \
CCApplication.cpp \ CCApplication.cpp \
CCCommon.cpp \ CCCommon.cpp \
CCDevice.cpp \ CCDevice.cpp \
CCEGLView.cpp \ CCGLView.cpp \
CCFileUtilsAndroid.cpp \ CCFileUtilsAndroid.cpp \
CCImage.cpp \ CCImage.cpp \
nativeactivity.cpp \ nativeactivity.cpp \

View File

@ -22,11 +22,15 @@ 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "jni/JniHelper.h" #include "jni/JniHelper.h"
#include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h" #include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
#include "CCApplication.h" #include "CCApplication.h"
#include "CCDirector.h" #include "CCDirector.h"
#include "CCEGLView.h" #include "CCGLView.h"
#include <android/log.h> #include <android/log.h>
#include <jni.h> #include <jni.h>
#include <cstring> #include <cstring>
@ -116,6 +120,10 @@ LanguageType Application::getCurrentLanguage()
{ {
ret = LanguageType::RUSSIAN; ret = LanguageType::RUSSIAN;
} }
else if (0 == strcmp("nl", pLanguageName))
{
ret = LanguageType::DUTCH;
}
else if (0 == strcmp("ko", pLanguageName)) else if (0 == strcmp("ko", pLanguageName))
{ {
ret = LanguageType::KOREAN; ret = LanguageType::KOREAN;
@ -157,3 +165,6 @@ void Application::applicationScreenSizeChanged(int newWidth, int newHeight) {
} }
NS_CC_END NS_CC_END
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID

View File

@ -22,9 +22,13 @@ 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#ifndef __CC_APPLICATION_ANDROID_H__ #ifndef __CC_APPLICATION_ANDROID_H__
#define __CC_APPLICATION_ANDROID_H__ #define __CC_APPLICATION_ANDROID_H__
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "platform/CCCommon.h" #include "platform/CCCommon.h"
#include "platform/CCApplicationProtocol.h" #include "platform/CCApplicationProtocol.h"
@ -87,4 +91,6 @@ protected:
NS_CC_END NS_CC_END
#endif // __CC_APPLICATION_ANDROID_H__ #endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#endif // __CC_APPLICATION_ANDROID_H__

View File

@ -23,6 +23,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "platform/CCCommon.h" #include "platform/CCCommon.h"
#include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h" #include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
#include <android/log.h> #include <android/log.h>
@ -44,3 +47,6 @@ void LuaLog(const char * pszFormat)
} }
NS_CC_END NS_CC_END
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID

View File

@ -22,6 +22,10 @@ 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "platform/CCDevice.h" #include "platform/CCDevice.h"
#include "jni/DPIJni.h" #include "jni/DPIJni.h"
#include "nativeactivity.h" #include "nativeactivity.h"
@ -56,3 +60,6 @@ void Device::setAccelerometerInterval(float interval)
} }
NS_CC_END NS_CC_END
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID

View File

@ -22,6 +22,10 @@ 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "CCFileUtilsAndroid.h" #include "CCFileUtilsAndroid.h"
#include "platform/CCCommon.h" #include "platform/CCCommon.h"
#include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h" #include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
@ -353,3 +357,5 @@ string FileUtilsAndroid::getWritablePath() const
} }
NS_CC_END NS_CC_END
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID

View File

@ -25,6 +25,9 @@ Copyright (c) 2013-2014 Chukong Technologies Inc.
#ifndef __CC_FILEUTILS_ANDROID_H__ #ifndef __CC_FILEUTILS_ANDROID_H__
#define __CC_FILEUTILS_ANDROID_H__ #define __CC_FILEUTILS_ANDROID_H__
#include "CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "platform/CCFileUtils.h" #include "platform/CCFileUtils.h"
#include "CCPlatformMacros.h" #include "CCPlatformMacros.h"
#include "ccTypes.h" #include "ccTypes.h"
@ -86,4 +89,6 @@ private:
NS_CC_END NS_CC_END
#endif // __CC_FILEUTILS_ANDROID_H__ #endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#endif // __CC_FILEUTILS_ANDROID_H__

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