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

This commit is contained in:
bmanGH 2013-11-11 23:29:45 +08:00
commit 9989426d8a
470 changed files with 14967 additions and 15522 deletions

5
.gitignore vendored
View File

@ -100,3 +100,8 @@ tools/jenkins_scripts/mac/android/userconf.ini
# CTags # CTags
tags tags
# ignore files, created with make-all-linux-project script
/lib
/build/linux-build

View File

@ -26,3 +26,9 @@ script:
- tools/travis-scripts/run-script.sh - tools/travis-scripts/run-script.sh
before_install: before_install:
- tools/travis-scripts/before-install.sh - tools/travis-scripts/before-install.sh
# whitelist
branches:
only:
- master
- develop

View File

@ -628,6 +628,7 @@ Developers:
HoGarfield (garfield_ho) HoGarfield (garfield_ho)
Fixed a bug that CCBReader can't play sequence automatically in JSB. Fixed a bug that CCBReader can't play sequence automatically in JSB.
Could not set next animation in CCBAnimationCompleted callback. Could not set next animation in CCBAnimationCompleted callback.
Fixed missing to add JSAutoCompartment when invoking JS functions from C++.
lite3 lite3
Fixed a bug that Node's anchor point was changed after being added to ScrollView. Fixed a bug that Node's anchor point was changed after being added to ScrollView.
@ -640,6 +641,13 @@ Developers:
ledyba ledyba
Fixed a bug that EventListeners can't be removed sometimes. Fixed a bug that EventListeners can't be removed sometimes.
Fixed a bug that the data size has to be specified when parsing XML using TinyXML.
Luis Parravicini (luisparravicini)
Fixed typos in create_project.py.
xhcnb
Device::setAccelerometerEnabled needs to be invoked before adding ACC listener.
Retired Core Developers: Retired Core Developers:
WenSheng Yang WenSheng Yang

View File

@ -10,19 +10,30 @@ cocos2d-x-3.0alpha1 @??? 2013
[FIX] Could not set next animation in CCBAnimationCompleted callback. [FIX] Could not set next animation in CCBAnimationCompleted callback.
[FIX] The Node's anchor point was changed after being added to ScrollView. [FIX] The Node's anchor point was changed after being added to ScrollView.
[FIX] Refactored and improved EventDispatcher. [FIX] Refactored and improved EventDispatcher.
[NEW] Added Mouse Support For Desktop Platforms.
[FIX] EventListeners can't be removed sometimes. [FIX] EventListeners can't be removed sometimes.
[FIX] When parsing XML using TinyXML, the data size has to be specified.
[FIX] Parameter type: const char* -> const string&
[FIX] Armature: many bug fixed, add more samples, add function to skip some frames when playing animation
[NEW] Arm64 support.
[NEW] Added Mouse Support For Desktop Platforms.
[NEW] Point: Adds ANCHOR_XXX constants like ANCHOR_MIDDLE, ANCHOR_TOP_RIGHT, etc.
[NEW] Sprite: Override setScale(float scaleX, float scaleY)
[NEW] External: added | operator for Control::EventType
[NEW] Android & iOS screen size change support
[Android] [Android]
[FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes
[NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again
[FIX] Fixed application will crash when pause and resume. [FIX] Fixed application will crash when pause and resume.
[FIX] Clear NoSuchMethodError Exception when JniHelper fails to find method id [FIX] Clear NoSuchMethodError Exception when JniHelper fails to find method id
[NEW] Added xlargeScreens="true" to supports-screens [NEW] Added xlargeScreens="true" to supports-screens
[NEW] Added build/android-build.py to build all Android samples [NEW] Added build/android-build.py to build all Android samples, and remove all build_native.sh/cmd
[NEW] Added build_native.py to build template projects, and remove build_native.sh/cmd
[NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again
[Mac] [Mac]
[FIX] Removed unused CCLOG() from GL initialization [FIX] Removed unused CCLOG() from GL initialization
[iOS] [iOS]
[FIX] Can't click the area that outside of keyboard to close keyboard when using EditBox. [FIX] Can't click the area that outside of keyboard to close keyboard when using EditBox.
[Linux]
[NEW] Used CMake to build linux projects.
[Desktop] [Desktop]
[FIX] Trigger onKeyReleased only after the key has been released. [FIX] Trigger onKeyReleased only after the key has been released.
[Javascript binding] [Javascript binding]
@ -30,6 +41,7 @@ cocos2d-x-3.0alpha1 @??? 2013
[FIX] sys.localStorage.getItem() does not support non-ascii string. [FIX] sys.localStorage.getItem() does not support non-ascii string.
[FIX] cc.Scheduler.schedule(target, func) without repeat argument couldn't repeat schedule forever on device. [FIX] cc.Scheduler.schedule(target, func) without repeat argument couldn't repeat schedule forever on device.
[FIX] CCBReader can't play sequence automatically in JSB. [FIX] CCBReader can't play sequence automatically in JSB.
[NEW] main.js -> cocos2d-jsb.js
[Lua Binding] [Lua Binding]
[NEW] Added Armature lua binding and added test samples. [NEW] Added Armature lua binding and added test samples.

164
CMakeLists.txt Normal file
View File

@ -0,0 +1,164 @@
cmake_minimum_required(VERSION 2.6)
project (Cocos2dx)
# The version number
set(Cocos2dxSamples_VERSION_MAJOR 3)
set(Cocos2dxSamples_VERSION_MINOR 0)
include(build/BuildHelpers.CMakeLists.txt)
option(USE_CHIPMUNK "Use chipmunk for physics library" ON)
option(USE_BOX2D "Use box2d for physics library" OFF)
option(DEBUG_MODE "Debug or release?" ON)
option(BUILD_LIBS_LUA "Build lua libraries" ON)
option(BUILD_GUI "Build GUI library" ON)
option(BUILD_NETWORK "Build network library" ON)
option(BUILD_EXTENSIONS "Build extension library" ON)
option(BUILD_EDITOR_SPINE "Build editor support for spine" ON)
option(BUILD_EDITOR_COCOSTUDIO "Build editor support for cocostudio" 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_HelloLua "Only build HelloLua sample" ON)
option(BUILD_TestLua "Only build TestLua sample" ON)
if(DEBUG_MODE)
set(CMAKE_BUILD_TYPE DEBUG)
else(DEBUG_MODE)
set(CMAKE_BUILD_TYPE RELEASE)
endif(DEBUG_MODE)
set(CMAKE_C_FLAGS_DEBUG "-g -Wall -DCOCOS2D_DEBUG=1")
set(CMAKE_CXX_FLAGS_DEBUG ${CMAKE_C_FLAGS_DEBUG})
set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "-std=c99")
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11")
if(USE_CHIPMUNK)
message("Using chipmunk ...")
add_definitions(-DLINUX -DCC_ENABLE_CHIPMUNK_INTEGRATION=1)
elseif(USE_BOX2D)
message("Using box2d ...")
add_definitions(-DLINUX -DCC_ENABLE_BOX2D_INTEGRATION=1)
else(USE_CHIPMUNK)
message(FATAL_ERROR "Must choose a physics library.")
endif(USE_CHIPMUNK)
# architecture
if ( CMAKE_SIZEOF_VOID_P EQUAL 8 )
set(ARCH_DIR "64-bit")
else()
set(ARCH_DIR "32-bit")
endif()
include_directories(
.
cocos
cocos/audio/include
cocos/2d
cocos/2d/platform
cocos/2d/platform/linux
cocos/base
cocos/physics
cocos/editor-support
cocos/math/kazmath/include
extensions
external
external/jpeg/include/linux
external/tiff/include/linux
external/webp/include/linux
external/glfw3/include/linux
external/curl/include/linux/${ARCH_DIR}
external/tinyxml2
external/unzip
external/chipmunk/include/chipmunk
external/freetype2/include/linux
external/linux-specific/fmod/include/${ARCH_DIR}
)
link_directories(
/usr/local/lib
${CMAKE_SOURCE_DIR}/external/jpeg/prebuilt/linux/${ARCH_DIR}
${CMAKE_SOURCE_DIR}/external/tiff/prebuilt/linux/${ARCH_DIR}
${CMAKE_SOURCE_DIR}/external/webp/prebuilt/linux/${ARCH_DIR}
${CMAKE_SOURCE_DIR}/external/freetype2/prebuilt/linux/${ARCH_DIR}
${CMAKE_SOURCE_DIR}/external/curl/prebuilt/linux/${ARCH_DIR}
${CMAKE_SOURCE_DIR}/external/linux-specific/fmod/prebuilt/${ARCH_DIR}
)
# kazmath
add_subdirectory(cocos/math/kazmath)
# chipmunk library
add_subdirectory(external/chipmunk/src)
# box2d library
add_subdirectory(external/Box2D)
# unzip library
add_subdirectory(external/unzip)
# tinyxml2 library
add_subdirectory(external/tinyxml2)
# audio
add_subdirectory(cocos/audio)
# cocos base library
add_subdirectory(cocos/base)
# cocos 2d library
add_subdirectory(cocos/2d)
if(BUILD_GUI)
# gui
add_subdirectory(cocos/gui)
endif(BUILD_GUI)
if(BUILD_NETWORK)
# network
add_subdirectory(cocos/network)
endif(BUILD_NETWORK)
if(BUILD_EXTENSIONS)
# extensions
add_subdirectory(extensions)
endif(BUILD_EXTENSIONS)
## Editor Support
if(BUILD_EDITOR_SPINE)
# spine
add_subdirectory(cocos/editor-support/spine)
endif(BUILD_EDITOR_SPINE)
if(BUILD_EDITOR_COCOSBUILDER)
# cocosbuilder
add_subdirectory(cocos/editor-support/cocosbuilder)
endif(BUILD_EDITOR_COCOSBUILDER)
if(BUILD_EDITOR_COCOSTUDIO)
# cocostudio
add_subdirectory(cocos/editor-support/cocostudio)
# jsoncpp library, cocostuido depends on jsoncpp
add_subdirectory(external/json)
endif(BUILD_EDITOR_COCOSTUDIO)
if(BUILD_LIBS_LUA)
## Scripting
# lua
add_subdirectory(external/lua/lua)
# tolua
add_subdirectory(external/lua/tolua)
# luabinding
add_subdirectory(cocos/scripting)
endif(BUILD_LIBS_LUA)
# build samples
add_subdirectory(samples)

View File

@ -29,8 +29,8 @@ How to start a new game
Example: Example:
$ cd cocos2d-x/tools/project-creator $ cd cocos2d-x/tools/project-creator
$ ./create-multi-platform-projects.py -p mygame -k com.your_company.mygame -l cpp $ ./create-multi-platform-projects.py -p mygame -k com.your_company.mygame -l cpp
$ cd ../../projects/mygame $ cd ../../projects/mygame
@ -70,7 +70,7 @@ Build Requirements
------------------ ------------------
* Mac OS X 10.7+, Xcode 4.6+ * Mac OS X 10.7+, Xcode 4.6+
* or Ubuntu 13.04+ * or Ubuntu 12.10+, CMake 2.6+
* or Windows 7+, VS 2012+ * or Windows 7+, VS 2012+
@ -98,9 +98,14 @@ $ open samples.xcodeproj
``` ```
$ cd cocos2d-x/build $ cd cocos2d-x/build
$ ./make-all-linux-projects.sh $ ./install-deps-linux.sh
$ cmake ..
$ make
``` ```
You may meet building errors when building libGLFW.so. It is because libGL.so directs to an error target, you should make it to direct to a correct one.
`install-deps-linux.sh` only has to be run onece.
* For Windows * For Windows
Open the `cocos2d-x/build/cocos2d-win32.vc2012.sln` Open the `cocos2d-x/build/cocos2d-win32.vc2012.sln`

View File

@ -0,0 +1,13 @@
macro(pre_build TARGET_NAME)
add_custom_target( ${TARGET_NAME}_PRE_BUILD ALL )
add_custom_command(
TARGET ${TARGET_NAME}_PRE_BUILD
${ARGN}
PRE_BUILD
COMMENT "${TARGET_NAME}_PRE_BUILD ..."
)
add_custom_target( ${TARGET_NAME}_CORE_PRE_BUILD )
add_dependencies( ${TARGET_NAME}_PRE_BUILD ${TARGET_NAME}_CORE_PRE_BUILD )
endmacro()

View File

@ -1,91 +0,0 @@
PLATFORM ?= linux
all:
chipmunk:
$(MAKE) -C ../external/chipmunk/proj.$(PLATFORM)
chipmunk-clean:
$(MAKE) -C ../external/chipmunk/proj.$(PLATFORM) clean
box2d:
$(MAKE) -C ../external/Box2D/proj.$(PLATFORM)
box2d-clean:
$(MAKE) -C ../external/Box2D/proj.$(PLATFORM) clean
cocos2dx: chipmunk
$(MAKE) -C ../cocos/2d
cocos2dx-clean:
$(MAKE) -C ../cocos/2d clean
audio: cocos2dx
$(MAKE) -C ../cocos/audio/proj.$(PLATFORM)
audio-clean:
$(MAKE) -C ../cocos/audio/proj.$(PLATFORM) clean
gui:
$(MAKE) -C ../cocos/gui
gui-clean:
$(MAKE) -C ../cocos/gui clean
network: cocos2dx
$(MAKE) -C ../cocos/network
network-clean:
$(MAKE) -C ../cocos/network clean
cocosbuilder:
$(MAKE) -C ../cocos/editor-support/cocosbuilder
cocosbuilder-clean:
$(MAKE) -C ../cocos/editor-support/cocosbuilder clean
spine:
$(MAKE) -C ../cocos/editor-support/spine
spine-clean:
$(MAKE) -C ../cocos/editor-support/spine clean
cocostudio:
$(MAKE) -C ../cocos/editor-support/cocostudio
cocostudio-clean:
$(MAKE) -C ../cocos/editor-support/cocostudio clean
extensions: chipmunk audio box2d
$(MAKE) -C ../extensions/proj.$(PLATFORM)
extensions-clean:
$(MAKE) -C ../extensions/proj.$(PLATFORM) clean
lua: extensions cocosbuilder cocostudio
$(MAKE) -C ../cocos/scripting/lua/bindings
lua-clean:
$(MAKE) -C ../cocos/scripting/lua/bindings clean
hellocpp: cocos2dx
$(MAKE) -C ../samples/Cpp/HelloCpp/proj.$(PLATFORM)
hellocpp-clean:
$(MAKE) -C ../samples/Cpp/HelloCpp/proj.$(PLATFORM) clean
testcpp: cocos2dx audio extensions cocostudio gui cocosbuilder spine network
$(MAKE) -C ../samples/Cpp/TestCpp/proj.$(PLATFORM)
testcpp-clean:
$(MAKE) -C ../samples/Cpp/TestCpp/proj.$(PLATFORM) clean
simplegame: cocos2dx audio
$(MAKE) -C ../samples/Cpp/SimpleGame/proj.$(PLATFORM)
simplegame-clean:
$(MAKE) -C ../samples/Cpp/SimpleGame/proj.$(PLATFORM) clean
all: chipmunk audio extensions cocos2dx lua hellocpp testcpp simplegame
clean: cocos2dx-clean box2d-clean chipmunk-clean audio-clean extensions-clean lua-clean hellocpp-clean testcpp-clean simplegame-clean
hellolua: cocos2dx lua
$(MAKE) -C ../samples/Lua/HelloLua/proj.$(PLATFORM)
hellolua-clean:
$(MAKE) -C ../samples/Lua/HelloLua/proj.$(PLATFORM) clean
testlua: cocos2dx lua
$(MAKE) -C ../samples/Lua/TestLua/proj.$(PLATFORM)
testlua-clean:
$(MAKE) -C ../samples/Lua/TestLua/proj.$(PLATFORM) clean
all: hellolua testlua
clean: hellolua-clean testlua-clean
.PHONY: all clean

View File

@ -2,10 +2,6 @@
# android-build.py # android-build.py
# Build android samples # Build android samples
# You can use
# begin
import sys import sys
import os, os.path import os, os.path
import shutil import shutil
@ -99,7 +95,8 @@ def do_build(cocos_root, ndk_root, app_android_root, ndk_build_param):
command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path) command = '%s -C %s %s' % (ndk_path, 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 -C %s %s %s' % (ndk_path, app_android_root, ndk_build_param, ndk_module_path)
os.system(command) if os.system(command) != 0:
raise Exception("Build project [ " + app_android_root + " ] fails!")
def copy_files(src, dst): def copy_files(src, dst):
@ -182,15 +179,15 @@ def build_samples(target,ndk_build_param):
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, 'samples/Lua/TestLua/proj.android')
elif target == 'cocosdragon': elif target == 'cocosdragon':
app_android_root = os.path.join(cocos_root, 'samples/JavaScript/CocosDragonJS/proj.android') app_android_root = os.path.join(cocos_root, 'samples/Javascript/CocosDragonJS/proj.android')
elif target == 'crystalcraze': elif target == 'crystalcraze':
app_android_root = os.path.join(cocos_root, 'samples/JavaScript/CrystalCraze/proj.android') app_android_root = os.path.join(cocos_root, 'samples/Javascript/CrystalCraze/proj.android')
elif target == 'moonwarriors': elif target == 'moonwarriors':
app_android_root = os.path.join(cocos_root, 'samples/JavaScript/MoonWarriors/proj.android') 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, 'samples/Javascript/TestJavascript/proj.android')
elif target == 'watermelonwithme': elif target == 'watermelonwithme':
app_android_root = os.path.join(cocos_root, 'samples/JavaScript/WatermelonWithMe/proj.android') 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
@ -209,4 +206,8 @@ if __name__ == '__main__':
if len(args) == 0: if len(args) == 0:
usage() usage()
else: else:
build_samples(args, opts.ndk_build_param) try:
build_samples(args, opts.ndk_build_param)
except Exception as e:
print e
sys.exit(1)

View File

@ -1 +1 @@
8c640bf1e2f1cd0a489e6169c930234b809636f2 a70914e0a87ee8ced4d662bd6038fc955e77f6ca

View File

@ -1 +1 @@
b473303312be3b69891020b5fb470dd382f31284 3ff18018375c71f683a484652678740cc6395eaf

View File

@ -1,26 +0,0 @@
#!/bin/bash
# This script will perform a clean linux build of all targets in both
# debug and release configurations. It will also ensure that all the required
# packages are installed. For day-to-day work on the linux port it is
# faster/better to simply use 'make' either at the top level or in the subpject
# you are working on.
# Exit of first error.
set -e
# Change directory to the location of this script
cd $(dirname ${BASH_SOURCE[0]})
[ -z "$COCOS2DX_USEAPT" ] && COCOS2DX_USEAPT=true
if $COCOS2DX_USEAPT; then
./install-deps-linux.sh
fi
export MAKEFLAGS=-j10
make PLATFORM=linux DEBUG=1 clean
make PLATFORM=linux DEBUG=0 clean
make PLATFORM=linux DEBUG=1 all
make PLATFORM=linux DEBUG=0 all

View File

@ -149,16 +149,16 @@ platform/CCThread.cpp \
../physics/CCPhysicsJoint.cpp \ ../physics/CCPhysicsJoint.cpp \
../physics/CCPhysicsShape.cpp \ ../physics/CCPhysicsShape.cpp \
../physics/CCPhysicsWorld.cpp \ ../physics/CCPhysicsWorld.cpp \
../physics/box2d/CCPhysicsBodyInfo.cpp \ ../physics/box2d/CCPhysicsBodyInfo_box2d.cpp \
../physics/box2d/CCPhysicsContactInfo.cpp \ ../physics/box2d/CCPhysicsContactInfo_box2d.cpp \
../physics/box2d/CCPhysicsJointInfo.cpp \ ../physics/box2d/CCPhysicsJointInfo_box2d.cpp \
../physics/box2d/CCPhysicsShapeInfo.cpp \ ../physics/box2d/CCPhysicsShapeInfo_box2d.cpp \
../physics/box2d/CCPhysicsWorldInfo.cpp \ ../physics/box2d/CCPhysicsWorldInfo_box2d.cpp \
../physics/chipmunk/CCPhysicsBodyInfo.cpp \ ../physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp \
../physics/chipmunk/CCPhysicsContactInfo.cpp \ ../physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp \
../physics/chipmunk/CCPhysicsJointInfo.cpp \ ../physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp \
../physics/chipmunk/CCPhysicsShapeInfo.cpp \ ../physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp \
../physics/chipmunk/CCPhysicsWorldInfo.cpp \ ../physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp \
../../external/tinyxml2/tinyxml2.cpp \ ../../external/tinyxml2/tinyxml2.cpp \
../../external/unzip/ioapi.cpp \ ../../external/unzip/ioapi.cpp \
../../external/unzip/unzip.cpp ../../external/unzip/unzip.cpp

View File

@ -203,7 +203,7 @@ Sequence* Sequence::create(Array* arrayOfActions)
Sequence* pRet = NULL; Sequence* pRet = NULL;
do do
{ {
unsigned int count = arrayOfActions->count(); long count = arrayOfActions->count();
CC_BREAK_IF(count == 0); CC_BREAK_IF(count == 0);
FiniteTimeAction* prev = static_cast<FiniteTimeAction*>(arrayOfActions->getObjectAtIndex(0)); FiniteTimeAction* prev = static_cast<FiniteTimeAction*>(arrayOfActions->getObjectAtIndex(0));
@ -576,7 +576,7 @@ Spawn* Spawn::create(Array *arrayOfActions)
Spawn* pRet = NULL; Spawn* pRet = NULL;
do do
{ {
unsigned int count = arrayOfActions->count(); long count = arrayOfActions->count();
CC_BREAK_IF(count == 0); CC_BREAK_IF(count == 0);
FiniteTimeAction* prev = static_cast<FiniteTimeAction*>(arrayOfActions->getObjectAtIndex(0)); FiniteTimeAction* prev = static_cast<FiniteTimeAction*>(arrayOfActions->getObjectAtIndex(0));
if (count > 1) if (count > 1)
@ -2100,7 +2100,7 @@ void Animate::update(float t)
} }
Array* frames = _animation->getFrames(); Array* frames = _animation->getFrames();
int numberOfFrames = frames->count(); long numberOfFrames = frames->count();
SpriteFrame *frameToDisplay = NULL; SpriteFrame *frameToDisplay = NULL;
for( int i=_nextFrame; i < numberOfFrames; i++ ) { for( int i=_nextFrame; i < numberOfFrames; i++ ) {

View File

@ -65,55 +65,55 @@ ActionManager::~ActionManager(void)
// private // private
void ActionManager::deleteHashElement(tHashElement *pElement) void ActionManager::deleteHashElement(tHashElement *element)
{ {
ccArrayFree(pElement->actions); ccArrayFree(element->actions);
HASH_DEL(_targets, pElement); HASH_DEL(_targets, element);
pElement->target->release(); element->target->release();
free(pElement); free(element);
} }
void ActionManager::actionAllocWithHashElement(tHashElement *pElement) void ActionManager::actionAllocWithHashElement(tHashElement *element)
{ {
// 4 actions per Node by default // 4 actions per Node by default
if (pElement->actions == NULL) if (element->actions == NULL)
{ {
pElement->actions = ccArrayNew(4); element->actions = ccArrayNew(4);
}else }else
if (pElement->actions->num == pElement->actions->max) if (element->actions->num == element->actions->max)
{ {
ccArrayDoubleCapacity(pElement->actions); ccArrayDoubleCapacity(element->actions);
} }
} }
void ActionManager::removeActionAtIndex(int index, tHashElement *pElement) void ActionManager::removeActionAtIndex(long index, tHashElement *element)
{ {
Action *pAction = (Action*)pElement->actions->arr[index]; Action *action = (Action*)element->actions->arr[index];
if (pAction == pElement->currentAction && (! pElement->currentActionSalvaged)) if (action == element->currentAction && (! element->currentActionSalvaged))
{ {
pElement->currentAction->retain(); element->currentAction->retain();
pElement->currentActionSalvaged = true; element->currentActionSalvaged = true;
} }
ccArrayRemoveObjectAtIndex(pElement->actions, index, true); ccArrayRemoveObjectAtIndex(element->actions, index, true);
// update actionIndex in case we are in tick. looping over the actions // update actionIndex in case we are in tick. looping over the actions
if (pElement->actionIndex >= index) if (element->actionIndex >= index)
{ {
pElement->actionIndex--; element->actionIndex--;
} }
if (pElement->actions->num == 0) if (element->actions->num == 0)
{ {
if (_currentTarget == pElement) if (_currentTarget == element)
{ {
_currentTargetSalvaged = true; _currentTargetSalvaged = true;
} }
else else
{ {
deleteHashElement(pElement); deleteHashElement(element);
} }
} }
} }
@ -122,21 +122,21 @@ void ActionManager::removeActionAtIndex(int index, tHashElement *pElement)
void ActionManager::pauseTarget(Object *target) void ActionManager::pauseTarget(Object *target)
{ {
tHashElement *pElement = NULL; tHashElement *element = NULL;
HASH_FIND_INT(_targets, &target, pElement); HASH_FIND_PTR(_targets, &target, element);
if (pElement) if (element)
{ {
pElement->paused = true; element->paused = true;
} }
} }
void ActionManager::resumeTarget(Object *target) void ActionManager::resumeTarget(Object *target)
{ {
tHashElement *pElement = NULL; tHashElement *element = NULL;
HASH_FIND_INT(_targets, &target, pElement); HASH_FIND_PTR(_targets, &target, element);
if (pElement) if (element)
{ {
pElement->paused = false; element->paused = false;
} }
} }
@ -168,40 +168,40 @@ void ActionManager::resumeTargets(cocos2d::Set *targetsToResume)
// run // run
void ActionManager::addAction(Action *pAction, Node *target, bool paused) void ActionManager::addAction(Action *action, Node *target, bool paused)
{ {
CCASSERT(pAction != NULL, ""); CCASSERT(action != NULL, "");
CCASSERT(target != NULL, ""); CCASSERT(target != NULL, "");
tHashElement *pElement = NULL; tHashElement *element = NULL;
// we should convert it to Object*, because we save it as Object* // we should convert it to Object*, because we save it as Object*
Object *tmp = target; Object *tmp = target;
HASH_FIND_INT(_targets, &tmp, pElement); HASH_FIND_PTR(_targets, &tmp, element);
if (! pElement) if (! element)
{ {
pElement = (tHashElement*)calloc(sizeof(*pElement), 1); element = (tHashElement*)calloc(sizeof(*element), 1);
pElement->paused = paused; element->paused = paused;
target->retain(); target->retain();
pElement->target = target; element->target = target;
HASH_ADD_INT(_targets, target, pElement); HASH_ADD_PTR(_targets, target, element);
} }
actionAllocWithHashElement(pElement); actionAllocWithHashElement(element);
CCASSERT(! ccArrayContainsObject(pElement->actions, pAction), ""); CCASSERT(! ccArrayContainsObject(element->actions, action), "");
ccArrayAppendObject(pElement->actions, pAction); ccArrayAppendObject(element->actions, action);
pAction->startWithTarget(target); action->startWithTarget(target);
} }
// remove // remove
void ActionManager::removeAllActions(void) void ActionManager::removeAllActions(void)
{ {
for (tHashElement *pElement = _targets; pElement != NULL; ) for (tHashElement *element = _targets; element != NULL; )
{ {
Object *target = pElement->target; Object *target = element->target;
pElement = (tHashElement*)pElement->hh.next; element = (tHashElement*)element->hh.next;
removeAllActionsFromTarget(target); removeAllActionsFromTarget(target);
} }
} }
@ -214,24 +214,24 @@ void ActionManager::removeAllActionsFromTarget(Object *target)
return; return;
} }
tHashElement *pElement = NULL; tHashElement *element = NULL;
HASH_FIND_INT(_targets, &target, pElement); HASH_FIND_PTR(_targets, &target, element);
if (pElement) if (element)
{ {
if (ccArrayContainsObject(pElement->actions, pElement->currentAction) && (! pElement->currentActionSalvaged)) if (ccArrayContainsObject(element->actions, element->currentAction) && (! element->currentActionSalvaged))
{ {
pElement->currentAction->retain(); element->currentAction->retain();
pElement->currentActionSalvaged = true; element->currentActionSalvaged = true;
} }
ccArrayRemoveAllObjects(pElement->actions); ccArrayRemoveAllObjects(element->actions);
if (_currentTarget == pElement) if (_currentTarget == element)
{ {
_currentTargetSalvaged = true; _currentTargetSalvaged = true;
} }
else else
{ {
deleteHashElement(pElement); deleteHashElement(element);
} }
} }
else else
@ -240,23 +240,23 @@ void ActionManager::removeAllActionsFromTarget(Object *target)
} }
} }
void ActionManager::removeAction(Action *pAction) void ActionManager::removeAction(Action *action)
{ {
// explicit null handling // explicit null handling
if (pAction == NULL) if (action == NULL)
{ {
return; return;
} }
tHashElement *pElement = NULL; tHashElement *element = NULL;
Object *target = pAction->getOriginalTarget(); Object *target = action->getOriginalTarget();
HASH_FIND_INT(_targets, &target, pElement); HASH_FIND_PTR(_targets, &target, element);
if (pElement) if (element)
{ {
unsigned int i = ccArrayGetIndexOfObject(pElement->actions, pAction); long i = ccArrayGetIndexOfObject(element->actions, action);
if (UINT_MAX != i) if (i != CC_INVALID_INDEX)
{ {
removeActionAtIndex(i, pElement); removeActionAtIndex(i, element);
} }
} }
else else
@ -270,19 +270,19 @@ void ActionManager::removeActionByTag(int tag, Object *target)
CCASSERT(tag != Action::INVALID_TAG, ""); CCASSERT(tag != Action::INVALID_TAG, "");
CCASSERT(target != NULL, ""); CCASSERT(target != NULL, "");
tHashElement *pElement = NULL; tHashElement *element = NULL;
HASH_FIND_INT(_targets, &target, pElement); HASH_FIND_PTR(_targets, &target, element);
if (pElement) if (element)
{ {
unsigned int limit = pElement->actions->num; long limit = element->actions->num;
for (unsigned int i = 0; i < limit; ++i) for (long i = 0; i < limit; ++i)
{ {
Action *pAction = (Action*)pElement->actions->arr[i]; Action *action = (Action*)element->actions->arr[i];
if (pAction->getTag() == (int)tag && pAction->getOriginalTarget() == target) if (action->getTag() == (int)tag && action->getOriginalTarget() == target)
{ {
removeActionAtIndex(i, pElement); removeActionAtIndex(i, element);
break; break;
} }
} }
@ -297,21 +297,21 @@ Action* ActionManager::getActionByTag(int tag, const Object *target) const
{ {
CCASSERT(tag != Action::INVALID_TAG, ""); CCASSERT(tag != Action::INVALID_TAG, "");
tHashElement *pElement = NULL; tHashElement *element = NULL;
HASH_FIND_INT(_targets, &target, pElement); HASH_FIND_PTR(_targets, &target, element);
if (pElement) if (element)
{ {
if (pElement->actions != NULL) if (element->actions != NULL)
{ {
unsigned int limit = pElement->actions->num; long limit = element->actions->num;
for (unsigned int i = 0; i < limit; ++i) for (long i = 0; i < limit; ++i)
{ {
Action *pAction = (Action*)pElement->actions->arr[i]; Action *action = (Action*)element->actions->arr[i];
if (pAction->getTag() == (int)tag) if (action->getTag() == (int)tag)
{ {
return pAction; return action;
} }
} }
} }
@ -327,13 +327,13 @@ Action* ActionManager::getActionByTag(int tag, const Object *target) const
// XXX: Passing "const O *" instead of "const O&" because HASH_FIND_IT requries the address of a pointer // XXX: Passing "const O *" instead of "const O&" because HASH_FIND_IT requries the address of a pointer
// and, it is not possible to get the address of a reference // and, it is not possible to get the address of a reference
unsigned int ActionManager::getNumberOfRunningActionsInTarget(const Object *target) const long ActionManager::getNumberOfRunningActionsInTarget(const Object *target) const
{ {
tHashElement *pElement = NULL; tHashElement *element = NULL;
HASH_FIND_INT(_targets, &target, pElement); HASH_FIND_PTR(_targets, &target, element);
if (pElement) if (element)
{ {
return pElement->actions ? pElement->actions->num : 0; return element->actions ? element->actions->num : 0;
} }
return 0; return 0;
@ -374,10 +374,10 @@ void ActionManager::update(float dt)
{ {
_currentTarget->currentAction->stop(); _currentTarget->currentAction->stop();
Action *pAction = _currentTarget->currentAction; Action *action = _currentTarget->currentAction;
// Make currentAction nil to prevent removeAction from salvaging it. // Make currentAction nil to prevent removeAction from salvaging it.
_currentTarget->currentAction = NULL; _currentTarget->currentAction = NULL;
removeAction(pAction); removeAction(action);
} }
_currentTarget->currentAction = NULL; _currentTarget->currentAction = NULL;

View File

@ -102,7 +102,7 @@ public:
* - If you are running 1 Sequence of 7 actions, it will return 1. * - If you are running 1 Sequence of 7 actions, it will return 1.
* - If you are running 7 Sequences of 2 actions, it will return 7. * - If you are running 7 Sequences of 2 actions, it will return 7.
*/ */
unsigned int getNumberOfRunningActionsInTarget(const Object *target) const; long getNumberOfRunningActionsInTarget(const Object *target) const;
/** @deprecated use getNumberOfRunningActionsInTarget() instead */ /** @deprecated use getNumberOfRunningActionsInTarget() instead */
CC_DEPRECATED_ATTRIBUTE inline unsigned int numberOfRunningActionsInTarget(Object *target) const { return getNumberOfRunningActionsInTarget(target); } CC_DEPRECATED_ATTRIBUTE inline unsigned int numberOfRunningActionsInTarget(Object *target) const { return getNumberOfRunningActionsInTarget(target); }
@ -126,7 +126,7 @@ public:
protected: protected:
// declared in ActionManager.m // declared in ActionManager.m
void removeActionAtIndex(int index, struct _hashElement *pElement); void removeActionAtIndex(long index, struct _hashElement *pElement);
void deleteHashElement(struct _hashElement *pElement); void deleteHashElement(struct _hashElement *pElement);
void actionAllocWithHashElement(struct _hashElement *pElement); void actionAllocWithHashElement(struct _hashElement *pElement);
void update(float dt); void update(float dt);

View File

@ -28,6 +28,7 @@ THE SOFTWARE.
#include "CCTexture2D.h" #include "CCTexture2D.h"
#include "ccMacros.h" #include "ccMacros.h"
#include "CCSpriteFrame.h" #include "CCSpriteFrame.h"
#include "CCDirector.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -176,7 +177,7 @@ void Animation::addSpriteFrame(SpriteFrame *pFrame)
void Animation::addSpriteFrameWithFile(const char *filename) void Animation::addSpriteFrameWithFile(const char *filename)
{ {
Texture2D *texture = TextureCache::getInstance()->addImage(filename); Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename);
Rect rect = Rect::ZERO; Rect rect = Rect::ZERO;
rect.size = texture->getContentSize(); rect.size = texture->getContentSize();
SpriteFrame *pFrame = SpriteFrame::createWithTexture(texture, rect); SpriteFrame *pFrame = SpriteFrame::createWithTexture(texture, rect);

View File

@ -71,22 +71,20 @@ AnimationCache::~AnimationCache()
CC_SAFE_RELEASE(_animations); CC_SAFE_RELEASE(_animations);
} }
void AnimationCache::addAnimation(Animation *animation, const char * name) void AnimationCache::addAnimation(Animation *animation, const std::string& name)
{ {
_animations->setObject(animation, name); _animations->setObject(animation, name);
} }
void AnimationCache::removeAnimation(const char* name) void AnimationCache::removeAnimation(const std::string& name)
{ {
if (! name) if (name.size()==0)
{
return; return;
}
_animations->removeObjectForKey(name); _animations->removeObjectForKey(name);
} }
Animation* AnimationCache::getAnimation(const char* name) Animation* AnimationCache::getAnimation(const std::string& name)
{ {
return (Animation*)_animations->objectForKey(name); return (Animation*)_animations->objectForKey(name);
} }
@ -95,17 +93,17 @@ void AnimationCache::parseVersion1(Dictionary* animations)
{ {
SpriteFrameCache *frameCache = SpriteFrameCache::getInstance(); SpriteFrameCache *frameCache = SpriteFrameCache::getInstance();
DictElement* pElement = NULL; DictElement* element = NULL;
CCDICT_FOREACH(animations, pElement) CCDICT_FOREACH(animations, element)
{ {
Dictionary* animationDict = static_cast<Dictionary*>(pElement->getObject()); Dictionary* animationDict = static_cast<Dictionary*>(element->getObject());
Array* frameNames = static_cast<Array*>(animationDict->objectForKey("frames")); Array* frameNames = static_cast<Array*>(animationDict->objectForKey("frames"));
float delay = animationDict->valueForKey("delay")->floatValue(); float delay = animationDict->valueForKey("delay")->floatValue();
Animation* animation = NULL; Animation* animation = NULL;
if ( frameNames == NULL ) if ( frameNames == NULL )
{ {
CCLOG("cocos2d: AnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.", pElement->getStrKey()); CCLOG("cocos2d: AnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.", element->getStrKey());
continue; continue;
} }
@ -115,11 +113,11 @@ void AnimationCache::parseVersion1(Dictionary* animations)
Object* pObj = NULL; Object* pObj = NULL;
CCARRAY_FOREACH(frameNames, pObj) CCARRAY_FOREACH(frameNames, pObj)
{ {
const char* frameName = static_cast<String*>(pObj)->getCString(); const std::string& frameName = static_cast<String*>(pObj)->getCString();
SpriteFrame* spriteFrame = frameCache->getSpriteFrameByName(frameName); SpriteFrame* spriteFrame = frameCache->getSpriteFrameByName(frameName);
if ( ! spriteFrame ) { if ( ! spriteFrame ) {
CCLOG("cocos2d: AnimationCache: Animation '%s' refers to frame '%s' which is not currently in the SpriteFrameCache. This frame will not be added to the animation.", pElement->getStrKey(), frameName); CCLOG("cocos2d: AnimationCache: Animation '%s' refers to frame '%s' which is not currently in the SpriteFrameCache. This frame will not be added to the animation.", element->getStrKey(), frameName.c_str());
continue; continue;
} }
@ -131,15 +129,15 @@ void AnimationCache::parseVersion1(Dictionary* animations)
} }
if ( frames->count() == 0 ) { if ( frames->count() == 0 ) {
CCLOG("cocos2d: AnimationCache: None of the frames for animation '%s' were found in the SpriteFrameCache. Animation is not being added to the Animation Cache.", pElement->getStrKey()); CCLOG("cocos2d: AnimationCache: None of the frames for animation '%s' were found in the SpriteFrameCache. Animation is not being added to the Animation Cache.", element->getStrKey());
continue; continue;
} else if ( frames->count() != frameNames->count() ) { } else if ( frames->count() != frameNames->count() ) {
CCLOG("cocos2d: AnimationCache: An animation in your dictionary refers to a frame which is not in the SpriteFrameCache. Some or all of the frames for the animation '%s' may be missing.", pElement->getStrKey()); CCLOG("cocos2d: AnimationCache: An animation in your dictionary refers to a frame which is not in the SpriteFrameCache. Some or all of the frames for the animation '%s' may be missing.", element->getStrKey());
} }
animation = Animation::create(frames, delay, 1); animation = Animation::create(frames, delay, 1);
AnimationCache::getInstance()->addAnimation(animation, pElement->getStrKey()); AnimationCache::getInstance()->addAnimation(animation, element->getStrKey());
frames->release(); frames->release();
} }
} }
@ -148,11 +146,11 @@ void AnimationCache::parseVersion2(Dictionary* animations)
{ {
SpriteFrameCache *frameCache = SpriteFrameCache::getInstance(); SpriteFrameCache *frameCache = SpriteFrameCache::getInstance();
DictElement* pElement = NULL; DictElement* element = NULL;
CCDICT_FOREACH(animations, pElement) CCDICT_FOREACH(animations, element)
{ {
const char* name = pElement->getStrKey(); const char* name = element->getStrKey();
Dictionary* animationDict = static_cast<Dictionary*>(pElement->getObject()); Dictionary* animationDict = static_cast<Dictionary*>(element->getObject());
const String* loops = animationDict->valueForKey("loops"); const String* loops = animationDict->valueForKey("loops");
bool restoreOriginalFrame = animationDict->valueForKey("restoreOriginalFrame")->boolValue(); bool restoreOriginalFrame = animationDict->valueForKey("restoreOriginalFrame")->boolValue();
@ -241,9 +239,9 @@ void AnimationCache::addAnimationsWithDictionary(Dictionary* dictionary)
} }
/** Read an NSDictionary from a plist file and parse it automatically for animations */ /** Read an NSDictionary from a plist file and parse it automatically for animations */
void AnimationCache::addAnimationsWithFile(const char* plist) void AnimationCache::addAnimationsWithFile(const std::string& plist)
{ {
CCASSERT( plist, "Invalid texture file name"); CCASSERT( plist.size()>0, "Invalid texture file name");
std::string path = FileUtils::getInstance()->fullPathForFilename(plist); std::string path = FileUtils::getInstance()->fullPathForFilename(plist);
Dictionary* dict = Dictionary::createWithContentsOfFile(path.c_str()); Dictionary* dict = Dictionary::createWithContentsOfFile(path.c_str());

View File

@ -76,29 +76,29 @@ public:
/** Adds a Animation with a name. /** Adds a Animation with a name.
*/ */
void addAnimation(Animation *animation, const char * name); void addAnimation(Animation *animation, const std::string& name);
/** Deletes a Animation from the cache. /** Deletes a Animation from the cache.
*/ */
void removeAnimation(const char* name); void removeAnimation(const std::string& name);
/** @deprecated. Use removeAnimation() instead /** @deprecated. Use removeAnimation() instead
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
CC_DEPRECATED_ATTRIBUTE void removeAnimationByName(const char* name){ removeAnimation(name);} CC_DEPRECATED_ATTRIBUTE void removeAnimationByName(const std::string& name){ removeAnimation(name);}
/** Returns a Animation that was previously added. /** Returns a Animation that was previously added.
If the name is not found it will return nil. If the name is not found it will return nil.
You should retain the returned copy if you are going to use it. You should retain the returned copy if you are going to use it.
*/ */
Animation* getAnimation(const char* name); Animation* getAnimation(const std::string& name);
/** /**
@deprecated. Use getAnimation() instead @deprecated. Use getAnimation() instead
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
CC_DEPRECATED_ATTRIBUTE Animation* animationByName(const char* name){ return getAnimation(name); } CC_DEPRECATED_ATTRIBUTE Animation* animationByName(const std::string& name){ return getAnimation(name); }
/** Adds an animation from an NSDictionary /** Adds an animation from an NSDictionary
Make sure that the frames were previously loaded in the SpriteFrameCache. Make sure that the frames were previously loaded in the SpriteFrameCache.
@ -112,7 +112,7 @@ public:
* @js addAnimations * @js addAnimations
* @lua addAnimations * @lua addAnimations
*/ */
void addAnimationsWithFile(const char* plist); void addAnimationsWithFile(const std::string& plist);
private: private:
void parseVersion1(Dictionary* animations); void parseVersion1(Dictionary* animations);

View File

@ -61,8 +61,7 @@ AtlasNode::~AtlasNode()
CC_SAFE_RELEASE(_textureAtlas); CC_SAFE_RELEASE(_textureAtlas);
} }
AtlasNode * AtlasNode::create(const char *tile, unsigned int tileWidth, unsigned int tileHeight, AtlasNode * AtlasNode::create(const std::string& tile, long tileWidth, long tileHeight, long itemsToRender)
unsigned int itemsToRender)
{ {
AtlasNode * pRet = new AtlasNode(); AtlasNode * pRet = new AtlasNode();
if (pRet->initWithTileFile(tile, tileWidth, tileHeight, itemsToRender)) if (pRet->initWithTileFile(tile, tileWidth, tileHeight, itemsToRender))
@ -74,15 +73,14 @@ AtlasNode * AtlasNode::create(const char *tile, unsigned int tileWidth, unsigned
return NULL; return NULL;
} }
bool AtlasNode::initWithTileFile(const char *tile, unsigned int tileWidth, unsigned int tileHeight, unsigned int itemsToRender) bool AtlasNode::initWithTileFile(const std::string& tile, long tileWidth, long tileHeight, long itemsToRender)
{ {
CCASSERT(tile != NULL, "title should not be null"); CCASSERT(tile.size() > 0, "file size should not be empty");
Texture2D *texture = TextureCache::getInstance()->addImage(tile); Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(tile);
return initWithTexture(texture, tileWidth, tileHeight, itemsToRender); return initWithTexture(texture, tileWidth, tileHeight, itemsToRender);
} }
bool AtlasNode::initWithTexture(Texture2D* texture, unsigned int tileWidth, unsigned int tileHeight, bool AtlasNode::initWithTexture(Texture2D* texture, long tileWidth, long tileHeight, long itemsToRender)
unsigned int itemsToRender)
{ {
_itemWidth = tileWidth; _itemWidth = tileWidth;
_itemHeight = tileHeight; _itemHeight = tileHeight;
@ -247,12 +245,12 @@ TextureAtlas * AtlasNode::getTextureAtlas() const
return _textureAtlas; return _textureAtlas;
} }
unsigned int AtlasNode::getQuadsToDraw() const long AtlasNode::getQuadsToDraw() const
{ {
return _quadsToDraw; return _quadsToDraw;
} }
void AtlasNode::setQuadsToDraw(unsigned int uQuadsToDraw) void AtlasNode::setQuadsToDraw(long uQuadsToDraw)
{ {
_quadsToDraw = uQuadsToDraw; _quadsToDraw = uQuadsToDraw;
} }

View File

@ -52,8 +52,7 @@ class CC_DLL AtlasNode : public NodeRGBA, public TextureProtocol
{ {
public: public:
/** creates a AtlasNode with an Atlas file the width and height of each item and the quantity of items to render*/ /** creates a AtlasNode with an Atlas file the width and height of each item and the quantity of items to render*/
static AtlasNode * create(const char* tile,unsigned int tileWidth, unsigned int tileHeight, static AtlasNode * create(const std::string& filename, long tileWidth, long tileHeight, long itemsToRender);
unsigned int itemsToRender);
/** /**
* @js ctor * @js ctor
*/ */
@ -65,10 +64,10 @@ public:
virtual ~AtlasNode(); virtual ~AtlasNode();
/** initializes an AtlasNode with an Atlas file the width and height of each item and the quantity of items to render*/ /** initializes an AtlasNode with an Atlas file the width and height of each item and the quantity of items to render*/
bool initWithTileFile(const char* tile, unsigned int tileWidth, unsigned int tileHeight, unsigned int itemsToRender); bool initWithTileFile(const std::string& tile, long tileWidth, long tileHeight, long itemsToRender);
/** initializes an AtlasNode with a texture the width and height of each item measured in points and the quantity of items to render*/ /** initializes an AtlasNode with a texture the width and height of each item measured in points and the quantity of items to render*/
bool initWithTexture(Texture2D* texture, unsigned int tileWidth, unsigned int tileHeight, unsigned int itemsToRender); bool initWithTexture(Texture2D* texture, long tileWidth, long tileHeight, long itemsToRender);
/** updates the Atlas (indexed vertex array). /** updates the Atlas (indexed vertex array).
* Shall be overridden in subclasses * Shall be overridden in subclasses
@ -78,8 +77,8 @@ public:
void setTextureAtlas(TextureAtlas* textureAtlas); void setTextureAtlas(TextureAtlas* textureAtlas);
TextureAtlas* getTextureAtlas() const; TextureAtlas* getTextureAtlas() const;
void setQuadsToDraw(unsigned int quadsToDraw); void setQuadsToDraw(long quadsToDraw);
unsigned int getQuadsToDraw() const; long getQuadsToDraw() const;
// Overrides // Overrides
@ -115,14 +114,14 @@ private :
protected: protected:
//! chars per row //! chars per row
unsigned int _itemsPerRow; long _itemsPerRow;
//! chars per column //! chars per column
unsigned int _itemsPerColumn; long _itemsPerColumn;
//! width of each char //! width of each char
unsigned int _itemWidth; long _itemWidth;
//! height of each char //! height of each char
unsigned int _itemHeight; long _itemHeight;
Color3B _colorUnmodified; Color3B _colorUnmodified;
@ -132,7 +131,7 @@ protected:
BlendFunc _blendFunc; BlendFunc _blendFunc;
// quads to draw // quads to draw
unsigned int _quadsToDraw; long _quadsToDraw;
// color uniform // color uniform
GLint _uniformColor; GLint _uniformColor;
// This varible is only used for LabelAtlas FPS display. So plz don't modify its value. // This varible is only used for LabelAtlas FPS display. So plz don't modify its value.

View File

@ -145,6 +145,8 @@ bool Director::init(void)
_scheduler->scheduleUpdateForTarget(_actionManager, Scheduler::PRIORITY_SYSTEM, false); _scheduler->scheduleUpdateForTarget(_actionManager, Scheduler::PRIORITY_SYSTEM, false);
_eventDispatcher = new EventDispatcher(); _eventDispatcher = new EventDispatcher();
//init TextureCache
initTextureCache();
// create autorelease pool // create autorelease pool
PoolManager::sharedPoolManager()->push(); PoolManager::sharedPoolManager()->push();
@ -359,6 +361,29 @@ void Director::setOpenGLView(EGLView *pobOpenGLView)
} }
} }
TextureCache* Director::getTextureCache() const
{
return _textureCache;
}
void Director::initTextureCache()
{
#ifdef EMSCRIPTEN
_textureCache = new TextureCacheEmscripten();
#else
_textureCache = new TextureCache();
#endif // EMSCRIPTEN
}
void Director::destroyTextureCache()
{
if (_textureCache)
{
_textureCache->waitForQuit();
CC_SAFE_RELEASE_NULL(_textureCache);
}
}
void Director::setViewport() void Director::setViewport()
{ {
if (_openGLView) if (_openGLView)
@ -437,7 +462,7 @@ void Director::purgeCachedData(void)
if (s_SharedDirector->getOpenGLView()) if (s_SharedDirector->getOpenGLView())
{ {
SpriteFrameCache::getInstance()->removeUnusedSpriteFrames(); SpriteFrameCache::getInstance()->removeUnusedSpriteFrames();
TextureCache::getInstance()->removeUnusedTextures(); _textureCache->removeUnusedTextures();
} }
FileUtils::getInstance()->purgeCachedEntries(); FileUtils::getInstance()->purgeCachedEntries();
} }
@ -693,7 +718,6 @@ void Director::purgeDirector()
DrawPrimitives::free(); DrawPrimitives::free();
AnimationCache::destroyInstance(); AnimationCache::destroyInstance();
SpriteFrameCache::destroyInstance(); SpriteFrameCache::destroyInstance();
TextureCache::destroyInstance();
ShaderCache::destroyInstance(); ShaderCache::destroyInstance();
FileUtils::destroyInstance(); FileUtils::destroyInstance();
Configuration::destroyInstance(); Configuration::destroyInstance();
@ -704,6 +728,8 @@ void Director::purgeDirector()
GL::invalidateStateCache(); GL::invalidateStateCache();
destroyTextureCache();
CHECK_GL_ERROR_DEBUG(); CHECK_GL_ERROR_DEBUG();
// OpenGL view // OpenGL view
@ -831,7 +857,7 @@ void Director::calculateMPF()
} }
// returns the FPS image data pointer and len // returns the FPS image data pointer and len
void Director::getFPSImageData(unsigned char** datapointer, unsigned int* length) void Director::getFPSImageData(unsigned char** datapointer, long* length)
{ {
// XXX fixed me if it should be used // XXX fixed me if it should be used
*datapointer = cc_fps_images_png; *datapointer = cc_fps_images_png;
@ -841,21 +867,20 @@ void Director::getFPSImageData(unsigned char** datapointer, unsigned int* length
void Director::createStatsLabel() void Director::createStatsLabel()
{ {
Texture2D *texture = nullptr; Texture2D *texture = nullptr;
TextureCache *textureCache = TextureCache::getInstance();
if (_FPSLabel && _SPFLabel) if (_FPSLabel && _SPFLabel)
{ {
CC_SAFE_RELEASE_NULL(_FPSLabel); CC_SAFE_RELEASE_NULL(_FPSLabel);
CC_SAFE_RELEASE_NULL(_SPFLabel); CC_SAFE_RELEASE_NULL(_SPFLabel);
CC_SAFE_RELEASE_NULL(_drawsLabel); CC_SAFE_RELEASE_NULL(_drawsLabel);
textureCache->removeTextureForKey("/cc_fps_images"); _textureCache->removeTextureForKey("/cc_fps_images");
FileUtils::getInstance()->purgeCachedEntries(); FileUtils::getInstance()->purgeCachedEntries();
} }
Texture2D::PixelFormat currentFormat = Texture2D::getDefaultAlphaPixelFormat(); Texture2D::PixelFormat currentFormat = Texture2D::getDefaultAlphaPixelFormat();
Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444);
unsigned char *data = nullptr; unsigned char *data = nullptr;
unsigned int dataLength = 0; long dataLength = 0;
getFPSImageData(&data, &dataLength); getFPSImageData(&data, &dataLength);
Image* image = new Image(); Image* image = new Image();
@ -865,7 +890,7 @@ void Director::createStatsLabel()
return; return;
} }
texture = textureCache->addImage(image, "/cc_fps_images"); texture = _textureCache->addImage(image, "/cc_fps_images");
CC_SAFE_RELEASE(image); CC_SAFE_RELEASE(image);
/* /*

View File

@ -54,6 +54,7 @@ class Node;
class Scheduler; class Scheduler;
class ActionManager; class ActionManager;
class EventDispatcher; class EventDispatcher;
class TextureCache;
/** /**
@brief Class that creates and handles the main Window and manages how @brief Class that creates and handles the main Window and manages how
@ -137,6 +138,8 @@ public:
inline EGLView* getOpenGLView() { return _openGLView; } inline EGLView* getOpenGLView() { return _openGLView; }
void setOpenGLView(EGLView *pobOpenGLView); void setOpenGLView(EGLView *pobOpenGLView);
TextureCache* getTextureCache() const;
inline bool isNextDeltaTimeZero() { return _nextDeltaTimeZero; } inline bool isNextDeltaTimeZero() { return _nextDeltaTimeZero; }
void setNextDeltaTimeZero(bool nextDeltaTimeZero); void setNextDeltaTimeZero(bool nextDeltaTimeZero);
@ -376,11 +379,15 @@ protected:
void showStats(); void showStats();
void createStatsLabel(); void createStatsLabel();
void calculateMPF(); void calculateMPF();
void getFPSImageData(unsigned char** datapointer, unsigned int* length); void getFPSImageData(unsigned char** datapointer, long* length);
/** calculates delta time since last time it was called */ /** calculates delta time since last time it was called */
void calculateDeltaTime(); void calculateDeltaTime();
//textureCache creation or release
void initTextureCache();
void destroyTextureCache();
protected: protected:
/** Scheduler associated with this director /** Scheduler associated with this director
@since v2.0 @since v2.0
@ -403,6 +410,9 @@ protected:
/* The EGLView, where everything is rendered */ /* The EGLView, where everything is rendered */
EGLView *_openGLView; EGLView *_openGLView;
//texture cache belongs to this director
TextureCache *_textureCache;
double _animationInterval; double _animationInterval;
double _oldAnimationInterval; double _oldAnimationInterval;

View File

@ -141,7 +141,7 @@ DrawNode* DrawNode::create()
return pRet; return pRet;
} }
void DrawNode::ensureCapacity(int count) void DrawNode::ensureCapacity(long count)
{ {
CCASSERT(count>=0, "capacity must be >= 0"); CCASSERT(count>=0, "capacity must be >= 0");
@ -333,8 +333,10 @@ void DrawNode::drawSegment(const Point &from, const Point &to, float radius, con
_dirty = true; _dirty = true;
} }
void DrawNode::drawPolygon(Point *verts, unsigned int count, const Color4F &fillColor, float borderWidth, const Color4F &borderColor) void DrawNode::drawPolygon(Point *verts, long count, const Color4F &fillColor, float borderWidth, const Color4F &borderColor)
{ {
CCASSERT(count >= 0, "invalid count value");
struct ExtrudeVerts {Vertex2F offset, n;}; struct ExtrudeVerts {Vertex2F offset, n;};
struct ExtrudeVerts* extrude = (struct ExtrudeVerts*)malloc(sizeof(struct ExtrudeVerts)*count); struct ExtrudeVerts* extrude = (struct ExtrudeVerts*)malloc(sizeof(struct ExtrudeVerts)*count);
memset(extrude, 0, sizeof(struct ExtrudeVerts)*count); memset(extrude, 0, sizeof(struct ExtrudeVerts)*count);
@ -378,9 +380,9 @@ void DrawNode::drawPolygon(Point *verts, unsigned int count, const Color4F &fill
*cursor++ = tmp; *cursor++ = tmp;
} }
for(unsigned int i = 0; i < count; i++) for(long i = 0; i < count; i++)
{ {
int j = (i+1)%count; long j = (i+1)%count;
Vertex2F v0 = __v2f(verts[i]); Vertex2F v0 = __v2f(verts[i]);
Vertex2F v1 = __v2f(verts[j]); Vertex2F v1 = __v2f(verts[j]);

View File

@ -71,7 +71,7 @@ public:
* In lua:local drawPolygon(local pointTable,local tableCount,local fillColor,local width,local borderColor) * In lua:local drawPolygon(local pointTable,local tableCount,local fillColor,local width,local borderColor)
* @endcode * @endcode
*/ */
void drawPolygon(Point *verts, unsigned int count, const Color4F &fillColor, float borderWidth, const Color4F &borderColor); void drawPolygon(Point *verts, long count, const Color4F &fillColor, float borderWidth, const Color4F &borderColor);
/** Clear the geometry in the node's buffer. */ /** Clear the geometry in the node's buffer. */
void clear(); void clear();
@ -99,13 +99,13 @@ public:
virtual void draw() override; virtual void draw() override;
protected: protected:
void ensureCapacity(int count); void ensureCapacity(long count);
void render(); void render();
GLuint _vao; GLuint _vao;
GLuint _vbo; GLuint _vbo;
int _bufferCapacity; long _bufferCapacity;
GLsizei _bufferCount; GLsizei _bufferCount;
V2F_C4B_T2F *_buffer; V2F_C4B_T2F *_buffer;

View File

@ -75,10 +75,9 @@ EventListenerTouchOneByOne* EventListenerTouchOneByOne::create()
bool EventListenerTouchOneByOne::checkAvailable() bool EventListenerTouchOneByOne::checkAvailable()
{ {
if (onTouchBegan == nullptr && onTouchMoved == nullptr if (onTouchBegan == nullptr)
&& onTouchEnded == nullptr && onTouchCancelled == nullptr)
{ {
CCASSERT(false, "Invalid TouchEventListener."); CCASSERT(false, "Invalid EventListenerTouchOneByOne!");
return false; return false;
} }
@ -150,7 +149,7 @@ bool EventListenerTouchAllAtOnce::checkAvailable()
if (onTouchesBegan == nullptr && onTouchesMoved == nullptr if (onTouchesBegan == nullptr && onTouchesMoved == nullptr
&& onTouchesEnded == nullptr && onTouchesCancelled == nullptr) && onTouchesEnded == nullptr && onTouchesCancelled == nullptr)
{ {
CCASSERT(false, "Invalid TouchEventListener."); CCASSERT(false, "Invalid EventListenerTouchAllAtOnce!");
return false; return false;
} }

View File

@ -75,7 +75,7 @@ void Font::setCurrentGlyphCollection(GlyphCollection glyphs, const char *customG
default: default:
if (customGlyphs) if (customGlyphs)
{ {
int lenght = strlen(customGlyphs); size_t lenght = strlen(customGlyphs);
_customGlyphs = new char [lenght + 2]; _customGlyphs = new char [lenght + 2];
memcpy(_customGlyphs, customGlyphs, lenght); memcpy(_customGlyphs, customGlyphs, lenght);
@ -99,12 +99,12 @@ const char * Font::getCurrentGlyphCollection() const
} }
} }
Font* Font::createWithTTF(const char* fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs) Font* Font::createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs)
{ {
return FontFreeType::create(fntName, fontSize, glyphs, customGlyphs); return FontFreeType::create(fntName, fontSize, glyphs, customGlyphs);
} }
Font* Font::createWithFNT(const char* fntFilePath) Font* Font::createWithFNT(const std::string& fntFilePath)
{ {
return FontFNT::create(fntFilePath); return FontFNT::create(fntFilePath);
} }

View File

@ -42,21 +42,21 @@ class CC_DLL Font : public Object
public: public:
// create the font // create the font
static Font* createWithTTF(const char* fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); static Font* createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs);
static Font* createWithFNT(const char* fntFilePath); static Font* createWithFNT(const std::string& fntFilePath);
virtual FontAtlas *createFontAtlas() = 0; virtual FontAtlas *createFontAtlas() = 0;
virtual Size * getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const = 0; virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const = 0;
virtual const char * getCurrentGlyphCollection() const; virtual const char* getCurrentGlyphCollection() const;
virtual int getLetterPadding() const { return 0; } 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 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 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 int * getUTF16Text(const char *text, int &outNumLetters) const;
virtual unsigned short int * trimUTF16Text(unsigned short int *text, int newBegin, int newEnd) const; virtual unsigned short int * trimUTF16Text(unsigned short int *text, int newBegin, int newEnd) const;
@ -71,8 +71,7 @@ protected:
void setCurrentGlyphCollection(GlyphCollection glyphs, const char *customGlyphs = 0); void setCurrentGlyphCollection(GlyphCollection glyphs, const char *customGlyphs = 0);
const char * getGlyphCollection(GlyphCollection glyphs) const; const char * getGlyphCollection(GlyphCollection glyphs) const;
private:
GlyphCollection _usedGlyphs; GlyphCollection _usedGlyphs;
char * _customGlyphs; char * _customGlyphs;
static const char * _glyphASCII; static const char * _glyphASCII;

View File

@ -1,10 +1,26 @@
// /****************************************************************************
// CCFontAtlas.cpp Copyright (c) 2013 Zynga Inc.
// cocos2d_libs
// http://www.cocos2d-x.org
// Created by Carlo Morgantini on 7/18/13.
// 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 "cocos2d.h"
#include "CCFontAtlas.h" #include "CCFontAtlas.h"

View File

@ -24,7 +24,7 @@
#ifndef _CCFontAtlas_h_ #ifndef _CCFontAtlas_h_
#define _CCFontAtlas_h_ #define _CCFontAtlas_h_
#include <map> #include <unordered_map>
NS_CC_BEGIN NS_CC_BEGIN
@ -34,17 +34,17 @@ class Font;
struct FontLetterDefinition struct FontLetterDefinition
{ {
unsigned short letteCharUTF16; unsigned short letteCharUTF16;
float U; float U;
float V; float V;
float width; float width;
float height; float height;
float offsetX; float offsetX;
float offsetY; float offsetY;
int textureID; int textureID;
float commonLineHeight; float commonLineHeight;
float anchorX; float anchorX;
float anchorY; float anchorY;
bool validDefinition; bool validDefinition;
}; };
class CC_DLL FontAtlas : public Object class CC_DLL FontAtlas : public Object
@ -69,26 +69,26 @@ public:
float getCommonLineHeight() const; float getCommonLineHeight() const;
void setCommonLineHeight(float newHeight); void setCommonLineHeight(float newHeight);
Texture2D & getTexture(int slot); Texture2D& getTexture(int slot);
const Font * getFont() const; const Font* getFont() const;
private: private:
bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize); bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize);
void relaseTextures(); void relaseTextures();
std::map<int, Texture2D *> _atlasTextures; std::unordered_map<int, Texture2D*> _atlasTextures;
std::map<unsigned short, FontLetterDefinition> _fontLetterDefinitions; std::unordered_map<unsigned short, FontLetterDefinition> _fontLetterDefinitions;
float _commonLineHeight; float _commonLineHeight;
Font * _font; Font * _font;
// Dynamic GlyphCollection related stuff // Dynamic GlyphCollection related stuff
int _currentPage; int _currentPage;
unsigned char *_currentPageData; unsigned char *_currentPageData;
int _currentPageDataSize; int _currentPageDataSize;
float _currentPageOrigX; float _currentPageOrigX;
float _currentPageOrigY; float _currentPageOrigY;
float _currentPageLineHeight; float _currentPageLineHeight;
float _letterPadding; float _letterPadding;
}; };

View File

@ -28,7 +28,7 @@
NS_CC_BEGIN NS_CC_BEGIN
std::map<std::string, FontAtlas *> FontAtlasCache::_atlasMap; std::unordered_map<std::string, FontAtlas *> FontAtlasCache::_atlasMap;
FontAtlas * FontAtlasCache::getFontAtlasTTF(const char *fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs) FontAtlas * FontAtlasCache::getFontAtlasTTF(const char *fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs)
{ {

View File

@ -26,7 +26,7 @@
#define _CCFontAtlasCache_h_ #define _CCFontAtlasCache_h_
#include <iostream> #include <iostream>
#include <map> #include <unordered_map>
#include "cocos2d.h" #include "cocos2d.h"
#include "CCFontAtlas.h" #include "CCFontAtlas.h"
@ -41,12 +41,12 @@ public:
static FontAtlas * getFontAtlasTTF(const char *fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs = 0); static FontAtlas * getFontAtlasTTF(const char *fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs = 0);
static FontAtlas * getFontAtlasFNT(const char *fontFileName); static FontAtlas * getFontAtlasFNT(const char *fontFileName);
static bool releaseFontAtlas(FontAtlas *atlas); static bool releaseFontAtlas(FontAtlas *atlas);
private: private:
static std::string generateFontName(const char *fontFileName, int size, GlyphCollection theGlyphs); static std::string generateFontName(const char *fontFileName, int size, GlyphCollection theGlyphs);
static std::map<std::string, FontAtlas *> _atlasMap; static std::unordered_map<std::string, FontAtlas *> _atlasMap;
}; };
NS_CC_END NS_CC_END

View File

@ -1,10 +1,26 @@
// /****************************************************************************
// CCFontAtlasFactory.cpp Copyright (c) 2013 Zynga Inc.
// cocos2d_libs
// http://www.cocos2d-x.org
// Created by Carlo Morgantini on 7/23/13.
// 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 "CCFontAtlasFactory.h" #include "CCFontAtlasFactory.h"
#include "CCFontFNT.h" #include "CCFontFNT.h"

View File

@ -27,7 +27,7 @@
NS_CC_BEGIN NS_CC_BEGIN
const int FontDefinitionTTF::DEFAUL_ATALS_TEXTURE_SIZE = 1024; const int FontDefinitionTTF::DEFAUL_ATLAS_TEXTURE_SIZE = 1024;
FontDefinitionTTF::FontDefinitionTTF():_textImages(0), _commonLineHeight(0) FontDefinitionTTF::FontDefinitionTTF():_textImages(0), _commonLineHeight(0)
{ {
@ -36,7 +36,7 @@ FontDefinitionTTF::FontDefinitionTTF():_textImages(0), _commonLineHeight(0)
FontDefinitionTTF* FontDefinitionTTF::create(Font *font, int textureSize) FontDefinitionTTF* FontDefinitionTTF::create(Font *font, int textureSize)
{ {
if (textureSize == 0) if (textureSize == 0)
textureSize = DEFAUL_ATALS_TEXTURE_SIZE; textureSize = DEFAUL_ATLAS_TEXTURE_SIZE;
FontDefinitionTTF *ret = new FontDefinitionTTF; FontDefinitionTTF *ret = new FontDefinitionTTF;
@ -82,8 +82,8 @@ bool FontDefinitionTTF::prepareLetterDefinitions(TextFontPagesDef *pageDefs)
// loops all the lines in this page // loops all the lines in this page
for (int cLines = 0; cLines<pages->getPageAt(cPages)->getNumLines(); ++cLines) for (int cLines = 0; cLines<pages->getPageAt(cPages)->getNumLines(); ++cLines)
{ {
float posXUV = 0.0; float posXUV = 0.0;
float posYUV = pages->getPageAt(cPages)->getLineAt(cLines)->getY(); float posYUV = pages->getPageAt(cPages)->getLineAt(cLines)->getY();
int charsCounter = 0; int charsCounter = 0;

View File

@ -25,6 +25,8 @@
#ifndef _FontDefinition_h_ #ifndef _FontDefinition_h_
#define _FontDefinition_h_ #define _FontDefinition_h_
#include <unordered_map>
#include "CCTextImage.h" #include "CCTextImage.h"
#include "CCFont.h" #include "CCFont.h"
#include "CCFontAtlas.h" #include "CCFontAtlas.h"
@ -55,11 +57,11 @@ private:
bool prepareLetterDefinitions(TextFontPagesDef *pageDefs); bool prepareLetterDefinitions(TextFontPagesDef *pageDefs);
void addLetterDefinition(const FontLetterDefinition &defToAdd); void addLetterDefinition(const FontLetterDefinition &defToAdd);
TextImage * _textImages; TextImage * _textImages;
std::map<unsigned short, FontLetterDefinition> _fontLettersDefinitionUTF16; std::unordered_map<unsigned short, FontLetterDefinition> _fontLettersDefinitionUTF16;
float _commonLineHeight; float _commonLineHeight;
static const int DEFAUL_ATALS_TEXTURE_SIZE;
static const int DEFAUL_ATLAS_TEXTURE_SIZE;
}; };
NS_CC_END NS_CC_END

View File

@ -1,24 +1,40 @@
// /****************************************************************************
// CCFontFNT.cpp Copyright (c) 2013 Zynga Inc.
// cocos2d_libs
// http://www.cocos2d-x.org
// Created by Carlo Morgantini on 7/24/13.
// 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 "CCFontFNT.h" #include "CCFontFNT.h"
#include "CCFontAtlas.h" #include "CCFontAtlas.h"
NS_CC_BEGIN NS_CC_BEGIN
FontFNT * FontFNT::create(const char* fntFilePath) FontFNT * FontFNT::create(const std::string& fntFilePath)
{ {
CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFilePath); CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFilePath);
if (!newConf) if (!newConf)
return nullptr; return nullptr;
// add the texture // add the texture
Texture2D *tempTexture = TextureCache::getInstance()->addImage(newConf->getAtlasName()); Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(newConf->getAtlasName());
if (!tempTexture) if (!tempTexture)
{ {
delete newConf; delete newConf;
@ -182,7 +198,7 @@ FontAtlas * FontFNT::createFontAtlas()
// add the texture (only one texture for now) // add the texture (only one texture for now)
Texture2D *tempTexture = TextureCache::getInstance()->addImage(_configuration->getAtlasName()); Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(_configuration->getAtlasName());
if (!tempTexture) if (!tempTexture)
return 0; return 0;

View File

@ -35,7 +35,7 @@ class FontFNT : public Font
public: public:
static FontFNT * create(const char* fntFilePath); static FontFNT * create(const std::string& fntFilePath);
virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const override; virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const override;
virtual Rect getRectForChar(unsigned short theChar) const override; virtual Rect getRectForChar(unsigned short theChar) const override;
@ -43,7 +43,8 @@ public:
protected: protected:
FontFNT(CCBMFontConfiguration *theContfig) : _configuration(theContfig) {} FontFNT(CCBMFontConfiguration *theContfig) :
_configuration(theContfig) {}
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
@ -56,7 +57,7 @@ private:
int getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const; int getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const;
Rect getRectForCharInternal(unsigned short theChar) const; Rect getRectForCharInternal(unsigned short theChar) const;
CCBMFontConfiguration * _configuration; CCBMFontConfiguration * _configuration;
}; };

View File

@ -99,8 +99,8 @@ bool FontFreeType::createFontObject(const std::string &fontName, int fontSize)
{ {
FT_Face face; FT_Face face;
int len = 0; long len = 0;
_ttfData = FileUtils::getInstance()->getFileData(fontName.c_str(), "rb", (unsigned long *)(&len)); _ttfData = FileUtils::getInstance()->getFileData(fontName.c_str(), "rb", &len);
if (!_ttfData) if (!_ttfData)
return false; return false;

View File

@ -59,7 +59,7 @@ public:
protected: protected:
GLuint _FBO; GLuint _FBO;
GLint _oldFBO; GLint _oldFBO;
GLfloat _oldClearColor[4]; GLfloat _oldClearColor[4];
}; };
// end of effects group // end of effects group

View File

@ -119,7 +119,7 @@ bool GridBase::initWithSize(const Size& gridSize)
// we only use rgba8888 // we only use rgba8888
Texture2D::PixelFormat format = Texture2D::PixelFormat::RGBA8888; Texture2D::PixelFormat format = Texture2D::PixelFormat::RGBA8888;
int dataLen = (int)(POTWide * POTHigh * 4); long dataLen = POTWide * POTHigh * 4;
void *data = calloc(dataLen, 1); void *data = calloc(dataLen, 1);
if (! data) if (! data)
{ {

View File

@ -66,23 +66,23 @@ public:
bool initWithSize(const Size& gridSize); bool initWithSize(const Size& gridSize);
/** whether or not the grid is active */ /** whether or not the grid is active */
inline bool isActive(void) { return _active; } inline bool isActive(void) const { return _active; }
void setActive(bool bActive); void setActive(bool bActive);
/** number of times that the grid will be reused */ /** number of times that the grid will be reused */
inline int getReuseGrid(void) { return _reuseGrid; } inline int getReuseGrid(void) const { return _reuseGrid; }
inline void setReuseGrid(int nReuseGrid) { _reuseGrid = nReuseGrid; } inline void setReuseGrid(int nReuseGrid) { _reuseGrid = nReuseGrid; }
/** size of the grid */ /** size of the grid */
inline const Size& getGridSize(void) { return _gridSize; } inline const Size& getGridSize(void) const { return _gridSize; }
inline void setGridSize(const Size& gridSize) { _gridSize = gridSize; } inline void setGridSize(const Size& gridSize) { _gridSize = gridSize; }
/** pixels between the grids */ /** pixels between the grids */
inline const Point& getStep(void) { return _step; } inline const Point& getStep(void) const { return _step; }
inline void setStep(const Point& step) { _step = step; } inline void setStep(const Point& step) { _step = step; }
/** is texture flipped */ /** is texture flipped */
inline bool isTextureFlipped(void) { return _isTextureFlipped; } inline bool isTextureFlipped(void) const { return _isTextureFlipped; }
void setTextureFlipped(bool bFlipped); void setTextureFlipped(bool bFlipped);
void beforeDraw(void); void beforeDraw(void);
@ -95,7 +95,7 @@ public:
protected: protected:
bool _active; bool _active;
int _reuseGrid; long _reuseGrid;
Size _gridSize; Size _gridSize;
Texture2D *_texture; Texture2D *_texture;
Point _step; Point _step;

View File

@ -29,9 +29,9 @@
NS_CC_BEGIN NS_CC_BEGIN
Label* Label::createWithTTF( const char* label, const char* fontFilePath, int fontSize, int lineSize, TextHAlignment alignment, GlyphCollection glyphs, const char *customGlyphs ) Label* Label::createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize, TextHAlignment alignment, GlyphCollection glyphs, const char *customGlyphs )
{ {
FontAtlas *tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath, fontSize, glyphs, customGlyphs); FontAtlas *tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath.c_str(), fontSize, glyphs, customGlyphs);
if (!tmpAtlas) if (!tmpAtlas)
return nullptr; return nullptr;
@ -48,10 +48,10 @@ Label* Label::createWithTTF( const char* label, const char* fontFilePath, int fo
return nullptr; return nullptr;
} }
Label* Label::createWithBMFont( const char* label, const char* bmfontFilePath, TextHAlignment alignment, int lineSize) Label* Label::createWithBMFont(const std::string& label, const std::string& bmfontFilePath, TextHAlignment alignment, int lineSize)
{ {
FontAtlas *tmpAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath); FontAtlas *tmpAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath.c_str());
if (!tmpAtlas) if (!tmpAtlas)
return 0; return 0;
@ -135,12 +135,12 @@ bool Label::init()
return true; return true;
} }
void Label::setString(const char *stringToRender) void Label::setString(const std::string &stringToRender)
{ {
setText(stringToRender, _width, TextHAlignment::CENTER, false); setText(stringToRender, _width, TextHAlignment::CENTER, false);
} }
bool Label::setText(const char *stringToRender, float lineWidth, TextHAlignment alignment, bool lineBreakWithoutSpaces) bool Label::setText(const std::string& stringToRender, float lineWidth, TextHAlignment alignment, bool lineBreakWithoutSpaces)
{ {
if (!_fontAtlas) if (!_fontAtlas)
return false; return false;
@ -158,8 +158,8 @@ bool Label::setText(const char *stringToRender, float lineWidth, TextHAlignment
if (_commonLineHeight <= 0) if (_commonLineHeight <= 0)
return false; return false;
int numLetter = 0; // int numLetter = 0;
unsigned short* utf16String = cc_utf8_to_utf16(stringToRender); unsigned short* utf16String = cc_utf8_to_utf16(stringToRender.c_str());
if(!utf16String) if(!utf16String)
return false; return false;

View File

@ -51,13 +51,13 @@ class CC_DLL Label : public SpriteBatchNode, public LabelProtocol, public RGBAPr
public: public:
// static create // static create
static Label* createWithTTF(const char* label, const char* fontFilePath, int fontSize, int lineSize = 0, TextHAlignment alignment = TextHAlignment::CENTER, GlyphCollection glyphs = GlyphCollection::NEHE, const char *customGlyphs = 0); 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);
static Label* createWithBMFont(const char* label, const char* bmfontFilePath, TextHAlignment alignment = TextHAlignment::CENTER, int lineSize = 0); static Label* createWithBMFont(const std::string& label, const std::string& bmfontFilePath, TextHAlignment alignment = TextHAlignment::CENTER, int lineSize = 0);
bool setText(const char *stringToRender, float lineWidth, TextHAlignment alignment = TextHAlignment::LEFT, bool lineBreakWithoutSpaces = false); bool setText(const std::string& stringToRender, float lineWidth, TextHAlignment alignment = TextHAlignment::LEFT, bool lineBreakWithoutSpaces = false);
virtual void setString(const char *stringToRender) override; virtual void setString(const std::string &stringToRender) override;
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);
@ -83,38 +83,38 @@ public:
// CCLabelTextFormat protocol implementation // CCLabelTextFormat protocol implementation
virtual std::vector<LetterInfo> *getLettersInfo() override { return &_lettersInfo; }; virtual std::vector<LetterInfo> *getLettersInfo() override { 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) override;
virtual bool recordPlaceholderInfo(int spriteIndex) override; virtual bool recordPlaceholderInfo(int spriteIndex) override;
virtual float getLetterPosXLeft( int index ) const override; virtual float getLetterPosXLeft( int index ) const override;
virtual float getLetterPosXRight( int index ) const override; virtual float getLetterPosXRight( int index ) const override;
virtual Sprite * getLetter(int ID) override; virtual Sprite * getLetter(int ID) override;
// font related stuff // font related stuff
virtual int getCommonLineHeight() const override; virtual int getCommonLineHeight() const override;
virtual int getKerningForCharsPair(unsigned short first, unsigned short second) const override; virtual int getKerningForCharsPair(unsigned short first, unsigned short second) const override;
virtual int getXOffsetForChar(unsigned short c) const override; virtual int getXOffsetForChar(unsigned short c) const override;
virtual int getYOffsetForChar(unsigned short c) const override; virtual int getYOffsetForChar(unsigned short c) const override;
virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const override; virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const override;
virtual Rect getRectForChar(unsigned short c) 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 override;
virtual int getStringLenght() const override; virtual int getStringLenght() const override;
virtual unsigned short getCharAtStringPosition(int position) const override; virtual unsigned short getCharAtStringPosition(int position) const override;
virtual unsigned short * getUTF8String() const override; virtual unsigned short * getUTF8String() const override;
virtual void assignNewUTF8String(unsigned short *newString) override; virtual void assignNewUTF8String(unsigned short *newString) override;
virtual TextHAlignment getTextAlignment() const override; virtual TextHAlignment getTextAlignment() const override;
// label related stuff // label related stuff
virtual float getMaxLineWidth() const override; virtual float getMaxLineWidth() const override;
virtual bool breakLineWithoutSpace() const override; virtual bool breakLineWithoutSpace() const override;
virtual Size getLabelContentSize() const override; virtual Size getLabelContentSize() const override;
virtual void setLabelContentSize(const Size &newSize) override; virtual void setLabelContentSize(const Size &newSize) override;
// carloX // carloX
const char * getString() const { return "not implemented"; } virtual const std::string& getString() const override { static std::string _ret("not implemented"); return _ret; }
void addChild(Node * child, int zOrder=0, int tag=0); void addChild(Node * child, int zOrder=0, int tag=0) override;
private: private:
/** /**

View File

@ -42,7 +42,7 @@ NS_CC_BEGIN
//CCLabelAtlas - Creation & Init //CCLabelAtlas - Creation & Init
LabelAtlas* LabelAtlas::create(const char *string, const char *charMapFile, unsigned int itemWidth, int unsigned itemHeight, unsigned int startCharMap) LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& charMapFile, long itemWidth, long itemHeight, long startCharMap)
{ {
LabelAtlas *pRet = new LabelAtlas(); LabelAtlas *pRet = new LabelAtlas();
if(pRet && pRet->initWithString(string, charMapFile, itemWidth, itemHeight, startCharMap)) if(pRet && pRet->initWithString(string, charMapFile, itemWidth, itemHeight, startCharMap))
@ -54,16 +54,15 @@ LabelAtlas* LabelAtlas::create(const char *string, const char *charMapFile, unsi
return NULL; return NULL;
} }
bool LabelAtlas::initWithString(const char *string, const char *charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) bool LabelAtlas::initWithString(const std::string& string, const std::string& charMapFile, long itemWidth, long itemHeight, long startCharMap)
{ {
Texture2D *texture = TextureCache::getInstance()->addImage(charMapFile); Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(charMapFile);
return initWithString(string, texture, itemWidth, itemHeight, startCharMap); return initWithString(string, texture, itemWidth, itemHeight, startCharMap);
} }
bool LabelAtlas::initWithString(const char *string, Texture2D* texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) bool LabelAtlas::initWithString(const std::string& string, Texture2D* texture, long itemWidth, long itemHeight, long startCharMap)
{ {
CCASSERT(string != NULL, ""); if (AtlasNode::initWithTexture(texture, itemWidth, itemHeight, string.size()))
if (AtlasNode::initWithTexture(texture, itemWidth, itemHeight, strlen(string)))
{ {
_mapStartChar = startCharMap; _mapStartChar = startCharMap;
this->setString(string); this->setString(string);
@ -72,7 +71,7 @@ bool LabelAtlas::initWithString(const char *string, Texture2D* texture, unsigned
return false; return false;
} }
LabelAtlas* LabelAtlas::create(const char *string, const char *fntFile) LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& fntFile)
{ {
LabelAtlas *ret = new LabelAtlas(); LabelAtlas *ret = new LabelAtlas();
if (ret) if (ret)
@ -90,30 +89,30 @@ LabelAtlas* LabelAtlas::create(const char *string, const char *fntFile)
return ret; return ret;
} }
bool LabelAtlas::initWithString(const char *theString, const char *fntFile) bool LabelAtlas::initWithString(const std::string& theString, const std::string& fntFile)
{ {
std::string pathStr = FileUtils::getInstance()->fullPathForFilename(fntFile); std::string pathStr = FileUtils::getInstance()->fullPathForFilename(fntFile);
std::string relPathStr = pathStr.substr(0, pathStr.find_last_of("/"))+"/"; std::string relPathStr = pathStr.substr(0, pathStr.find_last_of("/"))+"/";
Dictionary *dict = Dictionary::createWithContentsOfFile(pathStr.c_str()); Dictionary *dict = Dictionary::createWithContentsOfFile(pathStr.c_str());
CCASSERT(((String*)dict->objectForKey("version"))->intValue() == 1, "Unsupported version. Upgrade cocos2d version");
std::string texturePathStr = relPathStr + ((String*)dict->objectForKey("textureFilename"))->getCString();
String *textureFilename = String::create(texturePathStr);
unsigned int width = ((String*)dict->objectForKey("itemWidth"))->intValue() / CC_CONTENT_SCALE_FACTOR();
unsigned int height = ((String*)dict->objectForKey("itemHeight"))->intValue() / CC_CONTENT_SCALE_FACTOR();
unsigned int startChar = ((String*)dict->objectForKey("firstChar"))->intValue();
this->initWithString(theString, textureFilename->getCString(), width, height, startChar); CCASSERT(((String*)dict->objectForKey("version"))->intValue() == 1, "Unsupported version. Upgrade cocos2d version");
return true; std::string texturePathStr = relPathStr + ((String*)dict->objectForKey("textureFilename"))->getCString();
String *textureFilename = String::create(texturePathStr);
unsigned int width = ((String*)dict->objectForKey("itemWidth"))->intValue() / CC_CONTENT_SCALE_FACTOR();
unsigned int height = ((String*)dict->objectForKey("itemHeight"))->intValue() / CC_CONTENT_SCALE_FACTOR();
unsigned int startChar = ((String*)dict->objectForKey("firstChar"))->intValue();
this->initWithString(theString, textureFilename->getCString(), width, height, startChar);
return true;
} }
//CCLabelAtlas - Atlas generation //CCLabelAtlas - Atlas generation
void LabelAtlas::updateAtlasValues() void LabelAtlas::updateAtlasValues()
{ {
int n = _string.length(); size_t n = _string.length();
const unsigned char *s = (unsigned char*)_string.c_str(); const unsigned char *s = (unsigned char*)_string.c_str();
@ -186,9 +185,9 @@ void LabelAtlas::updateAtlasValues()
} }
//CCLabelAtlas - LabelProtocol //CCLabelAtlas - LabelProtocol
void LabelAtlas::setString(const char *label) void LabelAtlas::setString(const std::string &label)
{ {
int len = strlen(label); size_t len = label.size();
if (len > _textureAtlas->getTotalQuads()) if (len > _textureAtlas->getTotalQuads())
{ {
_textureAtlas->resizeCapacity(len); _textureAtlas->resizeCapacity(len);
@ -204,9 +203,9 @@ void LabelAtlas::setString(const char *label)
_quadsToDraw = len; _quadsToDraw = len;
} }
const char* LabelAtlas::getString(void) const const std::string& LabelAtlas::getString(void) const
{ {
return _string.c_str(); return _string;
} }
//CCLabelAtlas - draw //CCLabelAtlas - draw

View File

@ -67,38 +67,39 @@ public:
} }
/** creates the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas */ /** creates the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas */
static LabelAtlas * create(const char *string, const char *charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); static LabelAtlas * create(const std::string& string, const std::string& charMapFile, long itemWidth, long itemHeight, long startCharMap);
/** creates the LabelAtlas with a string and a configuration file /** creates the LabelAtlas with a string and a configuration file
@since v2.0 @since v2.0
*/ */
static LabelAtlas* create(const char *string, const char *fntFile); static LabelAtlas* create(const std::string& string, const std::string& fntFile);
/** initializes the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas */ /** initializes the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas */
bool initWithString(const char *string, const char *charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); bool initWithString(const std::string& string, const std::string& charMapFile, long itemWidth, long itemHeight, long startCharMap);
/** initializes the LabelAtlas with a string and a configuration file /** initializes the LabelAtlas with a string and a configuration file
@since v2.0 @since v2.0
*/ */
bool initWithString(const char *string, const char *fntFile); bool initWithString(const std::string& string, const std::string& fntFile);
/** initializes the LabelAtlas with a string, a texture, the width and height in points of each element and the starting char of the atlas */ /** initializes the LabelAtlas with a string, a texture, the width and height in points of each element and the starting char of the atlas */
bool initWithString(const char* string, Texture2D* texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); bool initWithString(const std::string& string, Texture2D* texture, long itemWidth, long itemHeight, long startCharMap);
// super methods // super methods
virtual void updateAtlasValues(); virtual void updateAtlasValues();
virtual void setString(const char *label);
virtual const char* getString(void) const; virtual void setString(const std::string &label) override;
virtual const std::string& getString(void) const override;
#if CC_LABELATLAS_DEBUG_DRAW #if CC_LABELATLAS_DEBUG_DRAW
virtual void draw(); virtual void draw() override;
#endif #endif
protected: protected:
// string to render // string to render
std::string _string; std::string _string;
// the first char in the charmap // the first char in the charmap
unsigned int _mapStartChar; long _mapStartChar;
}; };
// end of GUI group // end of GUI group

View File

@ -62,9 +62,9 @@ static unsigned short* copyUTF16StringN(unsigned short* str)
// //
static Dictionary* s_pConfigurations = NULL; static Dictionary* s_pConfigurations = NULL;
CCBMFontConfiguration* FNTConfigLoadFile( const char *fntFile) CCBMFontConfiguration* FNTConfigLoadFile(const std::string& fntFile)
{ {
CCBMFontConfiguration* pRet = NULL; CCBMFontConfiguration* ret = NULL;
if( s_pConfigurations == NULL ) if( s_pConfigurations == NULL )
{ {
@ -72,17 +72,17 @@ CCBMFontConfiguration* FNTConfigLoadFile( const char *fntFile)
s_pConfigurations->init(); s_pConfigurations->init();
} }
pRet = static_cast<CCBMFontConfiguration*>( s_pConfigurations->objectForKey(fntFile) ); ret = static_cast<CCBMFontConfiguration*>( s_pConfigurations->objectForKey(fntFile) );
if( pRet == NULL ) if( ret == NULL )
{ {
pRet = CCBMFontConfiguration::create(fntFile); ret = CCBMFontConfiguration::create(fntFile.c_str());
if (pRet) if (ret)
{ {
s_pConfigurations->setObject(pRet, fntFile); s_pConfigurations->setObject(ret, fntFile);
} }
} }
return pRet; return ret;
} }
void FNTConfigRemoveCache( void ) void FNTConfigRemoveCache( void )
@ -98,19 +98,19 @@ void FNTConfigRemoveCache( void )
//BitmapFontConfiguration //BitmapFontConfiguration
// //
CCBMFontConfiguration * CCBMFontConfiguration::create(const char *FNTfile) CCBMFontConfiguration * CCBMFontConfiguration::create(const std::string& FNTfile)
{ {
CCBMFontConfiguration * pRet = new CCBMFontConfiguration(); CCBMFontConfiguration * ret = new CCBMFontConfiguration();
if (pRet->initWithFNTfile(FNTfile)) if (ret->initWithFNTfile(FNTfile))
{ {
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
return NULL; return NULL;
} }
bool CCBMFontConfiguration::initWithFNTfile(const char *FNTfile) bool CCBMFontConfiguration::initWithFNTfile(const std::string& FNTfile)
{ {
_kerningDictionary = NULL; _kerningDictionary = NULL;
_fontDefDictionary = NULL; _fontDefDictionary = NULL;
@ -180,7 +180,7 @@ void CCBMFontConfiguration::purgeFontDefDictionary()
} }
} }
std::set<unsigned int>* CCBMFontConfiguration::parseConfigFile(const char *controlFile) std::set<unsigned int>* CCBMFontConfiguration::parseConfigFile(const std::string& controlFile)
{ {
std::string fullpath = FileUtils::getInstance()->fullPathForFilename(controlFile); std::string fullpath = FileUtils::getInstance()->fullPathForFilename(controlFile);
String *contents = String::createWithContentsOfFile(fullpath.c_str()); String *contents = String::createWithContentsOfFile(fullpath.c_str());
@ -191,7 +191,7 @@ std::set<unsigned int>* CCBMFontConfiguration::parseConfigFile(const char *contr
if (!contents) if (!contents)
{ {
CCLOG("cocos2d: Error parsing FNTfile %s", controlFile); CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.c_str());
return NULL; return NULL;
} }
@ -200,7 +200,7 @@ std::set<unsigned int>* CCBMFontConfiguration::parseConfigFile(const char *contr
std::string strLeft = contents->getCString(); std::string strLeft = contents->getCString();
while (strLeft.length() > 0) while (strLeft.length() > 0)
{ {
int pos = strLeft.find('\n'); size_t pos = strLeft.find('\n');
if (pos != (int)std::string::npos) if (pos != (int)std::string::npos)
{ {
@ -259,7 +259,7 @@ std::set<unsigned int>* CCBMFontConfiguration::parseConfigFile(const char *contr
return validCharsString; return validCharsString;
} }
void CCBMFontConfiguration::parseImageFileName(std::string line, const char *fntFile) void CCBMFontConfiguration::parseImageFileName(std::string line, const std::string& fntFile)
{ {
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
// line to parse: // line to parse:
@ -267,8 +267,8 @@ void CCBMFontConfiguration::parseImageFileName(std::string line, const char *fnt
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
// page ID. Sanity check // page ID. Sanity check
int index = line.find('=')+1; long index = line.find('=')+1;
int index2 = line.find(' ', index); long index2 = line.find(' ', index);
std::string value = line.substr(index, index2-index); std::string value = line.substr(index, index2-index);
CCASSERT(atoi(value.c_str()) == 0, "LabelBMFont file could not be found"); CCASSERT(atoi(value.c_str()) == 0, "LabelBMFont file could not be found");
// file // file
@ -288,8 +288,8 @@ void CCBMFontConfiguration::parseInfoArguments(std::string line)
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
// padding // padding
int index = line.find("padding="); long index = line.find("padding=");
int index2 = line.find(' ', index); long index2 = line.find(' ', index);
std::string value = line.substr(index, index2-index); std::string value = line.substr(index, index2-index);
sscanf(value.c_str(), "padding=%d,%d,%d,%d", &_padding.top, &_padding.right, &_padding.bottom, &_padding.left); sscanf(value.c_str(), "padding=%d,%d,%d,%d", &_padding.top, &_padding.right, &_padding.bottom, &_padding.left);
CCLOG("cocos2d: padding: %d,%d,%d,%d", _padding.left, _padding.top, _padding.right, _padding.bottom); CCLOG("cocos2d: padding: %d,%d,%d,%d", _padding.left, _padding.top, _padding.right, _padding.bottom);
@ -303,8 +303,8 @@ void CCBMFontConfiguration::parseCommonArguments(std::string line)
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
// Height // Height
int index = line.find("lineHeight="); long index = line.find("lineHeight=");
int index2 = line.find(' ', index); long index2 = line.find(' ', index);
std::string value = line.substr(index, index2-index); std::string value = line.substr(index, index2-index);
sscanf(value.c_str(), "lineHeight=%d", &_commonHeight); sscanf(value.c_str(), "lineHeight=%d", &_commonHeight);
// scaleW. sanity check // scaleW. sanity check
@ -334,8 +334,8 @@ void CCBMFontConfiguration::parseCharacterDefinition(std::string line, ccBMFontD
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
// Character ID // Character ID
int index = line.find("id="); long index = line.find("id=");
int index2 = line.find(' ', index); long index2 = line.find(' ', index);
std::string value = line.substr(index, index2-index); std::string value = line.substr(index, index2-index);
sscanf(value.c_str(), "id=%u", &characterDefinition->charID); sscanf(value.c_str(), "id=%u", &characterDefinition->charID);
@ -385,8 +385,8 @@ void CCBMFontConfiguration::parseKerningEntry(std::string line)
// first // first
int first; int first;
int index = line.find("first="); long index = line.find("first=");
int index2 = line.find(' ', index); long index2 = line.find(' ', index);
std::string value = line.substr(index, index2-index); std::string value = line.substr(index, index2-index);
sscanf(value.c_str(), "first=%d", &first); sscanf(value.c_str(), "first=%d", &first);
@ -431,23 +431,23 @@ LabelBMFont * LabelBMFont::create()
return NULL; return NULL;
} }
LabelBMFont * LabelBMFont::create(const char *str, const char *fntFile, float width, TextHAlignment alignment) LabelBMFont * LabelBMFont::create(const std::string& str, const std::string& fntFile, float width, TextHAlignment alignment)
{ {
return LabelBMFont::create(str, fntFile, width, alignment, Point::ZERO); return LabelBMFont::create(str, fntFile, width, alignment, Point::ZERO);
} }
LabelBMFont * LabelBMFont::create(const char *str, const char *fntFile, float width) LabelBMFont * LabelBMFont::create(const std::string& str, const std::string& fntFile, float width)
{ {
return LabelBMFont::create(str, fntFile, width, TextHAlignment::LEFT, Point::ZERO); return LabelBMFont::create(str, fntFile, width, TextHAlignment::LEFT, Point::ZERO);
} }
LabelBMFont * LabelBMFont::create(const char *str, const char *fntFile) LabelBMFont * LabelBMFont::create(const std::string& str, const std::string& fntFile)
{ {
return LabelBMFont::create(str, fntFile, kLabelAutomaticWidth, TextHAlignment::LEFT, Point::ZERO); return LabelBMFont::create(str, fntFile, kLabelAutomaticWidth, TextHAlignment::LEFT, Point::ZERO);
} }
//LabelBMFont - Creation & Init //LabelBMFont - Creation & Init
LabelBMFont *LabelBMFont::create(const char *str, const char *fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = TextHAlignment::LEFT*/, Point imageOffset/* = Point::ZERO*/) LabelBMFont *LabelBMFont::create(const std::string& str, const std::string& fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = TextHAlignment::LEFT*/, Point imageOffset/* = Point::ZERO*/)
{ {
LabelBMFont *pRet = new LabelBMFont(); LabelBMFont *pRet = new LabelBMFont();
if(pRet && pRet->initWithString(str, fntFile, width, alignment, imageOffset)) if(pRet && pRet->initWithString(str, fntFile, width, alignment, imageOffset))
@ -461,22 +461,21 @@ LabelBMFont *LabelBMFont::create(const char *str, const char *fntFile, float wid
bool LabelBMFont::init() bool LabelBMFont::init()
{ {
return initWithString(NULL, NULL, kLabelAutomaticWidth, TextHAlignment::LEFT, Point::ZERO); return initWithString("", "", kLabelAutomaticWidth, TextHAlignment::LEFT, Point::ZERO);
} }
bool LabelBMFont::initWithString(const char *theString, const char *fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = TextHAlignment::LEFT*/, Point imageOffset/* = Point::ZERO*/) bool LabelBMFont::initWithString(const std::string& theString, const std::string& fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = TextHAlignment::LEFT*/, Point imageOffset/* = Point::ZERO*/)
{ {
CCASSERT(!_configuration, "re-init is no longer supported"); CCASSERT(!_configuration, "re-init is no longer supported");
CCASSERT( (theString && fntFile) || (theString==NULL && fntFile==NULL), "Invalid params for LabelBMFont");
Texture2D *texture = NULL; Texture2D *texture = NULL;
if (fntFile) if (fntFile.size() > 0 )
{ {
CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFile); CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFile);
if (!newConf) if (!newConf)
{ {
CCLOG("cocos2d: WARNING. LabelBMFont: Impossible to create font. Please check file: '%s'", fntFile); CCLOG("cocos2d: WARNING. LabelBMFont: Impossible to create font. Please check file: '%s'", fntFile.c_str());
release(); release();
return false; return false;
} }
@ -487,7 +486,7 @@ bool LabelBMFont::initWithString(const char *theString, const char *fntFile, flo
_fntFile = fntFile; _fntFile = fntFile;
texture = TextureCache::getInstance()->addImage(_configuration->getAtlasName()); texture = Director::getInstance()->getTextureCache()->addImage(_configuration->getAtlasName());
} }
else else
{ {
@ -495,12 +494,7 @@ bool LabelBMFont::initWithString(const char *theString, const char *fntFile, flo
texture->autorelease(); texture->autorelease();
} }
if (theString == NULL) if (SpriteBatchNode::initWithTexture(texture, theString.size()))
{
theString = "";
}
if (SpriteBatchNode::initWithTexture(texture, strlen(theString)))
{ {
_width = width; _width = width;
_alignment = alignment; _alignment = alignment;
@ -724,20 +718,17 @@ void LabelBMFont::createFontChars()
} }
//LabelBMFont - LabelProtocol protocol //LabelBMFont - LabelProtocol protocol
void LabelBMFont::setString(const char *newString) void LabelBMFont::setString(const std::string &newString)
{ {
this->setString(newString, true); this->setString(newString, true);
} }
void LabelBMFont::setString(const char *newString, bool needUpdateLabel) void LabelBMFont::setString(const std::string &newString, bool needUpdateLabel)
{ {
if (newString == NULL) {
newString = "";
}
if (needUpdateLabel) { if (needUpdateLabel) {
_initialStringUTF8 = newString; _initialStringUTF8 = newString;
} }
unsigned short* utf16String = cc_utf8_to_utf16(newString); unsigned short* utf16String = cc_utf8_to_utf16(newString.c_str());
setString(utf16String, needUpdateLabel); setString(utf16String, needUpdateLabel);
CC_SAFE_DELETE_ARRAY(utf16String); CC_SAFE_DELETE_ARRAY(utf16String);
} }
@ -776,9 +767,9 @@ void LabelBMFont::setString(unsigned short *newString, bool needUpdateLabel)
} }
} }
const char* LabelBMFont::getString(void) const const std::string& LabelBMFont::getString() const
{ {
return _initialStringUTF8.c_str(); return _initialStringUTF8;
} }
void LabelBMFont::setCString(const char *label) void LabelBMFont::setCString(const char *label)
@ -1082,9 +1073,9 @@ void LabelBMFont::updateLabel()
int size = multiline_string.size(); int size = multiline_string.size();
unsigned short* str_new = new unsigned short[size + 1]; unsigned short* str_new = new unsigned short[size + 1];
for (int i = 0; i < size; ++i) for (int j = 0; j < size; ++j)
{ {
str_new[i] = multiline_string[i]; str_new[j] = multiline_string[j];
} }
str_new[size] = '\0'; str_new[size] = '\0';
@ -1222,7 +1213,7 @@ void LabelBMFont::setFntFile(const char* fntFile)
CC_SAFE_RELEASE(_configuration); CC_SAFE_RELEASE(_configuration);
_configuration = newConf; _configuration = newConf;
this->setTexture(TextureCache::getInstance()->addImage(_configuration->getAtlasName())); this->setTexture(Director::getInstance()->getTextureCache()->addImage(_configuration->getAtlasName()));
this->createFontChars(); this->createFontChars();
} }
} }

View File

@ -140,21 +140,21 @@ public:
const char * description() const; const char * description() const;
/** allocates a CCBMFontConfiguration with a FNT file */ /** allocates a CCBMFontConfiguration with a FNT file */
static CCBMFontConfiguration * create(const char *FNTfile); static CCBMFontConfiguration * create(const std::string& FNTfile);
/** initializes a BitmapFontConfiguration with a FNT file */ /** initializes a BitmapFontConfiguration with a FNT file */
bool initWithFNTfile(const char *FNTfile); bool initWithFNTfile(const std::string& FNTfile);
inline const char* getAtlasName(){ return _atlasName.c_str(); } inline const std::string& getAtlasName(){ return _atlasName; }
inline void setAtlasName(const char* atlasName) { _atlasName = atlasName; } inline void setAtlasName(const std::string& atlasName) { _atlasName = atlasName; }
std::set<unsigned int>* getCharacterSet() const; std::set<unsigned int>* getCharacterSet() const;
private: private:
std::set<unsigned int>* parseConfigFile(const char *controlFile); std::set<unsigned int>* parseConfigFile(const std::string& controlFile);
void parseCharacterDefinition(std::string line, ccBMFontDef *characterDefinition); void parseCharacterDefinition(std::string line, ccBMFontDef *characterDefinition);
void parseInfoArguments(std::string line); void parseInfoArguments(std::string line);
void parseCommonArguments(std::string line); void parseCommonArguments(std::string line);
void parseImageFileName(std::string line, const char *fntFile); void parseImageFileName(std::string line, const std::string& fntFile);
void parseKerningEntry(std::string line); void parseKerningEntry(std::string line);
void purgeKerningDictionary(); void purgeKerningDictionary();
void purgeFontDefDictionary(); void purgeFontDefDictionary();
@ -209,13 +209,13 @@ public:
static void purgeCachedData(); static void purgeCachedData();
/** creates a bitmap font atlas with an initial string and the FNT file */ /** creates a bitmap font atlas with an initial string and the FNT file */
static LabelBMFont * create(const char *str, const char *fntFile, float width, TextHAlignment alignment, Point imageOffset); static LabelBMFont * create(const std::string& str, const std::string& fntFile, float width, TextHAlignment alignment, Point imageOffset);
static LabelBMFont * create(const char *str, const char *fntFile, float width, TextHAlignment alignment); static LabelBMFont * create(const std::string& str, const std::string& fntFile, float width, TextHAlignment alignment);
static LabelBMFont * create(const char *str, const char *fntFile, float width); static LabelBMFont * create(const std::string& str, const std::string& fntFile, float width);
static LabelBMFont * create(const char *str, const char *fntFile); static LabelBMFont * create(const std::string& str, const std::string& fntFile);
/** Creates an label. /** Creates an label.
*/ */
@ -223,15 +223,15 @@ public:
bool init(); bool init();
/** init a bitmap font atlas with an initial string and the FNT file */ /** init a bitmap font atlas with an initial string and the FNT file */
bool initWithString(const char *str, const char *fntFile, float width = kLabelAutomaticWidth, TextHAlignment alignment = TextHAlignment::LEFT, Point imageOffset = Point::ZERO); bool initWithString(const std::string& str, const std::string& fntFile, float width = kLabelAutomaticWidth, TextHAlignment alignment = TextHAlignment::LEFT, Point imageOffset = Point::ZERO);
/** updates the font chars based on the string to render */ /** updates the font chars based on the string to render */
void createFontChars(); void createFontChars();
// super method // super method
virtual void setString(const char *newString); virtual void setString(const std::string& newString) override;
virtual void setString(const char *newString, bool needUpdateLabel); virtual void setString(const std::string& newString, bool needUpdateLabel);
virtual const char* getString(void) const; virtual const std::string& getString() const override;
virtual void setCString(const char *label); virtual void setCString(const char *label);
virtual void setAnchorPoint(const Point& var); virtual void setAnchorPoint(const Point& var);
virtual void updateLabel(); virtual void updateLabel();
@ -264,7 +264,7 @@ public:
virtual void draw(); virtual void draw();
#endif // CC_LABELBMFONT_DEBUG_DRAW #endif // CC_LABELBMFONT_DEBUG_DRAW
private: private:
char * atlasNameFromFntFile(const char *fntFile); char * atlasNameFromFntFile(const std::string& fntFile);
int kerningAmountForFirst(unsigned short first, unsigned short second); int kerningAmountForFirst(unsigned short first, unsigned short second);
float getLetterPosXLeft( Sprite* characterSprite ); float getLetterPosXLeft( Sprite* characterSprite );
float getLetterPosXRight( Sprite* characterSprite ); float getLetterPosXRight( Sprite* characterSprite );
@ -303,13 +303,13 @@ protected:
bool _cascadeColorEnabled; bool _cascadeColorEnabled;
bool _cascadeOpacityEnabled; bool _cascadeOpacityEnabled;
/** conforms to RGBAProtocol protocol */ /** conforms to RGBAProtocol protocol */
bool _isOpacityModifyRGB; bool _isOpacityModifyRGB;
}; };
/** Free function that parses a FNT file a place it on the cache /** Free function that parses a FNT file a place it on the cache
*/ */
CC_DLL CCBMFontConfiguration * FNTConfigLoadFile( const char *file ); CC_DLL CCBMFontConfiguration * FNTConfigLoadFile(const std::string &file);
/** Purges the FNT config cache /** Purges the FNT config cache
*/ */
CC_DLL void FNTConfigRemoveCache( void ); CC_DLL void FNTConfigRemoveCache( void );

View File

@ -42,7 +42,7 @@ NS_CC_BEGIN
LabelTTF::LabelTTF() LabelTTF::LabelTTF()
: _alignment(TextHAlignment::CENTER) : _alignment(TextHAlignment::CENTER)
, _vAlignment(TextVAlignment::TOP) , _vAlignment(TextVAlignment::TOP)
, _fontName(NULL) , _fontName("")
, _fontSize(0.0) , _fontSize(0.0)
, _string("") , _string("")
, _shadowEnabled(false) , _shadowEnabled(false)
@ -53,58 +53,57 @@ LabelTTF::LabelTTF()
LabelTTF::~LabelTTF() LabelTTF::~LabelTTF()
{ {
CC_SAFE_DELETE(_fontName);
} }
LabelTTF * LabelTTF::create() LabelTTF * LabelTTF::create()
{ {
LabelTTF * pRet = new LabelTTF(); LabelTTF * ret = new LabelTTF();
if (pRet && pRet->init()) if (ret && ret->init())
{ {
pRet->autorelease(); ret->autorelease();
} }
else else
{ {
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
} }
return pRet; return ret;
} }
LabelTTF * LabelTTF::create(const char *string, const char *fontName, float fontSize) LabelTTF * LabelTTF::create(const std::string& string, const std::string& fontName, float fontSize)
{ {
return LabelTTF::create(string, fontName, fontSize, return LabelTTF::create(string, fontName, fontSize,
Size::ZERO, TextHAlignment::CENTER, TextVAlignment::TOP); Size::ZERO, TextHAlignment::CENTER, TextVAlignment::TOP);
} }
LabelTTF * LabelTTF::create(const char *string, const char *fontName, float fontSize, LabelTTF * LabelTTF::create(const std::string& string, const std::string& fontName, float fontSize,
const Size& dimensions, TextHAlignment hAlignment) const Size& dimensions, TextHAlignment hAlignment)
{ {
return LabelTTF::create(string, fontName, fontSize, dimensions, hAlignment, TextVAlignment::TOP); return LabelTTF::create(string, fontName, fontSize, dimensions, hAlignment, TextVAlignment::TOP);
} }
LabelTTF* LabelTTF::create(const char *string, const char *fontName, float fontSize, LabelTTF* LabelTTF::create(const std::string& string, const std::string& fontName, float fontSize,
const Size &dimensions, TextHAlignment hAlignment, const Size &dimensions, TextHAlignment hAlignment,
TextVAlignment vAlignment) TextVAlignment vAlignment)
{ {
LabelTTF *pRet = new LabelTTF(); LabelTTF *ret = new LabelTTF();
if(pRet && pRet->initWithString(string, fontName, fontSize, dimensions, hAlignment, vAlignment)) if(ret && ret->initWithString(string, fontName, fontSize, dimensions, hAlignment, vAlignment))
{ {
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
return NULL; return NULL;
} }
LabelTTF * LabelTTF::createWithFontDefinition(const char *string, FontDefinition &textDefinition) LabelTTF * LabelTTF::createWithFontDefinition(const std::string& string, FontDefinition &textDefinition)
{ {
LabelTTF *pRet = new LabelTTF(); LabelTTF *ret = new LabelTTF();
if(pRet && pRet->initWithStringAndTextDefinition(string, textDefinition)) if(ret && ret->initWithStringAndTextDefinition(string, textDefinition))
{ {
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
return NULL; return NULL;
} }
@ -113,19 +112,19 @@ bool LabelTTF::init()
return this->initWithString("", "Helvetica", 12); return this->initWithString("", "Helvetica", 12);
} }
bool LabelTTF::initWithString(const char *label, const char *fontName, float fontSize, bool LabelTTF::initWithString(const std::string& label, const std::string& fontName, float fontSize,
const Size& dimensions, TextHAlignment alignment) const Size& dimensions, TextHAlignment alignment)
{ {
return this->initWithString(label, fontName, fontSize, dimensions, alignment, TextVAlignment::TOP); return this->initWithString(label, fontName, fontSize, dimensions, alignment, TextVAlignment::TOP);
} }
bool LabelTTF::initWithString(const char *label, const char *fontName, float fontSize) bool LabelTTF::initWithString(const std::string& label, const std::string& fontName, float fontSize)
{ {
return this->initWithString(label, fontName, fontSize, return this->initWithString(label, fontName, fontSize,
Size::ZERO, TextHAlignment::LEFT, TextVAlignment::TOP); Size::ZERO, TextHAlignment::LEFT, TextVAlignment::TOP);
} }
bool LabelTTF::initWithString(const char *string, const char *fontName, float fontSize, bool LabelTTF::initWithString(const std::string& string, const std::string& fontName, float fontSize,
const cocos2d::Size &dimensions, TextHAlignment hAlignment, const cocos2d::Size &dimensions, TextHAlignment hAlignment,
TextVAlignment vAlignment) TextVAlignment vAlignment)
{ {
@ -135,10 +134,10 @@ bool LabelTTF::initWithString(const char *string, const char *fontName, float fo
this->setShaderProgram(ShaderCache::getInstance()->getProgram(SHADER_PROGRAM)); this->setShaderProgram(ShaderCache::getInstance()->getProgram(SHADER_PROGRAM));
_dimensions = Size(dimensions.width, dimensions.height); _dimensions = Size(dimensions.width, dimensions.height);
_alignment = hAlignment; _alignment = hAlignment;
_vAlignment = vAlignment; _vAlignment = vAlignment;
_fontName = new std::string(fontName); _fontName = fontName;
_fontSize = fontSize; _fontSize = fontSize;
this->setString(string); this->setString(string);
@ -148,7 +147,7 @@ bool LabelTTF::initWithString(const char *string, const char *fontName, float fo
return false; return false;
} }
bool LabelTTF::initWithStringAndTextDefinition(const char *string, FontDefinition &textDefinition) bool LabelTTF::initWithStringAndTextDefinition(const std::string& string, FontDefinition &textDefinition)
{ {
if (Sprite::init()) if (Sprite::init())
{ {
@ -171,10 +170,8 @@ bool LabelTTF::initWithStringAndTextDefinition(const char *string, FontDefinitio
} }
void LabelTTF::setString(const char *string) void LabelTTF::setString(const std::string &string)
{ {
CCASSERT(string != NULL, "Invalid string");
if (_string.compare(string)) if (_string.compare(string))
{ {
_string = string; _string = string;
@ -183,14 +180,14 @@ void LabelTTF::setString(const char *string)
} }
} }
const char* LabelTTF::getString(void) const const std::string& LabelTTF::getString() const
{ {
return _string.c_str(); return _string;
} }
const char* LabelTTF::description() const const char* LabelTTF::description() const
{ {
return String::createWithFormat("<LabelTTF | FontName = %s, FontSize = %.1f>", _fontName->c_str(), _fontSize)->getCString(); return String::createWithFormat("<LabelTTF | FontName = %s, FontSize = %.1f>", _fontName.c_str(), _fontSize)->getCString();
} }
TextHAlignment LabelTTF::getHorizontalAlignment() const TextHAlignment LabelTTF::getHorizontalAlignment() const
@ -238,6 +235,7 @@ const Size& LabelTTF::getDimensions() const
void LabelTTF::setDimensions(const Size &dim) void LabelTTF::setDimensions(const Size &dim)
{ {
// XXX: float comparison... very unreliable
if (dim.width != _dimensions.width || dim.height != _dimensions.height) if (dim.width != _dimensions.width || dim.height != _dimensions.height)
{ {
_dimensions = dim; _dimensions = dim;
@ -257,6 +255,7 @@ float LabelTTF::getFontSize() const
void LabelTTF::setFontSize(float fontSize) void LabelTTF::setFontSize(float fontSize)
{ {
// XXX: float comparison... very unreliable
if (_fontSize != fontSize) if (_fontSize != fontSize)
{ {
_fontSize = fontSize; _fontSize = fontSize;
@ -269,17 +268,16 @@ void LabelTTF::setFontSize(float fontSize)
} }
} }
const char* LabelTTF::getFontName() const const std::string& LabelTTF::getFontName() const
{ {
return _fontName->c_str(); return _fontName;
} }
void LabelTTF::setFontName(const char *fontName) void LabelTTF::setFontName(const std::string& fontName)
{ {
if (_fontName->compare(fontName)) if (_fontName.compare(fontName))
{ {
delete _fontName; _fontName = fontName;
_fontName = new std::string(fontName);
// Force update // Force update
if (_string.size() > 0) if (_string.size() > 0)
@ -298,21 +296,21 @@ bool LabelTTF::updateTexture()
if (!tex) if (!tex)
return false; return false;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
FontDefinition texDef = _prepareTextDefinition(true); FontDefinition texDef = _prepareTextDefinition(true);
tex->initWithString( _string.c_str(), texDef ); tex->initWithString( _string.c_str(), texDef );
#else #else
tex->initWithString( _string.c_str(), tex->initWithString( _string.c_str(),
_fontName->c_str(), _fontName.c_str(),
_fontSize * CC_CONTENT_SCALE_FACTOR(), _fontSize * CC_CONTENT_SCALE_FACTOR(),
CC_SIZE_POINTS_TO_PIXELS(_dimensions), CC_SIZE_POINTS_TO_PIXELS(_dimensions),
_alignment, _alignment,
_vAlignment); _vAlignment);
#endif #endif
// set the texture // set the texture
this->setTexture(tex); this->setTexture(tex);
@ -342,7 +340,7 @@ void LabelTTF::enableShadow(const Size &shadowOffset, float shadowOpacity, float
if ( (_shadowOffset.width != shadowOffset.width) || (_shadowOffset.height!=shadowOffset.height) ) if ( (_shadowOffset.width != shadowOffset.width) || (_shadowOffset.height!=shadowOffset.height) )
{ {
_shadowOffset.width = shadowOffset.width; _shadowOffset.width = shadowOffset.width;
_shadowOffset.height = shadowOffset.height; _shadowOffset.height = shadowOffset.height;
valueChanged = true; valueChanged = true;
@ -354,27 +352,26 @@ void LabelTTF::enableShadow(const Size &shadowOffset, float shadowOpacity, float
valueChanged = true; valueChanged = true;
} }
if (_shadowBlur != shadowBlur) if (_shadowBlur != shadowBlur)
{ {
_shadowBlur = shadowBlur; _shadowBlur = shadowBlur;
valueChanged = true; valueChanged = true;
} }
if ( valueChanged && updateTexture ) if ( valueChanged && updateTexture )
{ {
this->updateTexture(); this->updateTexture();
} }
#else #else
CCLOGERROR("Currently only supported on iOS and Android!"); CCLOGERROR("Currently only supported on iOS and Android!");
#endif #endif
} }
void LabelTTF::disableShadow(bool updateTexture) void LabelTTF::disableShadow(bool updateTexture)
{ {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
if (_shadowEnabled) if (_shadowEnabled)
{ {
@ -382,17 +379,16 @@ void LabelTTF::disableShadow(bool updateTexture)
if (updateTexture) if (updateTexture)
this->updateTexture(); this->updateTexture();
} }
#else #else
CCLOGERROR("Currently only supported on iOS and Android!"); CCLOGERROR("Currently only supported on iOS and Android!");
#endif #endif
} }
void LabelTTF::enableStroke(const Color3B &strokeColor, float strokeSize, bool updateTexture) void LabelTTF::enableStroke(const Color3B &strokeColor, float strokeSize, bool updateTexture)
{ {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
bool valueChanged = false; bool valueChanged = false;
@ -419,15 +415,15 @@ void LabelTTF::enableStroke(const Color3B &strokeColor, float strokeSize, bool u
this->updateTexture(); this->updateTexture();
} }
#else #else
CCLOGERROR("Currently only supported on iOS and Android!"); CCLOGERROR("Currently only supported on iOS and Android!");
#endif #endif
} }
void LabelTTF::disableStroke(bool updateTexture) void LabelTTF::disableStroke(bool updateTexture)
{ {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
if (_strokeEnabled) if (_strokeEnabled)
{ {
@ -437,15 +433,15 @@ void LabelTTF::disableStroke(bool updateTexture)
this->updateTexture(); this->updateTexture();
} }
#else #else
CCLOGERROR("Currently only supported on iOS and Android!"); CCLOGERROR("Currently only supported on iOS and Android!");
#endif #endif
} }
void LabelTTF::setFontFillColor(const Color3B &tintColor, bool updateTexture) void LabelTTF::setFontFillColor(const Color3B &tintColor, bool updateTexture)
{ {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
if (_textFillColor.r != tintColor.r || _textFillColor.g != tintColor.g || _textFillColor.b != tintColor.b) if (_textFillColor.r != tintColor.r || _textFillColor.g != tintColor.g || _textFillColor.b != tintColor.b)
{ {
_textFillColor = tintColor; _textFillColor = tintColor;
@ -453,9 +449,9 @@ void LabelTTF::setFontFillColor(const Color3B &tintColor, bool updateTexture)
if (updateTexture) if (updateTexture)
this->updateTexture(); this->updateTexture();
} }
#else #else
CCLOGERROR("Currently only supported on iOS and Android!"); CCLOGERROR("Currently only supported on iOS and Android!");
#endif #endif
} }
void LabelTTF::setTextDefinition(const FontDefinition& theDefinition) void LabelTTF::setTextDefinition(const FontDefinition& theDefinition)
@ -471,11 +467,11 @@ FontDefinition LabelTTF::getTextDefinition()
void LabelTTF::_updateWithTextDefinition(const FontDefinition& textDefinition, bool mustUpdateTexture) void LabelTTF::_updateWithTextDefinition(const FontDefinition& textDefinition, bool mustUpdateTexture)
{ {
_dimensions = Size(textDefinition._dimensions.width, textDefinition._dimensions.height); _dimensions = Size(textDefinition._dimensions.width, textDefinition._dimensions.height);
_alignment = textDefinition._alignment; _alignment = textDefinition._alignment;
_vAlignment = textDefinition._vertAlignment; _vAlignment = textDefinition._vertAlignment;
_fontName = new std::string(textDefinition._fontName); _fontName = textDefinition._fontName;
_fontSize = textDefinition._fontSize; _fontSize = textDefinition._fontSize;
// shadow // shadow
@ -502,19 +498,19 @@ FontDefinition LabelTTF::_prepareTextDefinition(bool adjustForResolution)
FontDefinition texDef; FontDefinition texDef;
if (adjustForResolution) if (adjustForResolution)
texDef._fontSize = _fontSize * CC_CONTENT_SCALE_FACTOR(); texDef._fontSize = _fontSize * CC_CONTENT_SCALE_FACTOR();
else else
texDef._fontSize = _fontSize; texDef._fontSize = _fontSize;
texDef._fontName = *_fontName; texDef._fontName = _fontName;
texDef._alignment = _alignment; texDef._alignment = _alignment;
texDef._vertAlignment = _vAlignment; texDef._vertAlignment = _vAlignment;
if (adjustForResolution) if (adjustForResolution)
texDef._dimensions = CC_SIZE_POINTS_TO_PIXELS(_dimensions); texDef._dimensions = CC_SIZE_POINTS_TO_PIXELS(_dimensions);
else else
texDef._dimensions = _dimensions; texDef._dimensions = _dimensions;
// stroke // stroke
@ -527,21 +523,18 @@ FontDefinition LabelTTF::_prepareTextDefinition(bool adjustForResolution)
texDef._stroke._strokeSize = _strokeSize * CC_CONTENT_SCALE_FACTOR(); texDef._stroke._strokeSize = _strokeSize * CC_CONTENT_SCALE_FACTOR();
else else
texDef._stroke._strokeSize = _strokeSize; texDef._stroke._strokeSize = _strokeSize;
} }
else else
{ {
texDef._stroke._strokeEnabled = false; texDef._stroke._strokeEnabled = false;
} }
// shadow // shadow
if ( _shadowEnabled ) if ( _shadowEnabled )
{ {
texDef._shadow._shadowEnabled = true; texDef._shadow._shadowEnabled = true;
texDef._shadow._shadowBlur = _shadowBlur; texDef._shadow._shadowBlur = _shadowBlur;
texDef._shadow._shadowOpacity = _shadowOpacity; texDef._shadow._shadowOpacity = _shadowOpacity;
if (adjustForResolution) if (adjustForResolution)
texDef._shadow._shadowOffset = CC_SIZE_POINTS_TO_PIXELS(_shadowOffset); texDef._shadow._shadowOffset = CC_SIZE_POINTS_TO_PIXELS(_shadowOffset);

View File

@ -75,39 +75,39 @@ public:
/** creates a LabelTTF with a font name and font size in points /** creates a LabelTTF with a font name and font size in points
@since v2.0.1 @since v2.0.1
*/ */
static LabelTTF * create(const char *string, const char *fontName, float fontSize); static LabelTTF * create(const std::string& string, const std::string& fontName, float fontSize);
/** creates a LabelTTF from a fontname, horizontal alignment, dimension in points, and font size in points. /** creates a LabelTTF from a fontname, horizontal alignment, dimension in points, and font size in points.
@since v2.0.1 @since v2.0.1
*/ */
static LabelTTF * create(const char *string, const char *fontName, float fontSize, static LabelTTF * create(const std::string& string, const std::string& fontName, float fontSize,
const Size& dimensions, TextHAlignment hAlignment); const Size& dimensions, TextHAlignment hAlignment);
/** creates a Label from a fontname, alignment, dimension in points and font size in points /** creates a Label from a fontname, alignment, dimension in points and font size in points
@since v2.0.1 @since v2.0.1
*/ */
static LabelTTF * create(const char *string, const char *fontName, float fontSize, static LabelTTF * create(const std::string& string, const std::string& fontName, float fontSize,
const Size& dimensions, TextHAlignment hAlignment, const Size& dimensions, TextHAlignment hAlignment,
TextVAlignment vAlignment); TextVAlignment vAlignment);
/** Create a lable with string and a font definition*/ /** Create a lable with string and a font definition*/
static LabelTTF * createWithFontDefinition(const char *string, FontDefinition &textDefinition); static LabelTTF * createWithFontDefinition(const std::string& string, FontDefinition &textDefinition);
/** initializes the LabelTTF with a font name and font size */ /** initializes the LabelTTF with a font name and font size */
bool initWithString(const char *string, const char *fontName, float fontSize); bool initWithString(const std::string& string, const std::string& fontName, float fontSize);
/** initializes the LabelTTF with a font name, alignment, dimension and font size */ /** initializes the LabelTTF with a font name, alignment, dimension and font size */
bool initWithString(const char *string, const char *fontName, float fontSize, bool initWithString(const std::string& string, const std::string& fontName, float fontSize,
const Size& dimensions, TextHAlignment hAlignment); const Size& dimensions, TextHAlignment hAlignment);
/** initializes the LabelTTF with a font name, alignment, dimension and font size */ /** initializes the LabelTTF with a font name, alignment, dimension and font size */
bool initWithString(const char *string, const char *fontName, float fontSize, bool initWithString(const std::string& string, const std::string& fontName, float fontSize,
const Size& dimensions, TextHAlignment hAlignment, const Size& dimensions, TextHAlignment hAlignment,
TextVAlignment vAlignment); TextVAlignment vAlignment);
/** initializes the LabelTTF with a font name, alignment, dimension and font size */ /** initializes the LabelTTF with a font name, alignment, dimension and font size */
bool initWithStringAndTextDefinition(const char *string, FontDefinition &textDefinition); bool initWithStringAndTextDefinition(const std::string& string, FontDefinition &textDefinition);
/** set the text definition used by this label */ /** set the text definition used by this label */
void setTextDefinition(const FontDefinition& theDefinition); void setTextDefinition(const FontDefinition& theDefinition);
@ -144,8 +144,8 @@ public:
/** changes the string to render /** changes the string to render
* @warning Changing the string is as expensive as creating a new LabelTTF. To obtain better performance use LabelAtlas * @warning Changing the string is as expensive as creating a new LabelTTF. To obtain better performance use LabelAtlas
*/ */
virtual void setString(const char *label); virtual void setString(const std::string &label) override;
virtual const char* getString(void) const; virtual const std::string& getString(void) const override;
TextHAlignment getHorizontalAlignment() const; TextHAlignment getHorizontalAlignment() const;
void setHorizontalAlignment(TextHAlignment alignment); void setHorizontalAlignment(TextHAlignment alignment);
@ -159,8 +159,8 @@ public:
float getFontSize() const; float getFontSize() const;
void setFontSize(float fontSize); void setFontSize(float fontSize);
const char* getFontName() const; const std::string& getFontName() const;
void setFontName(const char *fontName); void setFontName(const std::string& fontName);
private: private:
bool updateTexture(); bool updateTexture();
@ -177,7 +177,7 @@ protected:
/** The vertical alignment of the label */ /** The vertical alignment of the label */
TextVAlignment _vAlignment; TextVAlignment _vAlignment;
/** Font name used in the label */ /** Font name used in the label */
std::string * _fontName; std::string _fontName;
/** Font size of the label */ /** Font size of the label */
float _fontSize; float _fontSize;
/** label's string */ /** label's string */

View File

@ -200,9 +200,9 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel)
int size = multiline_string.size(); int size = multiline_string.size();
unsigned short* strNew = new unsigned short[size + 1]; unsigned short* strNew = new unsigned short[size + 1];
for (int i = 0; i < size; ++i) for (int j = 0; j < size; ++j)
{ {
strNew[i] = multiline_string[i]; strNew[j] = multiline_string[j];
} }
strNew[size] = 0; strNew[size] = 0;

View File

@ -87,29 +87,6 @@ Layer *Layer::create()
} }
} }
#ifdef CC_USE_PHYSICS
void Layer::addChild(Node* child)
{
Node::addChild(child);
}
void Layer::addChild(Node* child, int zOrder)
{
Node::addChild(child, zOrder);
}
void Layer::addChild(Node* child, int zOrder, int tag)
{
Node::addChild(child, zOrder, tag);
if (this->getParent() &&
dynamic_cast<Scene*>(this->getParent()) != nullptr)
{
dynamic_cast<Scene*>(this->getParent())->addChildToPhysicsWorld(child);
}
}
#endif
// LayerRGBA // LayerRGBA
LayerRGBA::LayerRGBA() LayerRGBA::LayerRGBA()
: _displayedOpacity(255) : _displayedOpacity(255)

View File

@ -112,12 +112,6 @@ public:
// //
// Overrides // Overrides
// //
#ifdef CC_USE_PHYSICS
virtual void addChild(Node* child) override;
virtual void addChild(Node* child, int zOrder) override;
virtual void addChild(Node* child, int zOrder, int tag) override;
#endif // CC_USE_PHYSICS
}; };
#ifdef __apple__ #ifdef __apple__

View File

@ -42,7 +42,7 @@ THE SOFTWARE.
NS_CC_BEGIN NS_CC_BEGIN
static unsigned int _globalFontSize = kItemSize; static long _globalFontSize = kItemSize;
static std::string _globalFontName = "Marker Felt"; static std::string _globalFontName = "Marker Felt";
static bool _globalFontNameRelease = false; static bool _globalFontNameRelease = false;
@ -64,18 +64,18 @@ MenuItem* MenuItem::create()
// XXX deprecated // XXX deprecated
MenuItem* MenuItem::create(Object *target, SEL_MenuHandler selector) MenuItem* MenuItem::create(Object *target, SEL_MenuHandler selector)
{ {
MenuItem *pRet = new MenuItem(); MenuItem *ret = new MenuItem();
pRet->initWithTarget(target, selector); ret->initWithTarget(target, selector);
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
MenuItem* MenuItem::create( const ccMenuCallback& callback) MenuItem* MenuItem::create( const ccMenuCallback& callback)
{ {
MenuItem *pRet = new MenuItem(); MenuItem *ret = new MenuItem();
pRet->initWithCallback(callback); ret->initWithCallback(callback);
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
// XXX deprecated // XXX deprecated
@ -188,26 +188,26 @@ void MenuItemLabel::setLabel(Node* var)
// XXX: deprecated // XXX: deprecated
MenuItemLabel * MenuItemLabel::create(Node*label, Object* target, SEL_MenuHandler selector) MenuItemLabel * MenuItemLabel::create(Node*label, Object* target, SEL_MenuHandler selector)
{ {
MenuItemLabel *pRet = new MenuItemLabel(); MenuItemLabel *ret = new MenuItemLabel();
pRet->initWithLabel(label, target, selector); ret->initWithLabel(label, target, selector);
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
MenuItemLabel * MenuItemLabel::create(Node*label, const ccMenuCallback& callback) MenuItemLabel * MenuItemLabel::create(Node*label, const ccMenuCallback& callback)
{ {
MenuItemLabel *pRet = new MenuItemLabel(); MenuItemLabel *ret = new MenuItemLabel();
pRet->initWithLabel(label, callback); ret->initWithLabel(label, callback);
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
MenuItemLabel* MenuItemLabel::create(Node *label) MenuItemLabel* MenuItemLabel::create(Node *label)
{ {
MenuItemLabel *pRet = new MenuItemLabel(); MenuItemLabel *ret = new MenuItemLabel();
pRet->initWithLabel(label, (const ccMenuCallback&) nullptr); ret->initWithLabel(label, (const ccMenuCallback&) nullptr);
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
// XXX: deprecated // XXX: deprecated
@ -237,7 +237,7 @@ MenuItemLabel::~MenuItemLabel()
{ {
} }
void MenuItemLabel::setString(const char * label) void MenuItemLabel::setString(const std::string& label)
{ {
dynamic_cast<LabelProtocol*>(_label)->setString(label); dynamic_cast<LabelProtocol*>(_label)->setString(label);
this->setContentSize(_label->getContentSize()); this->setContentSize(_label->getContentSize());
@ -310,41 +310,39 @@ void MenuItemLabel::setEnabled(bool enabled)
//CCMenuItemAtlasFont //CCMenuItemAtlasFont
// //
MenuItemAtlasFont * MenuItemAtlasFont::create(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap) MenuItemAtlasFont * MenuItemAtlasFont::create(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap)
{ {
return MenuItemAtlasFont::create(value, charMapFile, itemWidth, itemHeight, startCharMap, (const ccMenuCallback&)nullptr); return MenuItemAtlasFont::create(value, charMapFile, itemWidth, itemHeight, startCharMap, (const ccMenuCallback&)nullptr);
} }
// XXX: deprecated // XXX: deprecated
MenuItemAtlasFont * MenuItemAtlasFont::create(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector) MenuItemAtlasFont * MenuItemAtlasFont::create(const char* value, const char* charMapFile, long itemWidth, long itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector)
{ {
MenuItemAtlasFont *pRet = new MenuItemAtlasFont(); MenuItemAtlasFont *ret = new MenuItemAtlasFont();
pRet->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, target, selector); ret->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, target, selector);
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
MenuItemAtlasFont * MenuItemAtlasFont::create(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback) MenuItemAtlasFont * MenuItemAtlasFont::create(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap, const ccMenuCallback& callback)
{ {
MenuItemAtlasFont *pRet = new MenuItemAtlasFont(); MenuItemAtlasFont *ret = new MenuItemAtlasFont();
pRet->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, callback); ret->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, callback);
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
// XXX: deprecated // XXX: deprecated
bool MenuItemAtlasFont::initWithString(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector) bool MenuItemAtlasFont::initWithString(const char* value, const char* charMapFile, long itemWidth, long itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector)
{ {
CCASSERT( value != NULL && strlen(value) != 0, "value length must be greater than 0");
_target = target; _target = target;
CC_SAFE_RETAIN(_target); CC_SAFE_RETAIN(_target);
return initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, std::bind(selector,target, std::placeholders::_1) ); return initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, std::bind(selector,target, std::placeholders::_1) );
} }
bool MenuItemAtlasFont::initWithString(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback) bool MenuItemAtlasFont::initWithString(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap, const ccMenuCallback& callback)
{ {
CCASSERT( value != NULL && strlen(value) != 0, "value length must be greater than 0"); CCASSERT( value.size() != 0, "value length must be greater than 0");
LabelAtlas *label = new LabelAtlas(); LabelAtlas *label = new LabelAtlas();
label->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap); label->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap);
label->autorelease(); label->autorelease();
@ -359,17 +357,17 @@ bool MenuItemAtlasFont::initWithString(const char *value, const char *charMapFil
//CCMenuItemFont //CCMenuItemFont
// //
void MenuItemFont::setFontSize(unsigned int s) void MenuItemFont::setFontSize(long s)
{ {
_globalFontSize = s; _globalFontSize = s;
} }
unsigned int MenuItemFont::getFontSize() long MenuItemFont::getFontSize()
{ {
return _globalFontSize; return _globalFontSize;
} }
void MenuItemFont::setFontName(const char *name) void MenuItemFont::setFontName(const std::string& name)
{ {
if (_globalFontNameRelease) if (_globalFontNameRelease)
{ {
@ -379,35 +377,35 @@ void MenuItemFont::setFontName(const char *name)
_globalFontNameRelease = true; _globalFontNameRelease = true;
} }
const char * MenuItemFont::getFontName() const std::string& MenuItemFont::getFontName()
{ {
return _globalFontName.c_str(); return _globalFontName;
} }
// XXX: deprecated // XXX: deprecated
MenuItemFont * MenuItemFont::create(const char *value, Object* target, SEL_MenuHandler selector) MenuItemFont * MenuItemFont::create(const char *value, Object* target, SEL_MenuHandler selector)
{ {
MenuItemFont *pRet = new MenuItemFont(); MenuItemFont *ret = new MenuItemFont();
pRet->initWithString(value, target, selector); ret->initWithString(value, target, selector);
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
MenuItemFont * MenuItemFont::create(const char *value, const ccMenuCallback& callback) MenuItemFont * MenuItemFont::create(const std::string& value, const ccMenuCallback& callback)
{ {
MenuItemFont *pRet = new MenuItemFont(); MenuItemFont *ret = new MenuItemFont();
pRet->initWithString(value, callback); ret->initWithString(value, callback);
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
MenuItemFont * MenuItemFont::create(const char *value) MenuItemFont * MenuItemFont::create(const std::string& value)
{ {
MenuItemFont *pRet = new MenuItemFont(); MenuItemFont *ret = new MenuItemFont();
pRet->initWithString(value, (const ccMenuCallback&)nullptr); ret->initWithString(value, (const ccMenuCallback&)nullptr);
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
MenuItemFont::MenuItemFont() MenuItemFont::MenuItemFont()
@ -429,14 +427,14 @@ bool MenuItemFont::initWithString(const char *value, Object* target, SEL_MenuHan
return initWithString(value, std::bind(selector,target, std::placeholders::_1) ); return initWithString(value, std::bind(selector,target, std::placeholders::_1) );
} }
bool MenuItemFont::initWithString(const char *value, const ccMenuCallback& callback) bool MenuItemFont::initWithString(const std::string& value, const ccMenuCallback& callback)
{ {
CCASSERT( value != NULL && strlen(value) != 0, "Value length must be greater than 0"); CCASSERT( value.size() >= 0, "Value length must be greater than 0");
_fontName = _globalFontName; _fontName = _globalFontName;
_fontSize = _globalFontSize; _fontSize = _globalFontSize;
LabelTTF *label = LabelTTF::create(value, _fontName.c_str(), (float)_fontSize); LabelTTF *label = LabelTTF::create(value, _fontName, (float)_fontSize);
if (MenuItemLabel::initWithLabel(label, callback)) if (MenuItemLabel::initWithLabel(label, callback))
{ {
// do something ? // do something ?
@ -451,26 +449,26 @@ void MenuItemFont::recreateLabel()
this->setLabel(label); this->setLabel(label);
} }
void MenuItemFont::setFontSizeObj(unsigned int s) void MenuItemFont::setFontSizeObj(long s)
{ {
_fontSize = s; _fontSize = s;
recreateLabel(); recreateLabel();
} }
unsigned int MenuItemFont::getFontSizeObj() const long MenuItemFont::getFontSizeObj() const
{ {
return _fontSize; return _fontSize;
} }
void MenuItemFont::setFontNameObj(const char* name) void MenuItemFont::setFontNameObj(const std::string& name)
{ {
_fontName = name; _fontName = name;
recreateLabel(); recreateLabel();
} }
const char* MenuItemFont::getFontNameObj() const const std::string& MenuItemFont::getFontNameObj() const
{ {
return _fontName.c_str(); return _fontName;
} }
// //
@ -561,18 +559,18 @@ MenuItemSprite * MenuItemSprite::create(Node* normalSprite, Node* selectedSprite
// XXX deprecated // XXX deprecated
MenuItemSprite * MenuItemSprite::create(Node *normalSprite, Node *selectedSprite, Node *disabledSprite, Object *target, SEL_MenuHandler selector) MenuItemSprite * MenuItemSprite::create(Node *normalSprite, Node *selectedSprite, Node *disabledSprite, Object *target, SEL_MenuHandler selector)
{ {
MenuItemSprite *pRet = new MenuItemSprite(); MenuItemSprite *ret = new MenuItemSprite();
pRet->initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, target, selector); ret->initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, target, selector);
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
MenuItemSprite * MenuItemSprite::create(Node *normalSprite, Node *selectedSprite, Node *disabledSprite, const ccMenuCallback& callback) MenuItemSprite * MenuItemSprite::create(Node *normalSprite, Node *selectedSprite, Node *disabledSprite, const ccMenuCallback& callback)
{ {
MenuItemSprite *pRet = new MenuItemSprite(); MenuItemSprite *ret = new MenuItemSprite();
pRet->initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, callback); ret->initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, callback);
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
// XXX deprecated // XXX deprecated
@ -687,71 +685,71 @@ void MenuItemSprite::updateImagesVisibility()
MenuItemImage* MenuItemImage::create() MenuItemImage* MenuItemImage::create()
{ {
MenuItemImage *pRet = new MenuItemImage(); MenuItemImage *ret = new MenuItemImage();
if (pRet && pRet->init()) if (ret && ret->init())
{ {
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
return NULL; return NULL;
} }
bool MenuItemImage::init(void) bool MenuItemImage::init(void)
{ {
return initWithNormalImage(NULL, NULL, NULL, (const ccMenuCallback&)nullptr); return initWithNormalImage("", "", "", (const ccMenuCallback&)nullptr);
} }
MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage) MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage)
{ {
return MenuItemImage::create(normalImage, selectedImage, NULL, (const ccMenuCallback&)nullptr); return MenuItemImage::create(normalImage, selectedImage, "", (const ccMenuCallback&)nullptr);
} }
// XXX deprecated // XXX deprecated
MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage, Object* target, SEL_MenuHandler selector) MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage, Object* target, SEL_MenuHandler selector)
{ {
return MenuItemImage::create(normalImage, selectedImage, NULL, target, selector); return MenuItemImage::create(normalImage, selectedImage, "", target, selector);
} }
MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage, const ccMenuCallback& callback) MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage, const ccMenuCallback& callback)
{ {
return MenuItemImage::create(normalImage, selectedImage, NULL, callback); return MenuItemImage::create(normalImage, selectedImage, "", callback);
} }
// XXX deprecated // XXX deprecated
MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage, const char *disabledImage, Object* target, SEL_MenuHandler selector) MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage, const char *disabledImage, Object* target, SEL_MenuHandler selector)
{ {
MenuItemImage *pRet = new MenuItemImage(); MenuItemImage *ret = new MenuItemImage();
if (pRet && pRet->initWithNormalImage(normalImage, selectedImage, disabledImage, target, selector)) if (ret && ret->initWithNormalImage(normalImage, selectedImage, disabledImage, target, selector))
{ {
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
return NULL; return NULL;
} }
MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage, const char *disabledImage, const ccMenuCallback& callback) MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage, const ccMenuCallback& callback)
{ {
MenuItemImage *pRet = new MenuItemImage(); MenuItemImage *ret = new MenuItemImage();
if (pRet && pRet->initWithNormalImage(normalImage, selectedImage, disabledImage, callback)) if (ret && ret->initWithNormalImage(normalImage, selectedImage, disabledImage, callback))
{ {
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
return NULL; return NULL;
} }
MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage, const char *disabledImage) MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage)
{ {
MenuItemImage *pRet = new MenuItemImage(); MenuItemImage *ret = new MenuItemImage();
if (pRet && pRet->initWithNormalImage(normalImage, selectedImage, disabledImage, (const ccMenuCallback&)nullptr)) if (ret && ret->initWithNormalImage(normalImage, selectedImage, disabledImage, (const ccMenuCallback&)nullptr))
{ {
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
return NULL; return NULL;
} }
@ -762,23 +760,23 @@ bool MenuItemImage::initWithNormalImage(const char *normalImage, const char *sel
CC_SAFE_RETAIN(_target); CC_SAFE_RETAIN(_target);
return initWithNormalImage(normalImage, selectedImage, disabledImage, std::bind(selector,target, std::placeholders::_1) ); return initWithNormalImage(normalImage, selectedImage, disabledImage, std::bind(selector,target, std::placeholders::_1) );
} }
bool MenuItemImage::initWithNormalImage(const char *normalImage, const char *selectedImage, const char *disabledImage, const ccMenuCallback& callback) bool MenuItemImage::initWithNormalImage(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage, const ccMenuCallback& callback)
{ {
Node *normalSprite = NULL; Node *normalSprite = NULL;
Node *selectedSprite = NULL; Node *selectedSprite = NULL;
Node *disabledSprite = NULL; Node *disabledSprite = NULL;
if (normalImage) if (normalImage.size() >0)
{ {
normalSprite = Sprite::create(normalImage); normalSprite = Sprite::create(normalImage);
} }
if (selectedImage) if (selectedImage.size() >0)
{ {
selectedSprite = Sprite::create(selectedImage); selectedSprite = Sprite::create(selectedImage);
} }
if(disabledImage) if(disabledImage.size() >0)
{ {
disabledSprite = Sprite::create(disabledImage); disabledSprite = Sprite::create(disabledImage);
} }
@ -810,38 +808,38 @@ void MenuItemImage::setDisabledSpriteFrame(SpriteFrame * frame)
// XXX: deprecated // XXX: deprecated
MenuItemToggle * MenuItemToggle::createWithTarget(Object* target, SEL_MenuHandler selector, Array* menuItems) MenuItemToggle * MenuItemToggle::createWithTarget(Object* target, SEL_MenuHandler selector, Array* menuItems)
{ {
MenuItemToggle *pRet = new MenuItemToggle(); MenuItemToggle *ret = new MenuItemToggle();
pRet->MenuItem::initWithTarget(target, selector); ret->MenuItem::initWithTarget(target, selector);
pRet->_subItems = Array::create(); ret->_subItems = Array::create();
pRet->_subItems->retain(); ret->_subItems->retain();
for (int z=0; z < menuItems->count(); z++) for (int z=0; z < menuItems->count(); z++)
{ {
MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z); MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z);
pRet->_subItems->addObject(menuItem); ret->_subItems->addObject(menuItem);
} }
pRet->_selectedIndex = UINT_MAX; ret->_selectedIndex = UINT_MAX;
pRet->setSelectedIndex(0); ret->setSelectedIndex(0);
return pRet; return ret;
} }
MenuItemToggle * MenuItemToggle::createWithCallback(const ccMenuCallback &callback, Array* menuItems) MenuItemToggle * MenuItemToggle::createWithCallback(const ccMenuCallback &callback, Array* menuItems)
{ {
MenuItemToggle *pRet = new MenuItemToggle(); MenuItemToggle *ret = new MenuItemToggle();
pRet->MenuItem::initWithCallback(callback); ret->MenuItem::initWithCallback(callback);
pRet->_subItems = Array::create(); ret->_subItems = Array::create();
pRet->_subItems->retain(); ret->_subItems->retain();
for (int z=0; z < menuItems->count(); z++) for (int z=0; z < menuItems->count(); z++)
{ {
MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z); MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z);
pRet->_subItems->addObject(menuItem); ret->_subItems->addObject(menuItem);
} }
pRet->_selectedIndex = UINT_MAX; ret->_selectedIndex = UINT_MAX;
pRet->setSelectedIndex(0); ret->setSelectedIndex(0);
return pRet; return ret;
} }
// XXX: deprecated // XXX: deprecated
@ -849,30 +847,30 @@ MenuItemToggle * MenuItemToggle::createWithTarget(Object* target, SEL_MenuHandle
{ {
va_list args; va_list args;
va_start(args, item); va_start(args, item);
MenuItemToggle *pRet = new MenuItemToggle(); MenuItemToggle *ret = new MenuItemToggle();
pRet->initWithTarget(target, selector, item, args); ret->initWithTarget(target, selector, item, args);
pRet->autorelease(); ret->autorelease();
va_end(args); va_end(args);
return pRet; return ret;
} }
MenuItemToggle * MenuItemToggle::createWithCallback(const ccMenuCallback &callback, MenuItem* item, ...) MenuItemToggle * MenuItemToggle::createWithCallback(const ccMenuCallback &callback, MenuItem* item, ...)
{ {
va_list args; va_list args;
va_start(args, item); va_start(args, item);
MenuItemToggle *pRet = new MenuItemToggle(); MenuItemToggle *ret = new MenuItemToggle();
pRet->initWithCallback(callback, item, args); ret->initWithCallback(callback, item, args);
pRet->autorelease(); ret->autorelease();
va_end(args); va_end(args);
return pRet; return ret;
} }
MenuItemToggle * MenuItemToggle::create() MenuItemToggle * MenuItemToggle::create()
{ {
MenuItemToggle *pRet = new MenuItemToggle(); MenuItemToggle *ret = new MenuItemToggle();
pRet->initWithItem(NULL); ret->initWithItem(NULL);
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
// XXX: deprecated // XXX: deprecated
@ -903,10 +901,10 @@ bool MenuItemToggle::initWithCallback(const ccMenuCallback &callback, MenuItem *
MenuItemToggle* MenuItemToggle::create(MenuItem *item) MenuItemToggle* MenuItemToggle::create(MenuItem *item)
{ {
MenuItemToggle *pRet = new MenuItemToggle(); MenuItemToggle *ret = new MenuItemToggle();
pRet->initWithItem(item); ret->initWithItem(item);
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
bool MenuItemToggle::initWithItem(MenuItem *item) bool MenuItemToggle::initWithItem(MenuItem *item)

View File

@ -166,7 +166,7 @@ public:
CC_DEPRECATED_ATTRIBUTE bool initWithLabel(Node* label, Object* target, SEL_MenuHandler selector); CC_DEPRECATED_ATTRIBUTE bool initWithLabel(Node* label, Object* target, SEL_MenuHandler selector);
/** sets a new string to the inner label */ /** sets a new string to the inner label */
void setString(const char * label); void setString(const std::string& label);
/** Gets the color that will be used to disable the item */ /** Gets the color that will be used to disable the item */
inline const Color3B& getDisabledColor() const { return _disabledColor; }; inline const Color3B& getDisabledColor() const { return _disabledColor; };
@ -204,11 +204,11 @@ class CC_DLL MenuItemAtlasFont : public MenuItemLabel
{ {
public: public:
/** creates a menu item from a string and atlas with a target/selector */ /** creates a menu item from a string and atlas with a target/selector */
static MenuItemAtlasFont* create(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap); static MenuItemAtlasFont* create(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap);
/** creates a menu item from a string and atlas. Use it with MenuItemToggle */ /** creates a menu item from a string and atlas. Use it with MenuItemToggle */
CC_DEPRECATED_ATTRIBUTE static MenuItemAtlasFont* create(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector); CC_DEPRECATED_ATTRIBUTE static MenuItemAtlasFont* create(const char* value, const char* charMapFile, long itemWidth, long itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector);
/** creates a menu item from a string and atlas. Use it with MenuItemToggle */ /** creates a menu item from a string and atlas. Use it with MenuItemToggle */
static MenuItemAtlasFont* create(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback); static MenuItemAtlasFont* create(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap, const ccMenuCallback& callback);
/** /**
* @js ctor * @js ctor
*/ */
@ -220,9 +220,9 @@ public:
virtual ~MenuItemAtlasFont(){} virtual ~MenuItemAtlasFont(){}
/** initializes a menu item from a string and atlas with a target/selector */ /** initializes a menu item from a string and atlas with a target/selector */
CC_DEPRECATED_ATTRIBUTE bool initWithString(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector); CC_DEPRECATED_ATTRIBUTE bool initWithString(const char *value, const char *charMapFile, long itemWidth, long itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector);
/** initializes a menu item from a string and atlas with a target/selector */ /** initializes a menu item from a string and atlas with a target/selector */
bool initWithString(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback); bool initWithString(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap, const ccMenuCallback& callback);
}; };
@ -233,11 +233,11 @@ class CC_DLL MenuItemFont : public MenuItemLabel
{ {
public: public:
/** creates a menu item from a string without target/selector. To be used with MenuItemToggle */ /** creates a menu item from a string without target/selector. To be used with MenuItemToggle */
static MenuItemFont * create(const char *value); static MenuItemFont * create(const std::string& value);
/** creates a menu item from a string with a target/selector */ /** creates a menu item from a string with a target/selector */
CC_DEPRECATED_ATTRIBUTE static MenuItemFont * create(const char *value, Object* target, SEL_MenuHandler selector); CC_DEPRECATED_ATTRIBUTE static MenuItemFont * create(const char *value, Object* target, SEL_MenuHandler selector);
/** creates a menu item from a string with a target/selector */ /** creates a menu item from a string with a target/selector */
static MenuItemFont * create(const char *value, const ccMenuCallback& callback); static MenuItemFont * create(const std::string& value, const ccMenuCallback& callback);
/** /**
* @js ctor * @js ctor
*/ */
@ -251,30 +251,30 @@ public:
/** initializes a menu item from a string with a target/selector */ /** initializes a menu item from a string with a target/selector */
CC_DEPRECATED_ATTRIBUTE bool initWithString(const char *value, Object* target, SEL_MenuHandler selector); CC_DEPRECATED_ATTRIBUTE bool initWithString(const char *value, Object* target, SEL_MenuHandler selector);
/** initializes a menu item from a string with a target/selector */ /** initializes a menu item from a string with a target/selector */
bool initWithString(const char *value, const ccMenuCallback& callback); bool initWithString(const std::string& value, const ccMenuCallback& callback);
/** set default font size */ /** set default font size */
static void setFontSize(unsigned int s); static void setFontSize(long size);
/** get default font size */ /** get default font size */
static unsigned int getFontSize(); static long getFontSize();
CC_DEPRECATED_ATTRIBUTE static unsigned int fontSize() { return MenuItemFont::getFontSize(); }; CC_DEPRECATED_ATTRIBUTE static unsigned int fontSize() { return MenuItemFont::getFontSize(); };
/** set the default font name */ /** set the default font name */
static void setFontName(const char *name); static void setFontName(const std::string& name);
/** get the default font name */ /** get the default font name */
static const char *getFontName(); static const std::string& getFontName();
CC_DEPRECATED_ATTRIBUTE static const char *fontName() { return MenuItemFont::getFontName(); }; CC_DEPRECATED_ATTRIBUTE static const std::string& fontName() { return MenuItemFont::getFontName(); };
/** set font size /** set font size
* c++ can not overload static and non-static member functions with the same parameter types * c++ can not overload static and non-static member functions with the same parameter types
* so change the name to setFontSizeObj * so change the name to setFontSizeObj
* @js setFontSize * @js setFontSize
*/ */
void setFontSizeObj(unsigned int s); void setFontSizeObj(long size);
/** get font size /** get font size
* @js getFontSize * @js getFontSize
*/ */
unsigned int getFontSizeObj() const; long getFontSizeObj() const;
CC_DEPRECATED_ATTRIBUTE unsigned int fontSizeObj() const { return getFontSizeObj(); }; CC_DEPRECATED_ATTRIBUTE unsigned int fontSizeObj() const { return getFontSizeObj(); };
/** set the font name /** set the font name
@ -282,20 +282,20 @@ public:
* so change the name to setFontNameObj * so change the name to setFontNameObj
* @js setFontName * @js setFontName
*/ */
void setFontNameObj(const char* name); void setFontNameObj(const std::string& name);
/** returns the name of the Font /** returns the name of the Font
* @js getFontNameObj * @js getFontNameObj
*/ */
const char* getFontNameObj() const; const std::string& getFontNameObj() const;
/** deprecated Use getFontNameObj() instead */ /** deprecated Use getFontNameObj() instead */
CC_DEPRECATED_ATTRIBUTE const char* fontNameObj() const { return getFontNameObj(); } CC_DEPRECATED_ATTRIBUTE const std::string& fontNameObj() const { return getFontNameObj(); }
protected: protected:
void recreateLabel(); void recreateLabel();
unsigned int _fontSize; long _fontSize;
std::string _fontName; std::string _fontName;
}; };
@ -384,18 +384,18 @@ public:
/** Creates an MenuItemImage. */ /** Creates an MenuItemImage. */
static MenuItemImage* create(); static MenuItemImage* create();
/** creates a menu item with a normal and selected image*/ /** creates a menu item with a normal and selected image*/
static MenuItemImage* create(const char *normalImage, const char *selectedImage); static MenuItemImage* create(const std::string& normalImage, const std::string& selectedImage);
/** creates a menu item with a normal,selected and disabled image*/ /** creates a menu item with a normal,selected and disabled image*/
static MenuItemImage* create(const char *normalImage, const char *selectedImage, const char *disabledImage); static MenuItemImage* create(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage);
/** creates a menu item with a normal and selected image with target/selector */ /** creates a menu item with a normal and selected image with target/selector */
CC_DEPRECATED_ATTRIBUTE static MenuItemImage* create(const char *normalImage, const char *selectedImage, Object* target, SEL_MenuHandler selector); CC_DEPRECATED_ATTRIBUTE static MenuItemImage* create(const char *normalImage, const char *selectedImage, Object* target, SEL_MenuHandler selector);
/** creates a menu item with a normal and selected image with a callable object */ /** creates a menu item with a normal and selected image with a callable object */
static MenuItemImage* create(const char *normalImage, const char *selectedImage, const ccMenuCallback& callback); static MenuItemImage* create(const std::string&normalImage, const std::string&selectedImage, const ccMenuCallback& callback);
/** creates a menu item with a normal,selected and disabled image with target/selector */ /** creates a menu item with a normal,selected and disabled image with target/selector */
CC_DEPRECATED_ATTRIBUTE static MenuItemImage* create(const char *normalImage, const char *selectedImage, const char *disabledImage, Object* target, SEL_MenuHandler selector); CC_DEPRECATED_ATTRIBUTE static MenuItemImage* create(const char *normalImage, const char *selectedImage, const char *disabledImage, Object* target, SEL_MenuHandler selector);
/** creates a menu item with a normal,selected and disabled image with a callable object */ /** creates a menu item with a normal,selected and disabled image with a callable object */
static MenuItemImage* create(const char *normalImage, const char *selectedImage, const char *disabledImage, const ccMenuCallback& callback); static MenuItemImage* create(const std::string&normalImage, const std::string&selectedImage, const std::string&disabledImage, const ccMenuCallback& callback);
/** /**
* @js ctor * @js ctor
*/ */
@ -410,7 +410,7 @@ public:
/** initializes a menu item with a normal, selected and disabled image with target/selector */ /** initializes a menu item with a normal, selected and disabled image with target/selector */
CC_DEPRECATED_ATTRIBUTE bool initWithNormalImage(const char *normalImage, const char *selectedImage, const char *disabledImage, Object* target, SEL_MenuHandler selector); CC_DEPRECATED_ATTRIBUTE bool initWithNormalImage(const char *normalImage, const char *selectedImage, const char *disabledImage, Object* target, SEL_MenuHandler selector);
/** initializes a menu item with a normal, selected and disabled image with a callable object */ /** initializes a menu item with a normal, selected and disabled image with a callable object */
bool initWithNormalImage(const char *normalImage, const char *selectedImage, const char *disabledImage, const ccMenuCallback& callback); bool initWithNormalImage(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage, const ccMenuCallback& callback);
/** sets the sprite frame for the normal image */ /** sets the sprite frame for the normal image */
void setNormalSpriteFrame(SpriteFrame* frame); void setNormalSpriteFrame(SpriteFrame* frame);

View File

@ -28,7 +28,7 @@ THE SOFTWARE.
#include "CCGLProgram.h" #include "CCGLProgram.h"
#include "CCShaderCache.h" #include "CCShaderCache.h"
#include "ccMacros.h" #include "ccMacros.h"
#include "CCDirector.h"
#include "CCVertex.h" #include "CCVertex.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -93,7 +93,7 @@ bool MotionStreak::initWithFade(float fade, float minSeg, float stroke, const Co
{ {
CCASSERT(path != NULL, "Invalid filename"); CCASSERT(path != NULL, "Invalid filename");
Texture2D *texture = TextureCache::getInstance()->addImage(path); Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(path);
return initWithFade(fade, minSeg, stroke, color, texture); return initWithFade(fade, minSeg, stroke, color, texture);
} }

View File

@ -43,6 +43,7 @@ THE SOFTWARE.
#include "CCEventDispatcher.h" #include "CCEventDispatcher.h"
#include "CCEvent.h" #include "CCEvent.h"
#include "CCEventTouch.h" #include "CCEventTouch.h"
#include "CCScene.h"
#ifdef CC_USE_PHYSICS #ifdef CC_USE_PHYSICS
#include "CCPhysicsBody.h" #include "CCPhysicsBody.h"
@ -401,7 +402,7 @@ void Node::setPositionY(float y)
setPosition(Point(_position.x, y)); setPosition(Point(_position.x, y));
} }
unsigned int Node::getChildrenCount() const long Node::getChildrenCount() const
{ {
return _children ? _children->count() : 0; return _children ? _children->count() : 0;
} }
@ -629,6 +630,17 @@ void Node::addChild(Node *child, int zOrder, int tag)
} }
this->insertChild(child, zOrder); this->insertChild(child, zOrder);
#ifdef CC_USE_PHYSICS
for (Node* node = this->getParent(); node != nullptr; node = node->getParent())
{
if (dynamic_cast<Scene*>(node) != nullptr)
{
(dynamic_cast<Scene*>(node))->addChildToPhysicsWorld(child);
break;
}
}
#endif
child->_tag = tag; child->_tag = tag;
@ -682,7 +694,7 @@ void Node::removeChild(Node* child, bool cleanup /* = true */)
return; return;
} }
int index = _children->getIndexOfObject(child); long index = _children->getIndexOfObject(child);
if( index != CC_INVALID_INDEX ) if( index != CC_INVALID_INDEX )
this->detachChild( child, index, cleanup ); this->detachChild( child, index, cleanup );
} }
@ -742,7 +754,7 @@ void Node::removeAllChildrenWithCleanup(bool cleanup)
} }
void Node::detachChild(Node *child, int childIndex, bool doCleanup) void Node::detachChild(Node *child, long childIndex, bool doCleanup)
{ {
// IMPORTANT: // IMPORTANT:
// -1st do onExit // -1st do onExit
@ -752,6 +764,14 @@ void Node::detachChild(Node *child, int childIndex, bool doCleanup)
child->onExitTransitionDidStart(); child->onExitTransitionDidStart();
child->onExit(); child->onExit();
} }
#ifdef CC_USE_PHYSICS
if (child->_physicsBody != nullptr)
{
child->_physicsBody->removeFromWorld();
}
#endif
// If you don't do cleanup, the child's actions will not get removed and the // If you don't do cleanup, the child's actions will not get removed and the
// its scheduledSelectors_ dict will not get released! // its scheduledSelectors_ dict will not get released!
@ -1369,10 +1389,12 @@ void Node::setPhysicsBody(PhysicsBody* body)
{ {
if (_physicsBody != nullptr) if (_physicsBody != nullptr)
{ {
_physicsBody->_node = nullptr;
_physicsBody->release(); _physicsBody->release();
} }
_physicsBody = body; _physicsBody = body;
_physicsBody->_node = this;
_physicsBody->retain(); _physicsBody->retain();
_physicsBody->setPosition(getPosition()); _physicsBody->setPosition(getPosition());
_physicsBody->setRotation(getRotation()); _physicsBody->setRotation(getRotation());

View File

@ -644,7 +644,7 @@ public:
* *
* @return The amount of children. * @return The amount of children.
*/ */
unsigned int getChildrenCount() const; long getChildrenCount() const;
/** /**
* Sets the parent node * Sets the parent node
@ -1421,7 +1421,7 @@ protected:
void insertChild(Node* child, int z); void insertChild(Node* child, int z);
/// Removes a child, call child->onExit(), do cleanup, remove it from children array. /// Removes a child, call child->onExit(), do cleanup, remove it from children array.
void detachChild(Node *child, int index, bool doCleanup); void detachChild(Node *child, long index, bool doCleanup);
/// Convert cocos2d coordinates to UI windows coordinate. /// Convert cocos2d coordinates to UI windows coordinate.
Point convertToWindowSpace(const Point& nodePoint) const; Point convertToWindowSpace(const Point& nodePoint) const;

View File

@ -111,7 +111,7 @@ bool ParticleBatchNode::initWithTexture(Texture2D *tex, unsigned int capacity)
*/ */
bool ParticleBatchNode::initWithFile(const char* fileImage, unsigned int capacity) bool ParticleBatchNode::initWithFile(const char* fileImage, unsigned int capacity)
{ {
Texture2D *tex = TextureCache::getInstance()->addImage(fileImage); Texture2D *tex = Director::getInstance()->getTextureCache()->addImage(fileImage);
return initWithTexture(tex, capacity); return initWithTexture(tex, capacity);
} }

View File

@ -42,7 +42,7 @@ static Texture2D* getDefaultTexture()
{ {
bool bRet = false; bool bRet = false;
const char* key = "/__firePngData"; const char* key = "/__firePngData";
texture = TextureCache::getInstance()->getTextureForKey(key); texture = Director::getInstance()->getTextureCache()->getTextureForKey(key);
CC_BREAK_IF(texture != NULL); CC_BREAK_IF(texture != NULL);
pImage = new Image(); pImage = new Image();
@ -50,7 +50,7 @@ static Texture2D* getDefaultTexture()
bRet = pImage->initWithImageData(__firePngData, sizeof(__firePngData)); bRet = pImage->initWithImageData(__firePngData, sizeof(__firePngData));
CC_BREAK_IF(!bRet); CC_BREAK_IF(!bRet);
texture = TextureCache::getInstance()->addImage(pImage, key); texture = Director::getInstance()->getTextureCache()->addImage(pImage, key);
} while (0); } while (0);
CC_SAFE_RELEASE(pImage); CC_SAFE_RELEASE(pImage);

View File

@ -136,7 +136,7 @@ ParticleSystem::ParticleSystem()
} }
// implementation ParticleSystem // implementation ParticleSystem
ParticleSystem * ParticleSystem::create(const char *plistFile) ParticleSystem * ParticleSystem::create(const std::string& plistFile)
{ {
ParticleSystem *pRet = new ParticleSystem(); ParticleSystem *pRet = new ParticleSystem();
if (pRet && pRet->initWithFile(plistFile)) if (pRet && pRet->initWithFile(plistFile))
@ -165,7 +165,7 @@ bool ParticleSystem::init()
return initWithTotalParticles(150); return initWithTotalParticles(150);
} }
bool ParticleSystem::initWithFile(const char *plistFile) bool ParticleSystem::initWithFile(const std::string& plistFile)
{ {
bool bRet = false; bool bRet = false;
_plistFile = FileUtils::getInstance()->fullPathForFilename(plistFile); _plistFile = FileUtils::getInstance()->fullPathForFilename(plistFile);
@ -195,7 +195,7 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary)
return initWithDictionary(dictionary, ""); return initWithDictionary(dictionary, "");
} }
bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const char *dirname) bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::string& dirname)
{ {
bool bRet = false; bool bRet = false;
unsigned char *buffer = NULL; unsigned char *buffer = NULL;
@ -353,17 +353,17 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const char *dirn
{ {
string textureDir = textureName.substr(0, rPos + 1); string textureDir = textureName.substr(0, rPos + 1);
if (dirname != NULL && textureDir != dirname) if (dirname.size()>0 && textureDir != dirname)
{ {
textureName = textureName.substr(rPos+1); textureName = textureName.substr(rPos+1);
textureName = string(dirname) + textureName; textureName = dirname + textureName;
} }
} }
else else
{ {
if (dirname != NULL) if (dirname.size()>0)
{ {
textureName = string(dirname) + textureName; textureName = dirname + textureName;
} }
} }
@ -374,7 +374,7 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const char *dirn
// set not pop-up message box when load image failed // set not pop-up message box when load image failed
bool bNotify = FileUtils::getInstance()->isPopupNotify(); bool bNotify = FileUtils::getInstance()->isPopupNotify();
FileUtils::getInstance()->setPopupNotify(false); FileUtils::getInstance()->setPopupNotify(false);
tex = TextureCache::getInstance()->addImage(textureName.c_str()); tex = Director::getInstance()->getTextureCache()->addImage(textureName.c_str());
// reset the value of UIImage notify // reset the value of UIImage notify
FileUtils::getInstance()->setPopupNotify(bNotify); FileUtils::getInstance()->setPopupNotify(bNotify);
} }
@ -388,7 +388,7 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const char *dirn
const char *textureData = dictionary->valueForKey("textureImageData")->getCString(); const char *textureData = dictionary->valueForKey("textureImageData")->getCString();
CCASSERT(textureData, ""); CCASSERT(textureData, "");
int dataLen = strlen(textureData); long dataLen = strlen(textureData);
if(dataLen != 0) if(dataLen != 0)
{ {
// if it fails, try to get it from the base64-gzipped data // if it fails, try to get it from the base64-gzipped data
@ -400,13 +400,13 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const char *dirn
CCASSERT( deflated != NULL, "CCParticleSystem: error ungzipping textureImageData"); CCASSERT( deflated != NULL, "CCParticleSystem: error ungzipping textureImageData");
CC_BREAK_IF(!deflated); CC_BREAK_IF(!deflated);
// For android, we should retain it in VolatileTexture::addImage which invoked in TextureCache::getInstance()->addUIImage() // For android, we should retain it in VolatileTexture::addImage which invoked in Director::getInstance()->getTextureCache()->addUIImage()
image = new Image(); image = new Image();
bool isOK = image->initWithImageData(deflated, deflatedLen); bool isOK = image->initWithImageData(deflated, deflatedLen);
CCASSERT(isOK, "CCParticleSystem: error init image with Data"); CCASSERT(isOK, "CCParticleSystem: error init image with Data");
CC_BREAK_IF(!isOK); CC_BREAK_IF(!isOK);
setTexture(TextureCache::getInstance()->addImage(image, textureName.c_str())); setTexture(Director::getInstance()->getTextureCache()->addImage(image, textureName.c_str()));
image->release(); image->release();
} }

View File

@ -167,7 +167,7 @@ public:
http://particledesigner.71squared.com/ http://particledesigner.71squared.com/
@since v2.0 @since v2.0
*/ */
static ParticleSystem * create(const char *plistFile); static ParticleSystem * create(const std::string& plistFile);
//! create a system with a fixed number of particles //! create a system with a fixed number of particles
static ParticleSystem* createWithTotalParticles(unsigned int numberOfParticles); static ParticleSystem* createWithTotalParticles(unsigned int numberOfParticles);
@ -188,7 +188,7 @@ public:
http://particledesigner.71squared.com/ http://particledesigner.71squared.com/
@since v0.99.3 @since v0.99.3
*/ */
bool initWithFile(const char *plistFile); bool initWithFile(const std::string& plistFile);
/** initializes a QuadParticleSystem from a Dictionary. /** initializes a QuadParticleSystem from a Dictionary.
@since v0.99.3 @since v0.99.3
@ -198,7 +198,7 @@ public:
/** initializes a particle system from a NSDictionary and the path from where to load the png /** initializes a particle system from a NSDictionary and the path from where to load the png
@since v2.1 @since v2.1
*/ */
bool initWithDictionary(Dictionary *dictionary, const char *dirname); bool initWithDictionary(Dictionary *dictionary, const std::string& dirname);
//! Initializes a system with a fixed number of particles //! Initializes a system with a fixed number of particles
virtual bool initWithTotalParticles(unsigned int numberOfParticles); virtual bool initWithTotalParticles(unsigned int numberOfParticles);

View File

@ -125,7 +125,7 @@ const char* ProfilingTimer::description() const
{ {
static char s_desciption[512] = {0}; static char s_desciption[512] = {0};
sprintf(s_desciption, "%s ::\tavg1: %dµ,\tavg2: %dµ,\tmin: %dµ,\tmax: %dµ,\ttotal: %.2fs,\tnr calls: %d", _nameStr.c_str(), _averageTime1, _averageTime2, minTime, maxTime, totalTime/1000000., numberOfCalls); sprintf(s_desciption, "%s ::\tavg1: %ldµ,\tavg2: %ldµ,\tmin: %ldµ,\tmax: %ldµ,\ttotal: %.2fs,\tnr calls: %ld", _nameStr.c_str(), _averageTime1, _averageTime2, minTime, maxTime, totalTime/1000000., numberOfCalls);
return s_desciption; return s_desciption;
} }
@ -166,7 +166,7 @@ void ProfilingEndTimingBlock(const char *timerName)
CCASSERT(timer, "CCProfilingTimer not found"); CCASSERT(timer, "CCProfilingTimer not found");
int duration = chrono::duration_cast<chrono::microseconds>(now - timer->_startTime).count(); long duration = static_cast<long>(chrono::duration_cast<chrono::microseconds>(now - timer->_startTime).count());
timer->totalTime += duration; timer->totalTime += duration;
timer->_averageTime1 = (timer->_averageTime1 + duration) / 2.0f; timer->_averageTime1 = (timer->_averageTime1 + duration) / 2.0f;

View File

@ -134,12 +134,12 @@ public:
std::string _nameStr; std::string _nameStr;
std::chrono::high_resolution_clock::time_point _startTime; std::chrono::high_resolution_clock::time_point _startTime;
int _averageTime1; long _averageTime1;
int _averageTime2; long _averageTime2;
int minTime; long minTime;
int maxTime; long maxTime;
long long totalTime; long totalTime;
int numberOfCalls; long numberOfCalls;
}; };
extern void ProfilingBeginTimingBlock(const char *timerName); extern void ProfilingBeginTimingBlock(const char *timerName);

View File

@ -229,7 +229,7 @@ public:
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual void setString(const char *label) = 0; virtual void setString(const std::string &label) = 0;
/** /**
* Returns the string that is currently being used in this label * Returns the string that is currently being used in this label
@ -238,7 +238,7 @@ public:
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual const char* getString() const = 0; virtual const std::string& getString() const = 0;
}; };
/** /**

View File

@ -102,11 +102,11 @@ void RenderTexture::listenToBackground(cocos2d::Object *obj)
if (_UITextureImage) if (_UITextureImage)
{ {
const Size& s = _texture->getContentSizeInPixels(); const Size& s = _texture->getContentSizeInPixels();
VolatileTexture::addDataTexture(_texture, _UITextureImage->getData(), s.width * s.height * 4, Texture2D::PixelFormat::RGBA8888, s); VolatileTextureMgr::addDataTexture(_texture, _UITextureImage->getData(), s.width * s.height * 4, Texture2D::PixelFormat::RGBA8888, s);
if ( _textureCopy ) if ( _textureCopy )
{ {
VolatileTexture::addDataTexture(_textureCopy, _UITextureImage->getData(), s.width * s.height * 4, Texture2D::PixelFormat::RGBA8888, s); VolatileTextureMgr::addDataTexture(_textureCopy, _UITextureImage->getData(), s.width * s.height * 4, Texture2D::PixelFormat::RGBA8888, s);
} }
} }
else else
@ -198,8 +198,8 @@ bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_oldFBO); glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_oldFBO);
// textures must be power of two squared // textures must be power of two squared
unsigned int powW = 0; long powW = 0;
unsigned int powH = 0; long powH = 0;
if (Configuration::getInstance()->supportsNPOT()) if (Configuration::getInstance()->supportsNPOT())
{ {
@ -212,7 +212,7 @@ bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat
powH = ccNextPOT(h); powH = ccNextPOT(h);
} }
int dataLen = (int)(powW * powH * 4); long dataLen = (long)(powW * powH * 4);
data = malloc(dataLen); data = malloc(dataLen);
CC_BREAK_IF(! data); CC_BREAK_IF(! data);

View File

@ -102,8 +102,7 @@ bool Scene::initWithPhysics()
Director * pDirector; Director * pDirector;
CC_BREAK_IF( ! (pDirector = Director::getInstance()) ); CC_BREAK_IF( ! (pDirector = Director::getInstance()) );
this->setContentSize(pDirector->getWinSize()); this->setContentSize(pDirector->getWinSize());
CC_BREAK_IF(! (_physicsWorld = PhysicsWorld::create())); CC_BREAK_IF(! (_physicsWorld = PhysicsWorld::create(*this)));
_physicsWorld->setScene(this);
this->scheduleUpdate(); this->scheduleUpdate();
// success // success
@ -134,37 +133,27 @@ void Scene::addChildToPhysicsWorld(Node* child)
if (_physicsWorld) if (_physicsWorld)
{ {
std::function<void(Object*)> addToPhysicsWorldFunc = nullptr; std::function<void(Object*)> addToPhysicsWorldFunc = nullptr;
addToPhysicsWorldFunc = [this, &addToPhysicsWorldFunc](Object* child) -> void addToPhysicsWorldFunc = [this, &addToPhysicsWorldFunc](Object* obj) -> void
{ {
if (dynamic_cast<SpriteBatchNode*>(child) != nullptr)
if (dynamic_cast<Node*>(obj) != nullptr)
{ {
Object* subChild = nullptr; Node* node = dynamic_cast<Node*>(obj);
CCARRAY_FOREACH((dynamic_cast<SpriteBatchNode*>(child))->getChildren(), subChild)
{
addToPhysicsWorldFunc(subChild);
}
}else if (dynamic_cast<Node*>(child) != nullptr)
{
Node* node = dynamic_cast<Node*>(child);
if (node->getPhysicsBody()) if (node->getPhysicsBody())
{ {
_physicsWorld->addBody(node->getPhysicsBody()); _physicsWorld->addBody(node->getPhysicsBody());
} }
Object* subChild = nullptr;
CCARRAY_FOREACH(node->getChildren(), subChild)
{
addToPhysicsWorldFunc(subChild);
}
} }
}; };
if(dynamic_cast<Layer*>(child) != nullptr) addToPhysicsWorldFunc(child);
{
Object* subChild = nullptr;
CCARRAY_FOREACH(child->getChildren(), subChild)
{
addToPhysicsWorldFunc(subChild);
}
}else
{
addToPhysicsWorldFunc(child);
}
} }
} }

View File

@ -68,18 +68,14 @@ public:
#ifdef CC_USE_PHYSICS #ifdef CC_USE_PHYSICS
public: public:
bool initWithPhysics(); bool initWithPhysics();
inline PhysicsWorld* getPhysicsWorld() { return _physicsWorld; }
virtual void addChild(Node* child) override; virtual void addChild(Node* child) override;
virtual void addChild(Node* child, int zOrder) override; virtual void addChild(Node* child, int zOrder) override;
virtual void addChild(Node* child, int zOrder, int tag) override; virtual void addChild(Node* child, int zOrder, int tag) override;
virtual void update(float delta) override;
/*
* Update method will be called automatically every frame if "scheduleUpdate" is called, and the node is "live"
*/
virtual void update(float delta) override;
inline PhysicsWorld* getPhysicsWorld() { return _physicsWorld; }
protected: protected:
virtual void addChildToPhysicsWorld(Node* child); virtual void addChildToPhysicsWorld(Node* child);
@ -87,7 +83,7 @@ protected:
PhysicsWorld* _physicsWorld; PhysicsWorld* _physicsWorld;
#endif // CC_USE_PHYSICS #endif // CC_USE_PHYSICS
friend class Layer; friend class Node;
friend class SpriteBatchNode; friend class SpriteBatchNode;
}; };

View File

@ -294,7 +294,7 @@ void Scheduler::scheduleSelector(SEL_SCHEDULE selector, Object *target, float in
CCASSERT(target, "Argument target must be non-NULL"); CCASSERT(target, "Argument target must be non-NULL");
tHashTimerEntry *element = NULL; tHashTimerEntry *element = NULL;
HASH_FIND_INT(_hashForTimers, &target, element); HASH_FIND_PTR(_hashForTimers, &target, element);
if (! element) if (! element)
{ {
@ -304,7 +304,7 @@ void Scheduler::scheduleSelector(SEL_SCHEDULE selector, Object *target, float in
{ {
target->retain(); target->retain();
} }
HASH_ADD_INT(_hashForTimers, target, element); HASH_ADD_PTR(_hashForTimers, target, element);
// Is this the 1st element ? Then set the pause level to all the selectors of this target // Is this the 1st element ? Then set the pause level to all the selectors of this target
element->paused = paused; element->paused = paused;
@ -352,7 +352,7 @@ void Scheduler::unscheduleSelector(SEL_SCHEDULE selector, Object *target)
//CCASSERT(selector); //CCASSERT(selector);
tHashTimerEntry *element = NULL; tHashTimerEntry *element = NULL;
HASH_FIND_INT(_hashForTimers, &target, element); HASH_FIND_PTR(_hashForTimers, &target, element);
if (element) if (element)
{ {
@ -448,7 +448,7 @@ void Scheduler::priorityIn(tListEntry **list, Object *target, int priority, bool
target->retain(); target->retain();
pHashElement->list = list; pHashElement->list = list;
pHashElement->entry = listElement; pHashElement->entry = listElement;
HASH_ADD_INT(_hashForUpdates, target, pHashElement); HASH_ADD_PTR(_hashForUpdates, target, pHashElement);
} }
void Scheduler::appendIn(_listEntry **list, Object *target, bool paused) void Scheduler::appendIn(_listEntry **list, Object *target, bool paused)
@ -467,14 +467,14 @@ void Scheduler::appendIn(_listEntry **list, Object *target, bool paused)
target->retain(); target->retain();
pHashElement->list = list; pHashElement->list = list;
pHashElement->entry = listElement; pHashElement->entry = listElement;
HASH_ADD_INT(_hashForUpdates, target, pHashElement); HASH_ADD_PTR(_hashForUpdates, target, pHashElement);
} }
void Scheduler::scheduleUpdateForTarget(Object *target, int priority, bool paused) void Scheduler::scheduleUpdateForTarget(Object *target, int priority, bool paused)
{ {
tHashUpdateEntry *pHashElement = NULL; tHashUpdateEntry *pHashElement = NULL;
HASH_FIND_INT(_hashForUpdates, &target, pHashElement); HASH_FIND_PTR(_hashForUpdates, &target, pHashElement);
if (pHashElement) if (pHashElement)
{ {
#if COCOS2D_DEBUG >= 1 #if COCOS2D_DEBUG >= 1
@ -509,7 +509,7 @@ bool Scheduler::isScheduledForTarget(SEL_SCHEDULE selector, Object *target)
CCASSERT(target, "Argument target must be non-NULL"); CCASSERT(target, "Argument target must be non-NULL");
tHashTimerEntry *element = NULL; tHashTimerEntry *element = NULL;
HASH_FIND_INT(_hashForTimers, &target, element); HASH_FIND_PTR(_hashForTimers, &target, element);
if (!element) if (!element)
{ {
@ -541,7 +541,7 @@ void Scheduler::removeUpdateFromHash(struct _listEntry *entry)
{ {
tHashUpdateEntry *element = NULL; tHashUpdateEntry *element = NULL;
HASH_FIND_INT(_hashForUpdates, &entry->target, element); HASH_FIND_PTR(_hashForUpdates, &entry->target, element);
if (element) if (element)
{ {
// list entry // list entry
@ -567,7 +567,7 @@ void Scheduler::unscheduleUpdateForTarget(const Object *target)
} }
tHashUpdateEntry *element = NULL; tHashUpdateEntry *element = NULL;
HASH_FIND_INT(_hashForUpdates, &target, element); HASH_FIND_PTR(_hashForUpdates, &target, element);
if (element) if (element)
{ {
if (_updateHashLocked) if (_updateHashLocked)
@ -601,31 +601,31 @@ void Scheduler::unscheduleAllWithMinPriority(int nMinPriority)
} }
// Updates selectors // Updates selectors
tListEntry *pEntry, *pTmp; tListEntry *entry, *tmp;
if(nMinPriority < 0) if(nMinPriority < 0)
{ {
DL_FOREACH_SAFE(_updatesNegList, pEntry, pTmp) DL_FOREACH_SAFE(_updatesNegList, entry, tmp)
{ {
if(pEntry->priority >= nMinPriority) if(entry->priority >= nMinPriority)
{ {
unscheduleUpdateForTarget(pEntry->target); unscheduleUpdateForTarget(entry->target);
} }
} }
} }
if(nMinPriority <= 0) if(nMinPriority <= 0)
{ {
DL_FOREACH_SAFE(_updates0List, pEntry, pTmp) DL_FOREACH_SAFE(_updates0List, entry, tmp)
{ {
unscheduleUpdateForTarget(pEntry->target); unscheduleUpdateForTarget(entry->target);
} }
} }
DL_FOREACH_SAFE(_updatesPosList, pEntry, pTmp) DL_FOREACH_SAFE(_updatesPosList, entry, tmp)
{ {
if(pEntry->priority >= nMinPriority) if(entry->priority >= nMinPriority)
{ {
unscheduleUpdateForTarget(pEntry->target); unscheduleUpdateForTarget(entry->target);
} }
} }
@ -645,7 +645,7 @@ void Scheduler::unscheduleAllForTarget(Object *target)
// Custom Selectors // Custom Selectors
tHashTimerEntry *element = NULL; tHashTimerEntry *element = NULL;
HASH_FIND_INT(_hashForTimers, &target, element); HASH_FIND_PTR(_hashForTimers, &target, element);
if (element) if (element)
{ {
@ -702,7 +702,7 @@ void Scheduler::resumeTarget(Object *target)
// custom selectors // custom selectors
tHashTimerEntry *element = NULL; tHashTimerEntry *element = NULL;
HASH_FIND_INT(_hashForTimers, &target, element); HASH_FIND_PTR(_hashForTimers, &target, element);
if (element) if (element)
{ {
element->paused = false; element->paused = false;
@ -710,7 +710,7 @@ void Scheduler::resumeTarget(Object *target)
// update selector // update selector
tHashUpdateEntry *elementUpdate = NULL; tHashUpdateEntry *elementUpdate = NULL;
HASH_FIND_INT(_hashForUpdates, &target, elementUpdate); HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate);
if (elementUpdate) if (elementUpdate)
{ {
CCASSERT(elementUpdate->entry != NULL, ""); CCASSERT(elementUpdate->entry != NULL, "");
@ -724,7 +724,7 @@ void Scheduler::pauseTarget(Object *target)
// custom selectors // custom selectors
tHashTimerEntry *element = NULL; tHashTimerEntry *element = NULL;
HASH_FIND_INT(_hashForTimers, &target, element); HASH_FIND_PTR(_hashForTimers, &target, element);
if (element) if (element)
{ {
element->paused = true; element->paused = true;
@ -732,7 +732,7 @@ void Scheduler::pauseTarget(Object *target)
// update selector // update selector
tHashUpdateEntry *elementUpdate = NULL; tHashUpdateEntry *elementUpdate = NULL;
HASH_FIND_INT(_hashForUpdates, &target, elementUpdate); HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate);
if (elementUpdate) if (elementUpdate)
{ {
CCASSERT(elementUpdate->entry != NULL, ""); CCASSERT(elementUpdate->entry != NULL, "");
@ -746,7 +746,7 @@ bool Scheduler::isTargetPaused(Object *target)
// Custom selectors // Custom selectors
tHashTimerEntry *element = NULL; tHashTimerEntry *element = NULL;
HASH_FIND_INT(_hashForTimers, &target, element); HASH_FIND_PTR(_hashForTimers, &target, element);
if( element ) if( element )
{ {
return element->paused; return element->paused;
@ -754,7 +754,7 @@ bool Scheduler::isTargetPaused(Object *target)
// We should check update selectors if target does not have custom selectors // We should check update selectors if target does not have custom selectors
tHashUpdateEntry *elementUpdate = NULL; tHashUpdateEntry *elementUpdate = NULL;
HASH_FIND_INT(_hashForUpdates, &target, elementUpdate); HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate);
if ( elementUpdate ) if ( elementUpdate )
{ {
return elementUpdate->entry->paused; return elementUpdate->entry->paused;
@ -836,32 +836,32 @@ void Scheduler::update(float dt)
} }
// Iterate over all the Updates' selectors // Iterate over all the Updates' selectors
tListEntry *pEntry, *pTmp; tListEntry *entry, *tmp;
// updates with priority < 0 // updates with priority < 0
DL_FOREACH_SAFE(_updatesNegList, pEntry, pTmp) DL_FOREACH_SAFE(_updatesNegList, entry, tmp)
{ {
if ((! pEntry->paused) && (! pEntry->markedForDeletion)) if ((! entry->paused) && (! entry->markedForDeletion))
{ {
pEntry->target->update(dt); entry->target->update(dt);
} }
} }
// updates with priority == 0 // updates with priority == 0
DL_FOREACH_SAFE(_updates0List, pEntry, pTmp) DL_FOREACH_SAFE(_updates0List, entry, tmp)
{ {
if ((! pEntry->paused) && (! pEntry->markedForDeletion)) if ((! entry->paused) && (! entry->markedForDeletion))
{ {
pEntry->target->update(dt); entry->target->update(dt);
} }
} }
// updates with priority > 0 // updates with priority > 0
DL_FOREACH_SAFE(_updatesPosList, pEntry, pTmp) DL_FOREACH_SAFE(_updatesPosList, entry, tmp)
{ {
if ((! pEntry->paused) && (! pEntry->markedForDeletion)) if ((! entry->paused) && (! entry->markedForDeletion))
{ {
pEntry->target->update(dt); entry->target->update(dt);
} }
} }
@ -909,43 +909,43 @@ void Scheduler::update(float dt)
{ {
for (int i = _scriptHandlerEntries->count() - 1; i >= 0; i--) for (int i = _scriptHandlerEntries->count() - 1; i >= 0; i--)
{ {
SchedulerScriptHandlerEntry* pEntry = static_cast<SchedulerScriptHandlerEntry*>(_scriptHandlerEntries->getObjectAtIndex(i)); SchedulerScriptHandlerEntry* eachEntry = static_cast<SchedulerScriptHandlerEntry*>(_scriptHandlerEntries->getObjectAtIndex(i));
if (pEntry->isMarkedForDeletion()) if (eachEntry->isMarkedForDeletion())
{ {
_scriptHandlerEntries->removeObjectAtIndex(i); _scriptHandlerEntries->removeObjectAtIndex(i);
} }
else if (!pEntry->isPaused()) else if (!eachEntry->isPaused())
{ {
pEntry->getTimer()->update(dt); eachEntry->getTimer()->update(dt);
} }
} }
} }
// delete all updates that are marked for deletion // delete all updates that are marked for deletion
// updates with priority < 0 // updates with priority < 0
DL_FOREACH_SAFE(_updatesNegList, pEntry, pTmp) DL_FOREACH_SAFE(_updatesNegList, entry, tmp)
{ {
if (pEntry->markedForDeletion) if (entry->markedForDeletion)
{ {
this->removeUpdateFromHash(pEntry); this->removeUpdateFromHash(entry);
} }
} }
// updates with priority == 0 // updates with priority == 0
DL_FOREACH_SAFE(_updates0List, pEntry, pTmp) DL_FOREACH_SAFE(_updates0List, entry, tmp)
{ {
if (pEntry->markedForDeletion) if (entry->markedForDeletion)
{ {
this->removeUpdateFromHash(pEntry); this->removeUpdateFromHash(entry);
} }
} }
// updates with priority > 0 // updates with priority > 0
DL_FOREACH_SAFE(_updatesPosList, pEntry, pTmp) DL_FOREACH_SAFE(_updatesPosList, entry, tmp)
{ {
if (pEntry->markedForDeletion) if (entry->markedForDeletion)
{ {
this->removeUpdateFromHash(pEntry); this->removeUpdateFromHash(entry);
} }
} }

View File

@ -82,7 +82,7 @@ Sprite* Sprite::createWithTexture(Texture2D *texture, const Rect& rect)
return NULL; return NULL;
} }
Sprite* Sprite::create(const char *filename) Sprite* Sprite::create(const std::string& filename)
{ {
Sprite *sprite = new Sprite(); Sprite *sprite = new Sprite();
if (sprite && sprite->initWithFile(filename)) if (sprite && sprite->initWithFile(filename))
@ -94,7 +94,7 @@ Sprite* Sprite::create(const char *filename)
return NULL; return NULL;
} }
Sprite* Sprite::create(const char *filename, const Rect& rect) Sprite* Sprite::create(const std::string& filename, const Rect& rect)
{ {
Sprite *sprite = new Sprite(); Sprite *sprite = new Sprite();
if (sprite && sprite->initWithFile(filename, rect)) if (sprite && sprite->initWithFile(filename, rect))
@ -118,13 +118,13 @@ Sprite* Sprite::createWithSpriteFrame(SpriteFrame *spriteFrame)
return NULL; return NULL;
} }
Sprite* Sprite::createWithSpriteFrameName(const char *spriteFrameName) Sprite* Sprite::createWithSpriteFrameName(const std::string& spriteFrameName)
{ {
SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName);
#if COCOS2D_DEBUG > 0 #if COCOS2D_DEBUG > 0
char msg[256] = {0}; char msg[256] = {0};
sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName); sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName.c_str());
CCASSERT(frame != NULL, msg); CCASSERT(frame != NULL, msg);
#endif #endif
@ -215,11 +215,11 @@ bool Sprite::initWithTexture(Texture2D *texture)
return initWithTexture(texture, rect); return initWithTexture(texture, rect);
} }
bool Sprite::initWithFile(const char *filename) bool Sprite::initWithFile(const std::string& filename)
{ {
CCASSERT(filename != NULL, "Invalid filename for sprite"); CCASSERT(filename.size()>0, "Invalid filename for sprite");
Texture2D *texture = TextureCache::getInstance()->addImage(filename); Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename);
if (texture) if (texture)
{ {
Rect rect = Rect::ZERO; Rect rect = Rect::ZERO;
@ -233,11 +233,11 @@ bool Sprite::initWithFile(const char *filename)
return false; return false;
} }
bool Sprite::initWithFile(const char *filename, const Rect& rect) bool Sprite::initWithFile(const std::string &filename, const Rect& rect)
{ {
CCASSERT(filename != NULL, ""); CCASSERT(filename.size()>0, "Invalid filename");
Texture2D *texture = TextureCache::getInstance()->addImage(filename); Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename);
if (texture) if (texture)
{ {
return initWithTexture(texture, rect); return initWithTexture(texture, rect);
@ -259,9 +259,9 @@ bool Sprite::initWithSpriteFrame(SpriteFrame *spriteFrame)
return bRet; return bRet;
} }
bool Sprite::initWithSpriteFrameName(const char *spriteFrameName) bool Sprite::initWithSpriteFrameName(const std::string& spriteFrameName)
{ {
CCASSERT(spriteFrameName != NULL, ""); CCASSERT(spriteFrameName.size() > 0, "Invalid spriteFrameName");
SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName);
return initWithSpriteFrame(frame); return initWithSpriteFrame(frame);
@ -284,7 +284,7 @@ Sprite* Sprite::initWithCGImage(CGImageRef pImage, const char *pszKey)
CCASSERT(pImage != NULL); CCASSERT(pImage != NULL);
// XXX: possible bug. See issue #349. New API should be added // XXX: possible bug. See issue #349. New API should be added
Texture2D *texture = TextureCache::getInstance()->addCGImage(pImage, pszKey); Texture2D *texture = Director::getInstance()->getTextureCache()->addCGImage(pImage, pszKey);
const Size& size = texture->getContentSize(); const Size& size = texture->getContentSize();
Rect rect = Rect(0 ,0, size.width, size.height); Rect rect = Rect(0 ,0, size.width, size.height);
@ -840,6 +840,12 @@ void Sprite::setScale(float fScale)
SET_DIRTY_RECURSIVELY(); SET_DIRTY_RECURSIVELY();
} }
void Sprite::setScale(float scaleX, float scaleY)
{
Node::setScale(scaleX, scaleY);
SET_DIRTY_RECURSIVELY();
}
void Sprite::setVertexZ(float fVertexZ) void Sprite::setVertexZ(float fVertexZ)
{ {
Node::setVertexZ(fVertexZ); Node::setVertexZ(fVertexZ);
@ -992,9 +998,9 @@ void Sprite::setDisplayFrame(SpriteFrame *pNewFrame)
setTextureRect(pNewFrame->getRect(), _rectRotated, pNewFrame->getOriginalSize()); setTextureRect(pNewFrame->getRect(), _rectRotated, pNewFrame->getOriginalSize());
} }
void Sprite::setDisplayFrameWithAnimationName(const char *animationName, int frameIndex) void Sprite::setDisplayFrameWithAnimationName(const std::string& animationName, int frameIndex)
{ {
CCASSERT(animationName, "CCSprite#setDisplayFrameWithAnimationName. animationName must not be NULL"); CCASSERT(animationName.size()>0, "CCSprite#setDisplayFrameWithAnimationName. animationName must not be NULL");
Animation *a = AnimationCache::getInstance()->getAnimation(animationName); Animation *a = AnimationCache::getInstance()->getAnimation(animationName);
@ -1107,7 +1113,7 @@ void Sprite::setTexture(Texture2D *texture)
if (NULL == texture) if (NULL == texture)
{ {
// Gets the texture by key firstly. // Gets the texture by key firstly.
texture = TextureCache::getInstance()->getTextureForKey(CC_2x2_WHITE_IMAGE_KEY); texture = Director::getInstance()->getTextureCache()->getTextureForKey(CC_2x2_WHITE_IMAGE_KEY);
// If texture wasn't in cache, create it from RAW data. // If texture wasn't in cache, create it from RAW data.
if (NULL == texture) if (NULL == texture)
@ -1116,7 +1122,7 @@ void Sprite::setTexture(Texture2D *texture)
bool isOK = image->initWithRawData(cc_2x2_white_image, sizeof(cc_2x2_white_image), 2, 2, 8); bool isOK = image->initWithRawData(cc_2x2_white_image, sizeof(cc_2x2_white_image), 2, 2, 8);
CCASSERT(isOK, "The 2x2 empty texture was created unsuccessfully."); CCASSERT(isOK, "The 2x2 empty texture was created unsuccessfully.");
texture = TextureCache::getInstance()->addImage(image, CC_2x2_WHITE_IMAGE_KEY); texture = Director::getInstance()->getTextureCache()->addImage(image, CC_2x2_WHITE_IMAGE_KEY);
CC_SAFE_RELEASE(image); CC_SAFE_RELEASE(image);
} }
} }

View File

@ -24,8 +24,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#ifndef __SPITE_NODE_CCSPRITE_H__ #ifndef __SPRITE_NODE_CCSPRITE_H__
#define __SPITE_NODE_CCSPRITE_H__ #define __SPRITE_NODE_CCSPRITE_H__
#include "CCNode.h" #include "CCNode.h"
#include "CCProtocols.h" #include "CCProtocols.h"
@ -54,7 +54,7 @@ struct transformValues_;
* @{ * @{
*/ */
/** /**
* Sprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_graphics) ) * Sprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_graphics) )
* *
* Sprite can be created with an image, or with a sub-rectangle of an image. * Sprite can be created with an image, or with a sub-rectangle of an image.
@ -88,14 +88,14 @@ public:
/// @{ /// @{
/// @name Creators /// @name Creators
/** /**
* Creates an empty sprite without texture. You can call setTexture method subsequently. * Creates an empty sprite without texture. You can call setTexture method subsequently.
* *
* @return An empty sprite object that is marked as autoreleased. * @return An empty sprite object that is marked as autoreleased.
*/ */
static Sprite* create(); static Sprite* create();
/** /**
* Creates a sprite with an image filename. * Creates a sprite with an image filename.
* *
@ -105,8 +105,8 @@ public:
* @param filename The string which indicates a path to image file, e.g., "scene1/monster.png". * @param filename The string which indicates a path to image file, e.g., "scene1/monster.png".
* @return A valid sprite object that is marked as autoreleased. * @return A valid sprite object that is marked as autoreleased.
*/ */
static Sprite* create(const char *filename); static Sprite* create(const std::string& filename);
/** /**
* Creates a sprite with an image filename and a rect. * Creates a sprite with an image filename and a rect.
* *
@ -114,8 +114,8 @@ public:
* @param rect Only the contents inside rect of filename's texture will be applied for this sprite. * @param rect Only the contents inside rect of filename's texture will be applied for this sprite.
* @return A valid sprite object that is marked as autoreleased. * @return A valid sprite object that is marked as autoreleased.
*/ */
static Sprite* create(const char *filename, const Rect& rect); static Sprite* create(const std::string& filename, const Rect& rect);
/** /**
* Creates a sprite with an exsiting texture contained in a Texture2D object * Creates a sprite with an exsiting texture contained in a Texture2D object
* After creation, the rect will be the size of the texture, and the offset will be (0,0). * After creation, the rect will be the size of the texture, and the offset will be (0,0).
@ -124,7 +124,7 @@ public:
* @return A valid sprite object that is marked as autoreleased. * @return A valid sprite object that is marked as autoreleased.
*/ */
static Sprite* createWithTexture(Texture2D *texture); static Sprite* createWithTexture(Texture2D *texture);
/** /**
* Creates a sprite with a texture and a rect. * Creates a sprite with a texture and a rect.
* *
@ -136,7 +136,7 @@ public:
* @return A valid sprite object that is marked as autoreleased. * @return A valid sprite object that is marked as autoreleased.
*/ */
static Sprite* createWithTexture(Texture2D *texture, const Rect& rect); static Sprite* createWithTexture(Texture2D *texture, const Rect& rect);
/** /**
* Creates a sprite with an sprite frame. * Creates a sprite with an sprite frame.
* *
@ -144,7 +144,7 @@ public:
* @return A valid sprite object that is marked as autoreleased. * @return A valid sprite object that is marked as autoreleased.
*/ */
static Sprite* createWithSpriteFrame(SpriteFrame *pSpriteFrame); static Sprite* createWithSpriteFrame(SpriteFrame *pSpriteFrame);
/** /**
* Creates a sprite with an sprite frame name. * Creates a sprite with an sprite frame name.
* *
@ -154,32 +154,32 @@ public:
* @param spriteFrameName A null terminated string which indicates the sprite frame name. * @param spriteFrameName A null terminated string which indicates the sprite frame name.
* @return A valid sprite object that is marked as autoreleased. * @return A valid sprite object that is marked as autoreleased.
*/ */
static Sprite* createWithSpriteFrameName(const char *spriteFrameName); static Sprite* createWithSpriteFrameName(const std::string& spriteFrameName);
/// @} end of creators group /// @} end of creators group
/// @{ /// @{
/// @name Initializers /// @name Initializers
/** /**
* Default constructor * Default constructor
* @js ctor * @js ctor
*/ */
Sprite(void); Sprite(void);
/** /**
* Default destructor * Default destructor
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual ~Sprite(void); virtual ~Sprite(void);
/** /**
* Initializes an empty sprite with nothing init. * Initializes an empty sprite with nothing init.
*/ */
virtual bool init(void); virtual bool init(void);
/** /**
* Initializes a sprite with a texture. * Initializes a sprite with a texture.
* *
@ -190,7 +190,7 @@ public:
* @return true if the sprite is initialized properly, false otherwise. * @return true if the sprite is initialized properly, false otherwise.
*/ */
virtual bool initWithTexture(Texture2D *texture); virtual bool initWithTexture(Texture2D *texture);
/** /**
* Initializes a sprite with a texture and a rect. * Initializes a sprite with a texture and a rect.
* *
@ -202,7 +202,7 @@ public:
* @return true if the sprite is initialized properly, false otherwise. * @return true if the sprite is initialized properly, false otherwise.
*/ */
virtual bool initWithTexture(Texture2D *texture, const Rect& rect); virtual bool initWithTexture(Texture2D *texture, const Rect& rect);
/** /**
* Initializes a sprite with a texture and a rect in points, optionally rotated. * Initializes a sprite with a texture and a rect in points, optionally rotated.
* *
@ -215,7 +215,7 @@ public:
* @return true if the sprite is initialized properly, false otherwise. * @return true if the sprite is initialized properly, false otherwise.
*/ */
virtual bool initWithTexture(Texture2D *texture, const Rect& rect, bool rotated); virtual bool initWithTexture(Texture2D *texture, const Rect& rect, bool rotated);
/** /**
* Initializes a sprite with an SpriteFrame. The texture and rect in SpriteFrame will be applied on this sprite * Initializes a sprite with an SpriteFrame. The texture and rect in SpriteFrame will be applied on this sprite
* *
@ -223,7 +223,7 @@ public:
* @return true if the sprite is initialized properly, false otherwise. * @return true if the sprite is initialized properly, false otherwise.
*/ */
virtual bool initWithSpriteFrame(SpriteFrame *pSpriteFrame); virtual bool initWithSpriteFrame(SpriteFrame *pSpriteFrame);
/** /**
* Initializes a sprite with an sprite frame name. * Initializes a sprite with an sprite frame name.
* *
@ -233,8 +233,8 @@ public:
* @param spriteFrameName A key string that can fected a volid SpriteFrame from SpriteFrameCache * @param spriteFrameName A key string that can fected a volid SpriteFrame from SpriteFrameCache
* @return true if the sprite is initialized properly, false otherwise. * @return true if the sprite is initialized properly, false otherwise.
*/ */
virtual bool initWithSpriteFrameName(const char *spriteFrameName); virtual bool initWithSpriteFrameName(const std::string& spriteFrameName);
/** /**
* Initializes a sprite with an image filename. * Initializes a sprite with an image filename.
* *
@ -247,8 +247,8 @@ public:
* @js init * @js init
* @lua init * @lua init
*/ */
virtual bool initWithFile(const char *filename); virtual bool initWithFile(const std::string& filename);
/** /**
* Initializes a sprite with an image filename, and a rect. * Initializes a sprite with an image filename, and a rect.
* *
@ -262,18 +262,18 @@ public:
* @js init * @js init
* @lua init * @lua init
*/ */
virtual bool initWithFile(const char *filename, const Rect& rect); virtual bool initWithFile(const std::string& filename, const Rect& rect);
/// @} end of initializers /// @} end of initializers
/// @{ /// @{
/// @name BatchNode methods /// @name BatchNode methods
/** /**
* Updates the quad according the rotation, position, scale values. * Updates the quad according the rotation, position, scale values.
*/ */
virtual void updateTransform(void); virtual void updateTransform(void);
/** /**
* Returns the batch node object if this sprite is rendered by SpriteBatchNode * Returns the batch node object if this sprite is rendered by SpriteBatchNode
* *
@ -292,26 +292,26 @@ public:
* @endcode * @endcode
*/ */
virtual void setBatchNode(SpriteBatchNode *spriteBatchNode); virtual void setBatchNode(SpriteBatchNode *spriteBatchNode);
/// @} end of BatchNode methods /// @} end of BatchNode methods
/// @{ /// @{
/// @name Texture methods /// @name Texture methods
/** /**
* Updates the texture rect of the Sprite in points. * Updates the texture rect of the Sprite in points.
* It will call setTextureRect(const Rect& rect, bool rotated, const Size& untrimmedSize) with \p rotated = false, and \p utrimmedSize = rect.size. * It will call setTextureRect(const Rect& rect, bool rotated, const Size& untrimmedSize) with \p rotated = false, and \p utrimmedSize = rect.size.
*/ */
virtual void setTextureRect(const Rect& rect); virtual void setTextureRect(const Rect& rect);
/** /**
* Sets the texture rect, rectRotated and untrimmed size of the Sprite in points. * Sets the texture rect, rectRotated and untrimmed size of the Sprite in points.
* It will update the texture coordinates and the vertex rectangle. * It will update the texture coordinates and the vertex rectangle.
*/ */
virtual void setTextureRect(const Rect& rect, bool rotated, const Size& untrimmedSize); virtual void setTextureRect(const Rect& rect, bool rotated, const Size& untrimmedSize);
/** /**
* Sets the vertex rect. * Sets the vertex rect.
* It will be called internally by setTextureRect. * It will be called internally by setTextureRect.
@ -319,34 +319,34 @@ public:
* Do not call it manually. Use setTextureRect instead. * Do not call it manually. Use setTextureRect instead.
*/ */
virtual void setVertexRect(const Rect& rect); virtual void setVertexRect(const Rect& rect);
/// @} end of texture methods
/// @} end of texture methods
/// @{ /// @{
/// @name Frames methods /// @name Frames methods
/** /**
* Sets a new display frame to the Sprite. * Sets a new display frame to the Sprite.
*/ */
virtual void setDisplayFrame(SpriteFrame *pNewFrame); virtual void setDisplayFrame(SpriteFrame *pNewFrame);
/** /**
* Returns whether or not a SpriteFrame is being displayed * Returns whether or not a SpriteFrame is being displayed
*/ */
virtual bool isFrameDisplayed(SpriteFrame *pFrame) const; virtual bool isFrameDisplayed(SpriteFrame *pFrame) const;
/** @deprecated Use getDisplayFrame() instead */ /** @deprecated Use getDisplayFrame() instead */
CC_DEPRECATED_ATTRIBUTE virtual SpriteFrame* displayFrame() { return getDisplayFrame(); }; CC_DEPRECATED_ATTRIBUTE virtual SpriteFrame* displayFrame() { return getDisplayFrame(); };
/** /**
* Returns the current displayed frame. * Returns the current displayed frame.
*/ */
virtual SpriteFrame* getDisplayFrame(); virtual SpriteFrame* getDisplayFrame();
/// @} End of frames methods /// @} End of frames methods
/// @{ /// @{
/// @name Animation methods /// @name Animation methods
@ -354,25 +354,25 @@ public:
* Changes the display frame with animation name and index. * Changes the display frame with animation name and index.
* The animation name will be get from the AnimationCache * The animation name will be get from the AnimationCache
*/ */
virtual void setDisplayFrameWithAnimationName(const char *animationName, int frameIndex); virtual void setDisplayFrameWithAnimationName(const std::string& animationName, int frameIndex);
/// @} /// @}
/// @{ /// @{
/// @name Sprite Properties' setter/getters /// @name Sprite Properties' setter/getters
/** /**
* Whether or not the Sprite needs to be updated in the Atlas. * Whether or not the Sprite needs to be updated in the Atlas.
* *
* @return true if the sprite needs to be updated in the Atlas, false otherwise. * @return true if the sprite needs to be updated in the Atlas, false otherwise.
*/ */
virtual bool isDirty(void) const { return _dirty; } virtual bool isDirty(void) const { return _dirty; }
/** /**
* Makes the Sprite to be updated in the Atlas. * Makes the Sprite to be updated in the Atlas.
*/ */
virtual void setDirty(bool bDirty) { _dirty = bDirty; } virtual void setDirty(bool bDirty) { _dirty = bDirty; }
/** /**
* Returns the quad (tex coords, vertex coords and color) information. * Returns the quad (tex coords, vertex coords and color) information.
* @js NA * @js NA
@ -380,24 +380,24 @@ public:
*/ */
inline V3F_C4B_T2F_Quad getQuad(void) const { return _quad; } inline V3F_C4B_T2F_Quad getQuad(void) const { return _quad; }
/** /**
* Returns whether or not the texture rectangle is rotated. * Returns whether or not the texture rectangle is rotated.
*/ */
inline bool isTextureRectRotated(void) const { return _rectRotated; } inline bool isTextureRectRotated(void) const { return _rectRotated; }
/** /**
* Returns the index used on the TextureAtlas. * Returns the index used on the TextureAtlas.
*/ */
inline int getAtlasIndex(void) const { return _atlasIndex; } inline int getAtlasIndex(void) const { return _atlasIndex; }
/** /**
* Sets the index used on the TextureAtlas. * Sets the index used on the TextureAtlas.
* @warning Don't modify this value unless you know what you are doing * @warning Don't modify this value unless you know what you are doing
*/ */
inline void setAtlasIndex(int atlasIndex) { _atlasIndex = atlasIndex; } inline void setAtlasIndex(int atlasIndex) { _atlasIndex = atlasIndex; }
/** /**
* Returns the rect of the Sprite in points * Returns the rect of the Sprite in points
*/ */
inline const Rect& getTextureRect(void) { return _rect; } inline const Rect& getTextureRect(void) { return _rect; }
@ -405,19 +405,19 @@ public:
* Gets the weak reference of the TextureAtlas when the sprite is rendered using via SpriteBatchNode * Gets the weak reference of the TextureAtlas when the sprite is rendered using via SpriteBatchNode
*/ */
inline TextureAtlas* getTextureAtlas(void) { return _textureAtlas; } inline TextureAtlas* getTextureAtlas(void) { return _textureAtlas; }
/** /**
* Sets the weak reference of the TextureAtlas when the sprite is rendered using via SpriteBatchNode * Sets the weak reference of the TextureAtlas when the sprite is rendered using via SpriteBatchNode
*/ */
inline void setTextureAtlas(TextureAtlas *pobTextureAtlas) { _textureAtlas = pobTextureAtlas; } inline void setTextureAtlas(TextureAtlas *pobTextureAtlas) { _textureAtlas = pobTextureAtlas; }
/** /**
* Gets the offset position of the sprite. Calculated automatically by editors like Zwoptex. * Gets the offset position of the sprite. Calculated automatically by editors like Zwoptex.
*/ */
inline const Point& getOffsetPosition(void) const { return _offsetPosition; } inline const Point& getOffsetPosition(void) const { return _offsetPosition; }
/** /**
* Returns the flag which indicates whether the sprite is flipped horizontally or not. * Returns the flag which indicates whether the sprite is flipped horizontally or not.
* *
* It only flips the texture of the sprite, and not the texture of the sprite's children. * It only flips the texture of the sprite, and not the texture of the sprite's children.
@ -425,48 +425,48 @@ public:
* If you want to flip the anchorPoint too, and/or to flip the children too use: * If you want to flip the anchorPoint too, and/or to flip the children too use:
* sprite->setScaleX(sprite->getScaleX() * -1); * sprite->setScaleX(sprite->getScaleX() * -1);
* *
* @return true if the sprite is flipped horizaontally, false otherwise. * @return true if the sprite is flipped horizontally, false otherwise.
*/ */
bool isFlippedX(void) const; bool isFlippedX(void) const;
/** /**
* Sets whether the sprite should be flipped horizontally or not. * Sets whether the sprite should be flipped horizontally or not.
* *
* @param bFlipX true if the sprite should be flipped horizaontally, false otherwise. * @param flippedX true if the sprite should be flipped horizontally, false otherwise.
*/ */
void setFlippedX(bool flippedX); void setFlippedX(bool flippedX);
/** @deprecated Use isFlippedX() instead /** @deprecated Use isFlippedX() instead
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
CC_DEPRECATED_ATTRIBUTE bool isFlipX() { return isFlippedX(); }; CC_DEPRECATED_ATTRIBUTE bool isFlipX() { return isFlippedX(); };
/** @deprecated Use setFlippedX() instead */ /** @deprecated Use setFlippedX() instead */
CC_DEPRECATED_ATTRIBUTE void setFlipX(bool flippedX) { setFlippedX(flippedX); }; CC_DEPRECATED_ATTRIBUTE void setFlipX(bool flippedX) { setFlippedX(flippedX); };
/** /**
* Return the flag which indicates whether the sprite is flipped vertically or not. * Return the flag which indicates whether the sprite is flipped vertically or not.
* *
* It only flips the texture of the sprite, and not the texture of the sprite's children. * It only flips the texture of the sprite, and not the texture of the sprite's children.
* Also, flipping the texture doesn't alter the anchorPoint. * Also, flipping the texture doesn't alter the anchorPoint.
* If you want to flip the anchorPoint too, and/or to flip the children too use: * If you want to flip the anchorPoint too, and/or to flip the children too use:
* sprite->setScaleY(sprite->getScaleY() * -1); * sprite->setScaleY(sprite->getScaleY() * -1);
* *
* @return true if the sprite is flipped vertically, flase otherwise. * @return true if the sprite is flipped vertically, false otherwise.
*/ */
bool isFlippedY(void) const; bool isFlippedY(void) const;
/** /**
* Sets whether the sprite should be flipped vertically or not. * Sets whether the sprite should be flipped vertically or not.
* *
* @param bFlipY true if the sprite should be flipped vertically, flase otherwise. * @param flippedY true if the sprite should be flipped vertically, false otherwise.
*/ */
void setFlippedY(bool flippedY); void setFlippedY(bool flippedY);
/// @} End of Sprite properties getter/setters /// @} End of Sprite properties getter/setters
/** @deprecated Use isFlippedY() instead */ /** @deprecated Use isFlippedY() instead */
CC_DEPRECATED_ATTRIBUTE bool isFlipY() { return isFlippedY(); }; CC_DEPRECATED_ATTRIBUTE bool isFlipY() { return isFlippedY(); };
/** @deprecated Use setFlippedY() instead */ /** @deprecated Use setFlippedY() instead */
CC_DEPRECATED_ATTRIBUTE void setFlipY(bool flippedY) { setFlippedY(flippedY); }; CC_DEPRECATED_ATTRIBUTE void setFlipY(bool flippedY) { setFlippedY(flippedY); };
// //
// Overrides // Overrides
@ -494,6 +494,7 @@ public:
/// @name Functions inherited from Node /// @name Functions inherited from Node
virtual void setScaleX(float scaleX) override; virtual void setScaleX(float scaleX) override;
virtual void setScaleY(float scaleY) override; virtual void setScaleY(float scaleY) override;
virtual void setScale(float scaleX, float scaleY) override;
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
@ -542,13 +543,13 @@ protected:
TextureAtlas* _textureAtlas; /// SpriteBatchNode texture atlas (weak reference) TextureAtlas* _textureAtlas; /// SpriteBatchNode texture atlas (weak reference)
int _atlasIndex; /// Absolute (real) Index on the SpriteSheet int _atlasIndex; /// Absolute (real) Index on the SpriteSheet
SpriteBatchNode* _batchNode; /// Used batch node (weak reference) SpriteBatchNode* _batchNode; /// Used batch node (weak reference)
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 _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
AffineTransform _transformToBatch; AffineTransform _transformToBatch;
// //
// Data used when the sprite is self-rendered // Data used when the sprite is self-rendered
// //
@ -574,8 +575,8 @@ protected:
bool _opacityModifyRGB; bool _opacityModifyRGB;
// image is flipped // image is flipped
bool _flippedX; /// Whether the sprite is flipped horizaontally or not. bool _flippedX; /// Whether the sprite is flipped horizontally or not
bool _flippedY; /// Whether the sprite is flipped vertically or not. bool _flippedY; /// Whether the sprite is flipped vertically or not
}; };
@ -584,4 +585,4 @@ protected:
NS_CC_END NS_CC_END
#endif // __SPITE_NODE_CCSPRITE_H__ #endif // __SPRITE_NODE_CCSPRITE_H__

View File

@ -64,7 +64,7 @@ SpriteBatchNode* SpriteBatchNode::createWithTexture(Texture2D* tex, int capacity
* creation with File Image * creation with File Image
*/ */
SpriteBatchNode* SpriteBatchNode::create(const char *fileImage, int capacity/* = DEFAULT_CAPACITY*/) SpriteBatchNode* SpriteBatchNode::create(const char *fileImage, long capacity/* = DEFAULT_CAPACITY*/)
{ {
SpriteBatchNode *batchNode = new SpriteBatchNode(); SpriteBatchNode *batchNode = new SpriteBatchNode();
batchNode->initWithFile(fileImage, capacity); batchNode->initWithFile(fileImage, capacity);
@ -76,7 +76,7 @@ SpriteBatchNode* SpriteBatchNode::create(const char *fileImage, int capacity/* =
/* /*
* init with Texture2D * init with Texture2D
*/ */
bool SpriteBatchNode::initWithTexture(Texture2D *tex, int capacity) bool SpriteBatchNode::initWithTexture(Texture2D *tex, long capacity)
{ {
CCASSERT(capacity>=0, "Capacity must be >= 0"); CCASSERT(capacity>=0, "Capacity must be >= 0");
@ -112,9 +112,9 @@ bool SpriteBatchNode::init()
/* /*
* init with FileImage * init with FileImage
*/ */
bool SpriteBatchNode::initWithFile(const char* fileImage, int capacity) bool SpriteBatchNode::initWithFile(const char* fileImage, long capacity)
{ {
Texture2D *texture2D = TextureCache::getInstance()->addImage(fileImage); Texture2D *texture2D = Director::getInstance()->getTextureCache()->addImage(fileImage);
return initWithTexture(texture2D, capacity); return initWithTexture(texture2D, capacity);
} }
@ -181,17 +181,6 @@ void SpriteBatchNode::addChild(Node *child, int zOrder, int tag)
Node::addChild(child, zOrder, tag); Node::addChild(child, zOrder, tag);
appendChild(sprite); appendChild(sprite);
if (this->getParent() &&
dynamic_cast<Layer*>(this->getParent()) != nullptr)
{
if (this->getParent()->getParent() &&
dynamic_cast<Scene*>(this->getParent()->getParent()))
{
dynamic_cast<Scene*>(this->getParent()->getParent())->addChildToPhysicsWorld(child);
}
}
} }
// override reorderChild // override reorderChild
@ -609,8 +598,8 @@ void SpriteBatchNode::removeSpriteFromAtlas(Sprite *sprite)
{ {
auto next = std::next(it); auto next = std::next(it);
std::for_each(next, _descendants.end(), [](Sprite *sprite) { std::for_each(next, _descendants.end(), [](Sprite *spr) {
sprite->setAtlasIndex( sprite->getAtlasIndex() - 1 ); spr->setAtlasIndex( spr->getAtlasIndex() - 1 );
}); });
_descendants.erase(it); _descendants.erase(it);

View File

@ -74,7 +74,7 @@ public:
The capacity will be increased in 33% in runtime if it run out of space. The capacity will be increased in 33% in runtime if it run out of space.
The file will be loaded using the TextureMgr. The file will be loaded using the TextureMgr.
*/ */
static SpriteBatchNode* create(const char* fileImage, int capacity = DEFAULT_CAPACITY); static SpriteBatchNode* create(const char* fileImage, long capacity = DEFAULT_CAPACITY);
/** /**
* @js ctor * @js ctor
*/ */
@ -88,14 +88,14 @@ public:
/** initializes a SpriteBatchNode with a texture2d and capacity of children. /** initializes a SpriteBatchNode with a texture2d and capacity of children.
The capacity will be increased in 33% in runtime if it run out of space. The capacity will be increased in 33% in runtime if it run out of space.
*/ */
bool initWithTexture(Texture2D *tex, int capacity); bool initWithTexture(Texture2D *tex, long capacity);
/** initializes a SpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and a capacity of children. /** initializes a SpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and a capacity of children.
The capacity will be increased in 33% in runtime if it run out of space. The capacity will be increased in 33% in runtime if it run out of space.
The file will be loaded using the TextureMgr. The file will be loaded using the TextureMgr.
* @js init * @js init
* @lua init * @lua init
*/ */
bool initWithFile(const char* fileImage, int capacity); bool initWithFile(const char* fileImage, long capacity);
bool init(); bool init();
/** returns the TextureAtlas object */ /** returns the TextureAtlas object */

View File

@ -31,61 +31,61 @@ NS_CC_BEGIN
// implementation of SpriteFrame // implementation of SpriteFrame
SpriteFrame* SpriteFrame::create(const char* filename, const Rect& rect) SpriteFrame* SpriteFrame::create(const std::string& filename, const Rect& rect)
{ {
SpriteFrame *pSpriteFrame = new SpriteFrame();; SpriteFrame *pSpriteFrame = new SpriteFrame();
pSpriteFrame->initWithTextureFilename(filename, rect); pSpriteFrame->initWithTextureFilename(filename, rect);
pSpriteFrame->autorelease(); pSpriteFrame->autorelease();
return pSpriteFrame; return pSpriteFrame;
} }
SpriteFrame* SpriteFrame::createWithTexture(Texture2D *pobTexture, const Rect& rect) SpriteFrame* SpriteFrame::createWithTexture(Texture2D *texture, const Rect& rect)
{ {
SpriteFrame *pSpriteFrame = new SpriteFrame();; SpriteFrame *pSpriteFrame = new SpriteFrame();
pSpriteFrame->initWithTexture(pobTexture, rect); pSpriteFrame->initWithTexture(texture, rect);
pSpriteFrame->autorelease(); pSpriteFrame->autorelease();
return pSpriteFrame; return pSpriteFrame;
} }
SpriteFrame* SpriteFrame::createWithTexture(Texture2D* pobTexture, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize) SpriteFrame* SpriteFrame::createWithTexture(Texture2D* texture, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize)
{ {
SpriteFrame *pSpriteFrame = new SpriteFrame();; SpriteFrame *pSpriteFrame = new SpriteFrame();
pSpriteFrame->initWithTexture(pobTexture, rect, rotated, offset, originalSize); pSpriteFrame->initWithTexture(texture, rect, rotated, offset, originalSize);
pSpriteFrame->autorelease(); pSpriteFrame->autorelease();
return pSpriteFrame; return pSpriteFrame;
} }
SpriteFrame* SpriteFrame::create(const char* filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize) SpriteFrame* SpriteFrame::create(const std::string& filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize)
{ {
SpriteFrame *pSpriteFrame = new SpriteFrame();; SpriteFrame *pSpriteFrame = new SpriteFrame();
pSpriteFrame->initWithTextureFilename(filename, rect, rotated, offset, originalSize); pSpriteFrame->initWithTextureFilename(filename, rect, rotated, offset, originalSize);
pSpriteFrame->autorelease(); pSpriteFrame->autorelease();
return pSpriteFrame; return pSpriteFrame;
} }
bool SpriteFrame::initWithTexture(Texture2D* pobTexture, const Rect& rect) bool SpriteFrame::initWithTexture(Texture2D* texture, const Rect& rect)
{ {
Rect rectInPixels = CC_RECT_POINTS_TO_PIXELS(rect); Rect rectInPixels = CC_RECT_POINTS_TO_PIXELS(rect);
return initWithTexture(pobTexture, rectInPixels, false, Point::ZERO, rectInPixels.size); return initWithTexture(texture, rectInPixels, false, Point::ZERO, rectInPixels.size);
} }
bool SpriteFrame::initWithTextureFilename(const char* filename, const Rect& rect) bool SpriteFrame::initWithTextureFilename(const std::string& filename, const Rect& rect)
{ {
Rect rectInPixels = CC_RECT_POINTS_TO_PIXELS( rect ); Rect rectInPixels = CC_RECT_POINTS_TO_PIXELS( rect );
return initWithTextureFilename(filename, rectInPixels, false, Point::ZERO, rectInPixels.size); return initWithTextureFilename(filename, rectInPixels, false, Point::ZERO, rectInPixels.size);
} }
bool SpriteFrame::initWithTexture(Texture2D* pobTexture, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize) bool SpriteFrame::initWithTexture(Texture2D* texture, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize)
{ {
_texture = pobTexture; _texture = texture;
if (pobTexture) if (texture)
{ {
pobTexture->retain(); texture->retain();
} }
_rectInPixels = rect; _rectInPixels = rect;
@ -99,7 +99,7 @@ bool SpriteFrame::initWithTexture(Texture2D* pobTexture, const Rect& rect, bool
return true; return true;
} }
bool SpriteFrame::initWithTextureFilename(const char* filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize) bool SpriteFrame::initWithTextureFilename(const std::string& filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize)
{ {
_texture = NULL; _texture = NULL;
_textureFilename = filename; _textureFilename = filename;
@ -180,7 +180,7 @@ Texture2D* SpriteFrame::getTexture(void)
} }
if( _textureFilename.length() > 0 ) { if( _textureFilename.length() > 0 ) {
return TextureCache::getInstance()->addImage(_textureFilename.c_str()); return Director::getInstance()->getTextureCache()->addImage(_textureFilename.c_str());
} }
// no texture or texture filename // no texture or texture filename
return NULL; return NULL;

View File

@ -58,12 +58,12 @@ public:
/** Create a SpriteFrame with a texture filename, rect in points. /** Create a SpriteFrame with a texture filename, rect in points.
It is assumed that the frame was not trimmed. It is assumed that the frame was not trimmed.
*/ */
static SpriteFrame* create(const char* filename, const Rect& rect); static SpriteFrame* create(const std::string& filename, const Rect& rect);
/** Create a SpriteFrame with a texture filename, rect, rotated, offset and originalSize in pixels. /** Create a SpriteFrame with a texture filename, rect, rotated, offset and originalSize in pixels.
The originalSize is the size in pixels of the frame before being trimmed. The originalSize is the size in pixels of the frame before being trimmed.
*/ */
static SpriteFrame* create(const char* filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize); static SpriteFrame* create(const std::string& filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize);
/** Create a SpriteFrame with a texture, rect in points. /** Create a SpriteFrame with a texture, rect in points.
It is assumed that the frame was not trimmed. It is assumed that the frame was not trimmed.
@ -88,7 +88,7 @@ public:
/** Initializes a SpriteFrame with a texture filename, rect in points; /** Initializes a SpriteFrame with a texture filename, rect in points;
It is assumed that the frame was not trimmed. It is assumed that the frame was not trimmed.
*/ */
bool initWithTextureFilename(const char* filename, const Rect& rect); bool initWithTextureFilename(const std::string& filename, const Rect& rect);
/** Initializes a SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels. /** Initializes a SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels.
The originalSize is the size in points of the frame before being trimmed. The originalSize is the size in points of the frame before being trimmed.
@ -100,7 +100,7 @@ public:
@since v1.1 @since v1.1
*/ */
bool initWithTextureFilename(const char* filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize); bool initWithTextureFilename(const std::string& filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize);
// attributes // attributes

View File

@ -37,6 +37,7 @@ THE SOFTWARE.
#include "CCString.h" #include "CCString.h"
#include "CCArray.h" #include "CCArray.h"
#include "CCDictionary.h" #include "CCDictionary.h"
#include "CCDirector.h"
#include <vector> #include <vector>
using namespace std; using namespace std;
@ -102,11 +103,11 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex
// check the format // check the format
CCASSERT(format >=0 && format <= 3, "format is not supported for SpriteFrameCache addSpriteFramesWithDictionary:textureFilename:"); CCASSERT(format >=0 && format <= 3, "format is not supported for SpriteFrameCache addSpriteFramesWithDictionary:textureFilename:");
DictElement* pElement = NULL; DictElement* element = NULL;
CCDICT_FOREACH(framesDict, pElement) CCDICT_FOREACH(framesDict, element)
{ {
Dictionary* frameDict = static_cast<Dictionary*>(pElement->getObject()); Dictionary* frameDict = static_cast<Dictionary*>(element->getObject());
std::string spriteFrameName = pElement->getStrKey(); std::string spriteFrameName = element->getStrKey();
SpriteFrame* spriteFrame = static_cast<SpriteFrame*>(_spriteFrames->objectForKey(spriteFrameName)); SpriteFrame* spriteFrame = static_cast<SpriteFrame*>(_spriteFrames->objectForKey(spriteFrameName));
if (spriteFrame) if (spriteFrame)
{ {
@ -203,7 +204,7 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex
} }
} }
void SpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist, Texture2D *pobTexture) void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist, Texture2D *pobTexture)
{ {
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(pszPlist); std::string fullPath = FileUtils::getInstance()->fullPathForFilename(pszPlist);
Dictionary *dict = Dictionary::createWithContentsOfFileThreadSafe(fullPath.c_str()); Dictionary *dict = Dictionary::createWithContentsOfFileThreadSafe(fullPath.c_str());
@ -212,10 +213,10 @@ void SpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist, Texture2D *
dict->release(); dict->release();
} }
void SpriteFrameCache::addSpriteFramesWithFile(const char* plist, const char* textureFileName) void SpriteFrameCache::addSpriteFramesWithFile(const std::string& plist, const std::string& textureFileName)
{ {
CCASSERT(textureFileName, "texture name should not be null"); CCASSERT(textureFileName.size()>0, "texture name should not be null");
Texture2D *texture = TextureCache::getInstance()->addImage(textureFileName); Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(textureFileName);
if (texture) if (texture)
{ {
@ -223,13 +224,13 @@ void SpriteFrameCache::addSpriteFramesWithFile(const char* plist, const char* te
} }
else else
{ {
CCLOG("cocos2d: SpriteFrameCache: couldn't load texture file. File not found %s", textureFileName); CCLOG("cocos2d: SpriteFrameCache: couldn't load texture file. File not found %s", textureFileName.c_str());
} }
} }
void SpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist) void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist)
{ {
CCASSERT(pszPlist, "plist filename should not be NULL"); CCASSERT(pszPlist.size()>0, "plist filename should not be NULL");
if (_loadedFileNames->find(pszPlist) == _loadedFileNames->end()) if (_loadedFileNames->find(pszPlist) == _loadedFileNames->end())
{ {
@ -265,7 +266,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist)
CCLOG("cocos2d: SpriteFrameCache: Trying to use file %s as texture", texturePath.c_str()); CCLOG("cocos2d: SpriteFrameCache: Trying to use file %s as texture", texturePath.c_str());
} }
Texture2D *texture = TextureCache::getInstance()->addImage(texturePath.c_str()); Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(texturePath.c_str());
if (texture) if (texture)
{ {
@ -280,7 +281,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist)
} }
} }
void SpriteFrameCache::addSpriteFrame(SpriteFrame *pobFrame, const char *pszFrameName) void SpriteFrameCache::addSpriteFrame(SpriteFrame *pobFrame, const std::string& pszFrameName)
{ {
_spriteFrames->setObject(pobFrame, pszFrameName); _spriteFrames->setObject(pobFrame, pszFrameName);
} }
@ -295,14 +296,14 @@ void SpriteFrameCache::removeSpriteFrames(void)
void SpriteFrameCache::removeUnusedSpriteFrames(void) void SpriteFrameCache::removeUnusedSpriteFrames(void)
{ {
bool bRemoved = false; bool bRemoved = false;
DictElement* pElement = NULL; DictElement* element = NULL;
CCDICT_FOREACH(_spriteFrames, pElement) CCDICT_FOREACH(_spriteFrames, element)
{ {
SpriteFrame* spriteFrame = static_cast<SpriteFrame*>(pElement->getObject()); SpriteFrame* spriteFrame = static_cast<SpriteFrame*>(element->getObject());
if( spriteFrame->retainCount() == 1 ) if( spriteFrame->retainCount() == 1 )
{ {
CCLOG("cocos2d: SpriteFrameCache: removing unused frame: %s", pElement->getStrKey()); CCLOG("cocos2d: SpriteFrameCache: removing unused frame: %s", element->getStrKey());
_spriteFrames->removeObjectForElememt(pElement); _spriteFrames->removeObjectForElememt(element);
bRemoved = true; bRemoved = true;
} }
} }
@ -315,16 +316,14 @@ void SpriteFrameCache::removeUnusedSpriteFrames(void)
} }
void SpriteFrameCache::removeSpriteFrameByName(const char *pszName) void SpriteFrameCache::removeSpriteFrameByName(const std::string& name)
{ {
// explicit nil handling // explicit nil handling
if( ! pszName ) if( ! name.size()>0 )
{
return; return;
}
// Is this an alias ? // Is this an alias ?
String* key = (String*)_spriteFramesAliases->objectForKey(pszName); String* key = (String*)_spriteFramesAliases->objectForKey(name);
if (key) if (key)
{ {
@ -333,20 +332,20 @@ void SpriteFrameCache::removeSpriteFrameByName(const char *pszName)
} }
else else
{ {
_spriteFrames->removeObjectForKey(pszName); _spriteFrames->removeObjectForKey(name);
} }
// XXX. Since we don't know the .plist file that originated the frame, we must remove all .plist from the cache // XXX. Since we don't know the .plist file that originated the frame, we must remove all .plist from the cache
_loadedFileNames->clear(); _loadedFileNames->clear();
} }
void SpriteFrameCache::removeSpriteFramesFromFile(const char* plist) void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& plist)
{ {
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist); std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist);
Dictionary* dict = Dictionary::createWithContentsOfFileThreadSafe(fullPath.c_str()); Dictionary* dict = Dictionary::createWithContentsOfFileThreadSafe(fullPath.c_str());
if (dict == nullptr) if (dict == nullptr)
{ {
CCLOG("cocos2d:SpriteFrameCache:removeSpriteFramesFromFile: create dict by %s fail.",plist); CCLOG("cocos2d:SpriteFrameCache:removeSpriteFramesFromFile: create dict by %s fail.",plist.c_str());
return; return;
} }
removeSpriteFramesFromDictionary((Dictionary*)dict); removeSpriteFramesFromDictionary((Dictionary*)dict);
@ -365,12 +364,12 @@ void SpriteFrameCache::removeSpriteFramesFromDictionary(Dictionary* dictionary)
Dictionary* framesDict = static_cast<Dictionary*>(dictionary->objectForKey("frames")); Dictionary* framesDict = static_cast<Dictionary*>(dictionary->objectForKey("frames"));
Array* keysToRemove = Array::create(); Array* keysToRemove = Array::create();
DictElement* pElement = NULL; DictElement* element = NULL;
CCDICT_FOREACH(framesDict, pElement) CCDICT_FOREACH(framesDict, element)
{ {
if (_spriteFrames->objectForKey(pElement->getStrKey())) if (_spriteFrames->objectForKey(element->getStrKey()))
{ {
keysToRemove->addObject(String::create(pElement->getStrKey())); keysToRemove->addObject(String::create(element->getStrKey()));
} }
} }
@ -381,33 +380,33 @@ void SpriteFrameCache::removeSpriteFramesFromTexture(Texture2D* texture)
{ {
Array* keysToRemove = Array::create(); Array* keysToRemove = Array::create();
DictElement* pElement = NULL; DictElement* element = NULL;
CCDICT_FOREACH(_spriteFrames, pElement) CCDICT_FOREACH(_spriteFrames, element)
{ {
string key = pElement->getStrKey(); string key = element->getStrKey();
SpriteFrame* frame = static_cast<SpriteFrame*>(_spriteFrames->objectForKey(key.c_str())); SpriteFrame* frame = static_cast<SpriteFrame*>(_spriteFrames->objectForKey(key.c_str()));
if (frame && (frame->getTexture() == texture)) if (frame && (frame->getTexture() == texture))
{ {
keysToRemove->addObject(String::create(pElement->getStrKey())); keysToRemove->addObject(String::create(element->getStrKey()));
} }
} }
_spriteFrames->removeObjectsForKeys(keysToRemove); _spriteFrames->removeObjectsForKeys(keysToRemove);
} }
SpriteFrame* SpriteFrameCache::getSpriteFrameByName(const char *pszName) SpriteFrame* SpriteFrameCache::getSpriteFrameByName(const std::string& name)
{ {
SpriteFrame* frame = (SpriteFrame*)_spriteFrames->objectForKey(pszName); SpriteFrame* frame = (SpriteFrame*)_spriteFrames->objectForKey(name);
if (!frame) if (!frame)
{ {
// try alias dictionary // try alias dictionary
String *key = (String*)_spriteFramesAliases->objectForKey(pszName); String *key = (String*)_spriteFramesAliases->objectForKey(name);
if (key) if (key)
{ {
frame = (SpriteFrame*)_spriteFrames->objectForKey(key->getCString()); frame = (SpriteFrame*)_spriteFrames->objectForKey(key->getCString());
if (! frame) if (! frame)
{ {
CCLOG("cocos2d: SpriteFrameCache: Frame '%s' not found", pszName); CCLOG("cocos2d: SpriteFrameCache: Frame '%s' not found", name.c_str());
} }
} }
} }

View File

@ -85,29 +85,29 @@ public:
public: public:
/** Adds multiple Sprite Frames from a plist file. /** Adds multiple Sprite Frames from a plist file.
* A texture will be loaded automatically. The texture name will composed by replacing the .plist suffix with .png * A texture will be loaded automatically. The texture name will composed by replacing the .plist suffix with .png
* If you want to use another texture, you should use the addSpriteFramesWithFile(const char *plist, const char *textureFileName) method. * If you want to use another texture, you should use the addSpriteFramesWithFile(const std::string& plist, const std::string& textureFileName) method.
* @js addSpriteFrames * @js addSpriteFrames
* @lua addSpriteFrames * @lua addSpriteFrames
*/ */
void addSpriteFramesWithFile(const char *plist); void addSpriteFramesWithFile(const std::string& plist);
/** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. /** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames.
@since v0.99.5 @since v0.99.5
* @js addSpriteFrames * @js addSpriteFrames
* @lua addSpriteFrames * @lua addSpriteFrames
*/ */
void addSpriteFramesWithFile(const char* plist, const char* textureFileName); void addSpriteFramesWithFile(const std::string& plist, const std::string& textureFileName);
/** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. /** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames.
* @js addSpriteFrames * @js addSpriteFrames
* @lua addSpriteFrames * @lua addSpriteFrames
*/ */
void addSpriteFramesWithFile(const char *plist, Texture2D *texture); void addSpriteFramesWithFile(const std::string&plist, Texture2D *texture);
/** Adds an sprite frame with a given name. /** Adds an sprite frame with a given name.
If the name already exists, then the contents of the old name will be replaced with the new one. If the name already exists, then the contents of the old name will be replaced with the new one.
*/ */
void addSpriteFrame(SpriteFrame *frame, const char *frameName); void addSpriteFrame(SpriteFrame *frame, const std::string& frameName);
/** Purges the dictionary of loaded sprite frames. /** Purges the dictionary of loaded sprite frames.
* Call this method if you receive the "Memory Warning". * Call this method if you receive the "Memory Warning".
@ -124,14 +124,14 @@ public:
void removeUnusedSpriteFrames(void); void removeUnusedSpriteFrames(void);
/** Deletes an sprite frame from the sprite frame cache. */ /** Deletes an sprite frame from the sprite frame cache. */
void removeSpriteFrameByName(const char *name); void removeSpriteFrameByName(const std::string& name);
/** Removes multiple Sprite Frames from a plist file. /** Removes multiple Sprite Frames from a plist file.
* Sprite Frames stored in this file will be removed. * Sprite Frames stored in this file will be removed.
* It is convenient to call this method when a specific texture needs to be removed. * It is convenient to call this method when a specific texture needs to be removed.
* @since v0.99.5 * @since v0.99.5
*/ */
void removeSpriteFramesFromFile(const char* plist); void removeSpriteFramesFromFile(const std::string& plist);
/** Removes all Sprite Frames associated with the specified textures. /** Removes all Sprite Frames associated with the specified textures.
* It is convenient to call this method when a specific texture needs to be removed. * It is convenient to call this method when a specific texture needs to be removed.
@ -145,10 +145,10 @@ public:
* @js getSpriteFrame * @js getSpriteFrame
* @lua getSpriteFrame * @lua getSpriteFrame
*/ */
SpriteFrame* getSpriteFrameByName(const char *name); SpriteFrame* getSpriteFrameByName(const std::string& name);
/** @deprecated use getSpriteFrameByName() instead */ /** @deprecated use getSpriteFrameByName() instead */
CC_DEPRECATED_ATTRIBUTE SpriteFrame* spriteFrameByName(const char *name) { return getSpriteFrameByName(name); } CC_DEPRECATED_ATTRIBUTE SpriteFrame* spriteFrameByName(const std::string&name) { return getSpriteFrameByName(name); }
private: private:
/*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames. /*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames.

View File

@ -58,7 +58,7 @@ bool TMXLayer::initWithTilesetInfo(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *la
Texture2D *texture = NULL; Texture2D *texture = NULL;
if( tilesetInfo ) if( tilesetInfo )
{ {
texture = TextureCache::getInstance()->addImage(tilesetInfo->_sourceImage.c_str()); texture = Director::getInstance()->getTextureCache()->addImage(tilesetInfo->_sourceImage.c_str());
} }
if (SpriteBatchNode::initWithTexture(texture, (unsigned int)capacity)) if (SpriteBatchNode::initWithTexture(texture, (unsigned int)capacity))

View File

@ -32,33 +32,33 @@ NS_CC_BEGIN
// implementation TMXTiledMap // implementation TMXTiledMap
TMXTiledMap * TMXTiledMap::create(const char *tmxFile) TMXTiledMap * TMXTiledMap::create(const std::string& tmxFile)
{ {
TMXTiledMap *pRet = new TMXTiledMap(); TMXTiledMap *ret = new TMXTiledMap();
if (pRet->initWithTMXFile(tmxFile)) if (ret->initWithTMXFile(tmxFile))
{ {
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
return NULL; return NULL;
} }
TMXTiledMap* TMXTiledMap::createWithXML(const char* tmxString, const char* resourcePath) TMXTiledMap* TMXTiledMap::createWithXML(const std::string& tmxString, const std::string& resourcePath)
{ {
TMXTiledMap *pRet = new TMXTiledMap(); TMXTiledMap *ret = new TMXTiledMap();
if (pRet->initWithXML(tmxString, resourcePath)) if (ret->initWithXML(tmxString, resourcePath))
{ {
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
return NULL; return NULL;
} }
bool TMXTiledMap::initWithTMXFile(const char *tmxFile) bool TMXTiledMap::initWithTMXFile(const std::string& tmxFile)
{ {
CCASSERT(tmxFile != NULL && strlen(tmxFile)>0, "TMXTiledMap: tmx file should not bi NULL"); CCASSERT(tmxFile.size()>0, "TMXTiledMap: tmx file should not be empty");
setContentSize(Size::ZERO); setContentSize(Size::ZERO);
@ -74,7 +74,7 @@ bool TMXTiledMap::initWithTMXFile(const char *tmxFile)
return true; return true;
} }
bool TMXTiledMap::initWithXML(const char* tmxString, const char* resourcePath) bool TMXTiledMap::initWithXML(const std::string& tmxString, const std::string& resourcePath)
{ {
setContentSize(Size::ZERO); setContentSize(Size::ZERO);
@ -195,8 +195,8 @@ void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo)
// update content size with the max size // update content size with the max size
const Size& childSize = child->getContentSize(); const Size& childSize = child->getContentSize();
Size currentSize = this->getContentSize(); Size currentSize = this->getContentSize();
currentSize.width = MAX( currentSize.width, childSize.width ); currentSize.width = std::max( currentSize.width, childSize.width );
currentSize.height = MAX( currentSize.height, childSize.height ); currentSize.height = std::max( currentSize.height, childSize.height );
this->setContentSize(currentSize); this->setContentSize(currentSize);
idx++; idx++;
@ -206,16 +206,16 @@ void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo)
} }
// public // public
TMXLayer * TMXTiledMap::getLayer(const char *layerName) const TMXLayer * TMXTiledMap::getLayer(const std::string& layerName) const
{ {
CCASSERT(layerName != NULL && strlen(layerName) > 0, "Invalid layer name!"); CCASSERT(layerName.size() > 0, "Invalid layer name!");
Object* pObj = NULL; Object* pObj = NULL;
CCARRAY_FOREACH(_children, pObj) CCARRAY_FOREACH(_children, pObj)
{ {
TMXLayer* layer = dynamic_cast<TMXLayer*>(pObj); TMXLayer* layer = dynamic_cast<TMXLayer*>(pObj);
if(layer) if(layer)
{ {
if(0 == strcmp(layer->getLayerName(), layerName)) if(layerName.compare( layer->getLayerName()) == 0)
{ {
return layer; return layer;
} }
@ -226,11 +226,10 @@ TMXLayer * TMXTiledMap::getLayer(const char *layerName) const
return NULL; return NULL;
} }
TMXObjectGroup * TMXTiledMap::getObjectGroup(const char *groupName) const TMXObjectGroup * TMXTiledMap::getObjectGroup(const std::string& groupName) const
{ {
CCASSERT(groupName != NULL && strlen(groupName) > 0, "Invalid group name!"); CCASSERT(groupName.size() > 0, "Invalid group name!");
std::string sGroupName = groupName;
if (_objectGroups && _objectGroups->count()>0) if (_objectGroups && _objectGroups->count()>0)
{ {
TMXObjectGroup* objectGroup = NULL; TMXObjectGroup* objectGroup = NULL;
@ -238,7 +237,7 @@ TMXObjectGroup * TMXTiledMap::getObjectGroup(const char *groupName) const
CCARRAY_FOREACH(_objectGroups, pObj) CCARRAY_FOREACH(_objectGroups, pObj)
{ {
objectGroup = static_cast<TMXObjectGroup*>(pObj); objectGroup = static_cast<TMXObjectGroup*>(pObj);
if (objectGroup && objectGroup->getGroupName() == sGroupName) if (objectGroup && objectGroup->getGroupName() == groupName)
{ {
return objectGroup; return objectGroup;
} }
@ -249,7 +248,7 @@ TMXObjectGroup * TMXTiledMap::getObjectGroup(const char *groupName) const
return NULL; return NULL;
} }
String* TMXTiledMap::getProperty(const char *propertyName) const String* TMXTiledMap::getProperty(const std::string& propertyName) const
{ {
return static_cast<String*>(_properties->objectForKey(propertyName)); return static_cast<String*>(_properties->objectForKey(propertyName));
} }

View File

@ -120,19 +120,19 @@ public:
virtual ~TMXTiledMap(); virtual ~TMXTiledMap();
/** creates a TMX Tiled Map with a TMX file.*/ /** creates a TMX Tiled Map with a TMX file.*/
static TMXTiledMap* create(const char *tmxFile); static TMXTiledMap* create(const std::string& tmxFile);
/** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ /** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */
static TMXTiledMap* createWithXML(const char* tmxString, const char* resourcePath); static TMXTiledMap* createWithXML(const std::string& tmxString, const std::string& resourcePath);
/** initializes a TMX Tiled Map with a TMX file */ /** initializes a TMX Tiled Map with a TMX file */
bool initWithTMXFile(const char *tmxFile); bool initWithTMXFile(const std::string& tmxFile);
/** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ /** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */
bool initWithXML(const char* tmxString, const char* resourcePath); bool initWithXML(const std::string& tmxString, const std::string& resourcePath);
/** return the TMXLayer for the specific layer */ /** return the TMXLayer for the specific layer */
TMXLayer* getLayer(const char *layerName) const; TMXLayer* getLayer(const std::string& layerName) const;
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
@ -140,7 +140,7 @@ public:
CC_DEPRECATED_ATTRIBUTE TMXLayer* layerNamed(const char *layerName) const { return getLayer(layerName); }; CC_DEPRECATED_ATTRIBUTE TMXLayer* layerNamed(const char *layerName) const { return getLayer(layerName); };
/** return the TMXObjectGroup for the specific group */ /** return the TMXObjectGroup for the specific group */
TMXObjectGroup* getObjectGroup(const char *groupName) const; TMXObjectGroup* getObjectGroup(const std::string& groupName) const;
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
@ -148,7 +148,7 @@ public:
CC_DEPRECATED_ATTRIBUTE TMXObjectGroup* objectGroupNamed(const char *groupName) const { return getObjectGroup(groupName); }; CC_DEPRECATED_ATTRIBUTE TMXObjectGroup* objectGroupNamed(const char *groupName) const { return getObjectGroup(groupName); };
/** return the value for the specific property name */ /** return the value for the specific property name */
String *getProperty(const char *propertyName) const; String *getProperty(const std::string& propertyName) const;
/** /**
* @js NA * @js NA
* @lua NA * @lua NA

View File

@ -112,7 +112,7 @@ Rect TMXTilesetInfo::rectForGID(unsigned int gid)
// implementation TMXMapInfo // implementation TMXMapInfo
TMXMapInfo * TMXMapInfo::create(const char *tmxFile) TMXMapInfo * TMXMapInfo::create(const std::string& tmxFile)
{ {
TMXMapInfo *pRet = new TMXMapInfo(); TMXMapInfo *pRet = new TMXMapInfo();
if(pRet->initWithTMXFile(tmxFile)) if(pRet->initWithTMXFile(tmxFile))
@ -124,7 +124,7 @@ TMXMapInfo * TMXMapInfo::create(const char *tmxFile)
return NULL; return NULL;
} }
TMXMapInfo * TMXMapInfo::createWithXML(const char* tmxString, const char* resourcePath) TMXMapInfo * TMXMapInfo::createWithXML(const std::string& tmxString, const std::string& resourcePath)
{ {
TMXMapInfo *pRet = new TMXMapInfo(); TMXMapInfo *pRet = new TMXMapInfo();
if(pRet->initWithXML(tmxString, resourcePath)) if(pRet->initWithXML(tmxString, resourcePath))
@ -136,7 +136,7 @@ TMXMapInfo * TMXMapInfo::createWithXML(const char* tmxString, const char* resour
return NULL; return NULL;
} }
void TMXMapInfo::internalInit(const char* tmxFileName, const char* resourcePath) void TMXMapInfo::internalInit(const std::string& tmxFileName, const std::string& resourcePath)
{ {
_tilesets = Array::create(); _tilesets = Array::create();
_tilesets->retain(); _tilesets->retain();
@ -144,12 +144,12 @@ void TMXMapInfo::internalInit(const char* tmxFileName, const char* resourcePath)
_layers = Array::create(); _layers = Array::create();
_layers->retain(); _layers->retain();
if (tmxFileName != NULL) if (tmxFileName.size() > 0)
{ {
_TMXFileName = FileUtils::getInstance()->fullPathForFilename(tmxFileName); _TMXFileName = FileUtils::getInstance()->fullPathForFilename(tmxFileName);
} }
if (resourcePath != NULL) if (resourcePath.size() > 0)
{ {
_resources = resourcePath; _resources = resourcePath;
} }
@ -169,15 +169,15 @@ void TMXMapInfo::internalInit(const char* tmxFileName, const char* resourcePath)
_parentElement = TMXPropertyNone; _parentElement = TMXPropertyNone;
_currentFirstGID = 0; _currentFirstGID = 0;
} }
bool TMXMapInfo::initWithXML(const char* tmxString, const char* resourcePath) bool TMXMapInfo::initWithXML(const std::string& tmxString, const std::string& resourcePath)
{ {
internalInit(NULL, resourcePath); internalInit("", resourcePath);
return parseXMLString(tmxString); return parseXMLString(tmxString);
} }
bool TMXMapInfo::initWithTMXFile(const char *tmxFile) bool TMXMapInfo::initWithTMXFile(const std::string& tmxFile)
{ {
internalInit(tmxFile, NULL); internalInit(tmxFile, "");
return parseXMLFile(_TMXFileName.c_str()); return parseXMLFile(_TMXFileName.c_str());
} }
@ -205,13 +205,11 @@ TMXMapInfo::~TMXMapInfo()
CC_SAFE_RELEASE(_objectGroups); CC_SAFE_RELEASE(_objectGroups);
} }
bool TMXMapInfo::parseXMLString(const char *xmlString) bool TMXMapInfo::parseXMLString(const std::string& xmlString)
{ {
int len = strlen(xmlString); int len = xmlString.size();
if (xmlString == NULL || len <= 0) if (len <= 0)
{
return false; return false;
}
SAXParser parser; SAXParser parser;
@ -222,10 +220,10 @@ bool TMXMapInfo::parseXMLString(const char *xmlString)
parser.setDelegator(this); parser.setDelegator(this);
return parser.parse(xmlString, len); return parser.parse(xmlString.c_str(), len);
} }
bool TMXMapInfo::parseXMLFile(const char *xmlFilename) bool TMXMapInfo::parseXMLFile(const std::string& xmlFilename)
{ {
SAXParser parser; SAXParser parser;

View File

@ -166,9 +166,9 @@ class CC_DLL TMXMapInfo : public Object, public SAXDelegator
{ {
public: public:
/** creates a TMX Format with a tmx file */ /** creates a TMX Format with a tmx file */
static TMXMapInfo * create(const char *tmxFile); static TMXMapInfo * create(const std::string& tmxFile);
/** creates a TMX Format with an XML string and a TMX resource path */ /** creates a TMX Format with an XML string and a TMX resource path */
static TMXMapInfo * createWithXML(const char* tmxString, const char* resourcePath); static TMXMapInfo * createWithXML(const std::string& tmxString, const std::string& resourcePath);
/** creates a TMX Format with a tmx file */ /** creates a TMX Format with a tmx file */
CC_DEPRECATED_ATTRIBUTE static TMXMapInfo * formatWithTMXFile(const char *tmxFile) { return TMXMapInfo::create(tmxFile); }; CC_DEPRECATED_ATTRIBUTE static TMXMapInfo * formatWithTMXFile(const char *tmxFile) { return TMXMapInfo::create(tmxFile); };
@ -185,13 +185,13 @@ public:
virtual ~TMXMapInfo(); virtual ~TMXMapInfo();
/** initializes a TMX format with a tmx file */ /** initializes a TMX format with a tmx file */
bool initWithTMXFile(const char *tmxFile); bool initWithTMXFile(const std::string& tmxFile);
/** initializes a TMX format with an XML string and a TMX resource path */ /** initializes a TMX format with an XML string and a TMX resource path */
bool initWithXML(const char* tmxString, const char* resourcePath); bool initWithXML(const std::string& tmxString, const std::string& resourcePath);
/** initializes parsing of an XML file, either a tmx (Map) file or tsx (Tileset) file */ /** initializes parsing of an XML file, either a tmx (Map) file or tsx (Tileset) file */
bool parseXMLFile(const char *xmlFilename); bool parseXMLFile(const std::string& xmlFilename);
/* initializes parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string */ /* initializes parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string */
bool parseXMLString(const char *xmlString); bool parseXMLString(const std::string& xmlString);
Dictionary* getTileProperties() { return _tileProperties; }; Dictionary* getTileProperties() { return _tileProperties; };
void setTileProperties(Dictionary* tileProperties) { void setTileProperties(Dictionary* tileProperties) {
@ -278,13 +278,13 @@ public:
*/ */
void textHandler(void *ctx, const char *ch, int len); void textHandler(void *ctx, const char *ch, int len);
inline const char* getCurrentString(){ return _currentString.c_str(); } inline const std::string& getCurrentString() const { return _currentString; }
inline void setCurrentString(const char *currentString){ _currentString = currentString; } inline void setCurrentString(const std::string& currentString){ _currentString = currentString; }
inline const char* getTMXFileName(){ return _TMXFileName.c_str(); } inline const std::string& getTMXFileName() const { return _TMXFileName; }
inline void setTMXFileName(const char *fileName){ _TMXFileName = fileName; } inline void setTMXFileName(const std::string& fileName){ _TMXFileName = fileName; }
private:
void internalInit(const char* tmxFileName, const char* resourcePath);
protected: protected:
void internalInit(const std::string& tmxFileName, const std::string& resourcePath);
/// map orientation /// map orientation
int _orientation; int _orientation;

View File

@ -53,8 +53,8 @@ static int _calcCharCount(const char * pszText)
TextFieldTTF::TextFieldTTF() TextFieldTTF::TextFieldTTF()
: _delegate(0) : _delegate(0)
, _charCount(0) , _charCount(0)
, _inputText(new std::string) , _inputText("")
, _placeHolder(new std::string) // prevent LabelTTF initWithString assertion , _placeHolder("") // prevent LabelTTF initWithString assertion
, _secureTextEntry(false) , _secureTextEntry(false)
{ {
_colorSpaceHolder.r = _colorSpaceHolder.g = _colorSpaceHolder.b = 127; _colorSpaceHolder.r = _colorSpaceHolder.g = _colorSpaceHolder.b = 127;
@ -62,43 +62,41 @@ TextFieldTTF::TextFieldTTF()
TextFieldTTF::~TextFieldTTF() TextFieldTTF::~TextFieldTTF()
{ {
CC_SAFE_DELETE(_inputText);
CC_SAFE_DELETE(_placeHolder);
} }
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
// static constructor // static constructor
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const char *placeholder, const Size& dimensions, TextHAlignment alignment, const char *fontName, float fontSize) TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize)
{ {
TextFieldTTF *pRet = new TextFieldTTF(); TextFieldTTF *ret = new TextFieldTTF();
if(pRet && pRet->initWithPlaceHolder("", dimensions, alignment, fontName, fontSize)) if(ret && ret->initWithPlaceHolder("", dimensions, alignment, fontName, fontSize))
{ {
pRet->autorelease(); ret->autorelease();
if (placeholder) if (placeholder.size()>0)
{ {
pRet->setPlaceHolder(placeholder); ret->setPlaceHolder(placeholder);
} }
return pRet; return ret;
} }
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
return NULL; return NULL;
} }
TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize) TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize)
{ {
TextFieldTTF *pRet = new TextFieldTTF(); TextFieldTTF *ret = new TextFieldTTF();
if(pRet && pRet->initWithString("", fontName, fontSize)) if(ret && ret->initWithString("", fontName, fontSize))
{ {
pRet->autorelease(); ret->autorelease();
if (placeholder) if (placeholder.size()>0)
{ {
pRet->setPlaceHolder(placeholder); ret->setPlaceHolder(placeholder);
} }
return pRet; return ret;
} }
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
return NULL; return NULL;
} }
@ -106,23 +104,15 @@ TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const char *placeholder, c
// initialize // initialize
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
bool TextFieldTTF::initWithPlaceHolder(const char *placeholder, const Size& dimensions, TextHAlignment alignment, const char *fontName, float fontSize) bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize)
{ {
if (placeholder) _placeHolder = placeholder;
{ return LabelTTF::initWithString(_placeHolder, fontName, fontSize, dimensions, alignment);
CC_SAFE_DELETE(_placeHolder);
_placeHolder = new std::string(placeholder);
}
return LabelTTF::initWithString(_placeHolder->c_str(), fontName, fontSize, dimensions, alignment);
} }
bool TextFieldTTF::initWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize) bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize)
{ {
if (placeholder) _placeHolder = std::string(placeholder);
{ return LabelTTF::initWithString(_placeHolder, fontName, fontSize);
CC_SAFE_DELETE(_placeHolder);
_placeHolder = new std::string(placeholder);
}
return LabelTTF::initWithString(_placeHolder->c_str(), fontName, fontSize);
} }
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
@ -190,9 +180,9 @@ void TextFieldTTF::insertText(const char * text, int len)
} }
_charCount += _calcCharCount(sInsert.c_str()); _charCount += _calcCharCount(sInsert.c_str());
std::string sText(*_inputText); std::string sText(_inputText);
sText.append(sInsert); sText.append(sInsert);
setString(sText.c_str()); setString(sText);
} }
if ((int)sInsert.npos == nPos) { if ((int)sInsert.npos == nPos) {
@ -211,7 +201,7 @@ void TextFieldTTF::insertText(const char * text, int len)
void TextFieldTTF::deleteBackward() void TextFieldTTF::deleteBackward()
{ {
int nStrLen = _inputText->length(); int nStrLen = _inputText.length();
if (! nStrLen) if (! nStrLen)
{ {
// there is no string // there is no string
@ -221,12 +211,12 @@ void TextFieldTTF::deleteBackward()
// get the delete byte number // get the delete byte number
int nDeleteLen = 1; // default, erase 1 byte int nDeleteLen = 1; // default, erase 1 byte
while(0x80 == (0xC0 & _inputText->at(nStrLen - nDeleteLen))) while(0x80 == (0xC0 & _inputText.at(nStrLen - nDeleteLen)))
{ {
++nDeleteLen; ++nDeleteLen;
} }
if (_delegate && _delegate->onTextFieldDeleteBackward(this, _inputText->c_str() + nStrLen - nDeleteLen, nDeleteLen)) if (_delegate && _delegate->onTextFieldDeleteBackward(this, _inputText.c_str() + nStrLen - nDeleteLen, nDeleteLen))
{ {
// delegate doesn't wan't to delete backwards // delegate doesn't wan't to delete backwards
return; return;
@ -235,21 +225,20 @@ void TextFieldTTF::deleteBackward()
// if all text deleted, show placeholder string // if all text deleted, show placeholder string
if (nStrLen <= nDeleteLen) if (nStrLen <= nDeleteLen)
{ {
CC_SAFE_DELETE(_inputText); _inputText = "";
_inputText = new std::string;
_charCount = 0; _charCount = 0;
LabelTTF::setString(_placeHolder->c_str()); LabelTTF::setString(_placeHolder);
return; return;
} }
// set new input text // set new input text
std::string sText(_inputText->c_str(), nStrLen - nDeleteLen); std::string sText(_inputText.c_str(), nStrLen - nDeleteLen);
setString(sText.c_str()); setString(sText);
} }
const char * TextFieldTTF::getContentText() const char * TextFieldTTF::getContentText()
{ {
return _inputText->c_str(); return _inputText.c_str();
} }
void TextFieldTTF::draw() void TextFieldTTF::draw()
@ -258,7 +247,7 @@ void TextFieldTTF::draw()
{ {
return; return;
} }
if (_inputText->length()) if (_inputText.length())
{ {
LabelTTF::draw(); LabelTTF::draw();
return; return;
@ -286,22 +275,20 @@ void TextFieldTTF::setColorSpaceHolder(const Color3B& color)
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
// input text property // input text property
void TextFieldTTF::setString(const char *text) void TextFieldTTF::setString(const std::string &text)
{ {
static char bulletString[] = {(char)0xe2, (char)0x80, (char)0xa2, (char)0x00}; static char bulletString[] = {(char)0xe2, (char)0x80, (char)0xa2, (char)0x00};
std::string displayText; std::string displayText;
int length; int length;
CC_SAFE_DELETE(_inputText); if (text.length()>0)
if (text)
{ {
_inputText = new std::string(text); _inputText = text;
displayText = *_inputText; displayText = _inputText;
if (_secureTextEntry) if (_secureTextEntry)
{ {
displayText = ""; displayText = "";
length = _inputText->length(); length = _inputText.length();
while (length) while (length)
{ {
displayText.append(bulletString); displayText.append(bulletString);
@ -311,40 +298,39 @@ void TextFieldTTF::setString(const char *text)
} }
else else
{ {
_inputText = new std::string; _inputText = "";
} }
// if there is no input text, display placeholder instead // if there is no input text, display placeholder instead
if (! _inputText->length()) if (! _inputText.length())
{ {
LabelTTF::setString(_placeHolder->c_str()); LabelTTF::setString(_placeHolder);
} }
else else
{ {
LabelTTF::setString(displayText.c_str()); LabelTTF::setString(displayText);
} }
_charCount = _calcCharCount(_inputText->c_str()); _charCount = _calcCharCount(_inputText.c_str());
} }
const char* TextFieldTTF::getString(void) const const std::string& TextFieldTTF::getString() const
{ {
return _inputText->c_str(); return _inputText;
} }
// place holder text property // place holder text property
void TextFieldTTF::setPlaceHolder(const char * text) void TextFieldTTF::setPlaceHolder(const std::string& text)
{ {
CC_SAFE_DELETE(_placeHolder); _placeHolder = text;
_placeHolder = (text) ? new std::string(text) : new std::string; if (! _inputText.length())
if (! _inputText->length())
{ {
LabelTTF::setString(_placeHolder->c_str()); LabelTTF::setString(_placeHolder);
} }
} }
const char * TextFieldTTF::getPlaceHolder(void) const std::string& TextFieldTTF::getPlaceHolder() const
{ {
return _placeHolder->c_str(); return _placeHolder;
} }
// secureTextEntry // secureTextEntry

View File

@ -109,13 +109,13 @@ public:
//char * description(); //char * description();
/** creates a TextFieldTTF from a fontname, alignment, dimension and font size */ /** creates a TextFieldTTF from a fontname, alignment, dimension and font size */
static TextFieldTTF * textFieldWithPlaceHolder(const char *placeholder, const Size& dimensions, TextHAlignment alignment, const char *fontName, float fontSize); static TextFieldTTF * textFieldWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize);
/** creates a LabelTTF from a fontname and font size */ /** creates a LabelTTF from a fontname and font size */
static TextFieldTTF * textFieldWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize); static TextFieldTTF * textFieldWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize);
/** initializes the TextFieldTTF with a font name, alignment, dimension and font size */ /** initializes the TextFieldTTF with a font name, alignment, dimension and font size */
bool initWithPlaceHolder(const char *placeholder, const Size& dimensions, TextHAlignment alignment, const char *fontName, float fontSize); bool initWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize);
/** initializes the TextFieldTTF with a font name and font size */ /** initializes the TextFieldTTF with a font name and font size */
bool initWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize); bool initWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize);
/** /**
@brief Open keyboard and receive input text. @brief Open keyboard and receive input text.
@ -147,21 +147,21 @@ public:
// input text property // input text property
public: public:
virtual void setString(const char *text); virtual void setString(const std::string& text) override;
virtual const char* getString(void) const; virtual const std::string& getString() const override;
protected: protected:
TextFieldDelegate * _delegate; TextFieldDelegate * _delegate;
int _charCount; int _charCount;
std::string * _inputText; std::string _inputText;
// place holder text property // place holder text property
// place holder text displayed when there is no text in the text field. // place holder text displayed when there is no text in the text field.
public: public:
virtual void setPlaceHolder(const char * text); virtual void setPlaceHolder(const std::string& text);
virtual const char * getPlaceHolder(void); virtual const std::string& getPlaceHolder(void) const;
protected: protected:
std::string * _placeHolder; std::string _placeHolder;
Color3B _colorSpaceHolder; Color3B _colorSpaceHolder;
public: public:
virtual void setSecureTextEntry(bool value); virtual void setSecureTextEntry(bool value);
@ -176,11 +176,11 @@ protected:
// IMEDelegate interface // IMEDelegate interface
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
virtual bool canAttachWithIME(); virtual bool canAttachWithIME() override;
virtual bool canDetachWithIME(); virtual bool canDetachWithIME() override;
virtual void insertText(const char * text, int len); virtual void insertText(const char * text, int len) override;
virtual void deleteBackward(); virtual void deleteBackward() override;
virtual const char * getContentText(); virtual const char * getContentText() override;
private: private:
class LengthStack; class LengthStack;
LengthStack * _lens; LengthStack * _lens;

View File

@ -119,7 +119,7 @@ static bool _PVRHaveAlphaPremultiplied = false;
//conventer function //conventer function
// IIIIIIII -> RRRRRRRRGGGGGGGGGBBBBBBBB // IIIIIIII -> RRRRRRRRGGGGGGGGGBBBBBBBB
void Texture2D::convertI8ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertI8ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
for (int i=0; i < dataLen; ++i) for (int i=0; i < dataLen; ++i)
{ {
@ -130,7 +130,7 @@ void Texture2D::convertI8ToRGB888(const unsigned char* data, int dataLen, unsign
} }
// IIIIIIIIAAAAAAAA -> RRRRRRRRGGGGGGGGBBBBBBBB // IIIIIIIIAAAAAAAA -> RRRRRRRRGGGGGGGGBBBBBBBB
void Texture2D::convertAI88ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertAI88ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
for (int i = 0, l = dataLen - 1; i < l; i += 2) for (int i = 0, l = dataLen - 1; i < l; i += 2)
{ {
@ -141,7 +141,7 @@ void Texture2D::convertAI88ToRGB888(const unsigned char* data, int dataLen, unsi
} }
// IIIIIIII -> RRRRRRRRGGGGGGGGGBBBBBBBBAAAAAAAA // IIIIIIII -> RRRRRRRRGGGGGGGGGBBBBBBBBAAAAAAAA
void Texture2D::convertI8ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertI8ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
for (int i = 0; i < dataLen; ++i) for (int i = 0; i < dataLen; ++i)
{ {
@ -153,7 +153,7 @@ void Texture2D::convertI8ToRGBA8888(const unsigned char* data, int dataLen, unsi
} }
// IIIIIIIIAAAAAAAA -> RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA // IIIIIIIIAAAAAAAA -> RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA
void Texture2D::convertAI88ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertAI88ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
for (int i = 0, l = dataLen - 1; i < l; i += 2) for (int i = 0, l = dataLen - 1; i < l; i += 2)
{ {
@ -165,7 +165,7 @@ void Texture2D::convertAI88ToRGBA8888(const unsigned char* data, int dataLen, un
} }
// IIIIIIII -> RRRRRGGGGGGBBBBB // IIIIIIII -> RRRRRGGGGGGBBBBB
void Texture2D::convertI8ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertI8ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
unsigned short* out16 = (unsigned short*)outData; unsigned short* out16 = (unsigned short*)outData;
for (int i = 0; i < dataLen; ++i) for (int i = 0; i < dataLen; ++i)
@ -177,7 +177,7 @@ void Texture2D::convertI8ToRGB565(const unsigned char* data, int dataLen, unsign
} }
// IIIIIIIIAAAAAAAA -> RRRRRGGGGGGBBBBB // IIIIIIIIAAAAAAAA -> RRRRRGGGGGGBBBBB
void Texture2D::convertAI88ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertAI88ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
unsigned short* out16 = (unsigned short*)outData; unsigned short* out16 = (unsigned short*)outData;
for (int i = 0, l = dataLen - 1; i < l; i += 2) for (int i = 0, l = dataLen - 1; i < l; i += 2)
@ -189,7 +189,7 @@ void Texture2D::convertAI88ToRGB565(const unsigned char* data, int dataLen, unsi
} }
// IIIIIIII -> RRRRGGGGBBBBAAAA // IIIIIIII -> RRRRGGGGBBBBAAAA
void Texture2D::convertI8ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertI8ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
unsigned short* out16 = (unsigned short*)outData; unsigned short* out16 = (unsigned short*)outData;
for (int i = 0; i < dataLen; ++i) for (int i = 0; i < dataLen; ++i)
@ -202,7 +202,7 @@ void Texture2D::convertI8ToRGBA4444(const unsigned char* data, int dataLen, unsi
} }
// IIIIIIIIAAAAAAAA -> RRRRGGGGBBBBAAAA // IIIIIIIIAAAAAAAA -> RRRRGGGGBBBBAAAA
void Texture2D::convertAI88ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertAI88ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
unsigned short* out16 = (unsigned short*)outData; unsigned short* out16 = (unsigned short*)outData;
for (int i = 0, l = dataLen - 1; i < l; i += 2) for (int i = 0, l = dataLen - 1; i < l; i += 2)
@ -215,7 +215,7 @@ void Texture2D::convertAI88ToRGBA4444(const unsigned char* data, int dataLen, un
} }
// IIIIIIII -> RRRRRGGGGGBBBBBA // IIIIIIII -> RRRRRGGGGGBBBBBA
void Texture2D::convertI8ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertI8ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
unsigned short* out16 = (unsigned short*)outData; unsigned short* out16 = (unsigned short*)outData;
for (int i = 0; i < dataLen; ++i) for (int i = 0; i < dataLen; ++i)
@ -228,7 +228,7 @@ void Texture2D::convertI8ToRGB5A1(const unsigned char* data, int dataLen, unsign
} }
// IIIIIIIIAAAAAAAA -> RRRRRGGGGGBBBBBA // IIIIIIIIAAAAAAAA -> RRRRRGGGGGBBBBBA
void Texture2D::convertAI88ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertAI88ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
unsigned short* out16 = (unsigned short*)outData; unsigned short* out16 = (unsigned short*)outData;
for (int i = 0, l = dataLen - 1; i < l; i += 2) for (int i = 0, l = dataLen - 1; i < l; i += 2)
@ -241,7 +241,7 @@ void Texture2D::convertAI88ToRGB5A1(const unsigned char* data, int dataLen, unsi
} }
// IIIIIIII -> IIIIIIIIAAAAAAAA // IIIIIIII -> IIIIIIIIAAAAAAAA
void Texture2D::convertI8ToAI88(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertI8ToAI88(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
unsigned short* out16 = (unsigned short*)outData; unsigned short* out16 = (unsigned short*)outData;
for (int i = 0; i < dataLen; ++i) for (int i = 0; i < dataLen; ++i)
@ -252,7 +252,7 @@ void Texture2D::convertI8ToAI88(const unsigned char* data, int dataLen, unsigned
} }
// IIIIIIIIAAAAAAAA -> AAAAAAAA // IIIIIIIIAAAAAAAA -> AAAAAAAA
void Texture2D::convertAI88ToA8(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertAI88ToA8(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
for (int i = 1; i < dataLen; i += 2) for (int i = 1; i < dataLen; i += 2)
{ {
@ -261,7 +261,7 @@ void Texture2D::convertAI88ToA8(const unsigned char* data, int dataLen, unsigned
} }
// IIIIIIIIAAAAAAAA -> IIIIIIII // IIIIIIIIAAAAAAAA -> IIIIIIII
void Texture2D::convertAI88ToI8(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertAI88ToI8(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
for (int i = 0, l = dataLen - 1; i < l; i += 2) for (int i = 0, l = dataLen - 1; i < l; i += 2)
{ {
@ -270,7 +270,7 @@ void Texture2D::convertAI88ToI8(const unsigned char* data, int dataLen, unsigned
} }
// RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA
void Texture2D::convertRGB888ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertRGB888ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
for (int i = 0, l = dataLen - 2; i < l; i += 3) for (int i = 0, l = dataLen - 2; i < l; i += 3)
{ {
@ -282,7 +282,7 @@ void Texture2D::convertRGB888ToRGBA8888(const unsigned char* data, int dataLen,
} }
// RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> RRRRRRRRGGGGGGGGBBBBBBBB // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> RRRRRRRRGGGGGGGGBBBBBBBB
void Texture2D::convertRGBA8888ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertRGBA8888ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
for (int i = 0, l = dataLen - 3; i < l; i += 4) for (int i = 0, l = dataLen - 3; i < l; i += 4)
{ {
@ -293,7 +293,7 @@ void Texture2D::convertRGBA8888ToRGB888(const unsigned char* data, int dataLen,
} }
// RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRGGGGGGBBBBB // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRGGGGGGBBBBB
void Texture2D::convertRGB888ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertRGB888ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
unsigned short* out16 = (unsigned short*)outData; unsigned short* out16 = (unsigned short*)outData;
for (int i = 0, l = dataLen - 2; i < l; i += 3) for (int i = 0, l = dataLen - 2; i < l; i += 3)
@ -305,7 +305,7 @@ void Texture2D::convertRGB888ToRGB565(const unsigned char* data, int dataLen, un
} }
// RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> RRRRRGGGGGGBBBBB // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> RRRRRGGGGGGBBBBB
void Texture2D::convertRGBA8888ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertRGBA8888ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
unsigned short* out16 = (unsigned short*)outData; unsigned short* out16 = (unsigned short*)outData;
for (int i = 0, l = dataLen - 3; i < l; i += 4) for (int i = 0, l = dataLen - 3; i < l; i += 4)
@ -317,7 +317,7 @@ void Texture2D::convertRGBA8888ToRGB565(const unsigned char* data, int dataLen,
} }
// RRRRRRRRGGGGGGGGBBBBBBBB -> IIIIIIII // RRRRRRRRGGGGGGGGBBBBBBBB -> IIIIIIII
void Texture2D::convertRGB888ToI8(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertRGB888ToI8(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
for (int i = 0, l = dataLen - 2; i < l; i += 3) for (int i = 0, l = dataLen - 2; i < l; i += 3)
{ {
@ -326,7 +326,7 @@ void Texture2D::convertRGB888ToI8(const unsigned char* data, int dataLen, unsign
} }
// RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> IIIIIIII // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> IIIIIIII
void Texture2D::convertRGBA8888ToI8(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertRGBA8888ToI8(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
for (int i = 0, l = dataLen - 3; i < l; i += 4) for (int i = 0, l = dataLen - 3; i < l; i += 4)
{ {
@ -335,7 +335,7 @@ void Texture2D::convertRGBA8888ToI8(const unsigned char* data, int dataLen, unsi
} }
// RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> AAAAAAAA // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> AAAAAAAA
void Texture2D::convertRGBA8888ToA8(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertRGBA8888ToA8(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
for (int i = 0, l = dataLen -3; i < l; i += 4) for (int i = 0, l = dataLen -3; i < l; i += 4)
{ {
@ -344,7 +344,7 @@ void Texture2D::convertRGBA8888ToA8(const unsigned char* data, int dataLen, unsi
} }
// RRRRRRRRGGGGGGGGBBBBBBBB -> IIIIIIIIAAAAAAAA // RRRRRRRRGGGGGGGGBBBBBBBB -> IIIIIIIIAAAAAAAA
void Texture2D::convertRGB888ToAI88(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertRGB888ToAI88(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
for (int i = 0, l = dataLen - 2; i < l; i += 3) for (int i = 0, l = dataLen - 2; i < l; i += 3)
{ {
@ -355,7 +355,7 @@ void Texture2D::convertRGB888ToAI88(const unsigned char* data, int dataLen, unsi
// RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> IIIIIIIIAAAAAAAA // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> IIIIIIIIAAAAAAAA
void Texture2D::convertRGBA8888ToAI88(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertRGBA8888ToAI88(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
for (int i = 0, l = dataLen - 3; i < l; i += 4) for (int i = 0, l = dataLen - 3; i < l; i += 4)
{ {
@ -365,7 +365,7 @@ void Texture2D::convertRGBA8888ToAI88(const unsigned char* data, int dataLen, un
} }
// RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRGGGGBBBBAAAA // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRGGGGBBBBAAAA
void Texture2D::convertRGB888ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertRGB888ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
unsigned short* out16 = (unsigned short*)outData; unsigned short* out16 = (unsigned short*)outData;
for (int i = 0, l = dataLen - 2; i < l; i += 3) for (int i = 0, l = dataLen - 2; i < l; i += 3)
@ -378,7 +378,7 @@ void Texture2D::convertRGB888ToRGBA4444(const unsigned char* data, int dataLen,
} }
// RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> RRRRGGGGBBBBAAAA // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> RRRRGGGGBBBBAAAA
void Texture2D::convertRGBA8888ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertRGBA8888ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
unsigned short* out16 = (unsigned short*)outData; unsigned short* out16 = (unsigned short*)outData;
for (int i = 0, l = dataLen - 3; i < l; i += 4) for (int i = 0, l = dataLen - 3; i < l; i += 4)
@ -391,10 +391,10 @@ void Texture2D::convertRGBA8888ToRGBA4444(const unsigned char* data, int dataLen
} }
// RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRGGGGGBBBBBA // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRGGGGGBBBBBA
void Texture2D::convertRGB888ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertRGB888ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
unsigned short* out16 = (unsigned short*)outData; unsigned short* out16 = (unsigned short*)outData;
for (int i = 0, l = dataLen - 2; i < l; i += 3) for (long i = 0, l = dataLen - 2; i < l; i += 3)
{ {
*out16++ = (data[i] & 0x00F8) << 8 //R *out16++ = (data[i] & 0x00F8) << 8 //R
| (data[i + 1] & 0x00F8) << 3 //G | (data[i + 1] & 0x00F8) << 3 //G
@ -404,10 +404,10 @@ void Texture2D::convertRGB888ToRGB5A1(const unsigned char* data, int dataLen, un
} }
// RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRGGGGGBBBBBA // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRGGGGGBBBBBA
void Texture2D::convertRGBA8888ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData) void Texture2D::convertRGBA8888ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData)
{ {
unsigned short* out16 = (unsigned short*)outData; unsigned short* out16 = (unsigned short*)outData;
for (int i = 0, l = dataLen - 2; i < l; i += 4) for (long i = 0, l = dataLen - 2; i < l; i += 4)
{ {
*out16++ = (data[i] & 0x00F8) << 8 //R *out16++ = (data[i] & 0x00F8) << 8 //R
| (data[i + 1] & 0x00F8) << 3 //G | (data[i + 1] & 0x00F8) << 3 //G
@ -434,7 +434,7 @@ Texture2D::Texture2D()
Texture2D::~Texture2D() Texture2D::~Texture2D()
{ {
#if CC_ENABLE_CACHE_TEXTURE_DATA #if CC_ENABLE_CACHE_TEXTURE_DATA
VolatileTexture::removeTexture(this); VolatileTextureMgr::removeTexture(this);
#endif #endif
CCLOGINFO("deallocing Texture2D: %p - id=%u", this, _name); CCLOGINFO("deallocing Texture2D: %p - id=%u", this, _name);
@ -451,12 +451,12 @@ Texture2D::PixelFormat Texture2D::getPixelFormat() const
return _pixelFormat; return _pixelFormat;
} }
unsigned int Texture2D::getPixelsWide() const long Texture2D::getPixelsWide() const
{ {
return _pixelsWide; return _pixelsWide;
} }
unsigned int Texture2D::getPixelsHigh() const long Texture2D::getPixelsHigh() const
{ {
return _pixelsHigh; return _pixelsHigh;
} }
@ -529,8 +529,10 @@ bool Texture2D::hasPremultipliedAlpha() const
return _hasPremultipliedAlpha; return _hasPremultipliedAlpha;
} }
bool Texture2D::initWithData(const void *data, int dataLen, Texture2D::PixelFormat pixelFormat, unsigned int pixelsWide, unsigned int pixelsHigh, const Size& contentSize) bool Texture2D::initWithData(const void *data, long dataLen, Texture2D::PixelFormat pixelFormat, long pixelsWide, long pixelsHigh, const Size& contentSize)
{ {
CCASSERT(dataLen>0 && pixelsWide>0 && pixelsHigh>0, "Invalid size");
//if data has no mipmaps, we will consider it has only one mipmap //if data has no mipmaps, we will consider it has only one mipmap
MipmapInfo mipmap; MipmapInfo mipmap;
mipmap.address = (unsigned char*)data; mipmap.address = (unsigned char*)data;
@ -544,10 +546,11 @@ bool Texture2D::initWithData(const void *data, int dataLen, Texture2D::PixelForm
} }
bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat pixelFormat, unsigned int pixelsWide, unsigned int pixelsHigh) bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat pixelFormat, long pixelsWide, long pixelsHigh)
{ {
//the pixelFormat must be a certain value //the pixelFormat must be a certain value
CCAssert(pixelFormat != PixelFormat::NONE && pixelFormat != PixelFormat::AUTO, "the \"pixelFormat\" param must be a certain value!"); CCASSERT(pixelFormat != PixelFormat::NONE && pixelFormat != PixelFormat::AUTO, "the \"pixelFormat\" param must be a certain value!");
CCASSERT(pixelsWide>0 && pixelsHigh>0, "Invalid size");
if (mipmapsNum <= 0) if (mipmapsNum <= 0)
{ {
@ -670,7 +673,7 @@ bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat
const char* Texture2D::description(void) const const char* Texture2D::description(void) const
{ {
return String::createWithFormat("<Texture2D | Name = %u | Dimensions = %u x %u | Coordinates = (%.2f, %.2f)>", _name, _pixelsWide, _pixelsHigh, _maxS, _maxT)->getCString(); return String::createWithFormat("<Texture2D | Name = %u | Dimensions = %ld x %ld | Coordinates = (%.2f, %.2f)>", _name, (long)_pixelsWide, (long)_pixelsHigh, _maxS, _maxT)->getCString();
} }
// implementation Texture2D (Image) // implementation Texture2D (Image)
@ -771,7 +774,7 @@ bool Texture2D::initWithImage(Image *image, PixelFormat format)
} }
} }
Texture2D::PixelFormat Texture2D::convertI8ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) Texture2D::PixelFormat Texture2D::convertI8ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen)
{ {
switch (format) switch (format)
{ {
@ -820,7 +823,7 @@ Texture2D::PixelFormat Texture2D::convertI8ToFormat(const unsigned char* data, i
return format; return format;
} }
Texture2D::PixelFormat Texture2D::convertAI88ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) Texture2D::PixelFormat Texture2D::convertAI88ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen)
{ {
switch (format) switch (format)
{ {
@ -875,7 +878,7 @@ Texture2D::PixelFormat Texture2D::convertAI88ToFormat(const unsigned char* data,
return format; return format;
} }
Texture2D::PixelFormat Texture2D::convertRGB888ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) Texture2D::PixelFormat Texture2D::convertRGB888ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen)
{ {
switch (format) switch (format)
{ {
@ -923,7 +926,7 @@ Texture2D::PixelFormat Texture2D::convertRGB888ToFormat(const unsigned char* dat
return format; return format;
} }
Texture2D::PixelFormat Texture2D::convertRGBA8888ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) Texture2D::PixelFormat Texture2D::convertRGBA8888ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen)
{ {
switch (format) switch (format)
@ -995,7 +998,7 @@ rgb(2) -> 1235678
rgba(1) -> 12345678 rgba(1) -> 12345678
*/ */
Texture2D::PixelFormat Texture2D::convertDataToFormat(const unsigned char* data, int dataLen, PixelFormat originFormat, PixelFormat format, unsigned char** outData, int* outDataLen) Texture2D::PixelFormat Texture2D::convertDataToFormat(const unsigned char* data, long dataLen, PixelFormat originFormat, PixelFormat format, unsigned char** outData, int* outDataLen)
{ {
switch (originFormat) switch (originFormat)
{ {
@ -1038,7 +1041,7 @@ bool Texture2D::initWithString(const char *text, const FontDefinition& textDefin
{ {
#if CC_ENABLE_CACHE_TEXTURE_DATA #if CC_ENABLE_CACHE_TEXTURE_DATA
// cache the texture data // cache the texture data
VolatileTexture::addStringTexture(this, text, textDefinition); VolatileTextureMgr::addStringTexture(this, text, textDefinition);
#endif #endif
bool bRet = false; bool bRet = false;
@ -1264,7 +1267,7 @@ void Texture2D::setTexParameters(const TexParams &texParams)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texParams.wrapT ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texParams.wrapT );
#if CC_ENABLE_CACHE_TEXTURE_DATA #if CC_ENABLE_CACHE_TEXTURE_DATA
VolatileTexture::setTexParameters(this, texParams); VolatileTextureMgr::setTexParameters(this, texParams);
#endif #endif
} }
@ -1284,7 +1287,7 @@ void Texture2D::setAliasTexParameters()
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
#if CC_ENABLE_CACHE_TEXTURE_DATA #if CC_ENABLE_CACHE_TEXTURE_DATA
TexParams texParams = {(GLuint)(_hasMipmaps?GL_NEAREST_MIPMAP_NEAREST:GL_NEAREST),GL_NEAREST,GL_NONE,GL_NONE}; TexParams texParams = {(GLuint)(_hasMipmaps?GL_NEAREST_MIPMAP_NEAREST:GL_NEAREST),GL_NEAREST,GL_NONE,GL_NONE};
VolatileTexture::setTexParameters(this, texParams); VolatileTextureMgr::setTexParameters(this, texParams);
#endif #endif
} }
@ -1304,7 +1307,7 @@ void Texture2D::setAntiAliasTexParameters()
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
#if CC_ENABLE_CACHE_TEXTURE_DATA #if CC_ENABLE_CACHE_TEXTURE_DATA
TexParams texParams = {(GLuint)(_hasMipmaps?GL_LINEAR_MIPMAP_NEAREST:GL_LINEAR),GL_LINEAR,GL_NONE,GL_NONE}; TexParams texParams = {(GLuint)(_hasMipmaps?GL_LINEAR_MIPMAP_NEAREST:GL_LINEAR),GL_LINEAR,GL_NONE,GL_NONE};
VolatileTexture::setTexParameters(this, texParams); VolatileTextureMgr::setTexParameters(this, texParams);
#endif #endif
} }

View File

@ -120,13 +120,13 @@ public:
struct PixelFormatInfo { struct PixelFormatInfo {
PixelFormatInfo(GLenum internalFormat, GLenum format, GLenum type, int bpp, bool compressed, bool alpha) PixelFormatInfo(GLenum anInternalFormat, GLenum aFormat, GLenum aType, int aBpp, bool aCompressed, bool anAlpha)
: internalFormat(internalFormat) : internalFormat(anInternalFormat)
, format(format) , format(aFormat)
, type(type) , type(aType)
, bpp(bpp) , bpp(aBpp)
, compressed(compressed) , compressed(aCompressed)
, alpha(alpha) , alpha(anAlpha)
{} {}
GLenum internalFormat; GLenum internalFormat;
@ -216,10 +216,10 @@ public:
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
bool initWithData(const void *data, int dataLen, Texture2D::PixelFormat pixelFormat, unsigned int pixelsWide, unsigned int pixelsHigh, const Size& contentSize); bool initWithData(const void *data, long dataLen, Texture2D::PixelFormat pixelFormat, long pixelsWide, long pixelsHigh, const Size& contentSize);
/** Initializes with mipmaps */ /** Initializes with mipmaps */
bool initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, Texture2D::PixelFormat pixelFormat, unsigned int pixelsWide, unsigned int pixelsHigh); bool initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, Texture2D::PixelFormat pixelFormat, long pixelsWide, long pixelsHigh);
/** /**
Drawing extensions to make it easy to draw basic quads using a Texture2D object. Drawing extensions to make it easy to draw basic quads using a Texture2D object.
@ -326,10 +326,10 @@ public:
Texture2D::PixelFormat getPixelFormat() const; Texture2D::PixelFormat getPixelFormat() const;
/** Gets the width of the texture in pixels */ /** Gets the width of the texture in pixels */
unsigned int getPixelsWide() const; long getPixelsWide() const;
/** Gets the height of the texture in pixels */ /** Gets the height of the texture in pixels */
unsigned int getPixelsHigh() const; long getPixelsHigh() const;
/** Gets the texture name */ /** Gets the texture name */
GLuint getName() const; GLuint getName() const;
@ -360,56 +360,56 @@ private:
Convert the format to the format param you specified, if the format is PixelFormat::Automatic, it will detect it automatically and convert to the closest format for you. Convert the format to the format param you specified, if the format is PixelFormat::Automatic, it will detect it automatically and convert to the closest format for you.
It will return the converted format to you. if the outData != data, you must delete it manually. It will return the converted format to you. if the outData != data, you must delete it manually.
*/ */
static PixelFormat convertDataToFormat(const unsigned char* data, int dataLen, PixelFormat originFormat, PixelFormat format, unsigned char** outData, int* outDataLen); static PixelFormat convertDataToFormat(const unsigned char* data, long dataLen, PixelFormat originFormat, PixelFormat format, unsigned char** outData, int* outDataLen);
static PixelFormat convertI8ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); static PixelFormat convertI8ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen);
static PixelFormat convertAI88ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); static PixelFormat convertAI88ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen);
static PixelFormat convertRGB888ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); static PixelFormat convertRGB888ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen);
static PixelFormat convertRGBA8888ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); static PixelFormat convertRGBA8888ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen);
//I8 to XXX //I8 to XXX
static void convertI8ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData); static void convertI8ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertI8ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData); static void convertI8ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertI8ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData); static void convertI8ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertI8ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData); static void convertI8ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertI8ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData); static void convertI8ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertI8ToAI88(const unsigned char* data, int dataLen, unsigned char* outData); static void convertI8ToAI88(const unsigned char* data, long dataLen, unsigned char* outData);
//AI88 to XXX //AI88 to XXX
static void convertAI88ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData); static void convertAI88ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertAI88ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData); static void convertAI88ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertAI88ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData); static void convertAI88ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertAI88ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData); static void convertAI88ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertAI88ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData); static void convertAI88ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertAI88ToA8(const unsigned char* data, int dataLen, unsigned char* outData); static void convertAI88ToA8(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertAI88ToI8(const unsigned char* data, int dataLen, unsigned char* outData); static void convertAI88ToI8(const unsigned char* data, long dataLen, unsigned char* outData);
//RGB888 to XXX //RGB888 to XXX
static void convertRGB888ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData); static void convertRGB888ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertRGB888ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData); static void convertRGB888ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertRGB888ToI8(const unsigned char* data, int dataLen, unsigned char* outData); static void convertRGB888ToI8(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertRGB888ToAI88(const unsigned char* data, int dataLen, unsigned char* outData); static void convertRGB888ToAI88(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertRGB888ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData); static void convertRGB888ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertRGB888ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData); static void convertRGB888ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData);
//RGBA8888 to XXX //RGBA8888 to XXX
static void convertRGBA8888ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData); static void convertRGBA8888ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertRGBA8888ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData); static void convertRGBA8888ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertRGBA8888ToI8(const unsigned char* data, int dataLen, unsigned char* outData); static void convertRGBA8888ToI8(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertRGBA8888ToA8(const unsigned char* data, int dataLen, unsigned char* outData); static void convertRGBA8888ToA8(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertRGBA8888ToAI88(const unsigned char* data, int dataLen, unsigned char* outData); static void convertRGBA8888ToAI88(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertRGBA8888ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData); static void convertRGBA8888ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData);
static void convertRGBA8888ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData); static void convertRGBA8888ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData);
protected: protected:
/** pixel format of the texture */ /** pixel format of the texture */
Texture2D::PixelFormat _pixelFormat; Texture2D::PixelFormat _pixelFormat;
/** width in pixels */ /** width in pixels */
unsigned int _pixelsWide; long _pixelsWide;
/** height in pixels */ /** height in pixels */
unsigned int _pixelsHigh; long _pixelsHigh;
/** texture name */ /** texture name */
GLuint _name; GLuint _name;

View File

@ -32,6 +32,7 @@ THE SOFTWARE.
#include "ccGLStateCache.h" #include "ccGLStateCache.h"
#include "CCNotificationCenter.h" #include "CCNotificationCenter.h"
#include "CCEventType.h" #include "CCEventType.h"
#include "CCDirector.h"
#include "CCGL.h" #include "CCGL.h"
#include "CCConfiguration.h" #include "CCConfiguration.h"
// support // support
@ -72,12 +73,12 @@ TextureAtlas::~TextureAtlas()
#endif #endif
} }
int TextureAtlas::getTotalQuads() const long TextureAtlas::getTotalQuads() const
{ {
return _totalQuads; return _totalQuads;
} }
int TextureAtlas::getCapacity() const long TextureAtlas::getCapacity() const
{ {
return _capacity; return _capacity;
} }
@ -108,7 +109,7 @@ void TextureAtlas::setQuads(V3F_C4B_T2F_Quad* quads)
// TextureAtlas - alloc & init // TextureAtlas - alloc & init
TextureAtlas * TextureAtlas::create(const char* file, int capacity) TextureAtlas * TextureAtlas::create(const char* file, long capacity)
{ {
TextureAtlas * textureAtlas = new TextureAtlas(); TextureAtlas * textureAtlas = new TextureAtlas();
if(textureAtlas && textureAtlas->initWithFile(file, capacity)) if(textureAtlas && textureAtlas->initWithFile(file, capacity))
@ -120,7 +121,7 @@ TextureAtlas * TextureAtlas::create(const char* file, int capacity)
return NULL; return NULL;
} }
TextureAtlas * TextureAtlas::createWithTexture(Texture2D *texture, int capacity) TextureAtlas * TextureAtlas::createWithTexture(Texture2D *texture, long capacity)
{ {
TextureAtlas * textureAtlas = new TextureAtlas(); TextureAtlas * textureAtlas = new TextureAtlas();
if (textureAtlas && textureAtlas->initWithTexture(texture, capacity)) if (textureAtlas && textureAtlas->initWithTexture(texture, capacity))
@ -132,10 +133,10 @@ TextureAtlas * TextureAtlas::createWithTexture(Texture2D *texture, int capacity)
return NULL; return NULL;
} }
bool TextureAtlas::initWithFile(const char * file, int capacity) bool TextureAtlas::initWithFile(const char * file, long capacity)
{ {
// retained in property // retained in property
Texture2D *texture = TextureCache::getInstance()->addImage(file); Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(file);
if (texture) if (texture)
{ {
@ -148,7 +149,7 @@ bool TextureAtlas::initWithFile(const char * file, int capacity)
} }
} }
bool TextureAtlas::initWithTexture(Texture2D *texture, int capacity) bool TextureAtlas::initWithTexture(Texture2D *texture, long capacity)
{ {
CCASSERT(capacity>=0, "Capacity must be >= 0"); CCASSERT(capacity>=0, "Capacity must be >= 0");
@ -218,7 +219,7 @@ void TextureAtlas::listenBackToForeground(Object *obj)
const char* TextureAtlas::description() const const char* TextureAtlas::description() const
{ {
return String::createWithFormat("<TextureAtlas | totalQuads = %u>", _totalQuads)->getCString(); return String::createWithFormat("<TextureAtlas | totalQuads = %ld>", _totalQuads)->getCString();
} }
@ -311,7 +312,7 @@ void TextureAtlas::mapBuffers()
// TextureAtlas - Update, Insert, Move & Remove // TextureAtlas - Update, Insert, Move & Remove
void TextureAtlas::updateQuad(V3F_C4B_T2F_Quad *quad, int index) void TextureAtlas::updateQuad(V3F_C4B_T2F_Quad *quad, long index)
{ {
CCASSERT( index >= 0 && index < _capacity, "updateQuadWithTexture: Invalid index"); CCASSERT( index >= 0 && index < _capacity, "updateQuadWithTexture: Invalid index");
@ -324,7 +325,7 @@ void TextureAtlas::updateQuad(V3F_C4B_T2F_Quad *quad, int index)
} }
void TextureAtlas::insertQuad(V3F_C4B_T2F_Quad *quad, int index) void TextureAtlas::insertQuad(V3F_C4B_T2F_Quad *quad, long index)
{ {
CCASSERT( index>=0 && index<_capacity, "insertQuadWithTexture: Invalid index"); CCASSERT( index>=0 && index<_capacity, "insertQuadWithTexture: Invalid index");
@ -348,7 +349,7 @@ void TextureAtlas::insertQuad(V3F_C4B_T2F_Quad *quad, int index)
} }
void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, int index, int amount) void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, long index, long amount)
{ {
CCASSERT(index>=0 && amount>=0 && index+amount<=_capacity, "insertQuadWithTexture: Invalid index + amount"); CCASSERT(index>=0 && amount>=0 && index+amount<=_capacity, "insertQuadWithTexture: Invalid index + amount");
@ -357,7 +358,7 @@ void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, int index, int amount)
CCASSERT( _totalQuads <= _capacity, "invalid totalQuads"); CCASSERT( _totalQuads <= _capacity, "invalid totalQuads");
// issue #575. index can be > totalQuads // issue #575. index can be > totalQuads
int remaining = (_totalQuads-1) - index - amount; long remaining = (_totalQuads-1) - index - amount;
// last object doesn't need to be moved // last object doesn't need to be moved
if( remaining > 0) if( remaining > 0)
@ -367,9 +368,9 @@ void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, int index, int amount)
} }
int max = index + amount; long max = index + amount;
int j = 0; int j = 0;
for (int i = index; i < max ; i++) for (long i = index; i < max ; i++)
{ {
_quads[index] = quads[j]; _quads[index] = quads[j];
index++; index++;
@ -379,7 +380,7 @@ void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, int index, int amount)
_dirty = true; _dirty = true;
} }
void TextureAtlas::insertQuadFromIndex(int oldIndex, int newIndex) void TextureAtlas::insertQuadFromIndex(long oldIndex, long newIndex)
{ {
CCASSERT( newIndex >= 0 && newIndex < _totalQuads, "insertQuadFromIndex:atIndex: Invalid index"); CCASSERT( newIndex >= 0 && newIndex < _totalQuads, "insertQuadFromIndex:atIndex: Invalid index");
CCASSERT( oldIndex >= 0 && oldIndex < _totalQuads, "insertQuadFromIndex:atIndex: Invalid index"); CCASSERT( oldIndex >= 0 && oldIndex < _totalQuads, "insertQuadFromIndex:atIndex: Invalid index");
@ -390,9 +391,9 @@ void TextureAtlas::insertQuadFromIndex(int oldIndex, int newIndex)
} }
// because it is ambiguous in iphone, so we implement abs ourselves // because it is ambiguous in iphone, so we implement abs ourselves
// unsigned int howMany = abs( oldIndex - newIndex); // unsigned int howMany = abs( oldIndex - newIndex);
int howMany = (oldIndex - newIndex) > 0 ? (oldIndex - newIndex) : (newIndex - oldIndex); long howMany = (oldIndex - newIndex) > 0 ? (oldIndex - newIndex) : (newIndex - oldIndex);
int dst = oldIndex; long dst = oldIndex;
int src = oldIndex + 1; long src = oldIndex + 1;
if( oldIndex > newIndex) if( oldIndex > newIndex)
{ {
dst = newIndex+1; dst = newIndex+1;
@ -408,11 +409,11 @@ void TextureAtlas::insertQuadFromIndex(int oldIndex, int newIndex)
_dirty = true; _dirty = true;
} }
void TextureAtlas::removeQuadAtIndex(int index) void TextureAtlas::removeQuadAtIndex(long index)
{ {
CCASSERT( index>=0 && index<_totalQuads, "removeQuadAtIndex: Invalid index"); CCASSERT( index>=0 && index<_totalQuads, "removeQuadAtIndex: Invalid index");
int remaining = (_totalQuads-1) - index; long remaining = (_totalQuads-1) - index;
// last object doesn't need to be moved // last object doesn't need to be moved
if( remaining ) if( remaining )
@ -427,11 +428,11 @@ void TextureAtlas::removeQuadAtIndex(int index)
_dirty = true; _dirty = true;
} }
void TextureAtlas::removeQuadsAtIndex(int index, int amount) void TextureAtlas::removeQuadsAtIndex(long index, long amount)
{ {
CCASSERT(index>=0 && amount>=0 && index+amount<=_totalQuads, "removeQuadAtIndex: index + amount out of bounds"); CCASSERT(index>=0 && amount>=0 && index+amount<=_totalQuads, "removeQuadAtIndex: index + amount out of bounds");
int remaining = (_totalQuads) - (index + amount); long remaining = (_totalQuads) - (index + amount);
_totalQuads -= amount; _totalQuads -= amount;
@ -449,14 +450,14 @@ void TextureAtlas::removeAllQuads()
} }
// TextureAtlas - Resize // TextureAtlas - Resize
bool TextureAtlas::resizeCapacity(int newCapacity) bool TextureAtlas::resizeCapacity(long newCapacity)
{ {
CCASSERT(newCapacity>=0, "capacity >= 0"); CCASSERT(newCapacity>=0, "capacity >= 0");
if( newCapacity == _capacity ) if( newCapacity == _capacity )
{ {
return true; return true;
} }
int oldCapactiy = _capacity; long oldCapactiy = _capacity;
// update capacity and totolQuads // update capacity and totolQuads
_totalQuads = MIN(_totalQuads, newCapacity); _totalQuads = MIN(_totalQuads, newCapacity);
_capacity = newCapacity; _capacity = newCapacity;
@ -523,13 +524,13 @@ bool TextureAtlas::resizeCapacity(int newCapacity)
return true; return true;
} }
void TextureAtlas::increaseTotalQuadsWith(int amount) void TextureAtlas::increaseTotalQuadsWith(long amount)
{ {
CCASSERT(amount>=0, "amount >= 0"); CCASSERT(amount>=0, "amount >= 0");
_totalQuads += amount; _totalQuads += amount;
} }
void TextureAtlas::moveQuadsFromIndex(int oldIndex, int amount, int newIndex) void TextureAtlas::moveQuadsFromIndex(long oldIndex, long amount, long newIndex)
{ {
CCASSERT(oldIndex>=0 && amount>=0 && newIndex>=0, "values must be >= 0"); CCASSERT(oldIndex>=0 && amount>=0 && newIndex>=0, "values must be >= 0");
CCASSERT(newIndex + amount <= _totalQuads, "insertQuadFromIndex:atIndex: Invalid index"); CCASSERT(newIndex + amount <= _totalQuads, "insertQuadFromIndex:atIndex: Invalid index");
@ -561,7 +562,7 @@ void TextureAtlas::moveQuadsFromIndex(int oldIndex, int amount, int newIndex)
_dirty = true; _dirty = true;
} }
void TextureAtlas::moveQuadsFromIndex(int index, int newIndex) void TextureAtlas::moveQuadsFromIndex(long index, long newIndex)
{ {
CCASSERT(index>=0 && newIndex>=0, "values must be >= 0"); CCASSERT(index>=0 && newIndex>=0, "values must be >= 0");
CCASSERT(newIndex + (_totalQuads - index) <= _capacity, "moveQuadsFromIndex move is out of bounds"); CCASSERT(newIndex + (_totalQuads - index) <= _capacity, "moveQuadsFromIndex move is out of bounds");
@ -569,14 +570,14 @@ void TextureAtlas::moveQuadsFromIndex(int index, int newIndex)
memmove(_quads + newIndex,_quads + index, (_totalQuads - index) * sizeof(_quads[0])); memmove(_quads + newIndex,_quads + index, (_totalQuads - index) * sizeof(_quads[0]));
} }
void TextureAtlas::fillWithEmptyQuadsFromIndex(int index, int amount) void TextureAtlas::fillWithEmptyQuadsFromIndex(long index, long amount)
{ {
CCASSERT(index>=0 && amount>=0, "values must be >= 0"); CCASSERT(index>=0 && amount>=0, "values must be >= 0");
V3F_C4B_T2F_Quad quad; V3F_C4B_T2F_Quad quad;
memset(&quad, 0, sizeof(quad)); memset(&quad, 0, sizeof(quad));
int to = index + amount; long to = index + amount;
for (int i = index ; i < to ; i++) for (long i = index ; i < to ; i++)
{ {
_quads[i] = quad; _quads[i] = quad;
} }
@ -589,13 +590,13 @@ void TextureAtlas::drawQuads()
this->drawNumberOfQuads(_totalQuads, 0); this->drawNumberOfQuads(_totalQuads, 0);
} }
void TextureAtlas::drawNumberOfQuads(int numberOfQuads) void TextureAtlas::drawNumberOfQuads(long numberOfQuads)
{ {
CCASSERT(numberOfQuads>=0, "numberOfQuads must be >= 0"); CCASSERT(numberOfQuads>=0, "numberOfQuads must be >= 0");
this->drawNumberOfQuads(numberOfQuads, 0); this->drawNumberOfQuads(numberOfQuads, 0);
} }
void TextureAtlas::drawNumberOfQuads(int numberOfQuads, int start) void TextureAtlas::drawNumberOfQuads(long numberOfQuads, long start)
{ {
CCASSERT(numberOfQuads>=0 && start>=0, "numberOfQuads and start must be >= 0"); CCASSERT(numberOfQuads>=0 && start>=0, "numberOfQuads and start must be >= 0");

View File

@ -59,13 +59,13 @@ public:
/** creates a TextureAtlas with an filename and with an initial capacity for Quads. /** creates a TextureAtlas with an filename and with an initial capacity for Quads.
* The TextureAtlas capacity can be increased in runtime. * The TextureAtlas capacity can be increased in runtime.
*/ */
static TextureAtlas* create(const char* file , int capacity); static TextureAtlas* create(const char* file , long capacity);
/** creates a TextureAtlas with a previously initialized Texture2D object, and /** creates a TextureAtlas with a previously initialized Texture2D object, and
* with an initial capacity for n Quads. * with an initial capacity for n Quads.
* The TextureAtlas capacity can be increased in runtime. * The TextureAtlas capacity can be increased in runtime.
*/ */
static TextureAtlas* createWithTexture(Texture2D *texture, int capacity); static TextureAtlas* createWithTexture(Texture2D *texture, long capacity);
/** /**
* @js ctor * @js ctor
*/ */
@ -81,7 +81,7 @@ public:
* *
* WARNING: Do not reinitialize the TextureAtlas because it will leak memory (issue #706) * WARNING: Do not reinitialize the TextureAtlas because it will leak memory (issue #706)
*/ */
bool initWithFile(const char* file, int capacity); bool initWithFile(const char* file, long capacity);
/** initializes a TextureAtlas with a previously initialized Texture2D object, and /** initializes a TextureAtlas with a previously initialized Texture2D object, and
* with an initial capacity for Quads. * with an initial capacity for Quads.
@ -89,43 +89,43 @@ public:
* *
* WARNING: Do not reinitialize the TextureAtlas because it will leak memory (issue #706) * WARNING: Do not reinitialize the TextureAtlas because it will leak memory (issue #706)
*/ */
bool initWithTexture(Texture2D *texture, int capacity); bool initWithTexture(Texture2D *texture, long capacity);
/** updates a Quad (texture, vertex and color) at a certain index /** updates a Quad (texture, vertex and color) at a certain index
* index must be between 0 and the atlas capacity - 1 * index must be between 0 and the atlas capacity - 1
@since v0.8 @since v0.8
*/ */
void updateQuad(V3F_C4B_T2F_Quad* quad, int index); void updateQuad(V3F_C4B_T2F_Quad* quad, long index);
/** Inserts a Quad (texture, vertex and color) at a certain index /** Inserts a Quad (texture, vertex and color) at a certain index
index must be between 0 and the atlas capacity - 1 index must be between 0 and the atlas capacity - 1
@since v0.8 @since v0.8
*/ */
void insertQuad(V3F_C4B_T2F_Quad* quad, int index); void insertQuad(V3F_C4B_T2F_Quad* quad, long index);
/** Inserts a c array of quads at a given index /** Inserts a c array of quads at a given index
index must be between 0 and the atlas capacity - 1 index must be between 0 and the atlas capacity - 1
this method doesn't enlarge the array when amount + index > totalQuads this method doesn't enlarge the array when amount + index > totalQuads
@since v1.1 @since v1.1
*/ */
void insertQuads(V3F_C4B_T2F_Quad* quads, int index, int amount); void insertQuads(V3F_C4B_T2F_Quad* quads, long index, long amount);
/** Removes the quad that is located at a certain index and inserts it at a new index /** Removes the quad that is located at a certain index and inserts it at a new index
This operation is faster than removing and inserting in a quad in 2 different steps This operation is faster than removing and inserting in a quad in 2 different steps
@since v0.7.2 @since v0.7.2
*/ */
void insertQuadFromIndex(int fromIndex, int newIndex); void insertQuadFromIndex(long fromIndex, long newIndex);
/** removes a quad at a given index number. /** removes a quad at a given index number.
The capacity remains the same, but the total number of quads to be drawn is reduced in 1 The capacity remains the same, but the total number of quads to be drawn is reduced in 1
@since v0.7.2 @since v0.7.2
*/ */
void removeQuadAtIndex(int index); void removeQuadAtIndex(long index);
/** removes a amount of quads starting from index /** removes a amount of quads starting from index
@since 1.1 @since 1.1
*/ */
void removeQuadsAtIndex(int index, int amount); void removeQuadsAtIndex(long index, long amount);
/** removes all Quads. /** removes all Quads.
The TextureAtlas capacity remains untouched. No memory is freed. The TextureAtlas capacity remains untouched. No memory is freed.
The total number of quads to be drawn will be 0 The total number of quads to be drawn will be 0
@ -138,19 +138,19 @@ public:
* It returns true if the resize was successful. * It returns true if the resize was successful.
* If it fails to resize the capacity it will return false with a new capacity of 0. * If it fails to resize the capacity it will return false with a new capacity of 0.
*/ */
bool resizeCapacity(int capacity); bool resizeCapacity(long capacity);
/** /**
Used internally by ParticleBatchNode Used internally by ParticleBatchNode
don't use this unless you know what you're doing don't use this unless you know what you're doing
@since 1.1 @since 1.1
*/ */
void increaseTotalQuadsWith(int amount); void increaseTotalQuadsWith(long amount);
/** Moves an amount of quads from oldIndex at newIndex /** Moves an amount of quads from oldIndex at newIndex
@since v1.1 @since v1.1
*/ */
void moveQuadsFromIndex(int oldIndex, int amount, int newIndex); void moveQuadsFromIndex(long oldIndex, long amount, long newIndex);
/** /**
Moves quads from index till totalQuads to the newIndex Moves quads from index till totalQuads to the newIndex
@ -158,26 +158,26 @@ public:
This method doesn't enlarge the array if newIndex + quads to be moved > capacity This method doesn't enlarge the array if newIndex + quads to be moved > capacity
@since 1.1 @since 1.1
*/ */
void moveQuadsFromIndex(int index, int newIndex); void moveQuadsFromIndex(long index, long newIndex);
/** /**
Ensures that after a realloc quads are still empty Ensures that after a realloc quads are still empty
Used internally by ParticleBatchNode Used internally by ParticleBatchNode
@since 1.1 @since 1.1
*/ */
void fillWithEmptyQuadsFromIndex(int index, int amount); void fillWithEmptyQuadsFromIndex(long index, long amount);
/** draws n quads /** draws n quads
* n can't be greater than the capacity of the Atlas * n can't be greater than the capacity of the Atlas
*/ */
void drawNumberOfQuads(int n); void drawNumberOfQuads(long n);
/** draws n quads from an index (offset). /** draws n quads from an index (offset).
n + start can't be greater than the capacity of the atlas n + start can't be greater than the capacity of the atlas
@since v1.0 @since v1.0
*/ */
void drawNumberOfQuads(int numberOfQuads, int start); void drawNumberOfQuads(long numberOfQuads, long start);
/** draws all the Atlas's Quads /** draws all the Atlas's Quads
*/ */
@ -197,10 +197,10 @@ public:
const char* description() const; const char* description() const;
/** Gets the quantity of quads that are going to be drawn */ /** Gets the quantity of quads that are going to be drawn */
int getTotalQuads() const; long getTotalQuads() const;
/** Gets the quantity of quads that can be stored with the current texture atlas size */ /** Gets the quantity of quads that can be stored with the current texture atlas size */
int getCapacity() const; long getCapacity() const;
/** Gets the texture of the texture atlas */ /** Gets the texture of the texture atlas */
Texture2D* getTexture() const; Texture2D* getTexture() const;
@ -226,9 +226,9 @@ protected:
GLuint _buffersVBO[2]; //0: vertex 1: indices GLuint _buffersVBO[2]; //0: vertex 1: indices
bool _dirty; //indicates whether or not the array buffer of the VBO needs to be updated bool _dirty; //indicates whether or not the array buffer of the VBO needs to be updated
/** quantity of quads that are going to be drawn */ /** quantity of quads that are going to be drawn */
int _totalQuads; long _totalQuads;
/** quantity of quads that can be stored with the current texture atlas size */ /** quantity of quads that can be stored with the current texture atlas size */
int _capacity; long _capacity;
/** Texture of the texture atlas */ /** Texture of the texture atlas */
Texture2D* _texture; Texture2D* _texture;
/** Quads that are going to be rendered */ /** Quads that are going to be rendered */

View File

@ -51,19 +51,9 @@ NS_CC_BEGIN
// implementation TextureCache // implementation TextureCache
TextureCache* TextureCache::_sharedTextureCache = nullptr;
TextureCache * TextureCache::getInstance() TextureCache * TextureCache::getInstance()
{ {
if (!_sharedTextureCache) return Director::getInstance()->getTextureCache();
{
#ifdef EMSCRIPTEN
_sharedTextureCache = new TextureCacheEmscripten();
#else
_sharedTextureCache = new TextureCache();
#endif // EMSCRIPTEN
}
return _sharedTextureCache;
} }
TextureCache::TextureCache() TextureCache::TextureCache()
@ -73,7 +63,6 @@ TextureCache::TextureCache()
, _needQuit(false) , _needQuit(false)
, _asyncRefCount(0) , _asyncRefCount(0)
{ {
CCASSERT(_sharedTextureCache == nullptr, "Attempted to allocate a second instance of a singleton.");
} }
TextureCache::~TextureCache() TextureCache::~TextureCache()
@ -84,20 +73,19 @@ TextureCache::~TextureCache()
(it->second)->release(); (it->second)->release();
CC_SAFE_DELETE(_loadingThread); CC_SAFE_DELETE(_loadingThread);
_sharedTextureCache = nullptr;
} }
void TextureCache::destroyInstance() void TextureCache::destroyInstance()
{ {
if (_sharedTextureCache) }
{
// notify sub thread to quick TextureCache * TextureCache::sharedTextureCache()
_sharedTextureCache->_needQuit = true; {
_sharedTextureCache->_sleepCondition.notify_one(); return Director::getInstance()->getTextureCache();
if (_sharedTextureCache->_loadingThread) _sharedTextureCache->_loadingThread->join(); }
CC_SAFE_RELEASE_NULL(_sharedTextureCache); void TextureCache::purgeSharedTextureCache()
} {
} }
const char* TextureCache::description() const const char* TextureCache::description() const
@ -260,7 +248,7 @@ void TextureCache::addImageAsyncCallBack(float dt)
#if CC_ENABLE_CACHE_TEXTURE_DATA #if CC_ENABLE_CACHE_TEXTURE_DATA
// cache the texture file name // cache the texture file name
VolatileTexture::addImageTexture(texture, filename); VolatileTextureMgr::addImageTexture(texture, filename);
#endif #endif
// cache the texture. retain it, since it is added in the map // cache the texture. retain it, since it is added in the map
_textures.insert( std::make_pair(filename, texture) ); _textures.insert( std::make_pair(filename, texture) );
@ -320,7 +308,7 @@ Texture2D * TextureCache::addImage(const std::string &path)
{ {
#if CC_ENABLE_CACHE_TEXTURE_DATA #if CC_ENABLE_CACHE_TEXTURE_DATA
// cache the texture file name // cache the texture file name
VolatileTexture::addImageTexture(texture, fullpath.c_str()); VolatileTextureMgr::addImageTexture(texture, fullpath.c_str());
#endif #endif
// texture already retained, no need to re-retain it // texture already retained, no need to re-retain it
_textures.insert( std::make_pair(fullpath, texture) ); _textures.insert( std::make_pair(fullpath, texture) );
@ -370,7 +358,7 @@ Texture2D* TextureCache::addImage(Image *image, const std::string &key)
} while (0); } while (0);
#if CC_ENABLE_CACHE_TEXTURE_DATA #if CC_ENABLE_CACHE_TEXTURE_DATA
VolatileTexture::addImage(texture, image); VolatileTextureMgr::addImage(texture, image);
#endif #endif
return texture; return texture;
@ -438,9 +426,18 @@ Texture2D* TextureCache::getTextureForKey(const std::string &key) const
void TextureCache::reloadAllTextures() void TextureCache::reloadAllTextures()
{ {
#if CC_ENABLE_CACHE_TEXTURE_DATA //will do nothing
VolatileTexture::reloadAllTextures(); // #if CC_ENABLE_CACHE_TEXTURE_DATA
#endif // VolatileTextureMgr::reloadAllTextures();
// #endif
}
void TextureCache::waitForQuit()
{
// notify sub thread to quick
_needQuit = true;
_sleepCondition.notify_one();
if (_loadingThread) _loadingThread->join();
} }
void TextureCache::dumpCachedTextureInfo() const void TextureCache::dumpCachedTextureInfo() const
@ -453,7 +450,7 @@ void TextureCache::dumpCachedTextureInfo() const
Texture2D* tex = it->second; Texture2D* tex = it->second;
unsigned int bpp = tex->getBitsPerPixelForFormat(); unsigned int bpp = tex->getBitsPerPixelForFormat();
// Each texture takes up width * height * bytesPerPixel bytes. // Each texture takes up width * height * bytesPerPixel bytes.
unsigned int bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8; long bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8;
totalBytes += bytes; totalBytes += bytes;
count++; count++;
log("cocos2d: \"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB", log("cocos2d: \"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB",
@ -471,8 +468,8 @@ void TextureCache::dumpCachedTextureInfo() const
#if CC_ENABLE_CACHE_TEXTURE_DATA #if CC_ENABLE_CACHE_TEXTURE_DATA
std::list<VolatileTexture*> VolatileTexture::_textures; std::list<VolatileTexture*> VolatileTextureMgr::_textures;
bool VolatileTexture::_isReloading = false; bool VolatileTextureMgr::_isReloading = false;
VolatileTexture::VolatileTexture(Texture2D *t) VolatileTexture::VolatileTexture(Texture2D *t)
: _texture(t) : _texture(t)
@ -487,16 +484,14 @@ VolatileTexture::VolatileTexture(Texture2D *t)
_texParams.magFilter = GL_LINEAR; _texParams.magFilter = GL_LINEAR;
_texParams.wrapS = GL_CLAMP_TO_EDGE; _texParams.wrapS = GL_CLAMP_TO_EDGE;
_texParams.wrapT = GL_CLAMP_TO_EDGE; _texParams.wrapT = GL_CLAMP_TO_EDGE;
_textures.push_back(this);
} }
VolatileTexture::~VolatileTexture() VolatileTexture::~VolatileTexture()
{ {
_textures.remove(this);
CC_SAFE_RELEASE(_uiImage); CC_SAFE_RELEASE(_uiImage);
} }
void VolatileTexture::addImageTexture(Texture2D *tt, const char* imageFileName) void VolatileTextureMgr::addImageTexture(Texture2D *tt, const char* imageFileName)
{ {
if (_isReloading) if (_isReloading)
{ {
@ -505,20 +500,20 @@ void VolatileTexture::addImageTexture(Texture2D *tt, const char* imageFileName)
VolatileTexture *vt = findVolotileTexture(tt); VolatileTexture *vt = findVolotileTexture(tt);
vt->_cashedImageType = kImageFile; vt->_cashedImageType = VolatileTexture::kImageFile;
vt->_fileName = imageFileName; vt->_fileName = imageFileName;
vt->_pixelFormat = tt->getPixelFormat(); vt->_pixelFormat = tt->getPixelFormat();
} }
void VolatileTexture::addImage(Texture2D *tt, Image *image) void VolatileTextureMgr::addImage(Texture2D *tt, Image *image)
{ {
VolatileTexture *vt = findVolotileTexture(tt); VolatileTexture *vt = findVolotileTexture(tt);
image->retain(); image->retain();
vt->_uiImage = image; vt->_uiImage = image;
vt->_cashedImageType = kImage; vt->_cashedImageType = VolatileTexture::kImage;
} }
VolatileTexture* VolatileTexture::findVolotileTexture(Texture2D *tt) VolatileTexture* VolatileTextureMgr::findVolotileTexture(Texture2D *tt)
{ {
VolatileTexture *vt = 0; VolatileTexture *vt = 0;
auto i = _textures.begin(); auto i = _textures.begin();
@ -535,12 +530,13 @@ VolatileTexture* VolatileTexture::findVolotileTexture(Texture2D *tt)
if (! vt) if (! vt)
{ {
vt = new VolatileTexture(tt); vt = new VolatileTexture(tt);
_textures.push_back(vt);
} }
return vt; return vt;
} }
void VolatileTexture::addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize) void VolatileTextureMgr::addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize)
{ {
if (_isReloading) if (_isReloading)
{ {
@ -549,14 +545,14 @@ void VolatileTexture::addDataTexture(Texture2D *tt, void* data, int dataLen, Tex
VolatileTexture *vt = findVolotileTexture(tt); VolatileTexture *vt = findVolotileTexture(tt);
vt->_cashedImageType = kImageData; vt->_cashedImageType = VolatileTexture::kImageData;
vt->_textureData = data; vt->_textureData = data;
vt->_dataLen = dataLen; vt->_dataLen = dataLen;
vt->_pixelFormat = pixelFormat; vt->_pixelFormat = pixelFormat;
vt->_textureSize = contentSize; vt->_textureSize = contentSize;
} }
void VolatileTexture::addStringTexture(Texture2D *tt, const char* text, const FontDefinition& fontDefinition) void VolatileTextureMgr::addStringTexture(Texture2D *tt, const char* text, const FontDefinition& fontDefinition)
{ {
if (_isReloading) if (_isReloading)
{ {
@ -565,12 +561,12 @@ void VolatileTexture::addStringTexture(Texture2D *tt, const char* text, const Fo
VolatileTexture *vt = findVolotileTexture(tt); VolatileTexture *vt = findVolotileTexture(tt);
vt->_cashedImageType = kString; vt->_cashedImageType = VolatileTexture::kString;
vt->_text = text; vt->_text = text;
vt->_fontDefinition = fontDefinition; vt->_fontDefinition = fontDefinition;
} }
void VolatileTexture::setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams) void VolatileTextureMgr::setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams)
{ {
VolatileTexture *vt = findVolotileTexture(t); VolatileTexture *vt = findVolotileTexture(t);
@ -584,7 +580,7 @@ void VolatileTexture::setTexParameters(Texture2D *t, const Texture2D::TexParams
vt->_texParams.wrapT = texParams.wrapT; vt->_texParams.wrapT = texParams.wrapT;
} }
void VolatileTexture::removeTexture(Texture2D *t) void VolatileTextureMgr::removeTexture(Texture2D *t)
{ {
auto i = _textures.begin(); auto i = _textures.begin();
while (i != _textures.end()) while (i != _textures.end())
@ -592,13 +588,14 @@ void VolatileTexture::removeTexture(Texture2D *t)
VolatileTexture *vt = *i++; VolatileTexture *vt = *i++;
if (vt->_texture == t) if (vt->_texture == t)
{ {
_textures.remove(vt);
delete vt; delete vt;
break; break;
} }
} }
} }
void VolatileTexture::reloadAllTextures() void VolatileTextureMgr::reloadAllTextures()
{ {
_isReloading = true; _isReloading = true;
@ -611,13 +608,13 @@ void VolatileTexture::reloadAllTextures()
switch (vt->_cashedImageType) switch (vt->_cashedImageType)
{ {
case kImageFile: case VolatileTexture::kImageFile:
{ {
Image* image = new Image(); Image* image = new Image();
unsigned long nSize = 0; long size = 0;
unsigned char* pBuffer = FileUtils::getInstance()->getFileData(vt->_fileName.c_str(), "rb", &nSize); unsigned char* pBuffer = FileUtils::getInstance()->getFileData(vt->_fileName.c_str(), "rb", &size);
if (image && image->initWithImageData(pBuffer, nSize)) if (image && image->initWithImageData(pBuffer, size))
{ {
Texture2D::PixelFormat oldPixelFormat = Texture2D::getDefaultAlphaPixelFormat(); Texture2D::PixelFormat oldPixelFormat = Texture2D::getDefaultAlphaPixelFormat();
Texture2D::setDefaultAlphaPixelFormat(vt->_pixelFormat); Texture2D::setDefaultAlphaPixelFormat(vt->_pixelFormat);
@ -629,7 +626,7 @@ void VolatileTexture::reloadAllTextures()
CC_SAFE_RELEASE(image); CC_SAFE_RELEASE(image);
} }
break; break;
case kImageData: case VolatileTexture::kImageData:
{ {
vt->_texture->initWithData(vt->_textureData, vt->_texture->initWithData(vt->_textureData,
vt->_dataLen, vt->_dataLen,
@ -639,12 +636,12 @@ void VolatileTexture::reloadAllTextures()
vt->_textureSize); vt->_textureSize);
} }
break; break;
case kString: case VolatileTexture::kString:
{ {
vt->_texture->initWithString(vt->_text.c_str(), vt->_fontDefinition); vt->_texture->initWithString(vt->_text.c_str(), vt->_fontDefinition);
} }
break; break;
case kImage: case VolatileTexture::kImage:
{ {
vt->_texture->initWithImage(vt->_uiImage); vt->_texture->initWithImage(vt->_uiImage);
} }

View File

@ -50,6 +50,10 @@ NS_CC_BEGIN
* @addtogroup textures * @addtogroup textures
* @{ * @{
*/ */
/*
* from version 3.0, TextureCache will never to treated as a singleton, it will be owned by director.
* all call by TextureCache::getInstance() should be replaced by Director::getInstance()->getTextureCache()
*/
/** @brief Singleton that handles the loading of textures /** @brief Singleton that handles the loading of textures
* Once the texture is loaded, the next time it will return * Once the texture is loaded, the next time it will return
@ -59,23 +63,24 @@ class CC_DLL TextureCache : public Object
{ {
public: public:
/** Returns the shared instance of the cache */ /** Returns the shared instance of the cache */
static TextureCache * getInstance(); CC_DEPRECATED_ATTRIBUTE static TextureCache * getInstance();
/** @deprecated Use getInstance() instead */ /** @deprecated Use getInstance() instead */
CC_DEPRECATED_ATTRIBUTE static TextureCache * sharedTextureCache() { return TextureCache::getInstance(); } CC_DEPRECATED_ATTRIBUTE static TextureCache * sharedTextureCache();
/** purges the cache. It releases the retained instance. /** purges the cache. It releases the retained instance.
@since v0.99.0 @since v0.99.0
*/ */
static void destroyInstance(); CC_DEPRECATED_ATTRIBUTE static void destroyInstance();
/** @deprecated Use destroyInstance() instead */ /** @deprecated Use destroyInstance() instead */
CC_DEPRECATED_ATTRIBUTE static void purgeSharedTextureCache() { return TextureCache::destroyInstance(); } CC_DEPRECATED_ATTRIBUTE static void purgeSharedTextureCache();
/** Reload all textures /** Reload all textures
It's only useful when the value of CC_ENABLE_CACHE_TEXTURE_DATA is 1 should not call it, called by frame work
now the function do nothing, use VolatileTextureMgr::reloadAllTextures
*/ */
static void reloadAllTextures(); CC_DEPRECATED_ATTRIBUTE static void reloadAllTextures();
public: public:
/** /**
@ -158,6 +163,10 @@ public:
*/ */
void dumpCachedTextureInfo() const; void dumpCachedTextureInfo() const;
//wait for texture cahe to quit befor destroy instance
//called by director, please do not called outside
void waitForQuit();
private: private:
void addImageAsyncCallBack(float dt); void addImageAsyncCallBack(float dt);
void loadImage(); void loadImage();
@ -196,8 +205,6 @@ protected:
int _asyncRefCount; int _asyncRefCount;
std::unordered_map<std::string, Texture2D*> _textures; std::unordered_map<std::string, Texture2D*> _textures;
static TextureCache *_sharedTextureCache;
}; };
#if CC_ENABLE_CACHE_TEXTURE_DATA #if CC_ENABLE_CACHE_TEXTURE_DATA
@ -212,7 +219,7 @@ class VolatileTexture
kImage, kImage,
}ccCachedImageType; }ccCachedImageType;
public: private:
VolatileTexture(Texture2D *t); VolatileTexture(Texture2D *t);
/** /**
* @js NA * @js NA
@ -220,25 +227,8 @@ public:
*/ */
~VolatileTexture(); ~VolatileTexture();
static void addImageTexture(Texture2D *tt, const char* imageFileName);
static void addStringTexture(Texture2D *tt, const char* text, const FontDefinition& fontDefinition);
static void addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize);
static void addImage(Texture2D *tt, Image *image);
static void setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams);
static void removeTexture(Texture2D *t);
static void reloadAllTextures();
public:
static std::list<VolatileTexture*> _textures;
static bool _isReloading;
private:
// find VolatileTexture by Texture2D*
// if not found, create a new one
static VolatileTexture* findVolotileTexture(Texture2D *tt);
protected: protected:
friend class VolatileTextureMgr;
Texture2D *_texture; Texture2D *_texture;
Image *_uiImage; Image *_uiImage;
@ -257,6 +247,26 @@ protected:
FontDefinition _fontDefinition; FontDefinition _fontDefinition;
}; };
class VolatileTextureMgr
{
public:
static void addImageTexture(Texture2D *tt, const char* imageFileName);
static void addStringTexture(Texture2D *tt, const char* text, const FontDefinition& fontDefinition);
static void addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize);
static void addImage(Texture2D *tt, Image *image);
static void setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams);
static void removeTexture(Texture2D *t);
static void reloadAllTextures();
public:
static std::list<VolatileTexture*> _textures;
static bool _isReloading;
private:
// find VolatileTexture by Texture2D*
// if not found, create a new one
static VolatileTexture* findVolotileTexture(Texture2D *tt);
};
#endif #endif
// end of textures group // end of textures group

View File

@ -58,7 +58,7 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLEle
tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument(); tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument();
*doc = xmlDoc; *doc = xmlDoc;
//CCFileData data(UserDefault::getInstance()->getXMLFilePath().c_str(),"rt"); //CCFileData data(UserDefault::getInstance()->getXMLFilePath().c_str(),"rt");
unsigned long nSize; long nSize;
const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &nSize); const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &nSize);
//const char* pXmlBuffer = (const char*)data.getBuffer(); //const char* pXmlBuffer = (const char*)data.getBuffer();
if(NULL == pXmlBuffer) if(NULL == pXmlBuffer)
@ -66,7 +66,7 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLEle
CCLOG("can not read xml file"); CCLOG("can not read xml file");
break; break;
} }
xmlDoc->Parse(pXmlBuffer); xmlDoc->Parse(pXmlBuffer, nSize);
delete[] pXmlBuffer; delete[] pXmlBuffer;
// get root node // get root node
*rootNode = xmlDoc->RootElement(); *rootNode = xmlDoc->RootElement();

View File

@ -73,8 +73,8 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLDoc
{ {
tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument(); tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument();
*doc = xmlDoc; *doc = xmlDoc;
unsigned long nSize; long size;
const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &nSize); const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &size);
//const char* pXmlBuffer = (const char*)data.getBuffer(); //const char* pXmlBuffer = (const char*)data.getBuffer();
if(NULL == pXmlBuffer) if(NULL == pXmlBuffer)
{ {

View File

@ -74,8 +74,8 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLDoc
{ {
tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument(); tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument();
*doc = xmlDoc; *doc = xmlDoc;
unsigned long nSize; long size;
const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &nSize); const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &size);
//const char* pXmlBuffer = (const char*)data.getBuffer(); //const char* pXmlBuffer = (const char*)data.getBuffer();
if(NULL == pXmlBuffer) if(NULL == pXmlBuffer)
{ {

151
cocos/2d/CMakeLists.txt Normal file
View File

@ -0,0 +1,151 @@
set(COCOS2D_SRC
CCAction.cpp
CCActionCamera.cpp
CCActionEase.cpp
CCActionGrid.cpp
CCActionGrid3D.cpp
CCActionInstant.cpp
CCActionInterval.cpp
CCActionManager.cpp
CCActionPageTurn3D.cpp
CCActionProgressTimer.cpp
CCActionTiledGrid.cpp
CCActionCatmullRom.cpp
CCActionTween.cpp
CCAtlasNode.cpp
CCNode.cpp
CCEventAcceleration.cpp
CCEventListenerAcceleration.cpp
CCEvent.cpp
CCEventDispatcher.cpp
CCEventListener.cpp
CCEventKeyboard.cpp
CCEventListenerKeyboard.cpp
CCEventMouse.cpp
CCEventListenerMouse.cpp
CCTouch.cpp
CCEventTouch.cpp
CCEventListenerTouch.cpp
CCEventCustom.cpp
CCEventListenerCustom.cpp
CCDrawingPrimitives.cpp
CCDrawNode.cpp
CCGrabber.cpp
CCGrid.cpp
CCFont.cpp
CCFontAtlas.cpp
CCFontAtlasCache.cpp
CCFontAtlasFactory.cpp
CCFontDefinition.cpp
CCFontFNT.cpp
CCFontFreeType.cpp
CCLabel.cpp
CCLabelAtlas.cpp
CCLabelBMFont.cpp
CCLabelTTF.cpp
CCLabelTextFormatter.cpp
CCTextImage.cpp
CCLayer.cpp
CCScene.cpp
CCTransition.cpp
CCTransitionPageTurn.cpp
CCTransitionProgress.cpp
CCMenu.cpp
CCMenuItem.cpp
CCMotionStreak.cpp
CCProgressTimer.cpp
CCClippingNode.cpp
CCRenderTexture.cpp
CCParticleExamples.cpp
CCParticleSystem.cpp
CCParticleSystemQuad.cpp
CCParticleBatchNode.cpp
CCScriptSupport.cpp
CCAnimation.cpp
CCAnimationCache.cpp
CCSprite.cpp
CCSpriteBatchNode.cpp
CCSpriteFrame.cpp
CCSpriteFrameCache.cpp
ccUTF8.cpp
CCProfiling.cpp
CCUserDefault.cpp
TransformUtils.cpp
base64.cpp
ccUtils.cpp
CCVertex.cpp
CCNotificationCenter.cpp
TGAlib.cpp
ZipUtils.cpp
ccCArray.cpp
CCComponent.cpp
CCComponentContainer.cpp
CCIMEDispatcher.cpp
CCTextFieldTTF.cpp
CCTexture2D.cpp
CCTextureAtlas.cpp
CCTextureCache.cpp
CCParallaxNode.cpp
CCTMXLayer.cpp
CCTMXObjectGroup.cpp
CCTMXTiledMap.cpp
CCTMXXMLParser.cpp
CCTileMapAtlas.cpp
CCGLProgram.cpp
ccGLStateCache.cpp
CCShaderCache.cpp
ccShaders.cpp
CCCamera.cpp
CCConfiguration.cpp
CCDirector.cpp
CCScheduler.cpp
ccFPSImages.c
ccTypes.cpp
cocos2d.cpp
CCDeprecated.cpp
platform/CCSAXParser.cpp
platform/CCThread.cpp
platform/CCEGLViewProtocol.cpp
platform/CCFileUtils.cpp
platform/linux/CCStdC.cpp
platform/linux/CCFileUtilsLinux.cpp
platform/linux/CCCommon.cpp
platform/linux/CCApplication.cpp
platform/linux/CCEGLView.cpp
platform/linux/CCImage.cpp
platform/linux/CCDevice.cpp
)
include(../physics/CMakeLists.txt)
add_library(cocos2d STATIC
${COCOS2D_SRC}
${COCOS_PHYSICS_SRC}
)
target_link_libraries(cocos2d
cocosbase
chipmunk_static
tinyxml2
kazmath
unzip
jpeg
webp
tiff
freetype
fontconfig
png
pthread
glfw
GLEW
GL
X11
rt
z
)
set_target_properties(cocos2d
PROPERTIES
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib"
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib"
)

View File

@ -1,204 +0,0 @@
TARGET = libcocos2d.so
INCLUDES =
SOURCES = \
CCAction.cpp \
CCActionCamera.cpp \
CCActionEase.cpp \
CCActionGrid.cpp \
CCActionGrid3D.cpp \
CCActionInstant.cpp \
CCActionInterval.cpp \
CCActionManager.cpp \
CCActionPageTurn3D.cpp \
CCActionProgressTimer.cpp \
CCActionTiledGrid.cpp \
CCActionCatmullRom.cpp \
CCActionTween.cpp \
CCAtlasNode.cpp \
CCNode.cpp \
../base/CCAffineTransform.cpp \
../base/CCAutoreleasePool.cpp \
../base/CCGeometry.cpp \
../base/CCNS.cpp \
../base/CCObject.cpp \
../base/CCSet.cpp \
../base/CCArray.cpp \
../base/CCDictionary.cpp \
../base/CCString.cpp \
../base/CCDataVisitor.cpp \
../base/CCData.cpp \
CCEventAcceleration.cpp \
CCEventListenerAcceleration.cpp \
CCEvent.cpp \
CCEventDispatcher.cpp \
CCEventListener.cpp \
CCEventKeyboard.cpp \
CCEventListenerKeyboard.cpp \
CCEventMouse.cpp \
CCEventListenerMouse.cpp \
CCTouch.cpp \
CCEventTouch.cpp \
CCEventListenerTouch.cpp \
CCEventCustom.cpp \
CCEventListenerCustom.cpp \
CCDrawingPrimitives.cpp \
CCDrawNode.cpp \
CCGrabber.cpp \
CCGrid.cpp \
CCFont.cpp \
CCFontAtlas.cpp \
CCFontAtlasCache.cpp \
CCFontAtlasFactory.cpp \
CCFontDefinition.cpp \
CCFontFNT.cpp \
CCFontFreeType.cpp \
CCLabel.cpp \
CCLabelAtlas.cpp \
CCLabelBMFont.cpp \
CCLabelTTF.cpp \
CCLabelTextFormatter.cpp \
CCTextImage.cpp \
CCLayer.cpp \
CCScene.cpp \
CCTransition.cpp \
CCTransitionPageTurn.cpp \
CCTransitionProgress.cpp \
CCMenu.cpp \
CCMenuItem.cpp \
CCMotionStreak.cpp \
CCProgressTimer.cpp \
CCClippingNode.cpp \
CCRenderTexture.cpp \
CCParticleExamples.cpp \
CCParticleSystem.cpp \
CCParticleSystemQuad.cpp \
CCParticleBatchNode.cpp \
../physics/box2d/CCPhysicsContactInfo.cpp \
../physics/box2d/CCPhysicsJointInfo.cpp \
../physics/box2d/CCPhysicsShapeInfo.cpp \
../physics/box2d/CCPhysicsBodyInfo.cpp \
../physics/box2d/CCPhysicsWorldInfo.cpp \
../physics/chipmunk/CCPhysicsContactInfo.cpp \
../physics/chipmunk/CCPhysicsJointInfo.cpp \
../physics/chipmunk/CCPhysicsShapeInfo.cpp \
../physics/chipmunk/CCPhysicsBodyInfo.cpp \
../physics/chipmunk/CCPhysicsWorldInfo.cpp \
../physics/CCPhysicsBody.cpp \
../physics/CCPhysicsContact.cpp \
../physics/CCPhysicsShape.cpp \
../physics/CCPhysicsJoint.cpp \
../physics/CCPhysicsWorld.cpp \
../platform/CCSAXParser.cpp \
../platform/CCThread.cpp \
../platform/CCEGLViewProtocol.cpp \
../platform/CCFileUtils.cpp \
../platform/linux/CCStdC.cpp \
../platform/linux/CCFileUtilsLinux.cpp \
../platform/linux/CCCommon.cpp \
../platform/linux/CCApplication.cpp \
../platform/linux/CCEGLView.cpp \
../platform/linux/CCImage.cpp \
../platform/linux/CCDevice.cpp \
../base/etc1.cpp \
../base/s3tc.cpp \
../base/atitc.cpp \
CCScriptSupport.cpp \
CCAnimation.cpp \
CCAnimationCache.cpp \
CCSprite.cpp \
CCSpriteBatchNode.cpp \
CCSpriteFrame.cpp \
CCSpriteFrameCache.cpp \
ccUTF8.cpp \
CCProfiling.cpp \
CCUserDefault.cpp \
TransformUtils.cpp \
base64.cpp \
ccUtils.cpp \
CCVertex.cpp \
CCNotificationCenter.cpp \
TGAlib.cpp \
../../external/tinyxml2/tinyxml2.cpp \
ZipUtils.cpp \
../../external/unzip/ioapi.cpp \
../../external/unzip/unzip.cpp \
ccCArray.cpp \
CCComponent.cpp \
CCComponentContainer.cpp \
CCIMEDispatcher.cpp \
CCTextFieldTTF.cpp \
CCTexture2D.cpp \
CCTextureAtlas.cpp \
CCTextureCache.cpp \
CCParallaxNode.cpp \
CCTMXLayer.cpp \
CCTMXObjectGroup.cpp \
CCTMXTiledMap.cpp \
CCTMXXMLParser.cpp \
CCTileMapAtlas.cpp \
CCGLProgram.cpp \
ccGLStateCache.cpp \
CCShaderCache.cpp \
ccShaders.cpp \
../math/kazmath/src/aabb.c \
../math/kazmath/src/plane.c \
../math/kazmath/src/vec2.c \
../math/kazmath/src/mat3.c \
../math/kazmath/src/quaternion.c \
../math/kazmath/src/vec3.c \
../math/kazmath/src/mat4.c \
../math/kazmath/src/ray2.c \
../math/kazmath/src/vec4.c \
../math/kazmath/src/neon_matrix_impl.c \
../math/kazmath/src/utility.c \
../math/kazmath/src/GL/mat4stack.c \
../math/kazmath/src/GL/matrix.c \
CCCamera.cpp \
CCConfiguration.cpp \
CCDirector.cpp \
CCScheduler.cpp \
ccFPSImages.c \
ccTypes.cpp \
cocos2d.cpp \
CCDeprecated.cpp
COCOS_ROOT = ../..
include cocos2dx.mk
CXXFLAGS += -Wno-sequence-point
CCFLAGS += -Wno-sequence-point
STATICLIBS += $(LIB_DIR)/libchipmunk.a
TARGET := $(LIB_DIR)/$(TARGET)
all: $(TARGET)
$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST)
@mkdir -p $(@D)
$(LOG_LINK)$(CXX) $(CXXFLAGS) $(OBJECTS) -shared -o $@ $(SHAREDLIBS) $(STATICLIBS) $(LIBS)
$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST)
@mkdir -p $(@D)
$(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@
$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST)
@mkdir -p $(@D)
$(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@
$(OBJ_DIR)/%.o: ../../%.cpp $(CORE_MAKEFILE_LIST)
@mkdir -p $(@D)
$(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@
$(OBJ_DIR)/%.o: %.c $(CORE_MAKEFILE_LIST)
@mkdir -p $(@D)
$(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@
$(OBJ_DIR)/%.o: ../%.c $(CORE_MAKEFILE_LIST)
@mkdir -p $(@D)
$(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@

View File

@ -198,8 +198,8 @@ tImageTGA * tgaLoad(const char *filename)
int mode,total; int mode,total;
tImageTGA *info = NULL; tImageTGA *info = NULL;
unsigned long nSize = 0; long size = 0;
unsigned char* pBuffer = FileUtils::getInstance()->getFileData(filename, "rb", &nSize); unsigned char* pBuffer = FileUtils::getInstance()->getFileData(filename, "rb", &size);
do do
{ {
@ -207,7 +207,7 @@ tImageTGA * tgaLoad(const char *filename)
info = (tImageTGA *)malloc(sizeof(tImageTGA)); info = (tImageTGA *)malloc(sizeof(tImageTGA));
// get the file header info // get the file header info
if (! tgaLoadHeader(pBuffer, nSize, info)) if (! tgaLoadHeader(pBuffer, size, info))
{ {
info->status = TGA_ERROR_MEMORY; info->status = TGA_ERROR_MEMORY;
break; break;
@ -245,11 +245,11 @@ tImageTGA * tgaLoad(const char *filename)
// finally load the image pixels // finally load the image pixels
if ( info->type == 10 ) if ( info->type == 10 )
{ {
bLoadImage = tgaLoadRLEImageData(pBuffer, nSize, info); bLoadImage = tgaLoadRLEImageData(pBuffer, size, info);
} }
else else
{ {
bLoadImage = tgaLoadImageData(pBuffer, nSize, info); bLoadImage = tgaLoadImageData(pBuffer, size, info);
} }
// check for errors when reading the pixels // check for errors when reading the pixels

View File

@ -39,7 +39,7 @@ bool ZipUtils::s_bEncryptionKeyIsValid = false;
// --------------------- ZipUtils --------------------- // --------------------- ZipUtils ---------------------
inline void ZipUtils::ccDecodeEncodedPvr(unsigned int *data, int len) inline void ZipUtils::ccDecodeEncodedPvr(unsigned int *data, long len)
{ {
const int enclen = 1024; const int enclen = 1024;
const int securelen = 512; const int securelen = 512;
@ -108,7 +108,7 @@ inline void ZipUtils::ccDecodeEncodedPvr(unsigned int *data, int len)
} }
} }
inline unsigned int ZipUtils::ccChecksumPvr(const unsigned int *data, int len) inline unsigned int ZipUtils::ccChecksumPvr(const unsigned int *data, long len)
{ {
unsigned int cs = 0; unsigned int cs = 0;
const int cslen = 128; const int cslen = 128;
@ -127,12 +127,12 @@ inline unsigned int ZipUtils::ccChecksumPvr(const unsigned int *data, int len)
// Should buffer factor be 1.5 instead of 2 ? // Should buffer factor be 1.5 instead of 2 ?
#define BUFFER_INC_FACTOR (2) #define BUFFER_INC_FACTOR (2)
int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int *outLength, unsigned int outLenghtHint) int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long *outLength, long outLenghtHint)
{ {
/* ret value */ /* ret value */
int err = Z_OK; int err = Z_OK;
int bufferSize = outLenghtHint; long bufferSize = outLenghtHint;
*out = new unsigned char[bufferSize]; *out = new unsigned char[bufferSize];
z_stream d_stream; /* decompression stream */ z_stream d_stream; /* decompression stream */
@ -192,9 +192,9 @@ int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength,
return err; return err;
} }
int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int outLengthHint) int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long outLengthHint)
{ {
unsigned int outLength = 0; long outLength = 0;
int err = ccInflateMemoryWithHint(in, inLength, out, &outLength, outLengthHint); int err = ccInflateMemoryWithHint(in, inLength, out, &outLength, outLengthHint);
if (err != Z_OK || *out == NULL) { if (err != Z_OK || *out == NULL) {
@ -223,7 +223,7 @@ int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength,
return outLength; return outLength;
} }
int ZipUtils::ccInflateMemory(unsigned char *in, unsigned int inLength, unsigned char **out) int ZipUtils::ccInflateMemory(unsigned char *in, long inLength, unsigned char **out)
{ {
// 256k for hint // 256k for hint
return ccInflateMemoryWithHint(in, inLength, out, 256 * 1024); return ccInflateMemoryWithHint(in, inLength, out, 256 * 1024);
@ -304,7 +304,7 @@ bool ZipUtils::ccIsCCZFile(const char *path)
// load file into memory // load file into memory
unsigned char* compressed = NULL; unsigned char* compressed = NULL;
unsigned long fileLen = 0; long fileLen = 0;
compressed = FileUtils::getInstance()->getFileData(path, "rb", &fileLen); compressed = FileUtils::getInstance()->getFileData(path, "rb", &fileLen);
if(NULL == compressed || 0 == fileLen) if(NULL == compressed || 0 == fileLen)
@ -316,7 +316,7 @@ bool ZipUtils::ccIsCCZFile(const char *path)
return ccIsCCZBuffer(compressed, fileLen); return ccIsCCZBuffer(compressed, fileLen);
} }
bool ZipUtils::ccIsCCZBuffer(const unsigned char *buffer, int len) bool ZipUtils::ccIsCCZBuffer(const unsigned char *buffer, long len)
{ {
if (len < sizeof(struct CCZHeader)) if (len < sizeof(struct CCZHeader))
{ {
@ -333,7 +333,7 @@ bool ZipUtils::ccIsGZipFile(const char *path)
// load file into memory // load file into memory
unsigned char* compressed = NULL; unsigned char* compressed = NULL;
unsigned long fileLen = 0; long fileLen = 0;
compressed = FileUtils::getInstance()->getFileData(path, "rb", &fileLen); compressed = FileUtils::getInstance()->getFileData(path, "rb", &fileLen);
if(NULL == compressed || 0 == fileLen) if(NULL == compressed || 0 == fileLen)
@ -345,7 +345,7 @@ bool ZipUtils::ccIsGZipFile(const char *path)
return ccIsGZipBuffer(compressed, fileLen); return ccIsGZipBuffer(compressed, fileLen);
} }
bool ZipUtils::ccIsGZipBuffer(const unsigned char *buffer, int len) bool ZipUtils::ccIsGZipBuffer(const unsigned char *buffer, long len)
{ {
if (len < 2) if (len < 2)
{ {
@ -356,7 +356,7 @@ bool ZipUtils::ccIsGZipBuffer(const unsigned char *buffer, int len)
} }
int ZipUtils::ccInflateCCZBuffer(const unsigned char *buffer, int bufferLen, unsigned char **out) int ZipUtils::ccInflateCCZBuffer(const unsigned char *buffer, long bufferLen, unsigned char **out)
{ {
struct CCZHeader *header = (struct CCZHeader*) buffer; struct CCZHeader *header = (struct CCZHeader*) buffer;
@ -454,7 +454,7 @@ int ZipUtils::ccInflateCCZFile(const char *path, unsigned char **out)
// load file into memory // load file into memory
unsigned char* compressed = NULL; unsigned char* compressed = NULL;
unsigned long fileLen = 0; long fileLen = 0;
compressed = FileUtils::getInstance()->getFileData(path, "rb", &fileLen); compressed = FileUtils::getInstance()->getFileData(path, "rb", &fileLen);
if(NULL == compressed || 0 == fileLen) if(NULL == compressed || 0 == fileLen)
@ -582,7 +582,7 @@ bool ZipFile::fileExists(const std::string &fileName) const
return ret; return ret;
} }
unsigned char *ZipFile::getFileData(const std::string &fileName, unsigned long *pSize) unsigned char *ZipFile::getFileData(const std::string &fileName, long *pSize)
{ {
unsigned char * pBuffer = NULL; unsigned char * pBuffer = NULL;
if (pSize) if (pSize)

View File

@ -64,7 +64,7 @@ namespace cocos2d
* *
@since v0.8.1 @since v0.8.1
*/ */
static int ccInflateMemory(unsigned char *in, unsigned int inLength, unsigned char **out); static int ccInflateMemory(unsigned char *in, long inLength, unsigned char **out);
/** /**
* Inflates either zlib or gzip deflated memory. The inflated memory is * Inflates either zlib or gzip deflated memory. The inflated memory is
@ -76,7 +76,7 @@ namespace cocos2d
* *
@since v1.0.0 @since v1.0.0
*/ */
static int ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int outLenghtHint); static int ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long outLenghtHint);
/** inflates a GZip file into memory /** inflates a GZip file into memory
* *
@ -100,7 +100,7 @@ namespace cocos2d
* *
* @since v3.0 * @since v3.0
*/ */
static bool ccIsGZipBuffer(const unsigned char *buffer, int len); static bool ccIsGZipBuffer(const unsigned char *buffer, long len);
/** inflates a CCZ file into memory /** inflates a CCZ file into memory
* *
@ -116,7 +116,7 @@ namespace cocos2d
* *
* @since v3.0 * @since v3.0
*/ */
static int ccInflateCCZBuffer(const unsigned char *buffer, int len, unsigned char **out); static int ccInflateCCZBuffer(const unsigned char *buffer, long len, unsigned char **out);
/** test a file is a CCZ format file or not /** test a file is a CCZ format file or not
* *
@ -132,7 +132,7 @@ namespace cocos2d
* *
* @since v3.0 * @since v3.0
*/ */
static bool ccIsCCZBuffer(const unsigned char *buffer, int len); static bool ccIsCCZBuffer(const unsigned char *buffer, long len);
/** Sets the pvr.ccz encryption key parts separately for added /** Sets the pvr.ccz encryption key parts separately for added
* security. * security.
@ -187,10 +187,10 @@ namespace cocos2d
static void ccSetPvrEncryptionKey(unsigned int keyPart1, unsigned int keyPart2, unsigned int keyPart3, unsigned int keyPart4); static void ccSetPvrEncryptionKey(unsigned int keyPart1, unsigned int keyPart2, unsigned int keyPart3, unsigned int keyPart4);
private: private:
static int ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int *outLength, static int ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long *outLength,
unsigned int outLenghtHint); long outLenghtHint);
static inline void ccDecodeEncodedPvr (unsigned int *data, int len); static inline void ccDecodeEncodedPvr (unsigned int *data, long len);
static inline unsigned int ccChecksumPvr(const unsigned int *data, int len); static inline unsigned int ccChecksumPvr(const unsigned int *data, long len);
static unsigned int s_uEncryptedPvrKeyParts[4]; static unsigned int s_uEncryptedPvrKeyParts[4];
static unsigned int s_uEncryptionKey[1024]; static unsigned int s_uEncryptionKey[1024];
@ -253,7 +253,7 @@ namespace cocos2d
* *
* @since v2.0.5 * @since v2.0.5
*/ */
unsigned char *getFileData(const std::string &fileName, unsigned long *pSize); unsigned char *getFileData(const std::string &fileName, long *size);
private: private:
/** Internal data like zip file pointer / file list array and so on */ /** Internal data like zip file pointer / file list array and so on */

View File

@ -28,10 +28,10 @@ THE SOFTWARE.
NS_CC_BEGIN NS_CC_BEGIN
const int CC_INVALID_INDEX = -1; const long CC_INVALID_INDEX = -1;
/** Allocates and initializes a new array with specified capacity */ /** Allocates and initializes a new array with specified capacity */
ccArray* ccArrayNew(int capacity) ccArray* ccArrayNew(long capacity)
{ {
if (capacity == 0) if (capacity == 0)
capacity = 7; capacity = 7;
@ -68,7 +68,7 @@ void ccArrayDoubleCapacity(ccArray *arr)
arr->arr = newArr; arr->arr = newArr;
} }
void ccArrayEnsureExtraCapacity(ccArray *arr, int extra) void ccArrayEnsureExtraCapacity(ccArray *arr, long extra)
{ {
while (arr->max < arr->num + extra) while (arr->max < arr->num + extra)
{ {
@ -82,7 +82,7 @@ void ccArrayEnsureExtraCapacity(ccArray *arr, int extra)
void ccArrayShrink(ccArray *arr) void ccArrayShrink(ccArray *arr)
{ {
int newSize = 0; long newSize = 0;
//only resize when necessary //only resize when necessary
if (arr->max > arr->num && !(arr->num==0 && arr->max==1)) if (arr->max > arr->num && !(arr->num==0 && arr->max==1))
@ -104,11 +104,11 @@ void ccArrayShrink(ccArray *arr)
} }
/** Returns index of first occurrence of object, CC_INVALID_INDEX if object not found. */ /** Returns index of first occurrence of object, CC_INVALID_INDEX if object not found. */
int ccArrayGetIndexOfObject(ccArray *arr, Object* object) long ccArrayGetIndexOfObject(ccArray *arr, Object* object)
{ {
const int arrNum = arr->num; const long arrNum = arr->num;
Object** ptr = arr->arr; Object** ptr = arr->arr;
for(int i = 0; i < arrNum; ++i, ++ptr) for(long i = 0; i < arrNum; ++i, ++ptr)
{ {
if( *ptr == object ) if( *ptr == object )
return i; return i;
@ -143,7 +143,7 @@ void ccArrayAppendObjectWithResize(ccArray *arr, Object* object)
enough capacity. */ enough capacity. */
void ccArrayAppendArray(ccArray *arr, ccArray *plusArr) void ccArrayAppendArray(ccArray *arr, ccArray *plusArr)
{ {
for(int i = 0; i < plusArr->num; i++) for(long i = 0; i < plusArr->num; i++)
{ {
ccArrayAppendObject(arr, plusArr->arr[i]); ccArrayAppendObject(arr, plusArr->arr[i]);
} }
@ -157,14 +157,14 @@ void ccArrayAppendArrayWithResize(ccArray *arr, ccArray *plusArr)
} }
/** Inserts an object at index */ /** Inserts an object at index */
void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, int index) void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, long index)
{ {
CCASSERT(index<=arr->num, "Invalid index. Out of bounds"); CCASSERT(index<=arr->num, "Invalid index. Out of bounds");
CCASSERT(object != NULL, "Invalid parameter!"); CCASSERT(object != NULL, "Invalid parameter!");
ccArrayEnsureExtraCapacity(arr, 1); ccArrayEnsureExtraCapacity(arr, 1);
int remaining = arr->num - index; long remaining = arr->num - index;
if( remaining > 0) if( remaining > 0)
{ {
memmove((void *)&arr->arr[index+1], (void *)&arr->arr[index], sizeof(Object*) * remaining ); memmove((void *)&arr->arr[index+1], (void *)&arr->arr[index], sizeof(Object*) * remaining );
@ -176,7 +176,7 @@ void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, int index)
} }
/** Swaps two objects */ /** Swaps two objects */
void ccArraySwapObjectsAtIndexes(ccArray *arr, int index1, int index2) void ccArraySwapObjectsAtIndexes(ccArray *arr, long index1, long index2)
{ {
CCASSERT(index1>=0 && index1 < arr->num, "(1) Invalid index. Out of bounds"); CCASSERT(index1>=0 && index1 < arr->num, "(1) Invalid index. Out of bounds");
CCASSERT(index2>=0 && index2 < arr->num, "(2) Invalid index. Out of bounds"); CCASSERT(index2>=0 && index2 < arr->num, "(2) Invalid index. Out of bounds");
@ -198,7 +198,7 @@ void ccArrayRemoveAllObjects(ccArray *arr)
/** Removes object at specified index and pushes back all subsequent objects. /** Removes object at specified index and pushes back all subsequent objects.
Behavior undefined if index outside [0, num-1]. */ Behavior undefined if index outside [0, num-1]. */
void ccArrayRemoveObjectAtIndex(ccArray *arr, int index, bool bReleaseObj/* = true*/) void ccArrayRemoveObjectAtIndex(ccArray *arr, long index, bool bReleaseObj/* = true*/)
{ {
CCASSERT(arr && arr->num > 0 && index>=0 && index < arr->num, "Invalid index. Out of bounds"); CCASSERT(arr && arr->num > 0 && index>=0 && index < arr->num, "Invalid index. Out of bounds");
if (bReleaseObj) if (bReleaseObj)
@ -208,7 +208,7 @@ void ccArrayRemoveObjectAtIndex(ccArray *arr, int index, bool bReleaseObj/* = tr
arr->num--; arr->num--;
int remaining = arr->num - index; long remaining = arr->num - index;
if(remaining>0) if(remaining>0)
{ {
memmove((void *)&arr->arr[index], (void *)&arr->arr[index+1], remaining * sizeof(Object*)); memmove((void *)&arr->arr[index], (void *)&arr->arr[index+1], remaining * sizeof(Object*));
@ -218,16 +218,16 @@ void ccArrayRemoveObjectAtIndex(ccArray *arr, int index, bool bReleaseObj/* = tr
/** Removes object at specified index and fills the gap with the last object, /** Removes object at specified index and fills the gap with the last object,
thereby avoiding the need to push back subsequent objects. thereby avoiding the need to push back subsequent objects.
Behavior undefined if index outside [0, num-1]. */ Behavior undefined if index outside [0, num-1]. */
void ccArrayFastRemoveObjectAtIndex(ccArray *arr, int index) void ccArrayFastRemoveObjectAtIndex(ccArray *arr, long index)
{ {
CC_SAFE_RELEASE(arr->arr[index]); CC_SAFE_RELEASE(arr->arr[index]);
int last = --arr->num; long last = --arr->num;
arr->arr[index] = arr->arr[last]; arr->arr[index] = arr->arr[last];
} }
void ccArrayFastRemoveObject(ccArray *arr, Object* object) void ccArrayFastRemoveObject(ccArray *arr, Object* object)
{ {
int index = ccArrayGetIndexOfObject(arr, object); long index = ccArrayGetIndexOfObject(arr, object);
if (index != CC_INVALID_INDEX) if (index != CC_INVALID_INDEX)
{ {
ccArrayFastRemoveObjectAtIndex(arr, index); ccArrayFastRemoveObjectAtIndex(arr, index);
@ -238,7 +238,7 @@ void ccArrayFastRemoveObject(ccArray *arr, Object* object)
found the function has no effect. */ found the function has no effect. */
void ccArrayRemoveObject(ccArray *arr, Object* object, bool bReleaseObj/* = true*/) void ccArrayRemoveObject(ccArray *arr, Object* object, bool bReleaseObj/* = true*/)
{ {
int index = ccArrayGetIndexOfObject(arr, object); long index = ccArrayGetIndexOfObject(arr, object);
if (index != CC_INVALID_INDEX) if (index != CC_INVALID_INDEX)
{ {
ccArrayRemoveObjectAtIndex(arr, index, bReleaseObj); ccArrayRemoveObjectAtIndex(arr, index, bReleaseObj);
@ -249,7 +249,7 @@ void ccArrayRemoveObject(ccArray *arr, Object* object, bool bReleaseObj/* = true
first matching instance in arr will be removed. */ first matching instance in arr will be removed. */
void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr) void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr)
{ {
for(int i = 0; i < minusArr->num; i++) for(long i = 0; i < minusArr->num; i++)
{ {
ccArrayRemoveObject(arr, minusArr->arr[i]); ccArrayRemoveObject(arr, minusArr->arr[i]);
} }
@ -259,8 +259,8 @@ void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr)
matching instances in arr will be removed. */ matching instances in arr will be removed. */
void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr) void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr)
{ {
int back = 0; long back = 0;
int i = 0; long i = 0;
for( i = 0; i < arr->num; i++) for( i = 0; i < arr->num; i++)
{ {
@ -282,7 +282,7 @@ void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr)
// #pragma mark ccCArray for Values (c structures) // #pragma mark ccCArray for Values (c structures)
/** Allocates and initializes a new C array with specified capacity */ /** Allocates and initializes a new C array with specified capacity */
ccCArray* ccCArrayNew(int capacity) ccCArray* ccCArrayNew(long capacity)
{ {
if (capacity == 0) if (capacity == 0)
{ {
@ -317,15 +317,15 @@ void ccCArrayDoubleCapacity(ccCArray *arr)
} }
/** Increases array capacity such that max >= num + extra. */ /** Increases array capacity such that max >= num + extra. */
void ccCArrayEnsureExtraCapacity(ccCArray *arr, int extra) void ccCArrayEnsureExtraCapacity(ccCArray *arr, long extra)
{ {
ccArrayEnsureExtraCapacity((ccArray*)arr,extra); ccArrayEnsureExtraCapacity((ccArray*)arr,extra);
} }
/** Returns index of first occurrence of value, CC_INVALID_INDEX if value not found. */ /** Returns index of first occurrence of value, CC_INVALID_INDEX if value not found. */
int ccCArrayGetIndexOfValue(ccCArray *arr, void* value) long ccCArrayGetIndexOfValue(ccCArray *arr, void* value)
{ {
for( int i = 0; i < arr->num; i++) for(long i = 0; i < arr->num; i++)
{ {
if( arr->arr[i] == value ) if( arr->arr[i] == value )
return i; return i;
@ -340,11 +340,11 @@ bool ccCArrayContainsValue(ccCArray *arr, void* value)
} }
/** Inserts a value at a certain position. Behavior undefined if array doesn't have enough capacity */ /** Inserts a value at a certain position. Behavior undefined if array doesn't have enough capacity */
void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, int index) void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, long index)
{ {
CCASSERT( index < arr->max, "ccCArrayInsertValueAtIndex: invalid index"); CCASSERT( index < arr->max, "ccCArrayInsertValueAtIndex: invalid index");
int remaining = arr->num - index; long remaining = arr->num - index;
// make sure it has enough capacity // make sure it has enough capacity
if (arr->num + 1 == arr->max) if (arr->num + 1 == arr->max)
{ {
@ -385,7 +385,7 @@ void ccCArrayAppendValueWithResize(ccCArray *arr, void* value)
enough capacity. */ enough capacity. */
void ccCArrayAppendArray(ccCArray *arr, ccCArray *plusArr) void ccCArrayAppendArray(ccCArray *arr, ccCArray *plusArr)
{ {
for( int i = 0; i < plusArr->num; i++) for( long i = 0; i < plusArr->num; i++)
{ {
ccCArrayAppendValue(arr, plusArr->arr[i]); ccCArrayAppendValue(arr, plusArr->arr[i]);
} }
@ -408,9 +408,9 @@ void ccCArrayRemoveAllValues(ccCArray *arr)
Behavior undefined if index outside [0, num-1]. Behavior undefined if index outside [0, num-1].
@since v0.99.4 @since v0.99.4
*/ */
void ccCArrayRemoveValueAtIndex(ccCArray *arr, int index) void ccCArrayRemoveValueAtIndex(ccCArray *arr, long index)
{ {
for( int last = --arr->num; index < last; index++) for( long last = --arr->num; index < last; index++)
{ {
arr->arr[index] = arr->arr[index + 1]; arr->arr[index] = arr->arr[index + 1];
} }
@ -421,9 +421,9 @@ void ccCArrayRemoveValueAtIndex(ccCArray *arr, int index)
Behavior undefined if index outside [0, num-1]. Behavior undefined if index outside [0, num-1].
@since v0.99.4 @since v0.99.4
*/ */
void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, int index) void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, long index)
{ {
int last = --arr->num; long last = --arr->num;
arr->arr[index] = arr->arr[last]; arr->arr[index] = arr->arr[last];
} }
@ -432,7 +432,7 @@ void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, int index)
*/ */
void ccCArrayRemoveValue(ccCArray *arr, void* value) void ccCArrayRemoveValue(ccCArray *arr, void* value)
{ {
int index = ccCArrayGetIndexOfValue(arr, value); long index = ccCArrayGetIndexOfValue(arr, value);
if (index != CC_INVALID_INDEX) if (index != CC_INVALID_INDEX)
{ {
ccCArrayRemoveValueAtIndex(arr, index); ccCArrayRemoveValueAtIndex(arr, index);
@ -444,7 +444,7 @@ void ccCArrayRemoveValue(ccCArray *arr, void* value)
*/ */
void ccCArrayRemoveArray(ccCArray *arr, ccCArray *minusArr) void ccCArrayRemoveArray(ccCArray *arr, ccCArray *minusArr)
{ {
for(int i = 0; i < minusArr->num; i++) for(long i = 0; i < minusArr->num; i++)
{ {
ccCArrayRemoveValue(arr, minusArr->arr[i]); ccCArrayRemoveValue(arr, minusArr->arr[i]);
} }
@ -455,9 +455,9 @@ void ccCArrayRemoveArray(ccCArray *arr, ccCArray *minusArr)
*/ */
void ccCArrayFullRemoveArray(ccCArray *arr, ccCArray *minusArr) void ccCArrayFullRemoveArray(ccCArray *arr, ccCArray *minusArr)
{ {
int back = 0; long back = 0;
for(int i = 0; i < arr->num; i++) for(long i = 0; i < arr->num; i++)
{ {
if( ccCArrayContainsValue(minusArr, arr->arr[i]) ) if( ccCArrayContainsValue(minusArr, arr->arr[i]) )
{ {

View File

@ -51,20 +51,20 @@ THE SOFTWARE.
NS_CC_BEGIN NS_CC_BEGIN
extern const int CC_INVALID_INDEX; extern const long CC_INVALID_INDEX;
// Easy integration // Easy integration
#define CCARRAYDATA_FOREACH(__array__, __object__) \ #define CCARRAYDATA_FOREACH(__array__, __object__) \
__object__=__array__->arr[0]; for(int i=0, num=__array__->num; i<num; i++, __object__=__array__->arr[i]) \ __object__=__array__->arr[0]; for(long i=0, num=__array__->num; i<num; i++, __object__=__array__->arr[i]) \
typedef struct _ccArray { typedef struct _ccArray {
int num, max; long num, max;
Object** arr; Object** arr;
} ccArray; } ccArray;
/** Allocates and initializes a new array with specified capacity */ /** Allocates and initializes a new array with specified capacity */
ccArray* ccArrayNew(int capacity); ccArray* ccArrayNew(long capacity);
/** Frees array after removing all remaining objects. Silently ignores nil arr. */ /** Frees array after removing all remaining objects. Silently ignores nil arr. */
void ccArrayFree(ccArray*& arr); void ccArrayFree(ccArray*& arr);
@ -73,13 +73,13 @@ void ccArrayFree(ccArray*& arr);
void ccArrayDoubleCapacity(ccArray *arr); void ccArrayDoubleCapacity(ccArray *arr);
/** Increases array capacity such that max >= num + extra. */ /** Increases array capacity such that max >= num + extra. */
void ccArrayEnsureExtraCapacity(ccArray *arr, int extra); void ccArrayEnsureExtraCapacity(ccArray *arr, long extra);
/** shrinks the array so the memory footprint corresponds with the number of items */ /** shrinks the array so the memory footprint corresponds with the number of items */
void ccArrayShrink(ccArray *arr); void ccArrayShrink(ccArray *arr);
/** Returns index of first occurrence of object, NSNotFound if object not found. */ /** Returns index of first occurrence of object, NSNotFound if object not found. */
int ccArrayGetIndexOfObject(ccArray *arr, Object* object); long ccArrayGetIndexOfObject(ccArray *arr, Object* object);
/** Returns a Boolean value that indicates whether object is present in array. */ /** Returns a Boolean value that indicates whether object is present in array. */
bool ccArrayContainsObject(ccArray *arr, Object* object); bool ccArrayContainsObject(ccArray *arr, Object* object);
@ -98,22 +98,22 @@ void ccArrayAppendArray(ccArray *arr, ccArray *plusArr);
void ccArrayAppendArrayWithResize(ccArray *arr, ccArray *plusArr); void ccArrayAppendArrayWithResize(ccArray *arr, ccArray *plusArr);
/** Inserts an object at index */ /** Inserts an object at index */
void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, int index); void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, long index);
/** Swaps two objects */ /** Swaps two objects */
void ccArraySwapObjectsAtIndexes(ccArray *arr, int index1, int index2); void ccArraySwapObjectsAtIndexes(ccArray *arr, long index1, long index2);
/** Removes all objects from arr */ /** Removes all objects from arr */
void ccArrayRemoveAllObjects(ccArray *arr); void ccArrayRemoveAllObjects(ccArray *arr);
/** Removes object at specified index and pushes back all subsequent objects. /** Removes object at specified index and pushes back all subsequent objects.
Behavior undefined if index outside [0, num-1]. */ Behavior undefined if index outside [0, num-1]. */
void ccArrayRemoveObjectAtIndex(ccArray *arr, int index, bool bReleaseObj = true); void ccArrayRemoveObjectAtIndex(ccArray *arr, long index, bool bReleaseObj = true);
/** Removes object at specified index and fills the gap with the last object, /** Removes object at specified index and fills the gap with the last object,
thereby avoiding the need to push back subsequent objects. thereby avoiding the need to push back subsequent objects.
Behavior undefined if index outside [0, num-1]. */ Behavior undefined if index outside [0, num-1]. */
void ccArrayFastRemoveObjectAtIndex(ccArray *arr, int index); void ccArrayFastRemoveObjectAtIndex(ccArray *arr, long index);
void ccArrayFastRemoveObject(ccArray *arr, Object* object); void ccArrayFastRemoveObject(ccArray *arr, Object* object);
@ -133,12 +133,12 @@ void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr);
// #pragma mark ccCArray for Values (c structures) // #pragma mark ccCArray for Values (c structures)
typedef struct _ccCArray { typedef struct _ccCArray {
int num, max; long num, max;
void** arr; void** arr;
} ccCArray; } ccCArray;
/** Allocates and initializes a new C array with specified capacity */ /** Allocates and initializes a new C array with specified capacity */
ccCArray* ccCArrayNew(int capacity); ccCArray* ccCArrayNew(long capacity);
/** Frees C array after removing all remaining values. Silently ignores nil arr. */ /** Frees C array after removing all remaining values. Silently ignores nil arr. */
void ccCArrayFree(ccCArray *arr); void ccCArrayFree(ccCArray *arr);
@ -147,16 +147,16 @@ void ccCArrayFree(ccCArray *arr);
void ccCArrayDoubleCapacity(ccCArray *arr); void ccCArrayDoubleCapacity(ccCArray *arr);
/** Increases array capacity such that max >= num + extra. */ /** Increases array capacity such that max >= num + extra. */
void ccCArrayEnsureExtraCapacity(ccCArray *arr, int extra); void ccCArrayEnsureExtraCapacity(ccCArray *arr, long extra);
/** Returns index of first occurrence of value, NSNotFound if value not found. */ /** Returns index of first occurrence of value, NSNotFound if value not found. */
int ccCArrayGetIndexOfValue(ccCArray *arr, void* value); long ccCArrayGetIndexOfValue(ccCArray *arr, void* value);
/** Returns a Boolean value that indicates whether value is present in the C array. */ /** Returns a Boolean value that indicates whether value is present in the C array. */
bool ccCArrayContainsValue(ccCArray *arr, void* value); bool ccCArrayContainsValue(ccCArray *arr, void* value);
/** Inserts a value at a certain position. Behavior undefined if array doesn't have enough capacity */ /** Inserts a value at a certain position. Behavior undefined if array doesn't have enough capacity */
void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, int index); void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, long index);
/** Appends an value. Behavior undefined if array doesn't have enough capacity. */ /** Appends an value. Behavior undefined if array doesn't have enough capacity. */
void ccCArrayAppendValue(ccCArray *arr, void* value); void ccCArrayAppendValue(ccCArray *arr, void* value);
@ -178,14 +178,14 @@ void ccCArrayRemoveAllValues(ccCArray *arr);
Behavior undefined if index outside [0, num-1]. Behavior undefined if index outside [0, num-1].
@since v0.99.4 @since v0.99.4
*/ */
void ccCArrayRemoveValueAtIndex(ccCArray *arr, int index); void ccCArrayRemoveValueAtIndex(ccCArray *arr, long index);
/** Removes value at specified index and fills the gap with the last value, /** Removes value at specified index and fills the gap with the last value,
thereby avoiding the need to push back subsequent values. thereby avoiding the need to push back subsequent values.
Behavior undefined if index outside [0, num-1]. Behavior undefined if index outside [0, num-1].
@since v0.99.4 @since v0.99.4
*/ */
void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, int index); void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, long index);
/** Searches for the first occurrence of value and removes it. If value is not found the function has no effect. /** Searches for the first occurrence of value and removes it. If value is not found the function has no effect.
@since v0.99.4 @since v0.99.4

View File

@ -192,21 +192,21 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClCompile Include="..\math\kazmath\src\vec2.c" /> <ClCompile Include="..\math\kazmath\src\vec2.c" />
<ClCompile Include="..\math\kazmath\src\vec3.c" /> <ClCompile Include="..\math\kazmath\src\vec3.c" />
<ClCompile Include="..\math\kazmath\src\vec4.c" /> <ClCompile Include="..\math\kazmath\src\vec4.c" />
<ClCompile Include="..\physics\Box2D\CCPhysicsBodyInfo.cpp" /> <ClCompile Include="..\physics\box2d\CCPhysicsBodyInfo_box2d.cpp" />
<ClCompile Include="..\physics\Box2D\CCPhysicsContactInfo.cpp" /> <ClCompile Include="..\physics\box2d\CCPhysicsContactInfo_box2d.cpp" />
<ClCompile Include="..\physics\Box2D\CCPhysicsJointInfo.cpp" /> <ClCompile Include="..\physics\box2d\CCPhysicsJointInfo_box2d.cpp" />
<ClCompile Include="..\physics\Box2D\CCPhysicsShapeInfo.cpp" /> <ClCompile Include="..\physics\box2d\CCPhysicsShapeInfo_box2d.cpp" />
<ClCompile Include="..\physics\Box2D\CCPhysicsWorldInfo.cpp" /> <ClCompile Include="..\physics\box2d\CCPhysicsWorldInfo_box2d.cpp" />
<ClCompile Include="..\physics\CCPhysicsBody.cpp" /> <ClCompile Include="..\physics\CCPhysicsBody.cpp" />
<ClCompile Include="..\physics\CCPhysicsContact.cpp" /> <ClCompile Include="..\physics\CCPhysicsContact.cpp" />
<ClCompile Include="..\physics\CCPhysicsJoint.cpp" /> <ClCompile Include="..\physics\CCPhysicsJoint.cpp" />
<ClCompile Include="..\physics\CCPhysicsShape.cpp" /> <ClCompile Include="..\physics\CCPhysicsShape.cpp" />
<ClCompile Include="..\physics\CCPhysicsWorld.cpp" /> <ClCompile Include="..\physics\CCPhysicsWorld.cpp" />
<ClCompile Include="..\physics\chipmunk\CCPhysicsBodyInfo.cpp" /> <ClCompile Include="..\physics\chipmunk\CCPhysicsBodyInfo_chipmunk.cpp" />
<ClCompile Include="..\physics\chipmunk\CCPhysicsContactInfo.cpp" /> <ClCompile Include="..\physics\chipmunk\CCPhysicsContactInfo_chipmunk.cpp" />
<ClCompile Include="..\physics\chipmunk\CCPhysicsJointInfo.cpp" /> <ClCompile Include="..\physics\chipmunk\CCPhysicsJointInfo_chipmunk.cpp" />
<ClCompile Include="..\physics\chipmunk\CCPhysicsShapeInfo.cpp" /> <ClCompile Include="..\physics\chipmunk\CCPhysicsShapeInfo_chipmunk.cpp" />
<ClCompile Include="..\physics\chipmunk\CCPhysicsWorldInfo.cpp" /> <ClCompile Include="..\physics\chipmunk\CCPhysicsWorldInfo_chipmunk.cpp" />
<ClCompile Include="base64.cpp" /> <ClCompile Include="base64.cpp" />
<ClCompile Include="CCAction.cpp" /> <ClCompile Include="CCAction.cpp" />
<ClCompile Include="CCActionCamera.cpp" /> <ClCompile Include="CCActionCamera.cpp" />
@ -361,24 +361,24 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClInclude Include="..\math\kazmath\include\kazmath\vec2.h" /> <ClInclude Include="..\math\kazmath\include\kazmath\vec2.h" />
<ClInclude Include="..\math\kazmath\include\kazmath\vec3.h" /> <ClInclude Include="..\math\kazmath\include\kazmath\vec3.h" />
<ClInclude Include="..\math\kazmath\include\kazmath\vec4.h" /> <ClInclude Include="..\math\kazmath\include\kazmath\vec4.h" />
<ClInclude Include="..\physics\Box2D\CCPhysicsBodyInfo.h" /> <ClInclude Include="..\physics\box2d\CCPhysicsBodyInfo_box2d.h" />
<ClInclude Include="..\physics\Box2D\CCPhysicsContactInfo.h" /> <ClInclude Include="..\physics\box2d\CCPhysicsContactInfo_box2d.h" />
<ClInclude Include="..\physics\Box2D\CCPhysicsHelper.h" /> <ClInclude Include="..\physics\box2d\CCPhysicsHelper_box2d.h" />
<ClInclude Include="..\physics\Box2D\CCPhysicsJointInfo.h" /> <ClInclude Include="..\physics\box2d\CCPhysicsJointInfo_box2d.h" />
<ClInclude Include="..\physics\Box2D\CCPhysicsShapeInfo.h" /> <ClInclude Include="..\physics\box2d\CCPhysicsShapeInfo_box2d.h" />
<ClInclude Include="..\physics\Box2D\CCPhysicsWorldInfo.h" /> <ClInclude Include="..\physics\box2d\CCPhysicsWorldInfo_box2d.h" />
<ClInclude Include="..\physics\CCPhysicsBody.h" /> <ClInclude Include="..\physics\CCPhysicsBody.h" />
<ClInclude Include="..\physics\CCPhysicsContact.h" /> <ClInclude Include="..\physics\CCPhysicsContact.h" />
<ClInclude Include="..\physics\CCPhysicsJoint.h" /> <ClInclude Include="..\physics\CCPhysicsJoint.h" />
<ClInclude Include="..\physics\CCPhysicsSetting.h" /> <ClInclude Include="..\physics\CCPhysicsSetting.h" />
<ClInclude Include="..\physics\CCPhysicsShape.h" /> <ClInclude Include="..\physics\CCPhysicsShape.h" />
<ClInclude Include="..\physics\CCPhysicsWorld.h" /> <ClInclude Include="..\physics\CCPhysicsWorld.h" />
<ClInclude Include="..\physics\chipmunk\CCPhysicsBodyInfo.h" /> <ClInclude Include="..\physics\chipmunk\CCPhysicsBodyInfo_chipmunk.h" />
<ClInclude Include="..\physics\chipmunk\CCPhysicsContactInfo.h" /> <ClInclude Include="..\physics\chipmunk\CCPhysicsContactInfo_chipmunk.h" />
<ClInclude Include="..\physics\chipmunk\CCPhysicsHelper.h" /> <ClInclude Include="..\physics\chipmunk\CCPhysicsHelper_chipmunk.h" />
<ClInclude Include="..\physics\chipmunk\CCPhysicsJointInfo.h" /> <ClInclude Include="..\physics\chipmunk\CCPhysicsJointInfo_chipmunk.h" />
<ClInclude Include="..\physics\chipmunk\CCPhysicsShapeInfo.h" /> <ClInclude Include="..\physics\chipmunk\CCPhysicsShapeInfo_chipmunk.h" />
<ClInclude Include="..\physics\chipmunk\CCPhysicsWorldInfo.h" /> <ClInclude Include="..\physics\chipmunk\CCPhysicsWorldInfo_chipmunk.h" />
<ClInclude Include="base64.h" /> <ClInclude Include="base64.h" />
<ClInclude Include="CCAction.h" /> <ClInclude Include="CCAction.h" />
<ClInclude Include="CCActionCamera.h" /> <ClInclude Include="CCActionCamera.h" />

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