diff --git a/.gitignore b/.gitignore index 8acdd3504c..d16b0398e7 100644 --- a/.gitignore +++ b/.gitignore @@ -100,3 +100,8 @@ tools/jenkins_scripts/mac/android/userconf.ini # CTags tags + +# ignore files, created with make-all-linux-project script +/lib +/build/linux-build + diff --git a/.travis.yml b/.travis.yml index 966f293146..1e67e468bf 100644 --- a/.travis.yml +++ b/.travis.yml @@ -26,3 +26,9 @@ script: - tools/travis-scripts/run-script.sh before_install: - tools/travis-scripts/before-install.sh + +# whitelist +branches: + only: + - master + - develop diff --git a/AUTHORS b/AUTHORS index 41e87fa132..d553c07d24 100644 --- a/AUTHORS +++ b/AUTHORS @@ -628,6 +628,7 @@ Developers: HoGarfield (garfield_ho) Fixed a bug that CCBReader can't play sequence automatically in JSB. Could not set next animation in CCBAnimationCompleted callback. + Fixed missing to add JSAutoCompartment when invoking JS functions from C++. lite3 Fixed a bug that Node's anchor point was changed after being added to ScrollView. @@ -640,6 +641,13 @@ Developers: ledyba 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: WenSheng Yang diff --git a/CHANGELOG b/CHANGELOG index c8e6b9d403..e9e1da977c 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -10,19 +10,30 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] Could not set next animation in CCBAnimationCompleted callback. [FIX] The Node's anchor point was changed after being added to ScrollView. [FIX] Refactored and improved EventDispatcher. - [NEW] Added Mouse Support For Desktop Platforms. [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] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes - [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again [FIX] Fixed application will crash when pause and resume. [FIX] Clear NoSuchMethodError Exception when JniHelper fails to find method id [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] [FIX] Removed unused CCLOG() from GL initialization [iOS] [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] [FIX] Trigger onKeyReleased only after the key has been released. [Javascript binding] @@ -30,6 +41,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [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] CCBReader can't play sequence automatically in JSB. + [NEW] main.js -> cocos2d-jsb.js [Lua Binding] [NEW] Added Armature lua binding and added test samples. diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000000..c03a1e9d87 --- /dev/null +++ b/CMakeLists.txt @@ -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) diff --git a/README.md b/README.md index 217779827f..938f0c39fb 100644 --- a/README.md +++ b/README.md @@ -29,8 +29,8 @@ How to start a new game Example: - $ cd cocos2d-x/tools/project-creator - $ ./create-multi-platform-projects.py -p mygame -k com.your_company.mygame -l cpp + $ cd cocos2d-x/tools/project-creator + $ ./create-multi-platform-projects.py -p mygame -k com.your_company.mygame -l cpp $ cd ../../projects/mygame @@ -70,7 +70,7 @@ Build Requirements ------------------ * Mac OS X 10.7+, Xcode 4.6+ -* or Ubuntu 13.04+ +* or Ubuntu 12.10+, CMake 2.6+ * or Windows 7+, VS 2012+ @@ -98,9 +98,14 @@ $ open samples.xcodeproj ``` $ 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 Open the `cocos2d-x/build/cocos2d-win32.vc2012.sln` diff --git a/build/BuildHelpers.CMakeLists.txt b/build/BuildHelpers.CMakeLists.txt new file mode 100644 index 0000000000..6e848d4f29 --- /dev/null +++ b/build/BuildHelpers.CMakeLists.txt @@ -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() diff --git a/build/Makefile b/build/Makefile deleted file mode 100644 index 761855d264..0000000000 --- a/build/Makefile +++ /dev/null @@ -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 diff --git a/build/android-build.py b/build/android-build.py index be4800453a..c630010ef8 100755 --- a/build/android-build.py +++ b/build/android-build.py @@ -2,10 +2,6 @@ # android-build.py # Build android samples -# You can use - - -# begin import sys import os, os.path 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) else: 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): @@ -182,15 +179,15 @@ def build_samples(target,ndk_build_param): elif target == 'testlua': app_android_root = os.path.join(cocos_root, 'samples/Lua/TestLua/proj.android') 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': - 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': - 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': - 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': - 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: print 'unknown target: %s' % target continue @@ -209,4 +206,8 @@ if __name__ == '__main__': if len(args) == 0: usage() 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) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index e32180792f..5639c9df83 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -8c640bf1e2f1cd0a489e6169c930234b809636f2 \ No newline at end of file +a70914e0a87ee8ced4d662bd6038fc955e77f6ca \ No newline at end of file diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index ba37de5f5d..420d377772 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -b473303312be3b69891020b5fb470dd382f31284 \ No newline at end of file +3ff18018375c71f683a484652678740cc6395eaf \ No newline at end of file diff --git a/build/make-all-linux-project.sh b/build/make-all-linux-project.sh deleted file mode 100755 index 4889355380..0000000000 --- a/build/make-all-linux-project.sh +++ /dev/null @@ -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 diff --git a/cocos/2d/Android.mk b/cocos/2d/Android.mk index 75ff000786..6d36b83b55 100644 --- a/cocos/2d/Android.mk +++ b/cocos/2d/Android.mk @@ -149,16 +149,16 @@ platform/CCThread.cpp \ ../physics/CCPhysicsJoint.cpp \ ../physics/CCPhysicsShape.cpp \ ../physics/CCPhysicsWorld.cpp \ -../physics/box2d/CCPhysicsBodyInfo.cpp \ -../physics/box2d/CCPhysicsContactInfo.cpp \ -../physics/box2d/CCPhysicsJointInfo.cpp \ -../physics/box2d/CCPhysicsShapeInfo.cpp \ -../physics/box2d/CCPhysicsWorldInfo.cpp \ -../physics/chipmunk/CCPhysicsBodyInfo.cpp \ -../physics/chipmunk/CCPhysicsContactInfo.cpp \ -../physics/chipmunk/CCPhysicsJointInfo.cpp \ -../physics/chipmunk/CCPhysicsShapeInfo.cpp \ -../physics/chipmunk/CCPhysicsWorldInfo.cpp \ +../physics/box2d/CCPhysicsBodyInfo_box2d.cpp \ +../physics/box2d/CCPhysicsContactInfo_box2d.cpp \ +../physics/box2d/CCPhysicsJointInfo_box2d.cpp \ +../physics/box2d/CCPhysicsShapeInfo_box2d.cpp \ +../physics/box2d/CCPhysicsWorldInfo_box2d.cpp \ +../physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp \ +../physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp \ +../physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp \ +../physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp \ +../physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp \ ../../external/tinyxml2/tinyxml2.cpp \ ../../external/unzip/ioapi.cpp \ ../../external/unzip/unzip.cpp diff --git a/cocos/2d/CCActionInterval.cpp b/cocos/2d/CCActionInterval.cpp index 0fe7e055b9..14c0fec762 100644 --- a/cocos/2d/CCActionInterval.cpp +++ b/cocos/2d/CCActionInterval.cpp @@ -203,7 +203,7 @@ Sequence* Sequence::create(Array* arrayOfActions) Sequence* pRet = NULL; do { - unsigned int count = arrayOfActions->count(); + long count = arrayOfActions->count(); CC_BREAK_IF(count == 0); FiniteTimeAction* prev = static_cast(arrayOfActions->getObjectAtIndex(0)); @@ -576,7 +576,7 @@ Spawn* Spawn::create(Array *arrayOfActions) Spawn* pRet = NULL; do { - unsigned int count = arrayOfActions->count(); + long count = arrayOfActions->count(); CC_BREAK_IF(count == 0); FiniteTimeAction* prev = static_cast(arrayOfActions->getObjectAtIndex(0)); if (count > 1) @@ -2100,7 +2100,7 @@ void Animate::update(float t) } Array* frames = _animation->getFrames(); - int numberOfFrames = frames->count(); + long numberOfFrames = frames->count(); SpriteFrame *frameToDisplay = NULL; for( int i=_nextFrame; i < numberOfFrames; i++ ) { diff --git a/cocos/2d/CCActionManager.cpp b/cocos/2d/CCActionManager.cpp index 9d1fb1ee93..dd2b528bce 100644 --- a/cocos/2d/CCActionManager.cpp +++ b/cocos/2d/CCActionManager.cpp @@ -65,55 +65,55 @@ ActionManager::~ActionManager(void) // private -void ActionManager::deleteHashElement(tHashElement *pElement) +void ActionManager::deleteHashElement(tHashElement *element) { - ccArrayFree(pElement->actions); - HASH_DEL(_targets, pElement); - pElement->target->release(); - free(pElement); + ccArrayFree(element->actions); + HASH_DEL(_targets, element); + element->target->release(); + free(element); } -void ActionManager::actionAllocWithHashElement(tHashElement *pElement) +void ActionManager::actionAllocWithHashElement(tHashElement *element) { // 4 actions per Node by default - if (pElement->actions == NULL) + if (element->actions == NULL) { - pElement->actions = ccArrayNew(4); + element->actions = ccArrayNew(4); }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(); - pElement->currentActionSalvaged = true; + element->currentAction->retain(); + 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 - 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; } else { - deleteHashElement(pElement); + deleteHashElement(element); } } } @@ -122,21 +122,21 @@ void ActionManager::removeActionAtIndex(int index, tHashElement *pElement) void ActionManager::pauseTarget(Object *target) { - tHashElement *pElement = NULL; - HASH_FIND_INT(_targets, &target, pElement); - if (pElement) + tHashElement *element = NULL; + HASH_FIND_PTR(_targets, &target, element); + if (element) { - pElement->paused = true; + element->paused = true; } } void ActionManager::resumeTarget(Object *target) { - tHashElement *pElement = NULL; - HASH_FIND_INT(_targets, &target, pElement); - if (pElement) + tHashElement *element = NULL; + HASH_FIND_PTR(_targets, &target, element); + if (element) { - pElement->paused = false; + element->paused = false; } } @@ -168,40 +168,40 @@ void ActionManager::resumeTargets(cocos2d::Set *targetsToResume) // 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, ""); - tHashElement *pElement = NULL; + tHashElement *element = NULL; // we should convert it to Object*, because we save it as Object* Object *tmp = target; - HASH_FIND_INT(_targets, &tmp, pElement); - if (! pElement) + HASH_FIND_PTR(_targets, &tmp, element); + if (! element) { - pElement = (tHashElement*)calloc(sizeof(*pElement), 1); - pElement->paused = paused; + element = (tHashElement*)calloc(sizeof(*element), 1); + element->paused = paused; target->retain(); - pElement->target = target; - HASH_ADD_INT(_targets, target, pElement); + element->target = target; + HASH_ADD_PTR(_targets, target, element); } - actionAllocWithHashElement(pElement); + actionAllocWithHashElement(element); - CCASSERT(! ccArrayContainsObject(pElement->actions, pAction), ""); - ccArrayAppendObject(pElement->actions, pAction); + CCASSERT(! ccArrayContainsObject(element->actions, action), ""); + ccArrayAppendObject(element->actions, action); - pAction->startWithTarget(target); + action->startWithTarget(target); } // remove void ActionManager::removeAllActions(void) { - for (tHashElement *pElement = _targets; pElement != NULL; ) + for (tHashElement *element = _targets; element != NULL; ) { - Object *target = pElement->target; - pElement = (tHashElement*)pElement->hh.next; + Object *target = element->target; + element = (tHashElement*)element->hh.next; removeAllActionsFromTarget(target); } } @@ -214,24 +214,24 @@ void ActionManager::removeAllActionsFromTarget(Object *target) return; } - tHashElement *pElement = NULL; - HASH_FIND_INT(_targets, &target, pElement); - if (pElement) + tHashElement *element = NULL; + HASH_FIND_PTR(_targets, &target, element); + if (element) { - if (ccArrayContainsObject(pElement->actions, pElement->currentAction) && (! pElement->currentActionSalvaged)) + if (ccArrayContainsObject(element->actions, element->currentAction) && (! element->currentActionSalvaged)) { - pElement->currentAction->retain(); - pElement->currentActionSalvaged = true; + element->currentAction->retain(); + element->currentActionSalvaged = true; } - ccArrayRemoveAllObjects(pElement->actions); - if (_currentTarget == pElement) + ccArrayRemoveAllObjects(element->actions); + if (_currentTarget == element) { _currentTargetSalvaged = true; } else { - deleteHashElement(pElement); + deleteHashElement(element); } } else @@ -240,23 +240,23 @@ void ActionManager::removeAllActionsFromTarget(Object *target) } } -void ActionManager::removeAction(Action *pAction) +void ActionManager::removeAction(Action *action) { // explicit null handling - if (pAction == NULL) + if (action == NULL) { return; } - tHashElement *pElement = NULL; - Object *target = pAction->getOriginalTarget(); - HASH_FIND_INT(_targets, &target, pElement); - if (pElement) + tHashElement *element = NULL; + Object *target = action->getOriginalTarget(); + HASH_FIND_PTR(_targets, &target, element); + if (element) { - unsigned int i = ccArrayGetIndexOfObject(pElement->actions, pAction); - if (UINT_MAX != i) + long i = ccArrayGetIndexOfObject(element->actions, action); + if (i != CC_INVALID_INDEX) { - removeActionAtIndex(i, pElement); + removeActionAtIndex(i, element); } } else @@ -270,19 +270,19 @@ void ActionManager::removeActionByTag(int tag, Object *target) CCASSERT(tag != Action::INVALID_TAG, ""); CCASSERT(target != NULL, ""); - tHashElement *pElement = NULL; - HASH_FIND_INT(_targets, &target, pElement); + tHashElement *element = NULL; + HASH_FIND_PTR(_targets, &target, element); - if (pElement) + if (element) { - unsigned int limit = pElement->actions->num; - for (unsigned int i = 0; i < limit; ++i) + long limit = element->actions->num; + 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; } } @@ -297,21 +297,21 @@ Action* ActionManager::getActionByTag(int tag, const Object *target) const { CCASSERT(tag != Action::INVALID_TAG, ""); - tHashElement *pElement = NULL; - HASH_FIND_INT(_targets, &target, pElement); + tHashElement *element = NULL; + HASH_FIND_PTR(_targets, &target, element); - if (pElement) + if (element) { - if (pElement->actions != NULL) + if (element->actions != NULL) { - unsigned int limit = pElement->actions->num; - for (unsigned int i = 0; i < limit; ++i) + long limit = element->actions->num; + 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 // 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; - HASH_FIND_INT(_targets, &target, pElement); - if (pElement) + tHashElement *element = NULL; + HASH_FIND_PTR(_targets, &target, element); + if (element) { - return pElement->actions ? pElement->actions->num : 0; + return element->actions ? element->actions->num : 0; } return 0; @@ -374,10 +374,10 @@ void ActionManager::update(float dt) { _currentTarget->currentAction->stop(); - Action *pAction = _currentTarget->currentAction; + Action *action = _currentTarget->currentAction; // Make currentAction nil to prevent removeAction from salvaging it. _currentTarget->currentAction = NULL; - removeAction(pAction); + removeAction(action); } _currentTarget->currentAction = NULL; diff --git a/cocos/2d/CCActionManager.h b/cocos/2d/CCActionManager.h index 72427a5648..8a2c077511 100644 --- a/cocos/2d/CCActionManager.h +++ b/cocos/2d/CCActionManager.h @@ -102,7 +102,7 @@ public: * - 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. */ - unsigned int getNumberOfRunningActionsInTarget(const Object *target) const; + long getNumberOfRunningActionsInTarget(const Object *target) const; /** @deprecated use getNumberOfRunningActionsInTarget() instead */ CC_DEPRECATED_ATTRIBUTE inline unsigned int numberOfRunningActionsInTarget(Object *target) const { return getNumberOfRunningActionsInTarget(target); } @@ -126,7 +126,7 @@ public: protected: // declared in ActionManager.m - void removeActionAtIndex(int index, struct _hashElement *pElement); + void removeActionAtIndex(long index, struct _hashElement *pElement); void deleteHashElement(struct _hashElement *pElement); void actionAllocWithHashElement(struct _hashElement *pElement); void update(float dt); diff --git a/cocos/2d/CCAnimation.cpp b/cocos/2d/CCAnimation.cpp index 5fa37cd85c..ca1c949882 100644 --- a/cocos/2d/CCAnimation.cpp +++ b/cocos/2d/CCAnimation.cpp @@ -28,6 +28,7 @@ THE SOFTWARE. #include "CCTexture2D.h" #include "ccMacros.h" #include "CCSpriteFrame.h" +#include "CCDirector.h" NS_CC_BEGIN @@ -176,7 +177,7 @@ void Animation::addSpriteFrame(SpriteFrame *pFrame) void Animation::addSpriteFrameWithFile(const char *filename) { - Texture2D *texture = TextureCache::getInstance()->addImage(filename); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename); Rect rect = Rect::ZERO; rect.size = texture->getContentSize(); SpriteFrame *pFrame = SpriteFrame::createWithTexture(texture, rect); diff --git a/cocos/2d/CCAnimationCache.cpp b/cocos/2d/CCAnimationCache.cpp index 37f516347a..a2c0fa9303 100644 --- a/cocos/2d/CCAnimationCache.cpp +++ b/cocos/2d/CCAnimationCache.cpp @@ -71,22 +71,20 @@ AnimationCache::~AnimationCache() 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); } -void AnimationCache::removeAnimation(const char* name) +void AnimationCache::removeAnimation(const std::string& name) { - if (! name) - { + if (name.size()==0) return; - } _animations->removeObjectForKey(name); } -Animation* AnimationCache::getAnimation(const char* name) +Animation* AnimationCache::getAnimation(const std::string& name) { return (Animation*)_animations->objectForKey(name); } @@ -95,17 +93,17 @@ void AnimationCache::parseVersion1(Dictionary* animations) { SpriteFrameCache *frameCache = SpriteFrameCache::getInstance(); - DictElement* pElement = NULL; - CCDICT_FOREACH(animations, pElement) + DictElement* element = NULL; + CCDICT_FOREACH(animations, element) { - Dictionary* animationDict = static_cast(pElement->getObject()); + Dictionary* animationDict = static_cast(element->getObject()); Array* frameNames = static_cast(animationDict->objectForKey("frames")); float delay = animationDict->valueForKey("delay")->floatValue(); Animation* animation = 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; } @@ -115,11 +113,11 @@ void AnimationCache::parseVersion1(Dictionary* animations) Object* pObj = NULL; CCARRAY_FOREACH(frameNames, pObj) { - const char* frameName = static_cast(pObj)->getCString(); + const std::string& frameName = static_cast(pObj)->getCString(); SpriteFrame* spriteFrame = frameCache->getSpriteFrameByName(frameName); 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; } @@ -131,15 +129,15 @@ void AnimationCache::parseVersion1(Dictionary* animations) } 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; } 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); - AnimationCache::getInstance()->addAnimation(animation, pElement->getStrKey()); + AnimationCache::getInstance()->addAnimation(animation, element->getStrKey()); frames->release(); } } @@ -148,11 +146,11 @@ void AnimationCache::parseVersion2(Dictionary* animations) { SpriteFrameCache *frameCache = SpriteFrameCache::getInstance(); - DictElement* pElement = NULL; - CCDICT_FOREACH(animations, pElement) + DictElement* element = NULL; + CCDICT_FOREACH(animations, element) { - const char* name = pElement->getStrKey(); - Dictionary* animationDict = static_cast(pElement->getObject()); + const char* name = element->getStrKey(); + Dictionary* animationDict = static_cast(element->getObject()); const String* loops = animationDict->valueForKey("loops"); 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 */ -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); Dictionary* dict = Dictionary::createWithContentsOfFile(path.c_str()); diff --git a/cocos/2d/CCAnimationCache.h b/cocos/2d/CCAnimationCache.h index f30d6ee94f..475c16ce87 100644 --- a/cocos/2d/CCAnimationCache.h +++ b/cocos/2d/CCAnimationCache.h @@ -76,29 +76,29 @@ public: /** 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. */ - void removeAnimation(const char* name); + void removeAnimation(const std::string& name); /** @deprecated. Use removeAnimation() instead * @js 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. If the name is not found it will return nil. 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 * @js 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 Make sure that the frames were previously loaded in the SpriteFrameCache. @@ -112,7 +112,7 @@ public: * @js addAnimations * @lua addAnimations */ - void addAnimationsWithFile(const char* plist); + void addAnimationsWithFile(const std::string& plist); private: void parseVersion1(Dictionary* animations); diff --git a/cocos/2d/CCAtlasNode.cpp b/cocos/2d/CCAtlasNode.cpp index 7d5a64dba7..b756a36193 100644 --- a/cocos/2d/CCAtlasNode.cpp +++ b/cocos/2d/CCAtlasNode.cpp @@ -61,8 +61,7 @@ AtlasNode::~AtlasNode() CC_SAFE_RELEASE(_textureAtlas); } -AtlasNode * AtlasNode::create(const char *tile, unsigned int tileWidth, unsigned int tileHeight, - unsigned int itemsToRender) +AtlasNode * AtlasNode::create(const std::string& tile, long tileWidth, long tileHeight, long itemsToRender) { AtlasNode * pRet = new AtlasNode(); if (pRet->initWithTileFile(tile, tileWidth, tileHeight, itemsToRender)) @@ -74,15 +73,14 @@ AtlasNode * AtlasNode::create(const char *tile, unsigned int tileWidth, unsigned 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"); - Texture2D *texture = TextureCache::getInstance()->addImage(tile); + CCASSERT(tile.size() > 0, "file size should not be empty"); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(tile); return initWithTexture(texture, tileWidth, tileHeight, itemsToRender); } -bool AtlasNode::initWithTexture(Texture2D* texture, unsigned int tileWidth, unsigned int tileHeight, - unsigned int itemsToRender) +bool AtlasNode::initWithTexture(Texture2D* texture, long tileWidth, long tileHeight, long itemsToRender) { _itemWidth = tileWidth; _itemHeight = tileHeight; @@ -247,12 +245,12 @@ TextureAtlas * AtlasNode::getTextureAtlas() const return _textureAtlas; } -unsigned int AtlasNode::getQuadsToDraw() const +long AtlasNode::getQuadsToDraw() const { return _quadsToDraw; } -void AtlasNode::setQuadsToDraw(unsigned int uQuadsToDraw) +void AtlasNode::setQuadsToDraw(long uQuadsToDraw) { _quadsToDraw = uQuadsToDraw; } diff --git a/cocos/2d/CCAtlasNode.h b/cocos/2d/CCAtlasNode.h index 74dcc9f970..8c31496d41 100644 --- a/cocos/2d/CCAtlasNode.h +++ b/cocos/2d/CCAtlasNode.h @@ -52,8 +52,7 @@ class CC_DLL AtlasNode : public NodeRGBA, public TextureProtocol { public: /** 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, - unsigned int itemsToRender); + static AtlasNode * create(const std::string& filename, long tileWidth, long tileHeight, long itemsToRender); /** * @js ctor */ @@ -65,10 +64,10 @@ public: virtual ~AtlasNode(); /** 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*/ - 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). * Shall be overridden in subclasses @@ -78,8 +77,8 @@ public: void setTextureAtlas(TextureAtlas* textureAtlas); TextureAtlas* getTextureAtlas() const; - void setQuadsToDraw(unsigned int quadsToDraw); - unsigned int getQuadsToDraw() const; + void setQuadsToDraw(long quadsToDraw); + long getQuadsToDraw() const; // Overrides @@ -115,14 +114,14 @@ private : protected: //! chars per row - unsigned int _itemsPerRow; + long _itemsPerRow; //! chars per column - unsigned int _itemsPerColumn; + long _itemsPerColumn; //! width of each char - unsigned int _itemWidth; + long _itemWidth; //! height of each char - unsigned int _itemHeight; + long _itemHeight; Color3B _colorUnmodified; @@ -132,7 +131,7 @@ protected: BlendFunc _blendFunc; // quads to draw - unsigned int _quadsToDraw; + long _quadsToDraw; // color uniform GLint _uniformColor; // This varible is only used for LabelAtlas FPS display. So plz don't modify its value. diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index 7255659d07..f948b099bf 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -145,6 +145,8 @@ bool Director::init(void) _scheduler->scheduleUpdateForTarget(_actionManager, Scheduler::PRIORITY_SYSTEM, false); _eventDispatcher = new EventDispatcher(); + //init TextureCache + initTextureCache(); // create autorelease pool 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() { if (_openGLView) @@ -437,7 +462,7 @@ void Director::purgeCachedData(void) if (s_SharedDirector->getOpenGLView()) { SpriteFrameCache::getInstance()->removeUnusedSpriteFrames(); - TextureCache::getInstance()->removeUnusedTextures(); + _textureCache->removeUnusedTextures(); } FileUtils::getInstance()->purgeCachedEntries(); } @@ -693,7 +718,6 @@ void Director::purgeDirector() DrawPrimitives::free(); AnimationCache::destroyInstance(); SpriteFrameCache::destroyInstance(); - TextureCache::destroyInstance(); ShaderCache::destroyInstance(); FileUtils::destroyInstance(); Configuration::destroyInstance(); @@ -704,6 +728,8 @@ void Director::purgeDirector() GL::invalidateStateCache(); + destroyTextureCache(); + CHECK_GL_ERROR_DEBUG(); // OpenGL view @@ -831,7 +857,7 @@ void Director::calculateMPF() } // 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 *datapointer = cc_fps_images_png; @@ -841,21 +867,20 @@ void Director::getFPSImageData(unsigned char** datapointer, unsigned int* length void Director::createStatsLabel() { Texture2D *texture = nullptr; - TextureCache *textureCache = TextureCache::getInstance(); if (_FPSLabel && _SPFLabel) { CC_SAFE_RELEASE_NULL(_FPSLabel); CC_SAFE_RELEASE_NULL(_SPFLabel); CC_SAFE_RELEASE_NULL(_drawsLabel); - textureCache->removeTextureForKey("/cc_fps_images"); + _textureCache->removeTextureForKey("/cc_fps_images"); FileUtils::getInstance()->purgeCachedEntries(); } Texture2D::PixelFormat currentFormat = Texture2D::getDefaultAlphaPixelFormat(); Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); unsigned char *data = nullptr; - unsigned int dataLength = 0; + long dataLength = 0; getFPSImageData(&data, &dataLength); Image* image = new Image(); @@ -865,7 +890,7 @@ void Director::createStatsLabel() return; } - texture = textureCache->addImage(image, "/cc_fps_images"); + texture = _textureCache->addImage(image, "/cc_fps_images"); CC_SAFE_RELEASE(image); /* diff --git a/cocos/2d/CCDirector.h b/cocos/2d/CCDirector.h index 5f0d6eb0a8..0eb4b5d390 100644 --- a/cocos/2d/CCDirector.h +++ b/cocos/2d/CCDirector.h @@ -54,6 +54,7 @@ class Node; class Scheduler; class ActionManager; class EventDispatcher; +class TextureCache; /** @brief Class that creates and handles the main Window and manages how @@ -137,6 +138,8 @@ public: inline EGLView* getOpenGLView() { return _openGLView; } void setOpenGLView(EGLView *pobOpenGLView); + TextureCache* getTextureCache() const; + inline bool isNextDeltaTimeZero() { return _nextDeltaTimeZero; } void setNextDeltaTimeZero(bool nextDeltaTimeZero); @@ -376,11 +379,15 @@ protected: void showStats(); void createStatsLabel(); 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 */ void calculateDeltaTime(); + //textureCache creation or release + void initTextureCache(); + void destroyTextureCache(); + protected: /** Scheduler associated with this director @since v2.0 @@ -403,6 +410,9 @@ protected: /* The EGLView, where everything is rendered */ EGLView *_openGLView; + //texture cache belongs to this director + TextureCache *_textureCache; + double _animationInterval; double _oldAnimationInterval; diff --git a/cocos/2d/CCDrawNode.cpp b/cocos/2d/CCDrawNode.cpp index 496389a85f..0fb35408bf 100644 --- a/cocos/2d/CCDrawNode.cpp +++ b/cocos/2d/CCDrawNode.cpp @@ -141,7 +141,7 @@ DrawNode* DrawNode::create() return pRet; } -void DrawNode::ensureCapacity(int count) +void DrawNode::ensureCapacity(long count) { 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; } -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* extrude = (struct ExtrudeVerts*)malloc(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; } - 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 v1 = __v2f(verts[j]); diff --git a/cocos/2d/CCDrawNode.h b/cocos/2d/CCDrawNode.h index 3e128d26ea..fe7312ade8 100644 --- a/cocos/2d/CCDrawNode.h +++ b/cocos/2d/CCDrawNode.h @@ -71,7 +71,7 @@ public: * In lua:local drawPolygon(local pointTable,local tableCount,local fillColor,local width,local borderColor) * @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. */ void clear(); @@ -99,13 +99,13 @@ public: virtual void draw() override; protected: - void ensureCapacity(int count); + void ensureCapacity(long count); void render(); GLuint _vao; GLuint _vbo; - int _bufferCapacity; + long _bufferCapacity; GLsizei _bufferCount; V2F_C4B_T2F *_buffer; diff --git a/cocos/2d/CCEventListenerTouch.cpp b/cocos/2d/CCEventListenerTouch.cpp index 1367645452..20e620910a 100644 --- a/cocos/2d/CCEventListenerTouch.cpp +++ b/cocos/2d/CCEventListenerTouch.cpp @@ -75,10 +75,9 @@ EventListenerTouchOneByOne* EventListenerTouchOneByOne::create() bool EventListenerTouchOneByOne::checkAvailable() { - if (onTouchBegan == nullptr && onTouchMoved == nullptr - && onTouchEnded == nullptr && onTouchCancelled == nullptr) + if (onTouchBegan == nullptr) { - CCASSERT(false, "Invalid TouchEventListener."); + CCASSERT(false, "Invalid EventListenerTouchOneByOne!"); return false; } @@ -150,7 +149,7 @@ bool EventListenerTouchAllAtOnce::checkAvailable() if (onTouchesBegan == nullptr && onTouchesMoved == nullptr && onTouchesEnded == nullptr && onTouchesCancelled == nullptr) { - CCASSERT(false, "Invalid TouchEventListener."); + CCASSERT(false, "Invalid EventListenerTouchAllAtOnce!"); return false; } diff --git a/cocos/2d/CCFont.cpp b/cocos/2d/CCFont.cpp index cad004a906..c48acdc0b5 100644 --- a/cocos/2d/CCFont.cpp +++ b/cocos/2d/CCFont.cpp @@ -75,7 +75,7 @@ void Font::setCurrentGlyphCollection(GlyphCollection glyphs, const char *customG default: if (customGlyphs) { - int lenght = strlen(customGlyphs); + size_t lenght = strlen(customGlyphs); _customGlyphs = new char [lenght + 2]; 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); } -Font* Font::createWithFNT(const char* fntFilePath) +Font* Font::createWithFNT(const std::string& fntFilePath) { return FontFNT::create(fntFilePath); } diff --git a/cocos/2d/CCFont.h b/cocos/2d/CCFont.h index e4bcb141ce..cf3084011d 100644 --- a/cocos/2d/CCFont.h +++ b/cocos/2d/CCFont.h @@ -42,21 +42,21 @@ class CC_DLL Font : public Object public: // create the font - static Font* createWithTTF(const char* fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); - static Font* createWithFNT(const char* fntFilePath); + static Font* createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); + static Font* createWithFNT(const std::string& fntFilePath); virtual FontAtlas *createFontAtlas() = 0; - virtual Size * getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const = 0; - virtual const char * getCurrentGlyphCollection() const; + virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const = 0; + virtual const char* getCurrentGlyphCollection() const; - virtual int getLetterPadding() const { return 0; } - virtual unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const { return 0; } - virtual GlyphDef * getGlyphDefintionsForText(const char *text, int &outNumGlyphs, bool UTF16text = false) const { return 0; } - virtual int getFontMaxHeight() const { return 0; } - virtual Rect getRectForChar(unsigned short theChar) const; + virtual int getLetterPadding() const { return 0; } + virtual unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const { return 0; } + virtual GlyphDef* getGlyphDefintionsForText(const char *text, int &outNumGlyphs, bool UTF16text = false) const { return 0; } + virtual int getFontMaxHeight() const { return 0; } + virtual 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 * trimUTF16Text(unsigned short int *text, int newBegin, int newEnd) const; @@ -71,8 +71,7 @@ protected: void setCurrentGlyphCollection(GlyphCollection glyphs, const char *customGlyphs = 0); const char * getGlyphCollection(GlyphCollection glyphs) const; -private: - + GlyphCollection _usedGlyphs; char * _customGlyphs; static const char * _glyphASCII; diff --git a/cocos/2d/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp index 24b56bd448..72f29e13d8 100644 --- a/cocos/2d/CCFontAtlas.cpp +++ b/cocos/2d/CCFontAtlas.cpp @@ -1,10 +1,26 @@ -// -// CCFontAtlas.cpp -// cocos2d_libs -// -// Created by Carlo Morgantini on 7/18/13. -// -// +/**************************************************************************** + Copyright (c) 2013 Zynga Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "cocos2d.h" #include "CCFontAtlas.h" diff --git a/cocos/2d/CCFontAtlas.h b/cocos/2d/CCFontAtlas.h index a388a5b987..317a06561d 100644 --- a/cocos/2d/CCFontAtlas.h +++ b/cocos/2d/CCFontAtlas.h @@ -24,7 +24,7 @@ #ifndef _CCFontAtlas_h_ #define _CCFontAtlas_h_ -#include +#include NS_CC_BEGIN @@ -34,17 +34,17 @@ class Font; struct FontLetterDefinition { unsigned short letteCharUTF16; - float U; - float V; - float width; - float height; - float offsetX; - float offsetY; - int textureID; - float commonLineHeight; - float anchorX; - float anchorY; - bool validDefinition; + float U; + float V; + float width; + float height; + float offsetX; + float offsetY; + int textureID; + float commonLineHeight; + float anchorX; + float anchorY; + bool validDefinition; }; class CC_DLL FontAtlas : public Object @@ -69,26 +69,26 @@ public: float getCommonLineHeight() const; void setCommonLineHeight(float newHeight); - Texture2D & getTexture(int slot); - const Font * getFont() const; + Texture2D& getTexture(int slot); + const Font* getFont() const; private: bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize); void relaseTextures(); - std::map _atlasTextures; - std::map _fontLetterDefinitions; - float _commonLineHeight; - Font * _font; + std::unordered_map _atlasTextures; + std::unordered_map _fontLetterDefinitions; + float _commonLineHeight; + Font * _font; // Dynamic GlyphCollection related stuff - int _currentPage; - unsigned char *_currentPageData; - int _currentPageDataSize; - float _currentPageOrigX; - float _currentPageOrigY; - float _currentPageLineHeight; - float _letterPadding; + int _currentPage; + unsigned char *_currentPageData; + int _currentPageDataSize; + float _currentPageOrigX; + float _currentPageOrigY; + float _currentPageLineHeight; + float _letterPadding; }; diff --git a/cocos/2d/CCFontAtlasCache.cpp b/cocos/2d/CCFontAtlasCache.cpp index 762a506ae4..00fc1e2a1f 100644 --- a/cocos/2d/CCFontAtlasCache.cpp +++ b/cocos/2d/CCFontAtlasCache.cpp @@ -28,7 +28,7 @@ NS_CC_BEGIN -std::map FontAtlasCache::_atlasMap; +std::unordered_map FontAtlasCache::_atlasMap; FontAtlas * FontAtlasCache::getFontAtlasTTF(const char *fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs) { diff --git a/cocos/2d/CCFontAtlasCache.h b/cocos/2d/CCFontAtlasCache.h index c63c832d48..f5f8ca7df4 100644 --- a/cocos/2d/CCFontAtlasCache.h +++ b/cocos/2d/CCFontAtlasCache.h @@ -26,7 +26,7 @@ #define _CCFontAtlasCache_h_ #include -#include +#include #include "cocos2d.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 * getFontAtlasFNT(const char *fontFileName); - static bool releaseFontAtlas(FontAtlas *atlas); + static bool releaseFontAtlas(FontAtlas *atlas); private: static std::string generateFontName(const char *fontFileName, int size, GlyphCollection theGlyphs); - static std::map _atlasMap; + static std::unordered_map _atlasMap; }; NS_CC_END diff --git a/cocos/2d/CCFontAtlasFactory.cpp b/cocos/2d/CCFontAtlasFactory.cpp index f5e4f60802..b1cd69172f 100644 --- a/cocos/2d/CCFontAtlasFactory.cpp +++ b/cocos/2d/CCFontAtlasFactory.cpp @@ -1,10 +1,26 @@ -// -// CCFontAtlasFactory.cpp -// cocos2d_libs -// -// Created by Carlo Morgantini on 7/23/13. -// -// +/**************************************************************************** + Copyright (c) 2013 Zynga Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "CCFontAtlasFactory.h" #include "CCFontFNT.h" diff --git a/cocos/2d/CCFontDefinition.cpp b/cocos/2d/CCFontDefinition.cpp index 938204f3b0..d8414dc64d 100644 --- a/cocos/2d/CCFontDefinition.cpp +++ b/cocos/2d/CCFontDefinition.cpp @@ -27,7 +27,7 @@ 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) { @@ -36,7 +36,7 @@ FontDefinitionTTF::FontDefinitionTTF():_textImages(0), _commonLineHeight(0) FontDefinitionTTF* FontDefinitionTTF::create(Font *font, int textureSize) { if (textureSize == 0) - textureSize = DEFAUL_ATALS_TEXTURE_SIZE; + textureSize = DEFAUL_ATLAS_TEXTURE_SIZE; FontDefinitionTTF *ret = new FontDefinitionTTF; @@ -82,8 +82,8 @@ bool FontDefinitionTTF::prepareLetterDefinitions(TextFontPagesDef *pageDefs) // loops all the lines in this page for (int cLines = 0; cLinesgetPageAt(cPages)->getNumLines(); ++cLines) { - float posXUV = 0.0; - float posYUV = pages->getPageAt(cPages)->getLineAt(cLines)->getY(); + float posXUV = 0.0; + float posYUV = pages->getPageAt(cPages)->getLineAt(cLines)->getY(); int charsCounter = 0; diff --git a/cocos/2d/CCFontDefinition.h b/cocos/2d/CCFontDefinition.h index f5e6da10b6..1f9504920c 100644 --- a/cocos/2d/CCFontDefinition.h +++ b/cocos/2d/CCFontDefinition.h @@ -25,6 +25,8 @@ #ifndef _FontDefinition_h_ #define _FontDefinition_h_ +#include + #include "CCTextImage.h" #include "CCFont.h" #include "CCFontAtlas.h" @@ -55,11 +57,11 @@ private: bool prepareLetterDefinitions(TextFontPagesDef *pageDefs); void addLetterDefinition(const FontLetterDefinition &defToAdd); - TextImage * _textImages; - std::map _fontLettersDefinitionUTF16; - float _commonLineHeight; - static const int DEFAUL_ATALS_TEXTURE_SIZE; - + TextImage * _textImages; + std::unordered_map _fontLettersDefinitionUTF16; + float _commonLineHeight; + + static const int DEFAUL_ATLAS_TEXTURE_SIZE; }; NS_CC_END diff --git a/cocos/2d/CCFontFNT.cpp b/cocos/2d/CCFontFNT.cpp index e655236a1b..25709c714e 100644 --- a/cocos/2d/CCFontFNT.cpp +++ b/cocos/2d/CCFontFNT.cpp @@ -1,24 +1,40 @@ -// -// CCFontFNT.cpp -// cocos2d_libs -// -// Created by Carlo Morgantini on 7/24/13. -// -// +/**************************************************************************** + Copyright (c) 2013 Zynga Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "CCFontFNT.h" #include "CCFontAtlas.h" NS_CC_BEGIN -FontFNT * FontFNT::create(const char* fntFilePath) +FontFNT * FontFNT::create(const std::string& fntFilePath) { CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFilePath); if (!newConf) return nullptr; // add the texture - Texture2D *tempTexture = TextureCache::getInstance()->addImage(newConf->getAtlasName()); + Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(newConf->getAtlasName()); if (!tempTexture) { delete newConf; @@ -182,7 +198,7 @@ FontAtlas * FontFNT::createFontAtlas() // 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) return 0; diff --git a/cocos/2d/CCFontFNT.h b/cocos/2d/CCFontFNT.h index 3994e14463..e9c4327672 100644 --- a/cocos/2d/CCFontFNT.h +++ b/cocos/2d/CCFontFNT.h @@ -35,7 +35,7 @@ class FontFNT : public Font 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 Rect getRectForChar(unsigned short theChar) const override; @@ -43,7 +43,8 @@ public: protected: - FontFNT(CCBMFontConfiguration *theContfig) : _configuration(theContfig) {} + FontFNT(CCBMFontConfiguration *theContfig) : + _configuration(theContfig) {} /** * @js NA * @lua NA @@ -56,7 +57,7 @@ private: int getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const; Rect getRectForCharInternal(unsigned short theChar) const; - CCBMFontConfiguration * _configuration; + CCBMFontConfiguration * _configuration; }; diff --git a/cocos/2d/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp index 0e4e49d96f..5e2173204f 100644 --- a/cocos/2d/CCFontFreeType.cpp +++ b/cocos/2d/CCFontFreeType.cpp @@ -99,8 +99,8 @@ bool FontFreeType::createFontObject(const std::string &fontName, int fontSize) { FT_Face face; - int len = 0; - _ttfData = FileUtils::getInstance()->getFileData(fontName.c_str(), "rb", (unsigned long *)(&len)); + long len = 0; + _ttfData = FileUtils::getInstance()->getFileData(fontName.c_str(), "rb", &len); if (!_ttfData) return false; diff --git a/cocos/2d/CCGrabber.h b/cocos/2d/CCGrabber.h index 9fef542459..022e68ed0d 100644 --- a/cocos/2d/CCGrabber.h +++ b/cocos/2d/CCGrabber.h @@ -59,7 +59,7 @@ public: protected: GLuint _FBO; GLint _oldFBO; - GLfloat _oldClearColor[4]; + GLfloat _oldClearColor[4]; }; // end of effects group diff --git a/cocos/2d/CCGrid.cpp b/cocos/2d/CCGrid.cpp index fc2152ab13..717277eff8 100644 --- a/cocos/2d/CCGrid.cpp +++ b/cocos/2d/CCGrid.cpp @@ -119,7 +119,7 @@ bool GridBase::initWithSize(const Size& gridSize) // we only use rgba8888 Texture2D::PixelFormat format = Texture2D::PixelFormat::RGBA8888; - int dataLen = (int)(POTWide * POTHigh * 4); + long dataLen = POTWide * POTHigh * 4; void *data = calloc(dataLen, 1); if (! data) { diff --git a/cocos/2d/CCGrid.h b/cocos/2d/CCGrid.h index 97904cdf3e..61a8cbbe34 100644 --- a/cocos/2d/CCGrid.h +++ b/cocos/2d/CCGrid.h @@ -66,23 +66,23 @@ public: bool initWithSize(const Size& gridSize); /** whether or not the grid is active */ - inline bool isActive(void) { return _active; } + inline bool isActive(void) const { return _active; } void setActive(bool bActive); /** 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; } /** 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; } /** 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; } /** is texture flipped */ - inline bool isTextureFlipped(void) { return _isTextureFlipped; } + inline bool isTextureFlipped(void) const { return _isTextureFlipped; } void setTextureFlipped(bool bFlipped); void beforeDraw(void); @@ -95,7 +95,7 @@ public: protected: bool _active; - int _reuseGrid; + long _reuseGrid; Size _gridSize; Texture2D *_texture; Point _step; diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 09192c0e89..0dc7fc5081 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -29,9 +29,9 @@ 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) return nullptr; @@ -48,10 +48,10 @@ Label* Label::createWithTTF( const char* label, const char* fontFilePath, int fo 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) return 0; @@ -135,12 +135,12 @@ bool Label::init() return true; } -void Label::setString(const char *stringToRender) +void Label::setString(const std::string &stringToRender) { 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) return false; @@ -158,8 +158,8 @@ bool Label::setText(const char *stringToRender, float lineWidth, TextHAlignment if (_commonLineHeight <= 0) return false; - int numLetter = 0; - unsigned short* utf16String = cc_utf8_to_utf16(stringToRender); +// int numLetter = 0; + unsigned short* utf16String = cc_utf8_to_utf16(stringToRender.c_str()); if(!utf16String) return false; diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index 0d668256f2..d781196777 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -51,13 +51,13 @@ class CC_DLL Label : public SpriteBatchNode, public LabelProtocol, public RGBAPr public: // 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 setWidth(float width); virtual void setLineBreakWithoutSpace(bool breakWithoutSpace); @@ -83,38 +83,38 @@ public: // CCLabelTextFormat protocol implementation virtual std::vector *getLettersInfo() override { return &_lettersInfo; }; - virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex) override; - virtual bool recordPlaceholderInfo(int spriteIndex) override; - virtual float getLetterPosXLeft( int index ) const override; - virtual float getLetterPosXRight( int index ) const override; + virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex) override; + virtual bool recordPlaceholderInfo(int spriteIndex) override; + virtual float getLetterPosXLeft( int index ) const override; + virtual float getLetterPosXRight( int index ) const override; - virtual Sprite * getLetter(int ID) override; + virtual Sprite * getLetter(int ID) override; // font related stuff - virtual int getCommonLineHeight() const override; - virtual int getKerningForCharsPair(unsigned short first, unsigned short second) const override; - virtual int getXOffsetForChar(unsigned short c) const override; - virtual int getYOffsetForChar(unsigned short c) const override; - virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const override; - virtual Rect getRectForChar(unsigned short c) const override; + virtual int getCommonLineHeight() const override; + virtual int getKerningForCharsPair(unsigned short first, unsigned short second) const override; + virtual int getXOffsetForChar(unsigned short c) const override; + virtual int getYOffsetForChar(unsigned short c) const override; + virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const override; + virtual Rect getRectForChar(unsigned short c) const override; // string related stuff - virtual int getStringNumLines() const override; - virtual int getStringLenght() const override; - virtual unsigned short getCharAtStringPosition(int position) const override; - virtual unsigned short * getUTF8String() const override; - virtual void assignNewUTF8String(unsigned short *newString) override; - virtual TextHAlignment getTextAlignment() const override; + virtual int getStringNumLines() const override; + virtual int getStringLenght() const override; + virtual unsigned short getCharAtStringPosition(int position) const override; + virtual unsigned short * getUTF8String() const override; + virtual void assignNewUTF8String(unsigned short *newString) override; + virtual TextHAlignment getTextAlignment() const override; // label related stuff - virtual float getMaxLineWidth() const override; - virtual bool breakLineWithoutSpace() const override; - virtual Size getLabelContentSize() const override; - virtual void setLabelContentSize(const Size &newSize) override; + virtual float getMaxLineWidth() const override; + virtual bool breakLineWithoutSpace() const override; + virtual Size getLabelContentSize() const override; + virtual void setLabelContentSize(const Size &newSize) override; // carloX - const char * getString() const { return "not implemented"; } - void addChild(Node * child, int zOrder=0, int tag=0); + 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) override; private: /** diff --git a/cocos/2d/CCLabelAtlas.cpp b/cocos/2d/CCLabelAtlas.cpp index e96df277b5..b9115741e3 100644 --- a/cocos/2d/CCLabelAtlas.cpp +++ b/cocos/2d/CCLabelAtlas.cpp @@ -42,7 +42,7 @@ NS_CC_BEGIN //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(); 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; } -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); } -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, strlen(string))) + if (AtlasNode::initWithTexture(texture, itemWidth, itemHeight, string.size())) { _mapStartChar = startCharMap; this->setString(string); @@ -72,7 +71,7 @@ bool LabelAtlas::initWithString(const char *string, Texture2D* texture, unsigned 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(); if (ret) @@ -90,30 +89,30 @@ LabelAtlas* LabelAtlas::create(const char *string, const char *fntFile) 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 relPathStr = pathStr.substr(0, pathStr.find_last_of("/"))+"/"; - 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(); - + std::string pathStr = FileUtils::getInstance()->fullPathForFilename(fntFile); + std::string relPathStr = pathStr.substr(0, pathStr.find_last_of("/"))+"/"; + Dictionary *dict = Dictionary::createWithContentsOfFile(pathStr.c_str()); - this->initWithString(theString, textureFilename->getCString(), width, height, startChar); - - return true; + 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); + + return true; } //CCLabelAtlas - Atlas generation void LabelAtlas::updateAtlasValues() { - int n = _string.length(); + size_t n = _string.length(); const unsigned char *s = (unsigned char*)_string.c_str(); @@ -186,9 +185,9 @@ void LabelAtlas::updateAtlasValues() } //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()) { _textureAtlas->resizeCapacity(len); @@ -204,9 +203,9 @@ void LabelAtlas::setString(const char *label) _quadsToDraw = len; } -const char* LabelAtlas::getString(void) const +const std::string& LabelAtlas::getString(void) const { - return _string.c_str(); + return _string; } //CCLabelAtlas - draw diff --git a/cocos/2d/CCLabelAtlas.h b/cocos/2d/CCLabelAtlas.h index 2c7d98ea5b..8fd81b9bda 100644 --- a/cocos/2d/CCLabelAtlas.h +++ b/cocos/2d/CCLabelAtlas.h @@ -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 */ - 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 @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 */ - 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 @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 */ - 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 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 - virtual void draw(); + virtual void draw() override; #endif protected: // string to render std::string _string; // the first char in the charmap - unsigned int _mapStartChar; + long _mapStartChar; }; // end of GUI group diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index 601187d619..6749c5d107 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -62,9 +62,9 @@ static unsigned short* copyUTF16StringN(unsigned short* str) // 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 ) { @@ -72,17 +72,17 @@ CCBMFontConfiguration* FNTConfigLoadFile( const char *fntFile) s_pConfigurations->init(); } - pRet = static_cast( s_pConfigurations->objectForKey(fntFile) ); - if( pRet == NULL ) + ret = static_cast( s_pConfigurations->objectForKey(fntFile) ); + if( ret == NULL ) { - pRet = CCBMFontConfiguration::create(fntFile); - if (pRet) + ret = CCBMFontConfiguration::create(fntFile.c_str()); + if (ret) { - s_pConfigurations->setObject(pRet, fntFile); + s_pConfigurations->setObject(ret, fntFile); } } - return pRet; + return ret; } void FNTConfigRemoveCache( void ) @@ -98,19 +98,19 @@ void FNTConfigRemoveCache( void ) //BitmapFontConfiguration // -CCBMFontConfiguration * CCBMFontConfiguration::create(const char *FNTfile) +CCBMFontConfiguration * CCBMFontConfiguration::create(const std::string& FNTfile) { - CCBMFontConfiguration * pRet = new CCBMFontConfiguration(); - if (pRet->initWithFNTfile(FNTfile)) + CCBMFontConfiguration * ret = new CCBMFontConfiguration(); + if (ret->initWithFNTfile(FNTfile)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } -bool CCBMFontConfiguration::initWithFNTfile(const char *FNTfile) +bool CCBMFontConfiguration::initWithFNTfile(const std::string& FNTfile) { _kerningDictionary = NULL; _fontDefDictionary = NULL; @@ -180,7 +180,7 @@ void CCBMFontConfiguration::purgeFontDefDictionary() } } -std::set* CCBMFontConfiguration::parseConfigFile(const char *controlFile) +std::set* CCBMFontConfiguration::parseConfigFile(const std::string& controlFile) { std::string fullpath = FileUtils::getInstance()->fullPathForFilename(controlFile); String *contents = String::createWithContentsOfFile(fullpath.c_str()); @@ -191,7 +191,7 @@ std::set* CCBMFontConfiguration::parseConfigFile(const char *contr if (!contents) { - CCLOG("cocos2d: Error parsing FNTfile %s", controlFile); + CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.c_str()); return NULL; } @@ -200,7 +200,7 @@ std::set* CCBMFontConfiguration::parseConfigFile(const char *contr std::string strLeft = contents->getCString(); while (strLeft.length() > 0) { - int pos = strLeft.find('\n'); + size_t pos = strLeft.find('\n'); if (pos != (int)std::string::npos) { @@ -259,7 +259,7 @@ std::set* CCBMFontConfiguration::parseConfigFile(const char *contr return validCharsString; } -void CCBMFontConfiguration::parseImageFileName(std::string line, const char *fntFile) +void CCBMFontConfiguration::parseImageFileName(std::string line, const std::string& fntFile) { ////////////////////////////////////////////////////////////////////////// // line to parse: @@ -267,8 +267,8 @@ void CCBMFontConfiguration::parseImageFileName(std::string line, const char *fnt ////////////////////////////////////////////////////////////////////////// // page ID. Sanity check - int index = line.find('=')+1; - int index2 = line.find(' ', index); + long index = line.find('=')+1; + long index2 = line.find(' ', index); std::string value = line.substr(index, index2-index); CCASSERT(atoi(value.c_str()) == 0, "LabelBMFont file could not be found"); // file @@ -288,8 +288,8 @@ void CCBMFontConfiguration::parseInfoArguments(std::string line) ////////////////////////////////////////////////////////////////////////// // padding - int index = line.find("padding="); - int index2 = line.find(' ', index); + long index = line.find("padding="); + long index2 = line.find(' ', 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); 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 - int index = line.find("lineHeight="); - int index2 = line.find(' ', index); + long index = line.find("lineHeight="); + long index2 = line.find(' ', index); std::string value = line.substr(index, index2-index); sscanf(value.c_str(), "lineHeight=%d", &_commonHeight); // scaleW. sanity check @@ -334,8 +334,8 @@ void CCBMFontConfiguration::parseCharacterDefinition(std::string line, ccBMFontD ////////////////////////////////////////////////////////////////////////// // Character ID - int index = line.find("id="); - int index2 = line.find(' ', index); + long index = line.find("id="); + long index2 = line.find(' ', index); std::string value = line.substr(index, index2-index); sscanf(value.c_str(), "id=%u", &characterDefinition->charID); @@ -385,8 +385,8 @@ void CCBMFontConfiguration::parseKerningEntry(std::string line) // first int first; - int index = line.find("first="); - int index2 = line.find(' ', index); + long index = line.find("first="); + long index2 = line.find(' ', index); std::string value = line.substr(index, index2-index); sscanf(value.c_str(), "first=%d", &first); @@ -431,23 +431,23 @@ LabelBMFont * LabelBMFont::create() 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); } -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); } -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); } //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(); 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() { - 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( (theString && fntFile) || (theString==NULL && fntFile==NULL), "Invalid params for LabelBMFont"); - + Texture2D *texture = NULL; - if (fntFile) + if (fntFile.size() > 0 ) { CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFile); 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(); return false; } @@ -487,7 +486,7 @@ bool LabelBMFont::initWithString(const char *theString, const char *fntFile, flo _fntFile = fntFile; - texture = TextureCache::getInstance()->addImage(_configuration->getAtlasName()); + texture = Director::getInstance()->getTextureCache()->addImage(_configuration->getAtlasName()); } else { @@ -495,12 +494,7 @@ bool LabelBMFont::initWithString(const char *theString, const char *fntFile, flo texture->autorelease(); } - if (theString == NULL) - { - theString = ""; - } - - if (SpriteBatchNode::initWithTexture(texture, strlen(theString))) + if (SpriteBatchNode::initWithTexture(texture, theString.size())) { _width = width; _alignment = alignment; @@ -724,20 +718,17 @@ void LabelBMFont::createFontChars() } //LabelBMFont - LabelProtocol protocol -void LabelBMFont::setString(const char *newString) +void LabelBMFont::setString(const std::string &newString) { 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) { _initialStringUTF8 = newString; } - unsigned short* utf16String = cc_utf8_to_utf16(newString); + unsigned short* utf16String = cc_utf8_to_utf16(newString.c_str()); setString(utf16String, needUpdateLabel); 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) @@ -1082,9 +1073,9 @@ void LabelBMFont::updateLabel() int size = multiline_string.size(); 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'; @@ -1222,7 +1213,7 @@ void LabelBMFont::setFntFile(const char* fntFile) CC_SAFE_RELEASE(_configuration); _configuration = newConf; - this->setTexture(TextureCache::getInstance()->addImage(_configuration->getAtlasName())); + this->setTexture(Director::getInstance()->getTextureCache()->addImage(_configuration->getAtlasName())); this->createFontChars(); } } diff --git a/cocos/2d/CCLabelBMFont.h b/cocos/2d/CCLabelBMFont.h index 11ff078ac5..a825d28ed6 100644 --- a/cocos/2d/CCLabelBMFont.h +++ b/cocos/2d/CCLabelBMFont.h @@ -140,21 +140,21 @@ public: const char * description() const; /** 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 */ - bool initWithFNTfile(const char *FNTfile); + bool initWithFNTfile(const std::string& FNTfile); - inline const char* getAtlasName(){ return _atlasName.c_str(); } - inline void setAtlasName(const char* atlasName) { _atlasName = atlasName; } + inline const std::string& getAtlasName(){ return _atlasName; } + inline void setAtlasName(const std::string& atlasName) { _atlasName = atlasName; } std::set* getCharacterSet() const; private: - std::set* parseConfigFile(const char *controlFile); + std::set* parseConfigFile(const std::string& controlFile); void parseCharacterDefinition(std::string line, ccBMFontDef *characterDefinition); void parseInfoArguments(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 purgeKerningDictionary(); void purgeFontDefDictionary(); @@ -209,13 +209,13 @@ public: static void purgeCachedData(); /** 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. */ @@ -223,15 +223,15 @@ public: bool init(); /** 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 */ void createFontChars(); // super method - virtual void setString(const char *newString); - virtual void setString(const char *newString, bool needUpdateLabel); + virtual void setString(const std::string& newString) override; + 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 setAnchorPoint(const Point& var); virtual void updateLabel(); @@ -264,7 +264,7 @@ public: virtual void draw(); #endif // CC_LABELBMFONT_DEBUG_DRAW private: - char * atlasNameFromFntFile(const char *fntFile); + char * atlasNameFromFntFile(const std::string& fntFile); int kerningAmountForFirst(unsigned short first, unsigned short second); float getLetterPosXLeft( Sprite* characterSprite ); float getLetterPosXRight( Sprite* characterSprite ); @@ -303,13 +303,13 @@ protected: bool _cascadeColorEnabled; bool _cascadeOpacityEnabled; /** conforms to RGBAProtocol protocol */ - bool _isOpacityModifyRGB; + bool _isOpacityModifyRGB; }; /** 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 */ CC_DLL void FNTConfigRemoveCache( void ); diff --git a/cocos/2d/CCLabelTTF.cpp b/cocos/2d/CCLabelTTF.cpp index bead3ea020..179f079e50 100644 --- a/cocos/2d/CCLabelTTF.cpp +++ b/cocos/2d/CCLabelTTF.cpp @@ -42,7 +42,7 @@ NS_CC_BEGIN LabelTTF::LabelTTF() : _alignment(TextHAlignment::CENTER) , _vAlignment(TextVAlignment::TOP) -, _fontName(NULL) +, _fontName("") , _fontSize(0.0) , _string("") , _shadowEnabled(false) @@ -53,58 +53,57 @@ LabelTTF::LabelTTF() LabelTTF::~LabelTTF() { - CC_SAFE_DELETE(_fontName); } LabelTTF * LabelTTF::create() { - LabelTTF * pRet = new LabelTTF(); - if (pRet && pRet->init()) + LabelTTF * ret = new LabelTTF(); + if (ret && ret->init()) { - pRet->autorelease(); + ret->autorelease(); } 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, 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) { 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, TextVAlignment vAlignment) { - LabelTTF *pRet = new LabelTTF(); - if(pRet && pRet->initWithString(string, fontName, fontSize, dimensions, hAlignment, vAlignment)) + LabelTTF *ret = new LabelTTF(); + if(ret && ret->initWithString(string, fontName, fontSize, dimensions, hAlignment, vAlignment)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } -LabelTTF * LabelTTF::createWithFontDefinition(const char *string, FontDefinition &textDefinition) +LabelTTF * LabelTTF::createWithFontDefinition(const std::string& string, FontDefinition &textDefinition) { - LabelTTF *pRet = new LabelTTF(); - if(pRet && pRet->initWithStringAndTextDefinition(string, textDefinition)) + LabelTTF *ret = new LabelTTF(); + if(ret && ret->initWithStringAndTextDefinition(string, textDefinition)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } @@ -113,19 +112,19 @@ bool LabelTTF::init() 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) { 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, 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, TextVAlignment vAlignment) { @@ -135,10 +134,10 @@ bool LabelTTF::initWithString(const char *string, const char *fontName, float fo this->setShaderProgram(ShaderCache::getInstance()->getProgram(SHADER_PROGRAM)); _dimensions = Size(dimensions.width, dimensions.height); - _alignment = hAlignment; - _vAlignment = vAlignment; - _fontName = new std::string(fontName); - _fontSize = fontSize; + _alignment = hAlignment; + _vAlignment = vAlignment; + _fontName = fontName; + _fontSize = fontSize; this->setString(string); @@ -148,7 +147,7 @@ bool LabelTTF::initWithString(const char *string, const char *fontName, float fo return false; } -bool LabelTTF::initWithStringAndTextDefinition(const char *string, FontDefinition &textDefinition) +bool LabelTTF::initWithStringAndTextDefinition(const std::string& string, FontDefinition &textDefinition) { 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)) { _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 { - return String::createWithFormat("", _fontName->c_str(), _fontSize)->getCString(); + return String::createWithFormat("", _fontName.c_str(), _fontSize)->getCString(); } TextHAlignment LabelTTF::getHorizontalAlignment() const @@ -238,6 +235,7 @@ const Size& LabelTTF::getDimensions() const void LabelTTF::setDimensions(const Size &dim) { + // XXX: float comparison... very unreliable if (dim.width != _dimensions.width || dim.height != _dimensions.height) { _dimensions = dim; @@ -257,6 +255,7 @@ float LabelTTF::getFontSize() const void LabelTTF::setFontSize(float fontSize) { + // XXX: float comparison... very unreliable if (_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 = new std::string(fontName); + _fontName = fontName; // Force update if (_string.size() > 0) @@ -298,21 +296,21 @@ bool LabelTTF::updateTexture() if (!tex) 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); tex->initWithString( _string.c_str(), texDef ); - #else +#else tex->initWithString( _string.c_str(), - _fontName->c_str(), + _fontName.c_str(), _fontSize * CC_CONTENT_SCALE_FACTOR(), CC_SIZE_POINTS_TO_PIXELS(_dimensions), _alignment, _vAlignment); - #endif +#endif // set the texture 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) ) { - _shadowOffset.width = shadowOffset.width; + _shadowOffset.width = shadowOffset.width; _shadowOffset.height = shadowOffset.height; valueChanged = true; @@ -354,27 +352,26 @@ void LabelTTF::enableShadow(const Size &shadowOffset, float shadowOpacity, float valueChanged = true; } - if (_shadowBlur != shadowBlur) + if (_shadowBlur != shadowBlur) { _shadowBlur = shadowBlur; valueChanged = true; } - if ( valueChanged && updateTexture ) { this->updateTexture(); } - #else +#else CCLOGERROR("Currently only supported on iOS and Android!"); - #endif +#endif } 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) { @@ -382,17 +379,16 @@ void LabelTTF::disableShadow(bool updateTexture) if (updateTexture) this->updateTexture(); - } - #else +#else CCLOGERROR("Currently only supported on iOS and Android!"); - #endif +#endif } 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; @@ -419,15 +415,15 @@ void LabelTTF::enableStroke(const Color3B &strokeColor, float strokeSize, bool u this->updateTexture(); } - #else +#else CCLOGERROR("Currently only supported on iOS and Android!"); - #endif +#endif } 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) { @@ -437,15 +433,15 @@ void LabelTTF::disableStroke(bool updateTexture) this->updateTexture(); } - #else +#else CCLOGERROR("Currently only supported on iOS and Android!"); - #endif +#endif } 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) { _textFillColor = tintColor; @@ -453,9 +449,9 @@ void LabelTTF::setFontFillColor(const Color3B &tintColor, bool updateTexture) if (updateTexture) this->updateTexture(); } - #else +#else CCLOGERROR("Currently only supported on iOS and Android!"); - #endif +#endif } void LabelTTF::setTextDefinition(const FontDefinition& theDefinition) @@ -471,11 +467,11 @@ FontDefinition LabelTTF::getTextDefinition() void LabelTTF::_updateWithTextDefinition(const FontDefinition& textDefinition, bool mustUpdateTexture) { _dimensions = Size(textDefinition._dimensions.width, textDefinition._dimensions.height); - _alignment = textDefinition._alignment; - _vAlignment = textDefinition._vertAlignment; + _alignment = textDefinition._alignment; + _vAlignment = textDefinition._vertAlignment; - _fontName = new std::string(textDefinition._fontName); - _fontSize = textDefinition._fontSize; + _fontName = textDefinition._fontName; + _fontSize = textDefinition._fontSize; // shadow @@ -502,19 +498,19 @@ FontDefinition LabelTTF::_prepareTextDefinition(bool adjustForResolution) FontDefinition texDef; if (adjustForResolution) - texDef._fontSize = _fontSize * CC_CONTENT_SCALE_FACTOR(); + texDef._fontSize = _fontSize * CC_CONTENT_SCALE_FACTOR(); else - texDef._fontSize = _fontSize; + texDef._fontSize = _fontSize; - texDef._fontName = *_fontName; - texDef._alignment = _alignment; - texDef._vertAlignment = _vAlignment; + texDef._fontName = _fontName; + texDef._alignment = _alignment; + texDef._vertAlignment = _vAlignment; if (adjustForResolution) - texDef._dimensions = CC_SIZE_POINTS_TO_PIXELS(_dimensions); + texDef._dimensions = CC_SIZE_POINTS_TO_PIXELS(_dimensions); else - texDef._dimensions = _dimensions; + texDef._dimensions = _dimensions; // stroke @@ -527,21 +523,18 @@ FontDefinition LabelTTF::_prepareTextDefinition(bool adjustForResolution) texDef._stroke._strokeSize = _strokeSize * CC_CONTENT_SCALE_FACTOR(); else texDef._stroke._strokeSize = _strokeSize; - - } else { texDef._stroke._strokeEnabled = false; } - // shadow if ( _shadowEnabled ) { - texDef._shadow._shadowEnabled = true; - texDef._shadow._shadowBlur = _shadowBlur; - texDef._shadow._shadowOpacity = _shadowOpacity; + texDef._shadow._shadowEnabled = true; + texDef._shadow._shadowBlur = _shadowBlur; + texDef._shadow._shadowOpacity = _shadowOpacity; if (adjustForResolution) texDef._shadow._shadowOffset = CC_SIZE_POINTS_TO_PIXELS(_shadowOffset); diff --git a/cocos/2d/CCLabelTTF.h b/cocos/2d/CCLabelTTF.h index 9243a50e1c..8c5689e3d0 100644 --- a/cocos/2d/CCLabelTTF.h +++ b/cocos/2d/CCLabelTTF.h @@ -75,39 +75,39 @@ public: /** creates a LabelTTF with a font name and font size in points @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. @since v2.0.1 */ - static LabelTTF * create(const char *string, const char *fontName, float fontSize, - const Size& dimensions, TextHAlignment hAlignment); + static LabelTTF * create(const std::string& string, const std::string& fontName, float fontSize, + const Size& dimensions, TextHAlignment hAlignment); /** creates a Label from a fontname, alignment, dimension in points and font size in points @since v2.0.1 */ - static LabelTTF * create(const char *string, const char *fontName, float fontSize, - const Size& dimensions, TextHAlignment hAlignment, - TextVAlignment vAlignment); + static LabelTTF * create(const std::string& string, const std::string& fontName, float fontSize, + const Size& dimensions, TextHAlignment hAlignment, + TextVAlignment vAlignment); /** 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 */ - 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 */ - 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); /** 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, TextVAlignment vAlignment); /** 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 */ void setTextDefinition(const FontDefinition& theDefinition); @@ -144,8 +144,8 @@ public: /** changes the string to render * @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 const char* getString(void) const; + virtual void setString(const std::string &label) override; + virtual const std::string& getString(void) const override; TextHAlignment getHorizontalAlignment() const; void setHorizontalAlignment(TextHAlignment alignment); @@ -159,8 +159,8 @@ public: float getFontSize() const; void setFontSize(float fontSize); - const char* getFontName() const; - void setFontName(const char *fontName); + const std::string& getFontName() const; + void setFontName(const std::string& fontName); private: bool updateTexture(); @@ -177,7 +177,7 @@ protected: /** The vertical alignment of the label */ TextVAlignment _vAlignment; /** Font name used in the label */ - std::string * _fontName; + std::string _fontName; /** Font size of the label */ float _fontSize; /** label's string */ diff --git a/cocos/2d/CCLabelTextFormatter.cpp b/cocos/2d/CCLabelTextFormatter.cpp index 87dd3cf7cd..6f85e1495a 100644 --- a/cocos/2d/CCLabelTextFormatter.cpp +++ b/cocos/2d/CCLabelTextFormatter.cpp @@ -200,9 +200,9 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel) int size = multiline_string.size(); 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; diff --git a/cocos/2d/CCLayer.cpp b/cocos/2d/CCLayer.cpp index 127261efd5..2556a98dda 100644 --- a/cocos/2d/CCLayer.cpp +++ b/cocos/2d/CCLayer.cpp @@ -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(this->getParent()) != nullptr) - { - dynamic_cast(this->getParent())->addChildToPhysicsWorld(child); - } -} -#endif - // LayerRGBA LayerRGBA::LayerRGBA() : _displayedOpacity(255) diff --git a/cocos/2d/CCLayer.h b/cocos/2d/CCLayer.h index e94224b580..2aafa9a895 100644 --- a/cocos/2d/CCLayer.h +++ b/cocos/2d/CCLayer.h @@ -112,12 +112,6 @@ public: // // 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__ diff --git a/cocos/2d/CCMenuItem.cpp b/cocos/2d/CCMenuItem.cpp index 24ec16a3a7..89aa7eaba6 100644 --- a/cocos/2d/CCMenuItem.cpp +++ b/cocos/2d/CCMenuItem.cpp @@ -42,7 +42,7 @@ THE SOFTWARE. NS_CC_BEGIN -static unsigned int _globalFontSize = kItemSize; +static long _globalFontSize = kItemSize; static std::string _globalFontName = "Marker Felt"; static bool _globalFontNameRelease = false; @@ -64,18 +64,18 @@ MenuItem* MenuItem::create() // XXX deprecated MenuItem* MenuItem::create(Object *target, SEL_MenuHandler selector) { - MenuItem *pRet = new MenuItem(); - pRet->initWithTarget(target, selector); - pRet->autorelease(); - return pRet; + MenuItem *ret = new MenuItem(); + ret->initWithTarget(target, selector); + ret->autorelease(); + return ret; } MenuItem* MenuItem::create( const ccMenuCallback& callback) { - MenuItem *pRet = new MenuItem(); - pRet->initWithCallback(callback); - pRet->autorelease(); - return pRet; + MenuItem *ret = new MenuItem(); + ret->initWithCallback(callback); + ret->autorelease(); + return ret; } // XXX deprecated @@ -188,26 +188,26 @@ void MenuItemLabel::setLabel(Node* var) // XXX: deprecated MenuItemLabel * MenuItemLabel::create(Node*label, Object* target, SEL_MenuHandler selector) { - MenuItemLabel *pRet = new MenuItemLabel(); - pRet->initWithLabel(label, target, selector); - pRet->autorelease(); - return pRet; + MenuItemLabel *ret = new MenuItemLabel(); + ret->initWithLabel(label, target, selector); + ret->autorelease(); + return ret; } MenuItemLabel * MenuItemLabel::create(Node*label, const ccMenuCallback& callback) { - MenuItemLabel *pRet = new MenuItemLabel(); - pRet->initWithLabel(label, callback); - pRet->autorelease(); - return pRet; + MenuItemLabel *ret = new MenuItemLabel(); + ret->initWithLabel(label, callback); + ret->autorelease(); + return ret; } MenuItemLabel* MenuItemLabel::create(Node *label) { - MenuItemLabel *pRet = new MenuItemLabel(); - pRet->initWithLabel(label, (const ccMenuCallback&) nullptr); - pRet->autorelease(); - return pRet; + MenuItemLabel *ret = new MenuItemLabel(); + ret->initWithLabel(label, (const ccMenuCallback&) nullptr); + ret->autorelease(); + return ret; } // XXX: deprecated @@ -237,7 +237,7 @@ MenuItemLabel::~MenuItemLabel() { } -void MenuItemLabel::setString(const char * label) +void MenuItemLabel::setString(const std::string& label) { dynamic_cast(_label)->setString(label); this->setContentSize(_label->getContentSize()); @@ -310,41 +310,39 @@ void MenuItemLabel::setEnabled(bool enabled) //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); } // 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(); - pRet->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, target, selector); - pRet->autorelease(); - return pRet; + MenuItemAtlasFont *ret = new MenuItemAtlasFont(); + ret->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, target, selector); + ret->autorelease(); + 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(); - pRet->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, callback); - pRet->autorelease(); - return pRet; + MenuItemAtlasFont *ret = new MenuItemAtlasFont(); + ret->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, callback); + ret->autorelease(); + return ret; } // 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; CC_SAFE_RETAIN(_target); 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(); label->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap); label->autorelease(); @@ -359,17 +357,17 @@ bool MenuItemAtlasFont::initWithString(const char *value, const char *charMapFil //CCMenuItemFont // -void MenuItemFont::setFontSize(unsigned int s) +void MenuItemFont::setFontSize(long s) { _globalFontSize = s; } -unsigned int MenuItemFont::getFontSize() +long MenuItemFont::getFontSize() { return _globalFontSize; } -void MenuItemFont::setFontName(const char *name) +void MenuItemFont::setFontName(const std::string& name) { if (_globalFontNameRelease) { @@ -379,35 +377,35 @@ void MenuItemFont::setFontName(const char *name) _globalFontNameRelease = true; } -const char * MenuItemFont::getFontName() +const std::string& MenuItemFont::getFontName() { - return _globalFontName.c_str(); + return _globalFontName; } // XXX: deprecated MenuItemFont * MenuItemFont::create(const char *value, Object* target, SEL_MenuHandler selector) { - MenuItemFont *pRet = new MenuItemFont(); - pRet->initWithString(value, target, selector); - pRet->autorelease(); - return pRet; + MenuItemFont *ret = new MenuItemFont(); + ret->initWithString(value, target, selector); + ret->autorelease(); + 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(); - pRet->initWithString(value, callback); - pRet->autorelease(); - return pRet; + MenuItemFont *ret = new MenuItemFont(); + ret->initWithString(value, callback); + ret->autorelease(); + return ret; } -MenuItemFont * MenuItemFont::create(const char *value) +MenuItemFont * MenuItemFont::create(const std::string& value) { - MenuItemFont *pRet = new MenuItemFont(); - pRet->initWithString(value, (const ccMenuCallback&)nullptr); - pRet->autorelease(); - return pRet; + MenuItemFont *ret = new MenuItemFont(); + ret->initWithString(value, (const ccMenuCallback&)nullptr); + ret->autorelease(); + return ret; } 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) ); } -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; _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)) { // do something ? @@ -451,26 +449,26 @@ void MenuItemFont::recreateLabel() this->setLabel(label); } -void MenuItemFont::setFontSizeObj(unsigned int s) +void MenuItemFont::setFontSizeObj(long s) { _fontSize = s; recreateLabel(); } -unsigned int MenuItemFont::getFontSizeObj() const +long MenuItemFont::getFontSizeObj() const { return _fontSize; } -void MenuItemFont::setFontNameObj(const char* name) +void MenuItemFont::setFontNameObj(const std::string& name) { _fontName = name; 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 MenuItemSprite * MenuItemSprite::create(Node *normalSprite, Node *selectedSprite, Node *disabledSprite, Object *target, SEL_MenuHandler selector) { - MenuItemSprite *pRet = new MenuItemSprite(); - pRet->initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, target, selector); - pRet->autorelease(); - return pRet; + MenuItemSprite *ret = new MenuItemSprite(); + ret->initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, target, selector); + ret->autorelease(); + return ret; } MenuItemSprite * MenuItemSprite::create(Node *normalSprite, Node *selectedSprite, Node *disabledSprite, const ccMenuCallback& callback) { - MenuItemSprite *pRet = new MenuItemSprite(); - pRet->initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, callback); - pRet->autorelease(); - return pRet; + MenuItemSprite *ret = new MenuItemSprite(); + ret->initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, callback); + ret->autorelease(); + return ret; } // XXX deprecated @@ -687,71 +685,71 @@ void MenuItemSprite::updateImagesVisibility() MenuItemImage* MenuItemImage::create() { - MenuItemImage *pRet = new MenuItemImage(); - if (pRet && pRet->init()) + MenuItemImage *ret = new MenuItemImage(); + if (ret && ret->init()) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } 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 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 MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage, const char *disabledImage, Object* target, SEL_MenuHandler selector) { - MenuItemImage *pRet = new MenuItemImage(); - if (pRet && pRet->initWithNormalImage(normalImage, selectedImage, disabledImage, target, selector)) + MenuItemImage *ret = new MenuItemImage(); + if (ret && ret->initWithNormalImage(normalImage, selectedImage, disabledImage, target, selector)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); 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(); - if (pRet && pRet->initWithNormalImage(normalImage, selectedImage, disabledImage, callback)) + MenuItemImage *ret = new MenuItemImage(); + if (ret && ret->initWithNormalImage(normalImage, selectedImage, disabledImage, callback)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); 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(); - if (pRet && pRet->initWithNormalImage(normalImage, selectedImage, disabledImage, (const ccMenuCallback&)nullptr)) + MenuItemImage *ret = new MenuItemImage(); + if (ret && ret->initWithNormalImage(normalImage, selectedImage, disabledImage, (const ccMenuCallback&)nullptr)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } @@ -762,23 +760,23 @@ bool MenuItemImage::initWithNormalImage(const char *normalImage, const char *sel CC_SAFE_RETAIN(_target); 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 *selectedSprite = NULL; Node *disabledSprite = NULL; - if (normalImage) + if (normalImage.size() >0) { normalSprite = Sprite::create(normalImage); } - if (selectedImage) + if (selectedImage.size() >0) { selectedSprite = Sprite::create(selectedImage); } - if(disabledImage) + if(disabledImage.size() >0) { disabledSprite = Sprite::create(disabledImage); } @@ -810,38 +808,38 @@ void MenuItemImage::setDisabledSpriteFrame(SpriteFrame * frame) // XXX: deprecated MenuItemToggle * MenuItemToggle::createWithTarget(Object* target, SEL_MenuHandler selector, Array* menuItems) { - MenuItemToggle *pRet = new MenuItemToggle(); - pRet->MenuItem::initWithTarget(target, selector); - pRet->_subItems = Array::create(); - pRet->_subItems->retain(); + MenuItemToggle *ret = new MenuItemToggle(); + ret->MenuItem::initWithTarget(target, selector); + ret->_subItems = Array::create(); + ret->_subItems->retain(); for (int z=0; z < menuItems->count(); z++) { MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z); - pRet->_subItems->addObject(menuItem); + ret->_subItems->addObject(menuItem); } - pRet->_selectedIndex = UINT_MAX; - pRet->setSelectedIndex(0); - return pRet; + ret->_selectedIndex = UINT_MAX; + ret->setSelectedIndex(0); + return ret; } MenuItemToggle * MenuItemToggle::createWithCallback(const ccMenuCallback &callback, Array* menuItems) { - MenuItemToggle *pRet = new MenuItemToggle(); - pRet->MenuItem::initWithCallback(callback); - pRet->_subItems = Array::create(); - pRet->_subItems->retain(); + MenuItemToggle *ret = new MenuItemToggle(); + ret->MenuItem::initWithCallback(callback); + ret->_subItems = Array::create(); + ret->_subItems->retain(); for (int z=0; z < menuItems->count(); z++) { MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z); - pRet->_subItems->addObject(menuItem); + ret->_subItems->addObject(menuItem); } - pRet->_selectedIndex = UINT_MAX; - pRet->setSelectedIndex(0); - return pRet; + ret->_selectedIndex = UINT_MAX; + ret->setSelectedIndex(0); + return ret; } // XXX: deprecated @@ -849,30 +847,30 @@ MenuItemToggle * MenuItemToggle::createWithTarget(Object* target, SEL_MenuHandle { va_list args; va_start(args, item); - MenuItemToggle *pRet = new MenuItemToggle(); - pRet->initWithTarget(target, selector, item, args); - pRet->autorelease(); + MenuItemToggle *ret = new MenuItemToggle(); + ret->initWithTarget(target, selector, item, args); + ret->autorelease(); va_end(args); - return pRet; + return ret; } MenuItemToggle * MenuItemToggle::createWithCallback(const ccMenuCallback &callback, MenuItem* item, ...) { va_list args; va_start(args, item); - MenuItemToggle *pRet = new MenuItemToggle(); - pRet->initWithCallback(callback, item, args); - pRet->autorelease(); + MenuItemToggle *ret = new MenuItemToggle(); + ret->initWithCallback(callback, item, args); + ret->autorelease(); va_end(args); - return pRet; + return ret; } MenuItemToggle * MenuItemToggle::create() { - MenuItemToggle *pRet = new MenuItemToggle(); - pRet->initWithItem(NULL); - pRet->autorelease(); - return pRet; + MenuItemToggle *ret = new MenuItemToggle(); + ret->initWithItem(NULL); + ret->autorelease(); + return ret; } // XXX: deprecated @@ -903,10 +901,10 @@ bool MenuItemToggle::initWithCallback(const ccMenuCallback &callback, MenuItem * MenuItemToggle* MenuItemToggle::create(MenuItem *item) { - MenuItemToggle *pRet = new MenuItemToggle(); - pRet->initWithItem(item); - pRet->autorelease(); - return pRet; + MenuItemToggle *ret = new MenuItemToggle(); + ret->initWithItem(item); + ret->autorelease(); + return ret; } bool MenuItemToggle::initWithItem(MenuItem *item) diff --git a/cocos/2d/CCMenuItem.h b/cocos/2d/CCMenuItem.h index 78b8d333ef..d0fcda9a50 100644 --- a/cocos/2d/CCMenuItem.h +++ b/cocos/2d/CCMenuItem.h @@ -166,7 +166,7 @@ public: CC_DEPRECATED_ATTRIBUTE bool initWithLabel(Node* label, Object* target, SEL_MenuHandler selector); /** 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 */ inline const Color3B& getDisabledColor() const { return _disabledColor; }; @@ -204,11 +204,11 @@ class CC_DLL MenuItemAtlasFont : public MenuItemLabel { public: /** 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 */ - 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 */ - 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 */ @@ -220,9 +220,9 @@ public: virtual ~MenuItemAtlasFont(){} /** 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 */ - 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: /** 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 */ 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 */ - static MenuItemFont * create(const char *value, const ccMenuCallback& callback); + static MenuItemFont * create(const std::string& value, const ccMenuCallback& callback); /** * @js ctor */ @@ -251,30 +251,30 @@ public: /** initializes a menu item from a string with a target/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 */ - bool initWithString(const char *value, const ccMenuCallback& callback); + bool initWithString(const std::string& value, const ccMenuCallback& callback); /** set default font size */ - static void setFontSize(unsigned int s); + static void setFontSize(long size); /** get default font size */ - static unsigned int getFontSize(); + static long getFontSize(); CC_DEPRECATED_ATTRIBUTE static unsigned int fontSize() { return MenuItemFont::getFontSize(); }; /** set the default font name */ - static void setFontName(const char *name); + static void setFontName(const std::string& name); /** get the default font name */ - static const char *getFontName(); - CC_DEPRECATED_ATTRIBUTE static const char *fontName() { return MenuItemFont::getFontName(); }; + static const std::string& getFontName(); + CC_DEPRECATED_ATTRIBUTE static const std::string& fontName() { return MenuItemFont::getFontName(); }; /** set font size * c++ can not overload static and non-static member functions with the same parameter types * so change the name to setFontSizeObj * @js setFontSize */ - void setFontSizeObj(unsigned int s); + void setFontSizeObj(long size); /** get font size * @js getFontSize */ - unsigned int getFontSizeObj() const; + long getFontSizeObj() const; CC_DEPRECATED_ATTRIBUTE unsigned int fontSizeObj() const { return getFontSizeObj(); }; /** set the font name @@ -282,20 +282,20 @@ public: * so change the name to setFontNameObj * @js setFontName */ - void setFontNameObj(const char* name); + void setFontNameObj(const std::string& name); /** returns the name of the Font * @js getFontNameObj */ - const char* getFontNameObj() const; + const std::string& getFontNameObj() const; /** deprecated Use getFontNameObj() instead */ - CC_DEPRECATED_ATTRIBUTE const char* fontNameObj() const { return getFontNameObj(); } + CC_DEPRECATED_ATTRIBUTE const std::string& fontNameObj() const { return getFontNameObj(); } protected: void recreateLabel(); - unsigned int _fontSize; + long _fontSize; std::string _fontName; }; @@ -384,18 +384,18 @@ public: /** Creates an MenuItemImage. */ static MenuItemImage* create(); /** 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*/ - 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 */ 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 */ - 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 */ 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 */ - 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 */ @@ -410,7 +410,7 @@ public: /** 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); /** 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 */ void setNormalSpriteFrame(SpriteFrame* frame); diff --git a/cocos/2d/CCMotionStreak.cpp b/cocos/2d/CCMotionStreak.cpp index 47cb43a207..14920662ce 100644 --- a/cocos/2d/CCMotionStreak.cpp +++ b/cocos/2d/CCMotionStreak.cpp @@ -28,7 +28,7 @@ THE SOFTWARE. #include "CCGLProgram.h" #include "CCShaderCache.h" #include "ccMacros.h" - +#include "CCDirector.h" #include "CCVertex.h" NS_CC_BEGIN @@ -93,7 +93,7 @@ bool MotionStreak::initWithFade(float fade, float minSeg, float stroke, const Co { 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); } diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 5302648923..e329f49c3e 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -43,6 +43,7 @@ THE SOFTWARE. #include "CCEventDispatcher.h" #include "CCEvent.h" #include "CCEventTouch.h" +#include "CCScene.h" #ifdef CC_USE_PHYSICS #include "CCPhysicsBody.h" @@ -401,7 +402,7 @@ void Node::setPositionY(float y) setPosition(Point(_position.x, y)); } -unsigned int Node::getChildrenCount() const +long Node::getChildrenCount() const { return _children ? _children->count() : 0; } @@ -629,6 +630,17 @@ void Node::addChild(Node *child, int zOrder, int tag) } this->insertChild(child, zOrder); + +#ifdef CC_USE_PHYSICS + for (Node* node = this->getParent(); node != nullptr; node = node->getParent()) + { + if (dynamic_cast(node) != nullptr) + { + (dynamic_cast(node))->addChildToPhysicsWorld(child); + break; + } + } +#endif child->_tag = tag; @@ -682,7 +694,7 @@ void Node::removeChild(Node* child, bool cleanup /* = true */) return; } - int index = _children->getIndexOfObject(child); + long index = _children->getIndexOfObject(child); if( index != CC_INVALID_INDEX ) 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: // -1st do onExit @@ -752,6 +764,14 @@ void Node::detachChild(Node *child, int childIndex, bool doCleanup) child->onExitTransitionDidStart(); 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 // its scheduledSelectors_ dict will not get released! @@ -1369,10 +1389,12 @@ void Node::setPhysicsBody(PhysicsBody* body) { if (_physicsBody != nullptr) { + _physicsBody->_node = nullptr; _physicsBody->release(); } _physicsBody = body; + _physicsBody->_node = this; _physicsBody->retain(); _physicsBody->setPosition(getPosition()); _physicsBody->setRotation(getRotation()); diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index cde05c34c3..5a363c8053 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -644,7 +644,7 @@ public: * * @return The amount of children. */ - unsigned int getChildrenCount() const; + long getChildrenCount() const; /** * Sets the parent node @@ -1421,7 +1421,7 @@ protected: void insertChild(Node* child, int z); /// 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. Point convertToWindowSpace(const Point& nodePoint) const; diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index 788fdd221c..cd473bf097 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -111,7 +111,7 @@ bool ParticleBatchNode::initWithTexture(Texture2D *tex, 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); } diff --git a/cocos/2d/CCParticleExamples.cpp b/cocos/2d/CCParticleExamples.cpp index c7e2946172..7120c4b821 100644 --- a/cocos/2d/CCParticleExamples.cpp +++ b/cocos/2d/CCParticleExamples.cpp @@ -42,7 +42,7 @@ static Texture2D* getDefaultTexture() { bool bRet = false; const char* key = "/__firePngData"; - texture = TextureCache::getInstance()->getTextureForKey(key); + texture = Director::getInstance()->getTextureCache()->getTextureForKey(key); CC_BREAK_IF(texture != NULL); pImage = new Image(); @@ -50,7 +50,7 @@ static Texture2D* getDefaultTexture() bRet = pImage->initWithImageData(__firePngData, sizeof(__firePngData)); CC_BREAK_IF(!bRet); - texture = TextureCache::getInstance()->addImage(pImage, key); + texture = Director::getInstance()->getTextureCache()->addImage(pImage, key); } while (0); CC_SAFE_RELEASE(pImage); diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index a42ac234cb..cb2c4326f3 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -136,7 +136,7 @@ ParticleSystem::ParticleSystem() } // implementation ParticleSystem -ParticleSystem * ParticleSystem::create(const char *plistFile) +ParticleSystem * ParticleSystem::create(const std::string& plistFile) { ParticleSystem *pRet = new ParticleSystem(); if (pRet && pRet->initWithFile(plistFile)) @@ -165,7 +165,7 @@ bool ParticleSystem::init() return initWithTotalParticles(150); } -bool ParticleSystem::initWithFile(const char *plistFile) +bool ParticleSystem::initWithFile(const std::string& plistFile) { bool bRet = false; _plistFile = FileUtils::getInstance()->fullPathForFilename(plistFile); @@ -195,7 +195,7 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary) return initWithDictionary(dictionary, ""); } -bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const char *dirname) +bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::string& dirname) { bool bRet = false; unsigned char *buffer = NULL; @@ -353,17 +353,17 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const char *dirn { string textureDir = textureName.substr(0, rPos + 1); - if (dirname != NULL && textureDir != dirname) + if (dirname.size()>0 && textureDir != dirname) { textureName = textureName.substr(rPos+1); - textureName = string(dirname) + textureName; + textureName = dirname + textureName; } } 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 bool bNotify = FileUtils::getInstance()->isPopupNotify(); 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 FileUtils::getInstance()->setPopupNotify(bNotify); } @@ -388,7 +388,7 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const char *dirn const char *textureData = dictionary->valueForKey("textureImageData")->getCString(); CCASSERT(textureData, ""); - int dataLen = strlen(textureData); + long dataLen = strlen(textureData); if(dataLen != 0) { // 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"); 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(); bool isOK = image->initWithImageData(deflated, deflatedLen); CCASSERT(isOK, "CCParticleSystem: error init image with Data"); CC_BREAK_IF(!isOK); - setTexture(TextureCache::getInstance()->addImage(image, textureName.c_str())); + setTexture(Director::getInstance()->getTextureCache()->addImage(image, textureName.c_str())); image->release(); } diff --git a/cocos/2d/CCParticleSystem.h b/cocos/2d/CCParticleSystem.h index ae22671c4c..1cd30b56c8 100644 --- a/cocos/2d/CCParticleSystem.h +++ b/cocos/2d/CCParticleSystem.h @@ -167,7 +167,7 @@ public: http://particledesigner.71squared.com/ @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 static ParticleSystem* createWithTotalParticles(unsigned int numberOfParticles); @@ -188,7 +188,7 @@ public: http://particledesigner.71squared.com/ @since v0.99.3 */ - bool initWithFile(const char *plistFile); + bool initWithFile(const std::string& plistFile); /** initializes a QuadParticleSystem from a Dictionary. @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 @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 virtual bool initWithTotalParticles(unsigned int numberOfParticles); diff --git a/cocos/2d/CCProfiling.cpp b/cocos/2d/CCProfiling.cpp index 2794b3b183..3c90394d58 100644 --- a/cocos/2d/CCProfiling.cpp +++ b/cocos/2d/CCProfiling.cpp @@ -125,7 +125,7 @@ const char* ProfilingTimer::description() const { 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; } @@ -166,7 +166,7 @@ void ProfilingEndTimingBlock(const char *timerName) CCASSERT(timer, "CCProfilingTimer not found"); - int duration = chrono::duration_cast(now - timer->_startTime).count(); + long duration = static_cast(chrono::duration_cast(now - timer->_startTime).count()); timer->totalTime += duration; timer->_averageTime1 = (timer->_averageTime1 + duration) / 2.0f; diff --git a/cocos/2d/CCProfiling.h b/cocos/2d/CCProfiling.h index d68dc6f918..b79c08c991 100644 --- a/cocos/2d/CCProfiling.h +++ b/cocos/2d/CCProfiling.h @@ -134,12 +134,12 @@ public: std::string _nameStr; std::chrono::high_resolution_clock::time_point _startTime; - int _averageTime1; - int _averageTime2; - int minTime; - int maxTime; - long long totalTime; - int numberOfCalls; + long _averageTime1; + long _averageTime2; + long minTime; + long maxTime; + long totalTime; + long numberOfCalls; }; extern void ProfilingBeginTimingBlock(const char *timerName); diff --git a/cocos/2d/CCProtocols.h b/cocos/2d/CCProtocols.h index 01b7ebc011..993d1fa161 100644 --- a/cocos/2d/CCProtocols.h +++ b/cocos/2d/CCProtocols.h @@ -229,7 +229,7 @@ public: * @js 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 @@ -238,7 +238,7 @@ public: * @js NA * @lua NA */ - virtual const char* getString() const = 0; + virtual const std::string& getString() const = 0; }; /** diff --git a/cocos/2d/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp index d76c258f87..8fa56c282d 100644 --- a/cocos/2d/CCRenderTexture.cpp +++ b/cocos/2d/CCRenderTexture.cpp @@ -102,11 +102,11 @@ void RenderTexture::listenToBackground(cocos2d::Object *obj) if (_UITextureImage) { 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 ) { - 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 @@ -198,8 +198,8 @@ bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_oldFBO); // textures must be power of two squared - unsigned int powW = 0; - unsigned int powH = 0; + long powW = 0; + long powH = 0; if (Configuration::getInstance()->supportsNPOT()) { @@ -212,7 +212,7 @@ bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat powH = ccNextPOT(h); } - int dataLen = (int)(powW * powH * 4); + long dataLen = (long)(powW * powH * 4); data = malloc(dataLen); CC_BREAK_IF(! data); diff --git a/cocos/2d/CCScene.cpp b/cocos/2d/CCScene.cpp index cc8654204b..9c636382dd 100644 --- a/cocos/2d/CCScene.cpp +++ b/cocos/2d/CCScene.cpp @@ -102,8 +102,7 @@ bool Scene::initWithPhysics() Director * pDirector; CC_BREAK_IF( ! (pDirector = Director::getInstance()) ); this->setContentSize(pDirector->getWinSize()); - CC_BREAK_IF(! (_physicsWorld = PhysicsWorld::create())); - _physicsWorld->setScene(this); + CC_BREAK_IF(! (_physicsWorld = PhysicsWorld::create(*this))); this->scheduleUpdate(); // success @@ -134,37 +133,27 @@ void Scene::addChildToPhysicsWorld(Node* child) if (_physicsWorld) { std::function addToPhysicsWorldFunc = nullptr; - addToPhysicsWorldFunc = [this, &addToPhysicsWorldFunc](Object* child) -> void + addToPhysicsWorldFunc = [this, &addToPhysicsWorldFunc](Object* obj) -> void { - if (dynamic_cast(child) != nullptr) + + if (dynamic_cast(obj) != nullptr) { - Object* subChild = nullptr; - CCARRAY_FOREACH((dynamic_cast(child))->getChildren(), subChild) - { - addToPhysicsWorldFunc(subChild); - } - }else if (dynamic_cast(child) != nullptr) - { - Node* node = dynamic_cast(child); + Node* node = dynamic_cast(obj); if (node->getPhysicsBody()) { _physicsWorld->addBody(node->getPhysicsBody()); } + + Object* subChild = nullptr; + CCARRAY_FOREACH(node->getChildren(), subChild) + { + addToPhysicsWorldFunc(subChild); + } } }; - if(dynamic_cast(child) != nullptr) - { - Object* subChild = nullptr; - CCARRAY_FOREACH(child->getChildren(), subChild) - { - addToPhysicsWorldFunc(subChild); - } - }else - { - addToPhysicsWorldFunc(child); - } + addToPhysicsWorldFunc(child); } } diff --git a/cocos/2d/CCScene.h b/cocos/2d/CCScene.h index 11e3e0fbb5..19f5c5f1cc 100644 --- a/cocos/2d/CCScene.h +++ b/cocos/2d/CCScene.h @@ -68,18 +68,14 @@ public: #ifdef CC_USE_PHYSICS public: bool initWithPhysics(); - + + inline PhysicsWorld* getPhysicsWorld() { return _physicsWorld; } + virtual void addChild(Node* child) override; virtual void addChild(Node* child, int zOrder) override; virtual void addChild(Node* child, int zOrder, int tag) 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; } - + virtual void update(float delta) override; + protected: virtual void addChildToPhysicsWorld(Node* child); @@ -87,7 +83,7 @@ protected: PhysicsWorld* _physicsWorld; #endif // CC_USE_PHYSICS - friend class Layer; + friend class Node; friend class SpriteBatchNode; }; diff --git a/cocos/2d/CCScheduler.cpp b/cocos/2d/CCScheduler.cpp index 3f9c9da9f8..efc80847d0 100644 --- a/cocos/2d/CCScheduler.cpp +++ b/cocos/2d/CCScheduler.cpp @@ -294,7 +294,7 @@ void Scheduler::scheduleSelector(SEL_SCHEDULE selector, Object *target, float in CCASSERT(target, "Argument target must be non-NULL"); tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if (! element) { @@ -304,7 +304,7 @@ void Scheduler::scheduleSelector(SEL_SCHEDULE selector, Object *target, float in { 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 element->paused = paused; @@ -352,7 +352,7 @@ void Scheduler::unscheduleSelector(SEL_SCHEDULE selector, Object *target) //CCASSERT(selector); tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if (element) { @@ -448,7 +448,7 @@ void Scheduler::priorityIn(tListEntry **list, Object *target, int priority, bool target->retain(); pHashElement->list = list; pHashElement->entry = listElement; - HASH_ADD_INT(_hashForUpdates, target, pHashElement); + HASH_ADD_PTR(_hashForUpdates, target, pHashElement); } void Scheduler::appendIn(_listEntry **list, Object *target, bool paused) @@ -467,14 +467,14 @@ void Scheduler::appendIn(_listEntry **list, Object *target, bool paused) target->retain(); pHashElement->list = list; pHashElement->entry = listElement; - HASH_ADD_INT(_hashForUpdates, target, pHashElement); + HASH_ADD_PTR(_hashForUpdates, target, pHashElement); } void Scheduler::scheduleUpdateForTarget(Object *target, int priority, bool paused) { tHashUpdateEntry *pHashElement = NULL; - HASH_FIND_INT(_hashForUpdates, &target, pHashElement); + HASH_FIND_PTR(_hashForUpdates, &target, pHashElement); if (pHashElement) { #if COCOS2D_DEBUG >= 1 @@ -509,7 +509,7 @@ bool Scheduler::isScheduledForTarget(SEL_SCHEDULE selector, Object *target) CCASSERT(target, "Argument target must be non-NULL"); tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if (!element) { @@ -541,7 +541,7 @@ void Scheduler::removeUpdateFromHash(struct _listEntry *entry) { tHashUpdateEntry *element = NULL; - HASH_FIND_INT(_hashForUpdates, &entry->target, element); + HASH_FIND_PTR(_hashForUpdates, &entry->target, element); if (element) { // list entry @@ -567,7 +567,7 @@ void Scheduler::unscheduleUpdateForTarget(const Object *target) } tHashUpdateEntry *element = NULL; - HASH_FIND_INT(_hashForUpdates, &target, element); + HASH_FIND_PTR(_hashForUpdates, &target, element); if (element) { if (_updateHashLocked) @@ -601,31 +601,31 @@ void Scheduler::unscheduleAllWithMinPriority(int nMinPriority) } // Updates selectors - tListEntry *pEntry, *pTmp; + tListEntry *entry, *tmp; 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) { - 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 tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if (element) { @@ -702,7 +702,7 @@ void Scheduler::resumeTarget(Object *target) // custom selectors tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if (element) { element->paused = false; @@ -710,7 +710,7 @@ void Scheduler::resumeTarget(Object *target) // update selector tHashUpdateEntry *elementUpdate = NULL; - HASH_FIND_INT(_hashForUpdates, &target, elementUpdate); + HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate); if (elementUpdate) { CCASSERT(elementUpdate->entry != NULL, ""); @@ -724,7 +724,7 @@ void Scheduler::pauseTarget(Object *target) // custom selectors tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if (element) { element->paused = true; @@ -732,7 +732,7 @@ void Scheduler::pauseTarget(Object *target) // update selector tHashUpdateEntry *elementUpdate = NULL; - HASH_FIND_INT(_hashForUpdates, &target, elementUpdate); + HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate); if (elementUpdate) { CCASSERT(elementUpdate->entry != NULL, ""); @@ -746,7 +746,7 @@ bool Scheduler::isTargetPaused(Object *target) // Custom selectors tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if( element ) { return element->paused; @@ -754,7 +754,7 @@ bool Scheduler::isTargetPaused(Object *target) // We should check update selectors if target does not have custom selectors tHashUpdateEntry *elementUpdate = NULL; - HASH_FIND_INT(_hashForUpdates, &target, elementUpdate); + HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate); if ( elementUpdate ) { return elementUpdate->entry->paused; @@ -836,32 +836,32 @@ void Scheduler::update(float dt) } // Iterate over all the Updates' selectors - tListEntry *pEntry, *pTmp; + tListEntry *entry, *tmp; // 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 - 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 - 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--) { - SchedulerScriptHandlerEntry* pEntry = static_cast(_scriptHandlerEntries->getObjectAtIndex(i)); - if (pEntry->isMarkedForDeletion()) + SchedulerScriptHandlerEntry* eachEntry = static_cast(_scriptHandlerEntries->getObjectAtIndex(i)); + if (eachEntry->isMarkedForDeletion()) { _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 // 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 - 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 - DL_FOREACH_SAFE(_updatesPosList, pEntry, pTmp) + DL_FOREACH_SAFE(_updatesPosList, entry, tmp) { - if (pEntry->markedForDeletion) + if (entry->markedForDeletion) { - this->removeUpdateFromHash(pEntry); + this->removeUpdateFromHash(entry); } } diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index 676138d9b1..186f569676 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -82,7 +82,7 @@ Sprite* Sprite::createWithTexture(Texture2D *texture, const Rect& rect) return NULL; } -Sprite* Sprite::create(const char *filename) +Sprite* Sprite::create(const std::string& filename) { Sprite *sprite = new Sprite(); if (sprite && sprite->initWithFile(filename)) @@ -94,7 +94,7 @@ Sprite* Sprite::create(const char *filename) 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(); if (sprite && sprite->initWithFile(filename, rect)) @@ -118,13 +118,13 @@ Sprite* Sprite::createWithSpriteFrame(SpriteFrame *spriteFrame) return NULL; } -Sprite* Sprite::createWithSpriteFrameName(const char *spriteFrameName) +Sprite* Sprite::createWithSpriteFrameName(const std::string& spriteFrameName) { SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); #if COCOS2D_DEBUG > 0 char msg[256] = {0}; - sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName); + sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName.c_str()); CCASSERT(frame != NULL, msg); #endif @@ -215,11 +215,11 @@ bool Sprite::initWithTexture(Texture2D *texture) 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) { Rect rect = Rect::ZERO; @@ -233,11 +233,11 @@ bool Sprite::initWithFile(const char *filename) 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) { return initWithTexture(texture, rect); @@ -259,9 +259,9 @@ bool Sprite::initWithSpriteFrame(SpriteFrame *spriteFrame) 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); return initWithSpriteFrame(frame); @@ -284,7 +284,7 @@ Sprite* Sprite::initWithCGImage(CGImageRef pImage, const char *pszKey) CCASSERT(pImage != NULL); // 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(); Rect rect = Rect(0 ,0, size.width, size.height); @@ -840,6 +840,12 @@ void Sprite::setScale(float fScale) SET_DIRTY_RECURSIVELY(); } +void Sprite::setScale(float scaleX, float scaleY) +{ + Node::setScale(scaleX, scaleY); + SET_DIRTY_RECURSIVELY(); +} + void Sprite::setVertexZ(float fVertexZ) { Node::setVertexZ(fVertexZ); @@ -992,9 +998,9 @@ void Sprite::setDisplayFrame(SpriteFrame *pNewFrame) 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); @@ -1107,7 +1113,7 @@ void Sprite::setTexture(Texture2D *texture) if (NULL == texture) { // 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 (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); 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); } } diff --git a/cocos/2d/CCSprite.h b/cocos/2d/CCSprite.h index cc6470c7da..317effad84 100644 --- a/cocos/2d/CCSprite.h +++ b/cocos/2d/CCSprite.h @@ -24,8 +24,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#ifndef __SPITE_NODE_CCSPRITE_H__ -#define __SPITE_NODE_CCSPRITE_H__ +#ifndef __SPRITE_NODE_CCSPRITE_H__ +#define __SPRITE_NODE_CCSPRITE_H__ #include "CCNode.h" #include "CCProtocols.h" @@ -54,7 +54,7 @@ struct transformValues_; * @{ */ -/** +/** * 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. @@ -88,14 +88,14 @@ public: /// @{ /// @name Creators - + /** * Creates an empty sprite without texture. You can call setTexture method subsequently. * * @return An empty sprite object that is marked as autoreleased. */ static Sprite* create(); - + /** * 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". * @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. * @@ -114,8 +114,8 @@ public: * @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. */ - 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 * 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. */ static Sprite* createWithTexture(Texture2D *texture); - + /** * Creates a sprite with a texture and a rect. * @@ -136,7 +136,7 @@ public: * @return A valid sprite object that is marked as autoreleased. */ static Sprite* createWithTexture(Texture2D *texture, const Rect& rect); - + /** * Creates a sprite with an sprite frame. * @@ -144,7 +144,7 @@ public: * @return A valid sprite object that is marked as autoreleased. */ static Sprite* createWithSpriteFrame(SpriteFrame *pSpriteFrame); - + /** * 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. * @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 - - + + /// @{ /// @name Initializers - + /** * Default constructor * @js ctor */ Sprite(void); - + /** * Default destructor * @js NA * @lua NA */ virtual ~Sprite(void); - + /** * Initializes an empty sprite with nothing init. */ virtual bool init(void); - + /** * Initializes a sprite with a texture. * @@ -190,7 +190,7 @@ public: * @return true if the sprite is initialized properly, false otherwise. */ virtual bool initWithTexture(Texture2D *texture); - + /** * Initializes a sprite with a texture and a rect. * @@ -202,7 +202,7 @@ public: * @return true if the sprite is initialized properly, false otherwise. */ virtual bool initWithTexture(Texture2D *texture, const Rect& rect); - + /** * 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. */ 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 * @@ -223,7 +223,7 @@ public: * @return true if the sprite is initialized properly, false otherwise. */ virtual bool initWithSpriteFrame(SpriteFrame *pSpriteFrame); - + /** * 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 * @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. * @@ -247,8 +247,8 @@ public: * @js 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. * @@ -262,18 +262,18 @@ public: * @js 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 /// @{ /// @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); - + /** * Returns the batch node object if this sprite is rendered by SpriteBatchNode * @@ -292,26 +292,26 @@ public: * @endcode */ virtual void setBatchNode(SpriteBatchNode *spriteBatchNode); - + /// @} end of BatchNode methods - - - + + + /// @{ /// @name Texture methods - + /** * 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. */ virtual void setTextureRect(const Rect& rect); - + /** * Sets the texture rect, rectRotated and untrimmed size of the Sprite in points. * It will update the texture coordinates and the vertex rectangle. */ virtual void setTextureRect(const Rect& rect, bool rotated, const Size& untrimmedSize); - + /** * Sets the vertex rect. * It will be called internally by setTextureRect. @@ -319,34 +319,34 @@ public: * Do not call it manually. Use setTextureRect instead. */ virtual void setVertexRect(const Rect& rect); - - /// @} end of texture methods - - + /// @} end of texture methods + + + /// @{ /// @name Frames methods - + /** * Sets a new display frame to the Sprite. */ virtual void setDisplayFrame(SpriteFrame *pNewFrame); - + /** * Returns whether or not a SpriteFrame is being displayed */ virtual bool isFrameDisplayed(SpriteFrame *pFrame) const; - + /** @deprecated Use getDisplayFrame() instead */ CC_DEPRECATED_ATTRIBUTE virtual SpriteFrame* displayFrame() { return getDisplayFrame(); }; - + /** * Returns the current displayed frame. */ virtual SpriteFrame* getDisplayFrame(); - + /// @} End of frames methods - + /// @{ /// @name Animation methods @@ -354,25 +354,25 @@ public: * Changes the display frame with animation name and index. * 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 - - /** + + /** * 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. */ virtual bool isDirty(void) const { return _dirty; } - - /** + + /** * Makes the Sprite to be updated in the Atlas. */ virtual void setDirty(bool bDirty) { _dirty = bDirty; } - + /** * Returns the quad (tex coords, vertex coords and color) information. * @js NA @@ -380,24 +380,24 @@ public: */ inline V3F_C4B_T2F_Quad getQuad(void) const { return _quad; } - /** + /** * Returns whether or not the texture rectangle is rotated. */ 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; } - - /** + + /** * Sets the index used on the TextureAtlas. * @warning Don't modify this value unless you know what you are doing */ 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; } @@ -405,19 +405,19 @@ public: * Gets the weak reference of the TextureAtlas when the sprite is rendered using via SpriteBatchNode */ inline TextureAtlas* getTextureAtlas(void) { return _textureAtlas; } - + /** * Sets the weak reference of the TextureAtlas when the sprite is rendered using via SpriteBatchNode */ inline void setTextureAtlas(TextureAtlas *pobTextureAtlas) { _textureAtlas = pobTextureAtlas; } - /** + /** * Gets the offset position of the sprite. Calculated automatically by editors like Zwoptex. */ inline const Point& getOffsetPosition(void) const { return _offsetPosition; } - /** + /** * 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. @@ -425,48 +425,48 @@ public: * If you want to flip the anchorPoint too, and/or to flip the children too use: * 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; /** * 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); - - /** @deprecated Use isFlippedX() instead + + /** @deprecated Use isFlippedX() instead * @js NA * @lua NA */ CC_DEPRECATED_ATTRIBUTE bool isFlipX() { return isFlippedX(); }; /** @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. - * + * * 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. * If you want to flip the anchorPoint too, and/or to flip the children too use: * 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; /** * 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); - + /// @} End of Sprite properties getter/setters - + /** @deprecated Use isFlippedY() instead */ CC_DEPRECATED_ATTRIBUTE bool isFlipY() { return isFlippedY(); }; /** @deprecated Use setFlippedY() instead */ - CC_DEPRECATED_ATTRIBUTE void setFlipY(bool flippedY) { setFlippedY(flippedY); }; + CC_DEPRECATED_ATTRIBUTE void setFlipY(bool flippedY) { setFlippedY(flippedY); }; // // Overrides @@ -494,6 +494,7 @@ public: /// @name Functions inherited from Node virtual void setScaleX(float scaleX) override; virtual void setScaleY(float scaleY) override; + virtual void setScale(float scaleX, float scaleY) override; /** * @js NA * @lua NA @@ -542,13 +543,13 @@ protected: TextureAtlas* _textureAtlas; /// SpriteBatchNode texture atlas (weak reference) int _atlasIndex; /// Absolute (real) Index on the SpriteSheet SpriteBatchNode* _batchNode; /// Used batch node (weak reference) - + bool _dirty; /// Whether the sprite needs to be updated bool _recursiveDirty; /// Whether all of the sprite's children needs to be updated bool _hasChildren; /// Whether the sprite contains children bool _shouldBeHidden; /// should not be drawn because one of the ancestors is not visible AffineTransform _transformToBatch; - + // // Data used when the sprite is self-rendered // @@ -574,8 +575,8 @@ protected: bool _opacityModifyRGB; // image is flipped - bool _flippedX; /// Whether the sprite is flipped horizaontally or not. - bool _flippedY; /// Whether the sprite is flipped vertically or not. + bool _flippedX; /// Whether the sprite is flipped horizontally or not + bool _flippedY; /// Whether the sprite is flipped vertically or not }; @@ -584,4 +585,4 @@ protected: NS_CC_END -#endif // __SPITE_NODE_CCSPRITE_H__ +#endif // __SPRITE_NODE_CCSPRITE_H__ diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index 195b5fa8eb..03a71abf1c 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -64,7 +64,7 @@ SpriteBatchNode* SpriteBatchNode::createWithTexture(Texture2D* tex, int capacity * 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(); batchNode->initWithFile(fileImage, capacity); @@ -76,7 +76,7 @@ SpriteBatchNode* SpriteBatchNode::create(const char *fileImage, int capacity/* = /* * init with Texture2D */ -bool SpriteBatchNode::initWithTexture(Texture2D *tex, int capacity) +bool SpriteBatchNode::initWithTexture(Texture2D *tex, long capacity) { CCASSERT(capacity>=0, "Capacity must be >= 0"); @@ -112,9 +112,9 @@ bool SpriteBatchNode::init() /* * 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); } @@ -181,17 +181,6 @@ void SpriteBatchNode::addChild(Node *child, int zOrder, int tag) Node::addChild(child, zOrder, tag); appendChild(sprite); - - - if (this->getParent() && - dynamic_cast(this->getParent()) != nullptr) - { - if (this->getParent()->getParent() && - dynamic_cast(this->getParent()->getParent())) - { - dynamic_cast(this->getParent()->getParent())->addChildToPhysicsWorld(child); - } - } } // override reorderChild @@ -609,8 +598,8 @@ void SpriteBatchNode::removeSpriteFromAtlas(Sprite *sprite) { auto next = std::next(it); - std::for_each(next, _descendants.end(), [](Sprite *sprite) { - sprite->setAtlasIndex( sprite->getAtlasIndex() - 1 ); + std::for_each(next, _descendants.end(), [](Sprite *spr) { + spr->setAtlasIndex( spr->getAtlasIndex() - 1 ); }); _descendants.erase(it); diff --git a/cocos/2d/CCSpriteBatchNode.h b/cocos/2d/CCSpriteBatchNode.h index 6ba402fe57..8d1b930771 100644 --- a/cocos/2d/CCSpriteBatchNode.h +++ b/cocos/2d/CCSpriteBatchNode.h @@ -74,7 +74,7 @@ public: The capacity will be increased in 33% in runtime if it run out of space. 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 */ @@ -88,14 +88,14 @@ public: /** 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. */ - 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. The capacity will be increased in 33% in runtime if it run out of space. The file will be loaded using the TextureMgr. * @js init * @lua init */ - bool initWithFile(const char* fileImage, int capacity); + bool initWithFile(const char* fileImage, long capacity); bool init(); /** returns the TextureAtlas object */ diff --git a/cocos/2d/CCSpriteFrame.cpp b/cocos/2d/CCSpriteFrame.cpp index 8bc0bafa6d..06ca1b80c5 100644 --- a/cocos/2d/CCSpriteFrame.cpp +++ b/cocos/2d/CCSpriteFrame.cpp @@ -31,61 +31,61 @@ NS_CC_BEGIN // 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->autorelease(); return pSpriteFrame; } -SpriteFrame* SpriteFrame::createWithTexture(Texture2D *pobTexture, const Rect& rect) +SpriteFrame* SpriteFrame::createWithTexture(Texture2D *texture, const Rect& rect) { - SpriteFrame *pSpriteFrame = new SpriteFrame();; - pSpriteFrame->initWithTexture(pobTexture, rect); + SpriteFrame *pSpriteFrame = new SpriteFrame(); + pSpriteFrame->initWithTexture(texture, rect); pSpriteFrame->autorelease(); 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();; - pSpriteFrame->initWithTexture(pobTexture, rect, rotated, offset, originalSize); + SpriteFrame *pSpriteFrame = new SpriteFrame(); + pSpriteFrame->initWithTexture(texture, rect, rotated, offset, originalSize); pSpriteFrame->autorelease(); 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->autorelease(); 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); - 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 ); 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; @@ -99,7 +99,7 @@ bool SpriteFrame::initWithTexture(Texture2D* pobTexture, const Rect& rect, bool 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; _textureFilename = filename; @@ -180,7 +180,7 @@ Texture2D* SpriteFrame::getTexture(void) } if( _textureFilename.length() > 0 ) { - return TextureCache::getInstance()->addImage(_textureFilename.c_str()); + return Director::getInstance()->getTextureCache()->addImage(_textureFilename.c_str()); } // no texture or texture filename return NULL; diff --git a/cocos/2d/CCSpriteFrame.h b/cocos/2d/CCSpriteFrame.h index f9b2d68c4a..4d205d0f8a 100644 --- a/cocos/2d/CCSpriteFrame.h +++ b/cocos/2d/CCSpriteFrame.h @@ -58,12 +58,12 @@ public: /** Create a SpriteFrame with a texture filename, rect in points. 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. 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. It is assumed that the frame was not trimmed. @@ -88,7 +88,7 @@ public: /** Initializes a SpriteFrame with a texture filename, rect in points; 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. The originalSize is the size in points of the frame before being trimmed. @@ -100,7 +100,7 @@ public: @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 diff --git a/cocos/2d/CCSpriteFrameCache.cpp b/cocos/2d/CCSpriteFrameCache.cpp index 78fc2f8fa6..f5afd18f76 100644 --- a/cocos/2d/CCSpriteFrameCache.cpp +++ b/cocos/2d/CCSpriteFrameCache.cpp @@ -37,6 +37,7 @@ THE SOFTWARE. #include "CCString.h" #include "CCArray.h" #include "CCDictionary.h" +#include "CCDirector.h" #include using namespace std; @@ -102,11 +103,11 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex // check the format CCASSERT(format >=0 && format <= 3, "format is not supported for SpriteFrameCache addSpriteFramesWithDictionary:textureFilename:"); - DictElement* pElement = NULL; - CCDICT_FOREACH(framesDict, pElement) + DictElement* element = NULL; + CCDICT_FOREACH(framesDict, element) { - Dictionary* frameDict = static_cast(pElement->getObject()); - std::string spriteFrameName = pElement->getStrKey(); + Dictionary* frameDict = static_cast(element->getObject()); + std::string spriteFrameName = element->getStrKey(); SpriteFrame* spriteFrame = static_cast(_spriteFrames->objectForKey(spriteFrameName)); 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); Dictionary *dict = Dictionary::createWithContentsOfFileThreadSafe(fullPath.c_str()); @@ -212,10 +213,10 @@ void SpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist, Texture2D * 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"); - Texture2D *texture = TextureCache::getInstance()->addImage(textureFileName); + CCASSERT(textureFileName.size()>0, "texture name should not be null"); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(textureFileName); if (texture) { @@ -223,13 +224,13 @@ void SpriteFrameCache::addSpriteFramesWithFile(const char* plist, const char* te } 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()) { @@ -265,7 +266,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist) 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) { @@ -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); } @@ -295,14 +296,14 @@ void SpriteFrameCache::removeSpriteFrames(void) void SpriteFrameCache::removeUnusedSpriteFrames(void) { bool bRemoved = false; - DictElement* pElement = NULL; - CCDICT_FOREACH(_spriteFrames, pElement) + DictElement* element = NULL; + CCDICT_FOREACH(_spriteFrames, element) { - SpriteFrame* spriteFrame = static_cast(pElement->getObject()); + SpriteFrame* spriteFrame = static_cast(element->getObject()); if( spriteFrame->retainCount() == 1 ) { - CCLOG("cocos2d: SpriteFrameCache: removing unused frame: %s", pElement->getStrKey()); - _spriteFrames->removeObjectForElememt(pElement); + CCLOG("cocos2d: SpriteFrameCache: removing unused frame: %s", element->getStrKey()); + _spriteFrames->removeObjectForElememt(element); 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 - if( ! pszName ) - { + if( ! name.size()>0 ) return; - } // Is this an alias ? - String* key = (String*)_spriteFramesAliases->objectForKey(pszName); + String* key = (String*)_spriteFramesAliases->objectForKey(name); if (key) { @@ -333,20 +332,20 @@ void SpriteFrameCache::removeSpriteFrameByName(const char *pszName) } 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 _loadedFileNames->clear(); } -void SpriteFrameCache::removeSpriteFramesFromFile(const char* plist) +void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& plist) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist); Dictionary* dict = Dictionary::createWithContentsOfFileThreadSafe(fullPath.c_str()); 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; } removeSpriteFramesFromDictionary((Dictionary*)dict); @@ -365,12 +364,12 @@ void SpriteFrameCache::removeSpriteFramesFromDictionary(Dictionary* dictionary) Dictionary* framesDict = static_cast(dictionary->objectForKey("frames")); Array* keysToRemove = Array::create(); - DictElement* pElement = NULL; - CCDICT_FOREACH(framesDict, pElement) + DictElement* element = NULL; + 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(); - DictElement* pElement = NULL; - CCDICT_FOREACH(_spriteFrames, pElement) + DictElement* element = NULL; + CCDICT_FOREACH(_spriteFrames, element) { - string key = pElement->getStrKey(); + string key = element->getStrKey(); SpriteFrame* frame = static_cast(_spriteFrames->objectForKey(key.c_str())); if (frame && (frame->getTexture() == texture)) { - keysToRemove->addObject(String::create(pElement->getStrKey())); + keysToRemove->addObject(String::create(element->getStrKey())); } } _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) { // try alias dictionary - String *key = (String*)_spriteFramesAliases->objectForKey(pszName); + String *key = (String*)_spriteFramesAliases->objectForKey(name); if (key) { frame = (SpriteFrame*)_spriteFrames->objectForKey(key->getCString()); if (! frame) { - CCLOG("cocos2d: SpriteFrameCache: Frame '%s' not found", pszName); + CCLOG("cocos2d: SpriteFrameCache: Frame '%s' not found", name.c_str()); } } } diff --git a/cocos/2d/CCSpriteFrameCache.h b/cocos/2d/CCSpriteFrameCache.h index c7249d222c..11733fa0ff 100644 --- a/cocos/2d/CCSpriteFrameCache.h +++ b/cocos/2d/CCSpriteFrameCache.h @@ -85,29 +85,29 @@ public: public: /** Adds multiple Sprite Frames from a plist file. * A texture will be loaded automatically. The texture name will composed by replacing the .plist suffix with .png - * If you want to use another texture, you should use the addSpriteFramesWithFile(const 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 * @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. @since v0.99.5 * @js 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. * @js 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. 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. * Call this method if you receive the "Memory Warning". @@ -124,14 +124,14 @@ public: void removeUnusedSpriteFrames(void); /** 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. * Sprite Frames stored in this file will be removed. * It is convenient to call this method when a specific texture needs to be removed. * @since v0.99.5 */ - void removeSpriteFramesFromFile(const char* plist); + void removeSpriteFramesFromFile(const std::string& plist); /** Removes all Sprite Frames associated with the specified textures. * It is convenient to call this method when a specific texture needs to be removed. @@ -145,10 +145,10 @@ public: * @js getSpriteFrame * @lua getSpriteFrame */ - SpriteFrame* getSpriteFrameByName(const char *name); + SpriteFrame* getSpriteFrameByName(const std::string& name); /** @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: /*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames. diff --git a/cocos/2d/CCTMXLayer.cpp b/cocos/2d/CCTMXLayer.cpp index 4b801ea83e..aa48b8b2b4 100644 --- a/cocos/2d/CCTMXLayer.cpp +++ b/cocos/2d/CCTMXLayer.cpp @@ -58,7 +58,7 @@ bool TMXLayer::initWithTilesetInfo(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *la Texture2D *texture = NULL; 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)) diff --git a/cocos/2d/CCTMXTiledMap.cpp b/cocos/2d/CCTMXTiledMap.cpp index c6c47b3abd..4205adb1fe 100644 --- a/cocos/2d/CCTMXTiledMap.cpp +++ b/cocos/2d/CCTMXTiledMap.cpp @@ -32,33 +32,33 @@ NS_CC_BEGIN // implementation TMXTiledMap -TMXTiledMap * TMXTiledMap::create(const char *tmxFile) +TMXTiledMap * TMXTiledMap::create(const std::string& tmxFile) { - TMXTiledMap *pRet = new TMXTiledMap(); - if (pRet->initWithTMXFile(tmxFile)) + TMXTiledMap *ret = new TMXTiledMap(); + if (ret->initWithTMXFile(tmxFile)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); 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(); - if (pRet->initWithXML(tmxString, resourcePath)) + TMXTiledMap *ret = new TMXTiledMap(); + if (ret->initWithXML(tmxString, resourcePath)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); 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); @@ -74,7 +74,7 @@ bool TMXTiledMap::initWithTMXFile(const char *tmxFile) 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); @@ -195,8 +195,8 @@ void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo) // update content size with the max size const Size& childSize = child->getContentSize(); Size currentSize = this->getContentSize(); - currentSize.width = MAX( currentSize.width, childSize.width ); - currentSize.height = MAX( currentSize.height, childSize.height ); + currentSize.width = std::max( currentSize.width, childSize.width ); + currentSize.height = std::max( currentSize.height, childSize.height ); this->setContentSize(currentSize); idx++; @@ -206,16 +206,16 @@ void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo) } // 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; CCARRAY_FOREACH(_children, pObj) { TMXLayer* layer = dynamic_cast(pObj); if(layer) { - if(0 == strcmp(layer->getLayerName(), layerName)) + if(layerName.compare( layer->getLayerName()) == 0) { return layer; } @@ -226,11 +226,10 @@ TMXLayer * TMXTiledMap::getLayer(const char *layerName) const 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) { TMXObjectGroup* objectGroup = NULL; @@ -238,7 +237,7 @@ TMXObjectGroup * TMXTiledMap::getObjectGroup(const char *groupName) const CCARRAY_FOREACH(_objectGroups, pObj) { objectGroup = static_cast(pObj); - if (objectGroup && objectGroup->getGroupName() == sGroupName) + if (objectGroup && objectGroup->getGroupName() == groupName) { return objectGroup; } @@ -249,7 +248,7 @@ TMXObjectGroup * TMXTiledMap::getObjectGroup(const char *groupName) const return NULL; } -String* TMXTiledMap::getProperty(const char *propertyName) const +String* TMXTiledMap::getProperty(const std::string& propertyName) const { return static_cast(_properties->objectForKey(propertyName)); } diff --git a/cocos/2d/CCTMXTiledMap.h b/cocos/2d/CCTMXTiledMap.h index 82ea45bd13..f870938174 100644 --- a/cocos/2d/CCTMXTiledMap.h +++ b/cocos/2d/CCTMXTiledMap.h @@ -120,19 +120,19 @@ public: virtual ~TMXTiledMap(); /** 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 */ - 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 */ - 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 */ - 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 */ - TMXLayer* getLayer(const char *layerName) const; + TMXLayer* getLayer(const std::string& layerName) const; /** * @js NA * @lua NA @@ -140,7 +140,7 @@ public: CC_DEPRECATED_ATTRIBUTE TMXLayer* layerNamed(const char *layerName) const { return getLayer(layerName); }; /** return the TMXObjectGroup for the specific group */ - TMXObjectGroup* getObjectGroup(const char *groupName) const; + TMXObjectGroup* getObjectGroup(const std::string& groupName) const; /** * @js NA * @lua NA @@ -148,7 +148,7 @@ public: CC_DEPRECATED_ATTRIBUTE TMXObjectGroup* objectGroupNamed(const char *groupName) const { return getObjectGroup(groupName); }; /** return the value for the specific property name */ - String *getProperty(const char *propertyName) const; + String *getProperty(const std::string& propertyName) const; /** * @js NA * @lua NA diff --git a/cocos/2d/CCTMXXMLParser.cpp b/cocos/2d/CCTMXXMLParser.cpp index 8497638cf7..d981cca6b4 100644 --- a/cocos/2d/CCTMXXMLParser.cpp +++ b/cocos/2d/CCTMXXMLParser.cpp @@ -112,7 +112,7 @@ Rect TMXTilesetInfo::rectForGID(unsigned int gid) // implementation TMXMapInfo -TMXMapInfo * TMXMapInfo::create(const char *tmxFile) +TMXMapInfo * TMXMapInfo::create(const std::string& tmxFile) { TMXMapInfo *pRet = new TMXMapInfo(); if(pRet->initWithTMXFile(tmxFile)) @@ -124,7 +124,7 @@ TMXMapInfo * TMXMapInfo::create(const char *tmxFile) 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(); if(pRet->initWithXML(tmxString, resourcePath)) @@ -136,7 +136,7 @@ TMXMapInfo * TMXMapInfo::createWithXML(const char* tmxString, const char* resour 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->retain(); @@ -144,12 +144,12 @@ void TMXMapInfo::internalInit(const char* tmxFileName, const char* resourcePath) _layers = Array::create(); _layers->retain(); - if (tmxFileName != NULL) + if (tmxFileName.size() > 0) { _TMXFileName = FileUtils::getInstance()->fullPathForFilename(tmxFileName); } - if (resourcePath != NULL) + if (resourcePath.size() > 0) { _resources = resourcePath; } @@ -169,15 +169,15 @@ void TMXMapInfo::internalInit(const char* tmxFileName, const char* resourcePath) _parentElement = TMXPropertyNone; _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); } -bool TMXMapInfo::initWithTMXFile(const char *tmxFile) +bool TMXMapInfo::initWithTMXFile(const std::string& tmxFile) { - internalInit(tmxFile, NULL); + internalInit(tmxFile, ""); return parseXMLFile(_TMXFileName.c_str()); } @@ -205,13 +205,11 @@ TMXMapInfo::~TMXMapInfo() CC_SAFE_RELEASE(_objectGroups); } -bool TMXMapInfo::parseXMLString(const char *xmlString) +bool TMXMapInfo::parseXMLString(const std::string& xmlString) { - int len = strlen(xmlString); - if (xmlString == NULL || len <= 0) - { + int len = xmlString.size(); + if (len <= 0) return false; - } SAXParser parser; @@ -222,10 +220,10 @@ bool TMXMapInfo::parseXMLString(const char *xmlString) 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; diff --git a/cocos/2d/CCTMXXMLParser.h b/cocos/2d/CCTMXXMLParser.h index 7b4851386c..80afafd1aa 100644 --- a/cocos/2d/CCTMXXMLParser.h +++ b/cocos/2d/CCTMXXMLParser.h @@ -166,9 +166,9 @@ class CC_DLL TMXMapInfo : public Object, public SAXDelegator { public: /** 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 */ - 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 */ CC_DEPRECATED_ATTRIBUTE static TMXMapInfo * formatWithTMXFile(const char *tmxFile) { return TMXMapInfo::create(tmxFile); }; @@ -185,13 +185,13 @@ public: virtual ~TMXMapInfo(); /** 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 */ - 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 */ - 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 */ - bool parseXMLString(const char *xmlString); + bool parseXMLString(const std::string& xmlString); Dictionary* getTileProperties() { return _tileProperties; }; void setTileProperties(Dictionary* tileProperties) { @@ -278,13 +278,13 @@ public: */ void textHandler(void *ctx, const char *ch, int len); - inline const char* getCurrentString(){ return _currentString.c_str(); } - inline void setCurrentString(const char *currentString){ _currentString = currentString; } - inline const char* getTMXFileName(){ return _TMXFileName.c_str(); } - inline void setTMXFileName(const char *fileName){ _TMXFileName = fileName; } -private: - void internalInit(const char* tmxFileName, const char* resourcePath); + inline const std::string& getCurrentString() const { return _currentString; } + inline void setCurrentString(const std::string& currentString){ _currentString = currentString; } + inline const std::string& getTMXFileName() const { return _TMXFileName; } + inline void setTMXFileName(const std::string& fileName){ _TMXFileName = fileName; } + protected: + void internalInit(const std::string& tmxFileName, const std::string& resourcePath); /// map orientation int _orientation; diff --git a/cocos/2d/CCTextFieldTTF.cpp b/cocos/2d/CCTextFieldTTF.cpp index 934b88a091..895aab58de 100644 --- a/cocos/2d/CCTextFieldTTF.cpp +++ b/cocos/2d/CCTextFieldTTF.cpp @@ -53,8 +53,8 @@ static int _calcCharCount(const char * pszText) TextFieldTTF::TextFieldTTF() : _delegate(0) , _charCount(0) -, _inputText(new std::string) -, _placeHolder(new std::string) // prevent LabelTTF initWithString assertion +, _inputText("") +, _placeHolder("") // prevent LabelTTF initWithString assertion , _secureTextEntry(false) { _colorSpaceHolder.r = _colorSpaceHolder.g = _colorSpaceHolder.b = 127; @@ -62,43 +62,41 @@ TextFieldTTF::TextFieldTTF() TextFieldTTF::~TextFieldTTF() { - CC_SAFE_DELETE(_inputText); - CC_SAFE_DELETE(_placeHolder); } ////////////////////////////////////////////////////////////////////////// // 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(); - if(pRet && pRet->initWithPlaceHolder("", dimensions, alignment, fontName, fontSize)) + TextFieldTTF *ret = new TextFieldTTF(); + if(ret && ret->initWithPlaceHolder("", dimensions, alignment, fontName, fontSize)) { - pRet->autorelease(); - if (placeholder) + ret->autorelease(); + if (placeholder.size()>0) { - pRet->setPlaceHolder(placeholder); + ret->setPlaceHolder(placeholder); } - return pRet; + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); 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(); - if(pRet && pRet->initWithString("", fontName, fontSize)) + TextFieldTTF *ret = new TextFieldTTF(); + if(ret && ret->initWithString("", fontName, fontSize)) { - pRet->autorelease(); - if (placeholder) + ret->autorelease(); + if (placeholder.size()>0) { - pRet->setPlaceHolder(placeholder); + ret->setPlaceHolder(placeholder); } - return pRet; + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } @@ -106,23 +104,15 @@ TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const char *placeholder, c // 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) - { - CC_SAFE_DELETE(_placeHolder); - _placeHolder = new std::string(placeholder); - } - return LabelTTF::initWithString(_placeHolder->c_str(), fontName, fontSize, dimensions, alignment); + _placeHolder = placeholder; + return LabelTTF::initWithString(_placeHolder, 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) - { - CC_SAFE_DELETE(_placeHolder); - _placeHolder = new std::string(placeholder); - } - return LabelTTF::initWithString(_placeHolder->c_str(), fontName, fontSize); + _placeHolder = std::string(placeholder); + return LabelTTF::initWithString(_placeHolder, fontName, fontSize); } ////////////////////////////////////////////////////////////////////////// @@ -190,9 +180,9 @@ void TextFieldTTF::insertText(const char * text, int len) } _charCount += _calcCharCount(sInsert.c_str()); - std::string sText(*_inputText); + std::string sText(_inputText); sText.append(sInsert); - setString(sText.c_str()); + setString(sText); } if ((int)sInsert.npos == nPos) { @@ -211,7 +201,7 @@ void TextFieldTTF::insertText(const char * text, int len) void TextFieldTTF::deleteBackward() { - int nStrLen = _inputText->length(); + int nStrLen = _inputText.length(); if (! nStrLen) { // there is no string @@ -221,12 +211,12 @@ void TextFieldTTF::deleteBackward() // get the delete byte number int nDeleteLen = 1; // default, erase 1 byte - while(0x80 == (0xC0 & _inputText->at(nStrLen - nDeleteLen))) + while(0x80 == (0xC0 & _inputText.at(nStrLen - 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 return; @@ -235,21 +225,20 @@ void TextFieldTTF::deleteBackward() // if all text deleted, show placeholder string if (nStrLen <= nDeleteLen) { - CC_SAFE_DELETE(_inputText); - _inputText = new std::string; + _inputText = ""; _charCount = 0; - LabelTTF::setString(_placeHolder->c_str()); + LabelTTF::setString(_placeHolder); return; } // set new input text - std::string sText(_inputText->c_str(), nStrLen - nDeleteLen); - setString(sText.c_str()); + std::string sText(_inputText.c_str(), nStrLen - nDeleteLen); + setString(sText); } const char * TextFieldTTF::getContentText() { - return _inputText->c_str(); + return _inputText.c_str(); } void TextFieldTTF::draw() @@ -258,7 +247,7 @@ void TextFieldTTF::draw() { return; } - if (_inputText->length()) + if (_inputText.length()) { LabelTTF::draw(); return; @@ -286,22 +275,20 @@ void TextFieldTTF::setColorSpaceHolder(const Color3B& color) ////////////////////////////////////////////////////////////////////////// // 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}; std::string displayText; int length; - CC_SAFE_DELETE(_inputText); - - if (text) + if (text.length()>0) { - _inputText = new std::string(text); - displayText = *_inputText; + _inputText = text; + displayText = _inputText; if (_secureTextEntry) { displayText = ""; - length = _inputText->length(); + length = _inputText.length(); while (length) { displayText.append(bulletString); @@ -311,40 +298,39 @@ void TextFieldTTF::setString(const char *text) } else { - _inputText = new std::string; + _inputText = ""; } // if there is no input text, display placeholder instead - if (! _inputText->length()) + if (! _inputText.length()) { - LabelTTF::setString(_placeHolder->c_str()); + LabelTTF::setString(_placeHolder); } 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 -void TextFieldTTF::setPlaceHolder(const char * text) +void TextFieldTTF::setPlaceHolder(const std::string& text) { - CC_SAFE_DELETE(_placeHolder); - _placeHolder = (text) ? new std::string(text) : new std::string; - if (! _inputText->length()) + _placeHolder = text; + 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 diff --git a/cocos/2d/CCTextFieldTTF.h b/cocos/2d/CCTextFieldTTF.h index 79feb55d7c..a6ae42dc8e 100644 --- a/cocos/2d/CCTextFieldTTF.h +++ b/cocos/2d/CCTextFieldTTF.h @@ -109,13 +109,13 @@ public: //char * description(); /** 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 */ - 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 */ - 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 */ - 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. @@ -147,21 +147,21 @@ public: // input text property public: - virtual void setString(const char *text); - virtual const char* getString(void) const; + virtual void setString(const std::string& text) override; + virtual const std::string& getString() const override; protected: TextFieldDelegate * _delegate; int _charCount; - std::string * _inputText; + std::string _inputText; // place holder text property // place holder text displayed when there is no text in the text field. public: - virtual void setPlaceHolder(const char * text); - virtual const char * getPlaceHolder(void); + virtual void setPlaceHolder(const std::string& text); + virtual const std::string& getPlaceHolder(void) const; protected: - std::string * _placeHolder; + std::string _placeHolder; Color3B _colorSpaceHolder; public: virtual void setSecureTextEntry(bool value); @@ -176,11 +176,11 @@ protected: // IMEDelegate interface ////////////////////////////////////////////////////////////////////////// - virtual bool canAttachWithIME(); - virtual bool canDetachWithIME(); - virtual void insertText(const char * text, int len); - virtual void deleteBackward(); - virtual const char * getContentText(); + virtual bool canAttachWithIME() override; + virtual bool canDetachWithIME() override; + virtual void insertText(const char * text, int len) override; + virtual void deleteBackward() override; + virtual const char * getContentText() override; private: class LengthStack; LengthStack * _lens; diff --git a/cocos/2d/CCTexture2D.cpp b/cocos/2d/CCTexture2D.cpp index 84a6822dda..2f0665afb4 100644 --- a/cocos/2d/CCTexture2D.cpp +++ b/cocos/2d/CCTexture2D.cpp @@ -119,7 +119,7 @@ static bool _PVRHaveAlphaPremultiplied = false; //conventer function // 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) { @@ -130,7 +130,7 @@ void Texture2D::convertI8ToRGB888(const unsigned char* data, int dataLen, unsign } // 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) { @@ -141,7 +141,7 @@ void Texture2D::convertAI88ToRGB888(const unsigned char* data, int dataLen, unsi } // 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) { @@ -153,7 +153,7 @@ void Texture2D::convertI8ToRGBA8888(const unsigned char* data, int dataLen, unsi } // 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) { @@ -165,7 +165,7 @@ void Texture2D::convertAI88ToRGBA8888(const unsigned char* data, int dataLen, un } // 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; for (int i = 0; i < dataLen; ++i) @@ -177,7 +177,7 @@ void Texture2D::convertI8ToRGB565(const unsigned char* data, int dataLen, unsign } // 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; 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 -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; for (int i = 0; i < dataLen; ++i) @@ -202,7 +202,7 @@ void Texture2D::convertI8ToRGBA4444(const unsigned char* data, int dataLen, unsi } // 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; 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 -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; for (int i = 0; i < dataLen; ++i) @@ -228,7 +228,7 @@ void Texture2D::convertI8ToRGB5A1(const unsigned char* data, int dataLen, unsign } // 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; 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 -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; for (int i = 0; i < dataLen; ++i) @@ -252,7 +252,7 @@ void Texture2D::convertI8ToAI88(const unsigned char* data, int dataLen, unsigned } // 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) { @@ -261,7 +261,7 @@ void Texture2D::convertAI88ToA8(const unsigned char* data, int dataLen, unsigned } // 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) { @@ -270,7 +270,7 @@ void Texture2D::convertAI88ToI8(const unsigned char* data, int dataLen, unsigned } // 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) { @@ -282,7 +282,7 @@ void Texture2D::convertRGB888ToRGBA8888(const unsigned char* data, int dataLen, } // 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) { @@ -293,7 +293,7 @@ void Texture2D::convertRGBA8888ToRGB888(const unsigned char* data, int dataLen, } // 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; 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 -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; 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 -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) { @@ -326,7 +326,7 @@ void Texture2D::convertRGB888ToI8(const unsigned char* data, int dataLen, unsign } // 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) { @@ -335,7 +335,7 @@ void Texture2D::convertRGBA8888ToI8(const unsigned char* data, int dataLen, unsi } // 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) { @@ -344,7 +344,7 @@ void Texture2D::convertRGBA8888ToA8(const unsigned char* data, int dataLen, unsi } // 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) { @@ -355,7 +355,7 @@ void Texture2D::convertRGB888ToAI88(const unsigned char* data, int dataLen, unsi // 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) { @@ -365,7 +365,7 @@ void Texture2D::convertRGBA8888ToAI88(const unsigned char* data, int dataLen, un } // 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; 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 -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; 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 -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; - 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 | (data[i + 1] & 0x00F8) << 3 //G @@ -404,10 +404,10 @@ void Texture2D::convertRGB888ToRGB5A1(const unsigned char* data, int dataLen, un } // 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; - 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 | (data[i + 1] & 0x00F8) << 3 //G @@ -434,7 +434,7 @@ Texture2D::Texture2D() Texture2D::~Texture2D() { #if CC_ENABLE_CACHE_TEXTURE_DATA - VolatileTexture::removeTexture(this); + VolatileTextureMgr::removeTexture(this); #endif CCLOGINFO("deallocing Texture2D: %p - id=%u", this, _name); @@ -451,12 +451,12 @@ Texture2D::PixelFormat Texture2D::getPixelFormat() const return _pixelFormat; } -unsigned int Texture2D::getPixelsWide() const +long Texture2D::getPixelsWide() const { return _pixelsWide; } -unsigned int Texture2D::getPixelsHigh() const +long Texture2D::getPixelsHigh() const { return _pixelsHigh; } @@ -529,8 +529,10 @@ bool Texture2D::hasPremultipliedAlpha() const 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 MipmapInfo mipmap; 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 - 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) { @@ -670,7 +673,7 @@ bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat const char* Texture2D::description(void) const { - return String::createWithFormat("", _name, _pixelsWide, _pixelsHigh, _maxS, _maxT)->getCString(); + return String::createWithFormat("", _name, (long)_pixelsWide, (long)_pixelsHigh, _maxS, _maxT)->getCString(); } // 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) { @@ -820,7 +823,7 @@ Texture2D::PixelFormat Texture2D::convertI8ToFormat(const unsigned char* data, i 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) { @@ -875,7 +878,7 @@ Texture2D::PixelFormat Texture2D::convertAI88ToFormat(const unsigned char* data, 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) { @@ -923,7 +926,7 @@ Texture2D::PixelFormat Texture2D::convertRGB888ToFormat(const unsigned char* dat 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) @@ -995,7 +998,7 @@ rgb(2) -> 1235678 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) { @@ -1038,7 +1041,7 @@ bool Texture2D::initWithString(const char *text, const FontDefinition& textDefin { #if CC_ENABLE_CACHE_TEXTURE_DATA // cache the texture data - VolatileTexture::addStringTexture(this, text, textDefinition); + VolatileTextureMgr::addStringTexture(this, text, textDefinition); #endif bool bRet = false; @@ -1264,7 +1267,7 @@ void Texture2D::setTexParameters(const TexParams &texParams) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texParams.wrapT ); #if CC_ENABLE_CACHE_TEXTURE_DATA - VolatileTexture::setTexParameters(this, texParams); + VolatileTextureMgr::setTexParameters(this, texParams); #endif } @@ -1284,7 +1287,7 @@ void Texture2D::setAliasTexParameters() glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); #if CC_ENABLE_CACHE_TEXTURE_DATA 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 } @@ -1304,7 +1307,7 @@ void Texture2D::setAntiAliasTexParameters() glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); #if CC_ENABLE_CACHE_TEXTURE_DATA 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 } diff --git a/cocos/2d/CCTexture2D.h b/cocos/2d/CCTexture2D.h index 6f15273f9c..bdb28ce582 100644 --- a/cocos/2d/CCTexture2D.h +++ b/cocos/2d/CCTexture2D.h @@ -120,13 +120,13 @@ public: struct PixelFormatInfo { - PixelFormatInfo(GLenum internalFormat, GLenum format, GLenum type, int bpp, bool compressed, bool alpha) - : internalFormat(internalFormat) - , format(format) - , type(type) - , bpp(bpp) - , compressed(compressed) - , alpha(alpha) + PixelFormatInfo(GLenum anInternalFormat, GLenum aFormat, GLenum aType, int aBpp, bool aCompressed, bool anAlpha) + : internalFormat(anInternalFormat) + , format(aFormat) + , type(aType) + , bpp(aBpp) + , compressed(aCompressed) + , alpha(anAlpha) {} GLenum internalFormat; @@ -216,10 +216,10 @@ public: * @js 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 */ - 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. @@ -326,10 +326,10 @@ public: Texture2D::PixelFormat getPixelFormat() const; /** Gets the width of the texture in pixels */ - unsigned int getPixelsWide() const; + long getPixelsWide() const; /** Gets the height of the texture in pixels */ - unsigned int getPixelsHigh() const; + long getPixelsHigh() const; /** Gets the texture name */ 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. 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 convertAI88ToFormat(const unsigned char* data, int 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 convertRGBA8888ToFormat(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, long 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, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); //I8 to XXX - static void convertI8ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertI8ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertI8ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertI8ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertI8ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertI8ToAI88(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, long dataLen, unsigned char* outData); + static void convertI8ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertI8ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertI8ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertI8ToAI88(const unsigned char* data, long dataLen, unsigned char* outData); //AI88 to XXX - static void convertAI88ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertAI88ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertAI88ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertAI88ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertAI88ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertAI88ToA8(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertAI88ToI8(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, long dataLen, unsigned char* outData); + static void convertAI88ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertAI88ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertAI88ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertAI88ToA8(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertAI88ToI8(const unsigned char* data, long dataLen, unsigned char* outData); //RGB888 to XXX - static void convertRGB888ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGB888ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGB888ToI8(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGB888ToAI88(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGB888ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGB888ToRGB5A1(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, long dataLen, unsigned char* outData); + static void convertRGB888ToI8(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGB888ToAI88(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGB888ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGB888ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData); //RGBA8888 to XXX - static void convertRGBA8888ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGBA8888ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGBA8888ToI8(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGBA8888ToA8(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGBA8888ToAI88(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGBA8888ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGBA8888ToRGB5A1(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, long dataLen, unsigned char* outData); + static void convertRGBA8888ToI8(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGBA8888ToA8(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGBA8888ToAI88(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGBA8888ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGBA8888ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData); protected: /** pixel format of the texture */ Texture2D::PixelFormat _pixelFormat; /** width in pixels */ - unsigned int _pixelsWide; + long _pixelsWide; /** height in pixels */ - unsigned int _pixelsHigh; + long _pixelsHigh; /** texture name */ GLuint _name; diff --git a/cocos/2d/CCTextureAtlas.cpp b/cocos/2d/CCTextureAtlas.cpp index 63854dd0a6..82ca929060 100644 --- a/cocos/2d/CCTextureAtlas.cpp +++ b/cocos/2d/CCTextureAtlas.cpp @@ -32,6 +32,7 @@ THE SOFTWARE. #include "ccGLStateCache.h" #include "CCNotificationCenter.h" #include "CCEventType.h" +#include "CCDirector.h" #include "CCGL.h" #include "CCConfiguration.h" // support @@ -72,12 +73,12 @@ TextureAtlas::~TextureAtlas() #endif } -int TextureAtlas::getTotalQuads() const +long TextureAtlas::getTotalQuads() const { return _totalQuads; } -int TextureAtlas::getCapacity() const +long TextureAtlas::getCapacity() const { return _capacity; } @@ -108,7 +109,7 @@ void TextureAtlas::setQuads(V3F_C4B_T2F_Quad* quads) // TextureAtlas - alloc & init -TextureAtlas * TextureAtlas::create(const char* file, int capacity) +TextureAtlas * TextureAtlas::create(const char* file, long capacity) { TextureAtlas * textureAtlas = new TextureAtlas(); if(textureAtlas && textureAtlas->initWithFile(file, capacity)) @@ -120,7 +121,7 @@ TextureAtlas * TextureAtlas::create(const char* file, int capacity) return NULL; } -TextureAtlas * TextureAtlas::createWithTexture(Texture2D *texture, int capacity) +TextureAtlas * TextureAtlas::createWithTexture(Texture2D *texture, long capacity) { TextureAtlas * textureAtlas = new TextureAtlas(); if (textureAtlas && textureAtlas->initWithTexture(texture, capacity)) @@ -132,10 +133,10 @@ TextureAtlas * TextureAtlas::createWithTexture(Texture2D *texture, int capacity) return NULL; } -bool TextureAtlas::initWithFile(const char * file, int capacity) +bool TextureAtlas::initWithFile(const char * file, long capacity) { // retained in property - Texture2D *texture = TextureCache::getInstance()->addImage(file); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(file); 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"); @@ -218,7 +219,7 @@ void TextureAtlas::listenBackToForeground(Object *obj) const char* TextureAtlas::description() const { - return String::createWithFormat("", _totalQuads)->getCString(); + return String::createWithFormat("", _totalQuads)->getCString(); } @@ -311,7 +312,7 @@ void TextureAtlas::mapBuffers() // 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"); @@ -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"); @@ -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"); @@ -357,7 +358,7 @@ void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, int index, int amount) CCASSERT( _totalQuads <= _capacity, "invalid 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 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; - for (int i = index; i < max ; i++) + for (long i = index; i < max ; i++) { _quads[index] = quads[j]; index++; @@ -379,7 +380,7 @@ void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, int index, int amount) _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( 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 // unsigned int howMany = abs( oldIndex - newIndex); - int howMany = (oldIndex - newIndex) > 0 ? (oldIndex - newIndex) : (newIndex - oldIndex); - int dst = oldIndex; - int src = oldIndex + 1; + long howMany = (oldIndex - newIndex) > 0 ? (oldIndex - newIndex) : (newIndex - oldIndex); + long dst = oldIndex; + long src = oldIndex + 1; if( oldIndex > newIndex) { dst = newIndex+1; @@ -408,11 +409,11 @@ void TextureAtlas::insertQuadFromIndex(int oldIndex, int newIndex) _dirty = true; } -void TextureAtlas::removeQuadAtIndex(int index) +void TextureAtlas::removeQuadAtIndex(long 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 if( remaining ) @@ -427,11 +428,11 @@ void TextureAtlas::removeQuadAtIndex(int index) _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"); - int remaining = (_totalQuads) - (index + amount); + long remaining = (_totalQuads) - (index + amount); _totalQuads -= amount; @@ -449,14 +450,14 @@ void TextureAtlas::removeAllQuads() } // TextureAtlas - Resize -bool TextureAtlas::resizeCapacity(int newCapacity) +bool TextureAtlas::resizeCapacity(long newCapacity) { CCASSERT(newCapacity>=0, "capacity >= 0"); if( newCapacity == _capacity ) { return true; } - int oldCapactiy = _capacity; + long oldCapactiy = _capacity; // update capacity and totolQuads _totalQuads = MIN(_totalQuads, newCapacity); _capacity = newCapacity; @@ -523,13 +524,13 @@ bool TextureAtlas::resizeCapacity(int newCapacity) return true; } -void TextureAtlas::increaseTotalQuadsWith(int amount) +void TextureAtlas::increaseTotalQuadsWith(long amount) { CCASSERT(amount>=0, "amount >= 0"); _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(newIndex + amount <= _totalQuads, "insertQuadFromIndex:atIndex: Invalid index"); @@ -561,7 +562,7 @@ void TextureAtlas::moveQuadsFromIndex(int oldIndex, int amount, int newIndex) _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(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])); } -void TextureAtlas::fillWithEmptyQuadsFromIndex(int index, int amount) +void TextureAtlas::fillWithEmptyQuadsFromIndex(long index, long amount) { CCASSERT(index>=0 && amount>=0, "values must be >= 0"); V3F_C4B_T2F_Quad quad; memset(&quad, 0, sizeof(quad)); - int to = index + amount; - for (int i = index ; i < to ; i++) + long to = index + amount; + for (long i = index ; i < to ; i++) { _quads[i] = quad; } @@ -589,13 +590,13 @@ void TextureAtlas::drawQuads() this->drawNumberOfQuads(_totalQuads, 0); } -void TextureAtlas::drawNumberOfQuads(int numberOfQuads) +void TextureAtlas::drawNumberOfQuads(long numberOfQuads) { CCASSERT(numberOfQuads>=0, "numberOfQuads must be >= 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"); diff --git a/cocos/2d/CCTextureAtlas.h b/cocos/2d/CCTextureAtlas.h index 47a5c1c484..86f0ba209f 100644 --- a/cocos/2d/CCTextureAtlas.h +++ b/cocos/2d/CCTextureAtlas.h @@ -59,13 +59,13 @@ public: /** creates a TextureAtlas with an filename and with an initial capacity for Quads. * 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 * with an initial capacity for n Quads. * The TextureAtlas capacity can be increased in runtime. */ - static TextureAtlas* createWithTexture(Texture2D *texture, int capacity); + static TextureAtlas* createWithTexture(Texture2D *texture, long capacity); /** * @js ctor */ @@ -81,7 +81,7 @@ public: * * 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 * with an initial capacity for Quads. @@ -89,43 +89,43 @@ public: * * 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 * index must be between 0 and the atlas capacity - 1 @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 index must be between 0 and the atlas capacity - 1 @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 index must be between 0 and the atlas capacity - 1 this method doesn't enlarge the array when amount + index > totalQuads @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 This operation is faster than removing and inserting in a quad in 2 different steps @since v0.7.2 */ - void insertQuadFromIndex(int fromIndex, int newIndex); + void insertQuadFromIndex(long fromIndex, long newIndex); /** 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 @since v0.7.2 */ - void removeQuadAtIndex(int index); + void removeQuadAtIndex(long index); /** removes a amount of quads starting from index @since 1.1 */ - void removeQuadsAtIndex(int index, int amount); + void removeQuadsAtIndex(long index, long amount); /** removes all Quads. The TextureAtlas capacity remains untouched. No memory is freed. The total number of quads to be drawn will be 0 @@ -138,19 +138,19 @@ public: * 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. */ - bool resizeCapacity(int capacity); + bool resizeCapacity(long capacity); /** Used internally by ParticleBatchNode don't use this unless you know what you're doing @since 1.1 */ - void increaseTotalQuadsWith(int amount); + void increaseTotalQuadsWith(long amount); /** Moves an amount of quads from oldIndex at newIndex @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 @@ -158,26 +158,26 @@ public: This method doesn't enlarge the array if newIndex + quads to be moved > capacity @since 1.1 */ - void moveQuadsFromIndex(int index, int newIndex); + void moveQuadsFromIndex(long index, long newIndex); /** Ensures that after a realloc quads are still empty Used internally by ParticleBatchNode @since 1.1 */ - void fillWithEmptyQuadsFromIndex(int index, int amount); + void fillWithEmptyQuadsFromIndex(long index, long amount); /** draws n quads * 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). n + start can't be greater than the capacity of the atlas @since v1.0 */ - void drawNumberOfQuads(int numberOfQuads, int start); + void drawNumberOfQuads(long numberOfQuads, long start); /** draws all the Atlas's Quads */ @@ -197,10 +197,10 @@ public: const char* description() const; /** 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 */ - int getCapacity() const; + long getCapacity() const; /** Gets the texture of the texture atlas */ Texture2D* getTexture() const; @@ -226,9 +226,9 @@ protected: GLuint _buffersVBO[2]; //0: vertex 1: indices 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 */ - int _totalQuads; + long _totalQuads; /** quantity of quads that can be stored with the current texture atlas size */ - int _capacity; + long _capacity; /** Texture of the texture atlas */ Texture2D* _texture; /** Quads that are going to be rendered */ diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index 95c02f8ff4..e4c9a0c8aa 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -51,19 +51,9 @@ NS_CC_BEGIN // implementation TextureCache -TextureCache* TextureCache::_sharedTextureCache = nullptr; - TextureCache * TextureCache::getInstance() { - if (!_sharedTextureCache) - { -#ifdef EMSCRIPTEN - _sharedTextureCache = new TextureCacheEmscripten(); -#else - _sharedTextureCache = new TextureCache(); -#endif // EMSCRIPTEN - } - return _sharedTextureCache; + return Director::getInstance()->getTextureCache(); } TextureCache::TextureCache() @@ -73,7 +63,6 @@ TextureCache::TextureCache() , _needQuit(false) , _asyncRefCount(0) { - CCASSERT(_sharedTextureCache == nullptr, "Attempted to allocate a second instance of a singleton."); } TextureCache::~TextureCache() @@ -84,20 +73,19 @@ TextureCache::~TextureCache() (it->second)->release(); CC_SAFE_DELETE(_loadingThread); - _sharedTextureCache = nullptr; } void TextureCache::destroyInstance() { - if (_sharedTextureCache) - { - // notify sub thread to quick - _sharedTextureCache->_needQuit = true; - _sharedTextureCache->_sleepCondition.notify_one(); - if (_sharedTextureCache->_loadingThread) _sharedTextureCache->_loadingThread->join(); - - CC_SAFE_RELEASE_NULL(_sharedTextureCache); - } +} + +TextureCache * TextureCache::sharedTextureCache() +{ + return Director::getInstance()->getTextureCache(); +} + +void TextureCache::purgeSharedTextureCache() +{ } const char* TextureCache::description() const @@ -260,7 +248,7 @@ void TextureCache::addImageAsyncCallBack(float dt) #if CC_ENABLE_CACHE_TEXTURE_DATA // cache the texture file name - VolatileTexture::addImageTexture(texture, filename); + VolatileTextureMgr::addImageTexture(texture, filename); #endif // cache the texture. retain it, since it is added in the map _textures.insert( std::make_pair(filename, texture) ); @@ -320,7 +308,7 @@ Texture2D * TextureCache::addImage(const std::string &path) { #if CC_ENABLE_CACHE_TEXTURE_DATA // cache the texture file name - VolatileTexture::addImageTexture(texture, fullpath.c_str()); + VolatileTextureMgr::addImageTexture(texture, fullpath.c_str()); #endif // texture already retained, no need to re-retain it _textures.insert( std::make_pair(fullpath, texture) ); @@ -370,7 +358,7 @@ Texture2D* TextureCache::addImage(Image *image, const std::string &key) } while (0); #if CC_ENABLE_CACHE_TEXTURE_DATA - VolatileTexture::addImage(texture, image); + VolatileTextureMgr::addImage(texture, image); #endif return texture; @@ -438,9 +426,18 @@ Texture2D* TextureCache::getTextureForKey(const std::string &key) const void TextureCache::reloadAllTextures() { -#if CC_ENABLE_CACHE_TEXTURE_DATA - VolatileTexture::reloadAllTextures(); -#endif +//will do nothing +// #if CC_ENABLE_CACHE_TEXTURE_DATA +// VolatileTextureMgr::reloadAllTextures(); +// #endif +} + +void TextureCache::waitForQuit() +{ + // notify sub thread to quick + _needQuit = true; + _sleepCondition.notify_one(); + if (_loadingThread) _loadingThread->join(); } void TextureCache::dumpCachedTextureInfo() const @@ -453,7 +450,7 @@ void TextureCache::dumpCachedTextureInfo() const Texture2D* tex = it->second; unsigned int bpp = tex->getBitsPerPixelForFormat(); // 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; count++; 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 -std::list VolatileTexture::_textures; -bool VolatileTexture::_isReloading = false; +std::list VolatileTextureMgr::_textures; +bool VolatileTextureMgr::_isReloading = false; VolatileTexture::VolatileTexture(Texture2D *t) : _texture(t) @@ -487,16 +484,14 @@ VolatileTexture::VolatileTexture(Texture2D *t) _texParams.magFilter = GL_LINEAR; _texParams.wrapS = GL_CLAMP_TO_EDGE; _texParams.wrapT = GL_CLAMP_TO_EDGE; - _textures.push_back(this); } VolatileTexture::~VolatileTexture() { - _textures.remove(this); CC_SAFE_RELEASE(_uiImage); } -void VolatileTexture::addImageTexture(Texture2D *tt, const char* imageFileName) +void VolatileTextureMgr::addImageTexture(Texture2D *tt, const char* imageFileName) { if (_isReloading) { @@ -505,20 +500,20 @@ void VolatileTexture::addImageTexture(Texture2D *tt, const char* imageFileName) VolatileTexture *vt = findVolotileTexture(tt); - vt->_cashedImageType = kImageFile; + vt->_cashedImageType = VolatileTexture::kImageFile; vt->_fileName = imageFileName; vt->_pixelFormat = tt->getPixelFormat(); } -void VolatileTexture::addImage(Texture2D *tt, Image *image) +void VolatileTextureMgr::addImage(Texture2D *tt, Image *image) { VolatileTexture *vt = findVolotileTexture(tt); image->retain(); vt->_uiImage = image; - vt->_cashedImageType = kImage; + vt->_cashedImageType = VolatileTexture::kImage; } -VolatileTexture* VolatileTexture::findVolotileTexture(Texture2D *tt) +VolatileTexture* VolatileTextureMgr::findVolotileTexture(Texture2D *tt) { VolatileTexture *vt = 0; auto i = _textures.begin(); @@ -535,12 +530,13 @@ VolatileTexture* VolatileTexture::findVolotileTexture(Texture2D *tt) if (! vt) { vt = new VolatileTexture(tt); + _textures.push_back(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) { @@ -549,14 +545,14 @@ void VolatileTexture::addDataTexture(Texture2D *tt, void* data, int dataLen, Tex VolatileTexture *vt = findVolotileTexture(tt); - vt->_cashedImageType = kImageData; + vt->_cashedImageType = VolatileTexture::kImageData; vt->_textureData = data; vt->_dataLen = dataLen; vt->_pixelFormat = pixelFormat; 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) { @@ -565,12 +561,12 @@ void VolatileTexture::addStringTexture(Texture2D *tt, const char* text, const Fo VolatileTexture *vt = findVolotileTexture(tt); - vt->_cashedImageType = kString; + vt->_cashedImageType = VolatileTexture::kString; vt->_text = text; 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); @@ -584,7 +580,7 @@ void VolatileTexture::setTexParameters(Texture2D *t, const Texture2D::TexParams vt->_texParams.wrapT = texParams.wrapT; } -void VolatileTexture::removeTexture(Texture2D *t) +void VolatileTextureMgr::removeTexture(Texture2D *t) { auto i = _textures.begin(); while (i != _textures.end()) @@ -592,13 +588,14 @@ void VolatileTexture::removeTexture(Texture2D *t) VolatileTexture *vt = *i++; if (vt->_texture == t) { + _textures.remove(vt); delete vt; break; } } } -void VolatileTexture::reloadAllTextures() +void VolatileTextureMgr::reloadAllTextures() { _isReloading = true; @@ -611,13 +608,13 @@ void VolatileTexture::reloadAllTextures() switch (vt->_cashedImageType) { - case kImageFile: + case VolatileTexture::kImageFile: { Image* image = new Image(); - unsigned long nSize = 0; - unsigned char* pBuffer = FileUtils::getInstance()->getFileData(vt->_fileName.c_str(), "rb", &nSize); + long size = 0; + 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::setDefaultAlphaPixelFormat(vt->_pixelFormat); @@ -629,7 +626,7 @@ void VolatileTexture::reloadAllTextures() CC_SAFE_RELEASE(image); } break; - case kImageData: + case VolatileTexture::kImageData: { vt->_texture->initWithData(vt->_textureData, vt->_dataLen, @@ -639,12 +636,12 @@ void VolatileTexture::reloadAllTextures() vt->_textureSize); } break; - case kString: + case VolatileTexture::kString: { vt->_texture->initWithString(vt->_text.c_str(), vt->_fontDefinition); } break; - case kImage: + case VolatileTexture::kImage: { vt->_texture->initWithImage(vt->_uiImage); } diff --git a/cocos/2d/CCTextureCache.h b/cocos/2d/CCTextureCache.h index ec87d891d8..eb6ca47a22 100644 --- a/cocos/2d/CCTextureCache.h +++ b/cocos/2d/CCTextureCache.h @@ -50,6 +50,10 @@ NS_CC_BEGIN * @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 * Once the texture is loaded, the next time it will return @@ -59,23 +63,24 @@ class CC_DLL TextureCache : public Object { public: /** Returns the shared instance of the cache */ - static TextureCache * getInstance(); + CC_DEPRECATED_ATTRIBUTE static TextureCache * getInstance(); /** @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. @since v0.99.0 */ - static void destroyInstance(); + CC_DEPRECATED_ATTRIBUTE static void destroyInstance(); /** @deprecated Use destroyInstance() instead */ - CC_DEPRECATED_ATTRIBUTE static void purgeSharedTextureCache() { return TextureCache::destroyInstance(); } + CC_DEPRECATED_ATTRIBUTE static void purgeSharedTextureCache(); /** 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: /** @@ -158,6 +163,10 @@ public: */ void dumpCachedTextureInfo() const; + //wait for texture cahe to quit befor destroy instance + //called by director, please do not called outside + void waitForQuit(); + private: void addImageAsyncCallBack(float dt); void loadImage(); @@ -196,8 +205,6 @@ protected: int _asyncRefCount; std::unordered_map _textures; - - static TextureCache *_sharedTextureCache; }; #if CC_ENABLE_CACHE_TEXTURE_DATA @@ -212,7 +219,7 @@ class VolatileTexture kImage, }ccCachedImageType; -public: +private: VolatileTexture(Texture2D *t); /** * @js NA @@ -220,25 +227,8 @@ public: */ ~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 _textures; - static bool _isReloading; - -private: - // find VolatileTexture by Texture2D* - // if not found, create a new one - static VolatileTexture* findVolotileTexture(Texture2D *tt); - protected: + friend class VolatileTextureMgr; Texture2D *_texture; Image *_uiImage; @@ -257,6 +247,26 @@ protected: 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 _textures; + static bool _isReloading; +private: + // find VolatileTexture by Texture2D* + // if not found, create a new one + static VolatileTexture* findVolotileTexture(Texture2D *tt); +}; + #endif // end of textures group diff --git a/cocos/2d/CCUserDefault.cpp b/cocos/2d/CCUserDefault.cpp index ab30c805a0..2104051f76 100644 --- a/cocos/2d/CCUserDefault.cpp +++ b/cocos/2d/CCUserDefault.cpp @@ -58,7 +58,7 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLEle tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument(); *doc = xmlDoc; //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*)data.getBuffer(); if(NULL == pXmlBuffer) @@ -66,7 +66,7 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLEle CCLOG("can not read xml file"); break; } - xmlDoc->Parse(pXmlBuffer); + xmlDoc->Parse(pXmlBuffer, nSize); delete[] pXmlBuffer; // get root node *rootNode = xmlDoc->RootElement(); diff --git a/cocos/2d/CCUserDefault.mm b/cocos/2d/CCUserDefault.mm index b55acfcf24..da1c8827fd 100644 --- a/cocos/2d/CCUserDefault.mm +++ b/cocos/2d/CCUserDefault.mm @@ -73,8 +73,8 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLDoc { tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument(); *doc = xmlDoc; - unsigned long nSize; - const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &nSize); + long size; + const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &size); //const char* pXmlBuffer = (const char*)data.getBuffer(); if(NULL == pXmlBuffer) { diff --git a/cocos/2d/CCUserDefaultAndroid.cpp b/cocos/2d/CCUserDefaultAndroid.cpp index 38c09c2a90..db18dd2951 100644 --- a/cocos/2d/CCUserDefaultAndroid.cpp +++ b/cocos/2d/CCUserDefaultAndroid.cpp @@ -74,8 +74,8 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLDoc { tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument(); *doc = xmlDoc; - unsigned long nSize; - const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &nSize); + long size; + const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &size); //const char* pXmlBuffer = (const char*)data.getBuffer(); if(NULL == pXmlBuffer) { diff --git a/cocos/2d/CMakeLists.txt b/cocos/2d/CMakeLists.txt new file mode 100644 index 0000000000..9446d95364 --- /dev/null +++ b/cocos/2d/CMakeLists.txt @@ -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" +) + diff --git a/cocos/2d/Makefile b/cocos/2d/Makefile deleted file mode 100644 index 6b89961f42..0000000000 --- a/cocos/2d/Makefile +++ /dev/null @@ -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 $@ - - diff --git a/cocos/2d/TGAlib.cpp b/cocos/2d/TGAlib.cpp index ba4ca83b01..8725e765cb 100644 --- a/cocos/2d/TGAlib.cpp +++ b/cocos/2d/TGAlib.cpp @@ -198,8 +198,8 @@ tImageTGA * tgaLoad(const char *filename) int mode,total; tImageTGA *info = NULL; - unsigned long nSize = 0; - unsigned char* pBuffer = FileUtils::getInstance()->getFileData(filename, "rb", &nSize); + long size = 0; + unsigned char* pBuffer = FileUtils::getInstance()->getFileData(filename, "rb", &size); do { @@ -207,7 +207,7 @@ tImageTGA * tgaLoad(const char *filename) info = (tImageTGA *)malloc(sizeof(tImageTGA)); // get the file header info - if (! tgaLoadHeader(pBuffer, nSize, info)) + if (! tgaLoadHeader(pBuffer, size, info)) { info->status = TGA_ERROR_MEMORY; break; @@ -245,11 +245,11 @@ tImageTGA * tgaLoad(const char *filename) // finally load the image pixels if ( info->type == 10 ) { - bLoadImage = tgaLoadRLEImageData(pBuffer, nSize, info); + bLoadImage = tgaLoadRLEImageData(pBuffer, size, info); } else { - bLoadImage = tgaLoadImageData(pBuffer, nSize, info); + bLoadImage = tgaLoadImageData(pBuffer, size, info); } // check for errors when reading the pixels diff --git a/cocos/2d/ZipUtils.cpp b/cocos/2d/ZipUtils.cpp index db2fab18ce..2e5d9fe43f 100644 --- a/cocos/2d/ZipUtils.cpp +++ b/cocos/2d/ZipUtils.cpp @@ -39,7 +39,7 @@ bool ZipUtils::s_bEncryptionKeyIsValid = false; // --------------------- 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 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; 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 ? #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 */ int err = Z_OK; - int bufferSize = outLenghtHint; + long bufferSize = outLenghtHint; *out = new unsigned char[bufferSize]; z_stream d_stream; /* decompression stream */ @@ -192,9 +192,9 @@ int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, 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); if (err != Z_OK || *out == NULL) { @@ -223,7 +223,7 @@ int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, 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 return ccInflateMemoryWithHint(in, inLength, out, 256 * 1024); @@ -304,7 +304,7 @@ bool ZipUtils::ccIsCCZFile(const char *path) // load file into memory unsigned char* compressed = NULL; - unsigned long fileLen = 0; + long fileLen = 0; compressed = FileUtils::getInstance()->getFileData(path, "rb", &fileLen); if(NULL == compressed || 0 == fileLen) @@ -316,7 +316,7 @@ bool ZipUtils::ccIsCCZFile(const char *path) 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)) { @@ -333,7 +333,7 @@ bool ZipUtils::ccIsGZipFile(const char *path) // load file into memory unsigned char* compressed = NULL; - unsigned long fileLen = 0; + long fileLen = 0; compressed = FileUtils::getInstance()->getFileData(path, "rb", &fileLen); if(NULL == compressed || 0 == fileLen) @@ -345,7 +345,7 @@ bool ZipUtils::ccIsGZipFile(const char *path) 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) { @@ -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; @@ -454,7 +454,7 @@ int ZipUtils::ccInflateCCZFile(const char *path, unsigned char **out) // load file into memory unsigned char* compressed = NULL; - unsigned long fileLen = 0; + long fileLen = 0; compressed = FileUtils::getInstance()->getFileData(path, "rb", &fileLen); if(NULL == compressed || 0 == fileLen) @@ -582,7 +582,7 @@ bool ZipFile::fileExists(const std::string &fileName) const 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; if (pSize) diff --git a/cocos/2d/ZipUtils.h b/cocos/2d/ZipUtils.h index 5564807540..48552502b4 100644 --- a/cocos/2d/ZipUtils.h +++ b/cocos/2d/ZipUtils.h @@ -64,7 +64,7 @@ namespace cocos2d * @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 @@ -76,7 +76,7 @@ namespace cocos2d * @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 * @@ -100,7 +100,7 @@ namespace cocos2d * * @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 * @@ -116,7 +116,7 @@ namespace cocos2d * * @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 * @@ -132,7 +132,7 @@ namespace cocos2d * * @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 * security. @@ -187,10 +187,10 @@ namespace cocos2d static void ccSetPvrEncryptionKey(unsigned int keyPart1, unsigned int keyPart2, unsigned int keyPart3, unsigned int keyPart4); private: - static int ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int *outLength, - unsigned int outLenghtHint); - static inline void ccDecodeEncodedPvr (unsigned int *data, int len); - static inline unsigned int ccChecksumPvr(const unsigned int *data, int len); + static int ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long *outLength, + long outLenghtHint); + static inline void ccDecodeEncodedPvr (unsigned int *data, long len); + static inline unsigned int ccChecksumPvr(const unsigned int *data, long len); static unsigned int s_uEncryptedPvrKeyParts[4]; static unsigned int s_uEncryptionKey[1024]; @@ -253,7 +253,7 @@ namespace cocos2d * * @since v2.0.5 */ - unsigned char *getFileData(const std::string &fileName, unsigned long *pSize); + unsigned char *getFileData(const std::string &fileName, long *size); private: /** Internal data like zip file pointer / file list array and so on */ diff --git a/cocos/2d/ccCArray.cpp b/cocos/2d/ccCArray.cpp index cd8f275311..f280bc5787 100644 --- a/cocos/2d/ccCArray.cpp +++ b/cocos/2d/ccCArray.cpp @@ -28,10 +28,10 @@ THE SOFTWARE. NS_CC_BEGIN -const int CC_INVALID_INDEX = -1; +const long CC_INVALID_INDEX = -1; /** Allocates and initializes a new array with specified capacity */ -ccArray* ccArrayNew(int capacity) +ccArray* ccArrayNew(long capacity) { if (capacity == 0) capacity = 7; @@ -68,7 +68,7 @@ void ccArrayDoubleCapacity(ccArray *arr) arr->arr = newArr; } -void ccArrayEnsureExtraCapacity(ccArray *arr, int extra) +void ccArrayEnsureExtraCapacity(ccArray *arr, long extra) { while (arr->max < arr->num + extra) { @@ -82,7 +82,7 @@ void ccArrayEnsureExtraCapacity(ccArray *arr, int extra) void ccArrayShrink(ccArray *arr) { - int newSize = 0; + long newSize = 0; //only resize when necessary 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. */ -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; - for(int i = 0; i < arrNum; ++i, ++ptr) + for(long i = 0; i < arrNum; ++i, ++ptr) { if( *ptr == object ) return i; @@ -143,7 +143,7 @@ void ccArrayAppendObjectWithResize(ccArray *arr, Object* object) enough capacity. */ 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]); } @@ -157,14 +157,14 @@ void ccArrayAppendArrayWithResize(ccArray *arr, ccArray *plusArr) } /** 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(object != NULL, "Invalid parameter!"); ccArrayEnsureExtraCapacity(arr, 1); - int remaining = arr->num - index; + long remaining = arr->num - index; if( remaining > 0) { 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 */ -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(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. 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"); if (bReleaseObj) @@ -208,7 +208,7 @@ void ccArrayRemoveObjectAtIndex(ccArray *arr, int index, bool bReleaseObj/* = tr arr->num--; - int remaining = arr->num - index; + long remaining = arr->num - index; if(remaining>0) { 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, thereby avoiding the need to push back subsequent objects. 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]); - int last = --arr->num; + long last = --arr->num; arr->arr[index] = arr->arr[last]; } void ccArrayFastRemoveObject(ccArray *arr, Object* object) { - int index = ccArrayGetIndexOfObject(arr, object); + long index = ccArrayGetIndexOfObject(arr, object); if (index != CC_INVALID_INDEX) { ccArrayFastRemoveObjectAtIndex(arr, index); @@ -238,7 +238,7 @@ void ccArrayFastRemoveObject(ccArray *arr, Object* object) found the function has no effect. */ void ccArrayRemoveObject(ccArray *arr, Object* object, bool bReleaseObj/* = true*/) { - int index = ccArrayGetIndexOfObject(arr, object); + long index = ccArrayGetIndexOfObject(arr, object); if (index != CC_INVALID_INDEX) { 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. */ 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]); } @@ -259,8 +259,8 @@ void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr) matching instances in arr will be removed. */ void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr) { - int back = 0; - int i = 0; + long back = 0; + long i = 0; for( i = 0; i < arr->num; i++) { @@ -282,7 +282,7 @@ void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr) // #pragma mark ccCArray for Values (c structures) /** Allocates and initializes a new C array with specified capacity */ -ccCArray* ccCArrayNew(int capacity) +ccCArray* ccCArrayNew(long capacity) { if (capacity == 0) { @@ -317,15 +317,15 @@ void ccCArrayDoubleCapacity(ccCArray *arr) } /** Increases array capacity such that max >= num + extra. */ -void ccCArrayEnsureExtraCapacity(ccCArray *arr, int extra) +void ccCArrayEnsureExtraCapacity(ccCArray *arr, long extra) { ccArrayEnsureExtraCapacity((ccArray*)arr,extra); } /** 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 ) 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 */ -void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, int index) +void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, long index) { CCASSERT( index < arr->max, "ccCArrayInsertValueAtIndex: invalid index"); - int remaining = arr->num - index; + long remaining = arr->num - index; // make sure it has enough capacity if (arr->num + 1 == arr->max) { @@ -385,7 +385,7 @@ void ccCArrayAppendValueWithResize(ccCArray *arr, void* value) enough capacity. */ 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]); } @@ -408,9 +408,9 @@ void ccCArrayRemoveAllValues(ccCArray *arr) Behavior undefined if index outside [0, num-1]. @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]; } @@ -421,9 +421,9 @@ void ccCArrayRemoveValueAtIndex(ccCArray *arr, int index) Behavior undefined if index outside [0, num-1]. @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]; } @@ -432,7 +432,7 @@ void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, int index) */ void ccCArrayRemoveValue(ccCArray *arr, void* value) { - int index = ccCArrayGetIndexOfValue(arr, value); + long index = ccCArrayGetIndexOfValue(arr, value); if (index != CC_INVALID_INDEX) { ccCArrayRemoveValueAtIndex(arr, index); @@ -444,7 +444,7 @@ void ccCArrayRemoveValue(ccCArray *arr, void* value) */ 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]); } @@ -455,9 +455,9 @@ void ccCArrayRemoveArray(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]) ) { diff --git a/cocos/2d/ccCArray.h b/cocos/2d/ccCArray.h index fff5152904..2bfff6224f 100644 --- a/cocos/2d/ccCArray.h +++ b/cocos/2d/ccCArray.h @@ -51,20 +51,20 @@ THE SOFTWARE. NS_CC_BEGIN -extern const int CC_INVALID_INDEX; +extern const long CC_INVALID_INDEX; // Easy integration #define CCARRAYDATA_FOREACH(__array__, __object__) \ -__object__=__array__->arr[0]; for(int i=0, num=__array__->num; iarr[i]) \ +__object__=__array__->arr[0]; for(long i=0, num=__array__->num; iarr[i]) \ typedef struct _ccArray { - int num, max; + long num, max; Object** arr; } ccArray; /** 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. */ void ccArrayFree(ccArray*& arr); @@ -73,13 +73,13 @@ void ccArrayFree(ccArray*& arr); void ccArrayDoubleCapacity(ccArray *arr); /** 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 */ void ccArrayShrink(ccArray *arr); /** 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. */ bool ccArrayContainsObject(ccArray *arr, Object* object); @@ -98,22 +98,22 @@ void ccArrayAppendArray(ccArray *arr, ccArray *plusArr); void ccArrayAppendArrayWithResize(ccArray *arr, ccArray *plusArr); /** Inserts an object at index */ -void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, int index); +void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, long index); /** Swaps two objects */ -void ccArraySwapObjectsAtIndexes(ccArray *arr, int index1, int index2); +void ccArraySwapObjectsAtIndexes(ccArray *arr, long index1, long index2); /** Removes all objects from arr */ void ccArrayRemoveAllObjects(ccArray *arr); /** Removes object at specified index and pushes back all subsequent objects. 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, thereby avoiding the need to push back subsequent objects. 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); @@ -133,12 +133,12 @@ void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr); // #pragma mark ccCArray for Values (c structures) typedef struct _ccCArray { - int num, max; + long num, max; void** arr; } ccCArray; /** 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. */ void ccCArrayFree(ccCArray *arr); @@ -147,16 +147,16 @@ void ccCArrayFree(ccCArray *arr); void ccCArrayDoubleCapacity(ccCArray *arr); /** 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. */ -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. */ bool ccCArrayContainsValue(ccCArray *arr, void* value); /** 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. */ void ccCArrayAppendValue(ccCArray *arr, void* value); @@ -178,14 +178,14 @@ void ccCArrayRemoveAllValues(ccCArray *arr); Behavior undefined if index outside [0, num-1]. @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, thereby avoiding the need to push back subsequent values. Behavior undefined if index outside [0, num-1]. @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. @since v0.99.4 diff --git a/cocos/2d/cocos2d.vcxproj b/cocos/2d/cocos2d.vcxproj index a59611bc90..5180e1a6f9 100644 --- a/cocos/2d/cocos2d.vcxproj +++ b/cocos/2d/cocos2d.vcxproj @@ -192,21 +192,21 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - - - - - + + + + + - - - - - + + + + + @@ -361,24 +361,24 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - - - - - - + + + + + + - - - - - - + + + + + + diff --git a/cocos/2d/cocos2d.vcxproj.filters b/cocos/2d/cocos2d.vcxproj.filters index 493e1dc747..9055db96e4 100644 --- a/cocos/2d/cocos2d.vcxproj.filters +++ b/cocos/2d/cocos2d.vcxproj.filters @@ -129,36 +129,6 @@ physics - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - base_nodes @@ -578,6 +548,36 @@ event_dispatcher + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + @@ -598,42 +598,6 @@ physics - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - base_nodes @@ -1164,5 +1128,41 @@ event_dispatcher + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + - \ No newline at end of file + diff --git a/cocos/2d/platform/CCEGLViewProtocol.cpp b/cocos/2d/platform/CCEGLViewProtocol.cpp index 9646f5948f..ebeba6b203 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.cpp +++ b/cocos/2d/platform/CCEGLViewProtocol.cpp @@ -12,7 +12,7 @@ namespace { static Touch* g_touches[EventTouch::MAX_TOUCHES] = { NULL }; static unsigned int g_indexBitsUsed = 0; // System touch pointer ID (It may not be ascending order number) <-> Ascending order number from 0 - static std::map g_touchIdReorderMap; + static std::map g_touchIdReorderMap; static int getUnUsedIndex() { @@ -201,9 +201,9 @@ const char* EGLViewProtocol::getViewName() return _viewName; } -void EGLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesBegin(int num, long ids[], float xs[], float ys[]) { - int id = 0; + long id = 0; float x = 0.0f; float y = 0.0f; int nUnusedIndex = 0; @@ -251,9 +251,9 @@ void EGLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float y dispatcher->dispatchEvent(&touchEvent); } -void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesMove(int num, long ids[], float xs[], float ys[]) { - int id = 0; + long id = 0; float x = 0.0f; float y = 0.0f; EventTouch touchEvent; @@ -283,7 +283,7 @@ void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys else { // It is error, should return. - CCLOG("Moving touches with id: %d error", id); + CCLOG("Moving touches with id: %ld error", id); return; } } @@ -299,9 +299,9 @@ void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys dispatcher->dispatchEvent(&touchEvent); } -void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, long ids[], float xs[], float ys[]) { - int id = 0; + long id = 0; float x = 0.0f; float y = 0.0f; EventTouch touchEvent; @@ -336,7 +336,7 @@ void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode } else { - CCLOG("Ending touches with id: %d error", id); + CCLOG("Ending touches with id: %ld error", id); return; } @@ -359,12 +359,12 @@ void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode } } -void EGLViewProtocol::handleTouchesEnd(int num, int ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesEnd(int num, long ids[], float xs[], float ys[]) { handleTouchesOfEndOrCancel(EventTouch::EventCode::ENDED, num, ids, xs, ys); } -void EGLViewProtocol::handleTouchesCancel(int num, int ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesCancel(int num, long ids[], float xs[], float ys[]) { handleTouchesOfEndOrCancel(EventTouch::EventCode::CANCELLED, num, ids, xs, ys); } diff --git a/cocos/2d/platform/CCEGLViewProtocol.h b/cocos/2d/platform/CCEGLViewProtocol.h index b8744d0dd1..ed54d59712 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.h +++ b/cocos/2d/platform/CCEGLViewProtocol.h @@ -136,10 +136,10 @@ public: const char* getViewName(); /** Touch events are handled by default; if you want to customize your handlers, please override these functions: */ - virtual void handleTouchesBegin(int num, int ids[], float xs[], float ys[]); - virtual void handleTouchesMove(int num, int ids[], float xs[], float ys[]); - virtual void handleTouchesEnd(int num, int ids[], float xs[], float ys[]); - virtual void handleTouchesCancel(int num, int ids[], float xs[], float ys[]); + virtual void handleTouchesBegin(int num, long ids[], float xs[], float ys[]); + virtual void handleTouchesMove(int num, long ids[], float xs[], float ys[]); + virtual void handleTouchesEnd(int num, long ids[], float xs[], float ys[]); + virtual void handleTouchesCancel(int num, long ids[], float xs[], float ys[]); /** * Get the opengl view port rectangle. @@ -156,7 +156,7 @@ public: */ float getScaleY() const; private: - void handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]); + void handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, long ids[], float xs[], float ys[]); protected: EGLTouchDelegate* _delegate; diff --git a/cocos/2d/platform/CCFileUtils.cpp b/cocos/2d/platform/CCFileUtils.cpp index e9e01589e2..6760432cad 100644 --- a/cocos/2d/platform/CCFileUtils.cpp +++ b/cocos/2d/platform/CCFileUtils.cpp @@ -451,7 +451,7 @@ NS_CC_BEGIN /* The subclass FileUtilsApple should override these two method. */ Dictionary* FileUtils::createDictionaryWithContentsOfFile(const std::string& filename) {return NULL;} -bool FileUtils::writeToFile(cocos2d::Dictionary *dict, const std::string &fullPath) {return NULL;} +bool FileUtils::writeToFile(cocos2d::Dictionary *dict, const std::string &fullPath) {return false;} Array* FileUtils::createArrayWithContentsOfFile(const std::string& filename) {return NULL;} #endif /* (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) && (CC_TARGET_PLATFORM != CC_PLATFORM_MAC) */ @@ -488,7 +488,7 @@ void FileUtils::purgeCachedEntries() _fullPathCache.clear(); } -unsigned char* FileUtils::getFileData(const char* filename, const char* mode, unsigned long * size) +unsigned char* FileUtils::getFileData(const char* filename, const char* mode, long *size) { unsigned char * buffer = NULL; CCASSERT(filename != NULL && size != NULL && mode != NULL, "Invalid parameters."); @@ -518,7 +518,7 @@ unsigned char* FileUtils::getFileData(const char* filename, const char* mode, un return buffer; } -unsigned char* FileUtils::getFileDataFromZip(const char* zipFilePath, const char* filename, unsigned long * size) +unsigned char* FileUtils::getFileDataFromZip(const char* zipFilePath, const char* filename, long *size) { unsigned char * buffer = NULL; unzFile pFile = NULL; diff --git a/cocos/2d/platform/CCFileUtils.h b/cocos/2d/platform/CCFileUtils.h index 299807af01..855f016fe5 100644 --- a/cocos/2d/platform/CCFileUtils.h +++ b/cocos/2d/platform/CCFileUtils.h @@ -88,7 +88,7 @@ public: * @return Upon success, a pointer to the data is returned, otherwise NULL. * @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned. */ - virtual unsigned char* getFileData(const char* filename, const char* mode, unsigned long * size); + virtual unsigned char* getFileData(const char* filename, const char* mode, long *size); /** * Gets resource file data from a zip file. @@ -98,7 +98,7 @@ public: * @return Upon success, a pointer to the data is returned, otherwise NULL. * @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned. */ - virtual unsigned char* getFileDataFromZip(const char* zipFilePath, const char* filename, unsigned long *size); + virtual unsigned char* getFileDataFromZip(const char* zipFilePath, const char* filename, long *size); /** Returns the fullpath for a given filename. diff --git a/cocos/2d/platform/CCImage.h b/cocos/2d/platform/CCImage.h index 25f09dade2..1f2e04ced7 100644 --- a/cocos/2d/platform/CCImage.h +++ b/cocos/2d/platform/CCImage.h @@ -119,10 +119,10 @@ public: * @js NA * @lua NA */ - bool initWithImageData(const unsigned char * data, int dataLen); + bool initWithImageData(const unsigned char * data, long dataLen); // @warning kFmtRawData only support RGBA8888 - bool initWithRawData(const unsigned char * data, int dataLen, int width, int height, int bitsPerComponent, bool preMulti = false); + bool initWithRawData(const unsigned char * data, long dataLen, long width, long height, long bitsPerComponent, bool preMulti = false); /** @brief Create image with specified string. diff --git a/cocos/2d/platform/CCImageCommon_cpp.h b/cocos/2d/platform/CCImageCommon_cpp.h index be7480a0ae..f2fc7a9a08 100644 --- a/cocos/2d/platform/CCImageCommon_cpp.h +++ b/cocos/2d/platform/CCImageCommon_cpp.h @@ -416,7 +416,7 @@ bool Image::initWithImageFile(const char * strPath) SDL_FreeSurface(iSurf); #else - unsigned long bufferLen = 0; + long bufferLen = 0; unsigned char* buffer = FileUtils::getInstance()->getFileData(fullPath.c_str(), "rb", &bufferLen); if (buffer != nullptr && bufferLen > 0) @@ -432,23 +432,23 @@ bool Image::initWithImageFile(const char * strPath) bool Image::initWithImageFileThreadSafe(const char *fullpath) { - bool bRet = false; - unsigned long dataLen = 0; + bool ret = false; + long dataLen = 0; #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) FileUtilsAndroid *fileUitls = (FileUtilsAndroid*)FileUtils::getInstance(); - unsigned char *pBuffer = fileUitls->getFileDataForAsync(fullpath, "rb", &dataLen); + unsigned char *buffer = fileUitls->getFileDataForAsync(fullpath, "rb", &dataLen); #else - unsigned char *pBuffer = FileUtils::getInstance()->getFileData(fullpath, "rb", &dataLen); + unsigned char *buffer = FileUtils::getInstance()->getFileData(fullpath, "rb", &dataLen); #endif - if (pBuffer != NULL && dataLen > 0) + if (buffer != NULL && dataLen > 0) { - bRet = initWithImageData(pBuffer, dataLen); + ret = initWithImageData(buffer, dataLen); } - CC_SAFE_DELETE_ARRAY(pBuffer); - return bRet; + CC_SAFE_DELETE_ARRAY(buffer); + return ret; } -bool Image::initWithImageData(const unsigned char * data, int dataLen) +bool Image::initWithImageData(const unsigned char * data, long dataLen) { bool ret = false; @@ -1190,13 +1190,13 @@ bool Image::initWithPVRv2Data(const unsigned char * data, int dataLen) if (!testFormatForPvr2TCSupport(formatFlags)) { - CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", formatFlags); + CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags); return false; } if (v2_pixel_formathash.find(formatFlags) == v2_pixel_formathash.end()) { - CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", formatFlags); + CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags); return false; } @@ -1204,7 +1204,7 @@ bool Image::initWithPVRv2Data(const unsigned char * data, int dataLen) if (it == Texture2D::getPixelFormatInfoMap().end()) { - CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", formatFlags); + CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags); return false; } @@ -1757,7 +1757,7 @@ bool Image::initWithWebpData(const unsigned char * data, int dataLen) return bRet; } -bool Image::initWithRawData(const unsigned char * data, int dataLen, int width, int height, int bitsPerComponent, bool preMulti) +bool Image::initWithRawData(const unsigned char * data, long dataLen, long width, long height, long bitsPerComponent, bool preMulti) { bool bRet = false; do diff --git a/cocos/2d/platform/CCSAXParser.cpp b/cocos/2d/platform/CCSAXParser.cpp index 0f823f938d..04201557c1 100644 --- a/cocos/2d/platform/CCSAXParser.cpp +++ b/cocos/2d/platform/CCSAXParser.cpp @@ -114,15 +114,15 @@ bool SAXParser::parse(const char* pXMLData, unsigned int uDataLength) bool SAXParser::parse(const char *pszFile) { - bool bRet = false; - unsigned long size = 0; + bool ret = false; + long size = 0; char* pBuffer = (char*)FileUtils::getInstance()->getFileData(pszFile, "rt", &size); if (pBuffer != NULL && size > 0) { - bRet = parse(pBuffer, size); + ret = parse(pBuffer, size); } CC_SAFE_DELETE_ARRAY(pBuffer); - return bRet; + return ret; } void SAXParser::startElement(void *ctx, const CC_XML_CHAR *name, const CC_XML_CHAR **atts) diff --git a/cocos/2d/platform/android/CCApplication.cpp b/cocos/2d/platform/android/CCApplication.cpp index 61b3f288cd..07c5814b3e 100644 --- a/cocos/2d/platform/android/CCApplication.cpp +++ b/cocos/2d/platform/android/CCApplication.cpp @@ -128,4 +128,8 @@ Application::Platform Application::getTargetPlatform() return Platform::OS_ANDROID; } +void Application::applicationScreenSizeChanged(int newWidth, int newHeight) { + +} + NS_CC_END diff --git a/cocos/2d/platform/android/CCApplication.h b/cocos/2d/platform/android/CCApplication.h index e321266c81..d9b7d00f34 100644 --- a/cocos/2d/platform/android/CCApplication.h +++ b/cocos/2d/platform/android/CCApplication.h @@ -50,6 +50,13 @@ public: */ virtual Platform getTargetPlatform(); + /** + @brief This function will be called when the application screen size is changed. + @param new width + @param new height + */ + virtual void applicationScreenSizeChanged(int newWidth, int newHeight); + protected: static Application * sm_pSharedApplication; }; diff --git a/cocos/2d/platform/android/CCFileUtilsAndroid.cpp b/cocos/2d/platform/android/CCFileUtilsAndroid.cpp index d15e4f874a..c447b5db32 100644 --- a/cocos/2d/platform/android/CCFileUtilsAndroid.cpp +++ b/cocos/2d/platform/android/CCFileUtilsAndroid.cpp @@ -130,21 +130,21 @@ bool FileUtilsAndroid::isAbsolutePath(const std::string& strPath) const } -unsigned char* FileUtilsAndroid::getFileData(const char* filename, const char* pszMode, unsigned long * pSize) +unsigned char* FileUtilsAndroid::getFileData(const char* filename, const char* mode, long * size) { - return doGetFileData(filename, pszMode, pSize, false); + return doGetFileData(filename, mode, size, false); } -unsigned char* FileUtilsAndroid::getFileDataForAsync(const char* filename, const char* pszMode, unsigned long * pSize) +unsigned char* FileUtilsAndroid::getFileDataForAsync(const char* filename, const char* pszMode, long * pSize) { return doGetFileData(filename, pszMode, pSize, true); } -unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char* pszMode, unsigned long * pSize, bool forAsync) +unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char* mode, long * size, bool forAsync) { - unsigned char * pData = 0; + unsigned char * data = 0; - if ((! filename) || (! pszMode) || 0 == strlen(filename)) + if ((! filename) || (! mode) || 0 == strlen(filename)) { return 0; } @@ -189,14 +189,14 @@ unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char* return NULL; } - off_t size = AAsset_getLength(asset); + off_t fileSize = AAsset_getLength(asset); - pData = new unsigned char[size]; + data = new unsigned char[fileSize]; - int bytesread = AAsset_read(asset, (void*)pData, size); - if (pSize) + int bytesread = AAsset_read(asset, (void*)data, fileSize); + if (size) { - *pSize = bytesread; + *size = bytesread; } AAsset_close(asset); @@ -207,32 +207,32 @@ unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char* { // read rrom other path than user set it //CCLOG("GETTING FILE ABSOLUTE DATA: %s", filename); - FILE *fp = fopen(fullPath.c_str(), pszMode); + FILE *fp = fopen(fullPath.c_str(), mode); CC_BREAK_IF(!fp); - unsigned long size; + long fileSize; fseek(fp,0,SEEK_END); - size = ftell(fp); + fileSize = ftell(fp); fseek(fp,0,SEEK_SET); - pData = new unsigned char[size]; - size = fread(pData,sizeof(unsigned char), size,fp); + data = new unsigned char[fileSize]; + fileSize = fread(data,sizeof(unsigned char), fileSize,fp); fclose(fp); - if (pSize) + if (size) { - *pSize = size; + *size = fileSize; } } while (0); } - if (! pData) + if (! data) { std::string msg = "Get data from file("; msg.append(filename).append(") failed!"); CCLOG("%s", msg.c_str()); } - return pData; + return data; } string FileUtilsAndroid::getWritablePath() const diff --git a/cocos/2d/platform/android/CCFileUtilsAndroid.h b/cocos/2d/platform/android/CCFileUtilsAndroid.h index 87a2445f48..3bee6d2e39 100644 --- a/cocos/2d/platform/android/CCFileUtilsAndroid.h +++ b/cocos/2d/platform/android/CCFileUtilsAndroid.h @@ -55,7 +55,7 @@ public: /* override funtions */ bool init(); - virtual unsigned char* getFileData(const char* filename, const char* pszMode, unsigned long * pSize); + virtual unsigned char* getFileData(const char* filename, const char* mode, long * size); virtual std::string getWritablePath() const; virtual bool isFileExist(const std::string& strFilePath) const; @@ -64,10 +64,10 @@ public: /** This function is android specific. It is used for TextureCache::addImageAsync(). Don't use it in your codes. */ - unsigned char* getFileDataForAsync(const char* filename, const char* pszMode, unsigned long * pSize); + unsigned char* getFileDataForAsync(const char* filename, const char* mode, long * size); private: - unsigned char* doGetFileData(const char* filename, const char* pszMode, unsigned long * pSize, bool forAsync); + unsigned char* doGetFileData(const char* filename, const char* mode, long * size, bool forAsync); static AAssetManager* assetmanager; }; diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java old mode 100755 new mode 100644 diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java old mode 100755 new mode 100644 diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java old mode 100755 new mode 100644 diff --git a/cocos/2d/platform/android/nativeactivity.cpp b/cocos/2d/platform/android/nativeactivity.cpp index 5ac17a5ee5..e92d9e5b78 100644 --- a/cocos/2d/platform/android/nativeactivity.cpp +++ b/cocos/2d/platform/android/nativeactivity.cpp @@ -12,6 +12,7 @@ #include #include +#include #include "CCDirector.h" #include "CCApplication.h" @@ -69,6 +70,9 @@ struct engine { struct saved_state state; }; +static bool isContentRectChanged = false; +static std::chrono::steady_clock::time_point timeRectChanged; + static struct engine engine; static char* editboxText = NULL; @@ -127,7 +131,7 @@ static void cocos_init(cocos_dimensions d, struct android_app* app) { cocos2d::GL::invalidateStateCache(); cocos2d::ShaderCache::getInstance()->reloadDefaultShaders(); cocos2d::DrawPrimitives::init(); - cocos2d::TextureCache::reloadAllTextures(); + cocos2d::VolatileTextureMgr::reloadAllTextures(); cocos2d::NotificationCenter::getInstance()->postNotification(EVNET_COME_TO_FOREGROUND, NULL); cocos2d::Director::getInstance()->setGLDefaultValues(); } @@ -292,7 +296,7 @@ static void engine_term_display(struct engine* engine) { /* * Get X, Y positions and ID's for all pointers */ -static void getTouchPos(AInputEvent *event, int ids[], float xs[], float ys[]) { +static void getTouchPos(AInputEvent *event, long ids[], float xs[], float ys[]) { int pointerCount = AMotionEvent_getPointerCount(event); for(int i = 0; i < pointerCount; ++i) { ids[i] = AMotionEvent_getPointerId(event, i); @@ -321,7 +325,7 @@ static int32_t handle_touch_input(AInputEvent *event) { LOG_EVENTS_DEBUG("Event: Action DOWN x=%f y=%f pointerID=%d\n", xP, yP, pointerId); - int pId = pointerId; + long pId = pointerId; float x = xP; float y = yP; @@ -340,7 +344,7 @@ static int32_t handle_touch_input(AInputEvent *event) { LOG_EVENTS_DEBUG("Event: Action POINTER DOWN x=%f y=%f pointerID=%d\n", xP, yP, pointerId); - int pId = pointerId; + long pId = pointerId; float x = xP; float y = yP; @@ -353,10 +357,10 @@ static int32_t handle_touch_input(AInputEvent *event) { { LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_MOVE"); int pointerCount = AMotionEvent_getPointerCount(event); - int ids[pointerCount]; + long ids[pointerCount]; float xs[pointerCount], ys[pointerCount]; getTouchPos(event, ids, xs, ys); - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(pointerCount, ids, xs, ys); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(pointerCount, ids, xs, ys); return 1; } break; @@ -369,7 +373,7 @@ static int32_t handle_touch_input(AInputEvent *event) { float yP = AMotionEvent_getY(event,0); LOG_EVENTS_DEBUG("Event: Action UP x=%f y=%f pointerID=%d\n", xP, yP, pointerId); - int pId = pointerId; + long pId = pointerId; float x = xP; float y = yP; @@ -387,7 +391,7 @@ static int32_t handle_touch_input(AInputEvent *event) { float yP = AMotionEvent_getY(event,pointerIndex); LOG_EVENTS_DEBUG("Event: Action POINTER UP x=%f y=%f pointerID=%d\n", xP, yP, pointerIndex); - int pId = pointerId; + long pId = pointerId; float x = xP; float y = yP; @@ -400,10 +404,10 @@ static int32_t handle_touch_input(AInputEvent *event) { { LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_CANCEL"); int pointerCount = AMotionEvent_getPointerCount(event); - int ids[pointerCount]; + long ids[pointerCount]; float xs[pointerCount], ys[pointerCount]; getTouchPos(event, ids, xs, ys); - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(pointerCount, ids, xs, ys); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(pointerCount, ids, xs, ys); return 1; } break; @@ -558,6 +562,11 @@ static void engine_handle_cmd(struct android_app* app, int32_t cmd) { } } +static void onContentRectChanged(ANativeActivity* activity, const ARect* rect) { + timeRectChanged = std::chrono::steady_clock::now(); + isContentRectChanged = true; +} + /** * This is the main entry point of a native application that is using * android_native_app_glue. It runs in its own thread, with its own @@ -586,6 +595,9 @@ void android_main(struct android_app* state) { engine.state = *(struct saved_state*)state->savedState; } + // Screen size change support + state->activity->callbacks->onContentRectChanged = onContentRectChanged; + // loop waiting for stuff to do. while (1) { @@ -673,5 +685,20 @@ void android_main(struct android_app* state) { } else { LOG_RENDER_DEBUG("android_main : !engine.animating"); } + + // Check if screen size changed + if (isContentRectChanged) { + std::chrono::duration duration( + std::chrono::duration_cast>(std::chrono::steady_clock::now() - timeRectChanged)); + + // Wait about 30 ms to get new width and height. Without waiting we can get old values sometime + if (duration.count() > 30) { + isContentRectChanged = false; + + int32_t newWidth = ANativeWindow_getWidth(engine.app->window); + int32_t newHeight = ANativeWindow_getHeight(engine.app->window); + cocos2d::Application::getInstance()->applicationScreenSizeChanged(newWidth, newHeight); + } + } } } diff --git a/cocos/2d/platform/ios/CCApplication.h b/cocos/2d/platform/ios/CCApplication.h index 86be67bd29..a281a4f554 100644 --- a/cocos/2d/platform/ios/CCApplication.h +++ b/cocos/2d/platform/ios/CCApplication.h @@ -76,6 +76,13 @@ public: */ virtual Platform getTargetPlatform(); + /** + @brief This function will be called when the application screen size is changed. + @param new width + @param new height + */ + virtual void applicationScreenSizeChanged(int newWidth, int newHeight); + protected: static Application * sm_pSharedApplication; }; diff --git a/cocos/2d/platform/ios/CCApplication.mm b/cocos/2d/platform/ios/CCApplication.mm index 8c8d543c2e..c09a0aa8a9 100644 --- a/cocos/2d/platform/ios/CCApplication.mm +++ b/cocos/2d/platform/ios/CCApplication.mm @@ -146,4 +146,8 @@ Application::Platform Application::getTargetPlatform() } } +void Application::applicationScreenSizeChanged(int newWidth, int newHeight) { + +} + NS_CC_END diff --git a/cocos/2d/platform/ios/EAGLView.h b/cocos/2d/platform/ios/EAGLView.h old mode 100755 new mode 100644 diff --git a/cocos/2d/platform/ios/EAGLView.mm b/cocos/2d/platform/ios/EAGLView.mm index e577fc14fd..0b86c027d0 100644 --- a/cocos/2d/platform/ios/EAGLView.mm +++ b/cocos/2d/platform/ios/EAGLView.mm @@ -75,7 +75,7 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. #define IOS_MAX_TOUCHES_COUNT 10 -static CCEAGLView *view = 0; +static CCEAGLView *__view = 0; @interface CCEAGLView (Private) - (BOOL) setupSurfaceWithSharegroup:(EAGLSharegroup*)sharegroup; @@ -117,7 +117,7 @@ static CCEAGLView *view = 0; + (id) sharedEGLView { - return view; + return __view; } - (id) initWithFrame:(CGRect)frame @@ -147,14 +147,14 @@ static CCEAGLView *view = 0; } - view = self; + __view = self; originalRect_ = self.frame; self.keyboardShowNotification = nil; - if ([view respondsToSelector:@selector(setContentScaleFactor:)]) + if ([__view respondsToSelector:@selector(setContentScaleFactor:)]) { - view.contentScaleFactor = [[UIScreen mainScreen] scale]; + __view.contentScaleFactor = [[UIScreen mainScreen] scale]; } } @@ -180,7 +180,7 @@ static CCEAGLView *view = 0; } } - view = self; + __view = self; return self; } @@ -205,13 +205,13 @@ static CCEAGLView *view = 0; -(int) getWidth { CGSize bound = [self bounds].size; - return bound.width * self.contentScaleFactor; + return (int)bound.width * self.contentScaleFactor; } -(int) getHeight { CGSize bound = [self bounds].size; - return bound.height * self.contentScaleFactor; + return (int)bound.height * self.contentScaleFactor; } @@ -402,18 +402,18 @@ static CCEAGLView *view = 0; return; } - int ids[IOS_MAX_TOUCHES_COUNT] = {0}; + UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0}; float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; int i = 0; for (UITouch *touch in touches) { - ids[i] = (int)touch; - xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;; - ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;; + ids[i] = touch; + xs[i] = [touch locationInView: [touch view]].x * __view.contentScaleFactor;; + ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesBegin(i, ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesBegin(i, (long*)ids, xs, ys); } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event @@ -422,18 +422,18 @@ static CCEAGLView *view = 0; { return; } - int ids[IOS_MAX_TOUCHES_COUNT] = {0}; + UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0}; float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; int i = 0; for (UITouch *touch in touches) { - ids[i] = (int)touch; - xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;; - ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;; + ids[i] = touch; + xs[i] = [touch locationInView: [touch view]].x * __view.contentScaleFactor;; + ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesMove(i, ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesMove(i, (long*)ids, xs, ys); } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event @@ -443,18 +443,18 @@ static CCEAGLView *view = 0; return; } - int ids[IOS_MAX_TOUCHES_COUNT] = {0}; + UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0}; float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; int i = 0; for (UITouch *touch in touches) { - ids[i] = (int)touch; - xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;; - ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;; + ids[i] = touch; + xs[i] = [touch locationInView: [touch view]].x * __view.contentScaleFactor;; + ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesEnd(i, ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesEnd(i, (long*)ids, xs, ys); } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event @@ -464,18 +464,18 @@ static CCEAGLView *view = 0; return; } - int ids[IOS_MAX_TOUCHES_COUNT] = {0}; + UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0}; float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; int i = 0; for (UITouch *touch in touches) { - ids[i] = (int)touch; - xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;; - ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;; + ids[i] = touch; + xs[i] = [touch locationInView: [touch view]].x * __view.contentScaleFactor;; + ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesCancel(i, ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesCancel(i, (long*)ids, xs, ys); } #pragma mark - diff --git a/cocos/2d/platform/ios/OpenGL_Internal.h b/cocos/2d/platform/ios/OpenGL_Internal.h old mode 100755 new mode 100644 diff --git a/cocos/2d/platform/linux/CCEGLView.cpp b/cocos/2d/platform/linux/CCEGLView.cpp index 33b8796959..a136ba54b3 100644 --- a/cocos/2d/platform/linux/CCEGLView.cpp +++ b/cocos/2d/platform/linux/CCEGLView.cpp @@ -186,7 +186,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = true; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesBegin(1, &id, &s_mouseX, &s_mouseY); } } @@ -195,7 +195,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = false; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesEnd(1, &id, &s_mouseX, &s_mouseY); } } @@ -231,7 +231,7 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, { if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,eglView->getFrameSize().height - s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY); } } diff --git a/cocos/2d/platform/linux/CCFileUtilsLinux.cpp b/cocos/2d/platform/linux/CCFileUtilsLinux.cpp index 227c59b0ba..dc3fb5b513 100644 --- a/cocos/2d/platform/linux/CCFileUtilsLinux.cpp +++ b/cocos/2d/platform/linux/CCFileUtilsLinux.cpp @@ -49,7 +49,7 @@ bool FileUtilsLinux::init() fullpath[length] = '\0'; std::string appPath = fullpath; _defaultResRootPath = appPath.substr(0, appPath.find_last_of("/")); - _defaultResRootPath += "/../../../Resources/"; + _defaultResRootPath += "/Resources/"; // Set writable path to $XDG_CONFIG_HOME or ~/.config// if $XDG_CONFIG_HOME not exists. const char* xdg_config_path = getenv("XDG_CONFIG_HOME"); diff --git a/cocos/2d/platform/mac/CCEGLView.mm b/cocos/2d/platform/mac/CCEGLView.mm index af3863476d..d66f1dc17c 100644 --- a/cocos/2d/platform/mac/CCEGLView.mm +++ b/cocos/2d/platform/mac/CCEGLView.mm @@ -202,7 +202,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = true; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesBegin(1, &id, &s_mouseX, &s_mouseY); } } @@ -211,7 +211,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = false; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesEnd(1, &id, &s_mouseX, &s_mouseY); } } @@ -249,7 +249,7 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, { if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,eglView->getFrameSize().height - s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY); } } diff --git a/cocos/2d/platform/mac/EAGLView.h b/cocos/2d/platform/mac/EAGLView.h old mode 100755 new mode 100644 diff --git a/cocos/2d/platform/mac/EAGLView.mm b/cocos/2d/platform/mac/EAGLView.mm index ff456d0e6a..1894440ced 100644 --- a/cocos/2d/platform/mac/EAGLView.mm +++ b/cocos/2d/platform/mac/EAGLView.mm @@ -327,7 +327,7 @@ static CCEAGLView *view; float x = local_point.x; float y = [self getHeight] - local_point.y; - int ids[1] = {0}; + NSInteger ids[1] = {0}; float xs[1] = {0.0f}; float ys[1] = {0.0f}; @@ -335,7 +335,7 @@ static CCEAGLView *view; xs[0] = x / frameZoomFactor_; ys[0] = y / frameZoomFactor_; - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, ids, xs, ys); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, (long*)ids, xs, ys); } - (void)mouseMoved:(NSEvent *)theEvent @@ -351,7 +351,7 @@ static CCEAGLView *view; float x = local_point.x; float y = [self getHeight] - local_point.y; - int ids[1] = {0}; + NSInteger ids[1] = {0}; float xs[1] = {0.0f}; float ys[1] = {0.0f}; @@ -359,7 +359,7 @@ static CCEAGLView *view; xs[0] = x / frameZoomFactor_; ys[0] = y / frameZoomFactor_; - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(1, ids, xs, ys); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(1, (long*)ids, xs, ys); } - (void)mouseUp:(NSEvent *)theEvent @@ -370,7 +370,7 @@ static CCEAGLView *view; float x = local_point.x; float y = [self getHeight] - local_point.y; - int ids[1] = {0}; + NSInteger ids[1] = {0}; float xs[1] = {0.0f}; float ys[1] = {0.0f}; @@ -378,7 +378,7 @@ static CCEAGLView *view; xs[0] = x / frameZoomFactor_; ys[0] = y / frameZoomFactor_; - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, ids, xs, ys); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, (long*)ids, xs, ys); } - (void)rightMouseDown:(NSEvent *)theEvent { diff --git a/cocos/2d/platform/win32/CCEGLView.cpp b/cocos/2d/platform/win32/CCEGLView.cpp index 6b19ec5bb5..3a18b81917 100644 --- a/cocos/2d/platform/win32/CCEGLView.cpp +++ b/cocos/2d/platform/win32/CCEGLView.cpp @@ -303,7 +303,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = true; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesBegin(1, &id, &s_mouseX, &s_mouseY); } } @@ -312,7 +312,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = false; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesEnd(1, &id, &s_mouseX, &s_mouseY); } } @@ -348,7 +348,7 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, { if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,eglView->getFrameSize().height - s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY); } } diff --git a/cocos/2d/platform/win32/CCFileUtilsWin32.cpp b/cocos/2d/platform/win32/CCFileUtilsWin32.cpp index a5c94dac90..216797bd9e 100644 --- a/cocos/2d/platform/win32/CCFileUtilsWin32.cpp +++ b/cocos/2d/platform/win32/CCFileUtilsWin32.cpp @@ -121,7 +121,7 @@ bool FileUtilsWin32::isAbsolutePath(const std::string& strPath) const return false; } -unsigned char* FileUtilsWin32::getFileData(const char* filename, const char* mode, unsigned long* size) +unsigned char* FileUtilsWin32::getFileData(const char* filename, const char* mode, long* size) { unsigned char * pBuffer = NULL; CCASSERT(filename != NULL && size != NULL && mode != NULL, "Invalid parameters."); diff --git a/cocos/2d/platform/win32/CCFileUtilsWin32.h b/cocos/2d/platform/win32/CCFileUtilsWin32.h index 4f01adabeb..5c88d97cf9 100644 --- a/cocos/2d/platform/win32/CCFileUtilsWin32.h +++ b/cocos/2d/platform/win32/CCFileUtilsWin32.h @@ -58,7 +58,7 @@ protected: * @return Upon success, a pointer to the data is returned, otherwise NULL. * @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned. */ - virtual unsigned char* getFileData(const char* filename, const char* mode, unsigned long * size) override; + virtual unsigned char* getFileData(const char* filename, const char* mode, long * size) override; /** * Gets full path for filename, resolution directory and search path. diff --git a/cocos/audio/CMakeLists.txt b/cocos/audio/CMakeLists.txt new file mode 100644 index 0000000000..2f1d642cb2 --- /dev/null +++ b/cocos/audio/CMakeLists.txt @@ -0,0 +1,36 @@ +set(AUDIO_SRC + linux/SimpleAudioEngineFMOD.cpp + linux/FmodAudioPlayer.cpp +) + +# architecture +if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) +set(ARCH_DIR "64-bit") +else() +set(ARCH_DIR "32-bit") +endif() + +include_directories( + ../../external/linux-specific/fmod/include/${ARCH_DIR} +) + +add_library(audio STATIC + ${AUDIO_SRC} +) + +if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) +set(FMOD_LIB "fmodex64") +else() +set(FMOD_LIB "fmodex") +endif() + +target_link_libraries(audio + ${FMOD_LIB} +) + +set_target_properties(audio + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/cocos/audio/mac/CDXMacOSXSupport.h b/cocos/audio/mac/CDXMacOSXSupport.h old mode 100755 new mode 100644 diff --git a/cocos/audio/mac/CDXMacOSXSupport.mm b/cocos/audio/mac/CDXMacOSXSupport.mm old mode 100755 new mode 100644 diff --git a/cocos/audio/proj.linux/.cproject b/cocos/audio/proj.linux/.cproject deleted file mode 100755 index fc010e1ed7..0000000000 --- a/cocos/audio/proj.linux/.cproject +++ /dev/null @@ -1,378 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cocos/audio/proj.linux/.project b/cocos/audio/proj.linux/.project deleted file mode 100755 index 2860d8d849..0000000000 --- a/cocos/audio/proj.linux/.project +++ /dev/null @@ -1,100 +0,0 @@ - - - libCocosDenshion - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - clean,full,incremental, - - - ?name? - - - - org.eclipse.cdt.make.core.append_environment - true - - - org.eclipse.cdt.make.core.autoBuildTarget - all - - - org.eclipse.cdt.make.core.buildArguments - - - - org.eclipse.cdt.make.core.buildCommand - make - - - org.eclipse.cdt.make.core.buildLocation - ${workspace_loc:/CocosDenshion/Debug} - - - org.eclipse.cdt.make.core.cleanBuildTarget - clean - - - org.eclipse.cdt.make.core.contents - org.eclipse.cdt.make.core.activeConfigSettings - - - org.eclipse.cdt.make.core.enableAutoBuild - false - - - org.eclipse.cdt.make.core.enableCleanBuild - true - - - org.eclipse.cdt.make.core.enableFullBuild - true - - - org.eclipse.cdt.make.core.fullBuildTarget - all - - - org.eclipse.cdt.make.core.stopOnError - true - - - org.eclipse.cdt.make.core.useDefaultBuildCmd - true - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - include - 2 - PARENT-1-PROJECT_LOC/include - - - linux - 2 - PARENT-1-PROJECT_LOC/linux - - - third_party - 2 - PARENT-1-PROJECT_LOC/third_party - - - diff --git a/cocos/audio/proj.linux/CocosDenshion.prf b/cocos/audio/proj.linux/CocosDenshion.prf deleted file mode 100644 index 4c7ec10f0c..0000000000 --- a/cocos/audio/proj.linux/CocosDenshion.prf +++ /dev/null @@ -1,20 +0,0 @@ -################################################################################ -# Do not include this file in your project: see cocos2dx.pri. -################################################################################ - -linux { - # We will compile extensions on demand using Makefile. - build_CocosDension.name = Build extension static library - build_CocosDension.input = $$PWD/Makefile - build_CocosDension.output = $$CC_LIBRARY_DIR/libcocosdenshion.so - build_CocosDension.target = $$CC_LIBRARY_DIR/libcocosdenshion.so - build_CocosDension.CONFIG = no_link target_predeps - build_CocosDension.commands = cd $$PWD && make $$CC_MAKE_FLAGS - - QMAKE_EXTRA_COMPILERS += build_CocosDension - QMAKE_EXTRA_TARGETS += build_CocosDension - - PRE_TARGETDEPS += $$CC_LIBRARY_DIR/libcocosdenshion.so - LIBS += -lcocosdenshion -} - diff --git a/cocos/audio/proj.linux/Makefile b/cocos/audio/proj.linux/Makefile deleted file mode 100644 index e8b18e3972..0000000000 --- a/cocos/audio/proj.linux/Makefile +++ /dev/null @@ -1,49 +0,0 @@ -TARGET = libcocosdenshion.so - -INCLUDES = -I.. -I../include - -##Using OpenAL -ifeq ($(OPENAL),1) -SOURCES = ../openal/OpenALDecoder.cpp \ - ../openal/SimpleAudioEngineOpenAL.cpp -SHAREDLIBS += -lopenal -lalut - -ifeq ($(OPENAL_MP3),1) -DEFINES += -DENABLE_MPG123 -SHAREDLIBS += -lmpg123 -endif - -ifneq ($(NOVORBIS),1) -SHAREDLIBS += -logg -lvorbis -lvorbisfile -else -DEFINES += -DDISABLE_VORBIS -endif - -##Using FMOD -else -SOURCES = \ - ../linux/SimpleAudioEngineFMOD.cpp \ - ../linux/FmodAudioPlayer.cpp - -ifeq ($(LBITS),64) -INCLUDES += -I../third-party/fmod/lib64/api/inc -else -INCLUDES += -I../third-party/fmod/api/inc -endif - -endif - -COCOS_ROOT = ../../.. -include $(COCOS_ROOT)/cocos/2d/cocos2dx.mk - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_LINK)$(CXX) $(CXXFLAGS) $(OBJECTS) -shared -o $(TARGET) $(SHAREDLIBS) $(STATICLIBS) - -$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) $(VISIBILITY) -c $< -o $@ diff --git a/cocos/audio/third-party/fmod/Makefile b/cocos/audio/third-party/fmod/Makefile deleted file mode 100644 index ef3df253c6..0000000000 --- a/cocos/audio/third-party/fmod/Makefile +++ /dev/null @@ -1,81 +0,0 @@ -LBITS := $(shell getconf LONG_BIT) -ifeq ($(LBITS),64) -FMODEX = libfmodex64 -FMODEXL = libfmodexL64 -VERSION = 4.38.00 -LIBDIR = lib64/api/lib -HDRDIR = lib64/api/inc -else -FMODEX = libfmodex -FMODEXL = libfmodexL -VERSION = 4.36.01 -LIBDIR = api/lib -HDRDIR = api/inc -endif - -DESTLIBDIR = /usr/local/lib -DESTHDRDIR = /usr/local/include/fmodex - -all: - @echo "Possible targets:" - @echo "'make fmod_examples' - Build all examples" - @echo "'make install' - Install FMOD Ex libraries and headers" - @echo "'make uninstall' - Uninstall FMOD Ex libraries and headers" - -fmod_examples: - cd examples/3d && make - cd examples/cdplayer && make - cd examples/channelgroups && make - cd examples/dsp_effectperspeaker && make - cd examples/dsp_custom && make - cd examples/effects && make - cd examples/filecallbacks && make - cd examples/generatetone && make - cd examples/loadfrommemory && make - cd examples/multiplesoundcard && make - cd examples/multispeakeroutput && make - cd examples/netstream && make - cd examples/offlinedecoding && make - cd examples/pitchdetection && make - cd examples/playlist && make - cd examples/playsound && make - cd examples/playstream && make - cd examples/plugin_dev/codec_raw && make - cd examples/plugin_dev/dsp_gain && make - cd examples/readtags && make - cd examples/realtimestitching && make - cd examples/recording && make - cd examples/recordtodisk && make - cd examples/ripnetstream && make - cd examples/submixing && make - cd examples/useplugins && make - cd examples/usercreatedsound && make - cd fmoddesignerapi/examples/effects && make - cd fmoddesignerapi/examples/info_only && make - cd fmoddesignerapi/examples/load_data && make - cd fmoddesignerapi/examples/max_playbacks && make - cd fmoddesignerapi/examples/parameters && make - cd fmoddesignerapi/examples/programmer_selected && make - cd fmoddesignerapi/examples/programmer_sound && make - cd fmoddesignerapi/examples/simple_event && make - -install: - @echo "Installing FMOD Ex libraries and headers..." - cp -f ${LIBDIR}/${FMODEX}-${VERSION}.so ${DESTLIBDIR} - cp -f ${LIBDIR}/${FMODEXL}-${VERSION}.so ${DESTLIBDIR} - ln -s -f ${DESTLIBDIR}/${FMODEX}-${VERSION}.so ${DESTLIBDIR}/${FMODEX}.so - ln -s -f ${DESTLIBDIR}/${FMODEXL}-${VERSION}.so ${DESTLIBDIR}/${FMODEXL}.so - ldconfig -n ${DESTLIBDIR} - mkdir -p ${DESTHDRDIR} - cp -f ${HDRDIR}/*.h* ${DESTHDRDIR} - @echo "done." - -uninstall: - @echo "Uninstalling FMOD Ex libraries..." - rm -f ${DESTLIBDIR}/${FMODEX}.so - rm -f ${DESTLIBDIR}/${FMODEXL}.so - rm -f ${DESTLIBDIR}/${FMODEX}-${VERSION}.so - rm -f ${DESTLIBDIR}/${FMODEXL}-${VERSION}.so - ldconfig -n ${DESTLIBDIR} - rm -rf ${DESTHDRDIR} - @echo "done." diff --git a/cocos/audio/third-party/fmod/lib64/Makefile b/cocos/audio/third-party/fmod/lib64/Makefile deleted file mode 100644 index c461587728..0000000000 --- a/cocos/audio/third-party/fmod/lib64/Makefile +++ /dev/null @@ -1,65 +0,0 @@ -VERSION = 4.38.00 -LIBDIR = api/lib -HDRDIR = api/inc -DESTLIBDIR = /usr/local/lib -DESTHDRDIR = /usr/local/include/fmodex - -all: - @echo "Possible targets:" - @echo "'make fmod_examples' - Build all examples" - @echo "'make install' - Install FMOD Ex libraries and headers" - @echo "'make uninstall' - Uninstall FMOD Ex libraries and headers" - -fmod_examples: - cd examples/3d && make - cd examples/cdplayer && make - cd examples/channelgroups && make - cd examples/dsp_effectperspeaker && make - cd examples/dsp_custom && make - cd examples/effects && make - cd examples/filecallbacks && make - cd examples/generatetone && make - cd examples/loadfrommemory && make - cd examples/multiplesoundcard && make - cd examples/multispeakeroutput && make - cd examples/netstream && make - cd examples/offlinedecoding && make - cd examples/pitchdetection && make - cd examples/playlist && make - cd examples/playsound && make - cd examples/playstream && make - cd examples/plugin_dev/codec_raw && make - cd examples/plugin_dev/dsp_gain && make - cd examples/readtags && make - cd examples/realtimestitching && make - cd examples/recording && make - cd examples/recordtodisk && make - cd examples/ripnetstream && make - cd examples/submixing && make - cd examples/useplugins && make - cd examples/usercreatedsound && make - cd fmoddesignerapi/examples/effects && make - cd fmoddesignerapi/examples/info_only && make - cd fmoddesignerapi/examples/load_data && make - cd fmoddesignerapi/examples/max_playbacks && make - cd fmoddesignerapi/examples/parameters && make - cd fmoddesignerapi/examples/programmer_selected && make - cd fmoddesignerapi/examples/programmer_sound && make - cd fmoddesignerapi/examples/simple_event && make - -install: - @echo "Installing FMOD Ex libraries and headers..." - cp -f ${LIBDIR}/libfmodex64-${VERSION}.so ${DESTLIBDIR} - cp -f ${LIBDIR}/libfmodexL64-${VERSION}.so ${DESTLIBDIR} - ldconfig -n ${DESTLIBDIR} - mkdir -p ${DESTHDRDIR} - cp -f ${HDRDIR}/*.h* ${DESTHDRDIR} - @echo "done." - -uninstall: - @echo "Uninstalling FMOD Ex libraries..." - rm -f ${DESTLIBDIR}/libfmodex64-${VERSION}.so - rm -f ${DESTLIBDIR}/libfmodexL64-${VERSION}.so - ldconfig -n ${DESTLIBDIR} - rm -rf ${DESTHDRDIR} - @echo "done." diff --git a/cocos/base/CCArray.cpp b/cocos/base/CCArray.cpp index 3a55d6050d..90c88ebe34 100644 --- a/cocos/base/CCArray.cpp +++ b/cocos/base/CCArray.cpp @@ -105,7 +105,7 @@ Array* Array::createWithArray(Array* otherArray) return otherArray->clone(); } -Array* Array::createWithCapacity(int capacity) +Array* Array::createWithCapacity(long capacity) { CCASSERT(capacity>=0, "Invalid capacity"); @@ -182,7 +182,7 @@ bool Array::initWithObjects(Object* object, ...) return ret; } -bool Array::initWithCapacity(int capacity) +bool Array::initWithCapacity(long capacity) { CCASSERT(capacity>=0, "Invalid capacity"); @@ -200,7 +200,7 @@ int Array::getIndexOfObject(Object* object) const { auto it = data.begin(); - for (int i = 0; it != data.end(); ++it, ++i) + for (long i = 0; it != data.end(); ++it, ++i) { if (it->get() == object) { @@ -238,7 +238,7 @@ bool Array::containsObject(Object* object) const bool Array::isEqualToArray(Array* otherArray) { - for (int i = 0; i< this->count(); i++) + for (long i = 0; i< this->count(); i++) { if (!this->getObjectAtIndex(i)->isEqual(otherArray->getObjectAtIndex(i))) { @@ -279,7 +279,7 @@ void Array::removeObject(Object* object, bool releaseObj /* ignored */) data.erase( std::remove( data.begin(), data.end(), object ) ); } -void Array::removeObjectAtIndex(int index, bool releaseObj /* ignored */) +void Array::removeObjectAtIndex(long index, bool releaseObj /* ignored */) { auto obj = data[index]; data.erase( data.begin() + index ); @@ -295,7 +295,7 @@ void Array::removeAllObjects() data.erase(std::begin(data), std::end(data)); } -void Array::fastRemoveObjectAtIndex(int index) +void Array::fastRemoveObjectAtIndex(long index) { removeObjectAtIndex(index); } @@ -315,12 +315,12 @@ void Array::exchangeObject(Object* object1, Object* object2) std::swap( data[idx1], data[idx2] ); } -void Array::exchangeObjectAtIndex(int index1, int index2) +void Array::exchangeObjectAtIndex(long index1, long index2) { std::swap( data[index1], data[index2] ); } -void Array::replaceObjectAtIndex(int index, Object* object, bool releaseObject /* ignored */) +void Array::replaceObjectAtIndex(long index, Object* object, bool releaseObject /* ignored */) { data[index] = object; } @@ -448,7 +448,7 @@ Array* Array::createWithArray(Array* otherArray) return otherArray->clone(); } -Array* Array::createWithCapacity(int capacity) +Array* Array::createWithCapacity(long capacity) { CCASSERT(capacity>=0, "Invalid capacity"); @@ -531,7 +531,7 @@ bool Array::initWithObjects(Object* object, ...) return ret; } -bool Array::initWithCapacity(int capacity) +bool Array::initWithCapacity(long capacity) { CCASSERT(capacity>=0 && !data, "Array cannot be re-initialized"); @@ -555,7 +555,7 @@ bool Array::initWithArray(Array* otherArray) return ret; } -int Array::getIndexOfObject(Object* object) const +long Array::getIndexOfObject(Object* object) const { return ccArrayGetIndexOfObject(data, object); } @@ -574,7 +574,7 @@ Object* Array::getRandomObject() r = 0; } - return data->arr[(int)(data->num * r)]; + return data->arr[(long)(data->num * r)]; } bool Array::containsObject(Object* object) const @@ -584,7 +584,7 @@ bool Array::containsObject(Object* object) const bool Array::isEqualToArray(Array* otherArray) { - for (int i = 0; i< this->count(); i++) + for (long i = 0; i< this->count(); i++) { if (!this->getObjectAtIndex(i)->isEqual(otherArray->getObjectAtIndex(i))) { @@ -606,13 +606,13 @@ void Array::addObjectsFromArray(Array* otherArray) ccArrayAppendArrayWithResize(data, otherArray->data); } -void Array::insertObject(Object* object, int index) +void Array::insertObject(Object* object, long index) { CCASSERT(data, "Array not initialized"); ccArrayInsertObjectAtIndex(data, object, index); } -void Array::setObject(Object* object, int index) +void Array::setObject(Object* object, long index) { CCASSERT(index>=0 && index < count(), "Invalid index"); @@ -635,7 +635,7 @@ void Array::removeObject(Object* object, bool releaseObj/* = true*/) ccArrayRemoveObject(data, object, releaseObj); } -void Array::removeObjectAtIndex(int index, bool releaseObj) +void Array::removeObjectAtIndex(long index, bool releaseObj) { ccArrayRemoveObjectAtIndex(data, index, releaseObj); } @@ -650,7 +650,7 @@ void Array::removeAllObjects() ccArrayRemoveAllObjects(data); } -void Array::fastRemoveObjectAtIndex(int index) +void Array::fastRemoveObjectAtIndex(long index) { ccArrayFastRemoveObjectAtIndex(data, index); } @@ -662,14 +662,14 @@ void Array::fastRemoveObject(Object* object) void Array::exchangeObject(Object* object1, Object* object2) { - int index1 = ccArrayGetIndexOfObject(data, object1); - if (index1 == UINT_MAX) + long index1 = ccArrayGetIndexOfObject(data, object1); + if (index1 == CC_INVALID_INDEX) { return; } - int index2 = ccArrayGetIndexOfObject(data, object2); - if (index2 == UINT_MAX) + long index2 = ccArrayGetIndexOfObject(data, object2); + if (index2 == CC_INVALID_INDEX) { return; } @@ -677,12 +677,12 @@ void Array::exchangeObject(Object* object1, Object* object2) ccArraySwapObjectsAtIndexes(data, index1, index2); } -void Array::exchangeObjectAtIndex(int index1, int index2) +void Array::exchangeObjectAtIndex(long index1, long index2) { ccArraySwapObjectsAtIndexes(data, index1, index2); } -void Array::replaceObjectAtIndex(int index, Object* object, bool releaseObject/* = true*/) +void Array::replaceObjectAtIndex(long index, Object* object, bool releaseObject/* = true*/) { ccArrayInsertObjectAtIndex(data, object, index); ccArrayRemoveObjectAtIndex(data, index+1); @@ -693,10 +693,10 @@ void Array::reverseObjects() if (data->num > 1) { // floorf(), since in the case of an even number, the number of swaps stays the same - int count = (int) floorf(data->num/2.f); - int maxIndex = data->num - 1; + long count = (long) floorf(data->num/2.f); + long maxIndex = data->num - 1; - for (int i = 0; i < count ; i++) + for (long i = 0; i < count ; i++) { ccArraySwapObjectsAtIndexes(data, i, maxIndex); --maxIndex; diff --git a/cocos/base/CCArray.h b/cocos/base/CCArray.h index 7f67569faa..f68ee8b64d 100644 --- a/cocos/base/CCArray.h +++ b/cocos/base/CCArray.h @@ -250,7 +250,7 @@ public: /** Create an array with a default capacity * @js NA */ - static Array* createWithCapacity(int capacity); + static Array* createWithCapacity(long capacity); /** Create an array with from an existing array * @js NA */ @@ -295,7 +295,7 @@ public: * @js NA * @lua NA */ - bool initWithCapacity(int capacity); + bool initWithCapacity(long capacity); /** Initializes an array with an existing array * @js NA * @lua NA @@ -307,7 +307,7 @@ public: /** Returns element count of the array * @js NA */ - int count() const + long count() const { #if CC_USE_ARRAY_VECTOR return data.size(); @@ -318,7 +318,7 @@ public: /** Returns capacity of the array * @js NA */ - int capacity() const + long capacity() const { #if CC_USE_ARRAY_VECTOR return data.capacity(); @@ -330,17 +330,17 @@ public: * @js NA * @lua NA */ - int getIndexOfObject(Object* object) const; + long getIndexOfObject(Object* object) const; /** * @js NA */ - CC_DEPRECATED_ATTRIBUTE int indexOfObject(Object* object) const { return getIndexOfObject(object); } + CC_DEPRECATED_ATTRIBUTE long indexOfObject(Object* object) const { return getIndexOfObject(object); } /** Returns an element with a certain index * @js NA * @lua NA */ - Object* getObjectAtIndex(int index) + Object* getObjectAtIndex(long index) { CCASSERT(index>=0 && index < count(), "index out of range in getObjectAtIndex()"); #if CC_USE_ARRAY_VECTOR @@ -349,7 +349,7 @@ public: return data->arr[index]; #endif } - CC_DEPRECATED_ATTRIBUTE Object* objectAtIndex(int index) { return getObjectAtIndex(index); } + CC_DEPRECATED_ATTRIBUTE Object* objectAtIndex(long index) { return getObjectAtIndex(index); } /** Returns the last element of the array * @js NA */ @@ -401,17 +401,17 @@ public: /** Insert a certain object at a certain index * @js NA */ - void insertObject(Object* object, int index); + void insertObject(Object* object, long index); /** sets a certain object at a certain index * @js NA * @lua NA */ - void setObject(Object* object, int index); + void setObject(Object* object, long index); /** sets a certain object at a certain index without retaining. Use it with caution * @js NA * @lua NA */ - void fastSetObject(Object* object, int index) + void fastSetObject(Object* object, long index) { #if CC_USE_ARRAY_VECTOR setObject(object, index); @@ -424,7 +424,7 @@ public: * @js NA * @lua NA */ - void swap( int indexOne, int indexTwo ) + void swap( long indexOne, long indexTwo ) { CCASSERT(indexOne >=0 && indexOne < count() && indexTwo >= 0 && indexTwo < count(), "Invalid indices"); #if CC_USE_ARRAY_VECTOR @@ -447,7 +447,7 @@ public: /** Remove an element with a certain index * @js NA */ - void removeObjectAtIndex(int index, bool releaseObj = true); + void removeObjectAtIndex(long index, bool releaseObj = true); /** Remove all elements * @js NA */ @@ -463,7 +463,7 @@ public: /** Fast way to remove an element with a certain index * @js NA */ - void fastRemoveObjectAtIndex(int index); + void fastRemoveObjectAtIndex(long index); // Rearranging Content @@ -474,12 +474,12 @@ public: /** Swap two elements with certain indexes * @js NA */ - void exchangeObjectAtIndex(int index1, int index2); + void exchangeObjectAtIndex(long index1, long index2); /** Replace object at index with another object. * @js NA */ - void replaceObjectAtIndex(int index, Object* object, bool releaseObject = true); + void replaceObjectAtIndex(long index, Object* object, bool releaseObject = true); /** Revers the array * @js NA diff --git a/cocos/base/CCGeometry.cpp b/cocos/base/CCGeometry.cpp index 1d5c4896c6..fe5086cba9 100644 --- a/cocos/base/CCGeometry.cpp +++ b/cocos/base/CCGeometry.cpp @@ -96,6 +96,16 @@ bool Point::operator!=(const Point& right) return this->x != right.x || this->y != right.y; } +bool Point::operator==(const Point& right) const +{ + return this->x == right.x && this->y == right.y; +} + +bool Point::operator!=(const Point& right) const +{ + return this->x != right.x || this->y != right.y; +} + Point Point::operator*(float a) const { return Point(this->x * a, this->y * a); @@ -283,7 +293,16 @@ Point Point::getIntersectPoint(const Point& A, const Point& B, const Point& C, c return Point::ZERO; } -const Point Point::ZERO = Point(0, 0); +const Point Point::ZERO = Point(0.0f, 0.0f); +const Point Point::ANCHOR_MIDDLE = Point(0.5f, 0.5f); +const Point Point::ANCHOR_BOTTOM_LEFT = Point(0.0f, 0.0f); +const Point Point::ANCHOR_TOP_LEFT = Point(0.0f, 1.0f); +const Point Point::ANCHOR_BOTTOM_RIGHT = Point(1.0f, 0.0f); +const Point Point::ANCHOR_TOP_RIGHT = Point(1.0f, 1.0f); +const Point Point::ANCHOR_MIDDLE_RIGHT = Point(1.0f, 0.5f); +const Point Point::ANCHOR_MIDDLE_LEFT = Point(0.0f, 0.5f); +const Point Point::ANCHOR_MIDDLE_TOP = Point(0.5f, 1.0f); +const Point Point::ANCHOR_MIDDLE_BOTTOM = Point(0.5f, 0.0f); // implementation of Size diff --git a/cocos/base/CCGeometry.h b/cocos/base/CCGeometry.h index 847557cb35..f1a080fdc5 100644 --- a/cocos/base/CCGeometry.h +++ b/cocos/base/CCGeometry.h @@ -123,6 +123,16 @@ public: * @lua NA */ bool operator!=(const Point& right); + /** + * @js NA + * @lua NA + */ + bool operator==(const Point& right) const; + /** + * @js NA + * @lua NA + */ + bool operator!=(const Point& right) const; /** * @js NA * @lua NA @@ -423,7 +433,26 @@ public: */ static Point getIntersectPoint(const Point& A, const Point& B, const Point& C, const Point& D); + /** equals to Point(0,0) */ static const Point ZERO; + /** equals to Point(0.5, 0.5) */ + static const Point ANCHOR_MIDDLE; + /** equals to Point(0, 0) */ + static const Point ANCHOR_BOTTOM_LEFT; + /** equals to Point(0, 1) */ + static const Point ANCHOR_TOP_LEFT; + /** equals to Point(1, 0) */ + static const Point ANCHOR_BOTTOM_RIGHT; + /** equals to Point(1, 1) */ + static const Point ANCHOR_TOP_RIGHT; + /** equals to Point(1, 0.5) */ + static const Point ANCHOR_MIDDLE_RIGHT; + /** equals to Point(0, 0.5) */ + static const Point ANCHOR_MIDDLE_LEFT; + /** equals to Point(0.5, 1) */ + static const Point ANCHOR_MIDDLE_TOP; + /** equals to Point(0.5, 0) */ + static const Point ANCHOR_MIDDLE_BOTTOM; private: // returns true if segment A-B intersects with segment C-D. S->E is the ovderlap part diff --git a/cocos/base/CCObject.h b/cocos/base/CCObject.h index 3c3e6c5321..dc1a6adfd2 100644 --- a/cocos/base/CCObject.h +++ b/cocos/base/CCObject.h @@ -207,6 +207,7 @@ typedef int (Object::*SEL_Compare)(Object*); #define CC_CALLBACK_0(__selector__,__target__, ...) std::bind(&__selector__,__target__, ##__VA_ARGS__) #define CC_CALLBACK_1(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, ##__VA_ARGS__) #define CC_CALLBACK_2(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, std::placeholders::_2, ##__VA_ARGS__) +#define CC_CALLBACK_3(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3 ##__VA_ARGS__) // end of base_nodes group /// @} diff --git a/cocos/base/CCString.cpp b/cocos/base/CCString.cpp index f9962b1ba4..67193eb52c 100644 --- a/cocos/base/CCString.cpp +++ b/cocos/base/CCString.cpp @@ -216,15 +216,15 @@ bool String::isEqual(const Object* pObject) String* String::create(const std::string& str) { - String* pRet = new String(str); - pRet->autorelease(); - return pRet; + String* ret = new String(str); + ret->autorelease(); + return ret; } -String* String::createWithData(const unsigned char* pData, unsigned long nLen) +String* String::createWithData(const unsigned char* data, unsigned long nLen) { - String* pRet = NULL; - if (pData != NULL) + String* ret = NULL; + if (data != NULL) { char* pStr = (char*)malloc(nLen+1); if (pStr != NULL) @@ -232,36 +232,36 @@ String* String::createWithData(const unsigned char* pData, unsigned long nLen) pStr[nLen] = '\0'; if (nLen > 0) { - memcpy(pStr, pData, nLen); + memcpy(pStr, data, nLen); } - pRet = String::create(pStr); + ret = String::create(pStr); free(pStr); } } - return pRet; + return ret; } String* String::createWithFormat(const char* format, ...) { - String* pRet = String::create(""); + String* ret = String::create(""); va_list ap; va_start(ap, format); - pRet->initWithFormatAndValist(format, ap); + ret->initWithFormatAndValist(format, ap); va_end(ap); - return pRet; + return ret; } String* String::createWithContentsOfFile(const char* filename) { - unsigned long size = 0; - unsigned char* pData = 0; - String* pRet = NULL; - pData = FileUtils::getInstance()->getFileData(filename, "rb", &size); - pRet = String::createWithData(pData, size); - CC_SAFE_DELETE_ARRAY(pData); - return pRet; + long size = 0; + unsigned char* data = 0; + String* ret = NULL; + data = FileUtils::getInstance()->getFileData(filename, "rb", &size); + ret = String::createWithData(data, size); + CC_SAFE_DELETE_ARRAY(data); + return ret; } void String::acceptVisitor(DataVisitor &visitor) diff --git a/cocos/base/CMakeLists.txt b/cocos/base/CMakeLists.txt new file mode 100644 index 0000000000..3d37d21a2f --- /dev/null +++ b/cocos/base/CMakeLists.txt @@ -0,0 +1,27 @@ +set(COCOS_BASE_SRC + CCAffineTransform.cpp + CCAutoreleasePool.cpp + CCGeometry.cpp + CCNS.cpp + CCObject.cpp + CCSet.cpp + CCArray.cpp + CCDictionary.cpp + CCString.cpp + CCDataVisitor.cpp + CCData.cpp + etc1.cpp + s3tc.cpp + atitc.cpp +) + +add_library(cocosbase STATIC + ${COCOS_BASE_SRC} +) + +set_target_properties(cocosbase + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/cocos/base/atitc.cpp b/cocos/base/atitc.cpp index 3a60d6d2f7..e93cb801b2 100644 --- a/cocos/base/atitc.cpp +++ b/cocos/base/atitc.cpp @@ -138,7 +138,7 @@ static void atitc_decode_block(uint8_t **blockData, { for (int x = 0; x < 4; ++x) { - initAlpha = (alpha & 0x0f) << 28; + initAlpha = (static_cast(alpha) & 0x0f) << 28; initAlpha += initAlpha >> 4; decodeBlockData[x] = initAlpha + colors[pixelsIndex & 3]; pixelsIndex >>= 2; diff --git a/cocos/base/s3tc.cpp b/cocos/base/s3tc.cpp index e7869df631..2995849603 100644 --- a/cocos/base/s3tc.cpp +++ b/cocos/base/s3tc.cpp @@ -126,7 +126,7 @@ static void s3tc_decode_block(uint8_t **blockData, { for (int x = 0; x < 4; ++x) { - initAlpha = (alpha & 0x0f) << 28; + initAlpha = (static_cast(alpha) & 0x0f) << 28; initAlpha += initAlpha >> 4; decodeBlockData[x] = initAlpha + colors[pixelsIndex & 3]; pixelsIndex >>= 2; diff --git a/cocos/editor-support/cocosbuilder/CCBReader.cpp b/cocos/editor-support/cocosbuilder/CCBReader.cpp index 938c595f46..2fec8df55a 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.cpp +++ b/cocos/editor-support/cocosbuilder/CCBReader.cpp @@ -244,7 +244,7 @@ Node* CCBReader::readNodeGraphFromFile(const char *pCCBFileName, Object *pOwner, } std::string strPath = FileUtils::getInstance()->fullPathForFilename(strCCBFileName.c_str()); - unsigned long size = 0; + long size = 0; unsigned char * pBytes = FileUtils::getInstance()->getFileData(strPath.c_str(), "rb", &size); Data *data = new Data(pBytes, size); @@ -482,12 +482,12 @@ int CCBReader::readInt(bool pSigned) { if(pSigned) { int s = current % 2; if(s) { - num = (int)(current / 2); + num = static_cast(current / 2); } else { - num = (int)(-current / 2); + num = static_cast(-current / 2); } } else { - num = current - 1; + num = static_cast(current - 1); } this->alignBits(); @@ -833,7 +833,7 @@ CCBKeyframe* CCBReader::readKeyframe(PropertyType type) { spriteFile = _CCBRootPath + spriteFile; - Texture2D *texture = TextureCache::getInstance()->addImage(spriteFile.c_str()); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(spriteFile.c_str()); Rect bounds = Rect(0, 0, texture->getContentSize().width, texture->getContentSize().height); spriteFrame = SpriteFrame::createWithTexture(texture, bounds); diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp index f1aedc7104..7eba8e9340 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp @@ -577,7 +577,7 @@ SpriteFrame * NodeLoader::parsePropTypeSpriteFrame(Node * pNode, Node * pParent, if (spriteSheet.length() == 0) { spriteFile = ccbReader->getCCBRootPath() + spriteFile; - Texture2D * texture = TextureCache::getInstance()->addImage(spriteFile.c_str()); + Texture2D * texture = Director::getInstance()->getTextureCache()->addImage(spriteFile.c_str()); if(texture != NULL) { Rect bounds = Rect(0, 0, texture->getContentSize().width, texture->getContentSize().height); spriteFrame = SpriteFrame::createWithTexture(texture, bounds); @@ -635,7 +635,7 @@ Texture2D * NodeLoader::parsePropTypeTexture(Node * pNode, Node * pParent, CCBRe if (spriteFile.length() > 0) { - return TextureCache::getInstance()->addImage(spriteFile.c_str()); + return Director::getInstance()->getTextureCache()->addImage(spriteFile.c_str()); } else { @@ -918,7 +918,7 @@ Node * NodeLoader::parsePropTypeCCBFile(Node * pNode, Node * pParent, CCBReader // Load sub file std::string path = FileUtils::getInstance()->fullPathForFilename(ccbFileName.c_str()); - unsigned long size = 0; + long size = 0; unsigned char * pBytes = FileUtils::getInstance()->getFileData(path.c_str(), "rb", &size); CCBReader * reader = new CCBReader(pCCBReader); diff --git a/cocos/editor-support/cocosbuilder/CMakeLists.txt b/cocos/editor-support/cocosbuilder/CMakeLists.txt new file mode 100644 index 0000000000..00763e1fb7 --- /dev/null +++ b/cocos/editor-support/cocosbuilder/CMakeLists.txt @@ -0,0 +1,40 @@ +set(CCB_SRC + CCBFileLoader.cpp + CCMenuItemImageLoader.cpp + CCBReader.cpp + CCMenuItemLoader.cpp + CCControlButtonLoader.cpp + CCNodeLoader.cpp + CCControlLoader.cpp + CCNodeLoaderLibrary.cpp + CCLabelBMFontLoader.cpp + CCParticleSystemQuadLoader.cpp + CCLabelTTFLoader.cpp + CCScale9SpriteLoader.cpp + CCLayerColorLoader.cpp + CCScrollViewLoader.cpp + CCLayerGradientLoader.cpp + CCSpriteLoader.cpp + CCLayerLoader.cpp + CCBAnimationManager.cpp + CCBKeyframe.cpp + CCBSequence.cpp + CCBSequenceProperty.cpp + CCBValue.cpp + CCNode+CCBRelativePositioning.cpp +) + +include_directories( + .. +) + +add_library(cocosbuilder STATIC + ${CCB_SRC} +) + +set_target_properties(cocosbuilder + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/cocos/editor-support/cocosbuilder/Makefile b/cocos/editor-support/cocosbuilder/Makefile deleted file mode 100644 index 688c5d49d5..0000000000 --- a/cocos/editor-support/cocosbuilder/Makefile +++ /dev/null @@ -1,44 +0,0 @@ -TARGET = libcocosbuilder.a - -INCLUDES = - -SOURCES = CCBFileLoader.cpp \ -CCMenuItemImageLoader.cpp \ -CCBReader.cpp \ -CCMenuItemLoader.cpp \ -CCControlButtonLoader.cpp \ -CCNodeLoader.cpp \ -CCControlLoader.cpp \ -CCNodeLoaderLibrary.cpp \ -CCLabelBMFontLoader.cpp \ -CCParticleSystemQuadLoader.cpp \ -CCLabelTTFLoader.cpp \ -CCScale9SpriteLoader.cpp \ -CCLayerColorLoader.cpp \ -CCScrollViewLoader.cpp \ -CCLayerGradientLoader.cpp \ -CCSpriteLoader.cpp \ -CCLayerLoader.cpp \ -CCBAnimationManager.cpp \ -CCBKeyframe.cpp \ -CCBSequence.cpp \ -CCBSequenceProperty.cpp \ -CCBValue.cpp \ -CCNode+CCBRelativePositioning.cpp - -include ../../2d/cocos2dx.mk - -CXXFLAGS += -Wno-multichar - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - diff --git a/cocos/editor-support/cocostudio/CCActionNode.cpp b/cocos/editor-support/cocostudio/CCActionNode.cpp index fceca8816c..ed7eae3aed 100644 --- a/cocos/editor-support/cocostudio/CCActionNode.cpp +++ b/cocos/editor-support/cocostudio/CCActionNode.cpp @@ -159,7 +159,7 @@ void ActionNode::initActionNodeFromRoot(Object* root) UIWidget* rootWidget = dynamic_cast(root); if (rootWidget != NULL) { - UIWidget* widget = UIHelper::instance()->seekActionWidgetByActionTag(rootWidget, getActionTag()); + UIWidget* widget = UIHelper::seekActionWidgetByActionTag(rootWidget, getActionTag()); if (widget != NULL) { setObject(widget); @@ -424,7 +424,7 @@ bool ActionNode::updateActionToTimeLine(float fTime) bool bFindFrame = false; ActionFrame* srcFrame = NULL; - ActionFrame* destFrame = NULL; +// ActionFrame* destFrame = NULL; for (int n = 0; n < _frameArrayNum; n++) { diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index 5c3b54e3df..b09922ff70 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -49,7 +49,7 @@ Armature *Armature::create() return armature; } CC_SAFE_DELETE(armature); - return NULL; + return nullptr; } @@ -62,7 +62,7 @@ Armature *Armature::create(const char *name) return armature; } CC_SAFE_DELETE(armature); - return NULL; + return nullptr; } Armature *Armature::create(const char *name, Bone *parentBone) @@ -74,41 +74,43 @@ Armature *Armature::create(const char *name, Bone *parentBone) return armature; } CC_SAFE_DELETE(armature); - return NULL; + return nullptr; } Armature::Armature() - : _armatureData(NULL) - , _batchNode(NULL) - , _atlas(NULL) - , _parentBone(NULL) + : _armatureData(nullptr) + , _batchNode(nullptr) + , _atlas(nullptr) + , _parentBone(nullptr) , _armatureTransformDirty(true) - , _boneDic(NULL) - , _topBoneList(NULL) - , _animation(NULL) + , _boneDic(nullptr) + , _topBoneList(nullptr) + , _animation(nullptr) + , _textureAtlasDic(nullptr) { } Armature::~Armature(void) { - if(NULL != _boneDic) + if(nullptr != _boneDic) { _boneDic->removeAllObjects(); CC_SAFE_DELETE(_boneDic); } - if (NULL != _topBoneList) + if (nullptr != _topBoneList) { _topBoneList->removeAllObjects(); CC_SAFE_DELETE(_topBoneList); } CC_SAFE_DELETE(_animation); + CC_SAFE_RELEASE_NULL(_textureAtlasDic); } bool Armature::init() { - return init(NULL); + return init(nullptr); } @@ -130,12 +132,14 @@ bool Armature::init(const char *name) _topBoneList = new Array(); _topBoneList->init(); + CC_SAFE_DELETE(_textureAtlasDic); + _textureAtlasDic = new Dictionary(); _blendFunc.src = CC_BLEND_SRC; _blendFunc.dst = CC_BLEND_DST; - _name = name == NULL ? "" : name; + _name = name == nullptr ? "" : name; ArmatureDataManager *armatureDataManager = ArmatureDataManager::getInstance(); @@ -155,7 +159,7 @@ bool Armature::init(const char *name) _armatureData = armatureData; - DictElement *_element = NULL; + DictElement *_element = nullptr; Dictionary *boneDataDic = &armatureData->boneDataDic; CCDICT_FOREACH(boneDataDic, _element) { @@ -224,13 +228,13 @@ bool Armature::init(const char *name, Bone *parentBone) Bone *Armature::createBone(const char *boneName) { Bone *existedBone = getBone(boneName); - if(existedBone != NULL) + if(existedBone != nullptr) return existedBone; BoneData *boneData = (BoneData *)_armatureData->getBoneData(boneName); std::string parentName = boneData->parentName; - Bone *bone = NULL; + Bone *bone = nullptr; if( parentName.length() != 0 ) { @@ -253,10 +257,10 @@ Bone *Armature::createBone(const char *boneName) void Armature::addBone(Bone *bone, const char *parentName) { - CCASSERT( bone != NULL, "Argument must be non-nil"); - CCASSERT(_boneDic->objectForKey(bone->getName()) == NULL, "bone already added. It can't be added again"); + CCASSERT( bone != nullptr, "Argument must be non-nil"); + CCASSERT(_boneDic->objectForKey(bone->getName()) == nullptr, "bone already added. It can't be added again"); - if (NULL != parentName) + if (nullptr != parentName) { Bone *boneParent = (Bone *)_boneDic->objectForKey(parentName); if (boneParent) @@ -265,18 +269,12 @@ void Armature::addBone(Bone *bone, const char *parentName) } else { - if (_parentBone) - _parentBone->addChildBone(bone); - else - _topBoneList->addObject(bone); + _topBoneList->addObject(bone); } } else { - if (_parentBone) - _parentBone->addChildBone(bone); - else - _topBoneList->addObject(bone); + _topBoneList->addObject(bone); } bone->setArmature(this); @@ -288,9 +286,9 @@ void Armature::addBone(Bone *bone, const char *parentName) void Armature::removeBone(Bone *bone, bool recursion) { - CCASSERT(bone != NULL, "bone must be added to the bone dictionary!"); + CCASSERT(bone != nullptr, "bone must be added to the bone dictionary!"); - bone->setArmature(NULL); + bone->setArmature(nullptr); bone->removeFromParent(recursion); if (_topBoneList->containsObject(bone)) @@ -310,15 +308,15 @@ Bone *Armature::getBone(const char *name) const void Armature::changeBoneParent(Bone *bone, const char *parentName) { - CCASSERT(bone != NULL, "bone must be added to the bone dictionary!"); + CCASSERT(bone != nullptr, "bone must be added to the bone dictionary!"); if(bone->getParentBone()) { bone->getParentBone()->getChildren()->removeObject(bone); - bone->setParentBone(NULL); + bone->setParentBone(nullptr); } - if (parentName != NULL) + if (parentName != nullptr) { Bone *boneParent = (Bone *)_boneDic->objectForKey(parentName); @@ -337,7 +335,7 @@ void Armature::changeBoneParent(Bone *bone, const char *parentName) } } -Dictionary *Armature::getBoneDic() +Dictionary *Armature::getBoneDic() const { return _boneDic; } @@ -439,12 +437,12 @@ void Armature::setAnimation(ArmatureAnimation *animation) _animation = animation; } -ArmatureAnimation *Armature::getAnimation() +ArmatureAnimation *Armature::getAnimation() const { return _animation; } -bool Armature::getArmatureTransformDirty() +bool Armature::getArmatureTransformDirty() const { return _armatureTransformDirty; } @@ -453,8 +451,7 @@ void Armature::update(float dt) { _animation->update(dt); - Object *object = NULL; - CCARRAY_FOREACH(_topBoneList, object) + for (auto object : *_topBoneList) { static_cast(object)->update(dt); } @@ -464,24 +461,22 @@ void Armature::update(float dt) void Armature::draw() { - if (_parentBone == NULL) + if (_parentBone == nullptr && _batchNode == nullptr) { CC_NODE_DRAW_SETUP(); GL::blendFunc(_blendFunc.src, _blendFunc.dst); } - Object *object = NULL; - CCARRAY_FOREACH(_children, object) + for (auto object : *_children) { if (Bone *bone = dynamic_cast(object)) { - DisplayManager *displayManager = bone->getDisplayManager(); - Node *node = displayManager->getDisplayRenderNode(); + Node *node = bone->getDisplayRenderNode(); - if (NULL == node) + if (nullptr == node) continue; - switch (displayManager->getCurrentDecorativeDisplay()->getDisplayData()->displayType) + switch (bone->getDisplayRenderNodeType()) { case CS_DISPLAY_SPRITE: { @@ -527,6 +522,7 @@ void Armature::draw() } } armature->draw(); + _atlas = armature->getTextureAtlas(); } break; default: @@ -558,7 +554,7 @@ void Armature::draw() } } - if(_atlas && !_batchNode && _parentBone == NULL) + if(_atlas && !_batchNode && _parentBone == nullptr) { _atlas->drawQuads(); _atlas->removeAllQuads(); @@ -644,8 +640,7 @@ Rect Armature::getBoundingBox() const Rect boundingBox = Rect(0, 0, 0, 0); - Object *object = NULL; - CCARRAY_FOREACH(_children, object) + for(auto object : *_children) { if (Bone *bone = dynamic_cast(object)) { @@ -672,10 +667,10 @@ Rect Armature::getBoundingBox() const } } - return boundingBox; + return RectApplyAffineTransform(boundingBox, getNodeToParentTransform()); } -Bone *Armature::getBoneAtPoint(float x, float y) +Bone *Armature::getBoneAtPoint(float x, float y) const { int length = _children->count(); Bone *bs; @@ -688,11 +683,60 @@ Bone *Armature::getBoneAtPoint(float x, float y) return bs; } } - return NULL; + return nullptr; +} + +TextureAtlas *Armature::getTexureAtlasWithTexture(Texture2D *texture) const +{ + int key = texture->getName(); + + if (_parentBone && _parentBone->getArmature()) + { + return _parentBone->getArmature()->getTexureAtlasWithTexture(texture); + } + else if (_batchNode) + { + _batchNode->getTexureAtlasWithTexture(texture); + } + + TextureAtlas *atlas = static_cast(_textureAtlasDic->objectForKey(key)); + if (atlas == nullptr) + { + atlas = TextureAtlas::createWithTexture(texture, 4); + _textureAtlasDic->setObject(atlas, key); + } + return atlas; +} + +void Armature::setParentBone(Bone *parentBone) +{ + _parentBone = parentBone; + + DictElement *element = nullptr; + CCDICT_FOREACH(_boneDic, element) + { + Bone *bone = static_cast(element->getObject()); + bone->setArmature(this); + } +} + +Bone *Armature::getParentBone() const +{ + return _parentBone; +} + +void CCArmature::setColliderFilter(ColliderFilter *filter) +{ + DictElement *element = nullptr; + CCDICT_FOREACH(_boneDic, element) + { + Bone *bone = static_cast(element->getObject()); + bone->setColliderFilter(filter); + } } #if ENABLE_PHYSICS_BOX2D_DETECT -b2Body *Armature::getBody() +b2Body *Armature::getBody() const { return _body; } @@ -707,18 +751,16 @@ void Armature::setBody(b2Body *body) _body = body; _body->SetUserData(this); - Object *object = NULL; - CCARRAY_FOREACH(_children, object) + for(auto object : *_children) { if (Bone *bone = dynamic_cast(object)) { Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - Object *displayObject = NULL; - CCARRAY_FOREACH(displayList, displayObject) + for(auto displayObject : displayList) { - ColliderDetector *detector = ((DecorativeDisplay *)displayObject)->getColliderDetector(); - if (detector != NULL) + ColliderDetector *detector = static_cast(displayObject)->getColliderDetector(); + if (detector != nullptr) { detector->setBody(_body); } @@ -735,12 +777,12 @@ b2Fixture *Armature::getShapeList() } else { - return NULL; + return nullptr; } } #elif ENABLE_PHYSICS_CHIPMUNK_DETECT -cpBody *Armature::getBody() +cpBody *Armature::getBody() const { return _body; } @@ -755,18 +797,16 @@ void Armature::setBody(cpBody *body) _body = body; _body->data = this; - Object *object = NULL; - CCARRAY_FOREACH(_children, object) + for(auto object: *_children) { if (Bone *bone = dynamic_cast(object)) { Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - Object *displayObject = NULL; - CCARRAY_FOREACH(displayList, displayObject) + for(auto displayObject: *displayList) { - ColliderDetector *detector = ((DecorativeDisplay *)displayObject)->getColliderDetector(); - if (detector != NULL) + ColliderDetector *detector = static_cast(displayObject)->getColliderDetector(); + if (detector != nullptr) { detector->setBody(_body); } @@ -783,7 +823,7 @@ cpShape *Armature::getShapeList() } else { - return NULL; + return nullptr; } } #endif diff --git a/cocos/editor-support/cocostudio/CCArmature.h b/cocos/editor-support/cocostudio/CCArmature.h index 3e8c521011..3ace91b05e 100644 --- a/cocos/editor-support/cocostudio/CCArmature.h +++ b/cocos/editor-support/cocostudio/CCArmature.h @@ -65,6 +65,7 @@ CC_DEPRECATED_ATTRIBUTE typedef Bone CCBone; CC_DEPRECATED_ATTRIBUTE typedef ArmatureAnimation CCArmatureAnimation; CC_DEPRECATED_ATTRIBUTE typedef Armature CCArmature; CC_DEPRECATED_ATTRIBUTE typedef ArmatureDataManager CCArmatureDataManager; +CC_DEPRECATED_ATTRIBUTE typedef TweenType CCTweenType; class Armature : public cocos2d::NodeRGBA, public cocos2d::BlendProtocol { @@ -93,12 +94,12 @@ public: * @js NA * @lua NA */ - ~Armature(void); + virtual ~Armature(void); /** * Init the empty armature */ - virtual bool init(); + virtual bool init() override; /** * Init an armature with specified name @@ -111,7 +112,7 @@ public: * Add a Bone to this Armature, * * @param bone The Bone you want to add to Armature - * @param parentName The parent Bone's name you want to add to . If it's NULL, then set Armature to its parent + * @param parentName The parent Bone's name you want to add to . If it's nullptr, then set Armature to its parent */ virtual void addBone(Bone *bone, const char *parentName); /** @@ -139,14 +140,14 @@ public: * Get Armature's bone dictionary * @return Armature's bone dictionary */ - cocos2d::Dictionary *getBoneDic(); + cocos2d::Dictionary *getBoneDic() const; /** * This boundingBox will calculate all bones' boundingBox every time */ - virtual cocos2d::Rect getBoundingBox() const; + virtual cocos2d::Rect getBoundingBox() const override; - Bone *getBoneAtPoint(float x, float y); + Bone *getBoneAtPoint(float x, float y) const; // overrides /** @@ -169,14 +170,43 @@ public: virtual void updateOffsetPoint(); virtual void setAnimation(ArmatureAnimation *animation); - virtual ArmatureAnimation *getAnimation(); + virtual ArmatureAnimation *getAnimation() const; - virtual bool getArmatureTransformDirty(); + virtual bool getArmatureTransformDirty() const; + + virtual cocos2d::TextureAtlas *getTexureAtlasWithTexture(cocos2d::Texture2D *texture) const; + + virtual void setColliderFilter(ColliderFilter *filter); + + + virtual void setArmatureData(ArmatureData *armatureData) { _armatureData = armatureData; } + virtual ArmatureData *getArmatureData() const { return _armatureData; } + + virtual void setBatchNode(BatchNode *batchNode) { _batchNode = batchNode; } + virtual BatchNode *getBatchNode() const { return _batchNode; } + + virtual void setName(const std::string &name) { _name = name; } + virtual const std::string &getName() const { return _name; } + + virtual void setTextureAtlas(cocos2d::TextureAtlas *atlas) { _atlas = atlas; } + virtual cocos2d::TextureAtlas *getTextureAtlas() const { return _atlas; } + + virtual void setParentBone(Bone *parentBone); + virtual Bone *getParentBone() const; + + virtual void setVersion(float version) { _version = version; } + virtual float getVersion() const { return _version; } #if ENABLE_PHYSICS_BOX2D_DETECT virtual b2Fixture *getShapeList(); + + virtual void setBody(b2Body *body); + virtual b2Body *getBody() const; #elif ENABLE_PHYSICS_CHIPMUNK_DETECT virtual cpShape *getShapeList(); + + virtual void setBody(cpBody *body); + virtual cpBody *getBody() const; #endif protected: @@ -189,19 +219,14 @@ protected: //! Update blend function void updateBlendType(BlendType blendType); - CC_SYNTHESIZE(ArmatureData *, _armatureData, ArmatureData); - - CC_SYNTHESIZE(BatchNode *, _batchNode, BatchNode); - - CC_SYNTHESIZE(std::string, _name, Name); - - CC_SYNTHESIZE(cocos2d::TextureAtlas *, _atlas, TextureAtlas); - - CC_SYNTHESIZE(Bone *, _parentBone, ParentBone); - - CC_SYNTHESIZE(float, _version, Version); - protected: + ArmatureData *_armatureData; + BatchNode *_batchNode; + std::string _name; + cocos2d::TextureAtlas *_atlas; + Bone *_parentBone; + float _version; + mutable bool _armatureTransformDirty; cocos2d::Dictionary *_boneDic; //! The dictionary of the bones, include all bones in the armature, no matter it is the direct bone or the indirect bone. It is different from m_pChindren. @@ -214,10 +239,12 @@ protected: ArmatureAnimation *_animation; + cocos2d::Dictionary *_textureAtlasDic; + #if ENABLE_PHYSICS_BOX2D_DETECT - CC_PROPERTY(b2Body *, _body, Body); + b2Body *_body; #elif ENABLE_PHYSICS_CHIPMUNK_DETECT - CC_PROPERTY(cpBody *, _body, Body); + cpBody *_body; #endif }; diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp index a026fc33c9..49aa8e1c6f 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp @@ -43,22 +43,24 @@ ArmatureAnimation *ArmatureAnimation::create(Armature *armature) return pArmatureAnimation; } CC_SAFE_DELETE(pArmatureAnimation); - return NULL; + return nullptr; } ArmatureAnimation::ArmatureAnimation() - : _animationData(NULL) + : _animationData(nullptr) , _speedScale(1) - , _movementData(NULL) - , _armature(NULL) + , _movementData(nullptr) + , _armature(nullptr) , _movementID("") , _toIndex(0) + , _tweenList(nullptr) + , _ignoreFrameEvent(false) - , _movementEventCallFunc(NULL) - , _frameEventCallFunc(NULL) - , _movementEventTarget(NULL) - , _frameEventTarget(NULL) + , _movementEventCallFunc(nullptr) + , _frameEventCallFunc(nullptr) + , _movementEventTarget(nullptr) + , _frameEventTarget(nullptr) { } @@ -92,8 +94,7 @@ bool ArmatureAnimation::init(Armature *armature) void ArmatureAnimation:: pause() { - Object *object = NULL; - CCARRAY_FOREACH(_tweenList, object) + for(auto object : *_tweenList) { static_cast(object)->pause(); } @@ -102,8 +103,7 @@ void ArmatureAnimation:: pause() void ArmatureAnimation::resume() { - Object *object = NULL; - CCARRAY_FOREACH(_tweenList, object) + for(auto object : *_tweenList) { static_cast(object)->resume(); } @@ -112,8 +112,7 @@ void ArmatureAnimation::resume() void ArmatureAnimation::stop() { - Object *object = NULL; - CCARRAY_FOREACH(_tweenList, object) + for(auto object : *_tweenList) { static_cast(object)->stop(); } @@ -143,8 +142,8 @@ void ArmatureAnimation::setSpeedScale(float speedScale) _processScale = !_movementData ? _speedScale : _speedScale * _movementData->scale; - DictElement *element = NULL; - Dictionary *dict = _armature->getBoneDic(); + DictElement *element = nullptr; + const Dictionary *dict = _armature->getBoneDic(); CCDICT_FOREACH(dict, element) { Bone *bone = static_cast(element->getObject()); @@ -171,8 +170,8 @@ void ArmatureAnimation::setAnimationInternal(float animationInternal) _animationInternal = animationInternal; - DictElement *element = NULL; - Dictionary *dict = _armature->getBoneDic(); + DictElement *element = nullptr; + const Dictionary *dict = _armature->getBoneDic(); CCDICT_FOREACH(dict, element) { Bone *bone = static_cast(element->getObject()); @@ -230,11 +229,11 @@ void ArmatureAnimation::play(const char *animationName, int durationTo, int dura _durationTween = durationTween; } - MovementBoneData *movementBoneData = NULL; + MovementBoneData *movementBoneData = nullptr; _tweenList->removeAllObjects(); - DictElement *element = NULL; - Dictionary *dict = _armature->getBoneDic(); + DictElement *element = nullptr; + const Dictionary *dict = _armature->getBoneDic(); CCDICT_FOREACH(dict, element) { @@ -259,7 +258,7 @@ void ArmatureAnimation::play(const char *animationName, int durationTo, int dura } else { - if(!bone->getIgnoreMovementBoneData()) + if(!bone->isIgnoreMovementBoneData()) { //! this bone is not include in this movement, so hide it bone->getDisplayManager()->changeDisplayByIndex(-1, false); @@ -268,6 +267,8 @@ void ArmatureAnimation::play(const char *animationName, int durationTo, int dura } } + + _armature->update(0); } @@ -280,9 +281,41 @@ void ArmatureAnimation::playByIndex(int animationIndex, int durationTo, int dura play(animationName.c_str(), durationTo, durationTween, loop, tweenEasing); } +void ArmatureAnimation::gotoAndPlay(int frameIndex) +{ + if (!_movementData || frameIndex < 0 || frameIndex >= _movementData->duration) + { + CCLOG("Please ensure you have played a movement, and the frameIndex is in the range."); + return; + } + bool ignoreFrameEvent = _ignoreFrameEvent; + _ignoreFrameEvent = true; -int ArmatureAnimation::getMovementCount() + _isPlaying = true; + _isComplete = _isPause = false; + + ProcessBase::gotoFrame(frameIndex); + _currentPercent = (float)_curFrameIndex / (float)_movementData->duration; + _currentFrame = _nextFrameIndex * _currentPercent; + + for(auto object : *_tweenList) + { + static_cast(object)->gotoAndPlay(frameIndex); + } + + _armature->update(0); + + _ignoreFrameEvent = ignoreFrameEvent; +} + +void ArmatureAnimation::gotoAndPause(int frameIndex) +{ + gotoAndPlay(frameIndex); + pause(); +} + +int ArmatureAnimation::getMovementCount() const { return _animationData->getMovementCount(); } @@ -290,11 +323,23 @@ int ArmatureAnimation::getMovementCount() void ArmatureAnimation::update(float dt) { ProcessBase::update(dt); - Object *object = NULL; - CCARRAY_FOREACH(_tweenList, object) + + for(auto object : *_tweenList) { static_cast(object)->update(dt); } + + while (_frameEventQueue.size() > 0) + { + FrameEvent *frameEvent = _frameEventQueue.front(); + _frameEventQueue.pop(); + + _ignoreFrameEvent = true; + (_frameEventTarget->*_frameEventCallFunc)(frameEvent->bone, frameEvent->frameEventName, frameEvent->originFrameIndex, frameEvent->currentFrameIndex); + _ignoreFrameEvent = false; + + CC_SAFE_DELETE(frameEvent); + } } void ArmatureAnimation::updateHandler() @@ -367,7 +412,7 @@ void ArmatureAnimation::updateHandler() } } -std::string ArmatureAnimation::getCurrentMovementID() +std::string ArmatureAnimation::getCurrentMovementID() const { if (_isComplete) { @@ -402,7 +447,13 @@ void ArmatureAnimation::frameEvent(Bone *bone, const char *frameEventName, int o { if (_frameEventTarget && _frameEventCallFunc) { - (_frameEventTarget->*_frameEventCallFunc)(bone, frameEventName, originFrameIndex, currentFrameIndex); + FrameEvent *frameEvent = new FrameEvent(); + frameEvent->bone = bone; + frameEvent->frameEventName = frameEventName; + frameEvent->originFrameIndex = originFrameIndex; + frameEvent->currentFrameIndex = currentFrameIndex; + + _frameEventQueue.push(frameEvent); } } } diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.h b/cocos/editor-support/cocostudio/CCArmatureAnimation.h index 9551f97ff9..8d306398e9 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.h +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.h @@ -27,6 +27,7 @@ THE SOFTWARE. #define __CCANIMATION_H__ #include "cocostudio/CCProcessBase.h" +#include namespace cocostudio { @@ -48,6 +49,13 @@ typedef void (cocos2d::Object::*SEL_FrameEventCallFunc)(Bone *, const char *, in #define movementEvent_selector(_SELECTOR) (cocostudio::SEL_MovementEventCallFunc)(&_SELECTOR) #define frameEvent_selector(_SELECTOR) (cocostudio::SEL_FrameEventCallFunc)(&_SELECTOR) +struct FrameEvent +{ + Bone *bone; + const char *frameEventName; + int originFrameIndex; + int currentFrameIndex; +}; class ArmatureAnimation : public ProcessBase { @@ -76,10 +84,11 @@ public: /** * Scale animation play speed. + * This method is deprecated, please use setSpeedScale. * @param animationScale Scale value */ - virtual void setAnimationScale(float animationScale); - virtual float getAnimationScale() const; + CC_DEPRECATED_ATTRIBUTE virtual void setAnimationScale(float animationScale); + CC_DEPRECATED_ATTRIBUTE virtual float getAnimationScale() const; /** * Scale animation play speed. @@ -123,10 +132,27 @@ public: /** * Play animation by index, the other param is the same to play. - * @param _animationIndex the animation index you want to play + * @param animationIndex the animation index you want to play */ void playByIndex(int animationIndex, int durationTo = -1, int durationTween = -1, int loop = -1, int tweenEasing = TWEEN_EASING_MAX); + /** + * Go to specified frame and play current movement. + * You need first switch to the movement you want to play, then call this function. + * + * example : playByIndex(0); + * gotoAndPlay(0); + * playByIndex(1); + * gotoAndPlay(0); + * gotoAndPlay(15); + */ + virtual void gotoAndPlay(int frameIndex); + + /** + * Go to specified frame and pause current movement. + */ + virtual void gotoAndPause(int frameIndex); + /** * Pause the Process */ @@ -144,7 +170,7 @@ public: /** * Get movement count */ - int getMovementCount(); + int getMovementCount() const; void update(float dt); @@ -152,20 +178,30 @@ public: * Get current movementID * @return The name of current movement */ - std::string getCurrentMovementID(); + std::string getCurrentMovementID() const; /** * Set armature's movement event callback function - * To disconnect this event, just setMovementEventCallFunc(NULL, NULL); + * To disconnect this event, just setMovementEventCallFunc(nullptr, nullptr); */ void setMovementEventCallFunc(cocos2d::Object *target, SEL_MovementEventCallFunc callFunc); /** * Set armature's frame event callback function - * To disconnect this event, just setFrameEventCallFunc(NULL, NULL); + * To disconnect this event, just setFrameEventCallFunc(nullptr, nullptr); */ void setFrameEventCallFunc(cocos2d::Object *target, SEL_FrameEventCallFunc callFunc); + virtual void setAnimationData(AnimationData *data) + { + if (_animationData != data) + { + CC_SAFE_RETAIN(data); + CC_SAFE_RELEASE(_animationData); + _animationData = data; + } + } + virtual AnimationData *getAnimationData() const { return _animationData; } protected: /** @@ -183,10 +219,12 @@ protected: */ void frameEvent(Bone *bone, const char *frameEventName, int originFrameIndex, int currentFrameIndex); + bool isIgnoreFrameEvent() const { return _ignoreFrameEvent; } + friend class Tween; protected: //! AnimationData save all MovementDatas this animation used. - CC_SYNTHESIZE_RETAIN(AnimationData *, _animationData, AnimationData); + AnimationData *_animationData; //! Scale the animation speed float _speedScale; @@ -201,6 +239,9 @@ protected: cocos2d::Array *_tweenList; + bool _ignoreFrameEvent; + + std::queue _frameEventQueue; protected: /** * MovementEvent CallFunc. diff --git a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp index 113ff33202..57f9bf5cdc 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp @@ -32,11 +32,11 @@ using namespace cocos2d; namespace cocostudio { -static ArmatureDataManager *s_sharedArmatureDataManager = NULL; +static ArmatureDataManager *s_sharedArmatureDataManager = nullptr; ArmatureDataManager *ArmatureDataManager::getInstance() { - if (s_sharedArmatureDataManager == NULL) + if (s_sharedArmatureDataManager == nullptr) { s_sharedArmatureDataManager = new ArmatureDataManager(); if (!s_sharedArmatureDataManager || !s_sharedArmatureDataManager->init()) @@ -56,16 +56,30 @@ void ArmatureDataManager::destoryInstance() ArmatureDataManager::ArmatureDataManager(void) { - _armarureDatas = NULL; - _animationDatas = NULL; - _textureDatas = NULL; + _armarureDatas = nullptr; + _animationDatas = nullptr; + _textureDatas = nullptr; _autoLoadSpriteFile = false; } ArmatureDataManager::~ArmatureDataManager(void) { - removeAll(); + if( _animationDatas ) + { + _animationDatas->removeAllObjects(); + } + if( _armarureDatas ) + { + _armarureDatas->removeAllObjects(); + } + + if( _textureDatas ) + { + _textureDatas->removeAllObjects(); + } + + _relativeDatas.clear(); CC_SAFE_DELETE(_animationDatas); CC_SAFE_DELETE(_armarureDatas); @@ -97,17 +111,52 @@ bool ArmatureDataManager::init() return bRet; } -void ArmatureDataManager::addArmatureData(const char *id, ArmatureData *armatureData) +void ArmatureDataManager::removeArmatureFileInfo(const char *configFilePath) +{ + if (RelativeData *data = getRelativeData(configFilePath)) + { + for (std::string str : data->armatures) + { + removeArmatureData(str.c_str()); + } + + for (std::string str : data->animations) + { + removeAnimationData(str.c_str()); + } + + for (std::string str : data->textures) + { + removeTextureData(str.c_str()); + } + + for (std::string str : data->plistFiles) + { + SpriteFrameCache::getInstance()->removeSpriteFramesFromFile(str.c_str()); + } + + _relativeDatas.erase(configFilePath); + DataReaderHelper::getInstance()->removeConfigFile(configFilePath); + } +} + + +void ArmatureDataManager::addArmatureData(const char *id, ArmatureData *armatureData, const char *configFilePath) { if(_armarureDatas) { + if (RelativeData *data = getRelativeData(configFilePath)) + { + data->armatures.push_back(id); + } + _armarureDatas->setObject(armatureData, id); } } ArmatureData *ArmatureDataManager::getArmatureData(const char *id) { - ArmatureData *armatureData = NULL; + ArmatureData *armatureData = nullptr; if (_armarureDatas) { armatureData = (ArmatureData *)_armarureDatas->objectForKey(id); @@ -123,17 +172,22 @@ void ArmatureDataManager::removeArmatureData(const char *id) } } -void ArmatureDataManager::addAnimationData(const char *id, AnimationData *animationData) +void ArmatureDataManager::addAnimationData(const char *id, AnimationData *animationData, const char *configFilePath) { if(_animationDatas) { + if (RelativeData *data = getRelativeData(configFilePath)) + { + data->animations.push_back(id); + } + _animationDatas->setObject(animationData, id); } } AnimationData *ArmatureDataManager::getAnimationData(const char *id) { - AnimationData *animationData = NULL; + AnimationData *animationData = nullptr; if (_animationDatas) { animationData = (AnimationData *)_animationDatas->objectForKey(id); @@ -149,10 +203,15 @@ void ArmatureDataManager::removeAnimationData(const char *id) } } -void ArmatureDataManager::addTextureData(const char *id, TextureData *textureData) +void ArmatureDataManager::addTextureData(const char *id, TextureData *textureData, const char *configFilePath) { if(_textureDatas) { + if (RelativeData *data = getRelativeData(configFilePath)) + { + data->textures.push_back(id); + } + _textureDatas->setObject(textureData, id); } } @@ -160,7 +219,7 @@ void ArmatureDataManager::addTextureData(const char *id, TextureData *textureDat TextureData *ArmatureDataManager::getTextureData(const char *id) { - TextureData *textureData = NULL; + TextureData *textureData = nullptr; if (_textureDatas) { textureData = (TextureData *)_textureDatas->objectForKey(id); @@ -179,18 +238,24 @@ void ArmatureDataManager::removeTextureData(const char *id) void ArmatureDataManager::addArmatureFileInfo(const char *configFilePath) { + addRelativeData(configFilePath); + _autoLoadSpriteFile = true; DataReaderHelper::getInstance()->addDataFromFile(configFilePath); } void ArmatureDataManager::addArmatureFileInfoAsync(const char *configFilePath, Object *target, SEL_SCHEDULE selector) { + addRelativeData(configFilePath); + _autoLoadSpriteFile = true; - DataReaderHelper::getInstance()->addDataFromFileAsync(configFilePath, target, selector); + DataReaderHelper::getInstance()->addDataFromFileAsync("", "", configFilePath, target, selector); } void ArmatureDataManager::addArmatureFileInfo(const char *imagePath, const char *plistPath, const char *configFilePath) { + addRelativeData(configFilePath); + _autoLoadSpriteFile = false; DataReaderHelper::getInstance()->addDataFromFile(configFilePath); addSpriteFrameFromFile(plistPath, imagePath); @@ -198,36 +263,23 @@ void ArmatureDataManager::addArmatureFileInfo(const char *imagePath, const char void ArmatureDataManager::addArmatureFileInfoAsync(const char *imagePath, const char *plistPath, const char *configFilePath, Object *target, SEL_SCHEDULE selector) { + addRelativeData(configFilePath); + _autoLoadSpriteFile = false; - DataReaderHelper::getInstance()->addDataFromFileAsync(configFilePath, target, selector); + DataReaderHelper::getInstance()->addDataFromFileAsync(imagePath, plistPath, configFilePath, target, selector); addSpriteFrameFromFile(plistPath, imagePath); } -void ArmatureDataManager::addSpriteFrameFromFile(const char *plistPath, const char *imagePath) +void ArmatureDataManager::addSpriteFrameFromFile(const char *plistPath, const char *imagePath, const char *configFilePath) { + if (RelativeData *data = getRelativeData(configFilePath)) + { + data->plistFiles.push_back(plistPath); + } SpriteFrameCacheHelper::getInstance()->addSpriteFrameFromFile(plistPath, imagePath); } -void ArmatureDataManager::removeAll() -{ - if( _animationDatas ) - { - _animationDatas->removeAllObjects(); - } - if( _armarureDatas ) - { - _armarureDatas->removeAllObjects(); - } - - if( _textureDatas ) - { - _textureDatas->removeAllObjects(); - } - - DataReaderHelper::clear(); -} - bool ArmatureDataManager::isAutoLoadSpriteFile() { return _autoLoadSpriteFile; @@ -246,4 +298,17 @@ Dictionary *ArmatureDataManager::getTextureDatas() const return _textureDatas; } +void CCArmatureDataManager::addRelativeData(const char *configFilePath) +{ + if (_relativeDatas.find(configFilePath) == _relativeDatas.end()) + { + _relativeDatas[configFilePath] = RelativeData(); + } +} + +RelativeData *CCArmatureDataManager::getRelativeData(const char* configFilePath) +{ + return &_relativeDatas[configFilePath]; +} + } diff --git a/cocos/editor-support/cocostudio/CCArmatureDataManager.h b/cocos/editor-support/cocostudio/CCArmatureDataManager.h index 1bd426784d..b73dc99ef9 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDataManager.h +++ b/cocos/editor-support/cocostudio/CCArmatureDataManager.h @@ -31,6 +31,14 @@ THE SOFTWARE. namespace cocostudio { +struct RelativeData +{ + std::vector plistFiles; + std::vector armatures; + std::vector animations; + std::vector textures; +}; + /** * @brief format and manage armature configuration and armature animation */ @@ -69,7 +77,7 @@ public: * @param id The id of the armature data * @param armatureData ArmatureData * */ - void addArmatureData(const char *id, ArmatureData *armatureData); + void addArmatureData(const char *id, ArmatureData *armatureData, const char *configFilePath = ""); /** * @brief get armature data @@ -89,7 +97,7 @@ public: * @param id the id of the animation data * @return AnimationData * */ - void addAnimationData(const char *id, AnimationData *animationData); + void addAnimationData(const char *id, AnimationData *animationData, const char *configFilePath = ""); /** * @brief get animation data from _animationDatas(Dictionary) @@ -109,7 +117,7 @@ public: * @param id the id of the texture data * @return TextureData * */ - void addTextureData(const char *id, TextureData *textureData); + void addTextureData(const char *id, TextureData *textureData, const char *configFilePath = ""); /** * @brief get texture data @@ -149,13 +157,10 @@ public: /** * @brief Add sprite frame to CCSpriteFrameCache, it will save display name and it's relative image name */ - void addSpriteFrameFromFile(const char *plistPath, const char *imagePath); + void addSpriteFrameFromFile(const char *plistPath, const char *imagePath, const char *configFilePath = ""); + virtual void removeArmatureFileInfo(const char *configFilePath); - /** - * @brief Clear the data in the _armarureDatas and _animationDatas, and set _armarureDatas and _animationDatas to NULL - */ - void removeAll(); /** * @brief Juge whether or not need auto load sprite file @@ -166,6 +171,10 @@ public: cocos2d::Dictionary *getArmatureDatas() const; cocos2d::Dictionary *getAnimationDatas() const; cocos2d::Dictionary *getTextureDatas() const; + +protected: + void addRelativeData(const char* configFilePath); + RelativeData *getRelativeData(const char* configFilePath); private: /** * @brief save amature datas @@ -189,6 +198,8 @@ private: cocos2d::Dictionary *_textureDatas; bool _autoLoadSpriteFile; + + std::map _relativeDatas; }; diff --git a/cocos/editor-support/cocostudio/CCArmatureDefine.cpp b/cocos/editor-support/cocostudio/CCArmatureDefine.cpp index 3672943778..4f48e0024e 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDefine.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureDefine.cpp @@ -28,7 +28,7 @@ namespace cocostudio { const char *armatureVersion() { - return "0.4.0.0"; + return "1.0.0.0"; } } diff --git a/cocos/editor-support/cocostudio/CCArmatureDefine.h b/cocos/editor-support/cocostudio/CCArmatureDefine.h index 8b7cb42312..c79b58ff81 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDefine.h +++ b/cocos/editor-support/cocostudio/CCArmatureDefine.h @@ -30,6 +30,7 @@ THE SOFTWARE. #define VERSION_COMBINED 0.30f #define VERSION_CHANGE_ROTATION_RANGE 1.0f +#define VERSION_COLOR_READING 1.1f #ifndef AUTO_ADD_SPRITE_FRAME_NAME_PREFIX #define AUTO_ADD_SPRITE_FRAME_NAME_PREFIX 0 @@ -44,8 +45,12 @@ THE SOFTWARE. #define ENABLE_PHYSICS_CHIPMUNK_DETECT 1 #endif +#ifndef ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX +#define ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX 0 +#endif + #define CS_RETURN_IF(cond) if (cond) return -#define CS_RETURN_NULL_IF(cond) if (cond) return NULL; +#define CS_RETURN_NULL_IF(cond) if (cond) return nullptr; namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCBatchNode.cpp b/cocos/editor-support/cocostudio/CCBatchNode.cpp index 7ef2188fb8..7219969b57 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.cpp +++ b/cocos/editor-support/cocostudio/CCBatchNode.cpp @@ -25,6 +25,7 @@ THE SOFTWARE. #include "cocostudio/CCBatchNode.h" #include "cocostudio/CCArmatureDefine.h" #include "cocostudio/CCArmature.h" +#include "cocostudio/CCSkin.h" using namespace cocos2d; @@ -39,31 +40,98 @@ BatchNode *BatchNode::create() return batchNode; } CC_SAFE_DELETE(batchNode); - return NULL; + return nullptr; } BatchNode::BatchNode() - : _atlas(NULL) + : _atlas(nullptr) + , _textureAtlasDic(nullptr) { } +BatchNode::~BatchNode() +{ + CC_SAFE_RELEASE_NULL(_textureAtlasDic); +} + bool BatchNode::init() { bool ret = Node::init(); setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); + + CC_SAFE_DELETE(_textureAtlasDic); + _textureAtlasDic = new Dictionary(); + return ret; } +void BatchNode::addChild(Node *pChild) +{ + Node::addChild(pChild); +} + +void BatchNode::addChild(Node *child, int zOrder) +{ + Node::addChild(child, zOrder); +} + void BatchNode::addChild(Node *child, int zOrder, int tag) { Node::addChild(child, zOrder, tag); Armature *armature = dynamic_cast(child); - if (armature != NULL) + if (armature != nullptr) { armature->setBatchNode(this); + + const Dictionary *dict = armature->getBoneDic(); + DictElement *element = nullptr; + CCDICT_FOREACH(dict, element) + { + Bone *bone = static_cast(element->getObject()); + + Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); + for(auto object : *displayList) + { + DecorativeDisplay *display = static_cast(object); + + if (Skin *skin = dynamic_cast(display->getDisplay())) + { + skin->setTextureAtlas(getTexureAtlasWithTexture(skin->getTexture())); + } + } + } } } +void BatchNode::removeChild(Node* child, bool cleanup) +{ + Armature *armature = dynamic_cast(child); + if (armature != nullptr) + { + armature->setBatchNode(nullptr); + + const Dictionary *dict = armature->getBoneDic(); + DictElement *element = nullptr; + CCDICT_FOREACH(dict, element) + { + Bone *bone = static_cast(element->getObject()); + + Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); + for(auto object : *displayList) + { + DecorativeDisplay *display = static_cast(object); + + if (Skin *skin = dynamic_cast(display->getDisplay())) + { + skin->setTextureAtlas(armature->getTexureAtlasWithTexture(skin->getTexture())); + } + } + } + } + + Node::removeChild(child, cleanup); +} + void BatchNode::visit() { // quick return if not visible. children won't be drawn. @@ -96,8 +164,8 @@ void BatchNode::visit() void BatchNode::draw() { CC_NODE_DRAW_SETUP(); - Object *object = NULL; - CCARRAY_FOREACH(_children, object) + + for(auto object : *_children) { Armature *armature = dynamic_cast(object); if (armature) @@ -118,4 +186,17 @@ void BatchNode::draw() } } +TextureAtlas *BatchNode::getTexureAtlasWithTexture(Texture2D *texture) const +{ + int key = texture->getName(); + + TextureAtlas *atlas = static_cast(_textureAtlasDic->objectForKey(key)); + if (atlas == nullptr) + { + atlas = CCTextureAtlas::createWithTexture(texture, 4); + _textureAtlasDic->setObject(atlas, key); + } + return atlas; +} + } diff --git a/cocos/editor-support/cocostudio/CCBatchNode.h b/cocos/editor-support/cocostudio/CCBatchNode.h index df33e44e0b..fa654a19ba 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.h +++ b/cocos/editor-support/cocostudio/CCBatchNode.h @@ -38,14 +38,20 @@ public: * @js ctor */ BatchNode(); + ~BatchNode(); - virtual bool init(); - virtual void addChild(cocos2d::Node *child, int zOrder, int tag); - virtual void visit(); - void draw(); + virtual bool init() override; + virtual void addChild(cocos2d::Node *pChild) override; + virtual void addChild(cocos2d::Node *pChild, int zOrder) override; + virtual void addChild(cocos2d::Node *pChild, int zOrder, int tag) override; + virtual void removeChild(cocos2d::Node* child, bool cleanup) override; + virtual void visit() override; + void draw() override; + virtual cocos2d::TextureAtlas *getTexureAtlasWithTexture(cocos2d::Texture2D *texture) const; protected: cocos2d::TextureAtlas *_atlas; + cocos2d::Dictionary *_textureAtlasDic; }; } diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index abd0cb85a5..cbd4544120 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -43,7 +43,7 @@ Bone *Bone::create() return pBone; } CC_SAFE_DELETE(pBone); - return NULL; + return nullptr; } @@ -57,24 +57,28 @@ Bone *Bone::create(const char *name) return pBone; } CC_SAFE_DELETE(pBone); - return NULL; + return nullptr; } Bone::Bone() { - _tweenData = NULL; - _parentBone = NULL; - _armature = NULL; - _childArmature = NULL; - _boneData = NULL; - _tween = NULL; - _tween = NULL; - _children = NULL; - _displayManager = NULL; + _tweenData = nullptr; + _parentBone = nullptr; + _armature = nullptr; + _childArmature = nullptr; + _boneData = nullptr; + _tween = nullptr; + _tween = nullptr; + _children = nullptr; + _displayManager = nullptr; _ignoreMovementBoneData = false; _worldTransform = AffineTransformMake(1, 0, 0, 1, 0, 0); _boneTransformDirty = true; _blendType = BLEND_NORMAL; + _worldInfo = nullptr; + + _armatureParentBone = nullptr; + _dataVersion = 0; } @@ -84,18 +88,16 @@ Bone::~Bone(void) CC_SAFE_DELETE(_children); CC_SAFE_DELETE(_tween); CC_SAFE_DELETE(_displayManager); + CC_SAFE_DELETE(_worldInfo); - if(_boneData) - { - _boneData->release(); - } + CC_SAFE_RELEASE_NULL(_boneData); CC_SAFE_RELEASE(_childArmature); } bool Bone::init() { - return Bone::init(NULL); + return Bone::init(nullptr); } @@ -105,7 +107,7 @@ bool Bone::init(const char *name) do { - if(NULL != name) + if(nullptr != name) { _name = name; } @@ -121,6 +123,11 @@ bool Bone::init(const char *name) _displayManager = new DisplayManager(); _displayManager->init(this); + CC_SAFE_DELETE(_worldInfo); + _worldInfo = new BaseData(); + + CC_SAFE_DELETE(_boneData); + _boneData = new BoneData(); bRet = true; } @@ -131,10 +138,14 @@ bool Bone::init(const char *name) void Bone::setBoneData(BoneData *boneData) { - CCASSERT(NULL != boneData, "_boneData must not be NULL"); + CCASSERT(nullptr != boneData, "_boneData must not be nullptr"); - _boneData = boneData; - _boneData->retain(); + if (_boneData != boneData) + { + CC_SAFE_RETAIN(boneData); + CC_SAFE_RELEASE(_boneData); + _boneData = boneData; + } _name = _boneData->name; _ZOrder = _boneData->zOrder; @@ -142,7 +153,7 @@ void Bone::setBoneData(BoneData *boneData) _displayManager->initDisplayList(boneData); } -BoneData *Bone::getBoneData() +BoneData *Bone::getBoneData() const { return _boneData; } @@ -153,11 +164,17 @@ void Bone::setArmature(Armature *armature) if (_armature) { _tween->setAnimation(_armature->getAnimation()); + _dataVersion = _armature->getArmatureData()->dataVersion; + _armatureParentBone = _armature->getParentBone(); + } + else + { + _armatureParentBone = nullptr; } } -Armature *Bone::getArmature() +Armature *Bone::getArmature() const { return _armature; } @@ -167,37 +184,75 @@ void Bone::update(float delta) if (_parentBone) _boneTransformDirty = _boneTransformDirty || _parentBone->isTransformDirty(); + if (_armatureParentBone && !_boneTransformDirty) + { + _boneTransformDirty = _armatureParentBone->isTransformDirty(); + } + if (_boneTransformDirty) { - if (_armature->getArmatureData()->dataVersion >= VERSION_COMBINED) + if (_dataVersion >= VERSION_COMBINED) { TransformHelp::nodeConcat(*_tweenData, *_boneData); _tweenData->scaleX -= 1; _tweenData->scaleY -= 1; } - TransformHelp::nodeToMatrix(*_tweenData, _worldTransform); + _worldInfo->copy(_tweenData); - _worldTransform = AffineTransformConcat(getNodeToParentTransform(), _worldTransform); + _worldInfo->x = _tweenData->x + _position.x; + _worldInfo->y = _tweenData->y + _position.y; + _worldInfo->scaleX = _tweenData->scaleX * _scaleX; + _worldInfo->scaleY = _tweenData->scaleY * _scaleY; + _worldInfo->skewX = _tweenData->skewX + _skewX + _rotationX; + _worldInfo->skewY = _tweenData->skewY + _skewY - _rotationY; if(_parentBone) { - _worldTransform = AffineTransformConcat(_worldTransform, _parentBone->_worldTransform); + applyParentTransform(_parentBone); + } + else + { + if (_armatureParentBone) + { + applyParentTransform(_armatureParentBone); + } + } + + TransformHelp::nodeToMatrix(*_worldInfo, _worldTransform); + + if (_armatureParentBone) + { + _worldTransform = AffineTransformConcat(_worldTransform, _armature->getNodeToParentTransform()); } } - DisplayFactory::updateDisplay(this, _displayManager->getCurrentDecorativeDisplay(), delta, _boneTransformDirty || _armature->getArmatureTransformDirty()); + DisplayFactory::updateDisplay(this, delta, _boneTransformDirty || _armature->getArmatureTransformDirty()); - Object *object = NULL; - CCARRAY_FOREACH(_children, object) + if (_children) { - Bone *childBone = (Bone *)object; - childBone->update(delta); + for(auto object : *_children) + { + Bone *childBone = (Bone *)object; + childBone->update(delta); + } } _boneTransformDirty = false; } +void Bone::applyParentTransform(Bone *parent) +{ + float x = _worldInfo->x; + float y = _worldInfo->y; + _worldInfo->x = x * parent->_worldTransform.a + y * parent->_worldTransform.c + parent->_worldInfo->x; + _worldInfo->y = x * parent->_worldTransform.b + y * parent->_worldTransform.d + parent->_worldInfo->y; + _worldInfo->scaleX = _worldInfo->scaleX * parent->_worldInfo->scaleX; + _worldInfo->scaleY = _worldInfo->scaleY * parent->_worldInfo->scaleY; + _worldInfo->skewX = _worldInfo->skewX + parent->_worldInfo->skewX; + _worldInfo->skewY = _worldInfo->skewY + parent->_worldInfo->skewY; +} + void Bone::updateDisplayedColor(const Color3B &parentColor) { @@ -213,11 +268,23 @@ void Bone::updateDisplayedOpacity(GLubyte parentOpacity) updateColor(); } +void Bone::setColor(const Color3B& color) +{ + NodeRGBA::setColor(color); + updateColor(); +} + +void Bone::setOpacity(GLubyte opacity) +{ + NodeRGBA::setOpacity(opacity); + updateColor(); +} + void Bone::updateColor() { Node *display = _displayManager->getDisplayRenderNode(); RGBAProtocol *protocol = dynamic_cast(display); - if(protocol != NULL) + if(protocol != nullptr) { protocol->setColor(Color3B(_displayedColor.r * _tweenData->r / 255, _displayedColor.g * _tweenData->g / 255, _displayedColor.b * _tweenData->b / 255)); protocol->setOpacity(_displayedOpacity * _tweenData->a / 255); @@ -226,7 +293,7 @@ void Bone::updateColor() void Bone::updateZOrder() { - if (_armature->getArmatureData()->dataVersion >= VERSION_COMBINED) + if (_dataVersion >= VERSION_COMBINED) { int zorder = _tweenData->zOrder + _boneData->zOrder; setZOrder(zorder); @@ -239,8 +306,8 @@ void Bone::updateZOrder() void Bone::addChildBone(Bone *child) { - CCASSERT( NULL != child, "Argument must be non-nil"); - CCASSERT( NULL == child->_parentBone, "child already added. It can't be added again"); + CCASSERT( nullptr != child, "Argument must be non-nil"); + CCASSERT( nullptr == child->_parentBone, "child already added. It can't be added again"); if(!_children) { @@ -257,22 +324,22 @@ void Bone::addChildBone(Bone *child) void Bone::removeChildBone(Bone *bone, bool recursion) { - if ( _children->getIndexOfObject(bone) != UINT_MAX ) + if (_children && _children->getIndexOfObject(bone) != UINT_MAX ) { if(recursion) { - Array *_ccbones = bone->_children; - Object *_object = NULL; - CCARRAY_FOREACH(_ccbones, _object) + Array *ccbones = bone->_children; + + for(auto object : *ccbones) { - Bone *_ccBone = (Bone *)_object; - bone->removeChildBone(_ccBone, recursion); + Bone *ccBone = (Bone *)object; + bone->removeChildBone(ccBone, recursion); } } - bone->setParentBone(NULL); + bone->setParentBone(nullptr); - bone->getDisplayManager()->setCurrentDecorativeDisplay(NULL); + bone->getDisplayManager()->setCurrentDecorativeDisplay(nullptr); _children->removeObject(bone); } @@ -280,7 +347,7 @@ void Bone::removeChildBone(Bone *bone, bool recursion) void Bone::removeFromParent(bool recursion) { - if (NULL != _parentBone) + if (nullptr != _parentBone) { _parentBone->removeChildBone(this, recursion); } @@ -300,13 +367,18 @@ void Bone::setChildArmature(Armature *armature) { if (_childArmature != armature) { + if (armature == nullptr && _childArmature) + { + _childArmature->setParentBone(nullptr); + } + CC_SAFE_RETAIN(armature); CC_SAFE_RELEASE(_childArmature); _childArmature = armature; } } -Armature *Bone::getChildArmature() +Armature *Bone::getChildArmature() const { return _childArmature; } @@ -322,16 +394,6 @@ void Bone::setZOrder(int zOrder) Node::setZOrder(zOrder); } -void Bone::setTransformDirty(bool dirty) -{ - _boneTransformDirty = dirty; -} - -bool Bone::isTransformDirty() -{ - return _boneTransformDirty; -} - AffineTransform Bone::getNodeToArmatureTransform() const { return _worldTransform; @@ -347,6 +409,12 @@ Node *Bone::getDisplayRenderNode() return _displayManager->getDisplayRenderNode(); } +DisplayType Bone::getDisplayRenderNodeType() +{ + return _displayManager->getDisplayRenderNodeType(); +} + + void Bone::addDisplay(DisplayData *displayData, int index) { _displayManager->addDisplay(displayData, index); @@ -357,6 +425,11 @@ void Bone::addDisplay(Node *display, int index) _displayManager->addDisplay(display, index); } +void Bone::removeDisplay(int index) +{ + _displayManager->removeDisplay(index); +} + void Bone::changeDisplayByIndex(int index, bool force) { _displayManager->changeDisplayByIndex(index, force); @@ -371,7 +444,34 @@ Array *Bone::getColliderBodyList() return detector->getColliderBodyList(); } } - return NULL; + return nullptr; +} + + + +void Bone::setColliderFilter(ColliderFilter *filter) +{ + Array *array = _displayManager->getDecorativeDisplayList(); + + for(auto object : *array) + { + DecorativeDisplay *decoDisplay = static_cast(object); + if (ColliderDetector *detector = decoDisplay->getColliderDetector()) + { + detector->setColliderFilter(filter); + } + } +} +ColliderFilter *Bone::getColliderFilter() +{ + if (DecorativeDisplay *decoDisplay = _displayManager->getCurrentDecorativeDisplay()) + { + if (ColliderDetector *detector = decoDisplay->getColliderDetector()) + { + return detector->getColliderFilter(); + } + } + return nullptr; } diff --git a/cocos/editor-support/cocostudio/CCBone.h b/cocos/editor-support/cocostudio/CCBone.h index 1163738515..4d67c41e2e 100644 --- a/cocos/editor-support/cocostudio/CCBone.h +++ b/cocos/editor-support/cocostudio/CCBone.h @@ -63,7 +63,7 @@ public: /** * Initializes an empty Bone with nothing init. */ - virtual bool init(); + virtual bool init() override; /** * Initializes a Bone with the specified name @@ -86,6 +86,8 @@ public: void addDisplay(cocos2d::Node *display, int index); + void removeDisplay(int index); + void changeDisplayByIndex(int index, bool force); /** @@ -100,7 +102,7 @@ public: * It will not set the Armature, if you want to add the bone to a Armature, you should use Armature::addBone(Bone *bone, const char* parentName). * * @param parent the parent bone. - * NULL : remove this bone from armature + * nullptr : remove this bone from armature */ void setParentBone(Bone *parent); @@ -122,10 +124,13 @@ public: */ void removeChildBone(Bone *bone, bool recursion); - void update(float delta); + void update(float delta) override; - void updateDisplayedColor(const cocos2d::Color3B &parentColor); - void updateDisplayedOpacity(GLubyte parentOpacity); + void updateDisplayedColor(const cocos2d::Color3B &parentColor) override; + void updateDisplayedOpacity(GLubyte parentOpacity) override; + + virtual void setColor(const cocos2d::Color3B& color) override; + virtual void setOpacity(GLubyte opacity) override; //! Update color to render display void updateColor(); @@ -133,62 +138,103 @@ public: //! Update zorder void updateZOrder(); - virtual void setZOrder(int zOrder); + virtual void setZOrder(int zOrder) override; Tween *getTween(); /* * Whether or not the bone's transform property changed. if true, the bone will update the transform. */ - virtual void setTransformDirty(bool dirty); - - virtual bool isTransformDirty(); + virtual void setTransformDirty(bool dirty) { _boneTransformDirty = dirty; } + virtual bool isTransformDirty() { return _boneTransformDirty; } virtual cocos2d::AffineTransform getNodeToArmatureTransform() const; virtual cocos2d::AffineTransform getNodeToWorldTransform() const override; Node *getDisplayRenderNode(); + DisplayType getDisplayRenderNodeType(); /* * Get the ColliderBody list in this bone. The object in the Array is ColliderBody. */ virtual cocos2d::Array *getColliderBodyList(); -public: + virtual void setColliderFilter(ColliderFilter *filter); + virtual ColliderFilter *getColliderFilter(); + + virtual void setBoneData(BoneData *boneData); + virtual BoneData *getBoneData() const; + + virtual void setArmature(Armature *armature); + virtual Armature *getArmature() const; + + virtual void setChildArmature(Armature *childArmature); + virtual Armature *getChildArmature() const; + + virtual DisplayManager *getDisplayManager() const { return _displayManager; } + + virtual void setIgnoreMovementBoneData(bool ignore) { _ignoreMovementBoneData = ignore; } + virtual bool isIgnoreMovementBoneData() const { return _ignoreMovementBoneData; } + + /* + * This function is deprecated, please use isIgnoreMovementBoneData() + */ + CC_DEPRECATED_ATTRIBUTE virtual bool getIgnoreMovementBoneData() const { return isIgnoreMovementBoneData(); } + + virtual void setBlendType(BlendType type) { _blendType = type; } + virtual BlendType getBlendType() const { return _blendType; } + + virtual FrameData *getTweenData() const { return _tweenData; } + + virtual void setName(const std::string &name) { _name = name; } + virtual const std::string getName() const { return _name; } + + virtual BaseData *getWorldInfo() const { return _worldInfo; } +protected: + void applyParentTransform(Bone *parent); + /* * The origin state of the Bone. Display's state is effected by _boneData, m_pNode, _tweenData * when call setData function, it will copy from the BoneData. */ - CC_PROPERTY(BoneData *, _boneData, BoneData); + BoneData *_boneData; //! A weak reference to the Armature - CC_PROPERTY(Armature *, _armature, Armature); + Armature *_armature; //! A weak reference to the child Armature - CC_PROPERTY(Armature *, _childArmature, ChildArmature); + Armature *_childArmature; - CC_SYNTHESIZE(DisplayManager *, _displayManager, DisplayManager) + DisplayManager *_displayManager; /* * When Armature play an animation, if there is not a MovementBoneData of this bone in this MovementData, this bone will be hidden. * Set IgnoreMovementBoneData to true, then this bone will also be shown. */ - CC_SYNTHESIZE(bool, _ignoreMovementBoneData, IgnoreMovementBoneData) + bool _ignoreMovementBoneData; + + BlendType _blendType; - CC_SYNTHESIZE(BlendType, _blendType, BlendType) -protected: Tween *_tween; //! Calculate tween effect //! Used for making tween effect in every frame - CC_SYNTHESIZE_READONLY(FrameData *, _tweenData, TweenData); + FrameData *_tweenData; - CC_SYNTHESIZE(std::string, _name, Name); + std::string _name; - Bone *_parentBone; //! A weak reference to its parent + Bone *_parentBone; //! A weak reference to its parent bool _boneTransformDirty; //! Whether or not transform dirty //! self Transform, use this to change display's state cocos2d::AffineTransform _worldTransform; + + BaseData *_worldInfo; + + //! Armature's parent bone + Bone *_armatureParentBone; + + //! Data version + float _dataVersion; }; } diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.cpp b/cocos/editor-support/cocostudio/CCColliderDetector.cpp index 0839a30d7a..35d1fe95f3 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.cpp +++ b/cocos/editor-support/cocostudio/CCColliderDetector.cpp @@ -37,33 +37,85 @@ using namespace cocos2d; namespace cocostudio { +#if ENABLE_PHYSICS_BOX2D_DETECT +ColliderFilter::ColliderFilter(unsigned short categoryBits, unsigned short maskBits, signed short groupIndex) + : _categoryBits(categoryBits) + , _maskBits(maskBits) + , _groupIndex(groupIndex) +{ +} + +void ColliderFilter::updateShape(b2Fixture *fixture) +{ + b2Filter filter; + filter.categoryBits = _categoryBits; + filter.groupIndex = _groupIndex; + filter.maskBits = _maskBits; + + fixture->SetFilterData(filter); +} + +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT +ColliderFilter::ColliderFilter(uintptr_t collisionType, uintptr_t group) + : _collisionType(collisionType) + , _group(group) +{ +} +void ColliderFilter::updateShape(cpShape *shape) +{ + shape->collision_type = _collisionType; + shape->group = _group; +} +#endif + #if ENABLE_PHYSICS_BOX2D_DETECT ColliderBody::ColliderBody(ContourData *contourData) - : _fixture(NULL) - , _filter(NULL) + : _fixture(nullptr) , _contourData(contourData) { CC_SAFE_RETAIN(_contourData); + _filter = new ColliderFilter(); + +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + _calculatedVertexList = Array::create(); + CC_SAFE_RETAIN(_calculatedVertexList); +#endif } #elif ENABLE_PHYSICS_CHIPMUNK_DETECT ColliderBody::ColliderBody(ContourData *contourData) - : _shape(NULL) + : _shape(nullptr) , _contourData(contourData) { CC_SAFE_RETAIN(_contourData); + _filter = new ColliderFilter(); + +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + _calculatedVertexList = Array::create(); + CC_SAFE_RETAIN(_calculatedVertexList); +#endif } #endif ColliderBody::~ColliderBody() { CC_SAFE_RELEASE(_contourData); - -#if ENABLE_PHYSICS_BOX2D_DETECT CC_SAFE_DELETE(_filter); + +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + CC_SAFE_RELEASE(_calculatedVertexList); #endif } +void ColliderBody::setColliderFilter(ColliderFilter *filter) +{ + *_filter = *filter; +} +ColliderFilter *ColliderBody::getColliderFilter() +{ + return _filter; +} + ColliderDetector *ColliderDetector::create() @@ -75,7 +127,7 @@ ColliderDetector *ColliderDetector::create() return pColliderDetector; } CC_SAFE_DELETE(pColliderDetector); - return NULL; + return nullptr; } ColliderDetector *ColliderDetector::create(Bone *bone) @@ -87,20 +139,22 @@ ColliderDetector *ColliderDetector::create(Bone *bone) return pColliderDetector; } CC_SAFE_DELETE(pColliderDetector); - return NULL; + return nullptr; } ColliderDetector::ColliderDetector() - : _colliderBodyList(NULL) + : _colliderBodyList(nullptr) + , _filter(nullptr) , _active(false) { - _body = NULL; + _body = nullptr; } ColliderDetector::~ColliderDetector() { _colliderBodyList->removeAllObjects(); CC_SAFE_DELETE(_colliderBodyList); + CC_SAFE_DELETE(_filter); } bool ColliderDetector::init() @@ -109,6 +163,8 @@ bool ColliderDetector::init() CCASSERT(_colliderBodyList, "create _colliderBodyList failed!"); _colliderBodyList->retain(); + _filter = new ColliderFilter(); + return true; } @@ -125,12 +181,24 @@ void ColliderDetector::addContourData(ContourData *contourData) ColliderBody *colliderBody = new ColliderBody(contourData); _colliderBodyList->addObject(colliderBody); colliderBody->release(); + + +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + CCArray *calculatedVertexList = colliderBody->getCalculatedVertexList(); + + int num = contourData->vertexList.count(); + for (int i = 0; i < num; i++) + { + ContourVertex2 *newVertex = new ContourVertex2(0, 0); + calculatedVertexList->addObject(newVertex); + newVertex->release(); + } +#endif } void ColliderDetector::addContourDataList(Array *contourDataList) { - Object *object = NULL; - CCARRAY_FOREACH(contourDataList, object) + for(auto object : *contourDataList) { addContourData((ContourData *)object); } @@ -138,8 +206,7 @@ void ColliderDetector::addContourDataList(Array *contourDataList) void ColliderDetector::removeContourData(ContourData *contourData) { - Object *object = NULL; - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *body = (ColliderBody*)object; if (body && body->getContourData() == contourData) @@ -173,40 +240,41 @@ void ColliderDetector::setActive(bool active) } else { - Object *object = NULL; - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *colliderBody = (ColliderBody *)object; b2Fixture *fixture = colliderBody->getB2Fixture(); - b2Filter *filter = colliderBody->getB2Filter(); - *filter = fixture->GetFilterData(); - _body->DestroyFixture(fixture); - colliderBody->setB2Fixture(NULL); + colliderBody->setB2Fixture(nullptr); } } } #elif ENABLE_PHYSICS_CHIPMUNK_DETECT if (_body) { - Object *object = NULL; if (_active) { - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *colliderBody = (ColliderBody *)object; cpShape *shape = colliderBody->getShape(); - cpSpaceAddShape(_body->space_private, shape); + if(shape->space_private == nullptr) + { + cpSpaceAddShape(_body->space_private, shape); + } } } else { - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *colliderBody = (ColliderBody *)object; cpShape *shape = colliderBody->getShape(); - cpSpaceRemoveShape(_body->space_private, shape); + if (shape->space_private != nullptr) + { + cpSpaceRemoveShape(_body->space_private, shape); + } } } } @@ -223,6 +291,33 @@ Array *ColliderDetector::getColliderBodyList() return _colliderBodyList; } +void ColliderDetector::setColliderFilter(ColliderFilter *filter) +{ + *_filter = *filter; + + for(auto object : *_colliderBodyList) + { + ColliderBody *colliderBody = (ColliderBody *)object; + colliderBody->setColliderFilter(filter); + +#if ENABLE_PHYSICS_BOX2D_DETECT + if (colliderBody->getB2Fixture()) + { + colliderBody->getColliderFilter()->updateShape(colliderBody->getB2Fixture()); + } +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT + if (colliderBody->getShape()) + { + colliderBody->getColliderFilter()->updateShape(colliderBody->getShape()); + } +#endif + } +} +ColliderFilter *ColliderDetector::getColliderFilter() +{ + return _filter; +} + Point helpPoint; @@ -233,21 +328,20 @@ void ColliderDetector::updateTransform(AffineTransform &t) return; } - Object *object = NULL; - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *colliderBody = (ColliderBody *)object; ContourData *contourData = colliderBody->getContourData(); #if ENABLE_PHYSICS_BOX2D_DETECT - b2PolygonShape *shape = NULL; - if (_body != NULL) + b2PolygonShape *shape = nullptr; + if (_body != nullptr) { shape = (b2PolygonShape *)colliderBody->getB2Fixture()->GetShape(); } #elif ENABLE_PHYSICS_CHIPMUNK_DETECT - cpPolyShape *shape = NULL; - if (_body != NULL) + cpPolyShape *shape = nullptr; + if (_body != nullptr) { shape = (cpPolyShape *)colliderBody->getShape(); } @@ -256,20 +350,29 @@ void ColliderDetector::updateTransform(AffineTransform &t) int num = contourData->vertexList.count(); ContourVertex2 **vs = (ContourVertex2 **)contourData->vertexList.data->arr; +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + ContourVertex2 **cvs = (ContourVertex2 **)colliderBody->getCalculatedVertexList()->data->arr; +#endif + for (int i = 0; i < num; i++) { helpPoint.setPoint( vs[i]->x, vs[i]->y); helpPoint = PointApplyAffineTransform(helpPoint, t); +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + cvs[i]->x = helpPoint.x; + cvs[i]->y = helpPoint.y; +#endif + #if ENABLE_PHYSICS_BOX2D_DETECT - if (shape != NULL) + if (shape != nullptr) { b2Vec2 &bv = shape->m_vertices[i]; bv.Set(helpPoint.x / PT_RATIO, helpPoint.y / PT_RATIO); } #elif ENABLE_PHYSICS_CHIPMUNK_DETECT - if (shape != NULL) + if (shape != nullptr) { cpVect v ; v.x = helpPoint.x; @@ -280,7 +383,7 @@ void ColliderDetector::updateTransform(AffineTransform &t) } #if ENABLE_PHYSICS_CHIPMUNK_DETECT - cpConvexHull(num, shape->verts, NULL, NULL, 0); + cpConvexHull(num, shape->verts, nullptr, nullptr, 0); for (int i = 0; i < num; i++) { cpVect b = shape->verts[(i + 1) % shape->numVerts]; @@ -299,19 +402,18 @@ void ColliderDetector::setBody(b2Body *pBody) { _body = pBody; - Object *object = NULL; - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *colliderBody = (ColliderBody *)object; ContourData *contourData = colliderBody->getContourData(); const Array *array = &contourData->vertexList; - Object *object = NULL; + Object *object = nullptr; b2Vec2 *b2bv = new b2Vec2[contourData->vertexList.count()]; int i = 0; - CCARRAY_FOREACH(array, object) + for(auto object : *array) { ContourVertex2 *v = (ContourVertex2 *)object; b2bv[i].Set(v->x / PT_RATIO, v->y / PT_RATIO); @@ -330,25 +432,17 @@ void ColliderDetector::setBody(b2Body *pBody) b2Fixture *fixture = _body->CreateFixture(&fixtureDef); fixture->SetUserData(_bone); - if (colliderBody->getB2Fixture() != NULL) + if (colliderBody->getB2Fixture() != nullptr) { _body->DestroyFixture(colliderBody->getB2Fixture()); } colliderBody->setB2Fixture(fixture); - if (colliderBody->getB2Filter() == NULL) - { - b2Filter *filter = new b2Filter; - colliderBody->setB2Filter(filter); - } - else - { - fixture->SetFilterData(*colliderBody->getB2Filter()); - } + colliderBody->getColliderFilter()->updateShape(fixture); } } -b2Body *ColliderDetector::getBody() +b2Body *ColliderDetector::getBody() const { return _body; } @@ -358,8 +452,7 @@ void ColliderDetector::setBody(cpBody *pBody) { _body = pBody; - Object *object = NULL; - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *colliderBody = (ColliderBody *)object; @@ -378,15 +471,20 @@ void ColliderDetector::setBody(cpBody *pBody) shape->sensor = true; shape->data = _bone; - cpSpaceAddShape(_body->space_private, shape); + + if (_active) + { + cpSpaceAddShape(_body->space_private, shape); + } colliderBody->setShape(shape); + colliderBody->getColliderFilter()->updateShape(shape); delete []verts; } } -cpBody *ColliderDetector::getBody() +cpBody *ColliderDetector::getBody() const { return _body; } diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.h b/cocos/editor-support/cocostudio/CCColliderDetector.h index 4f6fbeebfe..2737980f60 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.h +++ b/cocos/editor-support/cocostudio/CCColliderDetector.h @@ -33,38 +33,93 @@ THE SOFTWARE. #endif +#if ENABLE_PHYSICS_CHIPMUNK_DETECT +struct cpBody; +struct cpShape; +#elif ENABLE_PHYSICS_BOX2D_DETECT class b2Body; class b2Fixture; struct b2Filter; - -struct cpBody; -struct cpShape; +#endif namespace cocostudio { class Bone; -class ColliderBody : public cocos2d::Object + +class ColliderFilter { public: + ~ColliderFilter() { } #if ENABLE_PHYSICS_BOX2D_DETECT - CC_SYNTHESIZE(b2Fixture *, _fixture, B2Fixture) - CC_SYNTHESIZE(b2Filter *, _filter, B2Filter) +public: + ColliderFilter(unsigned short categoryBits = 0x0001, unsigned short maskBits = 0xFFFF, signed short groupIndex = 0); + void updateShape(b2Fixture *fixture); + virtual void setCategoryBits(unsigned short categoryBits) { _categoryBits = categoryBits; } + virtual unsigned short getCategoryBits() const { return _categoryBits; } + + virtual void setMaskBits(unsigned short maskBits) { _maskBits = maskBits; } + virtual unsigned short getMaskBits() const { return _maskBits; } + + virtual void setGroupIndex(signed short groupIndex) { _groupIndex = groupIndex; } + virtual signed short getGroupIndex() const { return _groupIndex; } +protected: + unsigned short _categoryBits; + unsigned short _maskBits; + signed short _groupIndex; #elif ENABLE_PHYSICS_CHIPMUNK_DETECT - CC_SYNTHESIZE(cpShape *, _shape, Shape) -#endif +public: + ColliderFilter(uintptr_t collisionType = 0, uintptr_t group = 0); + void updateShape(cpShape *shape); + virtual void setCollisionType(uintptr_t collisionType) { _collisionType = collisionType; } + virtual uintptr_t getCollisionType() const { return _collisionType; } + + virtual void setGroup(uintptr_t group) { _group = group; } + virtual uintptr_t getGroup() const { return _group; } +protected: + uintptr_t _collisionType; + uintptr_t _group; +#endif +}; + +class ColliderBody : public cocos2d::Object +{ public: ColliderBody(ContourData *contourData); ~ColliderBody(); - inline ContourData *getContourData() - { - return _contourData; - } + inline ContourData *getContourData() { return _contourData; } + + void setColliderFilter(ColliderFilter *filter); + ColliderFilter *getColliderFilter(); + +#if ENABLE_PHYSICS_BOX2D_DETECT + virtual void setB2Fixture(b2Fixture *fixture) { _fixture = fixture; } + virtual b2Fixture *getB2Fixture() const { return _fixture; } +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT + virtual void setShape(cpShape *shape) { _shape = shape; } + virtual cpShape *getShape() const { return _shape; } +#endif + +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + virtual const cocos2d::Array *getCalculatedVertexList() const { return _calculatedVertexList; } +#endif private: + +#if ENABLE_PHYSICS_BOX2D_DETECT + b2Fixture *_fixture; +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT + cpShape *_shape; +#endif + ContourData *_contourData; + ColliderFilter *_filter; + +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + cocos2d::Array *_calculatedVertexList; +#endif }; /* @@ -102,14 +157,29 @@ public: cocos2d::Array *getColliderBodyList(); -protected: - cocos2d::Array *_colliderBodyList; - CC_SYNTHESIZE(Bone *, _bone, Bone); + virtual void setColliderFilter(ColliderFilter *filter); + virtual ColliderFilter *getColliderFilter(); + + virtual void setBone(Bone *bone) { _bone = bone; } + virtual Bone *getBone() const { return _bone; } #if ENABLE_PHYSICS_BOX2D_DETECT - CC_PROPERTY(b2Body *, _body, Body); + virtual void setBody(b2Body *body); + virtual b2Body *getBody() const; #elif ENABLE_PHYSICS_CHIPMUNK_DETECT - CC_PROPERTY(cpBody *, _body, Body); + virtual void setBody(cpBody *body); + virtual cpBody *getBody() const; +#endif + protected: + cocos2d::Array *_colliderBodyList; + ColliderFilter *_filter; + + Bone *_bone; + +#if ENABLE_PHYSICS_BOX2D_DETECT + b2Body *_body; +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT + cpBody *_body; #endif protected: diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index 4749f5eaf9..17f10067ed 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -133,26 +133,24 @@ static const char *VERTEX_POINT = "vertex"; static const char *COLOR_INFO = "color"; static const char *CONFIG_FILE_PATH = "config_file_path"; - +static const char *CONTENT_SCALE = "content_scale"; namespace cocostudio { - std::vector s_arrConfigFileList; + float s_PositionReadScale = 1; -static float s_FlashToolVersion = VERSION_2_0; -static float s_CocoStudioVersion = VERSION_COMBINED; -static std::string s_BasefilePath = ""; +std::vector DataReaderHelper::_configFileList; -DataReaderHelper *DataReaderHelper::_dataReaderHelper = NULL; +DataReaderHelper *DataReaderHelper::_dataReaderHelper = nullptr; //! Async load void DataReaderHelper::loadData() { - AsyncStruct *pAsyncStruct = NULL; + AsyncStruct *pAsyncStruct = nullptr; while (true) { @@ -183,9 +181,11 @@ void DataReaderHelper::loadData() _asyncStructQueueMutex.unlock(); } - // generate image info + // generate data info DataInfo *pDataInfo = new DataInfo(); pDataInfo->asyncStruct = pAsyncStruct; + pDataInfo->filename = pAsyncStruct->filename; + pDataInfo->baseFilePath = pAsyncStruct->baseFilePath; if (pAsyncStruct->configType == DragonBone_XML) { @@ -202,12 +202,12 @@ void DataReaderHelper::loadData() _dataInfoMutex.unlock(); } - if( _asyncStructQueue != NULL ) + if( _asyncStructQueue != nullptr ) { delete _asyncStructQueue; - _asyncStructQueue = NULL; + _asyncStructQueue = nullptr; delete _dataQueue; - _dataQueue = NULL; + _dataQueue = nullptr; } } @@ -235,14 +235,10 @@ float DataReaderHelper::getPositionReadScale() void DataReaderHelper::purge() { - DataReaderHelper::clear(); + _configFileList.clear(); CC_SAFE_RELEASE_NULL(_dataReaderHelper); } -void DataReaderHelper::clear() -{ - s_arrConfigFileList.clear(); -} DataReaderHelper::DataReaderHelper() : _loadingThread(nullptr) @@ -263,7 +259,7 @@ DataReaderHelper::~DataReaderHelper() if (_loadingThread) _loadingThread->join(); CC_SAFE_DELETE(_loadingThread); - _dataReaderHelper = NULL; + _dataReaderHelper = nullptr; } void DataReaderHelper::addDataFromFile(const char *filePath) @@ -271,26 +267,27 @@ void DataReaderHelper::addDataFromFile(const char *filePath) /* * Check if file is already added to ArmatureDataManager, if then return. */ - for(unsigned int i = 0; i < s_arrConfigFileList.size(); i++) + for(unsigned int i = 0; i < _configFileList.size(); i++) { - if (s_arrConfigFileList[i].compare(filePath) == 0) + if (_configFileList[i].compare(filePath) == 0) { return; } } - s_arrConfigFileList.push_back(filePath); + _configFileList.push_back(filePath); //! find the base file path - s_BasefilePath = filePath; - size_t pos = s_BasefilePath.find_last_of("/"); + std::string basefilePath = filePath; + size_t pos = basefilePath.find_last_of("/"); + if (pos != std::string::npos) { - s_BasefilePath = s_BasefilePath.substr(0, pos + 1); + basefilePath = basefilePath.substr(0, pos + 1); } else { - s_BasefilePath = ""; + basefilePath = ""; } @@ -298,28 +295,33 @@ void DataReaderHelper::addDataFromFile(const char *filePath) size_t startPos = filePathStr.find_last_of("."); std::string str = &filePathStr[startPos]; - unsigned long size; + long size; std::string fullPath = CCFileUtils::getInstance()->fullPathForFilename(filePath); const char *pFileContent = (char *)CCFileUtils::getInstance()->getFileData(fullPath.c_str() , "r", &size); + DataInfo dataInfo; + dataInfo.filename = filePathStr; + dataInfo.asyncStruct = nullptr; + dataInfo.baseFilePath = basefilePath; + if (str.compare(".xml") == 0) { - DataReaderHelper::addDataFromCache(pFileContent); + DataReaderHelper::addDataFromCache(pFileContent, &dataInfo); } else if(str.compare(".json") == 0 || str.compare(".ExportJson") == 0) { - DataReaderHelper::addDataFromJsonCache(pFileContent); + DataReaderHelper::addDataFromJsonCache(pFileContent, &dataInfo); } } -void DataReaderHelper::addDataFromFileAsync(const char *filePath, Object *target, SEL_SCHEDULE selector) +void DataReaderHelper::addDataFromFileAsync(const char *imagePath, const char *plistPath, const char *filePath, Object *target, SEL_SCHEDULE selector) { /* * Check if file is already added to ArmatureDataManager, if then return. */ - for(unsigned int i = 0; i < s_arrConfigFileList.size(); i++) + for(unsigned int i = 0; i < _configFileList.size(); i++) { - if (s_arrConfigFileList[i].compare(filePath) == 0) + if (_configFileList[i].compare(filePath) == 0) { if (target && selector) { @@ -335,23 +337,24 @@ void DataReaderHelper::addDataFromFileAsync(const char *filePath, Object *target return; } } - s_arrConfigFileList.push_back(filePath); + _configFileList.push_back(filePath); //! find the base file path - s_BasefilePath = filePath; - size_t pos = s_BasefilePath.find_last_of("/"); + std::string basefilePath = filePath; + size_t pos = basefilePath.find_last_of("/"); + if (pos != std::string::npos) { - s_BasefilePath = s_BasefilePath.substr(0, pos + 1); + basefilePath = basefilePath.substr(0, pos + 1); } else { - s_BasefilePath = ""; + basefilePath = ""; } // lazy init - if (_asyncStructQueue == NULL) + if (_asyncStructQueue == nullptr) { _asyncStructQueue = new std::queue(); _dataQueue = new std::queue(); @@ -378,18 +381,20 @@ void DataReaderHelper::addDataFromFileAsync(const char *filePath, Object *target // generate async struct AsyncStruct *data = new AsyncStruct(); data->filename = filePath; - data->baseFilePath = s_BasefilePath; + data->baseFilePath = basefilePath; data->target = target; data->selector = selector; data->autoLoadSpriteFile = ArmatureDataManager::getInstance()->isAutoLoadSpriteFile(); + data->imagePath = imagePath; + data->plistPath = plistPath; std::string filePathStr = filePath; size_t startPos = filePathStr.find_last_of("."); std::string str = &filePathStr[startPos]; std::string fullPath = CCFileUtils::getInstance()->fullPathForFilename(filePath); - unsigned long size; + long size; data->fileContent = (char *)CCFileUtils::getInstance()->getFileData(fullPath.c_str() , "r", &size); if (str.compare(".xml") == 0) @@ -428,10 +433,20 @@ void DataReaderHelper::addDataAsyncCallBack(float dt) AsyncStruct *pAsyncStruct = pDataInfo->asyncStruct; + + if (pAsyncStruct->imagePath != "" && pAsyncStruct->plistPath != "") + { + _getFileMutex.lock(); + ArmatureDataManager::getInstance()->addSpriteFrameFromFile(pAsyncStruct->plistPath.c_str(), pAsyncStruct->imagePath.c_str()); + _getFileMutex.unlock(); + } + while (!pDataInfo->configFileQueue.empty()) { std::string configPath = pDataInfo->configFileQueue.front(); + _getFileMutex.lock(); ArmatureDataManager::getInstance()->addSpriteFrameFromFile((pAsyncStruct->baseFilePath + configPath + ".plist").c_str(), (pAsyncStruct->baseFilePath + configPath + ".png").c_str()); + _getFileMutex.unlock(); pDataInfo->configFileQueue.pop(); } @@ -460,7 +475,22 @@ void DataReaderHelper::addDataAsyncCallBack(float dt) } +void DataReaderHelper::removeConfigFile(const char *configFile) +{ + std::vector::iterator it = _configFileList.end(); + for (std::vector::iterator i = _configFileList.begin(); i != _configFileList.end(); i++) + { + if (*i == configFile) + { + it = i; + } + } + if (it != _configFileList.end()) + { + _configFileList.erase(it); + } +} @@ -472,7 +502,7 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data tinyxml2::XMLElement *root = document.RootElement(); CCASSERT(root, "XML error or XML is empty."); - root->QueryFloatAttribute(VERSION, &s_FlashToolVersion); + root->QueryFloatAttribute(VERSION, &dataInfo->flashToolVersion); /* @@ -482,15 +512,15 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data tinyxml2::XMLElement *armatureXML = armaturesXML->FirstChildElement(ARMATURE); while(armatureXML) { - ArmatureData *armatureData = DataReaderHelper::decodeArmature(armatureXML); + ArmatureData *armatureData = DataReaderHelper::decodeArmature(armatureXML, dataInfo); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.lock(); } - ArmatureDataManager::getInstance()->addArmatureData(armatureData->name.c_str(), armatureData); + ArmatureDataManager::getInstance()->addArmatureData(armatureData->name.c_str(), armatureData, dataInfo->filename.c_str()); armatureData->release(); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.unlock(); } @@ -506,14 +536,14 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data tinyxml2::XMLElement *animationXML = animationsXML->FirstChildElement(ANIMATION); while(animationXML) { - AnimationData *animationData = DataReaderHelper::decodeAnimation(animationXML); - if (dataInfo) + AnimationData *animationData = DataReaderHelper::decodeAnimation(animationXML, dataInfo); + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.lock(); } - ArmatureDataManager::getInstance()->addAnimationData(animationData->name.c_str(), animationData); + ArmatureDataManager::getInstance()->addAnimationData(animationData->name.c_str(), animationData, dataInfo->filename.c_str()); animationData->release(); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.unlock(); } @@ -528,15 +558,15 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data tinyxml2::XMLElement *textureXML = texturesXML->FirstChildElement(SUB_TEXTURE); while(textureXML) { - TextureData *textureData = DataReaderHelper::decodeTexture(textureXML); + TextureData *textureData = DataReaderHelper::decodeTexture(textureXML, dataInfo); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.lock(); } - ArmatureDataManager::getInstance()->addTextureData(textureData->name.c_str(), textureData); + ArmatureDataManager::getInstance()->addTextureData(textureData->name.c_str(), textureData, dataInfo->filename.c_str()); textureData->release(); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.unlock(); } @@ -544,13 +574,12 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data } } -ArmatureData *DataReaderHelper::decodeArmature(tinyxml2::XMLElement *armatureXML) +ArmatureData *DataReaderHelper::decodeArmature(tinyxml2::XMLElement *armatureXML, DataInfo *dataInfo) { ArmatureData *armatureData = new ArmatureData(); armatureData->init(); - const char *name = armatureXML->Attribute(A_NAME); - armatureData->name = name; + armatureData->name = armatureXML->Attribute(A_NAME); tinyxml2::XMLElement *boneXML = armatureXML->FirstChildElement(BONE); @@ -561,7 +590,7 @@ ArmatureData *DataReaderHelper::decodeArmature(tinyxml2::XMLElement *armatureXML * If this bone have parent, then get the parent bone xml */ const char *parentName = boneXML->Attribute(A_PARENT); - tinyxml2::XMLElement *parentXML = NULL; + tinyxml2::XMLElement *parentXML = nullptr; if (parentName) { parentXML = armatureXML->FirstChildElement(BONE); @@ -576,7 +605,7 @@ ArmatureData *DataReaderHelper::decodeArmature(tinyxml2::XMLElement *armatureXML } } - BoneData *boneData = decodeBone(boneXML, parentXML); + BoneData *boneData = decodeBone(boneXML, parentXML, dataInfo); armatureData->addBoneData(boneData); boneData->release(); @@ -586,7 +615,7 @@ ArmatureData *DataReaderHelper::decodeArmature(tinyxml2::XMLElement *armatureXML return armatureData; } -BoneData *DataReaderHelper::decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2::XMLElement *parentXml) +BoneData *DataReaderHelper::decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2::XMLElement *parentXml, DataInfo *dataInfo) { BoneData *boneData = new BoneData(); boneData->init(); @@ -594,7 +623,7 @@ BoneData *DataReaderHelper::decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2:: std::string name = boneXML->Attribute(A_NAME); boneData->name = name; - if( boneXML->Attribute(A_PARENT) != NULL ) + if( boneXML->Attribute(A_PARENT) != nullptr ) { boneData->parentName = boneXML->Attribute(A_PARENT); } @@ -604,7 +633,7 @@ BoneData *DataReaderHelper::decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2:: tinyxml2::XMLElement *displayXML = boneXML->FirstChildElement(DISPLAY); while(displayXML) { - DisplayData *displayData = decodeBoneDisplay(displayXML); + DisplayData *displayData = decodeBoneDisplay(displayXML, dataInfo); boneData->addDisplayData(displayData); displayData->release(); @@ -614,7 +643,7 @@ BoneData *DataReaderHelper::decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2:: return boneData; } -DisplayData *DataReaderHelper::decodeBoneDisplay(tinyxml2::XMLElement *displayXML) +DisplayData *DataReaderHelper::decodeBoneDisplay(tinyxml2::XMLElement *displayXML, DataInfo *dataInfo) { int _isArmature = 0; @@ -641,7 +670,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(tinyxml2::XMLElement *displayXM } - if(displayXML->Attribute(A_NAME) != NULL ) + if(displayXML->Attribute(A_NAME) != nullptr ) { if(!_isArmature) { @@ -657,7 +686,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(tinyxml2::XMLElement *displayXM return displayData; } -AnimationData *DataReaderHelper::decodeAnimation(tinyxml2::XMLElement *animationXML) +AnimationData *DataReaderHelper::decodeAnimation(tinyxml2::XMLElement *animationXML, DataInfo *dataInfo) { AnimationData *aniData = new AnimationData(); @@ -671,7 +700,7 @@ AnimationData *DataReaderHelper::decodeAnimation(tinyxml2::XMLElement *animation while( movementXML ) { - MovementData *movementData = decodeMovement(movementXML, armatureData); + MovementData *movementData = decodeMovement(movementXML, armatureData, dataInfo); aniData->addMovement(movementData); movementData->release(); @@ -682,7 +711,7 @@ AnimationData *DataReaderHelper::decodeAnimation(tinyxml2::XMLElement *animation return aniData; } -MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML, ArmatureData *armatureData) +MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML, ArmatureData *armatureData, DataInfo *dataInfo) { MovementData *movementData = new MovementData(); @@ -710,19 +739,19 @@ MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML } const char *_easing = movementXML->Attribute(A_TWEEN_EASING); - if(_easing != NULL) + if(_easing != nullptr) { std::string str = _easing; if(str.compare(FL_NAN) != 0) { if( movementXML->QueryIntAttribute(A_TWEEN_EASING, &(tweenEasing)) == tinyxml2::XML_SUCCESS) { - movementData->tweenEasing = (CCTweenType)tweenEasing; + movementData->tweenEasing = tweenEasing == 2 ? Sine_EaseInOut : (TweenType)tweenEasing; } } else { - movementData->tweenEasing = TWEEN_EASING_MAX; + movementData->tweenEasing = Linear; } } @@ -743,7 +772,7 @@ MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML std::string parentName = boneData->parentName; - tinyxml2::XMLElement *parentXml = NULL; + tinyxml2::XMLElement *parentXml = nullptr; if (parentName.length() != 0) { parentXml = movementXML->FirstChildElement(BONE); @@ -758,7 +787,7 @@ MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML } } - MovementBoneData *moveBoneData = decodeMovementBone(movBoneXml, parentXml, boneData); + MovementBoneData *moveBoneData = decodeMovementBone(movBoneXml, parentXml, boneData, dataInfo); movementData->addMovementBoneData(moveBoneData); moveBoneData->release(); @@ -769,7 +798,7 @@ MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML } -MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *movBoneXml, tinyxml2::XMLElement *parentXml, BoneData *boneData) +MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *movBoneXml, tinyxml2::XMLElement *parentXml, BoneData *boneData, DataInfo *dataInfo) { MovementBoneData *movBoneData = new MovementBoneData(); movBoneData->init(); @@ -797,14 +826,14 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov int parentTotalDuration = 0; int currentDuration = 0; - tinyxml2::XMLElement *parentFrameXML = NULL; + tinyxml2::XMLElement *parentFrameXML = nullptr; std::vector parentXmlList; /* * get the parent frame xml list, we need get the origin data */ - if( parentXml != NULL ) + if( parentXml != nullptr ) { parentFrameXML = parentXml->FirstChildElement(FRAME); while (parentFrameXML) @@ -813,7 +842,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov parentFrameXML = parentFrameXML->NextSiblingElement(FRAME); } - parentFrameXML = NULL; + parentFrameXML = nullptr; length = parentXmlList.size(); } @@ -844,7 +873,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov } } - FrameData *frameData = decodeFrame( frameXML, parentFrameXML, boneData); + FrameData *frameData = decodeFrame( frameXML, parentFrameXML, boneData, dataInfo); movBoneData->addFrameData(frameData); frameData->release(); @@ -858,21 +887,21 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov //! Change rotation range from (-180 -- 180) to (-infinity -- infinity) FrameData **frames = (FrameData **)movBoneData->frameList.data->arr; - for (int i = movBoneData->frameList.count() - 1; i >= 0; i--) + for (int j = movBoneData->frameList.count() - 1; j >= 0; j--) { - if (i > 0) + if (j > 0) { - float difSkewX = frames[i]->skewX - frames[i - 1]->skewX; - float difSkewY = frames[i]->skewY - frames[i - 1]->skewY; + float difSkewX = frames[j]->skewX - frames[j - 1]->skewX; + float difSkewY = frames[j]->skewY - frames[j - 1]->skewY; if (difSkewX < -M_PI || difSkewX > M_PI) { - frames[i - 1]->skewX = difSkewX < 0 ? frames[i - 1]->skewX - 2 * M_PI : frames[i - 1]->skewX + 2 * M_PI; + frames[j - 1]->skewX = difSkewX < 0 ? frames[j - 1]->skewX - 2 * M_PI : frames[j - 1]->skewX + 2 * M_PI; } if (difSkewY < -M_PI || difSkewY > M_PI) { - frames[i - 1]->skewY = difSkewY < 0 ? frames[i - 1]->skewY - 2 * M_PI : frames[i - 1]->skewY + 2 * M_PI; + frames[j - 1]->skewY = difSkewY < 0 ? frames[j - 1]->skewY - 2 * M_PI : frames[j - 1]->skewY + 2 * M_PI; } } } @@ -888,33 +917,33 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov return movBoneData; } -FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxml2::XMLElement *parentFrameXml, BoneData *boneData) +FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxml2::XMLElement *parentFrameXml, BoneData *boneData, DataInfo *dataInfo) { float x, y, scale_x, scale_y, skew_x, skew_y = 0; int duration, displayIndex, zOrder, tweenEasing, blendType = 0; FrameData *frameData = new FrameData(); - if(frameXML->Attribute(A_MOVEMENT) != NULL) + if(frameXML->Attribute(A_MOVEMENT) != nullptr) { frameData->strMovement = frameXML->Attribute(A_MOVEMENT); } - if(frameXML->Attribute(A_EVENT) != NULL) + if(frameXML->Attribute(A_EVENT) != nullptr) { frameData->strEvent = frameXML->Attribute(A_EVENT); } - if(frameXML->Attribute(A_SOUND) != NULL) + if(frameXML->Attribute(A_SOUND) != nullptr) { frameData->strSound = frameXML->Attribute(A_SOUND); } - if(frameXML->Attribute(A_SOUND_EFFECT) != NULL) + if(frameXML->Attribute(A_SOUND_EFFECT) != nullptr) { frameData->strSoundEffect = frameXML->Attribute(A_SOUND_EFFECT); } - if (s_FlashToolVersion >= VERSION_2_0) + if (dataInfo->flashToolVersion >= VERSION_2_0) { if(frameXML->QueryFloatAttribute(A_COCOS2DX_X, &x) == tinyxml2::XML_SUCCESS) { @@ -1000,19 +1029,19 @@ FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxm const char *_easing = frameXML->Attribute(A_TWEEN_EASING); - if(_easing != NULL) + if(_easing != nullptr) { std::string str = _easing; if(str.compare(FL_NAN) != 0) { if( frameXML->QueryIntAttribute(A_TWEEN_EASING, &(tweenEasing)) == tinyxml2::XML_SUCCESS) { - frameData->tweenEasing = (CCTweenType)tweenEasing; + frameData->tweenEasing = tweenEasing == 2 ? Sine_EaseInOut : (TweenType)tweenEasing; } } else { - frameData->tweenEasing = TWEEN_EASING_MAX; + frameData->tweenEasing = Linear; } } @@ -1022,7 +1051,7 @@ FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxm * recalculate frame data from parent frame data, use for translate matrix */ BaseData helpNode; - if (s_FlashToolVersion >= VERSION_2_0) + if (dataInfo->flashToolVersion >= VERSION_2_0) { parentFrameXml->QueryFloatAttribute(A_COCOS2DX_X, &helpNode.x); parentFrameXml->QueryFloatAttribute(A_COCOS2DX_Y, &helpNode.y); @@ -1046,19 +1075,19 @@ FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxm return frameData; } -TextureData *DataReaderHelper::decodeTexture(tinyxml2::XMLElement *textureXML) +TextureData *DataReaderHelper::decodeTexture(tinyxml2::XMLElement *textureXML, DataInfo *dataInfo) { TextureData *textureData = new TextureData(); textureData->init(); - if( textureXML->Attribute(A_NAME) != NULL) + if( textureXML->Attribute(A_NAME) != nullptr) { textureData->name = textureXML->Attribute(A_NAME); } float px, py, width, height = 0; - if(s_FlashToolVersion >= VERSION_2_0) + if(dataInfo->flashToolVersion >= VERSION_2_0) { textureXML->QueryFloatAttribute(A_COCOS2D_PIVOT_X, &px); textureXML->QueryFloatAttribute(A_COCOS2D_PIVOT_Y, &py); @@ -1082,7 +1111,7 @@ TextureData *DataReaderHelper::decodeTexture(tinyxml2::XMLElement *textureXML) while (contourXML) { - ContourData *contourData = decodeContour(contourXML); + ContourData *contourData = decodeContour(contourXML, dataInfo); textureData->addContourData(contourData); contourData->release(); @@ -1092,7 +1121,7 @@ TextureData *DataReaderHelper::decodeTexture(tinyxml2::XMLElement *textureXML) return textureData; } -ContourData *DataReaderHelper::decodeContour(tinyxml2::XMLElement *contourXML) +ContourData *DataReaderHelper::decodeContour(tinyxml2::XMLElement *contourXML, DataInfo *dataInfo) { ContourData *contourData = new ContourData(); contourData->init(); @@ -1123,20 +1152,22 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d JsonDictionary json; json.initWithDescription(fileContent); + dataInfo->contentScale = json.getItemFloatValue(CONTENT_SCALE, 1); + // Decode armatures int length = json.getArrayItemCount(ARMATURE_DATA); for (int i = 0; i < length; i++) { JsonDictionary *armatureDic = json.getSubItemFromArray(ARMATURE_DATA, i); - ArmatureData *armatureData = decodeArmature(*armatureDic); + ArmatureData *armatureData = decodeArmature(*armatureDic, dataInfo); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.lock(); } ArmatureDataManager::getInstance()->addArmatureData(armatureData->name.c_str(), armatureData); armatureData->release(); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.unlock(); } @@ -1148,15 +1179,15 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d for (int i = 0; i < length; i++) { JsonDictionary *animationDic = json.getSubItemFromArray(ANIMATION_DATA, i); - AnimationData *animationData = decodeAnimation(*animationDic); + AnimationData *animationData = decodeAnimation(*animationDic, dataInfo); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.lock(); } ArmatureDataManager::getInstance()->addAnimationData(animationData->name.c_str(), animationData); animationData->release(); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.unlock(); } @@ -1170,13 +1201,13 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d JsonDictionary *textureDic = json.getSubItemFromArray(TEXTURE_DATA, i); TextureData *textureData = decodeTexture(*textureDic); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.lock(); } ArmatureDataManager::getInstance()->addTextureData(textureData->name.c_str(), textureData); textureData->release(); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.unlock(); } @@ -1184,14 +1215,14 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d } // Auto load sprite file - bool autoLoad = dataInfo == NULL ? ArmatureDataManager::getInstance()->isAutoLoadSpriteFile() : dataInfo->asyncStruct->autoLoadSpriteFile; + bool autoLoad = dataInfo->asyncStruct == nullptr ? ArmatureDataManager::getInstance()->isAutoLoadSpriteFile() : dataInfo->asyncStruct->autoLoadSpriteFile; if (autoLoad) { length = json.getArrayItemCount(CONFIG_FILE_PATH); for (int i = 0; i < length; i++) { const char *path = json.getStringValueFromArray(CONFIG_FILE_PATH, i); - if (path == NULL) + if (path == nullptr) { CCLOG("load CONFIG_FILE_PATH error."); return; @@ -1200,7 +1231,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d std::string filePath = path; filePath = filePath.erase(filePath.find_last_of(".")); - if (dataInfo != NULL) + if (dataInfo->asyncStruct) { dataInfo->configFileQueue.push(filePath); } @@ -1209,30 +1240,30 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d std::string plistPath = filePath + ".plist"; std::string pngPath = filePath + ".png"; - ArmatureDataManager::getInstance()->addSpriteFrameFromFile((s_BasefilePath + plistPath).c_str(), (s_BasefilePath + pngPath).c_str()); + ArmatureDataManager::getInstance()->addSpriteFrameFromFile((dataInfo->baseFilePath + plistPath).c_str(), (dataInfo->baseFilePath + pngPath).c_str()); } } } } -ArmatureData *DataReaderHelper::decodeArmature(JsonDictionary &json) +ArmatureData *DataReaderHelper::decodeArmature(JsonDictionary &json, DataInfo *dataInfo) { ArmatureData *armatureData = new ArmatureData(); armatureData->init(); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { armatureData->name = name; } - s_CocoStudioVersion = armatureData->dataVersion = json.getItemFloatValue(VERSION, 0.1f); + dataInfo->cocoStudioVersion = armatureData->dataVersion = json.getItemFloatValue(VERSION, 0.1f); int length = json.getArrayItemCount(BONE_DATA); for (int i = 0; i < length; i++) { JsonDictionary *dic = json.getSubItemFromArray(BONE_DATA, i); - BoneData *boneData = decodeBone(*dic); + BoneData *boneData = decodeBone(*dic, dataInfo); armatureData->addBoneData(boneData); boneData->release(); @@ -1242,21 +1273,21 @@ ArmatureData *DataReaderHelper::decodeArmature(JsonDictionary &json) return armatureData; } -BoneData *DataReaderHelper::decodeBone(JsonDictionary &json) +BoneData *DataReaderHelper::decodeBone(JsonDictionary &json, DataInfo *dataInfo) { BoneData *boneData = new BoneData(); boneData->init(); - decodeNode(boneData, json); + decodeNode(boneData, json, dataInfo); const char *str = json.getItemStringValue(A_NAME); - if(str != NULL) + if(str != nullptr) { boneData->name = str; } str = json.getItemStringValue(A_PARENT); - if(str != NULL) + if(str != nullptr) { boneData->parentName = str; } @@ -1266,7 +1297,7 @@ BoneData *DataReaderHelper::decodeBone(JsonDictionary &json) for (int i = 0; i < length; i++) { JsonDictionary *dic = json.getSubItemFromArray(DISPLAY_DATA, i); - DisplayData *displayData = decodeBoneDisplay(*dic); + DisplayData *displayData = decodeBoneDisplay(*dic, dataInfo); boneData->addDisplayData(displayData); displayData->release(); @@ -1276,11 +1307,11 @@ BoneData *DataReaderHelper::decodeBone(JsonDictionary &json) return boneData; } -DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json) +DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo *dataInfo) { DisplayType displayType = (DisplayType)json.getItemIntValue(A_DISPLAY_TYPE, CS_DISPLAY_SPRITE); - DisplayData *displayData = NULL; + DisplayData *displayData = nullptr; switch (displayType) { @@ -1289,13 +1320,13 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json) displayData = new SpriteDisplayData(); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { ((SpriteDisplayData *)displayData)->displayName = name; } JsonDictionary *dic = json.getSubItemFromArray(SKIN_DATA, 0); - if (dic != NULL) + if (dic != nullptr) { SpriteDisplayData *sdd = (SpriteDisplayData *)displayData; sdd->skinData.x = dic->getItemFloatValue(A_X, 0) * s_PositionReadScale; @@ -1304,6 +1335,10 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json) sdd->skinData.scaleY = dic->getItemFloatValue(A_SCALE_Y, 1); sdd->skinData.skewX = dic->getItemFloatValue(A_SKEW_X, 0); sdd->skinData.skewY = dic->getItemFloatValue(A_SKEW_Y, 0); + + sdd->skinData.x *= dataInfo->contentScale; + sdd->skinData.y *= dataInfo->contentScale; + delete dic; } } @@ -1314,7 +1349,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json) displayData = new ArmatureDisplayData(); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { ((ArmatureDisplayData *)displayData)->displayName = name; } @@ -1325,9 +1360,16 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json) displayData = new ParticleDisplayData(); const char *plist = json.getItemStringValue(A_PLIST); - if(plist != NULL) + if(plist != nullptr) { - ((ParticleDisplayData *)displayData)->plist = s_BasefilePath + plist; + if (dataInfo->asyncStruct) + { + static_cast(displayData)->plist = dataInfo->asyncStruct->baseFilePath + plist; + } + else + { + static_cast(displayData)->plist = dataInfo->baseFilePath + plist; + } } } break; @@ -1343,12 +1385,12 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json) return displayData; } -AnimationData *DataReaderHelper::decodeAnimation(JsonDictionary &json) +AnimationData *DataReaderHelper::decodeAnimation(JsonDictionary &json, DataInfo *dataInfo) { AnimationData *aniData = new AnimationData(); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { aniData->name = name; } @@ -1358,7 +1400,7 @@ AnimationData *DataReaderHelper::decodeAnimation(JsonDictionary &json) for (int i = 0; i < length; i++) { JsonDictionary *dic = json.getSubItemFromArray(MOVEMENT_DATA, i); - MovementData *movementData = decodeMovement(*dic); + MovementData *movementData = decodeMovement(*dic, dataInfo); aniData->addMovement(movementData); movementData->release(); @@ -1368,7 +1410,7 @@ AnimationData *DataReaderHelper::decodeAnimation(JsonDictionary &json) return aniData; } -MovementData *DataReaderHelper::decodeMovement(JsonDictionary &json) +MovementData *DataReaderHelper::decodeMovement(JsonDictionary &json, DataInfo *dataInfo) { MovementData *movementData = new MovementData(); @@ -1377,10 +1419,10 @@ MovementData *DataReaderHelper::decodeMovement(JsonDictionary &json) movementData->durationTo = json.getItemIntValue(A_DURATION_TO, 0); movementData->duration = json.getItemIntValue(A_DURATION, 0); movementData->scale = json.getItemFloatValue(A_MOVEMENT_SCALE, 1); - movementData->tweenEasing = (CCTweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); + movementData->tweenEasing = (TweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { movementData->name = name; } @@ -1389,7 +1431,7 @@ MovementData *DataReaderHelper::decodeMovement(JsonDictionary &json) for (int i = 0; i < length; i++) { JsonDictionary *dic = json.getSubItemFromArray(MOVEMENT_BONE_DATA, i); - MovementBoneData *movementBoneData = decodeMovementBone(*dic); + MovementBoneData *movementBoneData = decodeMovementBone(*dic, dataInfo); movementData->addMovementBoneData(movementBoneData); movementBoneData->release(); @@ -1399,7 +1441,7 @@ MovementData *DataReaderHelper::decodeMovement(JsonDictionary &json) return movementData; } -MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json) +MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json, DataInfo *dataInfo) { MovementBoneData *movementBoneData = new MovementBoneData(); movementBoneData->init(); @@ -1407,7 +1449,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json) movementBoneData->delay = json.getItemFloatValue(A_MOVEMENT_DELAY, 0); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { movementBoneData->name = name; } @@ -1416,12 +1458,12 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json) for (int i = 0; i < length; i++) { JsonDictionary *dic = json.getSubItemFromArray(FRAME_DATA, i); - FrameData *frameData = decodeFrame(*dic); + FrameData *frameData = decodeFrame(*dic, dataInfo); movementBoneData->addFrameData(frameData); frameData->release(); - if (s_CocoStudioVersion < VERSION_COMBINED) + if (dataInfo->cocoStudioVersion < VERSION_COMBINED) { frameData->frameID = movementBoneData->duration; movementBoneData->duration += frameData->duration; @@ -1431,7 +1473,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json) } - if (s_CocoStudioVersion < VERSION_CHANGE_ROTATION_RANGE) + if (dataInfo->cocoStudioVersion < VERSION_CHANGE_ROTATION_RANGE) { //! Change rotation range from (-180 -- 180) to (-infinity -- infinity) FrameData **frames = (FrameData **)movementBoneData->frameList.data->arr; @@ -1455,7 +1497,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json) } } - if (s_CocoStudioVersion < VERSION_COMBINED) + if (dataInfo->cocoStudioVersion < VERSION_COMBINED) { if (movementBoneData->frameList.count() > 0) { @@ -1471,24 +1513,24 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json) return movementBoneData; } -FrameData *DataReaderHelper::decodeFrame(JsonDictionary &json) +FrameData *DataReaderHelper::decodeFrame(JsonDictionary &json, DataInfo *dataInfo) { FrameData *frameData = new FrameData(); - decodeNode(frameData, json); + decodeNode(frameData, json, dataInfo); - frameData->tweenEasing = (CCTweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); + frameData->tweenEasing = (TweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); frameData->displayIndex = json.getItemIntValue(A_DISPLAY_INDEX, 0); frameData->blendType = (BlendType)json.getItemIntValue(A_BLEND_TYPE, 0); frameData->isTween = (bool)json.getItemBoolvalue(A_TWEEN_FRAME, true); const char *event = json.getItemStringValue(A_EVENT); - if (event != NULL) + if (event != nullptr) { frameData->strEvent = event; } - if (s_CocoStudioVersion < VERSION_COMBINED) + if (dataInfo->cocoStudioVersion < VERSION_COMBINED) { frameData->duration = json.getItemIntValue(A_DURATION, 1); } @@ -1506,7 +1548,7 @@ TextureData *DataReaderHelper::decodeTexture(JsonDictionary &json) textureData->init(); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { textureData->name = name; } @@ -1554,10 +1596,14 @@ ContourData *DataReaderHelper::decodeContour(JsonDictionary &json) return contourData; } -void DataReaderHelper::decodeNode(BaseData *node, JsonDictionary &json) +void DataReaderHelper::decodeNode(BaseData *node, JsonDictionary &json, DataInfo *dataInfo) { node->x = json.getItemFloatValue(A_X, 0) * s_PositionReadScale; node->y = json.getItemFloatValue(A_Y, 0) * s_PositionReadScale; + + node->x *= dataInfo->contentScale; + node->y *= dataInfo->contentScale; + node->zOrder = json.getItemIntValue(A_Z, 0); node->skewX = json.getItemFloatValue(A_SKEW_X, 0); @@ -1565,7 +1611,15 @@ void DataReaderHelper::decodeNode(BaseData *node, JsonDictionary &json) node->scaleX = json.getItemFloatValue(A_SCALE_X, 1); node->scaleY = json.getItemFloatValue(A_SCALE_Y, 1); - JsonDictionary *colorDic = json.getSubItemFromArray(COLOR_INFO, 0); + JsonDictionary *colorDic = nullptr; + if (dataInfo->cocoStudioVersion < VERSION_COLOR_READING) + { + colorDic = json.getSubItemFromArray(COLOR_INFO, 0); + } + else + { + colorDic = json.getSubDictionary(COLOR_INFO); + } if (colorDic) { diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.h b/cocos/editor-support/cocostudio/CCDataReaderHelper.h index d5c8a0d6f5..33088e0043 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.h +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.h @@ -63,12 +63,20 @@ protected: cocos2d::Object *target; cocos2d::SEL_SCHEDULE selector; bool autoLoadSpriteFile; + + std::string imagePath; + std::string plistPath; } AsyncStruct; typedef struct _DataInfo { AsyncStruct *asyncStruct; std::queue configFileQueue; + float contentScale; + std::string filename; + std::string baseFilePath; + float flashToolVersion; + float cocoStudioVersion; } DataInfo; public: @@ -86,7 +94,6 @@ public: static float getPositionReadScale(); static void purge(); - static void clear(); public: /** * @js ctor @@ -99,10 +106,11 @@ public: ~DataReaderHelper(); void addDataFromFile(const char *filePath); - void addDataFromFileAsync(const char *filePath, cocos2d::Object *target, cocos2d::SEL_SCHEDULE selector); + void addDataFromFileAsync(const char *imagePath, const char *plistPath, const char *filePath, cocos2d::Object *target, cocos2d::SEL_SCHEDULE selector); void addDataAsyncCallBack(float dt); + void removeConfigFile(const char *configFile); public: /** @@ -111,54 +119,54 @@ public: * * @param xmlPath The cache of the xml */ - static void addDataFromCache(const char *pFileContent, DataInfo *dataInfo = NULL); + static void addDataFromCache(const char *pFileContent, DataInfo *dataInfo = nullptr); /** * Decode Armature Datas from xml export from Dragon Bone flash tool */ - static ArmatureData *decodeArmature(tinyxml2::XMLElement *armatureXML); - static BoneData *decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2::XMLElement *parentXML); - static DisplayData *decodeBoneDisplay(tinyxml2::XMLElement *displayXML); + static ArmatureData *decodeArmature(tinyxml2::XMLElement *armatureXML, DataInfo *dataInfo); + static BoneData *decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2::XMLElement *parentXML, DataInfo *dataInfo); + static DisplayData *decodeBoneDisplay(tinyxml2::XMLElement *displayXML, DataInfo *dataInfo); /** * Decode ArmatureAnimation Datas from xml export from Dragon Bone flash tool */ - static AnimationData *decodeAnimation(tinyxml2::XMLElement *animationXML); - static MovementData *decodeMovement(tinyxml2::XMLElement *movementXML, ArmatureData *armatureData); - static MovementBoneData *decodeMovementBone(tinyxml2::XMLElement *movBoneXml, tinyxml2::XMLElement *parentXml, BoneData *boneData); - static FrameData *decodeFrame(tinyxml2::XMLElement *frameXML, tinyxml2::XMLElement *parentFrameXml, BoneData *boneData); + static AnimationData *decodeAnimation(tinyxml2::XMLElement *animationXML, DataInfo *dataInfo); + static MovementData *decodeMovement(tinyxml2::XMLElement *movementXML, ArmatureData *armatureData, DataInfo *dataInfo); + static MovementBoneData *decodeMovementBone(tinyxml2::XMLElement *movBoneXml, tinyxml2::XMLElement *parentXml, BoneData *boneData, DataInfo *dataInfo); + static FrameData *decodeFrame(tinyxml2::XMLElement *frameXML, tinyxml2::XMLElement *parentFrameXml, BoneData *boneData, DataInfo *dataInfo); /** * Decode Texture Datas from xml export from Dragon Bone flash tool */ - static TextureData *decodeTexture(tinyxml2::XMLElement *textureXML); + static TextureData *decodeTexture(tinyxml2::XMLElement *textureXML, DataInfo *dataInfo); /** * Decode Contour Datas from xml export from Dragon Bone flash tool */ - static ContourData *decodeContour(tinyxml2::XMLElement *contourXML); + static ContourData *decodeContour(tinyxml2::XMLElement *contourXML, DataInfo *dataInfo); public: - static void addDataFromJsonCache(const char *fileContent, DataInfo *dataInfo = NULL); + static void addDataFromJsonCache(const char *fileContent, DataInfo *dataInfo = nullptr); - static ArmatureData *decodeArmature(JsonDictionary &json); - static BoneData *decodeBone(JsonDictionary &json); - static DisplayData *decodeBoneDisplay(JsonDictionary &json); + static ArmatureData *decodeArmature(JsonDictionary &json, DataInfo *dataInfo); + static BoneData *decodeBone(JsonDictionary &json, DataInfo *dataInfo); + static DisplayData *decodeBoneDisplay(JsonDictionary &json, DataInfo *dataInfo); - static AnimationData *decodeAnimation(JsonDictionary &json); - static MovementData *decodeMovement(JsonDictionary &json); - static MovementBoneData *decodeMovementBone(JsonDictionary &json); - static FrameData *decodeFrame(JsonDictionary &json); + static AnimationData *decodeAnimation(JsonDictionary &json, DataInfo *dataInfo); + static MovementData *decodeMovement(JsonDictionary &json, DataInfo *dataInfo); + static MovementBoneData *decodeMovementBone(JsonDictionary &json, DataInfo *dataInfo); + static FrameData *decodeFrame(JsonDictionary &json, DataInfo *dataInfo); static TextureData *decodeTexture(JsonDictionary &json); static ContourData *decodeContour(JsonDictionary &json); - static void decodeNode(BaseData *node, JsonDictionary &json); + static void decodeNode(BaseData *node, JsonDictionary &json, DataInfo *dataInfo); protected: void loadData(); @@ -177,6 +185,8 @@ protected: std::mutex _addDataMutex; + std::mutex _getFileMutex; + unsigned long _asyncRefCount; unsigned long _asyncRefTotalCount; @@ -186,6 +196,7 @@ protected: std::queue *_asyncStructQueue; std::queue *_dataQueue; + static std::vector _configFileList; static DataReaderHelper *_dataReaderHelper; }; diff --git a/cocos/editor-support/cocostudio/CCDatas.h b/cocos/editor-support/cocostudio/CCDatas.h index 26128020cf..4b9c2feca6 100644 --- a/cocos/editor-support/cocostudio/CCDatas.h +++ b/cocos/editor-support/cocostudio/CCDatas.h @@ -39,7 +39,7 @@ public: \ return var;\ }\ CC_SAFE_DELETE(var);\ - return NULL;\ + return nullptr;\ } #define CC_CREATE_NO_PARAM(varType)\ @@ -52,7 +52,7 @@ public: \ return var;\ }\ CC_SAFE_DELETE(var);\ - return NULL;\ + return nullptr;\ } namespace cocostudio { @@ -341,7 +341,7 @@ public: public: int frameID; int duration; //! The frame will last duration frames - CCTweenType tweenEasing; //! Every frame's tween easing effect + TweenType tweenEasing; //! Every frame's tween easing effect bool isTween; //! Whether it's a tween key frame /** @@ -435,7 +435,7 @@ public: * Which tween easing effect the movement use * TWEEN_EASING_MAX : use the value from MovementData get from flash design panel */ - CCTweenType tweenEasing; + TweenType tweenEasing; /** * @brief save movment bone data diff --git a/cocos/editor-support/cocostudio/CCDecorativeDisplay.cpp b/cocos/editor-support/cocostudio/CCDecorativeDisplay.cpp index e595ecbe0c..81cc4bc751 100644 --- a/cocos/editor-support/cocostudio/CCDecorativeDisplay.cpp +++ b/cocos/editor-support/cocostudio/CCDecorativeDisplay.cpp @@ -37,16 +37,16 @@ DecorativeDisplay *DecorativeDisplay::create() return pDisplay; } CC_SAFE_DELETE(pDisplay); - return NULL; + return nullptr; } DecorativeDisplay::DecorativeDisplay() - : _display(NULL) - , _displayData(NULL) + : _display(nullptr) + , _displayData(nullptr) { #if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT - _colliderDetector = NULL; + _colliderDetector = nullptr; #endif } diff --git a/cocos/editor-support/cocostudio/CCDecorativeDisplay.h b/cocos/editor-support/cocostudio/CCDecorativeDisplay.h index 7196d0e9ec..0444cae440 100644 --- a/cocos/editor-support/cocostudio/CCDecorativeDisplay.h +++ b/cocos/editor-support/cocostudio/CCDecorativeDisplay.h @@ -53,13 +53,46 @@ public: virtual bool init(); -protected: + virtual void setDisplay(cocos2d::Node *display) + { + if (_display != display) + { + CC_SAFE_RETAIN(display); + CC_SAFE_RELEASE(_display); + _display = display; + } + } + virtual cocos2d::Node *getDisplay() const { return _display; } - CC_SYNTHESIZE_RETAIN(cocos2d::Node *, _display, Display); - CC_SYNTHESIZE_RETAIN(DisplayData *, _displayData, DisplayData); + virtual void setDisplayData(DisplayData *data) + { + if (_displayData != data) + { + CC_SAFE_RETAIN(data); + CC_SAFE_RELEASE(_displayData); + _displayData = data; + } + } + virtual DisplayData *getDisplayData() const { return _displayData; } #if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT - CC_SYNTHESIZE_RETAIN(ColliderDetector *, _colliderDetector, ColliderDetector); + virtual void setColliderDetector(ColliderDetector *detector) + { + if (_colliderDetector != detector) + { + CC_SAFE_RETAIN(detector); + CC_SAFE_RELEASE(_colliderDetector); + _colliderDetector = detector; + } + } + virtual ColliderDetector *getColliderDetector() const { return _colliderDetector; } +#endif +protected: + cocos2d::Node *_display; + DisplayData *_displayData; + +#if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT + ColliderDetector *_colliderDetector; #endif }; diff --git a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp index 034f115481..46c7750d48 100644 --- a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp @@ -70,13 +70,15 @@ void DisplayFactory::createDisplay(Bone *bone, DecorativeDisplay *decoDisplay) } } -void DisplayFactory::updateDisplay(Bone *bone, DecorativeDisplay *decoDisplay, float dt, bool dirty) +void DisplayFactory::updateDisplay(Bone *bone, float dt, bool dirty) { - CS_RETURN_IF(!decoDisplay); + Node *display = bone->getDisplayRenderNode(); + CS_RETURN_IF(!display); #if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT if (dirty) { + DecorativeDisplay *decoDisplay = bone->getDisplayManager()->getCurrentDecorativeDisplay(); ColliderDetector *detector = decoDisplay->getColliderDetector(); if (detector) { @@ -84,9 +86,8 @@ void DisplayFactory::updateDisplay(Bone *bone, DecorativeDisplay *decoDisplay, f { CC_BREAK_IF(!detector->getBody()); - Node *node = decoDisplay->getDisplay(); - AffineTransform displayTransform = node->getNodeToParentTransform(); - Point anchorPoint = node->getAnchorPointInPoints(); + AffineTransform displayTransform = display->getNodeToParentTransform(); + Point anchorPoint = display->getAnchorPointInPoints(); anchorPoint = PointApplyAffineTransform(anchorPoint, displayTransform); displayTransform.tx = anchorPoint.x; displayTransform.ty = anchorPoint.y; @@ -98,18 +99,19 @@ void DisplayFactory::updateDisplay(Bone *bone, DecorativeDisplay *decoDisplay, f } #endif - Node *display = decoDisplay->getDisplay(); - - switch(decoDisplay->getDisplayData()->displayType) + switch(bone->getDisplayRenderNodeType()) { case CS_DISPLAY_SPRITE: - updateSpriteDisplay(bone, display, dt, dirty); + if (dirty) + { + static_cast(display)->updateArmatureTransform(); + } break; case CS_DISPLAY_PARTICLE: - updateParticleDisplay(bone, display, dt, dirty); + updateParticleDisplay(bone, display, dt); break; case CS_DISPLAY_ARMATURE: - updateArmatureDisplay(bone, display, dt, dirty); + updateArmatureDisplay(bone, display, dt); break; default: { @@ -131,7 +133,7 @@ void DisplayFactory::addSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay void DisplayFactory::createSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay) { - Skin *skin = NULL; + Skin *skin = nullptr; SpriteDisplayData *displayData = (SpriteDisplayData *)decoDisplay->getDisplayData(); @@ -153,6 +155,13 @@ void DisplayFactory::createSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisp skin = Skin::createWithSpriteFrameName((textureName + ".png").c_str()); } + decoDisplay->setDisplay(skin); + + if (skin == nullptr) + { + return; + } + skin->setBone(bone); initSpriteDisplay(bone, decoDisplay, displayData->displayName.c_str(), skin); @@ -170,8 +179,6 @@ void DisplayFactory::createSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisp } } - decoDisplay->setDisplay(skin); - } void DisplayFactory::initSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay, const char *displayName, Skin *skin) @@ -206,17 +213,11 @@ void DisplayFactory::initSpriteDisplay(Bone *bone, DecorativeDisplay *decoDispla #endif } -void DisplayFactory::updateSpriteDisplay(Bone *bone, Node *display, float dt, bool dirty) -{ - CS_RETURN_IF(!dirty); - Skin *skin = (Skin *)display; - skin->updateArmatureTransform(); -} void DisplayFactory::addArmatureDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData) { - ArmatureDisplayData *adp = ArmatureDisplayData::create(); ; + ArmatureDisplayData *adp = ArmatureDisplayData::create(); adp->copy((ArmatureDisplayData *)displayData); decoDisplay->setDisplayData(adp); @@ -228,15 +229,9 @@ void DisplayFactory::createArmatureDisplay(Bone *bone, DecorativeDisplay *decoDi Armature *armature = Armature::create(displayData->displayName.c_str(), bone); - /* - * because this bone have called this name, so armature should change it's name, or it can't add to - * Armature's bone children. - */ - armature->setName((bone->getName() + "_armatureChild").c_str()); - decoDisplay->setDisplay(armature); } -void DisplayFactory::updateArmatureDisplay(Bone *bone, Node *display, float dt, bool dirty) +void DisplayFactory::updateArmatureDisplay(Bone *bone, Node *display, float dt) { Armature *armature = (Armature *)display; if(armature) @@ -250,7 +245,7 @@ void DisplayFactory::updateArmatureDisplay(Bone *bone, Node *display, float dt, void DisplayFactory::addParticleDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData) { - ParticleDisplayData *adp = ParticleDisplayData::create(); ; + ParticleDisplayData *adp = ParticleDisplayData::create(); adp->copy((ParticleDisplayData *)displayData); decoDisplay->setDisplayData(adp); @@ -260,9 +255,18 @@ void DisplayFactory::createParticleDisplay(Bone *bone, DecorativeDisplay *decoDi { ParticleDisplayData *displayData = (ParticleDisplayData *)decoDisplay->getDisplayData(); ParticleSystem *system = ParticleSystemQuad::create(displayData->plist.c_str()); + + system->removeFromParent(); + + Armature *armature = bone->getArmature(); + if (armature) + { + system->setParent(armature); + } + decoDisplay->setDisplay(system); } -void DisplayFactory::updateParticleDisplay(Bone *bone, Node *display, float dt, bool dirty) +void DisplayFactory::updateParticleDisplay(Bone *bone, Node *display, float dt) { ParticleSystem *system = (ParticleSystem *)display; BaseData node; diff --git a/cocos/editor-support/cocostudio/CCDisplayFactory.h b/cocos/editor-support/cocostudio/CCDisplayFactory.h index 3ef0725ff0..a62329d548 100644 --- a/cocos/editor-support/cocostudio/CCDisplayFactory.h +++ b/cocos/editor-support/cocostudio/CCDisplayFactory.h @@ -40,21 +40,20 @@ class DisplayFactory public: static void addDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData); static void createDisplay(Bone *bone, DecorativeDisplay *decoDisplay); - static void updateDisplay(Bone *bone, DecorativeDisplay *decoDisplay, float dt, bool dirty); + static void updateDisplay(Bone *bone, float dt, bool dirty); static void addSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData); static void createSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay); static void initSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay, const char *displayName, Skin *skin); - static void updateSpriteDisplay(Bone *bone, cocos2d::Node *display, float dt, bool dirty); static void addArmatureDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData); static void createArmatureDisplay(Bone *bone, DecorativeDisplay *decoDisplay); - static void updateArmatureDisplay(Bone *bone, cocos2d::Node *display, float dt, bool dirty); + static void updateArmatureDisplay(Bone *bone, cocos2d::Node *display, float dt); static void addParticleDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData); static void createParticleDisplay(Bone *bone, DecorativeDisplay *decoDisplay); - static void updateParticleDisplay(Bone *bone, cocos2d::Node *display, float dt, bool dirty); + static void updateParticleDisplay(Bone *bone, cocos2d::Node *display, float dt); }; diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/CCDisplayManager.cpp index b7d337e3a9..a8c8f5d760 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayManager.cpp @@ -41,18 +41,19 @@ DisplayManager *DisplayManager::create(Bone *bone) return pDisplayManager; } CC_SAFE_DELETE(pDisplayManager); - return NULL; + return nullptr; } DisplayManager::DisplayManager() - : _decoDisplayList(NULL) - , _displayRenderNode(NULL) - , _currentDecoDisplay(NULL) + : _decoDisplayList(nullptr) + , _displayRenderNode(nullptr) + , _displayType(CS_DISPLAY_MAX) + , _currentDecoDisplay(nullptr) , _displayIndex(-1) , _forceChangeDisplay(false) , _visible(true) - , _bone(NULL) + , _bone(nullptr) { } @@ -90,7 +91,7 @@ bool DisplayManager::init(Bone *bone) void DisplayManager::addDisplay(DisplayData *displayData, int index) { - DecorativeDisplay *decoDisplay = NULL; + DecorativeDisplay *decoDisplay = nullptr; if( (index >= 0) && (index < _decoDisplayList->count()) ) { @@ -114,7 +115,7 @@ void DisplayManager::addDisplay(DisplayData *displayData, int index) void DisplayManager::addDisplay(Node *display, int index) { - DecorativeDisplay *decoDisplay = NULL; + DecorativeDisplay *decoDisplay = nullptr; if( (index >= 0) && (index < _decoDisplayList->count()) ) { @@ -126,7 +127,7 @@ void DisplayManager::addDisplay(Node *display, int index) _decoDisplayList->addObject(decoDisplay); } - DisplayData *displayData = NULL; + DisplayData *displayData = nullptr; if (Skin *skin = dynamic_cast(display)) { skin->setBone(_bone); @@ -137,6 +138,7 @@ void DisplayManager::addDisplay(Node *display, int index) if (SpriteDisplayData *spriteDisplayData = (SpriteDisplayData *)decoDisplay->getDisplayData()) { skin->setSkinData(spriteDisplayData->skinData); + ((SpriteDisplayData *)displayData)->skinData = spriteDisplayData->skinData; } else { @@ -147,6 +149,14 @@ void DisplayManager::addDisplay(Node *display, int index) else if (dynamic_cast(display)) { displayData = ParticleDisplayData::create(); + + display->removeFromParent(); + + Armature *armature = _bone->getArmature(); + if (armature) + { + display->setParent(armature); + } } else if(Armature *armature = dynamic_cast(display)) { @@ -171,15 +181,16 @@ void DisplayManager::addDisplay(Node *display, int index) void DisplayManager::removeDisplay(int index) { - _decoDisplayList->removeObjectAtIndex(index); - if(index == _displayIndex) { - setCurrentDecorativeDisplay(NULL); + setCurrentDecorativeDisplay(nullptr); + _displayIndex = -1; } + + _decoDisplayList->removeObjectAtIndex(index); } -Array *DisplayManager::getDecorativeDisplayList() +Array *DisplayManager::getDecorativeDisplayList() const { return _decoDisplayList; } @@ -203,7 +214,7 @@ void DisplayManager::changeDisplayByIndex(int index, bool force) if(_displayRenderNode) { _displayRenderNode->removeFromParentAndCleanup(true); - setCurrentDecorativeDisplay(NULL); + setCurrentDecorativeDisplay(nullptr); } return; } @@ -232,12 +243,12 @@ void DisplayManager::setCurrentDecorativeDisplay(DecorativeDisplay *decoDisplay) } #endif - Node *displayRenderNode = _currentDecoDisplay == NULL ? NULL : _currentDecoDisplay->getDisplay(); + Node *displayRenderNode = _currentDecoDisplay == nullptr ? nullptr : _currentDecoDisplay->getDisplay(); if (_displayRenderNode) { - if (dynamic_cast(_displayRenderNode) != NULL) + if (dynamic_cast(_displayRenderNode) != nullptr) { - _bone->setChildArmature(NULL); + _bone->setChildArmature(nullptr); } _displayRenderNode->removeFromParentAndCleanup(true); _displayRenderNode->release(); @@ -264,25 +275,37 @@ void DisplayManager::setCurrentDecorativeDisplay(DecorativeDisplay *decoDisplay) _displayRenderNode->retain(); _displayRenderNode->setVisible(_visible); + + _displayType = _currentDecoDisplay->getDisplayData()->displayType; + } + else + { + _displayType = CS_DISPLAY_MAX; } } -Node *DisplayManager::getDisplayRenderNode() +Node *DisplayManager::getDisplayRenderNode() const { return _displayRenderNode; } -int DisplayManager::getCurrentDisplayIndex() + +DisplayType DisplayManager::getDisplayRenderNodeType() const +{ + return _displayType; +} + +int DisplayManager::getCurrentDisplayIndex() const { return _displayIndex; } -DecorativeDisplay *DisplayManager::getCurrentDecorativeDisplay() +DecorativeDisplay *DisplayManager::getCurrentDecorativeDisplay() const { return _currentDecoDisplay; } -DecorativeDisplay *DisplayManager::getDecorativeDisplayByIndex( int index) +DecorativeDisplay *DisplayManager::getDecorativeDisplayByIndex( int index) const { return (DecorativeDisplay *)_decoDisplayList->getObjectAtIndex(index); } @@ -295,11 +318,9 @@ void DisplayManager::initDisplayList(BoneData *boneData) CS_RETURN_IF(!boneData); - Object *object = NULL; - Array *displayDataList = &boneData->displayDataList; - CCARRAY_FOREACH(displayDataList, object) + for(auto object : boneData->displayDataList) { - DisplayData *displayData = (DisplayData *)object; + DisplayData *displayData = static_cast(object); DecorativeDisplay *decoDisplay = DecorativeDisplay::create(); decoDisplay->setDisplayData(displayData); @@ -362,32 +383,32 @@ void DisplayManager::setVisible(bool visible) _displayRenderNode->setVisible(visible); } -bool DisplayManager::isVisible() +bool DisplayManager::isVisible() const { return _visible; } -Size DisplayManager::getContentSize() +Size DisplayManager::getContentSize() const { CS_RETURN_IF(!_displayRenderNode) Size(0, 0); return _displayRenderNode->getContentSize(); } -Rect DisplayManager::getBoundingBox() +Rect DisplayManager::getBoundingBox() const { CS_RETURN_IF(!_displayRenderNode) Rect(0, 0, 0, 0); return _displayRenderNode->getBoundingBox(); } -Point DisplayManager::getAnchorPoint() +Point DisplayManager::getAnchorPoint() const { CS_RETURN_IF(!_displayRenderNode) Point(0, 0); return _displayRenderNode->getAnchorPoint(); } -Point DisplayManager::getAnchorPointInPoints() +Point DisplayManager::getAnchorPointInPoints() const { CS_RETURN_IF(!_displayRenderNode) Point(0, 0); return _displayRenderNode->getAnchorPointInPoints(); diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.h b/cocos/editor-support/cocostudio/CCDisplayManager.h index 9953d77995..1f1b4190ba 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.h +++ b/cocos/editor-support/cocostudio/CCDisplayManager.h @@ -76,7 +76,7 @@ public: void removeDisplay(int index); - cocos2d::Array *getDecorativeDisplayList(); + cocos2d::Array *getDecorativeDisplayList() const; /** * Change display by index. You can just use this method to change display in the display list. @@ -90,13 +90,14 @@ public: void changeDisplayByIndex(int index, bool force); - cocos2d::Node *getDisplayRenderNode(); + cocos2d::Node *getDisplayRenderNode() const; + DisplayType getDisplayRenderNodeType() const; - int getCurrentDisplayIndex(); + int getCurrentDisplayIndex() const; virtual void setCurrentDecorativeDisplay(DecorativeDisplay *decoDisplay); - virtual DecorativeDisplay *getCurrentDecorativeDisplay(); - virtual DecorativeDisplay *getDecorativeDisplayByIndex( int index); + virtual DecorativeDisplay *getCurrentDecorativeDisplay() const; + virtual DecorativeDisplay *getDecorativeDisplayByIndex( int index) const; /** * Sets whether the display is visible @@ -111,13 +112,13 @@ public: * @see setVisible(bool) * @return true if the node is visible, false if the node is hidden. */ - virtual bool isVisible(); + virtual bool isVisible() const; - cocos2d::Size getContentSize(); - cocos2d::Rect getBoundingBox(); + cocos2d::Size getContentSize() const; + cocos2d::Rect getBoundingBox() const; - cocos2d::Point getAnchorPoint(); - cocos2d::Point getAnchorPointInPoints(); + cocos2d::Point getAnchorPoint() const; + cocos2d::Point getAnchorPointInPoints() const; /** * Check if the position is inside the bone. @@ -129,16 +130,20 @@ public: */ virtual bool containPoint(float x, float y); + virtual void setForceChangeDisplay(bool force) { _forceChangeDisplay = force; } + virtual bool isForceChangeDisplay() const { return _forceChangeDisplay; } protected: cocos2d::Array *_decoDisplayList; //! Display render node. cocos2d::Node *_displayRenderNode; + //! Display render node type + DisplayType _displayType; //! Include current display information, like contour sprite, etc. DecorativeDisplay *_currentDecoDisplay; //! Current display index int _displayIndex; - CC_SYNTHESIZE(bool, _forceChangeDisplay, ForceChangeDisplay) + bool _forceChangeDisplay; //! Whether of not the bone is visible. Default is true bool _visible; diff --git a/cocos/editor-support/cocostudio/CCInputDelegate.cpp b/cocos/editor-support/cocostudio/CCInputDelegate.cpp index a134e3cdfe..03ac5030a7 100644 --- a/cocos/editor-support/cocostudio/CCInputDelegate.cpp +++ b/cocos/editor-support/cocostudio/CCInputDelegate.cpp @@ -47,6 +47,7 @@ InputDelegate::~InputDelegate(void) dispatcher->removeEventListener(_touchListener); dispatcher->removeEventListener(_keyboardListener); dispatcher->removeEventListener(_accelerometerListener); + Device::setAccelerometerEnabled(false); } bool InputDelegate::onTouchBegan(Touch *pTouch, Event *pEvent) @@ -196,6 +197,8 @@ void InputDelegate::setAccelerometerEnabled(bool enabled) dispatcher->removeEventListener(_accelerometerListener); _accelerometerListener = nullptr; + Device::setAccelerometerEnabled(enabled); + if (enabled) { auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(InputDelegate::onAcceleration, this)); diff --git a/cocos/editor-support/cocostudio/CCProcessBase.cpp b/cocos/editor-support/cocostudio/CCProcessBase.cpp index c3e1bfbc20..62bac419b6 100644 --- a/cocos/editor-support/cocostudio/CCProcessBase.cpp +++ b/cocos/editor-support/cocostudio/CCProcessBase.cpp @@ -89,7 +89,7 @@ void ProcessBase::play(void *animation, int durationTo, int durationTween, int * When changing end, m_iTotalFrames will be setted to _durationTween */ _nextFrameIndex = durationTo; - _tweenEasing = (CCTweenType)tweenEasing; + _tweenEasing = (TweenType)tweenEasing; } @@ -141,8 +141,18 @@ void ProcessBase::update(float dt) void ProcessBase::gotoFrame(int frameIndex) { + if (_loopType == ANIMATION_NO_LOOP) + { + _loopType = ANIMATION_MAX; + } + else if (_loopType == ANIMATION_TO_LOOP_FRONT) + { + _loopType = ANIMATION_LOOP_FRONT; + } + _curFrameIndex = frameIndex; - pause(); + + _nextFrameIndex = _durationTween; } int ProcessBase::getCurrentFrameIndex() diff --git a/cocos/editor-support/cocostudio/CCProcessBase.h b/cocos/editor-support/cocostudio/CCProcessBase.h index 9f80fb2ea7..2b3ef4ab47 100644 --- a/cocos/editor-support/cocostudio/CCProcessBase.h +++ b/cocos/editor-support/cocostudio/CCProcessBase.h @@ -58,7 +58,7 @@ public: * @js NA * @lua NA */ - ~ProcessBase(void); + virtual ~ProcessBase(void); /** * Play animation by animation name. @@ -104,8 +104,6 @@ public: virtual void stop(); - virtual void gotoFrame(int frameIndex); - /** * You should never call this function, unless you know what you do * Update the Process, include current process, current frame and son on @@ -116,8 +114,26 @@ public: virtual int getCurrentFrameIndex(); + virtual void setProcessScale(float processScale) { _processScale = processScale; } + virtual float getProcessScale() const { return _processScale; } + + virtual void setIsPause(bool pause) { _isPause = pause; } + virtual bool isPause() const { return _isPause; } + + virtual void setIsComplete(bool complete) { _isComplete = complete; } + virtual bool isComplete() const { return _isComplete; } + + virtual void setIsPlaying(bool playing) { _isPlaying = playing; } + virtual bool isPlaying() const { return _isPlaying; } + + virtual float getCurrentPercent() const { return _currentPercent; } + virtual int getRawDuration() const { return _rawDuration; } + + virtual void setAnimationInternal(float animationInternal) { _animationInternal = animationInternal; } + virtual float getAnimationInternal() const { return _animationInternal; } protected: + virtual void gotoFrame(int frameIndex); /** * Update(float dt) will call this handler, you can handle your logic here @@ -126,31 +142,31 @@ protected: protected: //! Scale the process speed - CC_SYNTHESIZE(float, _processScale, ProcessScale); + float _processScale; //! Set and get whether the aniamtion is pause - CC_SYNTHESIZE(bool, _isPause, IsPause); + bool _isPause; //! Set and get whether the aniamtion is complete - CC_SYNTHESIZE(bool, _isComplete, IsComplete); + bool _isComplete; //! Set and get whether the aniamtion is playing - CC_SYNTHESIZE(bool, _isPlaying, IsPlaying); + bool _isPlaying; //! Current percent this process arrived - CC_SYNTHESIZE(float, _currentPercent, CurrentPercent); + float _currentPercent; //! The raw duration - CC_SYNTHESIZE(int, _rawDuration, RawDuration); + int _rawDuration; //! The animation whether or not loop - CC_SYNTHESIZE(AnimationType, _loopType, LoopType); + AnimationType _loopType; //! The tween easing effect - CC_SYNTHESIZE(CCTweenType, _tweenEasing, TweenEasing); + TweenType _tweenEasing; //! The animation update speed - CC_SYNTHESIZE(float, _animationInternal, AnimationInternal); + float _animationInternal; protected: diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp old mode 100755 new mode 100644 index 77cb5d56de..3ad788b563 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -40,12 +40,13 @@ CCSGUIReader::CCSGUIReader(): m_strFilePath(""), m_bOlderVersion(false) { - + _fileDesignSizes = Dictionary::create(); + CC_SAFE_RETAIN(_fileDesignSizes); } CCSGUIReader::~CCSGUIReader() { - + CC_SAFE_RELEASE(_fileDesignSizes); } CCSGUIReader* CCSGUIReader::shareReader() @@ -152,7 +153,7 @@ UIWidget* CCSGUIReader::widgetFromJsonDictionary(JsonDictionary* data) } else if (classname && strcmp(classname, "Panel") == 0) { - widget = Layout::create(); + widget = UILayout::create(); setPropsForPanelFromJsonDictionary(widget, uiOptions); } else if (classname && strcmp(classname, "Slider") == 0) @@ -162,8 +163,8 @@ UIWidget* CCSGUIReader::widgetFromJsonDictionary(JsonDictionary* data) } else if (classname && strcmp(classname, "ListView") == 0) { -// widget = UIListView::create(); -// setPropsForListViewFromJsonDictionary(widget, uiOptions); + widget = UIListView::create(); + setPropsForListViewFromJsonDictionary(widget, uiOptions); } else if (classname && strcmp(classname, "PageView") == 0) { @@ -177,7 +178,7 @@ UIWidget* CCSGUIReader::widgetFromJsonDictionary(JsonDictionary* data) } else if (classname && strcmp(classname, "DragPanel") == 0) { - widget = UIDragPanel::create(); + widget = UIScrollView::create(); setPropsForDragPanelFromJsonDictionary(widget, uiOptions); } @@ -197,7 +198,26 @@ UIWidget* CCSGUIReader::widgetFromJsonDictionary(JsonDictionary* data) return widget; } +void CCSGUIReader::storeFileDesignSize(const char *fileName, const cocos2d::Size &size) +{ + if (!_fileDesignSizes) + { + _fileDesignSizes = cocos2d::Dictionary::create(); + _fileDesignSizes->retain(); + } + cocos2d::String* strSize = cocos2d::String::createWithFormat("{%f,%f}", size.width, size.height); + _fileDesignSizes->setObject(strSize, fileName); +} +const cocos2d::Size CCSGUIReader::getFileDesignSize(const char* fileName) const +{ + if (!_fileDesignSizes) + { + return cocos2d::Size::ZERO; + } + cocos2d::Size designSize = cocos2d::SizeFromString(((cocos2d::String*)_fileDesignSizes->objectForKey(fileName))->_string.c_str()); + return designSize; +} UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) { @@ -207,7 +227,7 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) JsonDictionary *jsonDict = NULL; jsonpath = FileUtils::getInstance()->fullPathForFilename(fileName); - unsigned long size = 0; + long size = 0; des = (char*)(FileUtils::getInstance()->getFileData(jsonpath.c_str(),"r" , &size)); if(NULL == des || strcmp(des, "") == 0) { @@ -225,27 +245,26 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) } int texturesCount = DICTOOL->getArrayCount_json(jsonDict, "textures"); - int pos = jsonpath.find_last_of('/'); + long pos = jsonpath.find_last_of('/'); m_strFilePath = jsonpath.substr(0,pos+1); for (int i=0; igetStringValueFromArray_json(jsonDict, "textures", i); std::string tp = m_strFilePath; tp.append(file); - CCUIHELPER->addSpriteFrame(tp.c_str()); + SpriteFrameCache::getInstance()->addSpriteFramesWithFile(tp.c_str()); } float fileDesignWidth = DICTOOL->getFloatValue_json(jsonDict, "designWidth"); float fileDesignHeight = DICTOOL->getFloatValue_json(jsonDict, "designHeight"); - if (fileDesignWidth <= 0 || fileDesignHeight <= 0) { + if (fileDesignWidth <= 0 || fileDesignHeight <= 0) + { printf("Read design size error!\n"); Size winSize = Director::getInstance()->getWinSize(); - CCUIHELPER->setFileDesignWidth(winSize.width); - CCUIHELPER->setFileDesignHeight(winSize.height); + storeFileDesignSize(fileName, winSize); } else { - CCUIHELPER->setFileDesignWidth(fileDesignWidth); - CCUIHELPER->setFileDesignHeight(fileDesignHeight); + storeFileDesignSize(fileName, cocos2d::Size(fileDesignWidth, fileDesignHeight)); } JsonDictionary* widgetTree = DICTOOL->getSubDictionary_json(jsonDict, "widgetTree"); UIWidget* widget = widgetFromJsonDictionary(widgetTree); @@ -253,7 +272,7 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) /* *********temp********* */ if (widget->getContentSize().equals(Size::ZERO)) { - Layout* rootWidget = dynamic_cast(widget); + UILayout* rootWidget = dynamic_cast(widget); rootWidget->setSize(Size(fileDesignWidth, fileDesignHeight)); } /* ********************** */ @@ -792,7 +811,7 @@ void CCSGUIReader::setPropsForLabelFromJsonDictionary(UIWidget*widget,JsonDictio setPropsForWidgetFromJsonDictionary(widget, options); UILabel* label = (UILabel*)widget; bool touchScaleChangeAble = DICTOOL->getBooleanValue_json(options, "touchScaleEnable"); - label->setTouchScaleChangeAble(touchScaleChangeAble); + label->setTouchScaleChangeEnabled(touchScaleChangeAble); const char* text = DICTOOL->getStringValue_json(options, "text"); label->setText(text); bool fs = DICTOOL->checkObjectExist_json(options, "fontSize"); @@ -877,10 +896,9 @@ void CCSGUIReader::setPropsForLabelAtlasFromJsonDictionary(UIWidget*widget,JsonD void CCSGUIReader::setPropsForContainerWidgetFromJsonDictionary(UIWidget *widget, JsonDictionary *options) { setPropsForWidgetFromJsonDictionary(widget, options); - Layout* containerWidget = (Layout*)widget; + UILayout* containerWidget = (UILayout*)widget; if (!dynamic_cast(containerWidget) - && !dynamic_cast(containerWidget) - && !dynamic_cast(containerWidget)) + && !dynamic_cast(containerWidget)) { containerWidget->setClippingEnabled(DICTOOL->getBooleanValue_json(options, "clipAble")); } @@ -892,7 +910,7 @@ void CCSGUIReader::setPropsForPanelFromJsonDictionary(UIWidget*widget,JsonDictio if (m_bOlderVersion) { setPropsForContainerWidgetFromJsonDictionary(widget, options); - Layout* panel = (Layout*)widget; + UILayout* panel = (UILayout*)widget; bool backGroundScale9Enable = DICTOOL->getBooleanValue_json(options, "backGroundScale9Enable"); panel->setBackGroundImageScale9Enabled(backGroundScale9Enable); int cr = DICTOOL->getIntValue_json(options, "bgColorR"); @@ -959,7 +977,7 @@ void CCSGUIReader::setPropsForPanelFromJsonDictionary(UIWidget*widget,JsonDictio else { setPropsForContainerWidgetFromJsonDictionary(widget, options); - Layout* panel = (Layout*)widget; + UILayout* panel = (UILayout*)widget; bool backGroundScale9Enable = DICTOOL->getBooleanValue_json(options, "backGroundScale9Enable"); panel->setBackGroundImageScale9Enabled(backGroundScale9Enable); int cr = DICTOOL->getIntValue_json(options, "bgColorR"); @@ -1394,7 +1412,7 @@ void CCSGUIReader::setPropsForTextFieldFromJsonDictionary(UIWidget*widget,JsonDi //textField->setSize(CCSizeMake(dw, dh)); } bool maxLengthEnable = DICTOOL->getBooleanValue_json(options, "maxLengthEnable"); - textField->setMaxLengthEnable(maxLengthEnable); + textField->setMaxLengthEnabled(maxLengthEnable); if (maxLengthEnable) { @@ -1402,7 +1420,7 @@ void CCSGUIReader::setPropsForTextFieldFromJsonDictionary(UIWidget*widget,JsonDi textField->setMaxLength(maxLength); } bool passwordEnable = DICTOOL->getBooleanValue_json(options, "passwordEnable"); - textField->setPasswordEnable(passwordEnable); + textField->setPasswordEnabled(passwordEnable); if (passwordEnable) { textField->setPasswordStyleText(DICTOOL->getStringValue_json(options, "passwordStyleText")); @@ -1557,10 +1575,10 @@ void CCSGUIReader::setPropsForDragPanelFromJsonDictionary(UIWidget *widget, Json { setPropsForPanelFromJsonDictionary(widget, options); - UIDragPanel* dragPanel = (UIDragPanel*)widget; + UIScrollView* dragPanel = (UIScrollView*)widget; bool bounceEnable = DICTOOL->getBooleanValue_json(options, "bounceEnable"); - dragPanel->setBounceEnable(bounceEnable); + dragPanel->setBounceEnabled(bounceEnable); float innerWidth = DICTOOL->getFloatValue_json(options, "innerWidth"); float innerHeight = DICTOOL->getFloatValue_json(options, "innerHeight"); diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.h b/cocos/editor-support/cocostudio/CCSGUIReader.h old mode 100755 new mode 100644 index d39c349ee0..415b7b9e81 --- a/cocos/editor-support/cocostudio/CCSGUIReader.h +++ b/cocos/editor-support/cocostudio/CCSGUIReader.h @@ -65,9 +65,13 @@ public: void setPropsForLabelBMFontFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); void setPropsForDragPanelFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + void storeFileDesignSize(const char* fileName, const cocos2d::Size &size); + + const cocos2d::Size getFileDesignSize(const char* fileName) const; protected: std::string m_strFilePath; bool m_bOlderVersion; + cocos2d::Dictionary* _fileDesignSizes; }; } diff --git a/cocos/editor-support/cocostudio/CCSSceneReader.cpp b/cocos/editor-support/cocostudio/CCSSceneReader.cpp index 3d8bc7fd8c..25c84fd773 100644 --- a/cocos/editor-support/cocostudio/CCSSceneReader.cpp +++ b/cocos/editor-support/cocostudio/CCSSceneReader.cpp @@ -47,7 +47,7 @@ namespace cocostudio { cocos2d::Node* SceneReader::createNodeWithSceneFile(const char* pszFileName) { - unsigned long size = 0; + long size = 0; const char* pData = 0; cocos2d::Node *pNode = NULL; do { @@ -213,7 +213,7 @@ namespace cocostudio { { file_path = reDir.substr(0, pos+1); } - unsigned long size = 0; + long size = 0; const char *des = (char*)(cocos2d::FileUtils::getInstance()->getFileData(pPath.c_str(),"r" , &size)); JsonDictionary *jsonDict = new JsonDictionary(); jsonDict->initWithDescription(des); @@ -227,9 +227,9 @@ namespace cocostudio { const char *name = DICTOOL->getStringValue_json(subData, "name"); childrenCount = DICTOOL->getArrayCount_json(jsonDict, "config_file_path"); - for (int i = 0; i < childrenCount; ++i) + for (long j = 0; j < childrenCount; ++j) { - const char* plist = DICTOOL->getStringValueFromArray_json(jsonDict, "config_file_path", i); + const char* plist = DICTOOL->getStringValueFromArray_json(jsonDict, "config_file_path", j); std::string plistpath; plistpath += file_path; plistpath.append(plist); @@ -283,7 +283,7 @@ namespace cocostudio { if (nResType == 0) { pAttribute = ComAttribute::create(); - unsigned long size = 0; + long size = 0; const char* pData = 0; pData = (char*)(cocos2d::FileUtils::getInstance()->getFileData(pPath.c_str(), "r", &size)); if(pData != NULL && strcmp(pData, "") != 0) @@ -320,8 +320,8 @@ namespace cocostudio { { gui::UILayer *pLayer = gui::UILayer::create(); pLayer->scheduleUpdate(); - UIWidget* widget= gui::UIHelper::instance()->createWidgetFromJsonFile(pPath.c_str()); - pLayer->addWidget(widget); +// UIWidget* widget= gui::UIHelper::instance()->createWidgetFromJsonFile(pPath.c_str()); +// pLayer->addWidget(widget); ComRender *pRender = ComRender::create(pLayer, "GUIComponent"); if (pComName != NULL) { diff --git a/cocos/editor-support/cocostudio/CCSkin.cpp b/cocos/editor-support/cocostudio/CCSkin.cpp index afd6f5fc51..394dfb48ec 100644 --- a/cocos/editor-support/cocostudio/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/CCSkin.cpp @@ -37,6 +37,8 @@ namespace cocostudio { #define RENDER_IN_SUBPIXEL(__ARGS__) (ceil(__ARGS__)) #endif +#define SET_VERTEX3F(_v_, _x_, _y_, _z_) (_v_).x = (_x_); (_v_).y = (_y_); (_v_).z = (_z_); + Skin *Skin::create() { Skin *skin = new Skin(); @@ -46,7 +48,7 @@ Skin *Skin::create() return skin; } CC_SAFE_DELETE(skin); - return NULL; + return nullptr; } Skin *Skin::createWithSpriteFrameName(const char *pszSpriteFrameName) @@ -58,7 +60,7 @@ Skin *Skin::createWithSpriteFrameName(const char *pszSpriteFrameName) return skin; } CC_SAFE_DELETE(skin); - return NULL; + return nullptr; } Skin *Skin::create(const char *pszFileName) @@ -70,42 +72,44 @@ Skin *Skin::create(const char *pszFileName) return skin; } CC_SAFE_DELETE(skin); - return NULL; + return nullptr; } Skin::Skin() - : _bone(NULL) + : _bone(nullptr) + , _armature(nullptr) , _displayName("") { _skinTransform = AffineTransformIdentity; } -bool Skin::initWithSpriteFrameName(const char *pszSpriteFrameName) +bool Skin::initWithSpriteFrameName(const std::string& spriteFrameName) { - bool ret = Sprite::initWithSpriteFrameName(pszSpriteFrameName); + CCAssert(spriteFrameName != "", ""); - if (ret) + SpriteFrame *pFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); + bool ret = true; + + if (pFrame != nullptr) { - TextureAtlas *atlas = SpriteFrameCacheHelper::getInstance()->getTexureAtlasWithTexture(_texture); - setTextureAtlas(atlas); - - _displayName = pszSpriteFrameName; + ret = initWithSpriteFrame(pFrame); } + else + { + CCLOG("Cann't find CCSpriteFrame with %s. Please check your .plist file", spriteFrameName.c_str()); + ret = false; + } + + _displayName = spriteFrameName; return ret; } -bool Skin::initWithFile(const char *pszFilename) +bool Skin::initWithFile(const std::string& filename) { - bool ret = Sprite::initWithFile(pszFilename); + bool ret = Sprite::initWithFile(filename); - if (ret) - { - TextureAtlas *atlas = SpriteFrameCacheHelper::getInstance()->getTexureAtlasWithTexture(_texture); - setTextureAtlas(atlas); - - _displayName = pszFilename; - } + _displayName = filename; return ret; } @@ -116,10 +120,12 @@ void Skin::setSkinData(const BaseData &var) setScaleX(_skinData.scaleX); setScaleY(_skinData.scaleY); - setRotation(CC_RADIANS_TO_DEGREES(_skinData.skewX)); + setRotationX(CC_RADIANS_TO_DEGREES(_skinData.skewX)); + setRotationY(CC_RADIANS_TO_DEGREES(-_skinData.skewY)); setPosition(Point(_skinData.x, _skinData.y)); _skinTransform = getNodeToParentTransform(); + updateArmatureTransform(); } const BaseData &Skin::getSkinData() const @@ -130,6 +136,10 @@ const BaseData &Skin::getSkinData() const void Skin::updateArmatureTransform() { _transform = AffineTransformConcat(_skinTransform, _bone->getNodeToArmatureTransform()); + if(_armature && _armature->getBatchNode()) + { + _transform = AffineTransformConcat(_transform, _armature->getNodeToParentTransform()); + } } void Skin::updateTransform() @@ -172,13 +182,13 @@ void Skin::updateTransform() float dx = x1 * cr - y2 * sr2 + x; float dy = x1 * sr + y2 * cr2 + y; - _quad.bl.vertices = Vertex3F( RENDER_IN_SUBPIXEL(ax), RENDER_IN_SUBPIXEL(ay), _vertexZ ); - _quad.br.vertices = Vertex3F( RENDER_IN_SUBPIXEL(bx), RENDER_IN_SUBPIXEL(by), _vertexZ ); - _quad.tl.vertices = Vertex3F( RENDER_IN_SUBPIXEL(dx), RENDER_IN_SUBPIXEL(dy), _vertexZ ); - _quad.tr.vertices = Vertex3F( RENDER_IN_SUBPIXEL(cx), RENDER_IN_SUBPIXEL(cy), _vertexZ ); + SET_VERTEX3F( _quad.bl.vertices, RENDER_IN_SUBPIXEL(ax), RENDER_IN_SUBPIXEL(ay), _vertexZ ); + SET_VERTEX3F( _quad.br.vertices, RENDER_IN_SUBPIXEL(bx), RENDER_IN_SUBPIXEL(by), _vertexZ ); + SET_VERTEX3F( _quad.tl.vertices, RENDER_IN_SUBPIXEL(dx), RENDER_IN_SUBPIXEL(dy), _vertexZ ); + SET_VERTEX3F( _quad.tr.vertices, RENDER_IN_SUBPIXEL(cx), RENDER_IN_SUBPIXEL(cy), _vertexZ ); } - // MARMALADE CHANGE: ADDED CHECK FOR NULL, TO PERMIT SPRITES WITH NO BATCH NODE / TEXTURE ATLAS + // MARMALADE CHANGE: ADDED CHECK FOR nullptr, TO PERMIT SPRITES WITH NO BATCH NODE / TEXTURE ATLAS if (_textureAtlas) { _textureAtlas->updateQuad(&_quad, _textureAtlas->getTotalQuads()); @@ -203,4 +213,20 @@ AffineTransform Skin::getNodeToWorldTransformAR() const return AffineTransformConcat(displayTransform, _bone->getArmature()->getNodeToWorldTransform()); } +void Skin::setBone(Bone *bone) +{ + _bone = bone; + if(Armature *armature = _bone->getArmature()) + { + _armature = armature; + TextureAtlas *atlas = armature->getTexureAtlasWithTexture(_texture); + setTextureAtlas(atlas); + } +} + +Bone *Skin::getBone() const +{ + return _bone; +} + } diff --git a/cocos/editor-support/cocostudio/CCSkin.h b/cocos/editor-support/cocostudio/CCSkin.h index 3494c48436..e740d1eb01 100644 --- a/cocos/editor-support/cocostudio/CCSkin.h +++ b/cocos/editor-support/cocostudio/CCSkin.h @@ -39,21 +39,28 @@ public: public: Skin(); - bool initWithSpriteFrameName(const char *pszSpriteFrameName); - bool initWithFile(const char *pszFilename); + virtual bool initWithSpriteFrameName(const std::string& spriteFrameName) override; + virtual bool initWithFile(const std::string& filename) override; void updateArmatureTransform(); - void updateTransform(); + void updateTransform() override; - cocos2d::AffineTransform getNodeToWorldTransform() const; + cocos2d::AffineTransform getNodeToWorldTransform() const override; cocos2d::AffineTransform getNodeToWorldTransformAR() const; - CC_PROPERTY_PASS_BY_REF(BaseData, _skinData, SkinData); - CC_SYNTHESIZE(Bone *, _bone, Bone); + virtual void setSkinData(const BaseData &data); + virtual const BaseData &getSkinData() const; + virtual void setBone(Bone *bone); + virtual Bone *getBone() const; + + virtual const std::string &getDisplayName() const { return _displayName; } protected: + BaseData _skinData; + Bone *_bone; + Armature *_armature; cocos2d::AffineTransform _skinTransform; - CC_SYNTHESIZE_READONLY(std::string, _displayName, DisplayName) + std::string _displayName; }; } diff --git a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp index d783c4ba4e..d3e2b620fd 100644 --- a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp +++ b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp @@ -29,7 +29,7 @@ using namespace cocos2d; namespace cocostudio { -SpriteFrameCacheHelper *SpriteFrameCacheHelper::_spriteFrameCacheHelper = NULL; +SpriteFrameCacheHelper *SpriteFrameCacheHelper::_spriteFrameCacheHelper = nullptr; SpriteFrameCacheHelper *SpriteFrameCacheHelper::getInstance() { @@ -44,7 +44,7 @@ SpriteFrameCacheHelper *SpriteFrameCacheHelper::getInstance() void SpriteFrameCacheHelper::purge() { delete _spriteFrameCacheHelper; - _spriteFrameCacheHelper = NULL; + _spriteFrameCacheHelper = nullptr; } void SpriteFrameCacheHelper::addSpriteFrameFromFile(const char *plistPath, const char *imagePath) @@ -52,26 +52,12 @@ void SpriteFrameCacheHelper::addSpriteFrameFromFile(const char *plistPath, const CCSpriteFrameCache::getInstance()->addSpriteFramesWithFile(plistPath, imagePath); } -TextureAtlas *SpriteFrameCacheHelper::getTexureAtlasWithTexture(Texture2D *texture) -{ - int key = texture->getName(); - TextureAtlas *atlas = (TextureAtlas *)_textureAtlasDic->objectForKey(key); - if (atlas == NULL) - { - atlas = TextureAtlas::createWithTexture(texture, 4); - _textureAtlasDic->setObject(atlas, key); - } - return atlas; -} - SpriteFrameCacheHelper::SpriteFrameCacheHelper() { - _textureAtlasDic = new Dictionary(); } SpriteFrameCacheHelper::~SpriteFrameCacheHelper() { - CC_SAFE_RELEASE_NULL(_textureAtlasDic); } } diff --git a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h index 150fe96aaa..81ccf1b1f9 100644 --- a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h +++ b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h @@ -47,8 +47,6 @@ public: */ void addSpriteFrameFromFile(const char *plistPath, const char *imagePath); - cocos2d::TextureAtlas *getTexureAtlasWithTexture(cocos2d::Texture2D *texture); - private: /** * @js ctor @@ -60,8 +58,6 @@ private: */ ~SpriteFrameCacheHelper(); - cocos2d::Dictionary *_textureAtlasDic; - static SpriteFrameCacheHelper *_spriteFrameCacheHelper; }; diff --git a/cocos/editor-support/cocostudio/CCTransformHelp.cpp b/cocos/editor-support/cocostudio/CCTransformHelp.cpp index a836055c16..0107760a3b 100644 --- a/cocos/editor-support/cocostudio/CCTransformHelp.cpp +++ b/cocos/editor-support/cocostudio/CCTransformHelp.cpp @@ -96,10 +96,23 @@ void TransformHelp::transformToParentWithoutScale(BaseData &node, const BaseData void TransformHelp::nodeToMatrix(const BaseData &node, AffineTransform &matrix) { - matrix.a = node.scaleX * cos(node.skewY); - matrix.b = node.scaleX * sin(node.skewY); - matrix.c = node.scaleY * sin(node.skewX); - matrix.d = node.scaleY * cos(node.skewX); + if (node.skewX == -node.skewY) + { + double sine = sin(node.skewX); + double cosine = cos(node.skewX); + + matrix.a = node.scaleX * cosine; + matrix.b = node.scaleX * -sine; + matrix.c = node.scaleY * sine; + matrix.d = node.scaleY * cosine; + } + else + { + matrix.a = node.scaleX * cos(node.skewY); + matrix.b = node.scaleX * sin(node.skewY); + matrix.c = node.scaleY * sin(node.skewX); + matrix.d = node.scaleY * cos(node.skewX); + } matrix.tx = node.x; matrix.ty = node.y; diff --git a/cocos/editor-support/cocostudio/CCTween.cpp b/cocos/editor-support/cocostudio/CCTween.cpp index 8fec95b2a0..dec84bf295 100644 --- a/cocos/editor-support/cocostudio/CCTween.cpp +++ b/cocos/editor-support/cocostudio/CCTween.cpp @@ -43,24 +43,25 @@ Tween *Tween::create(Bone *bone) return pTween; } CC_SAFE_DELETE(pTween); - return NULL; + return nullptr; } Tween::Tween() - : _movementBoneData(NULL) - , _tweenData(NULL) - , _from(NULL) - , _to(NULL) - , _between(NULL) - , _bone(NULL) + : _movementBoneData(nullptr) + , _tweenData(nullptr) + , _from(nullptr) + , _to(nullptr) + , _between(nullptr) + , _bone(nullptr) , _frameTweenEasing(Linear) , _fromIndex(0) , _toIndex(0) - , _animation(NULL) + , _animation(nullptr) + , _passLastFrame(false) { } @@ -85,7 +86,7 @@ bool Tween::init(Bone *bone) _tweenData = _bone->getTweenData(); _tweenData->displayIndex = -1; - _animation = _bone->getArmature() != NULL ? _bone->getArmature()->getAnimation() : NULL; + _animation = _bone->getArmature() != nullptr ? _bone->getArmature()->getAnimation() : nullptr; bRet = true; } @@ -97,9 +98,16 @@ bool Tween::init(Bone *bone) void Tween::play(MovementBoneData *movementBoneData, int durationTo, int durationTween, int loop, int tweenEasing) { - ProcessBase::play(NULL, durationTo, durationTween, loop, tweenEasing); + ProcessBase::play(nullptr, durationTo, durationTween, loop, tweenEasing); - _loopType = (AnimationType)loop; + if (loop) + { + _loopType = ANIMATION_TO_LOOP_FRONT; + } + else + { + _loopType = ANIMATION_NO_LOOP; + } _totalDuration = 0; _betweenDuration = 0; @@ -135,15 +143,6 @@ void Tween::play(MovementBoneData *movementBoneData, int durationTo, int duratio } else if (_movementBoneData->frameList.count() > 1) { - if (loop) - { - _loopType = ANIMATION_TO_LOOP_BACK; - } - else - { - _loopType = ANIMATION_NO_LOOP; - } - _durationTween = durationTween * _movementBoneData->scale; if (loop && _movementBoneData->delay != 0) @@ -166,6 +165,27 @@ void Tween::play(MovementBoneData *movementBoneData, int durationTo, int duratio tweenNodeTo(0); } +void Tween::gotoAndPlay(int frameIndex) +{ + ProcessBase::gotoFrame(frameIndex); + + _totalDuration = 0; + _betweenDuration = 0; + _fromIndex = _toIndex = 0; + + _isPlaying = true; + _isComplete = _isPause = false; + + _currentPercent = (float)_curFrameIndex / (float)_rawDuration; + _currentFrame = _nextFrameIndex * _currentPercent; +} + +void Tween::gotoAndPause(int frameIndex) +{ + gotoAndPlay(frameIndex); + pause(); +} + void Tween::updateHandler() { if (_currentPercent >= 1) @@ -211,9 +231,9 @@ void Tween::updateHandler() } } break; - case ANIMATION_TO_LOOP_BACK: + case ANIMATION_TO_LOOP_FRONT: { - _loopType = ANIMATION_LOOP_BACK; + _loopType = ANIMATION_LOOP_FRONT; _nextFrameIndex = _durationTween > 0 ? _durationTween : 1; @@ -244,10 +264,6 @@ void Tween::updateHandler() default: { _currentFrame = fmodf(_currentFrame, _nextFrameIndex); - - _totalDuration = 0; - _betweenDuration = 0; - _fromIndex = _toIndex = 0; } break; } @@ -312,7 +328,7 @@ void Tween::arriveKeyFrame(FrameData *keyFrameData) //! Change bone's display int displayIndex = keyFrameData->displayIndex; - if (!displayManager->getForceChangeDisplay()) + if (!displayManager->isForceChangeDisplay()) { displayManager->changeDisplayByIndex(displayIndex, false); } @@ -338,11 +354,11 @@ void Tween::arriveKeyFrame(FrameData *keyFrameData) FrameData *Tween::tweenNodeTo(float percent, FrameData *node) { - node = node == NULL ? _tweenData : node; + node = node == nullptr ? _tweenData : node; if (!_from->isTween) { - return _from; + percent = 0; } node->x = _from->x + percent * _between->x; @@ -391,43 +407,54 @@ float Tween::updateFrameData(float currentPercent) int length = _movementBoneData->frameList.count(); FrameData **frames = (FrameData **)_movementBoneData->frameList.data->arr; - FrameData *from = NULL; - FrameData *to = NULL; + FrameData *from = nullptr; + FrameData *to = nullptr; if (playedTime < frames[0]->frameID) { from = to = frames[0]; setBetween(from, to); - return currentPercent; + return _currentPercent; } - else if(playedTime >= frames[length - 1]->frameID) + + if(playedTime >= frames[length - 1]->frameID) { - from = to = frames[length - 1]; - setBetween(from, to); - return currentPercent; + // If _passLastFrame is true and playedTime >= frames[length - 1]->frameID, then do not need to go on. + if (_passLastFrame) + { + from = to = frames[length - 1]; + setBetween(from, to); + return _currentPercent; + } + _passLastFrame = true; + } + else + { + _passLastFrame = false; } do { + _fromIndex = _toIndex; from = frames[_fromIndex]; _totalDuration = from->frameID; - if (++_toIndex >= length) + _toIndex = _fromIndex + 1; + if (_toIndex >= length) { _toIndex = 0; } - _fromIndex = _toIndex; to = frames[_toIndex]; //! Guaranteed to trigger frame event - if(from->strEvent.length() != 0) + if(from->strEvent.length() != 0 && !_animation->isIgnoreFrameEvent()) { _animation->frameEvent(_bone, from->strEvent.c_str(), from->frameID, playedTime); } - if (playedTime == from->frameID) + if (playedTime == from->frameID || (_passLastFrame && _fromIndex == length-1)) { break; } @@ -447,16 +474,10 @@ float Tween::updateFrameData(float currentPercent) /* * If frame tween easing equal to TWEEN_EASING_MAX, then it will not do tween. */ - - CCTweenType tweenType; - - if ( _frameTweenEasing != TWEEN_EASING_MAX) + TweenType tweenType = (_frameTweenEasing != Linear) ? _frameTweenEasing : _tweenEasing; + if (tweenType != TWEEN_EASING_MAX && tweenType != Linear) { - tweenType = (_tweenEasing == TWEEN_EASING_MAX) ? _frameTweenEasing : _tweenEasing; - if (tweenType != TWEEN_EASING_MAX && tweenType != Linear) - { - currentPercent = TweenFunction::tweenTo(0, 1, currentPercent, 1, tweenType); - } + currentPercent = TweenFunction::tweenTo(0, 1, currentPercent, 1, tweenType); } return currentPercent; diff --git a/cocos/editor-support/cocostudio/CCTween.h b/cocos/editor-support/cocostudio/CCTween.h index 80b6c6d7e9..8b4dcba9d2 100644 --- a/cocos/editor-support/cocostudio/CCTween.h +++ b/cocos/editor-support/cocostudio/CCTween.h @@ -83,14 +83,14 @@ public: */ virtual void play(MovementBoneData *movementBoneData, int durationTo, int durationTween, int loop, int tweenEasing); - inline void setAnimation(ArmatureAnimation *animation) - { - _animation = animation; - } - inline ArmatureAnimation *getAnimation() const - { - return _animation; - } + inline void setAnimation(ArmatureAnimation *animation) { _animation = animation; } + inline ArmatureAnimation *getAnimation() const { return _animation; } + + virtual void gotoAndPlay(int frameIndex); + virtual void gotoAndPause(int frameIndex); + + virtual void setMovementBoneData(MovementBoneData *data) { _movementBoneData = data; } + virtual const MovementBoneData *getMovementBoneData() const { return _movementBoneData; } protected: /** @@ -111,7 +111,7 @@ protected: /** * According to the percent to calculate current FrameData with tween effect */ - virtual FrameData *tweenNodeTo(float percent, FrameData *node = NULL); + virtual FrameData *tweenNodeTo(float percent, FrameData *node = nullptr); /** * According to the percent to calculate current color with tween effect @@ -124,27 +124,28 @@ protected: virtual void arriveKeyFrame(FrameData *keyFrameData); protected: //! A weak reference to the current MovementBoneData. The data is in the data pool - CC_SYNTHESIZE(MovementBoneData *, _movementBoneData, MovementBoneData) + MovementBoneData *_movementBoneData; - FrameData *_tweenData; //! The computational tween frame data, //! A weak reference to the Bone's tweenData - FrameData *_from; //! From frame data, used for calculate between value - FrameData *_to; //! To frame data, used for calculate between value - FrameData *_between; //! Between frame data, used for calculate current FrameData(m_pNode) value + FrameData *_tweenData; //! The computational tween frame data, //! A weak reference to the Bone's tweenData + FrameData *_from; //! From frame data, used for calculate between value + FrameData *_to; //! To frame data, used for calculate between value + FrameData *_between; //! Between frame data, used for calculate current FrameData(m_pNode) value - Bone *_bone; //! A weak reference to the Bone + Bone *_bone; //! A weak reference to the Bone - CCTweenType _frameTweenEasing; //! Dedermine which tween effect current frame use + TweenType _frameTweenEasing; //! Dedermine which tween effect current frame use - int _betweenDuration; //! Current key frame will last _betweenDuration frames + int _betweenDuration; //! Current key frame will last _betweenDuration frames int _totalDuration; - int _fromIndex; //! The current frame index in FrameList of MovementBoneData, it's different from m_iFrameIndex - int _toIndex; //! The next frame index in FrameList of MovementBoneData, it's different from m_iFrameIndex + int _fromIndex; //! The current frame index in FrameList of MovementBoneData, it's different from m_iFrameIndex + int _toIndex; //! The next frame index in FrameList of MovementBoneData, it's different from m_iFrameIndex ArmatureAnimation *_animation; + bool _passLastFrame; //! If current frame index is more than the last frame's index }; } diff --git a/cocos/editor-support/cocostudio/CCTweenFunction.cpp b/cocos/editor-support/cocostudio/CCTweenFunction.cpp index 37b523fc79..74e4471768 100644 --- a/cocos/editor-support/cocostudio/CCTweenFunction.cpp +++ b/cocos/editor-support/cocostudio/CCTweenFunction.cpp @@ -27,7 +27,7 @@ THE SOFTWARE. namespace cocostudio { -float TweenFunction::tweenTo(float from, float change, float time, float duration, CCTweenType tweenType) +float TweenFunction::tweenTo(float from, float change, float time, float duration, TweenType tweenType) { float delta = 0; @@ -163,8 +163,8 @@ float TweenFunction::quadEaseOut(float t, float b, float c, float d) } float TweenFunction::quadEaseInOut(float t, float b, float c, float d) { - t /= d; - if ((t / 2) < 1) + t = t/d*2; + if ((t) < 1) return c / 2 * t * t + b; --t; return -c / 2 * (t * (t - 2) - 1) + b; @@ -182,8 +182,8 @@ float TweenFunction::cubicEaseOut(float t, float b, float c, float d) } float TweenFunction::cubicEaseInOut(float t, float b, float c, float d) { - t /= d; - if ((t / 2) < 1) + t = t/d*2; + if ((t) < 1) return c / 2 * t * t * t + b; t -= 2; return c / 2 * (t * t * t + 2) + b; @@ -201,8 +201,8 @@ float TweenFunction::quartEaseOut(float t, float b, float c, float d) } float TweenFunction::quartEaseInOut(float t, float b, float c, float d) { - t /= d; - if ((t / 2) < 1) + t = t/d*2; + if ((t) < 1) return c / 2 * t * t * t * t + b; t -= 2; return -c / 2 * (t * t * t * t - 2) + b; @@ -220,8 +220,8 @@ float TweenFunction::quintEaseOut(float t, float b, float c, float d) } float TweenFunction::quintEaseInOut(float t, float b, float c, float d) { - t /= d; - if ((t / 2) < 1) + t = t/d*2; + if ((t) < 1) return c / 2 * t * t * t * t * t + b; t -= 2; return c / 2 * (t * t * t * t * t + 2) + b; @@ -272,8 +272,8 @@ float TweenFunction::circEaseOut(float t, float b, float c, float d) } float TweenFunction::circEaseInOut(float t, float b, float c, float d) { - t /= d; - if ((t / 2) < 1) + t = t/d*2; + if ((t) < 1) return -c / 2 * (sqrt(1 - t * t) - 1) + b; t -= 2; return c / 2 * (sqrt(1 - t * t) + 1) + b; @@ -323,8 +323,8 @@ float TweenFunction::elasticEaseInOut(float t, float b, float c, float d, float float s = 0; if (t == 0) return b; - t /= d; - if ((t / 2) == 2) + t = t/d*2; + if ((t) == 2) return b + c; if (!p) p = d * (.3 * 1.5); diff --git a/cocos/editor-support/cocostudio/CCTweenFunction.h b/cocos/editor-support/cocostudio/CCTweenFunction.h index 255d19d58e..ff7ad6016d 100644 --- a/cocos/editor-support/cocostudio/CCTweenFunction.h +++ b/cocos/editor-support/cocostudio/CCTweenFunction.h @@ -31,16 +31,15 @@ THE SOFTWARE. namespace cocostudio { -enum CCTweenType +enum TweenType { TWEEN_EASING_MIN = -1, Linear, Sine_EaseIn, - Sine_EaseInOut, Sine_EaseOut, - + Sine_EaseInOut, Quad_EaseIn, Quad_EaseOut, @@ -85,7 +84,7 @@ class TweenFunction { public: - static float tweenTo(float from, float change, float time, float duration, CCTweenType tweenType); + static float tweenTo(float from, float change, float time, float duration, TweenType tweenType); static float linear(float t, float b, float c, float d); diff --git a/cocos/editor-support/cocostudio/CMakeLists.txt b/cocos/editor-support/cocostudio/CMakeLists.txt new file mode 100644 index 0000000000..acff17a4a9 --- /dev/null +++ b/cocos/editor-support/cocostudio/CMakeLists.txt @@ -0,0 +1,54 @@ +set(CS_SRC + CCActionFrame.cpp + CCActionFrameEasing.cpp + CCActionManagerEx.cpp + CCActionNode.cpp + CCActionObject.cpp + CCArmature.cpp + CCBone.cpp + CCArmatureAnimation.cpp + CCProcessBase.cpp + CCTween.cpp + CCDatas.cpp + CCBatchNode.cpp + CCDecorativeDisplay.cpp + CCDisplayFactory.cpp + CCDisplayManager.cpp + CCSkin.cpp + CCColliderDetector.cpp + CCArmatureDataManager.cpp + CCArmatureDefine.cpp + CCDataReaderHelper.cpp + CCSpriteFrameCacheHelper.cpp + CCTransformHelp.cpp + CCTweenFunction.cpp + CCUtilMath.cpp + CCComAttribute.cpp + CCComAudio.cpp + CCComController.cpp + CCComRender.cpp + CCInputDelegate.cpp + CSContentJsonDictionary.cpp + DictionaryHelper.cpp + CCSGUIReader.cpp + CCSSceneReader.cpp +) + +include_directories( + .. +) + +add_library(cocostudio STATIC + ${CS_SRC} +) + +target_link_libraries(cocostudio + jsoncpp +) + +set_target_properties(cocostudio + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/cocos/editor-support/cocostudio/Makefile b/cocos/editor-support/cocostudio/Makefile deleted file mode 100644 index 810c28372e..0000000000 --- a/cocos/editor-support/cocostudio/Makefile +++ /dev/null @@ -1,69 +0,0 @@ -TARGET = libcocostudio.a - -COCOS_ROOT=../../.. - -INCLUDES = -I../../2d \ --I../../../external \ --I.. \ --I../.. \ - -SOURCES = CCActionFrame.cpp \ -CCActionFrameEasing.cpp \ -CCActionManagerEx.cpp \ -CCActionNode.cpp \ -CCActionObject.cpp \ -CCArmature.cpp \ -CCBone.cpp \ -CCArmatureAnimation.cpp \ -CCProcessBase.cpp \ -CCTween.cpp \ -CCDatas.cpp \ -CCBatchNode.cpp \ -CCDecorativeDisplay.cpp \ -CCDisplayFactory.cpp \ -CCDisplayManager.cpp \ -CCSkin.cpp \ -CCColliderDetector.cpp \ -CCArmatureDataManager.cpp \ -CCArmatureDefine.cpp \ -CCDataReaderHelper.cpp \ -CCSpriteFrameCacheHelper.cpp \ -CCTransformHelp.cpp \ -CCTweenFunction.cpp \ -CCUtilMath.cpp \ -CCComAttribute.cpp \ -CCComAudio.cpp \ -CCComController.cpp \ -CCComRender.cpp \ -CCInputDelegate.cpp \ -CSContentJsonDictionary.cpp \ -DictionaryHelper.cpp \ -CCSGUIReader.cpp \ -CCSSceneReader.cpp \ -../../../external/json/json_reader.cpp \ -../../../external/json/json_value.cpp \ -../../../external/json/json_writer.cpp - -include ../../2d/cocos2dx.mk - -CXXFLAGS += -Wno-multichar - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) - -$(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 $@ diff --git a/cocos/editor-support/spine/Animation.cpp b/cocos/editor-support/spine/Animation.cpp index 655e80be06..0cded9e16a 100644 --- a/cocos/editor-support/spine/Animation.cpp +++ b/cocos/editor-support/spine/Animation.cpp @@ -248,12 +248,12 @@ void _RotateTimeline_apply (const Timeline* timeline, Skeleton* skeleton, float bone = skeleton->bones[self->boneIndex]; if (time >= self->frames[self->framesLength - 2]) { /* Time is after last frame. */ - float amount = bone->data->rotation + self->frames[self->framesLength - 1] - bone->rotation; - while (amount > 180) - amount -= 360; - while (amount < -180) - amount += 360; - bone->rotation += amount * alpha; + float count = bone->data->rotation + self->frames[self->framesLength - 1] - bone->rotation; + while (count > 180) + count -= 360; + while (count < -180) + count += 360; + bone->rotation += count * alpha; return; } diff --git a/cocos/editor-support/spine/CMakeLists.txt b/cocos/editor-support/spine/CMakeLists.txt new file mode 100644 index 0000000000..0d6664b98d --- /dev/null +++ b/cocos/editor-support/spine/CMakeLists.txt @@ -0,0 +1,38 @@ +set(SPINE_SRC + Animation.cpp + AnimationState.cpp + AnimationStateData.cpp + Atlas.cpp + AtlasAttachmentLoader.cpp + Attachment.cpp + AttachmentLoader.cpp + Bone.cpp + BoneData.cpp + Json.cpp + RegionAttachment.cpp + Skeleton.cpp + SkeletonData.cpp + SkeletonJson.cpp + Skin.cpp + Slot.cpp + SlotData.cpp + extension.cpp + spine-cocos2dx.cpp + CCSkeleton.cpp + CCSkeletonAnimation.cpp +) + +include_directories( + .. +) + +add_library(spine STATIC + ${SPINE_SRC} +) + +set_target_properties(spine + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/cocos/editor-support/spine/Makefile b/cocos/editor-support/spine/Makefile deleted file mode 100644 index 88514a824e..0000000000 --- a/cocos/editor-support/spine/Makefile +++ /dev/null @@ -1,42 +0,0 @@ -TARGET = libspine.a - -INCLUDES = -I.. - -SOURCES = Animation.cpp \ -AnimationState.cpp \ -AnimationStateData.cpp \ -Atlas.cpp \ -AtlasAttachmentLoader.cpp \ -Attachment.cpp \ -AttachmentLoader.cpp \ -Bone.cpp \ -BoneData.cpp \ -Json.cpp \ -RegionAttachment.cpp \ -Skeleton.cpp \ -SkeletonData.cpp \ -SkeletonJson.cpp \ -Skin.cpp \ -Slot.cpp \ -SlotData.cpp \ -extension.cpp \ -spine-cocos2dx.cpp \ -CCSkeleton.cpp \ -CCSkeletonAnimation.cpp - -include ../../2d/cocos2dx.mk - -CXXFLAGS += -Wno-multichar - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - diff --git a/cocos/editor-support/spine/SkeletonJson.cpp b/cocos/editor-support/spine/SkeletonJson.cpp index 98e4be4334..6bfeeb24e7 100644 --- a/cocos/editor-support/spine/SkeletonJson.cpp +++ b/cocos/editor-support/spine/SkeletonJson.cpp @@ -118,7 +118,7 @@ static Animation* _SkeletonJson_readAnimation (SkeletonJson* self, Json* root, S skeletonData->animationCount++; for (i = 0; i < boneCount; ++i) { - int timelineCount; + timelineCount = 0; Json* boneMap = Json_getItemAt(bones, i); const char* boneName = boneMap->name; @@ -175,7 +175,7 @@ static Animation* _SkeletonJson_readAnimation (SkeletonJson* self, Json* root, S } for (i = 0; i < slotCount; ++i) { - int timelineCount; + timelineCount = 0; Json* slotMap = Json_getItemAt(slots, i); const char* slotName = slotMap->name; diff --git a/cocos/editor-support/spine/spine-cocos2dx.cpp b/cocos/editor-support/spine/spine-cocos2dx.cpp index cd9ea67e30..298031aaab 100644 --- a/cocos/editor-support/spine/spine-cocos2dx.cpp +++ b/cocos/editor-support/spine/spine-cocos2dx.cpp @@ -31,7 +31,7 @@ USING_NS_CC; namespace spine { void _AtlasPage_createTexture (AtlasPage* self, const char* path) { - Texture2D* texture = TextureCache::getInstance()->addImage(path); + Texture2D* texture = Director::getInstance()->getTextureCache()->addImage(path); TextureAtlas* textureAtlas = TextureAtlas::createWithTexture(texture, 4); textureAtlas->retain(); self->rendererObject = textureAtlas; @@ -47,7 +47,7 @@ void _AtlasPage_disposeTexture (AtlasPage* self) { } char* _Util_readFile (const char* path, int* length) { - unsigned long size; + long size; char* data = reinterpret_cast(FileUtils::getInstance()->getFileData( FileUtils::getInstance()->fullPathForFilename(path).c_str(), "r", &size)); *length = size; diff --git a/cocos/gui/Android.mk b/cocos/gui/Android.mk index 33171c7c1d..17f15efe44 100644 --- a/cocos/gui/Android.mk +++ b/cocos/gui/Android.mk @@ -7,14 +7,13 @@ LOCAL_MODULE_FILENAME := libgui LOCAL_SRC_FILES := UIRootWidget.cpp \ UIWidget.cpp \ -Layout.cpp \ -LayoutParameter.cpp \ +UILayout.cpp \ +UILayoutParameter.cpp \ UILayoutDefine.cpp \ CocosGUI.cpp \ UIHelper.cpp \ UIInputManager.cpp \ UILayer.cpp \ -UIDragPanel.cpp \ UIListView.cpp \ UIPageView.cpp \ UIScrollView.cpp \ diff --git a/cocos/gui/CMakeLists.txt b/cocos/gui/CMakeLists.txt new file mode 100644 index 0000000000..d4b428f890 --- /dev/null +++ b/cocos/gui/CMakeLists.txt @@ -0,0 +1,33 @@ +set(GUI_SRC + UIRootWidget.cpp + UIWidget.cpp + UILayout.cpp + UILayoutParameter.cpp + UILayoutDefine.cpp + CocosGUI.cpp + UIHelper.cpp + UIInputManager.cpp + UILayer.cpp + UIListView.cpp + UIPageView.cpp + UIScrollView.cpp + UIButton.cpp + UICheckBox.cpp + UIImageView.cpp + UILabel.cpp + UILabelAtlas.cpp + UILabelBMFont.cpp + UILoadingBar.cpp + UISlider.cpp + UITextField.cpp +) + +add_library(gui STATIC + ${GUI_SRC} +) + +set_target_properties(gui + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) diff --git a/cocos/gui/CocosGUI.h b/cocos/gui/CocosGUI.h index 497c4f89b6..663aff26e7 100644 --- a/cocos/gui/CocosGUI.h +++ b/cocos/gui/CocosGUI.h @@ -27,7 +27,7 @@ #include "gui/UIWidget.h" -#include "gui/Layout.h" +#include "gui/UILayout.h" #include "gui/UIRootWidget.h" #include "gui/UIButton.h" #include "gui/UICheckBox.h" @@ -36,10 +36,9 @@ #include "gui/UILabelAtlas.h" #include "gui/UILoadingBar.h" #include "gui/UIScrollView.h" +#include "gui/UIListView.h" #include "gui/UISlider.h" #include "gui/UITextField.h" -#include "gui/UIListView.h" -#include "gui/UIDragPanel.h" #include "gui/UILabelBMFont.h" #include "gui/UIPageView.h" #include "gui/UIHelper.h" diff --git a/cocos/gui/Layout.cpp b/cocos/gui/Layout.cpp deleted file mode 100644 index a9e4f75a30..0000000000 --- a/cocos/gui/Layout.cpp +++ /dev/null @@ -1,785 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "gui/Layout.h" -#include "gui/UILayer.h" -#include "gui/UIHelper.h" -#include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" - - using namespace cocos2d; - using namespace cocos2d::extension; - -namespace gui { - -#define DYNAMIC_CAST_CLIPPINGLAYER dynamic_cast(_renderer) - -Layout::Layout(): -_clippingEnabled(false), -_backGroundScale9Enabled(false), -_backGroundImage(NULL), -_backGroundImageFileName(""), -_backGroundImageCapInsets(Rect::ZERO), -_colorType(LAYOUT_COLOR_NONE), -_bgImageTexType(UI_TEX_TYPE_LOCAL), -_colorRender(NULL), -_gradientRender(NULL), -_cColor(Color3B::WHITE), -_gStartColor(Color3B::WHITE), -_gEndColor(Color3B::WHITE), -_alongVector(Point(0.0f, -1.0f)), -_cOpacity(255), -_backGroundImageTextureSize(Size::ZERO), -_layoutType(LAYOUT_ABSOLUTE) -{ - _widgetType = WidgetTypeContainer; -} - -Layout::~Layout() -{ -} - -Layout* Layout::create() -{ - Layout* layout = new Layout(); - if (layout && layout->init()) - { - layout->autorelease(); - return layout; - } - CC_SAFE_DELETE(layout); - return NULL; -} - -bool Layout::init() -{ - _children = CCArray::create(); - _children->retain(); - initRenderer(); - _renderer->retain(); - _renderer->setZOrder(_widgetZOrder); - RGBAProtocol* renderRGBA = dynamic_cast(_renderer); - if (renderRGBA) - { - renderRGBA->setCascadeColorEnabled(false); - renderRGBA->setCascadeOpacityEnabled(false); - } - ignoreContentAdaptWithSize(false); - setSize(Size::ZERO); - setBright(true); - setAnchorPoint(Point(0, 0)); - _scheduler = Director::getInstance()->getScheduler(); - CC_SAFE_RETAIN(_scheduler); - return true; -} - -void Layout::initRenderer() -{ - _renderer = RectClippingNode::create(); -} - -bool Layout::isClippingEnabled() -{ - return _clippingEnabled; -} - -bool Layout::hitTest(const Point &pt) -{ - Point nsp = _renderer->convertToNodeSpace(pt); - Rect bb = Rect(0.0f, 0.0f, _size.width, _size.height); - if (nsp.x >= bb.origin.x && nsp.x <= bb.origin.x + bb.size.width && nsp.y >= bb.origin.y && nsp.y <= bb.origin.y + bb.size.height) - { - return true; - } - return false; -} - -void Layout::setClippingEnabled(bool able) -{ - _clippingEnabled = able; - DYNAMIC_CAST_CLIPPINGLAYER->setClippingEnabled(able); -} - -void Layout::onSizeChanged() -{ - DYNAMIC_CAST_CLIPPINGLAYER->setClippingSize(_size); - doLayout(); - if (_backGroundImage) - { - _backGroundImage->setPosition(Point(_size.width/2.0f, _size.height/2.0f)); - if (_backGroundScale9Enabled) - { - dynamic_cast(_backGroundImage)->setPreferredSize(_size); - } - } - if (_colorRender) - { - _colorRender->setContentSize(_size); - } - if (_gradientRender) - { - _gradientRender->setContentSize(_size); - } -} - -void Layout::setBackGroundImageScale9Enabled(bool able) -{ - if (_backGroundScale9Enabled == able) - { - return; - } - _renderer->removeChild(_backGroundImage, true); - _backGroundImage = NULL; - _backGroundScale9Enabled = able; - if (_backGroundScale9Enabled) - { - _backGroundImage = Scale9Sprite::create(); - _renderer->addChild(_backGroundImage); - } - else - { - _backGroundImage = Sprite::create(); - _renderer->addChild(_backGroundImage); - } - _backGroundImage->setZOrder(-1); - setBackGroundImage(_backGroundImageFileName.c_str(),_bgImageTexType); - setBackGroundImageCapInsets(_backGroundImageCapInsets); -} - -void Layout::setBackGroundImage(const char* fileName,TextureResType texType) -{ - if (!fileName || strcmp(fileName, "") == 0) - { - return; - } - if (_backGroundImage == NULL) - { - addBackGroundImage(); - } - _backGroundImageFileName = fileName; - _bgImageTexType = texType; - if (_backGroundScale9Enabled) - { - switch (_bgImageTexType) - { - case UI_TEX_TYPE_LOCAL: - dynamic_cast(_backGroundImage)->initWithFile(fileName); - break; - case UI_TEX_TYPE_PLIST: - dynamic_cast(_backGroundImage)->initWithSpriteFrameName(fileName); - break; - default: - break; - } - dynamic_cast(_backGroundImage)->setPreferredSize(_size); - } - else - { - switch (_bgImageTexType) - { - case UI_TEX_TYPE_LOCAL: - dynamic_cast(_backGroundImage)->initWithFile(fileName); - break; - case UI_TEX_TYPE_PLIST: - dynamic_cast(_backGroundImage)->initWithSpriteFrameName(fileName); - break; - default: - break; - } - } - if (_backGroundScale9Enabled) - { - dynamic_cast(_backGroundImage)->setColor(getColor()); - dynamic_cast(_backGroundImage)->setOpacity(getOpacity()); - } - else - { - dynamic_cast(_backGroundImage)->setColor(getColor()); - dynamic_cast(_backGroundImage)->setOpacity(getOpacity()); - } - _backGroundImageTextureSize = _backGroundImage->getContentSize(); - _backGroundImage->setPosition(Point(_size.width/2.0f, _size.height/2.0f)); -} - -void Layout::setBackGroundImageCapInsets(const Rect &capInsets) -{ - _backGroundImageCapInsets = capInsets; - if (_backGroundScale9Enabled) - { - dynamic_cast(_backGroundImage)->setCapInsets(capInsets); - } -} - -void Layout::addBackGroundImage() -{ - if (_backGroundScale9Enabled) - { - _backGroundImage = Scale9Sprite::create(); - _backGroundImage->setZOrder(-1); - _renderer->addChild(_backGroundImage); - dynamic_cast(_backGroundImage)->setPreferredSize(_size); - } - else - { - _backGroundImage = CCSprite::create(); - _backGroundImage->setZOrder(-1); - _renderer->addChild(_backGroundImage); - } - _backGroundImage->setPosition(Point(_size.width/2.0f, _size.height/2.0f)); -} - -void Layout::removeBackGroundImage() -{ - if (!_backGroundImage) - { - return; - } - _renderer->removeChild(_backGroundImage, true); - _backGroundImage = NULL; - _backGroundImageFileName = ""; - _backGroundImageTextureSize = Size::ZERO; -} - -void Layout::setBackGroundColorType(LayoutBackGroundColorType type) -{ - if (_colorType == type) - { - return; - } - switch (_colorType) - { - case LAYOUT_COLOR_NONE: - if (_colorRender) - { - _renderer->removeChild(_colorRender, true); - _colorRender = NULL; - } - if (_gradientRender) - { - _renderer->removeChild(_gradientRender, true); - _gradientRender = NULL; - } - break; - case LAYOUT_COLOR_SOLID: - if (_colorRender) - { - _renderer->removeChild(_colorRender, true); - _colorRender = NULL; - } - break; - case LAYOUT_COLOR_GRADIENT: - if (_gradientRender) - { - _renderer->removeChild(_gradientRender, true); - _gradientRender = NULL; - } - break; - default: - break; - } - _colorType = type; - switch (_colorType) - { - case LAYOUT_COLOR_NONE: - break; - case LAYOUT_COLOR_SOLID: - _colorRender = CCLayerColor::create(); - _colorRender->setContentSize(_size); - _colorRender->setOpacity(_cOpacity); - _colorRender->setColor(_cColor); - _renderer->addChild(_colorRender,-2); - break; - case LAYOUT_COLOR_GRADIENT: - _gradientRender = CCLayerGradient::create(); - _gradientRender->setContentSize(_size); - _gradientRender->setOpacity(_cOpacity); - _gradientRender->setStartColor(_gStartColor); - _gradientRender->setEndColor(_gEndColor); - _gradientRender->setVector(_alongVector); - _renderer->addChild(_gradientRender,-2); - break; - default: - break; - } -} - -void Layout::setBackGroundColor(const Color3B &color) -{ - _cColor = color; - if (_colorRender) - { - _colorRender->setColor(color); - } -} - -void Layout::setBackGroundColor(const Color3B &startColor, const Color3B &endColor) -{ - _gStartColor = startColor; - if (_gradientRender) - { - _gradientRender->setStartColor(startColor); - } - _gEndColor = endColor; - if (_gradientRender) - { - _gradientRender->setEndColor(endColor); - } -} - -void Layout::setBackGroundColorOpacity(int opacity) -{ - _cOpacity = opacity; - switch (_colorType) - { - case LAYOUT_COLOR_NONE: - break; - case LAYOUT_COLOR_SOLID: - _colorRender->setOpacity(opacity); - break; - case LAYOUT_COLOR_GRADIENT: - _gradientRender->setOpacity(opacity); - break; - default: - break; - } -} - -void Layout::setBackGroundColorVector(const Point &vector) -{ - _alongVector = vector; - if (_gradientRender) - { - _gradientRender->setVector(vector); - } -} - -void Layout::setColor(const Color3B &color) -{ - UIWidget::setColor(color); - if (_backGroundImage) - { - RGBAProtocol* rgbap = dynamic_cast(_backGroundImage); - if (rgbap) - { - rgbap->setColor(color); - } - } -} - -void Layout::setOpacity(int opacity) -{ - UIWidget::setOpacity(opacity); - if (_backGroundImage) - { - RGBAProtocol* rgbap = dynamic_cast(_backGroundImage); - if (rgbap) - { - rgbap->setOpacity(opacity); - } - } -} - -const Size& Layout::getBackGroundImageTextureSize() const -{ - return _backGroundImageTextureSize; -} - -const Size& Layout::getContentSize() const -{ - return _renderer->getContentSize(); -} - -void Layout::setLayoutType(LayoutType type) -{ - _layoutType = type; -} - -LayoutType Layout::getLayoutType() const -{ - return _layoutType; -} - -void Layout::doLayout() -{ - switch (_layoutType) - { - case LAYOUT_ABSOLUTE: - break; - case LAYOUT_LINEAR_VERTICAL: - { - ccArray* layoutChildrenArray = getChildren()->data; - int length = layoutChildrenArray->num; - Size layoutSize = getSize(); - float topBoundary = layoutSize.height; - for (int i=0; i(layoutChildrenArray->arr[i]); - LinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter()); - - if (layoutParameter) - { - WidgetType childType = child->getWidgetType(); - UILinearGravity childGravity = layoutParameter->getGravity(); - Point ap = child->getAnchorPoint(); - Size cs = child->getSize(); - float finalPosX = childType == WidgetTypeWidget ? ap.x * cs.width : 0.0f; - float finalPosY = childType == WidgetTypeWidget ? topBoundary - ((1.0f-ap.y) * cs.height) : topBoundary - cs.height; - switch (childGravity) - { - case LINEAR_GRAVITY_NONE: - case LINEAR_GRAVITY_LEFT: - break; - case LINEAR_GRAVITY_RIGHT: - finalPosX = childType == WidgetTypeWidget ? layoutSize.width - ((1.0f - ap.x) * cs.width) : layoutSize.width - cs.width; - break; - case LINEAR_GRAVITY_CENTER_HORIZONTAL: - finalPosX = childType == WidgetTypeWidget ? layoutSize.width / 2.0f - cs.width * (0.5f-ap.x) : (layoutSize.width - cs.width) * 0.5f; - break; - default: - break; - } - UIMargin mg = layoutParameter->getMargin(); - finalPosX += mg.left; - finalPosY -= mg.top; - child->setPosition(Point(finalPosX, finalPosY)); - topBoundary = child->getBottomInParent() - mg.bottom; - } - } - break; - } - case LAYOUT_LINEAR_HORIZONTAL: - { - ccArray* layoutChildrenArray = getChildren()->data; - int length = layoutChildrenArray->num; - Size layoutSize = getSize(); - float leftBoundary = 0.0f; - for (int i=0; i(layoutChildrenArray->arr[i]); - LinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter()); - - if (layoutParameter) - { - WidgetType childType = child->getWidgetType(); - UILinearGravity childGravity = layoutParameter->getGravity(); - Point ap = child->getAnchorPoint(); - Size cs = child->getSize(); - float finalPosX = childType == WidgetTypeWidget ? leftBoundary + (ap.x * cs.width) : leftBoundary; - float finalPosY = childType == WidgetTypeWidget ? layoutSize.height - (1.0f - ap.y) * cs.height : layoutSize.height - cs.height; - switch (childGravity) - { - case LINEAR_GRAVITY_NONE: - case LINEAR_GRAVITY_TOP: - break; - case LINEAR_GRAVITY_BOTTOM: - finalPosY = childType == WidgetTypeWidget ? ap.y * cs.height : 0.0f; - break; - case LINEAR_GRAVITY_CENTER_VERTICAL: - finalPosY = childType == WidgetTypeWidget ? layoutSize.height/2.0f - cs.height * (0.5f - ap.y) : (layoutSize.height - cs.height) * 0.5f; - break; - default: - break; - } - UIMargin mg = layoutParameter->getMargin(); - finalPosX += mg.left; - finalPosY -= mg.top; - child->setPosition(Point(finalPosX, finalPosY)); - leftBoundary = child->getRightInParent() + mg.right; - } - } - break; - } - case LAYOUT_RELATIVE: - { - ccArray* layoutChildrenArray = getChildren()->data; - int length = layoutChildrenArray->num; - Size layoutSize = getSize(); - for (int i=0; i(layoutChildrenArray->arr[i]); - WidgetType childType = child->getWidgetType(); - Point ap = child->getAnchorPoint(); - Size cs = child->getSize(); - RelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter()); - if (layoutParameter) - { - float finalPosX = childType == WidgetTypeWidget ? ap.x * cs.width : 0.0f; - float finalPosY = childType == WidgetTypeWidget ? layoutSize.height - ((1.0f - ap.y) * cs.height) : layoutSize.height - cs.height; - UIRelativeAlign align = layoutParameter->getAlign(); - const char* relativeName = layoutParameter->getRelativeToWidgetName(); - UIWidget* relativeWidget = NULL; - if (relativeName && strcmp(relativeName, "")) - { - relativeWidget = CCUIHELPER->seekWidgetByRelativeName(this, relativeName); - } - switch (align) - { - case RELATIVE_ALIGN_NONE: - break; - case RELATIVE_ALIGN_PARENT_LEFT: - break; - case RELATIVE_ALIGN_PARENT_TOP: - break; - case RELATIVE_ALIGN_PARENT_RIGHT: - finalPosX = childType == WidgetTypeWidget ? layoutSize.width - ((1.0f - ap.x) * cs.width) : layoutSize.width - cs.width; - break; - case RELATIVE_ALIGN_PARENT_BOTTOM: - finalPosY = childType == WidgetTypeWidget ? ap.y * cs.height : 0.0f; - break; - case RELATIVE_CENTER_IN_PARENT: - finalPosX = childType == WidgetTypeWidget ? layoutSize.width * 0.5f - cs.width * (0.5f - ap.x) : (layoutSize.width - cs.width) * 0.5f; - finalPosY = childType == WidgetTypeWidget ? layoutSize.height * 0.5f - cs.height * (0.5f - ap.y) : (layoutSize.height - cs.height) * 0.5f; - break; - case RELATIVE_CENTER_HORIZONTAL: - finalPosX = childType == WidgetTypeWidget ? layoutSize.width * 0.5f - cs.width * (0.5f - ap.x) : (layoutSize.width - cs.width) * 0.5f; - break; - case RELATIVE_CENTER_VERTICAL: - finalPosY = childType == WidgetTypeWidget ? layoutSize.height * 0.5f - cs.height * (0.5f - ap.y) : (layoutSize.height - cs.height) * 0.5f; - break; - case RELATIVE_LOCATION_LEFT_OF_TOPALIGN: - if (relativeWidget) - { - float locationTop = relativeWidget->getTopInParent(); - float locationRight = relativeWidget->getLeftInParent(); - finalPosY = childType == WidgetTypeWidget ? locationTop - ap.y * cs.height : locationTop - cs.height; - finalPosX = childType == WidgetTypeWidget ? locationRight - (1.0f - ap.x) * cs.width : locationRight - cs.width; - } - break; - case RELATIVE_LOCATION_LEFT_OF_CENTER: - break; - case RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN: - if (relativeWidget) - { - float locationRight = relativeWidget->getLeftInParent(); - float locationBottom = relativeWidget->getBottomInParent(); - finalPosY = childType == WidgetTypeWidget ? locationBottom + ap.y * cs.height : locationBottom; - finalPosX = childType == WidgetTypeWidget ? locationRight - (1.0f - ap.x) * cs.width : locationRight - cs.width; - } - break; - case RELATIVE_LOCATION_RIGHT_OF_TOPALIGN: - if (relativeWidget) - { - float locationTop = relativeWidget->getTopInParent(); - float locationLeft = relativeWidget->getRightInParent(); - finalPosY = childType == WidgetTypeWidget ? locationTop - ap.y * cs.height : locationTop - cs.height; - finalPosX = childType == WidgetTypeWidget ? locationLeft + ap.x * cs.width : locationLeft; - } - break; - case RELATIVE_LOCATION_RIGHT_OF_CENTER: - break; - case RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN: - if (relativeWidget) - { - float locationLeft = relativeWidget->getRightInParent(); - float locationBottom = relativeWidget->getBottomInParent(); - finalPosY = childType == WidgetTypeWidget ? locationBottom + ap.y * cs.height : locationBottom; - finalPosX = childType == WidgetTypeWidget ? locationLeft + ap.x * cs.width : locationLeft; - } - break; - case RELATIVE_LOCATION_ABOVE_LEFTALIGN: - if (relativeWidget) - { - float locationBottom = relativeWidget->getTopInParent(); - float locationLeft = relativeWidget->getLeftInParent(); - finalPosY = childType == WidgetTypeWidget ? locationBottom + ap.y * cs.height : locationBottom; - finalPosX = childType == WidgetTypeWidget ? locationLeft + ap.x * cs.width : locationLeft; - } - break; - case RELATIVE_LOCATION_ABOVE_CENTER: - break; - case RELATIVE_LOCATION_ABOVE_RIGHTALIGN: - if (relativeWidget) - { - float locationBottom = relativeWidget->getTopInParent(); - float locationRight = relativeWidget->getRightInParent(); - finalPosY = childType == WidgetTypeWidget ? locationBottom + ap.y * cs.height : locationBottom; - finalPosX = childType == WidgetTypeWidget ? locationRight - (1.0f - ap.x) * cs.width : locationRight - cs.width; - } - break; - case RELATIVE_LOCATION_BELOW_LEFTALIGN: - if (relativeWidget) - { - float locationTop = relativeWidget->getBottomInParent(); - float locationLeft = relativeWidget->getLeftInParent(); - finalPosY = childType == WidgetTypeWidget ? locationTop - (1.0f - ap.y) * cs.height : locationTop - cs.height; - finalPosX = childType == WidgetTypeWidget ? locationLeft + ap.x * cs.width : locationLeft; - } - break; - case RELATIVE_LOCATION_BELOW_CENTER: - break; - case RELATIVE_LOCATION_BELOW_RIGHTALIGN: - if (relativeWidget) - { - float locationTop = relativeWidget->getBottomInParent(); - float locationRight = relativeWidget->getRightInParent(); - finalPosY = childType == WidgetTypeWidget ? locationTop - (1.0f - ap.y) * cs.height : locationTop - cs.height; - finalPosX = childType == WidgetTypeWidget ? locationRight - (1.0f - ap.x) * cs.width : locationRight - cs.width; - } - break; - default: - break; - } - UIMargin relativeWidgetMargin; - UIMargin mg; - if (relativeWidget) - { - relativeWidgetMargin = relativeWidget->getLayoutParameter()->getMargin(); - mg = child->getLayoutParameter()->getMargin(); - } - //handle margin - switch (align) - { - case RELATIVE_LOCATION_ABOVE_LEFTALIGN: - case RELATIVE_LOCATION_ABOVE_RIGHTALIGN: - case RELATIVE_LOCATION_ABOVE_CENTER: - finalPosY += relativeWidgetMargin.top; - finalPosY += mg.bottom; - break; - case RELATIVE_LOCATION_BELOW_LEFTALIGN: - case RELATIVE_LOCATION_BELOW_RIGHTALIGN: - case RELATIVE_LOCATION_BELOW_CENTER: - finalPosY -= relativeWidgetMargin.bottom; - finalPosY -= mg.top; - break; - case RELATIVE_LOCATION_LEFT_OF_TOPALIGN: - case RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN: - case RELATIVE_LOCATION_LEFT_OF_CENTER: - finalPosX -= relativeWidgetMargin.left; - finalPosX -= mg.right; - break; - case RELATIVE_LOCATION_RIGHT_OF_TOPALIGN: - case RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN: - case RELATIVE_LOCATION_RIGHT_OF_CENTER: - finalPosX += relativeWidgetMargin.right; - finalPosX += mg.left; - break; - default: - break; - } - child->setPosition(Point(finalPosX, finalPosY)); - } - } - break; - } - default: - break; - } -} - -const char* Layout::getDescription() const -{ - return "Layout"; -} - -RectClippingNode::RectClippingNode(): -m_pInnerStencil(NULL), -_enabled(true), -_clippingSize(Size(50.0f, 50.0f)), -_clippingEnabled(false) -{ - -} - -RectClippingNode::~RectClippingNode() -{ - -} - -RectClippingNode* RectClippingNode::create() -{ - RectClippingNode *pRet = new RectClippingNode(); - if (pRet && pRet->init()) - { - pRet->autorelease(); - } - else - { - CC_SAFE_DELETE(pRet); - } - - return pRet; -} - -bool RectClippingNode::init() -{ - m_pInnerStencil = CCDrawNode::create(); - rect[0] = Point(0, 0); - rect[1] = Point(_clippingSize.width, 0); - rect[2] = Point(_clippingSize.width, _clippingSize.height); - rect[3] = Point(0, _clippingSize.height); - - Color4F green(0, 1, 0, 1); - m_pInnerStencil->drawPolygon(rect, 4, green, 0, green); - if (CCClippingNode::init(m_pInnerStencil)) - { - return true; - } - return false; -} - - -void RectClippingNode::setClippingSize(const Size &size) -{ - setContentSize(size); - _clippingSize = size; - rect[0] = Point(0, 0); - rect[1] = Point(_clippingSize.width, 0); - rect[2] = Point(_clippingSize.width, _clippingSize.height); - rect[3] = Point(0, _clippingSize.height); - Color4F green(0, 1, 0, 1); - m_pInnerStencil->clear(); - m_pInnerStencil->drawPolygon(rect, 4, green, 0, green); -} - -void RectClippingNode::setClippingEnabled(bool enabled) -{ - _clippingEnabled = enabled; -} - -void RectClippingNode::visit() -{ - if (!_enabled) - { - return; - } - if (_clippingEnabled) - { - CCClippingNode::visit(); - } - else - { - CCNode::visit(); - } -} - -void RectClippingNode::setEnabled(bool enabled) -{ - _enabled = enabled; -} - -bool RectClippingNode::isEnabled() const -{ - return _enabled; -} - -} diff --git a/cocos/gui/Makefile b/cocos/gui/Makefile deleted file mode 100644 index 0e8501cc63..0000000000 --- a/cocos/gui/Makefile +++ /dev/null @@ -1,44 +0,0 @@ -TARGET = libgui.a - -INCLUDES = -I../ \ --I../editor-support \ --I../../external - -SOURCES = UIRootWidget.cpp \ -UIWidget.cpp \ -Layout.cpp \ -LayoutParameter.cpp \ -UILayoutDefine.cpp \ -CocosGUI.cpp \ -UIHelper.cpp \ -UIInputManager.cpp \ -UILayer.cpp \ -UIDragPanel.cpp \ -UIListView.cpp \ -UIPageView.cpp \ -UIScrollView.cpp \ -UIButton.cpp \ -UICheckBox.cpp \ -UIImageView.cpp \ -UILabel.cpp \ -UILabelAtlas.cpp \ -UILabelBMFont.cpp \ -UILoadingBar.cpp \ -UISlider.cpp \ -UITextField.cpp - -include ../2d/cocos2dx.mk - -CXXFLAGS += -Wno-multichar - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/cocos/gui/UIButton.cpp b/cocos/gui/UIButton.cpp index 12cc3cc932..d18627be1e 100644 --- a/cocos/gui/UIButton.cpp +++ b/cocos/gui/UIButton.cpp @@ -25,9 +25,6 @@ #include "gui/UIButton.h" #include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" - using namespace cocos2d; - using namespace cocos2d::extension; - namespace gui { #define NORMALRENDERERZ (0) @@ -45,9 +42,9 @@ _clickedFileName(""), _disabledFileName(""), _prevIgnoreSize(true), _scale9Enabled(false), -_capInsetsNormal(Rect::ZERO), -_capInsetsPressed(Rect::ZERO), -_capInsetsDisabled(Rect::ZERO), +_capInsetsNormal(cocos2d::Rect::ZERO), +_capInsetsPressed(cocos2d::Rect::ZERO), +_capInsetsDisabled(cocos2d::Rect::ZERO), _normalTexType(UI_TEX_TYPE_LOCAL), _pressedTexType(UI_TEX_TYPE_LOCAL), _disabledTexType(UI_TEX_TYPE_LOCAL), @@ -55,7 +52,7 @@ _normalTextureSize(_size), _pressedTextureSize(_size), _disabledTextureSize(_size), _pressedActionEnabled(false), -_titleColor(Color3B::WHITE) +_titleColor(cocos2d::Color3B::WHITE) { } @@ -88,10 +85,10 @@ bool UIButton::init() void UIButton::initRenderer() { UIWidget::initRenderer(); - _buttonNormalRenderer = Sprite::create(); - _buttonClickedRenderer = Sprite::create(); - _buttonDisableRenderer = Sprite::create(); - _titleRenderer = LabelTTF::create(); + _buttonNormalRenderer = cocos2d::Sprite::create(); + _buttonClickedRenderer = cocos2d::Sprite::create(); + _buttonDisableRenderer = cocos2d::Sprite::create(); + _titleRenderer = cocos2d::LabelTTF::create(); _renderer->addChild(_buttonNormalRenderer,NORMALRENDERERZ); _renderer->addChild(_buttonClickedRenderer,PRESSEDRENDERERZ); _renderer->addChild(_buttonDisableRenderer,DISABLEDRENDERERZ); @@ -117,15 +114,15 @@ void UIButton::setScale9Enabled(bool able) _buttonDisableRenderer = NULL; if (_scale9Enabled) { - _buttonNormalRenderer = Scale9Sprite::create(); - _buttonClickedRenderer = Scale9Sprite::create(); - _buttonDisableRenderer = Scale9Sprite::create(); + _buttonNormalRenderer = cocos2d::extension::Scale9Sprite::create(); + _buttonClickedRenderer = cocos2d::extension::Scale9Sprite::create(); + _buttonDisableRenderer = cocos2d::extension::Scale9Sprite::create(); } else { - _buttonNormalRenderer = CCSprite::create(); - _buttonClickedRenderer = CCSprite::create(); - _buttonDisableRenderer = CCSprite::create(); + _buttonNormalRenderer = cocos2d::Sprite::create(); + _buttonClickedRenderer = cocos2d::Sprite::create(); + _buttonDisableRenderer = cocos2d::Sprite::create(); } loadTextureNormal(_normalFileName.c_str(), _normalTexType); @@ -179,32 +176,33 @@ void UIButton::loadTextureNormal(const char* normal,TextureResType texType) switch (_normalTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonNormalRenderer)->initWithFile(normal); + dynamic_cast(_buttonNormalRenderer)->initWithFile(normal); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonNormalRenderer)->initWithSpriteFrameName(normal); + dynamic_cast(_buttonNormalRenderer)->initWithSpriteFrameName(normal); break; default: break; } - dynamic_cast(_buttonNormalRenderer)->setColor(getColor()); - dynamic_cast(_buttonNormalRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonNormalRenderer)->setColor(getColor()); + dynamic_cast(_buttonNormalRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonNormalRenderer)->setCapInsets(_capInsetsNormal); } else { switch (_normalTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonNormalRenderer)->initWithFile(normal); + dynamic_cast(_buttonNormalRenderer)->initWithFile(normal); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonNormalRenderer)->initWithSpriteFrameName(normal); + dynamic_cast(_buttonNormalRenderer)->initWithSpriteFrameName(normal); break; default: break; } - dynamic_cast(_buttonNormalRenderer)->setColor(getColor()); - dynamic_cast(_buttonNormalRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonNormalRenderer)->setColor(getColor()); + dynamic_cast(_buttonNormalRenderer)->setOpacity(getOpacity()); } _normalTextureSize = _buttonNormalRenderer->getContentSize(); updateAnchorPoint(); @@ -224,32 +222,33 @@ void UIButton::loadTexturePressed(const char* selected,TextureResType texType) switch (_pressedTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonClickedRenderer)->initWithFile(selected); + dynamic_cast(_buttonClickedRenderer)->initWithFile(selected); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonClickedRenderer)->initWithSpriteFrameName(selected); + dynamic_cast(_buttonClickedRenderer)->initWithSpriteFrameName(selected); break; default: break; } - dynamic_cast(_buttonClickedRenderer)->setColor(getColor()); - dynamic_cast(_buttonClickedRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonClickedRenderer)->setColor(getColor()); + dynamic_cast(_buttonClickedRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonClickedRenderer)->setCapInsets(_capInsetsPressed); } else { switch (_pressedTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonClickedRenderer)->initWithFile(selected); + dynamic_cast(_buttonClickedRenderer)->initWithFile(selected); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonClickedRenderer)->initWithSpriteFrameName(selected); + dynamic_cast(_buttonClickedRenderer)->initWithSpriteFrameName(selected); break; default: break; } - dynamic_cast(_buttonClickedRenderer)->setColor(getColor()); - dynamic_cast(_buttonClickedRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonClickedRenderer)->setColor(getColor()); + dynamic_cast(_buttonClickedRenderer)->setOpacity(getOpacity()); } _pressedTextureSize = _buttonClickedRenderer->getContentSize(); updateAnchorPoint(); @@ -269,73 +268,74 @@ void UIButton::loadTextureDisabled(const char* disabled,TextureResType texType) switch (_disabledTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonDisableRenderer)->initWithFile(disabled); + dynamic_cast(_buttonDisableRenderer)->initWithFile(disabled); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonDisableRenderer)->initWithSpriteFrameName(disabled); + dynamic_cast(_buttonDisableRenderer)->initWithSpriteFrameName(disabled); break; default: break; } - dynamic_cast(_buttonDisableRenderer)->setColor(getColor()); - dynamic_cast(_buttonDisableRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonDisableRenderer)->setColor(getColor()); + dynamic_cast(_buttonDisableRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonDisableRenderer)->setCapInsets(_capInsetsDisabled); } else { switch (_disabledTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonDisableRenderer)->initWithFile(disabled); + dynamic_cast(_buttonDisableRenderer)->initWithFile(disabled); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonDisableRenderer)->initWithSpriteFrameName(disabled); + dynamic_cast(_buttonDisableRenderer)->initWithSpriteFrameName(disabled); break; default: break; } - dynamic_cast(_buttonDisableRenderer)->setColor(getColor()); - dynamic_cast(_buttonDisableRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonDisableRenderer)->setColor(getColor()); + dynamic_cast(_buttonDisableRenderer)->setOpacity(getOpacity()); } _disabledTextureSize = _buttonDisableRenderer->getContentSize(); updateAnchorPoint(); disabledTextureScaleChangedWithSize(); } -void UIButton::setCapInsets(const Rect &capInsets) +void UIButton::setCapInsets(const cocos2d::Rect &capInsets) { setCapInsetsNormalRenderer(capInsets); setCapInsetsPressedRenderer(capInsets); setCapInsetsDisabledRenderer(capInsets); } -void UIButton::setCapInsetsNormalRenderer(const Rect &capInsets) +void UIButton::setCapInsetsNormalRenderer(const cocos2d::Rect &capInsets) { _capInsetsNormal = capInsets; if (!_scale9Enabled) { return; } - dynamic_cast(_buttonNormalRenderer)->setCapInsets(capInsets); + dynamic_cast(_buttonNormalRenderer)->setCapInsets(capInsets); } -void UIButton::setCapInsetsPressedRenderer(const Rect &capInsets) +void UIButton::setCapInsetsPressedRenderer(const cocos2d::Rect &capInsets) { _capInsetsPressed = capInsets; if (!_scale9Enabled) { return; } - dynamic_cast(_buttonClickedRenderer)->setCapInsets(capInsets); + dynamic_cast(_buttonClickedRenderer)->setCapInsets(capInsets); } -void UIButton::setCapInsetsDisabledRenderer(const Rect &capInsets) +void UIButton::setCapInsetsDisabledRenderer(const cocos2d::Rect &capInsets) { _capInsetsDisabled = capInsets; if (!_scale9Enabled) { return; } - dynamic_cast(_buttonDisableRenderer)->setCapInsets(capInsets); + dynamic_cast(_buttonDisableRenderer)->setCapInsets(capInsets); } void UIButton::onPressStateChangedToNormal() @@ -348,9 +348,9 @@ void UIButton::onPressStateChangedToNormal() _buttonNormalRenderer->stopAllActions(); _buttonClickedRenderer->stopAllActions(); _buttonDisableRenderer->stopAllActions(); - Action *zoomAction = ScaleTo::create(0.05f, 1.0f); - Action *zoomAction1 = ScaleTo::create(0.05f, 1.0f); - Action *zoomAction2 = ScaleTo::create(0.05f, 1.0f); + cocos2d::Action *zoomAction = cocos2d::ScaleTo::create(0.05f, 1.0f); + cocos2d::Action *zoomAction1 = cocos2d::ScaleTo::create(0.05f, 1.0f); + cocos2d::Action *zoomAction2 = cocos2d::ScaleTo::create(0.05f, 1.0f); _buttonNormalRenderer->runAction(zoomAction); _buttonClickedRenderer->runAction(zoomAction1); _buttonDisableRenderer->runAction(zoomAction2); @@ -367,9 +367,9 @@ void UIButton::onPressStateChangedToPressed() _buttonNormalRenderer->stopAllActions(); _buttonClickedRenderer->stopAllActions(); _buttonDisableRenderer->stopAllActions(); - Action *zoomAction = ScaleTo::create(0.05f, 1.1f); - Action *zoomAction1 = ScaleTo::create(0.05f, 1.1f); - Action *zoomAction2 = ScaleTo::create(0.05f, 1.1f); + cocos2d::Action *zoomAction = cocos2d::ScaleTo::create(0.05f, 1.1f); + cocos2d::Action *zoomAction1 = cocos2d::ScaleTo::create(0.05f, 1.1f); + cocos2d::Action *zoomAction2 = cocos2d::ScaleTo::create(0.05f, 1.1f); _buttonNormalRenderer->runAction(zoomAction); _buttonClickedRenderer->runAction(zoomAction1); _buttonDisableRenderer->runAction(zoomAction2); @@ -390,9 +390,9 @@ void UIButton::setFlipX(bool flipX) { return; } - dynamic_cast(_buttonNormalRenderer)->setFlippedX(flipX); - dynamic_cast(_buttonClickedRenderer)->setFlippedX(flipX); - dynamic_cast(_buttonDisableRenderer)->setFlippedX(flipX); + dynamic_cast(_buttonNormalRenderer)->setFlippedX(flipX); + dynamic_cast(_buttonClickedRenderer)->setFlippedX(flipX); + dynamic_cast(_buttonDisableRenderer)->setFlippedX(flipX); } void UIButton::setFlipY(bool flipY) @@ -402,9 +402,9 @@ void UIButton::setFlipY(bool flipY) { return; } - dynamic_cast(_buttonNormalRenderer)->setFlippedY(flipY); - dynamic_cast(_buttonClickedRenderer)->setFlippedY(flipY); - dynamic_cast(_buttonDisableRenderer)->setFlippedY(flipY); + dynamic_cast(_buttonNormalRenderer)->setFlippedY(flipY); + dynamic_cast(_buttonClickedRenderer)->setFlippedY(flipY); + dynamic_cast(_buttonDisableRenderer)->setFlippedY(flipY); } bool UIButton::isFlipX() @@ -413,7 +413,7 @@ bool UIButton::isFlipX() { return false; } - return dynamic_cast(_buttonNormalRenderer)->isFlippedX(); + return dynamic_cast(_buttonNormalRenderer)->isFlippedX(); } bool UIButton::isFlipY() @@ -422,16 +422,16 @@ bool UIButton::isFlipY() { return false; } - return dynamic_cast(_buttonNormalRenderer)->isFlippedY(); + return dynamic_cast(_buttonNormalRenderer)->isFlippedY(); } -void UIButton::setAnchorPoint(const Point &pt) +void UIButton::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); _buttonNormalRenderer->setAnchorPoint(pt); _buttonClickedRenderer->setAnchorPoint(pt); _buttonDisableRenderer->setAnchorPoint(pt); - _titleRenderer->setPosition(Point(_size.width*(0.5f-_anchorPoint.x), _size.height*(0.5f-_anchorPoint.y))); + _titleRenderer->setPosition(cocos2d::Point(_size.width*(0.5f-_anchorPoint.x), _size.height*(0.5f-_anchorPoint.y))); } void UIButton::onSizeChanged() @@ -441,12 +441,12 @@ void UIButton::onSizeChanged() disabledTextureScaleChangedWithSize(); } -const Size& UIButton::getContentSize() const +const cocos2d::Size& UIButton::getContentSize() const { return _normalTextureSize; } -Node* UIButton::getVirtualRenderer() +cocos2d::Node* UIButton::getVirtualRenderer() { if (_bright) { @@ -480,11 +480,11 @@ void UIButton::normalTextureScaleChangedWithSize() { if (_scale9Enabled) { - dynamic_cast(_buttonNormalRenderer)->setPreferredSize(_size); + dynamic_cast(_buttonNormalRenderer)->setPreferredSize(_size); } else { - Size textureSize = _normalTextureSize; + cocos2d::Size textureSize = _normalTextureSize; if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _buttonNormalRenderer->setScale(1.0f); @@ -511,11 +511,11 @@ void UIButton::pressedTextureScaleChangedWithSize() { if (_scale9Enabled) { - dynamic_cast(_buttonClickedRenderer)->setPreferredSize(_size); + dynamic_cast(_buttonClickedRenderer)->setPreferredSize(_size); } else { - Size textureSize = _pressedTextureSize; + cocos2d::Size textureSize = _pressedTextureSize; if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _buttonClickedRenderer->setScale(1.0f); @@ -542,11 +542,11 @@ void UIButton::disabledTextureScaleChangedWithSize() { if (_scale9Enabled) { - dynamic_cast(_buttonDisableRenderer)->setPreferredSize(_size); + dynamic_cast(_buttonDisableRenderer)->setPreferredSize(_size); } else { - Size textureSize = _disabledTextureSize; + cocos2d::Size textureSize = _disabledTextureSize; if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _buttonDisableRenderer->setScale(1.0f); @@ -565,23 +565,23 @@ void UIButton::setPressedActionEnabled(bool enabled) _pressedActionEnabled = enabled; } -void UIButton::setTitleText(const char* text) +void UIButton::setTitleText(const std::string& text) { _titleRenderer->setString(text); } -const char* UIButton::getTitleText() const +const std::string& UIButton::getTitleText() const { return _titleRenderer->getString(); } -void UIButton::setTitleColor(const Color3B& color) +void UIButton::setTitleColor(const cocos2d::Color3B& color) { _titleColor = color; _titleRenderer->setColor(color); } -const Color3B& UIButton::getTitleColor() const +const cocos2d::Color3B& UIButton::getTitleColor() const { return _titleRenderer->getColor(); } @@ -603,10 +603,10 @@ void UIButton::setTitleFontName(const char* fontName) const char* UIButton::getTitleFontName() const { - return _titleRenderer->getFontName(); + return _titleRenderer->getFontName().c_str(); } -void UIButton::setColor(const Color3B &color) +void UIButton::setColor(const cocos2d::Color3B &color) { UIWidget::setColor(color); setTitleColor(_titleColor); @@ -617,4 +617,30 @@ const char* UIButton::getDescription() const return "Button"; } +UIWidget* UIButton::createCloneInstance() +{ + return UIButton::create(); +} + +void UIButton::copySpecialProperties(UIWidget *widget) +{ + UIButton* button = dynamic_cast(widget); + if (button) + { + _prevIgnoreSize = button->_prevIgnoreSize; + setScale9Enabled(button->_scale9Enabled); + loadTextureNormal(button->_normalFileName.c_str(), button->_normalTexType); + loadTexturePressed(button->_clickedFileName.c_str(), button->_pressedTexType); + loadTextureDisabled(button->_disabledFileName.c_str(), button->_disabledTexType); + setCapInsetsNormalRenderer(button->_capInsetsNormal); + setCapInsetsPressedRenderer(button->_capInsetsPressed); + setCapInsetsDisabledRenderer(button->_capInsetsDisabled); + setTitleText(button->getTitleText()); + setTitleFontName(button->getTitleFontName()); + setTitleFontSize(button->getTitleFontSize()); + setTitleColor(button->getTitleColor()); + setPressedActionEnabled(button->_pressedActionEnabled); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UIButton.h b/cocos/gui/UIButton.h index 94d40ec65f..b069cbf5e0 100644 --- a/cocos/gui/UIButton.h +++ b/cocos/gui/UIButton.h @@ -27,8 +27,12 @@ #include "gui/UIWidget.h" -namespace gui { +namespace gui{ +/** +* @js NA +* @lua NA +*/ class UIButton : public UIWidget { public: @@ -162,19 +166,20 @@ public: */ virtual void setColor(const cocos2d::Color3B &color); - void setTitleText(const char* text); - const char* getTitleText() const; + /** + * Returns the "class name" of widget. + */ + virtual const char* getDescription() const; + + void setTitleText(const std::string& text); + const std::string& getTitleText() const; void setTitleColor(const cocos2d::Color3B& color); const cocos2d::Color3B& getTitleColor() const; void setTitleFontSize(float size); float getTitleFontSize() const; void setTitleFontName(const char* fontName); const char* getTitleFontName() const; - - /** - * Returns the "class name" of widget. - */ - virtual const char* getDescription() const; + protected: virtual bool init(); virtual void initRenderer(); @@ -186,6 +191,8 @@ protected: void normalTextureScaleChangedWithSize(); void pressedTextureScaleChangedWithSize(); void disabledTextureScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: cocos2d::Node* _buttonNormalRenderer; cocos2d::Node* _buttonClickedRenderer; diff --git a/cocos/gui/UICheckBox.cpp b/cocos/gui/UICheckBox.cpp index f685d73b11..e79be3d5f0 100644 --- a/cocos/gui/UICheckBox.cpp +++ b/cocos/gui/UICheckBox.cpp @@ -24,10 +24,9 @@ #include "gui/UICheckBox.h" - using namespace cocos2d; - namespace gui { + UICheckBox::UICheckBox(): _backGroundBoxRenderer(NULL), _backGroundSelectedBoxRenderer(NULL), @@ -41,13 +40,19 @@ _backGroundTexType(UI_TEX_TYPE_LOCAL), _backGroundSelectedTexType(UI_TEX_TYPE_LOCAL), _frontCrossTexType(UI_TEX_TYPE_LOCAL), _backGroundDisabledTexType(UI_TEX_TYPE_LOCAL), -_frontCrossDisabledTexType(UI_TEX_TYPE_LOCAL) +_frontCrossDisabledTexType(UI_TEX_TYPE_LOCAL), +_backGroundFileName(""), +_backGroundSelectedFileName(""), +_frontCrossFileName(""), +_backGroundDisabledFileName(""), +_frontCrossDisabledFileName("") { } UICheckBox::~UICheckBox() { - + _selectedStateEventListener = NULL; + _selectedStateEventSelector = NULL; } UICheckBox* UICheckBox::create() @@ -75,11 +80,11 @@ bool UICheckBox::init() void UICheckBox::initRenderer() { UIWidget::initRenderer(); - _backGroundBoxRenderer = Sprite::create(); - _backGroundSelectedBoxRenderer = Sprite::create(); - _frontCrossRenderer = Sprite::create(); - _backGroundBoxDisabledRenderer = Sprite::create(); - _frontCrossDisabledRenderer = Sprite::create(); + _backGroundBoxRenderer = cocos2d::Sprite::create(); + _backGroundSelectedBoxRenderer = cocos2d::Sprite::create(); + _frontCrossRenderer = cocos2d::Sprite::create(); + _backGroundBoxDisabledRenderer = cocos2d::Sprite::create(); + _frontCrossDisabledRenderer = cocos2d::Sprite::create(); _renderer->addChild(_backGroundBoxRenderer); _renderer->addChild(_backGroundSelectedBoxRenderer); _renderer->addChild(_frontCrossRenderer); @@ -102,6 +107,7 @@ void UICheckBox::loadTextureBackGround(const char *backGround,TextureResType tex { return; } + _backGroundFileName = backGround; _backGroundTexType = texType; switch (_backGroundTexType) { @@ -125,6 +131,7 @@ void UICheckBox::loadTextureBackGroundSelected(const char *backGroundSelected,Te { return; } + _backGroundSelectedFileName = backGroundSelected; _backGroundSelectedTexType = texType; switch (_backGroundSelectedTexType) { @@ -148,6 +155,7 @@ void UICheckBox::loadTextureFrontCross(const char *cross,TextureResType texType) { return; } + _frontCrossFileName = cross; _frontCrossTexType = texType; switch (_frontCrossTexType) { @@ -171,6 +179,7 @@ void UICheckBox::loadTextureBackGroundDisabled(const char *backGroundDisabled,Te { return; } + _backGroundDisabledFileName = backGroundDisabled; _backGroundDisabledTexType = texType; switch (_backGroundDisabledTexType) { @@ -194,6 +203,7 @@ void UICheckBox::loadTextureFrontCrossDisabled(const char *frontCrossDisabled,Te { return; } + _frontCrossDisabledFileName = frontCrossDisabled; _frontCrossDisabledTexType = texType; switch (_frontCrossDisabledTexType) { @@ -211,7 +221,7 @@ void UICheckBox::loadTextureFrontCrossDisabled(const char *frontCrossDisabled,Te frontCrossDisabledTextureScaleChangedWithSize(); } -void UICheckBox::onTouchEnded(const Point &touchPoint) +void UICheckBox::onTouchEnded(const cocos2d::Point &touchPoint) { if (_focus) { @@ -289,7 +299,7 @@ void UICheckBox::unSelectedEvent() } } -void UICheckBox::addEventListener(Object *target, SEL_SelectedStateEvent selector) +void UICheckBox::addEventListener(cocos2d::Object *target, SEL_SelectedStateEvent selector) { _selectedStateEventListener = target; _selectedStateEventSelector = selector; @@ -323,7 +333,7 @@ bool UICheckBox::isFlipY() return _backGroundBoxRenderer->isFlippedY(); } -void UICheckBox::setAnchorPoint(const Point &pt) +void UICheckBox::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); _backGroundBoxRenderer->setAnchorPoint(pt); @@ -342,12 +352,12 @@ void UICheckBox::onSizeChanged() frontCrossDisabledTextureScaleChangedWithSize(); } -const Size& UICheckBox::getContentSize() const +const cocos2d::Size& UICheckBox::getContentSize() const { return _backGroundBoxRenderer->getContentSize(); } -Node* UICheckBox::getVirtualRenderer() +cocos2d::Node* UICheckBox::getVirtualRenderer() { return _backGroundBoxRenderer; } @@ -361,7 +371,7 @@ void UICheckBox::backGroundTextureScaleChangedWithSize() } else { - Size textureSize = _backGroundBoxRenderer->getContentSize(); + cocos2d::Size textureSize = _backGroundBoxRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _backGroundBoxRenderer->setScale(1.0f); @@ -382,7 +392,7 @@ void UICheckBox::backGroundSelectedTextureScaleChangedWithSize() } else { - Size textureSize = _backGroundSelectedBoxRenderer->getContentSize(); + cocos2d::Size textureSize = _backGroundSelectedBoxRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _backGroundSelectedBoxRenderer->setScale(1.0f); @@ -403,7 +413,7 @@ void UICheckBox::frontCrossTextureScaleChangedWithSize() } else { - Size textureSize = _frontCrossRenderer->getContentSize(); + cocos2d::Size textureSize = _frontCrossRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _frontCrossRenderer->setScale(1.0f); @@ -424,7 +434,7 @@ void UICheckBox::backGroundDisabledTextureScaleChangedWithSize() } else { - Size textureSize = _backGroundBoxDisabledRenderer->getContentSize(); + cocos2d::Size textureSize = _backGroundBoxDisabledRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _backGroundBoxDisabledRenderer->setScale(1.0f); @@ -445,7 +455,7 @@ void UICheckBox::frontCrossDisabledTextureScaleChangedWithSize() } else { - Size textureSize = _frontCrossDisabledRenderer->getContentSize(); + cocos2d::Size textureSize = _frontCrossDisabledRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _frontCrossDisabledRenderer->setScale(1.0f); @@ -463,4 +473,23 @@ const char* UICheckBox::getDescription() const return "CheckBox"; } +UIWidget* UICheckBox::createCloneInstance() +{ + return UICheckBox::create(); +} + +void UICheckBox::copySpecialProperties(UIWidget *widget) +{ + UICheckBox* checkBox = dynamic_cast(widget); + if (checkBox) + { + loadTextureBackGround(checkBox->_backGroundFileName.c_str(), checkBox->_backGroundTexType); + loadTextureBackGroundSelected(checkBox->_backGroundSelectedFileName.c_str(), checkBox->_backGroundSelectedTexType); + loadTextureFrontCross(checkBox->_frontCrossFileName.c_str(), checkBox->_frontCrossTexType); + loadTextureBackGroundDisabled(checkBox->_backGroundDisabledFileName.c_str(), checkBox->_backGroundDisabledTexType); + loadTextureFrontCrossDisabled(checkBox->_frontCrossDisabledFileName.c_str(), checkBox->_frontCrossDisabledTexType); + setSelectedState(checkBox->_isSelected); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UICheckBox.h b/cocos/gui/UICheckBox.h index 46183f04db..5e9c836617 100644 --- a/cocos/gui/UICheckBox.h +++ b/cocos/gui/UICheckBox.h @@ -35,9 +35,13 @@ typedef enum CHECKBOX_STATE_EVENT_UNSELECTED }CheckBoxEventType; -typedef void (cocos2d::CCObject::*SEL_SelectedStateEvent)(cocos2d::Object*,CheckBoxEventType); +typedef void (cocos2d::Object::*SEL_SelectedStateEvent)(cocos2d::Object*,CheckBoxEventType); #define checkboxselectedeventselector(_SELECTOR) (SEL_SelectedStateEvent)(&_SELECTOR) +/** +* @js NA +* @lua NA +*/ class UICheckBox : public UIWidget { public: @@ -156,11 +160,12 @@ public: //override "getVirtualRenderer" method of widget. virtual cocos2d::Node* getVirtualRenderer(); - + /** * Returns the "class name" of widget. */ virtual const char* getDescription() const; + protected: virtual bool init(); virtual void initRenderer(); @@ -175,6 +180,8 @@ protected: void frontCrossTextureScaleChangedWithSize(); void backGroundDisabledTextureScaleChangedWithSize(); void frontCrossDisabledTextureScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: cocos2d::Sprite* _backGroundBoxRenderer; cocos2d::Sprite* _backGroundSelectedBoxRenderer; @@ -191,6 +198,12 @@ protected: TextureResType _frontCrossTexType; TextureResType _backGroundDisabledTexType; TextureResType _frontCrossDisabledTexType; + + std::string _backGroundFileName; + std::string _backGroundSelectedFileName; + std::string _frontCrossFileName; + std::string _backGroundDisabledFileName; + std::string _frontCrossDisabledFileName; }; } diff --git a/cocos/gui/UIDragPanel.cpp b/cocos/gui/UIDragPanel.cpp deleted file mode 100644 index 7c717c0636..0000000000 --- a/cocos/gui/UIDragPanel.cpp +++ /dev/null @@ -1,1269 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "gui/UIDragPanel.h" -#include "gui/UILayer.h" - - using namespace cocos2d; - -namespace gui { - -UIDragPanel::UIDragPanel() -: _innerContainer(NULL) -, _touchPressed(false) -, _touchMoved(false) -, _touchReleased(false) -, _touchCanceld(false) -, _touchStartNodeSpace(Point::ZERO) -, _touchStartWorldSpace(Point::ZERO) -, _touchEndWorldSpace(Point::ZERO) -, _slidTime(0.0f) -, _moveType(DRAGPANEL_MOVE_TYPE_AUTOMOVE) -, _autoMoveDuration(0.5f) -, _autoMoveEaseRate(2.0f) -, _eventLister(NULL) -, _eventSelector(NULL) -, _berthDirection(DRAGPANEL_BERTH_DIR_NONE) -, _bounceEnable(false) -, _bounceDirection(DRAGPANEL_BOUNCE_DIR_NONE) -, _bounceDuration(0.5f) -, _bounceEaseRate(2.0f) -, _runningAction(false) -, _actionType(0) -, _actionWidget(NULL) -, _duration(0.0f) -, _elapsed(0.0f) -, _firstTick(false) -, _positionDelta(Point::ZERO) -, _startPosition(Point::ZERO) -, _previousPosition(Point::ZERO) -, _endPosition(Point::ZERO) -{ - -} - -UIDragPanel::~UIDragPanel() -{ - -} - -UIDragPanel* UIDragPanel::create() -{ - UIDragPanel* widget = new UIDragPanel(); - if (widget && widget->init()) - { - widget->autorelease(); - return widget; - } - CC_SAFE_DELETE(widget); - return NULL; -} - -bool UIDragPanel::init() -{ - if (Layout::init()) - { - setUpdateEnabled(true); - setTouchEnabled(true); - setClippingEnabled(true); - return true; - } - return false; -} - -void UIDragPanel::initRenderer() -{ - Layout::initRenderer(); - - _innerContainer = Layout::create(); - Layout::addChild(_innerContainer); - -} - -void UIDragPanel::releaseResoures() -{ - setUpdateEnabled(false); - removeAllChildren(); - _renderer->removeAllChildrenWithCleanup(true); - _renderer->removeFromParentAndCleanup(true); - _renderer->release(); - - Layout::removeChild(_innerContainer); - - _children->release(); -} - -bool UIDragPanel::onTouchBegan(const Point &touchPoint) -{ - bool pass = Layout::onTouchBegan(touchPoint); - handlePressLogic(touchPoint); - return pass; -} - -void UIDragPanel::onTouchMoved(const Point &touchPoint) -{ - Layout::onTouchMoved(touchPoint); - handleMoveLogic(touchPoint); -} - -void UIDragPanel::onTouchEnded(const Point &touchPoint) -{ - Layout::onTouchEnded(touchPoint); - handleReleaseLogic(touchPoint); -} - -void UIDragPanel::onTouchCancelled(const Point &touchPoint) -{ - Layout::onTouchCancelled(touchPoint); -} - -void UIDragPanel::onTouchLongClicked(const Point &touchPoint) -{ - -} - -void UIDragPanel::update(float dt) -{ - // widget action - if (_runningAction) - { - if (actionIsDone()) - { - actionDone(); - actionStop(); - } - else - { - actionStep(dt); - } - } - - recordSlidTime(dt); -} - -bool UIDragPanel::addChild(UIWidget *widget) -{ - _innerContainer->addChild(widget); - return true; -} - -bool UIDragPanel::removeChild(UIWidget *child) -{ - bool value = false; - if (_innerContainer->removeChild(child)) - { - value = true; - } - - return value; -} - -void UIDragPanel::removeAllChildren() -{ - _innerContainer->removeAllChildren(); -} - -Array* UIDragPanel::getChildren() -{ - return _innerContainer->getChildren(); -} - -void UIDragPanel::onSizeChanged() -{ - Layout::onSizeChanged(); - Size innerSize = _innerContainer->getSize(); - float orginInnerSizeWidth = innerSize.width; - float orginInnerSizeHeight = innerSize.height; - float innerSizeWidth = MAX(orginInnerSizeWidth, _size.width); - float innerSizeHeight = MAX(orginInnerSizeHeight, _size.height); - _innerContainer->setSize(Size(innerSizeWidth, innerSizeHeight)); -} - -const Size& UIDragPanel::getInnerContainerSize() const -{ - return _innerContainer->getContentSize(); -} - -void UIDragPanel::setInnerContainerSize(const cocos2d::Size &size) -{ - float innerSizeWidth = _size.width; - float innerSizeHeight = _size.height; - if (size.width < _size.width) - { - CCLOG("Inner width <= scrollview width, it will be force sized!"); - } - else - { - innerSizeWidth = size.width; - } - if (size.height < _size.height) - { - CCLOG("Inner height <= scrollview height, it will be force sized!"); - } - else - { - innerSizeHeight = size.height; - } - _innerContainer->setSize(Size(innerSizeWidth, innerSizeHeight)); - _innerContainer->setPosition(Point(0, _size.height - _innerContainer->getSize().height)); -} - -const Point& UIDragPanel::getInnerContainerPosition() const -{ - return _innerContainer->getPosition(); -} - -void UIDragPanel::setInnerContainerPosition(const Point &point, bool animated) -{ - Point delta = point - _innerContainer->getPosition(); - -// Point delta = ccpSub(point, _innerContainer->getPosition()); - setInnerContainerOffset(delta, animated); -} - -void UIDragPanel::setInnerContainerOffset(const Point &offset, bool animated) -{ - if (animated) - { - Point delta = offset; - - if (checkToBoundaryWithDeltaPosition(delta)) - { - delta = calculateToBoundaryDeltaPosition(delta); - } - actionStartWithWidget(_innerContainer); - moveByWithDuration(_autoMoveDuration, delta); - } - else - { - setInnerContainerOffset(offset); - } -} - -void UIDragPanel::setInnerContainerOffset(const Point &offset) -{ - Point delta = offset; - - if (checkToBoundaryWithDeltaPosition(delta)) - { - delta = calculateToBoundaryDeltaPosition(delta); - } - moveWithDelta(delta); - if (checkBerth()) - { - berthEvent(); - } -} - - -void UIDragPanel::handlePressLogic(const Point &touchPoint) -{ - // check inner rect < drag panel rect - if (checkContainInnerRect()) - { - _touchPressed = false; - return; - } - - _touchPressed = true; - _touchMoved = false; - _touchReleased = false; - _touchCanceld = false; - - if (_runningAction) - { - switch (_moveType) - { - case DRAGPANEL_MOVE_TYPE_AUTOMOVE: - stopAutoMove(); - actionStop(); - break; - - case DRAGPANEL_MOVE_TYPE_BOUNCE: - _touchPressed = false; - break; - - default: - break; - } - } - - Point nsp = _renderer->convertToNodeSpace(touchPoint); - _touchStartNodeSpace = nsp; - - _touchStartWorldSpace = touchPoint; -} - -void UIDragPanel::handleMoveLogic(const Point &touchPoint) -{ - if (!_touchPressed) - { - return; - } - - // check touch out of drag panel boundary - if (_touchCanceld) - { - return; - } - - _touchMoved = true; - - Point nsp = _renderer->convertToNodeSpace(touchPoint); - Point delta = nsp - _touchStartNodeSpace; -// Point delta = ccpSub(nsp, _touchStartNodeSpace); - _touchStartNodeSpace = nsp; - - // reset berth dir to none - if (!_bounceEnable) - { - _berthDirection = DRAGPANEL_BERTH_DIR_NONE; - } - - // check will berth (bounce disable) - if (!_bounceEnable) - { - if (checkToBoundaryWithDeltaPosition(delta)) - { - delta = calculateToBoundaryDeltaPosition(delta); - } - } - // move - moveWithDelta(delta); - // check bounce or berth - if (_bounceEnable) - { - // bounce - if (!hitTest(touchPoint)) - { - _touchMoved = false; - - if (checkNeedBounce()) - { - _touchCanceld = true; - startBounce(); - } - } - } - else - { - // berth - if (checkBerth()) - { - berthEvent(); - } - } -} - -void UIDragPanel::handleReleaseLogic(const Point &touchPoint) -{ - if (!_touchPressed) - { - return; - } - - _touchPressed = false; - _touchMoved = false; - _touchReleased = true; - _touchCanceld = false; - - // check touch out of drag panel boundary - if (_touchCanceld) - { - return; - } - - if (hitTest(touchPoint)) - { - _touchEndWorldSpace = touchPoint; - startAutoMove(); - } -} - -void UIDragPanel::checkChildInfo(int handleState, UIWidget *sender, const Point &touchPoint) -{ - interceptTouchEvent(handleState, sender, touchPoint); -} - -void UIDragPanel::interceptTouchEvent(int handleState, UIWidget *sender, const Point &touchPoint) -{ - switch (handleState) - { - case 0: - handlePressLogic(touchPoint); - break; - - case 1: - { -// float offset = ccpDistance(sender->getTouchStartPos(), touchPoint); - float offset = sender->getTouchStartPos().getDistance(touchPoint); - if (offset > 5.0) - { - sender->setFocused(false); - handleMoveLogic(touchPoint); - } - } - break; - - case 2: - handleReleaseLogic(touchPoint); - break; - - case 3: - break; - } -} - -void UIDragPanel::recordSlidTime(float dt) -{ - if (_touchPressed) - { - _slidTime += dt; - } -} - -// check if dragpanel rect contain inner rect -bool UIDragPanel::checkContainInnerRect() -{ - float width = _size.width; - float height = _size.height; - float innerWidth = _innerContainer->getSize().width; - float innerHeight = _innerContainer->getSize().height; - - if (innerWidth <= width && innerHeight <= height) - { - return true; - } - - return false; -} - -// move -void UIDragPanel::moveWithDelta(const Point &delta) -{ - Point newPos = _innerContainer->getPosition() + delta; -// Point newPos = ccpAdd(_innerContainer->getPosition(), delta); - _innerContainer->setPosition(newPos); -} - -// auto move -void UIDragPanel::autoMove() -{ - if (_bounceEnable) - { - if (checkNeedBounce()) - { - stopAutoMove(); - startBounce(); - } - } -} - -void UIDragPanel::autoMoveOver() -{ - stopAutoMove(); - - if (checkBerth()) - { - berthEvent(); - _berthDirection = DRAGPANEL_BERTH_DIR_NONE; - } -} - -void UIDragPanel::startAutoMove() -{ - _moveType = DRAGPANEL_MOVE_TYPE_AUTOMOVE; - - actionStop(); - - Point delta = _touchEndWorldSpace - _touchStartWorldSpace; -// Point delta = ccpSub(m_touchEndWorldSpace, _touchStartWorldSpace); - delta.x /= _slidTime * 60; - delta.y /= _slidTime * 60; - _slidTime = 0.0; - - // bounceEnable is disable - if (!_bounceEnable) - { - if (checkToBoundaryWithDeltaPosition(delta)) - { - delta = calculateToBoundaryDeltaPosition(delta); - } - } - actionStartWithWidget(_innerContainer); - moveByWithDuration(_autoMoveDuration, delta); -} - -void UIDragPanel::stopAutoMove() -{ - _moveType = DRAGPANEL_MOVE_TYPE_NONE; -} - -void UIDragPanel::setAutoMoveDuration(float duration) -{ - _autoMoveDuration = duration; -} - -void UIDragPanel::setAutoMoveEaseRate(float rate) -{ - _autoMoveEaseRate = rate; -} - -// berth - -// check if move to boundary - -bool UIDragPanel::checkToBoundaryWithDeltaPosition(const Point& delta) -{ - float innerLeft = _innerContainer->getLeftInParent(); - float innerTop = _innerContainer->getTopInParent(); - float innerRight = _innerContainer->getRightInParent(); - float innerBottom = _innerContainer->getBottomInParent(); - - float left = 0; - float top = _size.height; - float right = _size.width; - float bottom = 0; - - bool toLeftBottom = false; - bool toLeftTop = false; - bool toRightBottom = false; - bool toRightTop = false; - bool toLeft = false; - bool toRight = false; - bool toTop = false; - bool toBottom = false; - - if (innerLeft + delta.x > left && innerBottom + delta.y > bottom) // left bottom - { - toLeftBottom = true; - } - else if (innerLeft + delta.x > left && innerTop + delta.y < top) // left top - { - toLeftTop = true; - } - else if (innerRight + delta.x < right && innerBottom + delta.y > bottom) // right bottom - { - toRightBottom = true; - } - else if (innerRight + delta.x < right && innerTop + delta.y < top) // right top - { - toRightTop = true; - } - else if (innerLeft + delta.x > left) // left - { - toLeft = true; - } - else if (innerRight + delta.x < right) // right - { - toRight = true; - } - else if (innerTop + delta.y < top) // top - { - toTop = true; - } - else if (innerBottom + delta.y > bottom) // bottom - { - toBottom = true; - } - - if (toLeft || toTop || toRight || toBottom - || toLeftBottom || toLeftTop || toRightBottom || toRightTop) - { - return true; - } - - return false; -} - -Point UIDragPanel::calculateToBoundaryDeltaPosition(const Point& paramDelta) -{ - float innerLeft = _innerContainer->getLeftInParent(); - float innerTop = _innerContainer->getTopInParent(); - float innerRight = _innerContainer->getRightInParent(); - float innerBottom = _innerContainer->getBottomInParent(); - - float left = 0; - float top = _size.height; - float right = _size.width; - float bottom = 0; - - Point delta = paramDelta; - - if (innerLeft + delta.x > left && innerBottom + delta.y > bottom) // left bottom - { - delta.x = left - innerLeft; - delta.y = bottom - innerBottom; - } - else if (innerLeft + delta.x > left && innerTop + delta.y < top) // left top - { - delta.x = left - innerLeft; - delta.y = top - innerTop; - } - else if (innerRight + delta.x < right && innerBottom + delta.y > bottom) // right bottom - { - delta.x = right - innerRight; - delta.y = bottom - innerBottom; - } - else if (innerRight + delta.x < right && innerTop + delta.y < top) // right bottom - { - delta.x = right - innerRight; - delta.y = top - innerTop; - } - else if (innerLeft + delta.x > left) // left - { - delta.x = left - innerLeft; - } - else if (innerRight + delta.x < right) // right - { - delta.x = right - innerRight; - } - else if (innerTop + delta.y < top) // top - { - delta.y = top - innerTop; - } - else if (innerBottom + delta.y > bottom) // bottom - { - delta.y = bottom - innerBottom; - } - - return delta; -} - -bool UIDragPanel::isBerth() -{ - return _berthDirection != DRAGPANEL_BERTH_DIR_NONE; -} - -// check berth -bool UIDragPanel::checkBerth() -{ - float innerLeft = _innerContainer->getLeftInParent(); - float innerTop = _innerContainer->getTopInParent(); - float innerRight = _innerContainer->getRightInParent(); - float innerBottom = _innerContainer->getBottomInParent(); - - float left = 0; - float top = _size.height; - float right = _size.width; - float bottom = 0; - - if (innerLeft == left && innerBottom == bottom) // left bottom - { - _berthDirection = DRAGPANEL_BERTH_DIR_LEFTBOTTOM; - } - else if (innerLeft == left && innerTop == top) // left top - { - _berthDirection = DRAGPANEL_BERTH_DIR_LFETTOP; - } - else if (innerRight == right && innerBottom == bottom) // right bottom - { - _berthDirection = DRAGPANEL_BERTH_DIR_RIGHTBOTTOM; - } - else if (innerRight == right && innerTop == top) // right top - { - _berthDirection = DRAGPANEL_BERTH_DIR_RIGHTTOP; - } - else if (innerLeft == left) // left - { - _berthDirection = DRAGPANEL_BERTH_DIR_LEFT; - } - else if (innerRight == right) // right - { - _berthDirection = DRAGPANEL_BERTH_DIR_RIGHT; - } - else if (innerTop == top) // top - { - _berthDirection = DRAGPANEL_BERTH_DIR_TOP; - } - else if (innerBottom == bottom) // bottom - { - _berthDirection = DRAGPANEL_BERTH_DIR_BOTTOM; - } - - if (_berthDirection != DRAGPANEL_BERTH_DIR_NONE) - { - return true; - } - - return false; -} - -void UIDragPanel::berthEvent() -{ - switch (_berthDirection) - { - case DRAGPANEL_BERTH_DIR_LEFTBOTTOM: - berthToLeftBottomEvent(); - break; - - case DRAGPANEL_BERTH_DIR_LFETTOP: - berthToLeftTopEvent(); - break; - - case DRAGPANEL_BERTH_DIR_RIGHTBOTTOM: - berthToRightBottomEvent(); - break; - - case DRAGPANEL_BERTH_DIR_RIGHTTOP: - berthToRightTopEvent(); - break; - - case DRAGPANEL_BERTH_DIR_LEFT: - berthToLeftEvent(); - break; - - case DRAGPANEL_BERTH_DIR_TOP: - berthToTopEvent(); - break; - - case DRAGPANEL_BERTH_DIR_RIGHT: - berthToRightEvent(); - break; - - case DRAGPANEL_BERTH_DIR_BOTTOM: - berthToBottomEvent(); - break; - - default: - break; - } -} - -void UIDragPanel::berthToLeftBottomEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_LEFTBOTTOM); - } -} - -void UIDragPanel::berthToLeftTopEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_LFETTOP); - } -} - -void UIDragPanel::berthToRightBottomEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_RIGHTBOTTOM); - } -} - -void UIDragPanel::berthToRightTopEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_RIGHTTOP); - } -} - -void UIDragPanel::berthToLeftEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_LEFT); - } -} - -void UIDragPanel::berthToTopEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_TOP); - } -} - -void UIDragPanel::berthToRightEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_RIGHT); - } -} - -void UIDragPanel::berthToBottomEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_BOTTOM); - } -} - -void UIDragPanel::addEventListener(Object *target, SEL_DragPanelEvent selector) -{ - _eventLister = target; - _eventSelector = selector; -} - -// bounce -bool UIDragPanel::isBounceEnable() -{ - return _bounceEnable; -} - -void UIDragPanel::setBounceEnable(bool bounce) -{ - _bounceEnable = bounce; -} - -bool UIDragPanel::checkNeedBounce() -{ - float innerLeft = _innerContainer->getLeftInParent(); - float innerTop = _innerContainer->getTopInParent(); - float innerRight = _innerContainer->getRightInParent(); - float innerBottom = _innerContainer->getBottomInParent(); - - float left = 0; - float top = _size.height; - float right = _size.width; - float bottom = 0; - - bool need = ((innerLeft > left && innerBottom > bottom) - || (innerLeft > left && innerTop < top) - || (innerRight < right && innerBottom > bottom) - || (innerRight < right && innerTop < top) - || (innerLeft > left) - || (innerTop < top) - || (innerRight < right) - || (innerBottom > bottom)); - return need; -} - -void UIDragPanel::startBounce() -{ - if (_moveType == DRAGPANEL_MOVE_TYPE_BOUNCE) - { - return; - } - - actionStop(); - _moveType = DRAGPANEL_MOVE_TYPE_BOUNCE; - bounceToCorner(); -} - -void UIDragPanel::stopBounce() -{ - _moveType = DRAGPANEL_MOVE_TYPE_NONE; -} - -void UIDragPanel::bounceToCorner() -{ - float innerLeft = _innerContainer->getLeftInParent(); - float innerTop = _innerContainer->getTopInParent(); - float innerRight = _innerContainer->getRightInParent(); - float innerBottom = _innerContainer->getBottomInParent(); - - float width = _size.width; - float height = _size.height; - float left = 0; - float top = height; - float right = width; - float bottom = 0; - - float from_x = 0; - float from_y = 0; - float to_x = 0; - float to_y = 0; - Point delta = Point::ZERO; - - if (innerLeft > left && innerBottom > bottom) // left bottom - { - from_x = innerLeft; - from_y = innerBottom; - to_x = left; - to_y = bottom; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_LEFTBOTTOM; - } - else if (innerLeft > left && innerTop < top) // left top - { - from_x = innerLeft; - from_y = innerTop; - to_x = left; - to_y = top; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_LEFTTOP; - } - else if (innerRight < right && innerBottom > bottom) // right bottom - { - from_x = innerRight; - from_y = innerBottom; - to_x = right; - to_y = bottom; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_RIGHTBOTTOM; - } - else if (innerRight < right && innerTop < top) // right top - { - from_x = innerRight; - from_y = innerTop; - to_x = right; - to_y = top; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_RIGHTTOP; - } - else if (innerLeft > left) // left - { - from_x = innerLeft; - from_y = innerBottom; - to_x = left; - to_y = from_y; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_LEFT; - } - else if (innerTop < top) // top - { - from_x = innerLeft; - from_y = innerTop; - to_x = from_x; - to_y = top; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_TOP; - } - else if (innerRight < right) // right - { - from_x = innerRight; - from_y = innerBottom; - to_x = right; - to_y = from_y; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_RIGHT; - } - else if (innerBottom > bottom) // bottom - { - from_x = innerLeft; - from_y = innerBottom; - to_x = from_x; - to_y = bottom; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_BOTTOM; - } - delta = Point(to_x, to_y) - Point(from_x, from_y); -// delta = ccpSub(ccp(to_x, to_y), ccp(from_x, from_y)); - - actionStartWithWidget(_innerContainer); - moveByWithDuration(_bounceDuration, delta); -} - -void UIDragPanel::bounceOver() -{ - stopBounce(); - - switch (_bounceDirection) - { - case DRAGPANEL_BOUNCE_DIR_LEFTBOTTOM: - bounceToLeftBottomEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_LEFTTOP: - bounceToLeftTopEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_RIGHTBOTTOM: - bounceToRightBottomEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_RIGHTTOP: - bounceToRightTopEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_LEFT: - bounceToLeftEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_TOP: - bounceToTopEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_RIGHT: - bounceToRightEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_BOTTOM: - bounceToBottomEvent(); - break; - - default: - break; - } - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_NONE; -} - -void UIDragPanel::bounceToLeftBottomEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_LEFTBOTTOM); - } -} - -void UIDragPanel::bounceToLeftTopEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_LEFTTOP); - } -} - -void UIDragPanel::bounceToRightBottomEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_RIGHTBOTTOM); - } -} - -void UIDragPanel::bounceToRightTopEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_RIGHTTOP); - } -} - -void UIDragPanel::bounceToLeftEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_LEFT); - } -} - -void UIDragPanel::bounceToTopEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_TOP); - } -} - -void UIDragPanel::bounceToRightEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_RIGHT); - } -} - -void UIDragPanel::bounceToBottomEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_BOTTOM); - } -} - -// widget action -void UIDragPanel::actionWithDuration(float duration) -{ - _duration = duration; - - if (_duration == 0) - { - _duration = FLT_EPSILON; - } - - _elapsed = 0; - _firstTick = true; -} - -bool UIDragPanel::actionIsDone() -{ - bool value = (_elapsed >= _duration); - return value; -} - -void UIDragPanel::actionStartWithWidget(UIWidget *widget) -{ - _runningAction = true; - _actionWidget = widget; -} - -void UIDragPanel::actionStep(float dt) -{ - if (_firstTick) - { - _firstTick = false; - _elapsed = 0; - } - else - { - _elapsed += dt; - } - - actionUpdate(MAX (0, - MIN(1, _elapsed / - MAX(_duration, FLT_EPSILON) - ) - ) - ); -} - -void UIDragPanel::actionUpdate(float dt) -{ - switch (_actionType) - { - case 1: // move by - moveByUpdate(dt); - break; - - case 2: // move to - moveToUpdate(dt); - break; - - default: - break; - } -} - -void UIDragPanel::actionStop() -{ - _runningAction = false; -} - -void UIDragPanel::actionDone() -{ - switch (_moveType) - { - case DRAGPANEL_MOVE_TYPE_AUTOMOVE: - autoMoveOver(); - break; - - case DRAGPANEL_MOVE_TYPE_BOUNCE: - bounceOver(); - break; - - default: - break; - } -} - -// move by -void UIDragPanel::moveByWithDuration(float duration, const Point& deltaPosition) -{ - actionWithDuration(duration); - _positionDelta = deltaPosition; - moveByInit(); - _actionType = 1; -} - -void UIDragPanel::moveByInit() -{ - _previousPosition = _startPosition = _actionWidget->getPosition(); -} - -void UIDragPanel::moveByUpdate(float t) -{ - float easeRate = 0.0f; - switch (_moveType) - { - case DRAGPANEL_MOVE_TYPE_AUTOMOVE: - easeRate = _autoMoveEaseRate; - break; - - case DRAGPANEL_MOVE_TYPE_BOUNCE: - easeRate = _bounceEaseRate; - break; - - default: - break; - } - t = powf(t, 1 / easeRate); - - Point currentPos = _actionWidget->getPosition(); - Point diff = currentPos - _previousPosition; - _startPosition = _startPosition + diff; -// Point diff = ccpSub(currentPos, _previousPosition); -// _startPosition = ccpAdd( _startPosition, diff); - -// Point newPos = ccpAdd( _startPosition, ccpMult(_positionDelta, t) ); - Point newPos = _startPosition + (_positionDelta * t); - - _actionWidget->setPosition(newPos); - _previousPosition = newPos; - - switch (_moveType) - { - case DRAGPANEL_MOVE_TYPE_AUTOMOVE: - autoMove(); - break; - - default: - break; - } -} - -// move to -void UIDragPanel::moveToWithDuration(float duration, const Point& position) -{ - actionWithDuration(duration); - _endPosition = position; - moveToInit(); - _actionType = 2; -} - -void UIDragPanel::moveToInit() -{ - moveByInit(); - _positionDelta = _endPosition - _actionWidget->getPosition(); -// _positionDelta = ccpSub( _endPosition, _actionWidget->getPosition() ); -} - -void UIDragPanel::moveToUpdate(float t) -{ - moveByUpdate(t); -} - -Layout* UIDragPanel::getInnerContainer() -{ - return _innerContainer; -} - -void UIDragPanel::setLayoutType(LayoutType type) -{ - _innerContainer->setLayoutType(type); -} - -LayoutType UIDragPanel::getLayoutType() const -{ - return _innerContainer->getLayoutType(); -} - -void UIDragPanel::doLayout() -{ - _innerContainer->doLayout(); -} - -const char* UIDragPanel::getDescription() const -{ - return "DragPanel"; -} - -} \ No newline at end of file diff --git a/cocos/gui/UIDragPanel.h b/cocos/gui/UIDragPanel.h deleted file mode 100644 index d6b4f0b62c..0000000000 --- a/cocos/gui/UIDragPanel.h +++ /dev/null @@ -1,367 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#ifndef __UIDRAGPANEL_H__ -#define __UIDRAGPANEL_H__ - -#include "gui/Layout.h" -#include "gui/UIScrollInterface.h" - -namespace gui { - -/** - * drag panel move type - */ -enum DRAGPANEL_MOVE_TYPE -{ - DRAGPANEL_MOVE_TYPE_NONE, - DRAGPANEL_MOVE_TYPE_AUTOMOVE, - DRAGPANEL_MOVE_TYPE_BOUNCE, -}; - -/** - * dragpanel berth direction - */ -enum DRAGPANEL_BERTH_DIR -{ - DRAGPANEL_BERTH_DIR_NONE, - DRAGPANEL_BERTH_DIR_LEFTBOTTOM, - DRAGPANEL_BERTH_DIR_LFETTOP, - DRAGPANEL_BERTH_DIR_RIGHTBOTTOM, - DRAGPANEL_BERTH_DIR_RIGHTTOP, - DRAGPANEL_BERTH_DIR_LEFT, - DRAGPANEL_BERTH_DIR_TOP, - DRAGPANEL_BERTH_DIR_RIGHT, - DRAGPANEL_BERTH_DIR_BOTTOM, -}; - -/** - * dragpanel bounce direction - */ -enum DRAGPANEL_BOUNCE_DIR -{ - DRAGPANEL_BOUNCE_DIR_NONE, - DRAGPANEL_BOUNCE_DIR_LEFTBOTTOM, - DRAGPANEL_BOUNCE_DIR_LEFTTOP, - DRAGPANEL_BOUNCE_DIR_RIGHTBOTTOM, - DRAGPANEL_BOUNCE_DIR_RIGHTTOP, - DRAGPANEL_BOUNCE_DIR_LEFT, - DRAGPANEL_BOUNCE_DIR_TOP, - DRAGPANEL_BOUNCE_DIR_RIGHT, - DRAGPANEL_BOUNCE_DIR_BOTTOM, -}; - -typedef enum -{ - DRAGPANEL_EVENT_BERTH_LEFTBOTTOM, - DRAGPANEL_EVENT_BERTH_LFETTOP, - DRAGPANEL_EVENT_BERTH_RIGHTBOTTOM, - DRAGPANEL_EVENT_BERTH_RIGHTTOP, - DRAGPANEL_EVENT_BERTH_LEFT, - DRAGPANEL_EVENT_BERTH_TOP, - DRAGPANEL_EVENT_BERTH_RIGHT, - DRAGPANEL_EVENT_BERTH_BOTTOM, - DRAGPANEL_EVENT_BOUNCE_LEFTBOTTOM, - DRAGPANEL_EVENT_BOUNCE_LEFTTOP, - DRAGPANEL_EVENT_BOUNCE_RIGHTBOTTOM, - DRAGPANEL_EVENT_BOUNCE_RIGHTTOP, - DRAGPANEL_EVENT_BOUNCE_LEFT, - DRAGPANEL_EVENT_BOUNCE_TOP, - DRAGPANEL_EVENT_BOUNCE_RIGHT, - DRAGPANEL_EVENT_BOUNCE_BOTTOM, -}DragPanelEventType; - -/** - * dragpanel event - */ -typedef void (cocos2d::Object::*SEL_DragPanelEvent)(cocos2d::Object*, DragPanelEventType); -#define dragpaneleventselector(_SELECTOR)(SEL_DragPanelEvent)(&_SELECTOR) - -class UIDragPanel : public Layout, public UIScrollInterface -{ -public: - UIDragPanel(); - virtual ~UIDragPanel(); - - static UIDragPanel* create(); - - virtual bool onTouchBegan(const cocos2d::Point &touchPoint); - virtual void onTouchMoved(const cocos2d::Point &touchPoint); - virtual void onTouchEnded(const cocos2d::Point &touchPoint); - virtual void onTouchCancelled(const cocos2d::Point &touchPoint); - virtual void onTouchLongClicked(const cocos2d::Point &touchPoint); - - virtual void update(float dt); - - /** - * add widget child override - */ - virtual bool addChild(UIWidget* widget); - /** - * remove widget child override - */ - virtual bool removeChild(UIWidget* child); - /** - * remove all widget children override - */ - virtual void removeAllChildren(); - /** - * get widget children of inner container - */ - virtual cocos2d::Array* getChildren(); - /* gui mark */ - /** - * get and set inner container size - */ - const cocos2d::Size& getInnerContainerSize() const; - void setInnerContainerSize(const cocos2d::Size &size); - /** - * get and set inner container position - */ - const cocos2d::Point& getInnerContainerPosition() const; - void setInnerContainerPosition(const cocos2d::Point& point, bool animated); - /** - * set inner container offset - */ - void setInnerContainerOffset(const cocos2d::Point& offset, bool animated); - /**/ - - // auto move - /** - * set auto move duration - */ - void setAutoMoveDuration(float duration); - /** - * set auto move ease rate - */ - void setAutoMoveEaseRate(float rate); - - // berth - /** - * get berth or not - */ - bool isBerth(); - - /** - * event - */ - void addEventListener(cocos2d::Object* target, SEL_DragPanelEvent selector); - - /** - * get and set bounce enable - */ - bool isBounceEnable(); - void setBounceEnable(bool bounce); - /** - * set bounce duration - */ - void setBounceDuratoin(float duration); - /** - * set bounce ease rate - */ - void setBounceEaseRate(float rate); - - /** - * Gets inner container of dragpanel. - * - * Inner container is the container of dragpanel's children. - * - * @return inner container. - */ - Layout* getInnerContainer(); - - /** - * Sets LayoutType. - * - * @see LayoutType - * - * @param LayoutType - */ - virtual void setLayoutType(LayoutType type); - - /** - * Gets LayoutType. - * - * @see LayoutType - * - * @return LayoutType - */ - virtual LayoutType getLayoutType() const; - - virtual void doLayout(); - - /** - * Returns the "class name" of widget. - */ - virtual const char* getDescription() const; - -protected: - virtual bool init(); - virtual void initRenderer(); - virtual void releaseResoures(); - - virtual void handlePressLogic(const cocos2d::Point &touchPoint); - virtual void handleMoveLogic(const cocos2d::Point &touchPoint); - virtual void handleReleaseLogic(const cocos2d::Point &touchPoint); - virtual void interceptTouchEvent(int handleState,UIWidget* sender, const cocos2d::Point &touchPoint); - /* gui mark */ -// virtual bool isInScrollDegreeRange(UIWidget* widget); - /**/ - virtual void checkChildInfo(int handleState, UIWidget *sender, const cocos2d::Point &touchPoint); -// void updateWidthAndHeight(); - void recordSlidTime(float dt); - - /* gui mark */ - void setInnerContainerOffset(const cocos2d::Point& offset); - /**/ - - // check if dragpanel rect contain inner rect - bool checkContainInnerRect(); - - // move - void moveWithDelta(const cocos2d::Point& delta); - - // auto move - void autoMove(); - void autoMoveOver(); - void startAutoMove(); - void stopAutoMove(); - - // berth - // check if move to boundary with update - bool checkToBoundaryWithDeltaPosition(const cocos2d::Point& delta); - - // calculate to boundary delta - cocos2d::Point calculateToBoundaryDeltaPosition(const cocos2d::Point& paramDelta); - - // check berth - bool checkBerth(); - - // berth event - void berthEvent(); - void berthToLeftEvent(); - void berthToRightEvent(); - void berthToTopEvent(); - void berthToBottomEvent(); - void berthToLeftBottomEvent(); - void berthToLeftTopEvent(); - void berthToRightBottomEvent(); - void berthToRightTopEvent(); - - // bounce - bool checkNeedBounce(); - void startBounce(); - void stopBounce(); - void bounceToCorner(); - void bounceOver(); - // bounce event - void bounceToLeftBottomEvent(); - void bounceToRightBottomEvent(); - void bounceToLeftTopEvent(); - void bounceToRightTopEvent(); - void bounceToLeftEvent(); - void bounceToTopEvent(); - void bounceToRightEvent(); - void bounceToBottomEvent(); - - void actionWithDuration(float duration); - bool actionIsDone(); - void actionStartWithWidget(UIWidget* widget); - void actionStep(float dt); - void actionUpdate(float dt); - void actionStop(); - void actionDone(); - void moveByWithDuration(float duration, const cocos2d::Point& deltaPosition); - void moveByInit(); - void moveByUpdate(float t); - void moveToWithDuration(float duration, const cocos2d::Point& position); - void moveToInit(); - void moveToUpdate(float t); - virtual void onSizeChanged(); - /*compatible*/ - /** - * These methods will be removed - */ - virtual void setClippingEnable(bool is){setClippingEnabled(is);}; - /************/ - virtual void setClippingEnabled(bool able){Layout::setClippingEnabled(able);}; -protected: - Layout* _innerContainer; - - /* - DRAGPANEL_DIR m_eDirection; - DRAGPANEL_MOVE_DIR m_eMoveDirection; - */ - - bool _touchPressed; - bool _touchMoved; - bool _touchReleased; - bool _touchCanceld; // check touch out of drag panel boundary - - cocos2d::Point _touchStartNodeSpace; - cocos2d::Point _touchStartWorldSpace; - cocos2d::Point _touchEndWorldSpace; - - float _slidTime; - - // move type - DRAGPANEL_MOVE_TYPE _moveType; - - // auto move - float _autoMoveDuration; - float _autoMoveEaseRate; - - // event - cocos2d::Object* _eventLister; - SEL_DragPanelEvent _eventSelector; - - // berth - DRAGPANEL_BERTH_DIR _berthDirection; - - // bounce - bool _bounceEnable; - DRAGPANEL_BOUNCE_DIR _bounceDirection; - float _bounceDuration; - float _bounceEaseRate; - - - float _runningAction; - int _actionType; - - UIWidget* _actionWidget; - - float _duration; - float _elapsed; - bool _firstTick; - - cocos2d::Point _positionDelta; - cocos2d::Point _startPosition; - cocos2d::Point _previousPosition; - - cocos2d::Point _endPosition; -}; - -} - -#endif /* defined(__TestCpp__UIDragPanel__) */ diff --git a/cocos/gui/UIHelper.cpp b/cocos/gui/UIHelper.cpp index 409d0f4461..d896a6372c 100644 --- a/cocos/gui/UIHelper.cpp +++ b/cocos/gui/UIHelper.cpp @@ -22,111 +22,9 @@ THE SOFTWARE. ****************************************************************************/ -#include "gui/UIHelper.h" -#include "cocos2d.h" -#include "cocostudio/DictionaryHelper.h" -#include "cocostudio/CCSGUIReader.h" - - -using namespace cocos2d; -using namespace cocostudio; +#include "CocosGUI.h" namespace gui { - -static UIHelper* helperInstance = NULL; - -UIHelper* UIHelper::instance() -{ - if (!helperInstance) - { - helperInstance = new UIHelper(); - } - return helperInstance; -} - -void UIHelper::purgeUIHelper() -{ - CC_SAFE_DELETE(helperInstance); -} - -UIHelper::UIHelper(): -_textureFiles(NULL), -_fileDesignHeight(0.0f), -_fileDesignWidth(0.0f) -{ - Size winSize = Director::getInstance()->getWinSize(); - _fileDesignWidth = winSize.width; - _fileDesignHeight = winSize.height; - init(); -} - -UIHelper::~UIHelper() -{ - cocostudio::CCSGUIReader::purgeCCSGUIReader(); -} - -void UIHelper::init() -{ - _textureFiles = CCArray::create(); - _textureFiles->retain(); -} - -UIWidget* UIHelper::createWidgetFromJsonFile(const char *fileName) -{ - return CCSGUIReader::shareReader()->widgetFromJsonFile(fileName); -} - -void UIHelper::addSpriteFrame(const char *fileName) -{ - if (!fileName || strcmp(fileName, "") == 0) - { - return; - } - ccArray* arrayTextures = _textureFiles->data; - int length = arrayTextures->num; - for (int i=0;iarr[i]); - if (strcmp(file->_string.c_str(), fileName) == 0) - { - return; - } - } - _textureFiles->addObject(CCString::create(fileName)); - SpriteFrameCache::getInstance()->addSpriteFramesWithFile(fileName); -} - -void UIHelper::removeSpriteFrame(const char *fileName) -{ - if (!fileName || strcmp(fileName, "") == 0) - { - return; - } - ccArray* arrayTextures = _textureFiles->data; - int length = arrayTextures->num; - for (int i=0;iarr[i]); - if (strcmp(file->_string.c_str(), fileName) == 0) - { - SpriteFrameCache::getInstance()->removeSpriteFrameByName(fileName); - _textureFiles->removeObject(file); - return; - } - } -} - -void UIHelper::removeAllSpriteFrame() -{ - ccArray* arrayTextures = _textureFiles->data; - int length = arrayTextures->num; - for (int i=0;iarr[i]); - SpriteFrameCache::getInstance()->removeSpriteFrameByName(file->_string.c_str()); - } - _textureFiles->removeAllObjects(); -} UIWidget* UIHelper::seekWidgetByTag(UIWidget* root, int tag) { @@ -138,7 +36,7 @@ UIWidget* UIHelper::seekWidgetByTag(UIWidget* root, int tag) { return root; } - ccArray* arrayRootChildren = root->getChildren()->data; + cocos2d::ccArray* arrayRootChildren = root->getChildren()->data; int length = arrayRootChildren->num; for (int i=0;igetChildren()->data; + cocos2d::ccArray* arrayRootChildren = root->getChildren()->data; int length = arrayRootChildren->num; for (int i=0;igetChildren()->data; + cocos2d::ccArray* arrayRootChildren = root->getChildren()->data; int length = arrayRootChildren->num; for (int i=0;iarr[i]); - RelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter()); + UIRelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); if (layoutParameter && strcmp(layoutParameter->getRelativeName(), name) == 0) { return child; @@ -196,26 +94,6 @@ UIWidget* UIHelper::seekWidgetByRelativeName(UIWidget *root, const char *name) return NULL; } -void UIHelper::setFileDesignWidth(float width) -{ - _fileDesignWidth = width; -} - -float UIHelper::getFileDesignWidth() -{ - return _fileDesignWidth; -} - -void UIHelper::setFileDesignHeight(float height) -{ - _fileDesignHeight = height; -} - -float UIHelper::getFileDesignHeight() -{ - return _fileDesignHeight; -} - /*temp action*/ UIWidget* UIHelper::seekActionWidgetByActionTag(UIWidget* root, int tag) { @@ -227,7 +105,7 @@ UIWidget* UIHelper::seekActionWidgetByActionTag(UIWidget* root, int tag) { return root; } - ccArray* arrayRootChildren = root->getChildren()->data; + cocos2d::ccArray* arrayRootChildren = root->getChildren()->data; int length = arrayRootChildren->num; for (int i=0;i(_imageRenderer) #define DYNAMIC_CAST_SCALE9SPRITE dynamic_cast(_imageRenderer) @@ -41,7 +39,7 @@ _touchRelease(false), _doubleClickEnabled(false), _scale9Enabled(false), _prevIgnoreSize(true), -_capInsets(Rect::ZERO), +_capInsets(cocos2d::Rect::ZERO), _imageRenderer(NULL), _textureFile(""), _imageTexType(UI_TEX_TYPE_LOCAL), @@ -70,7 +68,7 @@ UIImageView* UIImageView::create() void UIImageView::initRenderer() { UIWidget::initRenderer(); - _imageRenderer = Sprite::create(); + _imageRenderer = cocos2d::Sprite::create(); _renderer->addChild(_imageRenderer); } @@ -90,6 +88,7 @@ void UIImageView::loadTexture(const char *fileName, TextureResType texType) DYNAMIC_CAST_SCALE9SPRITE->initWithFile(fileName); DYNAMIC_CAST_SCALE9SPRITE->setColor(getColor()); DYNAMIC_CAST_SCALE9SPRITE->setOpacity(getOpacity()); + DYNAMIC_CAST_SCALE9SPRITE->setCapInsets(_capInsets); } else { @@ -104,6 +103,7 @@ void UIImageView::loadTexture(const char *fileName, TextureResType texType) DYNAMIC_CAST_SCALE9SPRITE->initWithSpriteFrameName(fileName); DYNAMIC_CAST_SCALE9SPRITE->setColor(getColor()); DYNAMIC_CAST_SCALE9SPRITE->setOpacity(getOpacity()); + DYNAMIC_CAST_SCALE9SPRITE->setCapInsets(_capInsets); } else { @@ -120,7 +120,7 @@ void UIImageView::loadTexture(const char *fileName, TextureResType texType) imageTextureScaleChangedWithSize(); } -void UIImageView::setTextureRect(const Rect &rect) +void UIImageView::setTextureRect(const cocos2d::Rect &rect) { if (_scale9Enabled) { @@ -131,7 +131,7 @@ void UIImageView::setTextureRect(const Rect &rect) } } -bool UIImageView::onTouchBegan(const Point &touchPoint) +bool UIImageView::onTouchBegan(const cocos2d::Point &touchPoint) { setFocused(true); _touchStartPos.x = touchPoint.x; @@ -149,7 +149,7 @@ bool UIImageView::onTouchBegan(const Point &touchPoint) return _touchPassedEnabled; } -void UIImageView::onTouchEnded(const Point &touchPoint) +void UIImageView::onTouchEnded(const cocos2d::Point &touchPoint) { if (_doubleClickEnabled) { @@ -278,11 +278,11 @@ void UIImageView::setScale9Enabled(bool able) _imageRenderer = NULL; if (_scale9Enabled) { - _imageRenderer = extension::Scale9Sprite::create(); + _imageRenderer = cocos2d::extension::Scale9Sprite::create(); } else { - _imageRenderer = CCSprite::create(); + _imageRenderer = cocos2d::Sprite::create(); } loadTexture(_textureFile.c_str(),_imageTexType); _renderer->addChild(_imageRenderer); @@ -308,7 +308,7 @@ void UIImageView::ignoreContentAdaptWithSize(bool ignore) } } -void UIImageView::setCapInsets(const Rect &capInsets) +void UIImageView::setCapInsets(const cocos2d::Rect &capInsets) { _capInsets = capInsets; if (!_scale9Enabled) @@ -318,7 +318,7 @@ void UIImageView::setCapInsets(const Rect &capInsets) DYNAMIC_CAST_SCALE9SPRITE->setCapInsets(capInsets); } -void UIImageView::setAnchorPoint(const Point &pt) +void UIImageView::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); _imageRenderer->setAnchorPoint(pt); @@ -329,12 +329,12 @@ void UIImageView::onSizeChanged() imageTextureScaleChangedWithSize(); } -const Size& UIImageView::getContentSize() const +const cocos2d::Size& UIImageView::getContentSize() const { return _imageTextureSize; } -Node* UIImageView::getVirtualRenderer() +cocos2d::Node* UIImageView::getVirtualRenderer() { return _imageRenderer; } @@ -353,11 +353,11 @@ void UIImageView::imageTextureScaleChangedWithSize() { if (_scale9Enabled) { - dynamic_cast(_imageRenderer)->setPreferredSize(_size); + dynamic_cast(_imageRenderer)->setPreferredSize(_size); } else { - Size textureSize = _imageRenderer->getContentSize(); + cocos2d::Size textureSize = _imageRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _imageRenderer->setScale(1.0f); @@ -376,4 +376,21 @@ const char* UIImageView::getDescription() const return "ImageView"; } +UIWidget* UIImageView::createCloneInstance() +{ + return UIImageView::create(); +} + +void UIImageView::copySpecialProperties(UIWidget *widget) +{ + UIImageView* imageView = dynamic_cast(widget); + if (imageView) + { + _prevIgnoreSize = imageView->_prevIgnoreSize; + setScale9Enabled(imageView->_scale9Enabled); + loadTexture(imageView->_textureFile.c_str(), imageView->_imageTexType); + setCapInsets(imageView->_capInsets); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UIImageView.h b/cocos/gui/UIImageView.h index 91bd2573ec..16103aa256 100644 --- a/cocos/gui/UIImageView.h +++ b/cocos/gui/UIImageView.h @@ -29,6 +29,10 @@ namespace gui { +/** +* @js NA +* @lua NA +*/ class UIImageView : public UIWidget { public: @@ -100,22 +104,22 @@ public: //override "ignoreContentAdaptWithSize" method of widget. virtual void ignoreContentAdaptWithSize(bool ignore); - + /** + * Returns the "class name" of widget. + */ + virtual const char* getDescription() const; void setDoubleClickEnabled(bool able); void doubleClickEvent(); void checkDoubleClick(float dt); virtual const cocos2d::Size& getContentSize() const; virtual cocos2d::Node* getVirtualRenderer(); - - /** - * Returns the "class name" of widget. - */ - virtual const char* getDescription() const; protected: virtual void initRenderer(); virtual void onSizeChanged(); void imageTextureScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: int _clickCount; float _clickTimeInterval; diff --git a/cocos/gui/UIInputManager.cpp b/cocos/gui/UIInputManager.cpp index 0fe2eb153e..a1c6659557 100644 --- a/cocos/gui/UIInputManager.cpp +++ b/cocos/gui/UIInputManager.cpp @@ -37,11 +37,11 @@ _longClickRecordTime(0.0), _checkedDoubleClickWidget(NULL), _rootWidget(NULL) { - _manageredWidget = CCArray::create(); + _manageredWidget = Array::create(); _manageredWidget->retain(); - _checkedDoubleClickWidget = CCArray::create(); + _checkedDoubleClickWidget = Array::create(); _checkedDoubleClickWidget->retain(); - _selectedWidgets = CCArray::create(); + _selectedWidgets = Array::create(); _selectedWidgets->retain(); } @@ -176,10 +176,10 @@ void UIInputManager::onTouchEnd(Touch* touch) int length = selectedWidgetArray->num; for (int i=0; iarr[i]); + UIWidget* hitWidget = (UIWidget*)(selectedWidgetArray->arr[0]); + _selectedWidgets->removeObject(hitWidget); hitWidget->onTouchEnded(_touchEndedPoint); } - _selectedWidgets->removeAllObjects(); } void UIInputManager::onTouchCancelled(Touch* touch) @@ -191,10 +191,10 @@ void UIInputManager::onTouchCancelled(Touch* touch) int length = selectedWidgetArray->num; for (int i=0; iarr[i]); + UIWidget* hitWidget = (UIWidget*)(selectedWidgetArray->arr[0]); + _selectedWidgets->removeObject(hitWidget); hitWidget->onTouchCancelled(_touchEndedPoint); } - _selectedWidgets->removeAllObjects(); } void UIInputManager::setRootWidget(UIWidget *root) diff --git a/cocos/gui/UIInputManager.h b/cocos/gui/UIInputManager.h index 9547b091a1..ed5a931f89 100644 --- a/cocos/gui/UIInputManager.h +++ b/cocos/gui/UIInputManager.h @@ -26,7 +26,7 @@ #define __UIINPUTMANAGER_H__ #include "cocos2d.h" -#include "gui/Layout.h" +#include "gui/UILayout.h" namespace gui { @@ -41,7 +41,7 @@ public: /** * Default destructor */ - ~UIInputManager(); + virtual ~UIInputManager(); /** * Regist a widget to input manager. diff --git a/cocos/gui/UILabel.cpp b/cocos/gui/UILabel.cpp index 6ac5d68fdf..cdf32c49c1 100644 --- a/cocos/gui/UILabel.cpp +++ b/cocos/gui/UILabel.cpp @@ -24,10 +24,9 @@ #include "gui/UILabel.h" - using namespace cocos2d; - namespace gui { + UILabel::UILabel(): _touchScaleChangeEnabled(false), _normalScaleValue(1.0f), @@ -67,57 +66,56 @@ bool UILabel::init() void UILabel::initRenderer() { UIWidget::initRenderer(); - _labelRenderer = CCLabelTTF::create(); + _labelRenderer = cocos2d::LabelTTF::create(); _renderer->addChild(_labelRenderer); } -void UILabel::setText(const char* text) +void UILabel::setText(const std::string& text) { - if (!text) - { + if (text.size()==0) return; - } - std::string strText(text); - _labelRenderer->setString(strText.c_str()); + + _labelRenderer->setString(text); labelScaleChangedWithSize(); } -const char* UILabel::getStringValue() +const std::string& UILabel::getStringValue() { return _labelRenderer->getString(); } int UILabel::getStringLength() { - const char* str = _labelRenderer->getString(); - return strlen(str); + return _labelRenderer->getString().size(); } void UILabel::setFontSize(int size) { + _fontSize = size; _labelRenderer->setFontSize(size); labelScaleChangedWithSize(); } -void UILabel::setFontName(const char* name) +void UILabel::setFontName(const std::string& name) { + _fontName = name; _labelRenderer->setFontName(name); labelScaleChangedWithSize(); } -void UILabel::setTextAreaSize(const Size &size) +void UILabel::setTextAreaSize(const cocos2d::Size &size) { _labelRenderer->setDimensions(size); labelScaleChangedWithSize(); } -void UILabel::setTextHorizontalAlignment(TextHAlignment alignment) +void UILabel::setTextHorizontalAlignment(cocos2d::TextHAlignment alignment) { _labelRenderer->setHorizontalAlignment(alignment); labelScaleChangedWithSize(); } -void UILabel::setTextVerticalAlignment(TextVAlignment alignment) +void UILabel::setTextVerticalAlignment(cocos2d::TextVAlignment alignment) { _labelRenderer->setVerticalAlignment(alignment); labelScaleChangedWithSize(); @@ -182,7 +180,7 @@ bool UILabel::isFlipY() return _labelRenderer->isFlippedY(); } -void UILabel::setAnchorPoint(const Point &pt) +void UILabel::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); _labelRenderer->setAnchorPoint(pt); @@ -193,12 +191,12 @@ void UILabel::onSizeChanged() labelScaleChangedWithSize(); } -const Size& UILabel::getContentSize() const +const cocos2d::Size& UILabel::getContentSize() const { return _labelRenderer->getContentSize(); } -Node* UILabel::getVirtualRenderer() +cocos2d::Node* UILabel::getVirtualRenderer() { return _labelRenderer; } @@ -212,7 +210,7 @@ void UILabel::labelScaleChangedWithSize() } else { - Size textureSize = _labelRenderer->getContentSize(); + cocos2d::Size textureSize = _labelRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _labelRenderer->setScale(1.0f); @@ -223,6 +221,7 @@ void UILabel::labelScaleChangedWithSize() _labelRenderer->setScaleX(scaleX); _labelRenderer->setScaleY(scaleY); } + } const char* UILabel::getDescription() const @@ -230,4 +229,21 @@ const char* UILabel::getDescription() const return "Label"; } +UIWidget* UILabel::createCloneInstance() +{ + return UILabel::create(); +} + +void UILabel::copySpecialProperties(UIWidget *widget) +{ + UILabel* label = dynamic_cast(widget); + if (label) + { + setFontName(label->_fontName.c_str()); + setFontSize(label->_labelRenderer->getFontSize()); + setText(label->getStringValue()); + setTouchScaleChangeEnabled(label->_touchScaleChangeEnabled); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UILabel.h b/cocos/gui/UILabel.h index 0d9150f17d..c38945bb9a 100644 --- a/cocos/gui/UILabel.h +++ b/cocos/gui/UILabel.h @@ -27,8 +27,13 @@ #include "gui/UIWidget.h" + namespace gui { +/** +* @js NA +* @lua NA +*/ class UILabel : public UIWidget { public: @@ -52,14 +57,14 @@ public: * * @param text string value. */ - void setText(const char* text); + void setText(const std::string& text); /** * Gets the string value of label. * * @return text string value. */ - const char* getStringValue(); + const std::string& getStringValue(); /** * Gets the string length of label. @@ -80,7 +85,7 @@ public: * * @param font name. */ - void setFontName(const char* name); + void setFontName(const std::string& name); /** * Sets the touch scale enabled of label. @@ -124,11 +129,7 @@ public: void setTextAreaSize(const cocos2d::Size &size); void setTextHorizontalAlignment(cocos2d::TextHAlignment alignment); - void setTextVerticalAlignment(cocos2d::TextVAlignment alignment); - - - void setTouchScaleChangeAble(bool able){setTouchScaleChangeEnabled(able);}; - bool getTouchScaleChangeAble(){return isTouchScaleChangeEnabled();}; + void setTextVerticalAlignment(cocos2d::TextVAlignment alignment); protected: virtual bool init(); virtual void initRenderer(); @@ -138,6 +139,8 @@ protected: virtual void onSizeChanged(); void clickScale(float scale); void labelScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: bool _touchScaleChangeEnabled; float _normalScaleValue; diff --git a/cocos/gui/UILabelAtlas.cpp b/cocos/gui/UILabelAtlas.cpp index 72b816e4a6..17963f595f 100644 --- a/cocos/gui/UILabelAtlas.cpp +++ b/cocos/gui/UILabelAtlas.cpp @@ -24,10 +24,9 @@ #include "gui/UILabelAtlas.h" - using namespace cocos2d; - namespace gui { + UICCLabelAtlas::UICCLabelAtlas() { @@ -51,12 +50,12 @@ UICCLabelAtlas* UICCLabelAtlas::create() return NULL; } -void UICCLabelAtlas::setProperty(const char *string, const char *charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) +void UICCLabelAtlas::setProperty(const std::string& string, const std::string& charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) { initWithString(string, charMapFile, itemWidth, itemHeight, startCharMap); } -void UICCLabelAtlas::setProperty(const char *string, Texture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) +void UICCLabelAtlas::setProperty(const std::string& string, cocos2d::Texture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) { initWithString(string, texture, itemWidth, itemHeight, startCharMap); } @@ -68,20 +67,26 @@ void UICCLabelAtlas::draw() return; } - CCAtlasNode::draw(); + cocos2d::AtlasNode::draw(); } void UICCLabelAtlas::updateDisplayedOpacity(GLubyte opacity) { - CCAtlasNode::setOpacity(opacity); + cocos2d::AtlasNode::setOpacity(opacity); } UILabelAtlas::UILabelAtlas(): -_laberAtlasRenderer(NULL) +_laberAtlasRenderer(NULL), +_stringValue(""), +_charMapFileName(""), +_itemWidth(0), +_itemHeight(0), +_startCharMap("") { + } UILabelAtlas::~UILabelAtlas() @@ -108,28 +113,34 @@ void UILabelAtlas::initRenderer() _renderer->addChild(_laberAtlasRenderer); } -void UILabelAtlas::setProperty(const char *stringValue, const char *charMapFile, int itemWidth, int itemHeight, const char *startCharMap,bool useSpriteFrame) +void UILabelAtlas::setProperty(const std::string& stringValue, const std::string& charMapFile, int itemWidth, int itemHeight, const std::string& startCharMap) { + _stringValue = stringValue; + _charMapFileName = charMapFile; + _itemWidth = itemWidth; + _itemHeight = itemHeight; + _startCharMap = startCharMap; _laberAtlasRenderer->setProperty(stringValue, charMapFile, itemWidth, itemHeight, (int)(startCharMap[0])); updateAnchorPoint(); labelAtlasScaleChangedWithSize(); } -void UILabelAtlas::setStringValue(const char *value) +void UILabelAtlas::setStringValue(const std::string& value) { + _stringValue = value; _laberAtlasRenderer->setString(value); labelAtlasScaleChangedWithSize(); } -const char* UILabelAtlas::getStringValue() +const std::string& UILabelAtlas::getStringValue() const { return _laberAtlasRenderer->getString(); } -void UILabelAtlas::setAnchorPoint(const Point &pt) +void UILabelAtlas::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); - _laberAtlasRenderer->setAnchorPoint(Point(pt.x, pt.y)); + _laberAtlasRenderer->setAnchorPoint(cocos2d::Point(pt.x, pt.y)); } void UILabelAtlas::onSizeChanged() @@ -137,12 +148,12 @@ void UILabelAtlas::onSizeChanged() labelAtlasScaleChangedWithSize(); } -const Size& UILabelAtlas::getContentSize() const +const cocos2d::Size& UILabelAtlas::getContentSize() const { return _laberAtlasRenderer->getContentSize(); } -Node* UILabelAtlas::getVirtualRenderer() +cocos2d::Node* UILabelAtlas::getVirtualRenderer() { return _laberAtlasRenderer; } @@ -156,7 +167,7 @@ void UILabelAtlas::labelAtlasScaleChangedWithSize() } else { - Size textureSize = _laberAtlasRenderer->getContentSize(); + cocos2d::Size textureSize = _laberAtlasRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _laberAtlasRenderer->setScale(1.0f); @@ -171,7 +182,21 @@ void UILabelAtlas::labelAtlasScaleChangedWithSize() const char* UILabelAtlas::getDescription() const { - return "LabelAtlase"; + return "LabelAtlas"; } +UIWidget* UILabelAtlas::createCloneInstance() +{ + return UILabelAtlas::create(); +} + +void UILabelAtlas::copySpecialProperties(UIWidget *widget) +{ + UILabelAtlas* labelAtlas = dynamic_cast(widget); + if (labelAtlas) + { + setProperty(labelAtlas->_stringValue, labelAtlas->_charMapFileName, labelAtlas->_itemWidth, labelAtlas->_itemHeight, labelAtlas->_startCharMap); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UILabelAtlas.h b/cocos/gui/UILabelAtlas.h index b74ea87644..a33872ef0c 100644 --- a/cocos/gui/UILabelAtlas.h +++ b/cocos/gui/UILabelAtlas.h @@ -29,6 +29,10 @@ namespace gui { +/** + * @js NA + * @lua NA + */ class UICCLabelAtlas : public cocos2d::LabelAtlas { public: @@ -46,12 +50,15 @@ public: * Allocates and initializes. */ static UICCLabelAtlas* create(); - void setProperty(const char *string, const char *charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); - void setProperty(const char *string, cocos2d::Texture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); + void setProperty(const std::string& string, const std::string& charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); + void setProperty(const std::string& string, cocos2d::Texture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); virtual void updateDisplayedOpacity(GLubyte opacity); virtual void draw(void); }; - +/** + * @js NA + * @lua NA + */ class UILabelAtlas : public UIWidget { public: @@ -71,13 +78,13 @@ public: static UILabelAtlas* create(); /** initializes the UILabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas */ - void setProperty(const char* stringValue,const char* charMapFile, int itemWidth, int itemHeight, const char* startCharMap,bool useSpriteFrame = false); + void setProperty(const std::string& stringValue,const std::string& charMapFile, int itemWidth, int itemHeight, const std::string& startCharMap); //set string value for labelatlas. - void setStringValue(const char* value); + void setStringValue(const std::string& value); //get string value for labelatlas. - const char* getStringValue(); + const std::string& getStringValue() const; //override "setAnchorPoint" method of widget. virtual void setAnchorPoint(const cocos2d::Point &pt); @@ -92,12 +99,20 @@ public: * Returns the "class name" of widget. */ virtual const char* getDescription() const; + protected: virtual void initRenderer(); virtual void onSizeChanged(); void labelAtlasScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: UICCLabelAtlas* _laberAtlasRenderer; + std::string _stringValue; + std::string _charMapFileName; + int _itemWidth; + int _itemHeight; + std::string _startCharMap; }; } diff --git a/cocos/gui/UILabelBMFont.cpp b/cocos/gui/UILabelBMFont.cpp index b112c06bf4..ee3ad66ddf 100644 --- a/cocos/gui/UILabelBMFont.cpp +++ b/cocos/gui/UILabelBMFont.cpp @@ -24,13 +24,13 @@ #include "gui/UILabelBMFont.h" - using namespace cocos2d; - namespace gui { UILabelBMFont::UILabelBMFont(): _labelBMFontRenderer(NULL), -_fntFileHasInit(false) +_fntFileHasInit(false), +_fntFileName(""), +_stringValue("") { } @@ -54,7 +54,7 @@ UILabelBMFont* UILabelBMFont::create() void UILabelBMFont::initRenderer() { UIWidget::initRenderer(); - _labelBMFontRenderer = CCLabelBMFont::create(); + _labelBMFontRenderer = cocos2d::LabelBMFont::create(); _renderer->addChild(_labelBMFontRenderer); } @@ -64,28 +64,35 @@ void UILabelBMFont::setFntFile(const char *fileName) { return; } + _fntFileName = fileName; _labelBMFontRenderer->initWithString("", fileName); updateAnchorPoint(); labelBMFontScaleChangedWithSize(); _fntFileHasInit = true; + setText(_stringValue.c_str()); } void UILabelBMFont::setText(const char* value) { - if (!value || !_fntFileHasInit) + if (!value) { return; } - _labelBMFontRenderer->setString(value); + _stringValue = value; + if (!_fntFileHasInit) + { + return; + } + _labelBMFontRenderer->setString(value); labelBMFontScaleChangedWithSize(); } const char* UILabelBMFont::getStringValue() { - return _labelBMFontRenderer->getString(); + return _stringValue.c_str(); } -void UILabelBMFont::setAnchorPoint(const Point &pt) +void UILabelBMFont::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); _labelBMFontRenderer->setAnchorPoint(pt); @@ -96,12 +103,12 @@ void UILabelBMFont::onSizeChanged() labelBMFontScaleChangedWithSize(); } -const Size& UILabelBMFont::getContentSize() const +const cocos2d::Size& UILabelBMFont::getContentSize() const { return _labelBMFontRenderer->getContentSize(); } -Node* UILabelBMFont::getVirtualRenderer() +cocos2d::Node* UILabelBMFont::getVirtualRenderer() { return _labelBMFontRenderer; } @@ -115,7 +122,7 @@ void UILabelBMFont::labelBMFontScaleChangedWithSize() } else { - Size textureSize = _labelBMFontRenderer->getContentSize(); + cocos2d::Size textureSize = _labelBMFontRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _labelBMFontRenderer->setScale(1.0f); @@ -133,5 +140,19 @@ const char* UILabelBMFont::getDescription() const return "LabelBMFont"; } +UIWidget* UILabelBMFont::createCloneInstance() +{ + return UILabelBMFont::create(); +} + +void UILabelBMFont::copySpecialProperties(UIWidget *widget) +{ + UILabelBMFont* labelBMFont = dynamic_cast(widget); + if (labelBMFont) + { + setFntFile(labelBMFont->_fntFileName.c_str()); + setText(labelBMFont->_stringValue.c_str()); + } +} } \ No newline at end of file diff --git a/cocos/gui/UILabelBMFont.h b/cocos/gui/UILabelBMFont.h index ddf4e31728..5c03c1ae75 100644 --- a/cocos/gui/UILabelBMFont.h +++ b/cocos/gui/UILabelBMFont.h @@ -29,6 +29,10 @@ namespace gui { +/** +* @js NA +* @lua NA +*/ class UILabelBMFont : public UIWidget { public: @@ -58,7 +62,6 @@ public: virtual void setAnchorPoint(const cocos2d::Point &pt); virtual const cocos2d::Size& getContentSize() const; virtual cocos2d::Node* getVirtualRenderer(); - /** * Returns the "class name" of widget. */ @@ -67,9 +70,13 @@ protected: virtual void initRenderer(); virtual void onSizeChanged(); void labelBMFontScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: cocos2d::LabelBMFont* _labelBMFontRenderer; bool _fntFileHasInit; + std::string _fntFileName; + std::string _stringValue; }; } diff --git a/cocos/gui/UILayer.cpp b/cocos/gui/UILayer.cpp index bfdea4094f..a935f9efc5 100644 --- a/cocos/gui/UILayer.cpp +++ b/cocos/gui/UILayer.cpp @@ -119,7 +119,7 @@ UIWidget* UILayer::getWidgetByTag(int tag) { return NULL; } - return CCUIHELPER->seekWidgetByTag(_rootWidget, tag); + return UIHelper::seekWidgetByTag(_rootWidget, tag); } UIWidget* UILayer::getWidgetByName(const char* name) @@ -128,7 +128,7 @@ UIWidget* UILayer::getWidgetByName(const char* name) { return NULL; } - return CCUIHELPER->seekWidgetByName(_rootWidget, name); + return UIHelper::seekWidgetByName(_rootWidget, name); } UIRootWidget* UILayer::getRootWidget() diff --git a/cocos/gui/UILayout.cpp b/cocos/gui/UILayout.cpp new file mode 100644 index 0000000000..a7af98c1b8 --- /dev/null +++ b/cocos/gui/UILayout.cpp @@ -0,0 +1,1010 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "gui/UILayout.h" +#include "gui/UILayer.h" +#include "gui/UIHelper.h" +#include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" + +namespace gui { + + +#define DYNAMIC_CAST_CLIPPINGLAYER dynamic_cast(_renderer) + +UILayout::UILayout(): +_clippingEnabled(false), +_backGroundScale9Enabled(false), +_backGroundImage(NULL), +_backGroundImageFileName(""), +_backGroundImageCapInsets(cocos2d::Rect::ZERO), +_colorType(LAYOUT_COLOR_NONE), +_bgImageTexType(UI_TEX_TYPE_LOCAL), +_colorRender(NULL), +_gradientRender(NULL), +_cColor(cocos2d::Color3B::WHITE), +_gStartColor(cocos2d::Color3B::WHITE), +_gEndColor(cocos2d::Color3B::WHITE), +_alongVector(cocos2d::Point(0.0f, -1.0f)), +_cOpacity(255), +_backGroundImageTextureSize(cocos2d::Size::ZERO), +_layoutType(LAYOUT_ABSOLUTE) +{ + _widgetType = WidgetTypeContainer; +} + +UILayout::~UILayout() +{ +} + +UILayout* UILayout::create() +{ + UILayout* layout = new UILayout(); + if (layout && layout->init()) + { + layout->autorelease(); + return layout; + } + CC_SAFE_DELETE(layout); + return NULL; +} + +bool UILayout::init() +{ + _children = cocos2d::Array::create(); + _children->retain(); + _layoutParameterDictionary = cocos2d::Dictionary::create(); + CC_SAFE_RETAIN(_layoutParameterDictionary); + initRenderer(); + _renderer->retain(); + _renderer->setZOrder(_widgetZOrder); + cocos2d::RGBAProtocol* renderRGBA = dynamic_cast(_renderer); + if (renderRGBA) + { + renderRGBA->setCascadeColorEnabled(false); + renderRGBA->setCascadeOpacityEnabled(false); + } + ignoreContentAdaptWithSize(false); + setSize(cocos2d::Size::ZERO); + setBright(true); + setAnchorPoint(cocos2d::Point(0, 0)); + _scheduler = cocos2d::Director::getInstance()->getScheduler(); + CC_SAFE_RETAIN(_scheduler); + return true; +} + +void UILayout::initRenderer() +{ + _renderer = UIRectClippingNode::create(); +} + +bool UILayout::addChild(UIWidget *child) +{ + supplyTheLayoutParameterLackToChild(child); + return UIWidget::addChild(child); +} + +bool UILayout::isClippingEnabled() +{ + return _clippingEnabled; +} + +bool UILayout::hitTest(const cocos2d::Point &pt) +{ + cocos2d::Point nsp = _renderer->convertToNodeSpace(pt); + cocos2d::Rect bb = cocos2d::Rect(0.0f, 0.0f, _size.width, _size.height); + if (nsp.x >= bb.origin.x && nsp.x <= bb.origin.x + bb.size.width && nsp.y >= bb.origin.y && nsp.y <= bb.origin.y + bb.size.height) + { + return true; + } + return false; +} + +void UILayout::setClippingEnabled(bool able) +{ + _clippingEnabled = able; + DYNAMIC_CAST_CLIPPINGLAYER->setClippingEnabled(able); +} + +void UILayout::onSizeChanged() +{ + DYNAMIC_CAST_CLIPPINGLAYER->setClippingSize(_size); + doLayout(); + if (_backGroundImage) + { + _backGroundImage->setPosition(cocos2d::Point(_size.width/2.0f, _size.height/2.0f)); + if (_backGroundScale9Enabled) + { + dynamic_cast(_backGroundImage)->setPreferredSize(_size); + } + } + if (_colorRender) + { + _colorRender->setContentSize(_size); + } + if (_gradientRender) + { + _gradientRender->setContentSize(_size); + } +} + +void UILayout::setBackGroundImageScale9Enabled(bool able) +{ + if (_backGroundScale9Enabled == able) + { + return; + } + _renderer->removeChild(_backGroundImage, true); + _backGroundImage = NULL; + _backGroundScale9Enabled = able; + if (_backGroundScale9Enabled) + { + _backGroundImage = cocos2d::extension::Scale9Sprite::create(); + _renderer->addChild(_backGroundImage); + } + else + { + _backGroundImage = cocos2d::Sprite::create(); + _renderer->addChild(_backGroundImage); + } + _backGroundImage->setZOrder(-1); + setBackGroundImage(_backGroundImageFileName.c_str(),_bgImageTexType); + setBackGroundImageCapInsets(_backGroundImageCapInsets); +} + +void UILayout::setBackGroundImage(const char* fileName,TextureResType texType) +{ + if (!fileName || strcmp(fileName, "") == 0) + { + return; + } + if (_backGroundImage == NULL) + { + addBackGroundImage(); + } + _backGroundImageFileName = fileName; + _bgImageTexType = texType; + if (_backGroundScale9Enabled) + { + switch (_bgImageTexType) + { + case UI_TEX_TYPE_LOCAL: + dynamic_cast(_backGroundImage)->initWithFile(fileName); + break; + case UI_TEX_TYPE_PLIST: + dynamic_cast(_backGroundImage)->initWithSpriteFrameName(fileName); + break; + default: + break; + } + dynamic_cast(_backGroundImage)->setPreferredSize(_size); + } + else + { + switch (_bgImageTexType) + { + case UI_TEX_TYPE_LOCAL: + dynamic_cast(_backGroundImage)->initWithFile(fileName); + break; + case UI_TEX_TYPE_PLIST: + dynamic_cast(_backGroundImage)->initWithSpriteFrameName(fileName); + break; + default: + break; + } + } + if (_backGroundScale9Enabled) + { + dynamic_cast(_backGroundImage)->setColor(getColor()); + dynamic_cast(_backGroundImage)->setOpacity(getOpacity()); + } + else + { + dynamic_cast(_backGroundImage)->setColor(getColor()); + dynamic_cast(_backGroundImage)->setOpacity(getOpacity()); + } + _backGroundImageTextureSize = _backGroundImage->getContentSize(); + _backGroundImage->setPosition(cocos2d::Point(_size.width/2.0f, _size.height/2.0f)); +} + +void UILayout::setBackGroundImageCapInsets(const cocos2d::Rect &capInsets) +{ + _backGroundImageCapInsets = capInsets; + if (_backGroundScale9Enabled) + { + dynamic_cast(_backGroundImage)->setCapInsets(capInsets); + } +} + +void UILayout::supplyTheLayoutParameterLackToChild(UIWidget *child) +{ + if (!child) + { + return; + } + switch (_layoutType) + { + case LAYOUT_ABSOLUTE: + break; + case LAYOUT_LINEAR_HORIZONTAL: + case LAYOUT_LINEAR_VERTICAL: + { + UILinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); + if (!layoutParameter) + { + child->setLayoutParameter(UILinearLayoutParameter::create()); + } + break; + } + case LAYOUT_RELATIVE: + { + UIRelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); + if (!layoutParameter) + { + child->setLayoutParameter(UIRelativeLayoutParameter::create()); + } + break; + } + default: + break; + } +} + +void UILayout::addBackGroundImage() +{ + if (_backGroundScale9Enabled) + { + _backGroundImage = cocos2d::extension::Scale9Sprite::create(); + _backGroundImage->setZOrder(-1); + _renderer->addChild(_backGroundImage); + dynamic_cast(_backGroundImage)->setPreferredSize(_size); + } + else + { + _backGroundImage = cocos2d::Sprite::create(); + _backGroundImage->setZOrder(-1); + _renderer->addChild(_backGroundImage); + } + _backGroundImage->setPosition(cocos2d::Point(_size.width/2.0f, _size.height/2.0f)); +} + +void UILayout::removeBackGroundImage() +{ + if (!_backGroundImage) + { + return; + } + _renderer->removeChild(_backGroundImage, true); + _backGroundImage = NULL; + _backGroundImageFileName = ""; + _backGroundImageTextureSize = cocos2d::Size::ZERO; +} + +void UILayout::setBackGroundColorType(LayoutBackGroundColorType type) +{ + if (_colorType == type) + { + return; + } + switch (_colorType) + { + case LAYOUT_COLOR_NONE: + if (_colorRender) + { + _renderer->removeChild(_colorRender, true); + _colorRender = NULL; + } + if (_gradientRender) + { + _renderer->removeChild(_gradientRender, true); + _gradientRender = NULL; + } + break; + case LAYOUT_COLOR_SOLID: + if (_colorRender) + { + _renderer->removeChild(_colorRender, true); + _colorRender = NULL; + } + break; + case LAYOUT_COLOR_GRADIENT: + if (_gradientRender) + { + _renderer->removeChild(_gradientRender, true); + _gradientRender = NULL; + } + break; + default: + break; + } + _colorType = type; + switch (_colorType) + { + case LAYOUT_COLOR_NONE: + break; + case LAYOUT_COLOR_SOLID: + _colorRender = cocos2d::LayerColor::create(); + _colorRender->setContentSize(_size); + _colorRender->setOpacity(_cOpacity); + _colorRender->setColor(_cColor); + _renderer->addChild(_colorRender,-2); + break; + case LAYOUT_COLOR_GRADIENT: + _gradientRender = cocos2d::LayerGradient::create(); + _gradientRender->setContentSize(_size); + _gradientRender->setOpacity(_cOpacity); + _gradientRender->setStartColor(_gStartColor); + _gradientRender->setEndColor(_gEndColor); + _gradientRender->setVector(_alongVector); + _renderer->addChild(_gradientRender,-2); + break; + default: + break; + } +} + +void UILayout::setBackGroundColor(const cocos2d::Color3B &color) +{ + _cColor = color; + if (_colorRender) + { + _colorRender->setColor(color); + } +} + +void UILayout::setBackGroundColor(const cocos2d::Color3B &startColor, const cocos2d::Color3B &endColor) +{ + _gStartColor = startColor; + if (_gradientRender) + { + _gradientRender->setStartColor(startColor); + } + _gEndColor = endColor; + if (_gradientRender) + { + _gradientRender->setEndColor(endColor); + } +} + +void UILayout::setBackGroundColorOpacity(int opacity) +{ + _cOpacity = opacity; + switch (_colorType) + { + case LAYOUT_COLOR_NONE: + break; + case LAYOUT_COLOR_SOLID: + _colorRender->setOpacity(opacity); + break; + case LAYOUT_COLOR_GRADIENT: + _gradientRender->setOpacity(opacity); + break; + default: + break; + } +} + +void UILayout::setBackGroundColorVector(const cocos2d::Point &vector) +{ + _alongVector = vector; + if (_gradientRender) + { + _gradientRender->setVector(vector); + } +} + +void UILayout::setColor(const cocos2d::Color3B &color) +{ + UIWidget::setColor(color); + if (_backGroundImage) + { + cocos2d::RGBAProtocol* rgbap = dynamic_cast(_backGroundImage); + if (rgbap) + { + rgbap->setColor(color); + } + } +} + +void UILayout::setOpacity(int opacity) +{ + UIWidget::setOpacity(opacity); + if (_backGroundImage) + { + cocos2d::RGBAProtocol* rgbap = dynamic_cast(_backGroundImage); + if (rgbap) + { + rgbap->setOpacity(opacity); + } + } +} + +const cocos2d::Size& UILayout::getBackGroundImageTextureSize() const +{ + return _backGroundImageTextureSize; +} + +const cocos2d::Size& UILayout::getContentSize() const +{ + return _renderer->getContentSize(); +} + +void UILayout::setLayoutType(LayoutType type) +{ + _layoutType = type; + + cocos2d::ccArray* layoutChildrenArray = getChildren()->data; + int length = layoutChildrenArray->num; + for (int i=0; i(layoutChildrenArray->arr[i]); + supplyTheLayoutParameterLackToChild(child); + } +} + +LayoutType UILayout::getLayoutType() const +{ + return _layoutType; +} + +void UILayout::doLayout() +{ + switch (_layoutType) + { + case LAYOUT_ABSOLUTE: + break; + case LAYOUT_LINEAR_VERTICAL: + { + cocos2d::ccArray* layoutChildrenArray = getChildren()->data; + int length = layoutChildrenArray->num; + cocos2d::Size layoutSize = getSize(); + float topBoundary = layoutSize.height; + for (int i=0; i(layoutChildrenArray->arr[i]); + UILinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); + + if (layoutParameter) + { + UILinearGravity childGravity = layoutParameter->getGravity(); + cocos2d::Point ap = child->getAnchorPoint(); + cocos2d::Size cs = child->getSize(); + float finalPosX = ap.x * cs.width; + float finalPosY = topBoundary - ((1.0f-ap.y) * cs.height); + switch (childGravity) + { + case LINEAR_GRAVITY_NONE: + case LINEAR_GRAVITY_LEFT: + break; + case LINEAR_GRAVITY_RIGHT: + finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); + break; + case LINEAR_GRAVITY_CENTER_HORIZONTAL: + finalPosX = layoutSize.width / 2.0f - cs.width * (0.5f-ap.x); + break; + default: + break; + } + UIMargin mg = layoutParameter->getMargin(); + finalPosX += mg.left; + finalPosY -= mg.top; + child->setPosition(cocos2d::Point(finalPosX, finalPosY)); + topBoundary = child->getBottomInParent() - mg.bottom; + } + } + break; + } + case LAYOUT_LINEAR_HORIZONTAL: + { + cocos2d::ccArray* layoutChildrenArray = getChildren()->data; + int length = layoutChildrenArray->num; + cocos2d::Size layoutSize = getSize(); + float leftBoundary = 0.0f; + for (int i=0; i(layoutChildrenArray->arr[i]); + UILinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); + + if (layoutParameter) + { + UILinearGravity childGravity = layoutParameter->getGravity(); + cocos2d::Point ap = child->getAnchorPoint(); + cocos2d::Size cs = child->getSize(); + float finalPosX = leftBoundary + (ap.x * cs.width); + float finalPosY = layoutSize.height - (1.0f - ap.y) * cs.height; + switch (childGravity) + { + case LINEAR_GRAVITY_NONE: + case LINEAR_GRAVITY_TOP: + break; + case LINEAR_GRAVITY_BOTTOM: + finalPosY = ap.y * cs.height; + break; + case LINEAR_GRAVITY_CENTER_VERTICAL: + finalPosY = layoutSize.height / 2.0f - cs.height * (0.5f - ap.y); + break; + default: + break; + } + UIMargin mg = layoutParameter->getMargin(); + finalPosX += mg.left; + finalPosY -= mg.top; + child->setPosition(cocos2d::Point(finalPosX, finalPosY)); + leftBoundary = child->getRightInParent() + mg.right; + } + } + break; + } + case LAYOUT_RELATIVE: + { + cocos2d::ccArray* layoutChildrenArray = getChildren()->data; + int length = layoutChildrenArray->num; + int unlayoutChildCount = length; + cocos2d::Size layoutSize = getSize(); + + for (int i=0; i(layoutChildrenArray->arr[i]); + UIRelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); + layoutParameter->_put = false; + } + + while (unlayoutChildCount > 0) + { + for (int i=0; i(layoutChildrenArray->arr[i]); + UIRelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); + + if (layoutParameter) + { + if (layoutParameter->_put) + { + continue; + } + cocos2d::Point ap = child->getAnchorPoint(); + cocos2d::Size cs = child->getSize(); + UIRelativeAlign align = layoutParameter->getAlign(); + const char* relativeName = layoutParameter->getRelativeToWidgetName(); + UIWidget* relativeWidget = NULL; + UIRelativeLayoutParameter* relativeWidgetLP = NULL; + float finalPosX = 0.0f; + float finalPosY = 0.0f; + if (relativeName && strcmp(relativeName, "")) + { + relativeWidget = UIHelper::seekWidgetByRelativeName(this, relativeName); + if (relativeWidget) + { + relativeWidgetLP = dynamic_cast(relativeWidget->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); + } + } + switch (align) + { + case RELATIVE_ALIGN_NONE: + case RELATIVE_ALIGN_PARENT_TOP_LEFT: + finalPosX = ap.x * cs.width; + finalPosY = layoutSize.height - ((1.0f - ap.y) * cs.height); + break; + case RELATIVE_ALIGN_PARENT_TOP_CENTER_HORIZONTAL: + finalPosX = layoutSize.width * 0.5f - cs.width * (0.5f - ap.x); + finalPosY = layoutSize.height - ((1.0f - ap.y) * cs.height); + break; + case RELATIVE_ALIGN_PARENT_TOP_RIGHT: + finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); + finalPosY = layoutSize.height - ((1.0f - ap.y) * cs.height); + break; + case RELATIVE_ALIGN_PARENT_LEFT_CENTER_VERTICAL: + finalPosX = ap.x * cs.width; + finalPosY = layoutSize.height * 0.5f - cs.height * (0.5f - ap.y); + break; + case RELATIVE_CENTER_IN_PARENT: + finalPosX = layoutSize.width * 0.5f - cs.width * (0.5f - ap.x); + finalPosY = layoutSize.height * 0.5f - cs.height * (0.5f - ap.y); + break; + case RELATIVE_ALIGN_PARENT_RIGHT_CENTER_VERTICAL: + finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); + finalPosY = layoutSize.height * 0.5f - cs.height * (0.5f - ap.y); + break; + case RELATIVE_ALIGN_PARENT_LEFT_BOTTOM: + finalPosX = ap.x * cs.width; + finalPosY = ap.y * cs.height; + break; + case RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL: + finalPosX = layoutSize.width * 0.5f - cs.width * (0.5f - ap.x); + finalPosY = ap.y * cs.height; + break; + case RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM: + finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); + finalPosY = ap.y * cs.height; + break; + + case RELATIVE_LOCATION_ABOVE_LEFTALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationBottom = relativeWidget->getTopInParent(); + float locationLeft = relativeWidget->getLeftInParent(); + finalPosY = locationBottom + ap.y * cs.height; + finalPosX = locationLeft + ap.x * cs.width; + } + break; + case RELATIVE_LOCATION_ABOVE_CENTER: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + cocos2d::Size rbs = relativeWidget->getSize(); + float locationBottom = relativeWidget->getTopInParent(); + + finalPosY = locationBottom + ap.y * cs.height; + finalPosX = relativeWidget->getLeftInParent() + rbs.width * 0.5f + ap.x * cs.width - cs.width * 0.5f; + } + break; + case RELATIVE_LOCATION_ABOVE_RIGHTALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationBottom = relativeWidget->getTopInParent(); + float locationRight = relativeWidget->getRightInParent(); + finalPosY = locationBottom + ap.y * cs.height; + finalPosX = locationRight - (1.0f - ap.x) * cs.width; + } + break; + case RELATIVE_LOCATION_LEFT_OF_TOPALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationTop = relativeWidget->getTopInParent(); + float locationRight = relativeWidget->getLeftInParent(); + finalPosY = locationTop - (1.0f - ap.y) * cs.height; + finalPosX = locationRight - (1.0f - ap.x) * cs.width; + } + break; + case RELATIVE_LOCATION_LEFT_OF_CENTER: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + cocos2d::Size rbs = relativeWidget->getSize(); + float locationRight = relativeWidget->getLeftInParent(); + finalPosX = locationRight - (1.0f - ap.x) * cs.width; + + finalPosY = relativeWidget->getBottomInParent() + rbs.height * 0.5f + ap.y * cs.height - cs.height * 0.5f; + } + break; + case RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationBottom = relativeWidget->getBottomInParent(); + float locationRight = relativeWidget->getLeftInParent(); + finalPosY = locationBottom + ap.y * cs.height; + finalPosX = locationRight - (1.0f - ap.x) * cs.width; + } + break; + case RELATIVE_LOCATION_RIGHT_OF_TOPALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationTop = relativeWidget->getTopInParent(); + float locationLeft = relativeWidget->getRightInParent(); + finalPosY = locationTop - (1.0f - ap.y) * cs.height; + finalPosX = locationLeft + ap.x * cs.width; + } + break; + case RELATIVE_LOCATION_RIGHT_OF_CENTER: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + cocos2d::Size rbs = relativeWidget->getSize(); + float locationLeft = relativeWidget->getRightInParent(); + finalPosX = locationLeft + ap.x * cs.width; + + finalPosY = relativeWidget->getBottomInParent() + rbs.height * 0.5f + ap.y * cs.height - cs.height * 0.5f; + } + break; + case RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationBottom = relativeWidget->getBottomInParent(); + float locationLeft = relativeWidget->getRightInParent(); + finalPosY = locationBottom + ap.y * cs.height; + finalPosX = locationLeft + ap.x * cs.width; + } + break; + case RELATIVE_LOCATION_BELOW_LEFTALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationTop = relativeWidget->getBottomInParent(); + float locationLeft = relativeWidget->getLeftInParent(); + finalPosY = locationTop - (1.0f - ap.y) * cs.height; + finalPosX = locationLeft + ap.x * cs.width; + } + break; + case RELATIVE_LOCATION_BELOW_CENTER: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + cocos2d::Size rbs = relativeWidget->getSize(); + float locationTop = relativeWidget->getBottomInParent(); + + finalPosY = locationTop - (1.0f - ap.y) * cs.height; + finalPosX = relativeWidget->getLeftInParent() + rbs.width * 0.5f + ap.x * cs.width - cs.width * 0.5f; + } + break; + case RELATIVE_LOCATION_BELOW_RIGHTALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationTop = relativeWidget->getBottomInParent(); + float locationRight = relativeWidget->getRightInParent(); + finalPosY = locationTop - (1.0f - ap.y) * cs.height; + finalPosX = locationRight - (1.0f - ap.x) * cs.width; + } + break; + default: + break; + } + UIMargin relativeWidgetMargin; + UIMargin mg = layoutParameter->getMargin(); + if (relativeWidget) + { + relativeWidgetMargin = relativeWidget->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)->getMargin(); + } + //handle margin + switch (align) + { + case RELATIVE_ALIGN_NONE: + case RELATIVE_ALIGN_PARENT_TOP_LEFT: + finalPosX += mg.left; + finalPosY -= mg.top; + break; + case RELATIVE_ALIGN_PARENT_TOP_CENTER_HORIZONTAL: + finalPosY -= mg.top; + break; + case RELATIVE_ALIGN_PARENT_TOP_RIGHT: + finalPosX -= mg.right; + finalPosY -= mg.top; + break; + case RELATIVE_ALIGN_PARENT_LEFT_CENTER_VERTICAL: + finalPosX += mg.left; + break; + case RELATIVE_CENTER_IN_PARENT: + break; + case RELATIVE_ALIGN_PARENT_RIGHT_CENTER_VERTICAL: + finalPosX -= mg.right; + break; + case RELATIVE_ALIGN_PARENT_LEFT_BOTTOM: + finalPosX += mg.left; + finalPosY += mg.bottom; + break; + case RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL: + finalPosY += mg.bottom; + break; + case RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM: + finalPosX -= mg.right; + finalPosY += mg.bottom; + break; + + case RELATIVE_LOCATION_ABOVE_LEFTALIGN: + case RELATIVE_LOCATION_ABOVE_CENTER: + case RELATIVE_LOCATION_ABOVE_RIGHTALIGN: + finalPosY += mg.bottom; + finalPosY += relativeWidgetMargin.top; + break; + case RELATIVE_LOCATION_LEFT_OF_TOPALIGN: + case RELATIVE_LOCATION_LEFT_OF_CENTER: + case RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN: + finalPosX -= mg.right; + finalPosX -= relativeWidgetMargin.left; + break; + case RELATIVE_LOCATION_RIGHT_OF_TOPALIGN: + case RELATIVE_LOCATION_RIGHT_OF_CENTER: + case RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN: + finalPosX += mg.left; + finalPosX += relativeWidgetMargin.right; + break; + case RELATIVE_LOCATION_BELOW_LEFTALIGN: + case RELATIVE_LOCATION_BELOW_CENTER: + case RELATIVE_LOCATION_BELOW_RIGHTALIGN: + finalPosY -= mg.top; + finalPosY -= relativeWidgetMargin.bottom; + break; + default: + break; + } + child->setPosition(cocos2d::Point(finalPosX, finalPosY)); + layoutParameter->_put = true; + unlayoutChildCount--; + } + } + } + break; + } + default: + break; + } +} + +const char* UILayout::getDescription() const +{ + return "Layout"; +} + +UIWidget* UILayout::createCloneInstance() +{ + return UILayout::create(); +} + +void UILayout::copyClonedWidgetChildren(UIWidget* model) +{ + UIWidget::copyClonedWidgetChildren(model); + doLayout(); +} + +void UILayout::copySpecialProperties(UIWidget *widget) +{ + UILayout* layout = dynamic_cast(widget); + if (layout) + { + setBackGroundImageScale9Enabled(layout->_backGroundScale9Enabled); + setBackGroundImage(layout->_backGroundImageFileName.c_str(),layout->_bgImageTexType); + setBackGroundImageCapInsets(layout->_backGroundImageCapInsets); + setBackGroundColorType(layout->_colorType); + setBackGroundColor(layout->_cColor); + setBackGroundColor(layout->_gStartColor, layout->_gEndColor); + setBackGroundColorOpacity(layout->_cOpacity); + setBackGroundColorVector(layout->_alongVector); + setLayoutType(layout->_layoutType); + setClippingEnabled(layout->_clippingEnabled); + } +} + +UIRectClippingNode::UIRectClippingNode(): +_innerStencil(NULL), +_enabled(true), +_clippingSize(cocos2d::Size(50.0f, 50.0f)), +_clippingEnabled(false) +{ + +} + +UIRectClippingNode::~UIRectClippingNode() +{ + +} + +UIRectClippingNode* UIRectClippingNode::create() +{ + UIRectClippingNode *pRet = new UIRectClippingNode(); + if (pRet && pRet->init()) + { + pRet->autorelease(); + } + else + { + CC_SAFE_DELETE(pRet); + } + + return pRet; +} + +bool UIRectClippingNode::init() +{ + _innerStencil = cocos2d::DrawNode::create(); + rect[0] = cocos2d::Point(0, 0); + rect[1] = cocos2d::Point(_clippingSize.width, 0); + rect[2] = cocos2d::Point(_clippingSize.width, _clippingSize.height); + rect[3] = cocos2d::Point(0, _clippingSize.height); + + cocos2d::Color4F green(0, 1, 0, 1); + _innerStencil->drawPolygon(rect, 4, green, 0, green); + if (cocos2d::ClippingNode::init(_innerStencil)) + { + return true; + } + return false; +} + + +void UIRectClippingNode::setClippingSize(const cocos2d::Size &size) +{ + setContentSize(size); + _clippingSize = size; + rect[0] = cocos2d::Point(0, 0); + rect[1] = cocos2d::Point(_clippingSize.width, 0); + rect[2] = cocos2d::Point(_clippingSize.width, _clippingSize.height); + rect[3] = cocos2d::Point(0, _clippingSize.height); + cocos2d::Color4F green(0, 1, 0, 1); + _innerStencil->clear(); + _innerStencil->drawPolygon(rect, 4, green, 0, green); +} + +void UIRectClippingNode::setClippingEnabled(bool enabled) +{ + _clippingEnabled = enabled; +} + +void UIRectClippingNode::visit() +{ + if (!_enabled) + { + return; + } + if (_clippingEnabled) + { + cocos2d::ClippingNode::visit(); + } + else + { + cocos2d::Node::visit(); + } +} + +void UIRectClippingNode::setEnabled(bool enabled) +{ + _enabled = enabled; +} + +bool UIRectClippingNode::isEnabled() const +{ + return _enabled; +} + +} \ No newline at end of file diff --git a/cocos/gui/Layout.h b/cocos/gui/UILayout.h similarity index 89% rename from cocos/gui/Layout.h rename to cocos/gui/UILayout.h index b58b0fbd2b..918bd868af 100644 --- a/cocos/gui/Layout.h +++ b/cocos/gui/UILayout.h @@ -44,23 +44,28 @@ typedef enum LAYOUT_RELATIVE }LayoutType; -class Layout : public UIWidget + +/** + * @js NA + * @lua NA + */ +class UILayout : public UIWidget { public: /** * Default constructor */ - Layout(); + UILayout(); /** * Default destructor */ - virtual ~Layout(); + virtual ~UILayout(); /** * Allocates and initializes a layout. */ - static Layout* create(); + static UILayout* create(); //override "hitTest" method of widget. virtual bool hitTest(const cocos2d::Point &pt); @@ -168,6 +173,11 @@ public: */ virtual const cocos2d::Size& getContentSize() const; + /** + * Returns the "class name" of widget. + */ + virtual const char* getDescription() const; + /** * Sets LayoutType. * @@ -187,11 +197,14 @@ public: virtual LayoutType getLayoutType() const; virtual void doLayout(); - + /** - * Returns the "class name" of widget. + * Adds a child to the container. + * + * @param child A child widget */ - virtual const char* getDescription() const; + virtual bool addChild(UIWidget* child); + protected: //override "init" method of widget. virtual bool init(); @@ -204,6 +217,11 @@ protected: //init background image renderer. void addBackGroundImage(); + + void supplyTheLayoutParameterLackToChild(UIWidget* child); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); + virtual void copyClonedWidgetChildren(UIWidget* model); protected: bool _clippingEnabled; @@ -224,23 +242,26 @@ protected: cocos2d::Size _backGroundImageTextureSize; LayoutType _layoutType; }; - -class RectClippingNode : public cocos2d::ClippingNode +/** + * @js NA + * @lua NA + */ +class UIRectClippingNode : public cocos2d::ClippingNode { public: - virtual ~RectClippingNode(); + virtual ~UIRectClippingNode(); virtual bool init(); - static RectClippingNode* create(); + static UIRectClippingNode* create(); void setClippingSize(const cocos2d::Size& size); void setClippingEnabled(bool enabled); virtual void visit(); void setEnabled(bool enabled); bool isEnabled() const; protected: - cocos2d::DrawNode* m_pInnerStencil; + cocos2d::DrawNode* _innerStencil; bool _enabled; private: - RectClippingNode(); + UIRectClippingNode(); cocos2d::Point rect[4]; cocos2d::Size _clippingSize; bool _clippingEnabled; diff --git a/cocos/gui/UILayoutDefine.cpp b/cocos/gui/UILayoutDefine.cpp index d79444fc75..b6b785a47d 100644 --- a/cocos/gui/UILayoutDefine.cpp +++ b/cocos/gui/UILayoutDefine.cpp @@ -21,7 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "gui/UILayoutDefine.h" +#include "UILayoutDefine.h" namespace gui { diff --git a/cocos/gui/UILayoutDefine.h b/cocos/gui/UILayoutDefine.h index 1d0bd716bf..70ab70251f 100644 --- a/cocos/gui/UILayoutDefine.h +++ b/cocos/gui/UILayoutDefine.h @@ -28,7 +28,10 @@ #include "cocos2d.h" namespace gui { - +/** +* @js NA +* @lua NA +*/ class UIMargin { public: @@ -46,6 +49,7 @@ public: bool equals(const UIMargin& target) const; }; +const UIMargin UIMarginZero = UIMargin(); typedef enum { @@ -61,22 +65,25 @@ typedef enum typedef enum { RELATIVE_ALIGN_NONE, - RELATIVE_ALIGN_PARENT_LEFT, - RELATIVE_ALIGN_PARENT_TOP, - RELATIVE_ALIGN_PARENT_RIGHT, - RELATIVE_ALIGN_PARENT_BOTTOM, + RELATIVE_ALIGN_PARENT_TOP_LEFT, + RELATIVE_ALIGN_PARENT_TOP_CENTER_HORIZONTAL, + RELATIVE_ALIGN_PARENT_TOP_RIGHT, + RELATIVE_ALIGN_PARENT_LEFT_CENTER_VERTICAL, RELATIVE_CENTER_IN_PARENT, - RELATIVE_CENTER_HORIZONTAL, - RELATIVE_CENTER_VERTICAL, + RELATIVE_ALIGN_PARENT_RIGHT_CENTER_VERTICAL, + RELATIVE_ALIGN_PARENT_LEFT_BOTTOM, + RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL, + RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM, + + RELATIVE_LOCATION_ABOVE_LEFTALIGN, + RELATIVE_LOCATION_ABOVE_CENTER, + RELATIVE_LOCATION_ABOVE_RIGHTALIGN, RELATIVE_LOCATION_LEFT_OF_TOPALIGN, RELATIVE_LOCATION_LEFT_OF_CENTER, RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN, RELATIVE_LOCATION_RIGHT_OF_TOPALIGN, RELATIVE_LOCATION_RIGHT_OF_CENTER, RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN, - RELATIVE_LOCATION_ABOVE_LEFTALIGN, - RELATIVE_LOCATION_ABOVE_CENTER, - RELATIVE_LOCATION_ABOVE_RIGHTALIGN, RELATIVE_LOCATION_BELOW_LEFTALIGN, RELATIVE_LOCATION_BELOW_CENTER, RELATIVE_LOCATION_BELOW_RIGHTALIGN diff --git a/cocos/gui/LayoutParameter.cpp b/cocos/gui/UILayoutParameter.cpp similarity index 65% rename from cocos/gui/LayoutParameter.cpp rename to cocos/gui/UILayoutParameter.cpp index 01caa33158..c468f69a24 100644 --- a/cocos/gui/LayoutParameter.cpp +++ b/cocos/gui/UILayoutParameter.cpp @@ -22,14 +22,15 @@ THE SOFTWARE. ****************************************************************************/ -#include "gui/LayoutParameter.h" -#include "gui/Layout.h" +#include "gui/UILayoutParameter.h" +#include "gui/UILayout.h" namespace gui { -LayoutParameter* LayoutParameter::create() + +UILayoutParameter* UILayoutParameter::create() { - LayoutParameter* parameter = new LayoutParameter(); + UILayoutParameter* parameter = new UILayoutParameter(); if (parameter) { parameter->autorelease(); @@ -39,24 +40,24 @@ LayoutParameter* LayoutParameter::create() return NULL; } -void LayoutParameter::setMargin(const UIMargin &margin) +void UILayoutParameter::setMargin(const UIMargin &margin) { _margin = margin; } -const UIMargin& LayoutParameter::getMargin() const +const UIMargin& UILayoutParameter::getMargin() const { return _margin; } -LayoutParameterType LayoutParameter::getLayoutType() const +LayoutParameterType UILayoutParameter::getLayoutType() const { return _layoutParameterType; } -LinearLayoutParameter* LinearLayoutParameter::create() +UILinearLayoutParameter* UILinearLayoutParameter::create() { - LinearLayoutParameter* parameter = new LinearLayoutParameter(); + UILinearLayoutParameter* parameter = new UILinearLayoutParameter(); if (parameter) { parameter->autorelease(); @@ -66,19 +67,19 @@ LinearLayoutParameter* LinearLayoutParameter::create() return NULL; } -void LinearLayoutParameter::setGravity(UILinearGravity gravity) +void UILinearLayoutParameter::setGravity(UILinearGravity gravity) { _linearGravity = gravity; } -UILinearGravity LinearLayoutParameter::getGravity() const +UILinearGravity UILinearLayoutParameter::getGravity() const { return _linearGravity; } -RelativeLayoutParameter* RelativeLayoutParameter::create() +UIRelativeLayoutParameter* UIRelativeLayoutParameter::create() { - RelativeLayoutParameter* parameter = new RelativeLayoutParameter(); + UIRelativeLayoutParameter* parameter = new UIRelativeLayoutParameter(); if (parameter) { parameter->autorelease(); @@ -88,32 +89,32 @@ RelativeLayoutParameter* RelativeLayoutParameter::create() return NULL; } -void RelativeLayoutParameter::setAlign(UIRelativeAlign align) +void UIRelativeLayoutParameter::setAlign(UIRelativeAlign align) { _relativeAlign = align; } -UIRelativeAlign RelativeLayoutParameter::getAlign() const +UIRelativeAlign UIRelativeLayoutParameter::getAlign() const { return _relativeAlign; } -void RelativeLayoutParameter::setRelativeToWidgetName(const char *name) +void UIRelativeLayoutParameter::setRelativeToWidgetName(const char *name) { _relativeWidgetName = name; } -const char* RelativeLayoutParameter::getRelativeToWidgetName() const +const char* UIRelativeLayoutParameter::getRelativeToWidgetName() const { return _relativeWidgetName.c_str(); } -void RelativeLayoutParameter::setRelativeName(const char* name) +void UIRelativeLayoutParameter::setRelativeName(const char* name) { _relativeLayoutName = name; } -const char* RelativeLayoutParameter::getRelativeName() const +const char* UIRelativeLayoutParameter::getRelativeName() const { return _relativeLayoutName.c_str(); } diff --git a/cocos/gui/LayoutParameter.h b/cocos/gui/UILayoutParameter.h similarity index 82% rename from cocos/gui/LayoutParameter.h rename to cocos/gui/UILayoutParameter.h index 3c457635d1..60a7e387ad 100644 --- a/cocos/gui/LayoutParameter.h +++ b/cocos/gui/UILayoutParameter.h @@ -35,25 +35,28 @@ typedef enum LAYOUT_PARAMETER_LINEAR, LAYOUT_PARAMETER_RELATIVE }LayoutParameterType; - -class LayoutParameter : public cocos2d::Object +/** +* @js NA +* @lua NA +*/ +class UILayoutParameter : public cocos2d::Object { public: /** * Default constructor */ - LayoutParameter() : _margin(UIMargin()){_layoutParameterType = LAYOUT_PARAMETER_NONE;}; + UILayoutParameter() : _margin(UIMargin()){_layoutParameterType = LAYOUT_PARAMETER_NONE;}; /** * Default destructor */ - virtual ~LayoutParameter(){}; + virtual ~UILayoutParameter(){}; /** * Allocates and initializes. * @return A initialized LayoutParameter which is marked as "autorelease". */ - static LayoutParameter* create(); + static UILayoutParameter* create(); /** * Sets Margin parameter for LayoutParameter. @@ -85,25 +88,28 @@ protected: UIMargin _margin; LayoutParameterType _layoutParameterType; }; - -class LinearLayoutParameter : public LayoutParameter +/** +* @js NA +* @lua NA +*/ +class UILinearLayoutParameter : public UILayoutParameter { public: /** * Default constructor */ - LinearLayoutParameter() : _linearGravity(LINEAR_GRAVITY_NONE){_layoutParameterType = LAYOUT_PARAMETER_LINEAR;}; + UILinearLayoutParameter() : _linearGravity(LINEAR_GRAVITY_NONE){_layoutParameterType = LAYOUT_PARAMETER_LINEAR;}; /** * Default destructor */ - virtual ~LinearLayoutParameter(){}; + virtual ~UILinearLayoutParameter(){}; /** * Allocates and initializes. * @return A initialized LayoutParameter which is marked as "autorelease". */ - static LinearLayoutParameter* create(); + static UILinearLayoutParameter* create(); /** * Sets UILinearGravity parameter for LayoutParameter. @@ -125,25 +131,31 @@ public: protected: UILinearGravity _linearGravity; }; +/** +* @js NA +* @lua NA +*/ -class RelativeLayoutParameter : public LayoutParameter +class UILayout; + +class UIRelativeLayoutParameter : public UILayoutParameter { public: /** * Default constructor */ - RelativeLayoutParameter() : _relativeAlign(RELATIVE_ALIGN_NONE),_relativeWidgetName(""),_relativeLayoutName(""){_layoutParameterType = LAYOUT_PARAMETER_RELATIVE;}; + UIRelativeLayoutParameter() : _relativeAlign(RELATIVE_ALIGN_NONE),_relativeWidgetName(""),_relativeLayoutName(""),_put(false){_layoutParameterType = LAYOUT_PARAMETER_RELATIVE;}; /** * Default destructor */ - virtual ~RelativeLayoutParameter(){}; + virtual ~UIRelativeLayoutParameter(){}; /** * Allocates and initializes. * @return A initialized LayoutParameter which is marked as "autorelease". */ - static RelativeLayoutParameter* create(); + static UIRelativeLayoutParameter* create(); /** * Sets UIRelativeAlign parameter for LayoutParameter. @@ -194,6 +206,8 @@ protected: UIRelativeAlign _relativeAlign; std::string _relativeWidgetName; std::string _relativeLayoutName; + bool _put; + friend class UILayout; }; } diff --git a/cocos/gui/UIListView.cpp b/cocos/gui/UIListView.cpp index 5ec6e71540..81baaad41d 100644 --- a/cocos/gui/UIListView.cpp +++ b/cocos/gui/UIListView.cpp @@ -23,55 +23,24 @@ ****************************************************************************/ #include "gui/UIListView.h" - - using namespace cocos2d; +#include "gui/UIHelper.h" +#include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" namespace gui { -UIListView::UIListView() -: _direction(LISTVIEW_DIR_VERTICAL) -, _moveDirection(LISTVIEW_MOVE_DIR_NONE) -, _touchStartLocation(0.0f) -, _touchEndLocation(0.0f) -, _touchMoveStartLocation(0.0f) -, _topBoundary(0.0f) -, _bottomBoundary(0.0f) -, _leftBoundary(0.0f) -, _rightBoundary(0.0f) -, _autoScroll(false) -, _autoScrollOriginalSpeed(0.0f) -, _autoScrollAcceleration(600.0f) -, _bePressed(false) -, _slidTime(0.0f) -, _childFocusCancelOffset(5.0f) -, _eventListener(NULL) -, _eventSelector(NULL) -, _childPool(NULL) -, _updatePool(NULL) -, _dataLength(0) -, _begin(0) -, _end(0) -, _updateChild(NULL) -, _updateDataIndex(-1) -, _updateSuccess(false) -, _overTopArray(NULL) -, _overBottomArray(NULL) -, _overLeftArray(NULL) -, _overRightArray(NULL) -, _disBoundaryToChild_0(0.0f) -, _disBetweenChild(0.0f) -, _scrollDegreeRange(45.0f) +UIListView::UIListView(): +_model(NULL), +_items(NULL), +_gravity(LISTVIEW_GRAVITY_CENTER_HORIZONTAL), +_itemsMargin(0.0f) { + } UIListView::~UIListView() { - CC_SAFE_RELEASE_NULL(_childPool); - CC_SAFE_RELEASE_NULL(_updatePool); - CC_SAFE_RELEASE_NULL(_overTopArray); - CC_SAFE_RELEASE_NULL(_overBottomArray); - CC_SAFE_RELEASE_NULL(_overLeftArray); - CC_SAFE_RELEASE_NULL(_overRightArray); + _items->removeAllObjects(); + CC_SAFE_RELEASE(_items); } UIListView* UIListView::create() @@ -88,1373 +57,365 @@ UIListView* UIListView::create() bool UIListView::init() { - if (Layout::init()) + if (UIScrollView::init()) { - setUpdateEnabled(true); - setTouchEnabled(true); - setClippingEnabled(true); - - _childPool = CCArray::create(); - _updatePool = CCArray::create(); - CC_SAFE_RETAIN(_childPool); - CC_SAFE_RETAIN(_updatePool); - _overTopArray = cocos2d::CCArray::create(); - _overBottomArray = cocos2d::CCArray::create(); - _overLeftArray = cocos2d::CCArray::create(); - _overRightArray = cocos2d::CCArray::create(); - CC_SAFE_RETAIN(_overTopArray); - CC_SAFE_RETAIN(_overBottomArray); - CC_SAFE_RETAIN(_overLeftArray); - CC_SAFE_RETAIN(_overRightArray); - + _items = cocos2d::Array::create(); + CC_SAFE_RETAIN(_items); + setLayoutType(LAYOUT_LINEAR_VERTICAL); return true; } return false; } +void UIListView::setItemModel(UIWidget *model) +{ + if (!model) + { + return; + } + CC_SAFE_RELEASE_NULL(_model); + _model = model; + CC_SAFE_RETAIN(_model); +} + +void UIListView::updateInnerContainerSize() +{ + if (!_model) + { + return; + } + switch (_direction) { + case SCROLLVIEW_DIR_VERTICAL: + { + int childrenCount = _items->count(); + float totalHeight = _model->getSize().height * childrenCount + (childrenCount - 1) * _itemsMargin; + float finalWidth = _size.width; + float finalHeight = totalHeight; + setInnerContainerSize(cocos2d::Size(finalWidth, finalHeight)); + break; + } + case SCROLLVIEW_DIR_HORIZONTAL: + { + int childrenCount = _items->count(); + float totalWidth = _model->getSize().width * childrenCount + (childrenCount - 1) * _itemsMargin; + float finalWidth = totalWidth; + float finalHeight = _size.height; + setInnerContainerSize(cocos2d::Size(finalWidth, finalHeight)); + break; + } + default: + break; + } +} + +void UIListView::remedyLayoutParameter(UIWidget *item) +{ + if (!item) + { + return; + } + switch (_direction) { + case SCROLLVIEW_DIR_VERTICAL: + { + UILinearLayoutParameter* llp = (UILinearLayoutParameter*)(item->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); + if (!llp) + { + UILinearLayoutParameter* defaultLp = UILinearLayoutParameter::create(); + switch (_gravity) { + case LISTVIEW_GRAVITY_LEFT: + defaultLp->setGravity(LINEAR_GRAVITY_LEFT); + break; + case LISTVIEW_GRAVITY_RIGHT: + defaultLp->setGravity(LINEAR_GRAVITY_RIGHT); + break; + case LISTVIEW_GRAVITY_CENTER_HORIZONTAL: + defaultLp->setGravity(LINEAR_GRAVITY_CENTER_HORIZONTAL); + break; + default: + break; + } + if (getIndex(item) == 0) + { + defaultLp->setMargin(UIMarginZero); + } + else + { + defaultLp->setMargin(UIMargin(0.0f, _itemsMargin, 0.0f, 0.0f)); + } + item->setLayoutParameter(defaultLp); + } + else + { + if (getIndex(item) == 0) + { + llp->setMargin(UIMarginZero); + } + else + { + llp->setMargin(UIMargin(0.0f, _itemsMargin, 0.0f, 0.0f)); + } + switch (_gravity) { + case LISTVIEW_GRAVITY_LEFT: + llp->setGravity(LINEAR_GRAVITY_LEFT); + break; + case LISTVIEW_GRAVITY_RIGHT: + llp->setGravity(LINEAR_GRAVITY_RIGHT); + break; + case LISTVIEW_GRAVITY_CENTER_HORIZONTAL: + llp->setGravity(LINEAR_GRAVITY_CENTER_HORIZONTAL); + break; + default: + break; + } + } + break; + } + case SCROLLVIEW_DIR_HORIZONTAL: + { + UILinearLayoutParameter* llp = (UILinearLayoutParameter*)(item->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); + if (!llp) + { + UILinearLayoutParameter* defaultLp = UILinearLayoutParameter::create(); + switch (_gravity) { + case LISTVIEW_GRAVITY_TOP: + defaultLp->setGravity(LINEAR_GRAVITY_TOP); + break; + case LISTVIEW_GRAVITY_BOTTOM: + defaultLp->setGravity(LINEAR_GRAVITY_BOTTOM); + break; + case LISTVIEW_GRAVITY_CENTER_VERTICAL: + defaultLp->setGravity(LINEAR_GRAVITY_CENTER_VERTICAL); + break; + default: + break; + } + if (getIndex(item) == 0) + { + defaultLp->setMargin(UIMarginZero); + } + else + { + defaultLp->setMargin(UIMargin(_itemsMargin, 0.0f, 0.0f, 0.0f)); + } + item->setLayoutParameter(defaultLp); + } + else + { + if (getIndex(item) == 0) + { + llp->setMargin(UIMarginZero); + } + else + { + llp->setMargin(UIMargin(_itemsMargin, 0.0f, 0.0f, 0.0f)); + } + switch (_gravity) { + case LISTVIEW_GRAVITY_TOP: + llp->setGravity(LINEAR_GRAVITY_TOP); + break; + case LISTVIEW_GRAVITY_BOTTOM: + llp->setGravity(LINEAR_GRAVITY_BOTTOM); + break; + case LISTVIEW_GRAVITY_CENTER_VERTICAL: + llp->setGravity(LINEAR_GRAVITY_CENTER_VERTICAL); + break; + default: + break; + } + } + break; + } + default: + break; + } + +} + +void UIListView::pushBackDefaultItem() +{ + if (!_model) + { + return; + } + UIWidget* newItem = _model->clone(); + _items->addObject(newItem); + remedyLayoutParameter(newItem); + addChild(newItem); +} + +void UIListView::insertDefaultItem(int index) +{ + if (!_items) + { + return; + } + if (!_model) + { + return; + } + UIWidget* newItem = _model->clone(); + _items->insertObject(newItem, index); + remedyLayoutParameter(newItem); + addChild(newItem); +} + +void UIListView::pushBackCustomItem(UIWidget* item) +{ + _items->addObject(item); + remedyLayoutParameter(item); + addChild(item); +} + +void UIListView::insertCustomItem(UIWidget* item, int index) +{ + _items->insertObject(item, index); + remedyLayoutParameter(item); + addChild(item); +} + +void UIListView::removeItem(int index) +{ + if (!_items) + { + return; + } + UIWidget* item = getItem(index); + if (!item) + { + return; + + } + _items->removeObject(item); + removeChild(item); +} + +void UIListView::removeLastItem() +{ + removeItem(_items->count() -1); +} + +UIWidget* UIListView::getItem(unsigned int index) +{ + if ((int)index < 0 || index >= _items->count()) + { + return NULL; + } + return (UIWidget*)(_items->data->arr[index]); +} + +cocos2d::Array* UIListView::getItems() +{ + return _items; +} + +unsigned int UIListView::getIndex(UIWidget *item) const +{ + if (!_items) + { + return -1; + } + if (!item) + { + return -1; + } + return _items->getIndexOfObject(item); +} + +void UIListView::setGravity(ListViewGravity gravity) +{ + if (_gravity == gravity) + { + return; + } + _gravity = gravity; + refreshView(); +} + +void UIListView::setItemsMargin(float margin) +{ + if (_itemsMargin == margin) + { + return; + } + _itemsMargin = margin; + refreshView(); +} + +void UIListView::setDirection(SCROLLVIEW_DIR dir) +{ + switch (dir) + { + case SCROLLVIEW_DIR_VERTICAL: + setLayoutType(LAYOUT_LINEAR_VERTICAL); + break; + case SCROLLVIEW_DIR_HORIZONTAL: + setLayoutType(LAYOUT_LINEAR_HORIZONTAL); + break; + case SCROLLVIEW_DIR_BOTH: + return; + default: + return; + break; + } + UIScrollView::setDirection(dir); + +} + +void UIListView::refreshView() +{ + if (!_items) + { + return; + } + cocos2d::ccArray* arrayItems = _items->data; + int length = arrayItems->num; + for (int i=0; iarr[i]); + item->setZOrder(i); + remedyLayoutParameter(item); + } + updateInnerContainerSize(); + doLayout(); +} + void UIListView::onSizeChanged() { - Layout::onSizeChanged(); - _topBoundary = _size.height; - _rightBoundary = _size.width; -} - -bool UIListView::addChild(UIWidget* widget) -{ - Layout::addChild(widget); - resetProperty(); - return true; -} - -void UIListView::removeAllChildren() -{ - _updatePool->removeAllObjects(); - _childPool->removeAllObjects(); - Layout::removeAllChildren(); -} - -bool UIListView::removeChild(UIWidget* child) -{ - bool value = false; - - if (Layout::removeChild(child)) - { - value = true; - resetProperty(); - } - - return value; -} - -bool UIListView::onTouchBegan(const Point &touchPoint) -{ - bool pass = Layout::onTouchBegan(touchPoint); - handlePressLogic(touchPoint); - return pass; -} - -void UIListView::onTouchMoved(const Point &touchPoint) -{ - Layout::onTouchMoved(touchPoint); - handleMoveLogic(touchPoint); -} - -void UIListView::onTouchEnded(const Point &touchPoint) -{ - Layout::onTouchEnded(touchPoint); - handleReleaseLogic(touchPoint); -} - -void UIListView::onTouchCancelled(const Point &touchPoint) -{ - Layout::onTouchCancelled(touchPoint); -} - -void UIListView::onTouchLongClicked(const Point &touchPoint) -{ - -} - -void UIListView::update(float dt) -{ - if (_autoScroll) - { - autoScrollChildren(dt); - } - recordSlidTime(dt); -} - -void UIListView::setDirection(ListViewDirection dir) -{ - _direction = dir; -} - -ListViewDirection UIListView::getDirection() -{ - return _direction; -} - -void UIListView::resetProperty() -{ - ccArray* arrayChildren = _children->data; - - if (arrayChildren->num <= 0) - { - return; - } - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - if (_topBoundary == 0) - { - return; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - if (_rightBoundary == 0) - { - return; - } - break; - - default: - break; - } - - float scroll_top = _topBoundary; - float scroll_left = _leftBoundary; - - switch (_children->count()) - { - case 1: - { - UIWidget* child_0 = dynamic_cast(arrayChildren->arr[0]); - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - { - float child_0_top = child_0->getTopInParent(); - _disBoundaryToChild_0 = scroll_top - child_0_top; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - { - float child_0_left = child_0->getLeftInParent(); - _disBoundaryToChild_0 = child_0_left - scroll_left; - } - break; - - default: - break; - } - } - break; - - default: - { - UIWidget* child_0 = dynamic_cast(arrayChildren->arr[0]); - UIWidget* child_1 = dynamic_cast(arrayChildren->arr[1]); - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - { - float child_0_top = child_0->getTopInParent(); - _disBoundaryToChild_0 = scroll_top - child_0_top; - _disBetweenChild = child_0->getPosition().y - child_1->getPosition().y; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - { - float child_0_left = child_0->getLeftInParent(); - _disBoundaryToChild_0 = child_0_left - scroll_left; - _disBetweenChild = child_1->getPosition().x - child_0->getPosition().x; - } - break; - - default: - break; - } - } - break; - } -} - -void UIListView::handlePressLogic(const Point &touchPoint) -{ - Point nsp = _renderer->convertToNodeSpace(touchPoint); - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - _touchMoveStartLocation = nsp.y; - _touchStartLocation = nsp.y; - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - _touchMoveStartLocation = nsp.x; - _touchStartLocation = nsp.x; - break; - - default: - break; - } - startRecordSlidAction(); - clearCollectOverArray(); -} - -void UIListView::handleMoveLogic(const Point &touchPoint) -{ - Point nsp = _renderer->convertToNodeSpace(touchPoint); - float offset = 0.0f; - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - { - float moveY = nsp.y; - offset = moveY - _touchMoveStartLocation; - _touchMoveStartLocation = moveY; - - if (offset < 0.0f) - { - _moveDirection = LISTVIEW_MOVE_DIR_DOWN; // down - } - else if (offset > 0.0f) - { - _moveDirection = LISTVIEW_MOVE_DIR_UP; // up - } - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - { - float moveX = nsp.x; - offset = moveX - _touchMoveStartLocation; - _touchMoveStartLocation = moveX; - - if (offset < 0) - { - _moveDirection = LISTVIEW_MOVE_DIR_LEFT; // left - } - else if (offset > 0) - { - _moveDirection = LISTVIEW_MOVE_DIR_RIGHT; // right - } - } - break; - - default: - break; - } - scrollChildren(offset); -} - -void UIListView::handleReleaseLogic(const Point &touchPoint) -{ - Point nsp = _renderer->convertToNodeSpace(touchPoint); - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - _touchEndLocation = nsp.y; - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - _touchEndLocation = nsp.x; - break; - - default: - break; - } - endRecordSlidAction(); -} - -void UIListView::interceptTouchEvent(int handleState, UIWidget *sender, const Point &touchPoint) -{ - switch (handleState) - { - case 0: - handlePressLogic(touchPoint); - break; - - case 1: - { - float offset = 0; - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - offset = fabs(sender->getTouchStartPos().y - touchPoint.y); - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - offset = fabs(sender->getTouchStartPos().x - touchPoint.x); - break; - - default: - break; - } - if (offset > _childFocusCancelOffset) - { - sender->setFocused(false); - handleMoveLogic(touchPoint); - } - } - break; - - case 2: - handleReleaseLogic(touchPoint); - break; - - case 3: - break; - } -} - -void UIListView::checkChildInfo(int handleState,UIWidget* sender,const Point &touchPoint) -{ - interceptTouchEvent(handleState, sender, touchPoint); -} - -void UIListView::moveChildren(float offset) -{ - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - { - ccArray* arrayChildren = _children->data; - int childrenCount = arrayChildren->num; - for (int i = 0; i < childrenCount; i++) - { - UIWidget* child = (UIWidget*)(arrayChildren->arr[i]); - _moveChildPoint.x = child->getPosition().x; - _moveChildPoint.y = child->getPosition().y + offset; - child->setPosition(_moveChildPoint); - } - break; - } - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - { - ccArray* arrayChildren = _children->data; - int childrenCount = arrayChildren->num; - for (int i=0;iarr[i]); - _moveChildPoint.x = child->getPosition().x + offset; - _moveChildPoint.y = child->getPosition().y; - child->setPosition(_moveChildPoint); - } - break; - } - - default: - break; - } -} - -bool UIListView::scrollChildren(float touchOffset) -{ - float realOffset = touchOffset; - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - { - realOffset = MIN(realOffset, _disBetweenChild); - - UIWidget* child_last = dynamic_cast(_childPool->getLastObject()); - float child_last_bottom = child_last->getBottomInParent(); - float scroll_bottom = _bottomBoundary; - - if (_end == _dataLength - 1) - { - if (realOffset > scroll_bottom + _disBoundaryToChild_0 - child_last_bottom) - { - realOffset = scroll_bottom + _disBoundaryToChild_0 - child_last_bottom; - } - moveChildren(realOffset); - return false; - } - moveChildren(realOffset); - - if (_end < _dataLength - 1) - { - collectOverTopChild(); - unsigned int count = _overTopArray->count(); - if (count > 0) - { - updateChild(); - setLoopPosition(); - _overTopArray->removeAllObjects(); - } - } - } - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - { - realOffset = MAX(realOffset, -_disBetweenChild); - - UIWidget* child_0 = dynamic_cast(_childPool->getObjectAtIndex(0)); - float child_0_top = child_0->getTopInParent(); - float scroll_top = _topBoundary; - - if (_begin == 0) - { - if (realOffset < scroll_top - _disBoundaryToChild_0 - child_0_top) - { - realOffset = scroll_top - _disBoundaryToChild_0 - child_0_top; - } - moveChildren(realOffset); - return false; - } - moveChildren(realOffset); - - if (_begin > 0) - { - collectOverBottomChild(); - int count = _overBottomArray->count(); - if (count > 0) - { - updateChild(); - setLoopPosition(); - _overBottomArray->removeAllObjects(); - } - } - } - break; - - default: - break; - } - return true; - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - { - realOffset = MAX(realOffset, -_disBetweenChild); - - UIWidget* child_last = dynamic_cast(_childPool->getLastObject()); - float child_last_right = child_last->getRightInParent(); - float scroll_right = _rightBoundary; - - if (_end == _dataLength - 1) - { - if (realOffset < scroll_right - _disBoundaryToChild_0 - child_last_right) - { - realOffset = scroll_right - _disBoundaryToChild_0 - child_last_right; - } - moveChildren(realOffset); - return false; - } - moveChildren(realOffset); - - if (_end < _dataLength - 1) - { - collectOverLeftChild(); - int count = _overLeftArray->count(); - if (count > 0) - { - updateChild(); - setLoopPosition(); - _overLeftArray->removeAllObjects(); - } - } - } - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - { - realOffset = MIN(realOffset, _disBetweenChild); - - UIWidget* child_0 = dynamic_cast(_childPool->getObjectAtIndex(0)); - float child_0_left = child_0->getLeftInParent(); - float scroll_left = _leftBoundary; - - if (_begin == 0) - { - if (realOffset > scroll_left + _disBoundaryToChild_0 - child_0_left) - { - realOffset = scroll_left + _disBoundaryToChild_0 - child_0_left; - } - moveChildren(realOffset); - return false; - } - moveChildren(realOffset); - - collectOverRightChild(); - int count = _overRightArray->count(); - if (count > 0) - { - updateChild(); - setLoopPosition(); - _overRightArray->removeAllObjects(); - } - } - break; - - default: - break; - } - return true; - break; - - default: - break; - } - - return false; -} - -void UIListView::autoScrollChildren(float dt) -{ - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(curDis)) - { - stopAutoScrollChildren(); - } - } - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(-curDis)) - { - stopAutoScrollChildren(); - } - } - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(-curDis)) - { - stopAutoScrollChildren(); - } - } - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(curDis)) - { - stopAutoScrollChildren(); - } - } - break; - - default: - break; - } - break; - - default: - break; - } -} - -float UIListView::getCurAutoScrollDistance(float time) -{ - float dt = time; - _autoScrollOriginalSpeed -= _autoScrollAcceleration*dt; - return _autoScrollOriginalSpeed*dt; -} - -void UIListView::startAutoScrollChildren(float v) -{ - _autoScrollOriginalSpeed = v; - _autoScroll = true; -} - -void UIListView::stopAutoScrollChildren() -{ - _autoScroll = false; - _autoScrollOriginalSpeed = 0.0f; -} - -void UIListView::recordSlidTime(float dt) -{ - if (_bePressed) - { - _slidTime += dt; - } -} - -void UIListView::startRecordSlidAction() -{ - if (_children->count() <= 0) - { - return; - } - if (_autoScroll) - { - stopAutoScrollChildren(); - } - _bePressed = true; - _slidTime = 0.0; -} - -void UIListView::endRecordSlidAction() -{ - if (_children->count() <= 0) - { - return; - } - if (_slidTime <= 0.016f) - { - return; - } - float totalDis = 0; - totalDis = _touchEndLocation-_touchStartLocation; - float orSpeed = fabs(totalDis)/(_slidTime); - startAutoScrollChildren(orSpeed / 4); - - _bePressed = false; - _slidTime = 0.0; -} - -UIWidget* UIListView::getCheckPositionChild() -{ - UIWidget* child = NULL; - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - child = dynamic_cast(_childPool->getLastObject()); - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - child = dynamic_cast(_childPool->getObjectAtIndex(0)); - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - child = dynamic_cast(_childPool->getLastObject()); - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - child = dynamic_cast(_childPool->getObjectAtIndex(0)); - break; - - default: - break; - } - break; - - default: - break; - } - - return child; -} - -void UIListView::initChildWithDataLength(int length) -{ - _dataLength = length; - _begin = 0; - _end = 0; - - // init child pool - ccArray* arrayChildren = _children->data; - int times = arrayChildren->num; - for (int i = 0; i < times; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - setUpdateChild(child); - setUpdateDataIndex(i); - initChildEvent(); - _childPool->addObject(child); - _end = i; - } -} - -UIWidget* UIListView::getChildFromUpdatePool() -{ - UIWidget* child = dynamic_cast(_updatePool->getLastObject()); - _updatePool->removeLastObject(); - return child; -} - -void UIListView::pushChildToPool() -{ - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - { - UIWidget* child = dynamic_cast(_childPool->getObjectAtIndex(0)); - _updatePool->insertObject(child, 0); - _childPool->removeObjectAtIndex(0); - } - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - { - UIWidget* child = dynamic_cast(_childPool->getLastObject()); - _updatePool->insertObject(child, 0); - _childPool->removeLastObject(); - - } - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - { - UIWidget* child = dynamic_cast(_childPool->getObjectAtIndex(0)); - _updatePool->insertObject(child, 0); - _childPool->removeObjectAtIndex(0); - } - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - { - UIWidget* child = dynamic_cast(_childPool->getLastObject()); - _updatePool->insertObject(child, 0); - _childPool->removeLastObject(); - } - break; - - default: - break; - } - break; - - default: - break; - } -} - -void UIListView::getAndCallback() -{ - UIWidget* child = getChildFromUpdatePool(); - - if (child == NULL) - { - return; - } - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - ++_end; - setUpdateChild(child); - setUpdateDataIndex(_end); - updateChildEvent(); - - if (_updateSuccess == false) - { - --_end; - _childPool->insertObject(child, 0); - return; - } - ++_begin; - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - --_begin; - setUpdateChild(child); - setUpdateDataIndex(_begin); - updateChildEvent(); - - if (_updateSuccess == false) - { - ++_begin; - _childPool->addObject(child); - return; - } - --_end; - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - ++_end; - setUpdateChild(child); - setUpdateDataIndex(_end); - updateChildEvent(); - - if (_updateSuccess == false) - { - --_end; - _childPool->insertObject(child, 0); - return; - } - ++_begin; - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - --_begin; - setUpdateChild(child); - setUpdateDataIndex(_begin); - updateChildEvent(); - - if (_updateSuccess == false) - { - ++_begin; - _childPool->addObject(child); - return; - } - --_end; - break; - - default: - break; - } - break; - - default: - break; - } - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - _childPool->addObject(child); - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - _childPool->insertObject(child, 0); - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - _childPool->addObject(child); - break; - case LISTVIEW_MOVE_DIR_RIGHT: // right - _childPool->insertObject(child, 0); - break; - - default: - break; - } - break; - - default: - break; - } -} - -int UIListView::getDataLength() -{ - return _dataLength; -} - -UIWidget* UIListView::getUpdateChild() -{ - return _updateChild; -} - -void UIListView::setUpdateChild(UIWidget* child) -{ - _updateChild = child; -} - -int UIListView::getUpdateDataIndex() -{ - return _updateDataIndex; -} - -void UIListView::setUpdateDataIndex(int index) -{ - _updateDataIndex = index; -} - -bool UIListView::getUpdateSuccess() -{ - return _updateSuccess; -} - -void UIListView::setUpdateSuccess(bool sucess) -{ - _updateSuccess = sucess; -} - -void UIListView::clearCollectOverArray() -{ - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: - _overTopArray->removeAllObjects(); - _overBottomArray->removeAllObjects(); - break; - - case LISTVIEW_DIR_HORIZONTAL: - _overLeftArray->removeAllObjects(); - _overRightArray->removeAllObjects(); - break; - - default: - break; - } -} - -void UIListView::collectOverTopChild() -{ - float scroll_top = _topBoundary; - - ccArray* arrayChildren = _children->data; - int times = arrayChildren->num; - for (int i = 0; i < times; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_bottom = child->getBottomInParent(); - - if (child_bottom >= scroll_top) - { - _overTopArray->addObject(child); - } - } -} - -void UIListView::collectOverBottomChild() -{ - float scroll_bottom = _bottomBoundary; - - ccArray* arrayChildren = _children->data; - int times = arrayChildren->num; - for (int i = 0; i < times; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_top = child->getTopInParent(); - - if (child_top <= scroll_bottom) - { - _overBottomArray->addObject(child); - } - } -} - -void UIListView::collectOverLeftChild() -{ - float scroll_left = _leftBoundary; - - ccArray* arrayChildren = _children->data; - int times = arrayChildren->num; - for (int i = 0; i < times; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_right = child->getRightInParent(); - - if (child_right <= scroll_left) - { - _overLeftArray->addObject(child); - } - } -} - -void UIListView::collectOverRightChild() -{ - float scroll_right = _rightBoundary; - - ccArray* arrayChildren = _children->data; - int times = arrayChildren->num; - for (int i = 0; i < times; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_left = child->getLeftInParent(); - if (child_left >= scroll_right) - { - _overRightArray->addObject(child); - } - } -} - -void UIListView::setLoopPosition() -{ - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - { - ccArray* arrayChildren = _children->data; - unsigned int childrenCount = arrayChildren->num; - - if (_overTopArray->count() == childrenCount) - { - unsigned int count = childrenCount; - for (unsigned int i = 0; i < count; ++i) - { - UIWidget* child = dynamic_cast(_overTopArray->getObjectAtIndex(i)); - - if (i == 0) - { - float height = child->getSize().height; - float offset = (child->getWidgetType() == WidgetTypeWidget) ? height / 2 : height; - float y = _topBoundary - _disBoundaryToChild_0 - offset; - child->setPosition(Point(child->getPosition().x, y)); - } - else - { - UIWidget* prev_child = dynamic_cast(_overTopArray->getObjectAtIndex(i - 1)); - child->setPosition(Point(child->getPosition().x, prev_child->getPosition().y - _disBetweenChild)); - } - } - } - else - { - float scroll_top = _topBoundary; - - ccArray* arrayChildren = _children->data; - int count = arrayChildren->num; - for (int i = 0; i < count; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_bottom = child->getBottomInParent(); - - if (child_bottom >= scroll_top) - { - int index = (i == 0) ? (count - 1) : (i - 1); - UIWidget* prev_child = dynamic_cast(arrayChildren->arr[index]); - child->setPosition(Point(child->getPosition().x, prev_child->getPosition().y - _disBetweenChild)); - } - } - } - } - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - { - ccArray* arrayChildren = _children->data; - unsigned int childrenCount = arrayChildren->num; - - if (_overBottomArray->count() == childrenCount) - { - unsigned int count = childrenCount; - for (unsigned int i = 0; i < count; ++i) - { - UIWidget* child = dynamic_cast(_overBottomArray->getObjectAtIndex(i)); - - if (i == 0) - { - float y = _bottomBoundary + _disBoundaryToChild_0 - _disBetweenChild; - child->setPosition(Point(child->getPosition().x, y)); - } - else - { - UIWidget* prev_child = dynamic_cast(_overBottomArray->getObjectAtIndex(i - 1)); - child->setPosition(Point(child->getPosition().x, prev_child->getPosition().y + _disBetweenChild)); - } - } - } - else - { - float scroll_bottom = _bottomBoundary; - - ccArray* arrayChildren = _children->data; - int count = arrayChildren->num; - for (int i = count - 1; i >= 0; --i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_top = child->getTopInParent(); - - if (child_top <= scroll_bottom) - { - int index = (i == count - 1) ? 0 : (i + 1); - UIWidget* next_child = dynamic_cast(arrayChildren->arr[index]); - child->setPosition(Point(child->getPosition().x, next_child->getPosition().y + _disBetweenChild)); - } - } - } - } - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - { - ccArray* arrayChildren = _children->data; - unsigned int childrenCount = arrayChildren->num; - - if (_overLeftArray->count() == childrenCount) - { - unsigned int count = childrenCount; - for (unsigned int i = 0; i < count; ++i) - { - UIWidget* child = dynamic_cast(_overLeftArray->getObjectAtIndex(i)); - - if (i == 0) - { - float width = child->getSize().width; - float offset = (child->getWidgetType() == WidgetTypeWidget) ? (width / 2) : 0; - float x = _leftBoundary + _disBoundaryToChild_0 + width + offset; - child->setPosition(Point(x, child->getPosition().y)); - } - else - { - UIWidget* prev_child = dynamic_cast(_overLeftArray->getObjectAtIndex(i - 1)); - child->setPosition(Point(prev_child->getPosition().x + _disBetweenChild, child->getPosition().y)); - } - } - } - else - { - float scroll_left = _leftBoundary; - - ccArray* arrayChildren = _children->data; - int count = arrayChildren->num; - for (int i = 0; i < count; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_right = child->getRightInParent(); - - if (child_right <= scroll_left) - { - int index = (i == 0) ? (count - 1) : (i - 1); - UIWidget* prev_child = dynamic_cast(arrayChildren->arr[index]); - child->setPosition(Point(prev_child->getPosition().x + _disBetweenChild, child->getPosition().y)); - } - } - } - } - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - { - ccArray* arrayChildren = _children->data; - unsigned int childrenCount = arrayChildren->num; - - if (_overRightArray->count() == childrenCount) - { - unsigned int count = childrenCount; - for (unsigned int i = 0; i < count; ++i) - { - UIWidget* child = dynamic_cast(_overRightArray->getObjectAtIndex(i)); - - if (i == 0) - { - float x = _rightBoundary - _disBoundaryToChild_0 + _disBetweenChild; - child->setPosition(Point(x, child->getPosition().y)); - } - else - { - UIWidget* prev_child = dynamic_cast(_overRightArray->getObjectAtIndex(i - 1)); - child->setPosition(Point(prev_child->getPosition().x - _disBetweenChild, child->getPosition().y)); - } - } - } - else - { - float scroll_right = _rightBoundary; - - ccArray* arrayChildren = _children->data; - int count = arrayChildren->num; - for (int i = count - 1; i >= 0; --i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_left = child->getLeftInParent(); - - if (child_left >= scroll_right) - { - int index = (i == count - 1) ? 0 : (i + 1); - UIWidget* next_child = dynamic_cast(arrayChildren->arr[index]); - child->setPosition(Point(next_child->getPosition().x - _disBetweenChild, child->getPosition().y)); - } - } - } - } - break; - - default: - break; - } - break; - - default: - break; - } -} - -void UIListView::updateChild() -{ - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - { - int count = _overTopArray->count(); - for (int i = 0; i < count; ++i) - { - pushChildToPool(); - getAndCallback(); - } - } - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - { - int count = _overBottomArray->count(); - for (int i = 0; i < count; ++i) - { - pushChildToPool(); - getAndCallback(); - } - } - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - { - int count = _overLeftArray->count(); - for (int i = 0; i < count; ++i) - { - pushChildToPool(); - getAndCallback(); - } - } - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - { - int count = _overRightArray->count(); - for (int i = 0; i < count; ++i) - { - pushChildToPool(); - getAndCallback(); - } - } - break; - - default: - break; - } - break; - - default: - break; - } -} - -void UIListView::initChildEvent() -{ - if (_eventListener && _eventSelector) - { - (_eventListener->*_eventSelector)(this, LISTVIEW_EVENT_INIT_CHILD); - } -} - -void UIListView::updateChildEvent() -{ - if (_eventListener && _eventSelector) - { - (_eventListener->*_eventSelector)(this, LISTVIEW_EVENT_UPDATE_CHILD); - } -} - -void UIListView::addEventListenter(Object *target, SEL_ListViewEvent selector) -{ - _eventListener = target; - _eventSelector = selector; + UIScrollView::onSizeChanged(); + refreshView(); } const char* UIListView::getDescription() const { - return "ListView"; + return "ListViewEx"; } +UIWidget* UIListView::createCloneInstance() +{ + return UIListView::create(); +} -} \ No newline at end of file +void UIListView::copyClonedWidgetChildren(UIWidget* model) +{ + cocos2d::ccArray* arrayItems = dynamic_cast(model)->getItems()->data; + int length = arrayItems->num; + for (int i=0; iarr[i]); + pushBackCustomItem(item->clone()); + } +} + +void UIListView::copySpecialProperties(UIWidget *widget) +{ + UIListView* listViewEx = dynamic_cast(widget); + if (listViewEx) + { + UIScrollView::copySpecialProperties(widget); + setItemModel(listViewEx->_model); + setItemsMargin(listViewEx->_itemsMargin); + setGravity(listViewEx->_gravity); + } +} + +} diff --git a/cocos/gui/UIListView.h b/cocos/gui/UIListView.h index 8830db6209..c78d06ace2 100644 --- a/cocos/gui/UIListView.h +++ b/cocos/gui/UIListView.h @@ -22,226 +22,156 @@ THE SOFTWARE. ****************************************************************************/ + #ifndef __UILISTVIEW_H__ #define __UILISTVIEW_H__ -/* gui mark */ -#include "gui/Layout.h" -/**/ +#include "gui/UIScrollView.h" -namespace gui { - -/** - * list view direction - */ -typedef enum LISTVIEW_DIR -{ - LISTVIEW_DIR_NONE, - LISTVIEW_DIR_VERTICAL, - LISTVIEW_DIR_HORIZONTAL -}ListViewDirection; - -/** - * list view scroll direction - */ -typedef enum LISTVIEW_MOVE_DIR -{ - LISTVIEW_MOVE_DIR_NONE, - LISTVIEW_MOVE_DIR_UP, - LISTVIEW_MOVE_DIR_DOWN, - LISTVIEW_MOVE_DIR_LEFT, - LISTVIEW_MOVE_DIR_RIGHT, -}ListViewMoveDirection; +namespace gui{ typedef enum { - LISTVIEW_EVENT_INIT_CHILD, - LISTVIEW_EVENT_UPDATE_CHILD, -}ListViewEventType; + LISTVIEW_GRAVITY_LEFT, + LISTVIEW_GRAVITY_RIGHT, + LISTVIEW_GRAVITY_CENTER_HORIZONTAL, + + LISTVIEW_GRAVITY_TOP, + LISTVIEW_GRAVITY_BOTTOM, + LISTVIEW_GRAVITY_CENTER_VERTICAL, +}ListViewGravity; -/** - * list view event - */ -typedef void (cocos2d::Object::*SEL_ListViewEvent)(cocos2d::Object*, ListViewEventType); -#define listvieweventselector(_SELECTOR)(SEL_ListViewEvent)(&_SELECTOR) - -class UIListView : public Layout +class UIListView : public UIScrollView { + public: + + /** + * Default constructor + */ UIListView(); + + /** + * Default destructor + */ virtual ~UIListView(); + + /** + * Allocates and initializes. + */ static UIListView* create(); /** - * add widget child override + * Sets a item model for listview + * + * A model will be cloned for adding default item. + * + * @param model item model for listview */ - virtual bool addChild(UIWidget* widget); - /** - * remove all widget children override - */ - virtual void removeAllChildren(); - /** - * remove widget child override - */ - virtual bool removeChild(UIWidget* child); - - virtual bool onTouchBegan(const cocos2d::Point &touchPoint); - virtual void onTouchMoved(const cocos2d::Point &touchPoint); - virtual void onTouchEnded(const cocos2d::Point &touchPoint); - virtual void onTouchCancelled(const cocos2d::Point &touchPoint); - virtual void onTouchLongClicked(const cocos2d::Point &touchPoint); + void setItemModel(UIWidget* model); /** - * set and get direction + * Push back a default item(create by a cloned model) into listview. */ - void setDirection(ListViewDirection dir); - ListViewDirection getDirection(); + void pushBackDefaultItem(); /** - * initialze data length - * and create children with parameter length + * Insert a default item(create by a cloned model) into listview. */ - void initChildWithDataLength(int length); - /** - * get data length - */ - int getDataLength(); + void insertDefaultItem(int index); /** - * update child function whetn trigger update child event + * Push back custom item into listview. */ - /** - * get update widget child - */ - UIWidget* getUpdateChild(); - /** - * get update data index - */ - int getUpdateDataIndex(); - /** - * get and set update success or not - */ - bool getUpdateSuccess(); - void setUpdateSuccess(bool sucess); + void pushBackCustomItem(UIWidget* item); /** - * add event call-back function + * Insert custom item into listview. */ - /** - * add event - */ - void addEventListenter(cocos2d::Object* target, SEL_ListViewEvent selector); - - /* gui mark */ - /** - * get and set degree range for checking move or not with scrolling - */ - /**/ - virtual void update(float dt); - - virtual void doLayout(){}; + void insertCustomItem(UIWidget* item, int index); /** - * Returns the "class name" of widget. + * Removes the last item of listview. */ + void removeLastItem(); + + /** + * Removes a item whose index is same as the parameter. + * + * @param index of item. + */ + void removeItem(int index); + + /** + * Returns a item whose index is same as the parameter. + * + * @param index of item. + * + * @return the item widget. + */ + UIWidget* getItem(unsigned int index); + + /** + * Returns the item container. + */ + cocos2d::Array* getItems(); + + /** + * Returns the index of item. + * + * @param item the item which need to be checked. + * + * @return the index of item. + */ + unsigned int getIndex(UIWidget* item) const; + + /** + * Changes the gravity of listview. + * @see ListViewGravity + */ + void setGravity(ListViewGravity gravity); + + /** + * Changes the margin between each item. + * + * @param margin + */ + void setItemsMargin(float margin); + + /** + * Refresh the view of list. + * + * If you change the data, you need to call this mathod. + */ + void refreshView(); + + /** + * Changes scroll direction of scrollview. + * + * @see SCROLLVIEW_DIR SCROLLVIEW_DIR_VERTICAL means vertical scroll, SCROLLVIEW_DIR_HORIZONTAL means horizontal scroll + * + * @param SCROLLVIEW_DIR + */ + virtual void setDirection(SCROLLVIEW_DIR dir); + virtual const char* getDescription() const; + protected: virtual bool init(); - + void updateInnerContainerSize(); + void remedyLayoutParameter(UIWidget* item); virtual void onSizeChanged(); - - void setMoveDirection(ListViewMoveDirection dir); - ListViewMoveDirection getMoveDirection(); - - virtual void resetProperty(); - - virtual void handlePressLogic(const cocos2d::Point &touchPoint); - virtual void handleMoveLogic(const cocos2d::Point &touchPoint); - virtual void handleReleaseLogic(const cocos2d::Point &touchPoint); - virtual void interceptTouchEvent(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint); - /* gui mark */ -// virtual bool isInScrollDegreeRange(UIWidget* widget); - /**/ - virtual void checkChildInfo(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint); - - void moveChildren(float offset); - virtual bool scrollChildren(float touchOffset); - void autoScrollChildren(float dt); - float getCurAutoScrollDistance(float time); - void startAutoScrollChildren(float v); - void stopAutoScrollChildren(); - void recordSlidTime(float dt); - void startRecordSlidAction(); - virtual void endRecordSlidAction(); - - UIWidget* getCheckPositionChild(); - UIWidget* getChildFromUpdatePool(); - void pushChildToPool(); - void getAndCallback(); - - void setUpdateChild(UIWidget* child); - void setUpdateDataIndex(int index); - void clearCollectOverArray(); - void collectOverTopChild(); - void collectOverBottomChild(); - void collectOverLeftChild(); - void collectOverRightChild(); - void setLoopPosition(); - void updateChild(); - - void initChildEvent(); - void updateChildEvent(); - - virtual void setClippingEnabled(bool able){Layout::setClippingEnabled(able);}; + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); + virtual void copyClonedWidgetChildren(UIWidget* model); protected: - ListViewDirection _direction; - ListViewMoveDirection _moveDirection; - float _touchStartLocation; - float _touchEndLocation; - float _touchMoveStartLocation; - float _topBoundary;//test - float _bottomBoundary;//test - float _leftBoundary; - float _rightBoundary; - - bool _autoScroll; - - float _autoScrollOriginalSpeed; - float _autoScrollAcceleration; - - bool _bePressed; - float _slidTime; - cocos2d::Point _moveChildPoint; - float _childFocusCancelOffset; - - cocos2d::Object* _eventListener; - SEL_ListViewEvent _eventSelector; - - cocos2d::Array* _childPool; - cocos2d::Array* _updatePool; - - int _dataLength; - int _begin; - int _end; - UIWidget* _updateChild; - int _updateDataIndex; - bool _updateSuccess; - - cocos2d::Array* _overTopArray; - cocos2d::Array* _overBottomArray; - cocos2d::Array* _overLeftArray; - cocos2d::Array* _overRightArray; - - float _disBoundaryToChild_0; - float _disBetweenChild; - - /* gui mark */ - float _scrollDegreeRange; - /**/ + UIWidget* _model; + cocos2d::Array* _items; + ListViewGravity _gravity; + float _itemsMargin; }; } - -#endif /* defined(__Test__UIListView__) */ +#endif /* defined(__UIListView__) */ diff --git a/cocos/gui/UILoadingBar.cpp b/cocos/gui/UILoadingBar.cpp index 6d74be86c4..09b78c7b25 100644 --- a/cocos/gui/UILoadingBar.cpp +++ b/cocos/gui/UILoadingBar.cpp @@ -25,11 +25,9 @@ #include "gui/UILoadingBar.h" #include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" - using namespace cocos2d; - using namespace cocos2d::extension; - namespace gui { + #define DYNAMIC_CAST_CCSPRITE dynamic_cast(_barRenderer) UILoadingBar::UILoadingBar(): @@ -38,10 +36,10 @@ _percent(100), _totalLength(0), _barRenderer(NULL), _renderBarTexType(UI_TEX_TYPE_LOCAL), -_barRendererTextureSize(Size::ZERO), +_barRendererTextureSize(cocos2d::Size::ZERO), _scale9Enabled(false), _prevIgnoreSize(true), -_capInsets(Rect::ZERO), +_capInsets(cocos2d::Rect::ZERO), _textureFile("") { } @@ -66,9 +64,9 @@ UILoadingBar* UILoadingBar::create() void UILoadingBar::initRenderer() { UIWidget::initRenderer(); - _barRenderer = CCSprite::create(); + _barRenderer = cocos2d::Sprite::create(); _renderer->addChild(_barRenderer); - _barRenderer->setAnchorPoint(Point(0.0f,0.5f)); + _barRenderer->setAnchorPoint(cocos2d::Point(0.0,0.5)); } void UILoadingBar::setDirection(LoadingBarType dir) @@ -82,19 +80,19 @@ void UILoadingBar::setDirection(LoadingBarType dir) switch (_barType) { case LoadingBarTypeLeft: - _barRenderer->setAnchorPoint(Point(0.0f,0.5f)); - _barRenderer->setPosition(Point(-_totalLength*0.5f,0.0f)); + _barRenderer->setAnchorPoint(cocos2d::Point(0.0f,0.5f)); + _barRenderer->setPosition(cocos2d::Point(-_totalLength*0.5f,0.0f)); if (!_scale9Enabled) { - dynamic_cast(_barRenderer)->setFlippedX(false); + dynamic_cast(_barRenderer)->setFlippedX(false); } break; case LoadingBarTypeRight: - _barRenderer->setAnchorPoint(Point(1.0f,0.5f)); - _barRenderer->setPosition(Point(_totalLength*0.5f,0.0f)); + _barRenderer->setAnchorPoint(cocos2d::Point(1.0f,0.5f)); + _barRenderer->setPosition(cocos2d::Point(_totalLength*0.5f,0.0f)); if (!_scale9Enabled) { - dynamic_cast(_barRenderer)->setFlippedX(true); + dynamic_cast(_barRenderer)->setFlippedX(true); } break; } @@ -118,21 +116,23 @@ void UILoadingBar::loadTexture(const char* texture,TextureResType texType) case UI_TEX_TYPE_LOCAL: if (_scale9Enabled) { - dynamic_cast(_barRenderer)->initWithFile(texture); + dynamic_cast(_barRenderer)->initWithFile(texture); + dynamic_cast(_barRenderer)->setCapInsets(_capInsets); } else { - dynamic_cast(_barRenderer)->initWithFile(texture); + dynamic_cast(_barRenderer)->initWithFile(texture); } break; case UI_TEX_TYPE_PLIST: if (_scale9Enabled) { - dynamic_cast(_barRenderer)->initWithSpriteFrameName(texture); + dynamic_cast(_barRenderer)->initWithSpriteFrameName(texture); + dynamic_cast(_barRenderer)->setCapInsets(_capInsets); } else { - dynamic_cast(_barRenderer)->initWithSpriteFrameName(texture); + dynamic_cast(_barRenderer)->initWithSpriteFrameName(texture); } break; default: @@ -140,31 +140,31 @@ void UILoadingBar::loadTexture(const char* texture,TextureResType texType) } if (_scale9Enabled) { - dynamic_cast(_barRenderer)->setColor(getColor()); - dynamic_cast(_barRenderer)->setOpacity(getOpacity()); + dynamic_cast(_barRenderer)->setColor(getColor()); + dynamic_cast(_barRenderer)->setOpacity(getOpacity()); + } else { - dynamic_cast(_barRenderer)->setColor(getColor()); - dynamic_cast(_barRenderer)->setOpacity(getOpacity()); + dynamic_cast(_barRenderer)->setColor(getColor()); + dynamic_cast(_barRenderer)->setOpacity(getOpacity()); } - _barRendererTextureSize.width = _barRenderer->getContentSize().width; - _barRendererTextureSize.height = _barRenderer->getContentSize().height; + _barRendererTextureSize = _barRenderer->getContentSize(); switch (_barType) { case LoadingBarTypeLeft: - _barRenderer->setAnchorPoint(Point(0.0f,0.5f)); + _barRenderer->setAnchorPoint(cocos2d::Point(0.0f,0.5f)); if (!_scale9Enabled) { - dynamic_cast(_barRenderer)->setFlippedX(false); + dynamic_cast(_barRenderer)->setFlippedX(false); } break; case LoadingBarTypeRight: - _barRenderer->setAnchorPoint(Point(1.0f,0.5f)); + _barRenderer->setAnchorPoint(cocos2d::Point(1.0f,0.5f)); if (!_scale9Enabled) { - dynamic_cast(_barRenderer)->setFlippedX(true); + dynamic_cast(_barRenderer)->setFlippedX(true); } break; } @@ -182,11 +182,11 @@ void UILoadingBar::setScale9Enabled(bool enabled) _barRenderer = NULL; if (_scale9Enabled) { - _barRenderer = Scale9Sprite::create(); + _barRenderer = cocos2d::extension::Scale9Sprite::create(); } else { - _barRenderer = CCSprite::create(); + _barRenderer = cocos2d::Sprite::create(); } loadTexture(_textureFile.c_str(),_renderBarTexType); _renderer->addChild(_barRenderer); @@ -203,14 +203,14 @@ void UILoadingBar::setScale9Enabled(bool enabled) setCapInsets(_capInsets); } -void UILoadingBar::setCapInsets(const Rect &capInsets) +void UILoadingBar::setCapInsets(const cocos2d::Rect &capInsets) { _capInsets = capInsets; if (!_scale9Enabled) { return; } - dynamic_cast(_barRenderer)->setCapInsets(capInsets); + dynamic_cast(_barRenderer)->setCapInsets(capInsets); } void UILoadingBar::setPercent(int percent) @@ -231,10 +231,10 @@ void UILoadingBar::setPercent(int percent) { case UI_TEX_TYPE_PLIST: { - Sprite* barNode = DYNAMIC_CAST_CCSPRITE; + cocos2d::Sprite* barNode = DYNAMIC_CAST_CCSPRITE; if (barNode) { - Point to = barNode->getTextureRect().origin; + cocos2d::Point to = barNode->getTextureRect().origin; x = to.x; y = to.y; } @@ -249,7 +249,7 @@ void UILoadingBar::setPercent(int percent) } else { - dynamic_cast(_barRenderer)->setTextureRect(Rect(x, y, _barRendererTextureSize.width * res, _barRendererTextureSize.height)); + dynamic_cast(_barRenderer)->setTextureRect(cocos2d::Rect(x, y, _barRendererTextureSize.width * res, _barRendererTextureSize.height)); } } @@ -272,12 +272,12 @@ void UILoadingBar::ignoreContentAdaptWithSize(bool ignore) } } -const Size& UILoadingBar::getContentSize() const +const cocos2d::Size& UILoadingBar::getContentSize() const { return _barRendererTextureSize; } -Node* UILoadingBar::getVirtualRenderer() +cocos2d::Node* UILoadingBar::getVirtualRenderer() { return _barRenderer; } @@ -303,7 +303,7 @@ void UILoadingBar::barRendererScaleChangedWithSize() else { - Size textureSize = _barRenderer->getContentSize(); + cocos2d::Size textureSize = _barRendererTextureSize; if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _barRenderer->setScale(1.0f); @@ -318,10 +318,10 @@ void UILoadingBar::barRendererScaleChangedWithSize() switch (_barType) { case LoadingBarTypeLeft: - _barRenderer->setPosition(Point(-_totalLength * 0.5f, 0.0f)); + _barRenderer->setPosition(cocos2d::Point(-_totalLength * 0.5f, 0.0f)); break; case LoadingBarTypeRight: - _barRenderer->setPosition(Point(_totalLength * 0.5f, 0.0f)); + _barRenderer->setPosition(cocos2d::Point(_totalLength * 0.5f, 0.0f)); break; default: break; @@ -331,7 +331,7 @@ void UILoadingBar::barRendererScaleChangedWithSize() void UILoadingBar::setScale9Scale() { float width = (float)(_percent) / 100 * _totalLength; - dynamic_cast(_barRenderer)->setPreferredSize(Size(width, _barRendererTextureSize.height)); + dynamic_cast(_barRenderer)->setPreferredSize(cocos2d::Size(width, _size.height)); } const char* UILoadingBar::getDescription() const @@ -339,4 +339,22 @@ const char* UILoadingBar::getDescription() const return "LoadingBar"; } +UIWidget* UILoadingBar::createCloneInstance() +{ + return UILoadingBar::create(); +} + +void UILoadingBar::copySpecialProperties(UIWidget *widget) +{ + UILoadingBar* loadingBar = dynamic_cast(widget); + if (loadingBar) + { + _prevIgnoreSize = loadingBar->_prevIgnoreSize; + setScale9Enabled(loadingBar->_scale9Enabled); + loadTexture(loadingBar->_textureFile.c_str(), loadingBar->_renderBarTexType); + setCapInsets(loadingBar->_capInsets); + setPercent(loadingBar->_percent); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UILoadingBar.h b/cocos/gui/UILoadingBar.h index b67e7314f5..81c5722b4b 100644 --- a/cocos/gui/UILoadingBar.h +++ b/cocos/gui/UILoadingBar.h @@ -34,7 +34,10 @@ typedef enum LoadingBarTypeLeft, LoadingBarTypeRight }LoadingBarType; - +/** +* @js NA +* @lua NA +*/ class UILoadingBar : public UIWidget { public: @@ -126,6 +129,8 @@ protected: virtual void onSizeChanged(); void setScale9Scale(); void barRendererScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: LoadingBarType _barType; int _percent; diff --git a/cocos/gui/UIPageView.cpp b/cocos/gui/UIPageView.cpp index 0fc6558975..54b0713b7a 100644 --- a/cocos/gui/UIPageView.cpp +++ b/cocos/gui/UIPageView.cpp @@ -24,8 +24,6 @@ #include "gui/UIPageView.h" - using namespace cocos2d; - namespace gui { UIPageView::UIPageView(): @@ -33,9 +31,8 @@ _curPageIdx(0), _pages(NULL), _touchMoveDir(PAGEVIEW_TOUCHLEFT), _touchStartLocation(0.0f), -_touchEndLocation(0.0f), _touchMoveStartLocation(0.0f), -_movePagePoint(Point::ZERO), +_movePagePoint(cocos2d::Point::ZERO), _leftChild(NULL), _rightChild(NULL), _leftBoundary(0.0f), @@ -52,7 +49,10 @@ _eventSelector(NULL) UIPageView::~UIPageView() { - _pages->release(); + _pages->removeAllObjects(); + CC_SAFE_RELEASE(_pages); + _eventListener = NULL; + _eventSelector = NULL; } UIPageView* UIPageView::create() @@ -69,12 +69,13 @@ UIPageView* UIPageView::create() bool UIPageView::init() { - if (Layout::init()) + if (UILayout::init()) { - _pages = CCArray::create(); + _pages = cocos2d::Array::create(); _pages->retain(); setClippingEnabled(true); setUpdateEnabled(true); + setTouchEnabled(true); return true; } return false; @@ -86,6 +87,10 @@ void UIPageView::addWidgetToPage(UIWidget *widget, int pageIdx, bool forceCreate { return; } + if (pageIdx < 0) + { + return; + } int pageCount = _pages->count(); if (pageIdx < 0 || pageIdx >= pageCount) { @@ -95,30 +100,29 @@ void UIPageView::addWidgetToPage(UIWidget *widget, int pageIdx, bool forceCreate { CCLOG("pageIdx is %d, it will be added as page id [%d]",pageIdx,pageCount); } - Layout* newPage = createPage(); + UILayout* newPage = createPage(); newPage->addChild(widget); addPage(newPage); } } else { - Layout * page = dynamic_cast(_pages->getObjectAtIndex(pageIdx)); + UILayout * page = dynamic_cast(_pages->getObjectAtIndex(pageIdx)); if (page) { page->addChild(widget); } } - } -Layout* UIPageView::createPage() +UILayout* UIPageView::createPage() { - Layout* newPage = Layout::create(); + UILayout* newPage = UILayout::create(); newPage->setSize(getSize()); return newPage; } -void UIPageView::addPage(Layout* page) +void UIPageView::addPage(UILayout* page) { if (!page) { @@ -132,20 +136,20 @@ void UIPageView::addPage(Layout* page) { return; } - Size pSize = page->getSize(); - Size pvSize = getSize(); + cocos2d::Size pSize = page->getSize(); + cocos2d::Size pvSize = getSize(); if (!pSize.equals(pvSize)) { CCLOG("page size does not match pageview size, it will be force sized!"); page->setSize(pvSize); } - page->setPosition(Point(getPositionXByIndex(_pages->count()), 0)); + page->setPosition(cocos2d::Point(getPositionXByIndex(_pages->count()), 0)); _pages->addObject(page); addChild(page); updateBoundaryPages(); } -void UIPageView::insertPage(Layout* page, int idx) +void UIPageView::insertPage(UILayout* page, int idx) { if (idx < 0) { @@ -172,27 +176,27 @@ void UIPageView::insertPage(Layout* page, int idx) else { _pages->insertObject(page, idx); - page->setPosition(Point(getPositionXByIndex(idx), 0)); + page->setPosition(cocos2d::Point(getPositionXByIndex(idx), 0)); addChild(page); - Size pSize = page->getSize(); - Size pvSize = getSize(); + cocos2d::Size pSize = page->getSize(); + cocos2d::Size pvSize = getSize(); if (!pSize.equals(pvSize)) { CCLOG("page size does not match pageview size, it will be force sized!"); page->setSize(pvSize); } - ccArray* arrayPages = _pages->data; + cocos2d::ccArray* arrayPages = _pages->data; int length = arrayPages->num; for (int i=(idx+1); i(arrayPages->arr[i]); - Point formerPos = behindPage->getPosition(); - behindPage->setPosition(Point(formerPos.x+getSize().width, 0)); + cocos2d::Point formerPos = behindPage->getPosition(); + behindPage->setPosition(cocos2d::Point(formerPos.x+getSize().width, 0)); } updateBoundaryPages(); } } -void UIPageView::removePage(Layout* page) +void UIPageView::removePage(UILayout* page) { if (!page) { @@ -209,7 +213,7 @@ void UIPageView::removePageAtIndex(int index) { return; } - Layout* page = dynamic_cast(_pages->getObjectAtIndex(index)); + UILayout* page = dynamic_cast(_pages->getObjectAtIndex(index)); if (page) { removePage(page); @@ -222,6 +226,7 @@ void UIPageView::updateBoundaryPages() { _leftChild = NULL; _rightChild = NULL; + return; } _leftChild = dynamic_cast(_pages->getObjectAtIndex(0)); _rightChild = dynamic_cast(_pages->getLastObject()); @@ -234,7 +239,7 @@ float UIPageView::getPositionXByIndex(int idx) bool UIPageView::addChild(UIWidget* widget) { - return Layout::addChild(widget); + return UILayout::addChild(widget); } bool UIPageView::removeChild(UIWidget* widget) @@ -242,14 +247,14 @@ bool UIPageView::removeChild(UIWidget* widget) if (_pages->containsObject(widget)) { _pages->removeObject(widget); - return Layout::removeChild(widget); + return UILayout::removeChild(widget); } return false; } void UIPageView::onSizeChanged() { - Layout::onSizeChanged(); + UILayout::onSizeChanged(); _rightBoundary = getSize().width; updateChildrenSize(); updateChildrenPosition(); @@ -262,10 +267,10 @@ void UIPageView::updateChildrenSize() return; } - Size selfSize = getSize(); - for (int i = 0; i < _pages->count(); i++) + cocos2d::Size selfSize = getSize(); + for (unsigned int i=0; i<_pages->count(); i++) { - Layout* page = dynamic_cast(_pages->getObjectAtIndex(i)); + UILayout* page = dynamic_cast(_pages->getObjectAtIndex(i)); page->setSize(selfSize); } } @@ -288,18 +293,18 @@ void UIPageView::updateChildrenPosition() _curPageIdx = pageCount-1; } float pageWidth = getSize().width; - ccArray* arrayPages = _pages->data; + cocos2d::ccArray* arrayPages = _pages->data; for (int i=0; i(arrayPages->arr[i]); - page->setPosition(Point((i-_curPageIdx)*pageWidth, 0)); + UILayout* page = dynamic_cast(arrayPages->arr[i]); + page->setPosition(cocos2d::Point((i-_curPageIdx)*pageWidth, 0)); } } void UIPageView::removeAllChildren() { _pages->removeAllObjects(); - Layout::removeAllChildren(); + UILayout::removeAllChildren(); } void UIPageView::scrollToPage(int idx) @@ -330,13 +335,16 @@ void UIPageView::update(float dt) step = -_autoScrollDistance; _autoScrollDistance = 0.0f; _isAutoScrolling = false; - pageTurningEvent(); } else { _autoScrollDistance += step; } scrollPages(-step); + if (!_isAutoScrolling) + { + pageTurningEvent(); + } break; } break; @@ -348,13 +356,16 @@ void UIPageView::update(float dt) step = _autoScrollDistance; _autoScrollDistance = 0.0f; _isAutoScrolling = false; - pageTurningEvent(); } else { _autoScrollDistance -= step; } scrollPages(step); + if (!_isAutoScrolling) + { + pageTurningEvent(); + } break; } default: @@ -363,14 +374,14 @@ void UIPageView::update(float dt) } } -bool UIPageView::onTouchBegan(const Point &touchPoint) +bool UIPageView::onTouchBegan(const cocos2d::Point &touchPoint) { - bool pass = Layout::onTouchBegan(touchPoint); + bool pass = UILayout::onTouchBegan(touchPoint); handlePressLogic(touchPoint); return pass; } -void UIPageView::onTouchMoved(const Point &touchPoint) +void UIPageView::onTouchMoved(const cocos2d::Point &touchPoint) { _touchMovePos.x = touchPoint.x; _touchMovePos.y = touchPoint.y; @@ -387,15 +398,15 @@ void UIPageView::onTouchMoved(const Point &touchPoint) } } -void UIPageView::onTouchEnded(const Point &touchPoint) +void UIPageView::onTouchEnded(const cocos2d::Point &touchPoint) { - Layout::onTouchEnded(touchPoint); + UILayout::onTouchEnded(touchPoint); handleReleaseLogic(touchPoint); } void UIPageView::movePages(float offset) { - ccArray* arrayPages = _pages->data; + cocos2d::ccArray* arrayPages = _pages->data; int length = arrayPages->num; for (int i = 0; i < length; i++) { @@ -447,21 +458,21 @@ bool UIPageView::scrollPages(float touchOffset) return true; } -void UIPageView::onTouchCancelled(const Point &touchPoint) +void UIPageView::onTouchCancelled(const cocos2d::Point &touchPoint) { - Layout::onTouchCancelled(touchPoint); + UILayout::onTouchCancelled(touchPoint); } -void UIPageView::handlePressLogic(const Point &touchPoint) +void UIPageView::handlePressLogic(const cocos2d::Point &touchPoint) { - Point nsp = _renderer->convertToNodeSpace(touchPoint); + cocos2d::Point nsp = _renderer->convertToNodeSpace(touchPoint); _touchMoveStartLocation = nsp.x; _touchStartLocation = nsp.x; } -void UIPageView::handleMoveLogic(const Point &touchPoint) +void UIPageView::handleMoveLogic(const cocos2d::Point &touchPoint) { - Point nsp = _renderer->convertToNodeSpace(touchPoint); + cocos2d::Point nsp = _renderer->convertToNodeSpace(touchPoint); float offset = 0.0; float moveX = nsp.x; offset = moveX - _touchMoveStartLocation; @@ -477,12 +488,16 @@ void UIPageView::handleMoveLogic(const Point &touchPoint) scrollPages(offset); } -void UIPageView::handleReleaseLogic(const Point &touchPoint) +void UIPageView::handleReleaseLogic(const cocos2d::Point &touchPoint) { + if (_pages->count() <= 0) + { + return; + } UIWidget* curPage = dynamic_cast(_pages->getObjectAtIndex(_curPageIdx)); if (curPage) { - Point curPagePos = curPage->getPosition(); + cocos2d::Point curPagePos = curPage->getPosition(); int pageCount = _pages->count(); float curPageLocation = curPagePos.x; float pageWidth = getSize().width; @@ -516,12 +531,12 @@ void UIPageView::handleReleaseLogic(const Point &touchPoint) } } -void UIPageView::checkChildInfo(int handleState,UIWidget* sender, const Point &touchPoint) +void UIPageView::checkChildInfo(int handleState,UIWidget* sender, const cocos2d::Point &touchPoint) { interceptTouchEvent(handleState, sender, touchPoint); } -void UIPageView::interceptTouchEvent(int handleState, UIWidget *sender, const Point &touchPoint) +void UIPageView::interceptTouchEvent(int handleState, UIWidget *sender, const cocos2d::Point &touchPoint) { switch (handleState) { @@ -556,7 +571,7 @@ void UIPageView::pageTurningEvent() } } -void UIPageView::addEventListener(Object *target, SEL_PageViewEvent selector) +void UIPageView::addEventListener(cocos2d::Object *target, SEL_PageViewEvent selector) { _eventListener = target; _eventSelector = selector; @@ -567,9 +582,39 @@ int UIPageView::getCurPageIndex() const return _curPageIdx; } +cocos2d::Array* UIPageView::getPages() +{ + return _pages; +} + const char* UIPageView::getDescription() const { return "PageView"; } +UIWidget* UIPageView::createCloneInstance() +{ + return UIPageView::create(); +} + +void UIPageView::copyClonedWidgetChildren(UIWidget* model) +{ + cocos2d::ccArray* arrayPages = dynamic_cast(model)->getPages()->data; + int length = arrayPages->num; + for (int i=0; iarr[i]); + addPage(dynamic_cast(page->clone())); + } +} + +void UIPageView::copySpecialProperties(UIWidget *widget) +{ + UIPageView* pageView = dynamic_cast(widget); + if (pageView) + { + UILayout::copySpecialProperties(widget); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UIPageView.h b/cocos/gui/UIPageView.h index e8d3d5192d..ec78df8bbd 100644 --- a/cocos/gui/UIPageView.h +++ b/cocos/gui/UIPageView.h @@ -25,7 +25,7 @@ #ifndef __UIPAGEVIEW_H__ #define __UIPAGEVIEW_H__ -#include "gui/Layout.h" +#include "gui/UILayout.h" #include "gui/UIScrollInterface.h" namespace gui { @@ -43,7 +43,7 @@ typedef enum { PAGEVIEW_TOUCHRIGHT }PVTouchDir; -class UIPageView : public Layout , public UIScrollInterface +class UIPageView : public UILayout , public UIScrollInterface { public: @@ -78,21 +78,21 @@ public: * * @param page page to be added to pageview. */ - void addPage(Layout* page); + void addPage(UILayout* page); /** * Inert a page to pageview. * * @param page page to be added to pageview. */ - void insertPage(Layout* page, int idx); + void insertPage(UILayout* page, int idx); /** * Remove a page of pageview. * * @param page page which will be removed. */ - void removePage(Layout* page); + void removePage(UILayout* page); /** * Remove a page at index of pageview. @@ -115,8 +115,11 @@ public: */ int getCurPageIndex() const; + cocos2d::Array* getPages(); + // event void addEventListener(cocos2d::Object *target, SEL_PageViewEvent selector); + //override "removeChild" method of widget. virtual bool removeChild(UIWidget* widget); @@ -140,15 +143,16 @@ public: virtual void update(float dt); virtual void doLayout(){}; - + /** * Returns the "class name" of widget. */ virtual const char* getDescription() const; + protected: virtual bool addChild(UIWidget* widget); virtual bool init(); - Layout* createPage(); + UILayout* createPage(); float getPositionXByIndex(int idx); void updateBoundaryPages(); virtual void handlePressLogic(const cocos2d::Point &touchPoint); @@ -162,14 +166,15 @@ protected: void updateChildrenSize(); void updateChildrenPosition(); virtual void onSizeChanged(); - - virtual void setClippingEnabled(bool able){Layout::setClippingEnabled(able);}; + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); + virtual void copyClonedWidgetChildren(UIWidget* model); + virtual void setClippingEnabled(bool able){UILayout::setClippingEnabled(able);}; protected: int _curPageIdx; cocos2d::Array* _pages; PVTouchDir _touchMoveDir; float _touchStartLocation; - float _touchEndLocation; float _touchMoveStartLocation; cocos2d::Point _movePagePoint; UIWidget* _leftChild; @@ -183,6 +188,7 @@ protected: float _childFocusCancelOffset; cocos2d::Object* _eventListener; SEL_PageViewEvent _eventSelector; + }; } diff --git a/cocos/gui/UIRootWidget.cpp b/cocos/gui/UIRootWidget.cpp index f6bf7359f0..0b7581287f 100644 --- a/cocos/gui/UIRootWidget.cpp +++ b/cocos/gui/UIRootWidget.cpp @@ -24,8 +24,6 @@ #include "gui/UIRootWidget.h" - using namespace cocos2d; - namespace gui { UIRootWidget::UIRootWidget() @@ -50,9 +48,9 @@ UIRootWidget* UIRootWidget::create() bool UIRootWidget::init() { - if (Layout::init()) + if (UILayout::init()) { - setSize(Director::getInstance()->getWinSize()); + setSize(cocos2d::Director::getInstance()->getWinSize()); return true; } return false; diff --git a/cocos/gui/UIRootWidget.h b/cocos/gui/UIRootWidget.h index f4bff4955f..dc93ac4645 100644 --- a/cocos/gui/UIRootWidget.h +++ b/cocos/gui/UIRootWidget.h @@ -25,11 +25,15 @@ #ifndef __UIROOTWIDGET_H__ #define __UIROOTWIDGET_H__ -#include "gui/Layout.h" +#include "gui/UILayout.h" namespace gui { - -class UIRootWidget : public Layout + +/** +* @js NA +* @lua NA +*/ +class UIRootWidget : public UILayout { public: /** diff --git a/cocos/gui/UIScrollInterface.h b/cocos/gui/UIScrollInterface.h index 2e835982fd..dfff4cd66c 100644 --- a/cocos/gui/UIScrollInterface.h +++ b/cocos/gui/UIScrollInterface.h @@ -36,7 +36,6 @@ protected: virtual void handleMoveLogic(const cocos2d::Point &touchPoint) = 0; virtual void handleReleaseLogic(const cocos2d::Point &touchPoint) = 0; virtual void interceptTouchEvent(int handleState, UIWidget* sender, const cocos2d::Point &touchPoint) = 0; -// virtual bool isInScrollDegreeRange(UIWidget* widget) = 0; }; } diff --git a/cocos/gui/UIScrollView.cpp b/cocos/gui/UIScrollView.cpp index bdb3d45a21..ebf32514da 100644 --- a/cocos/gui/UIScrollView.cpp +++ b/cocos/gui/UIScrollView.cpp @@ -23,34 +23,52 @@ ****************************************************************************/ #include "gui/UIScrollView.h" -#include "gui/UILayer.h" - - using namespace cocos2d; namespace gui { +#define AUTOSCROLLMAXSPEED 1000.0f + +const cocos2d::Point SCROLLDIR_UP = cocos2d::Point(0.0f, 1.0f); +const cocos2d::Point SCROLLDIR_DOWN = cocos2d::Point(0.0f, -1.0f); +const cocos2d::Point SCROLLDIR_LEFT = cocos2d::Point(-1.0f, 0.0f); +const cocos2d::Point SCROLLDIR_RIGHT = cocos2d::Point(1.0f, 0.0f); + UIScrollView::UIScrollView(): _innerContainer(NULL), _direction(SCROLLVIEW_DIR_VERTICAL), -_moveDirection(SCROLLVIEW_MOVE_DIR_NONE), -_touchStartLocation(0.0f), -_touchEndLocation(0.0f), -_touchMoveStartLocation(0.0f), +_touchBeganPoint(cocos2d::Point::ZERO), +_touchMovedPoint(cocos2d::Point::ZERO), +_touchEndedPoint(cocos2d::Point::ZERO), +_touchMovingPoint(cocos2d::Point::ZERO), +_autoScrollDir(cocos2d::Point::ZERO), _topBoundary(0.0f), _bottomBoundary(0.0f), _leftBoundary(0.0f), _rightBoundary(0.0f), -_topEnd(false), -_bottomEnd(false), -_leftEnd(false), -_rightEnd(false), +_bounceTopBoundary(0.0f), +_bounceBottomBoundary(0.0f), +_bounceLeftBoundary(0.0f), +_bounceRightBoundary(0.0f), _autoScroll(false), +_autoScrollAddUpTime(0.0f), _autoScrollOriginalSpeed(0.0f), -_autoScrollAcceleration(600.0f), +_autoScrollAcceleration(-1000.0f), +_isAutoScrollSpeedAttenuated(false), +_needCheckAutoScrollDestination(false), +_autoScrollDestination(cocos2d::Point::ZERO), _bePressed(false), _slidTime(0.0f), -_moveChildPoint(Point::ZERO), +_moveChildPoint(cocos2d::Point::ZERO), _childFocusCancelOffset(5.0f), +_leftBounceNeeded(false), +_topBounceNeeded(false), +_rightBounceNeeded(false), +_bottomBounceNeeded(false), +_bounceEnabled(false), +_bouncing(false), +_bounceDir(cocos2d::Point::ZERO), +_bounceOriginalSpeed(0.0f), +_inertiaScrollEnabled(true), _eventListener(NULL), _eventSelector(NULL) { @@ -58,7 +76,8 @@ _eventSelector(NULL) UIScrollView::~UIScrollView() { - + _eventListener = NULL; + _eventSelector = NULL; } UIScrollView* UIScrollView::create() @@ -73,22 +92,9 @@ UIScrollView* UIScrollView::create() return NULL; } -void UIScrollView::releaseResoures() -{ - setUpdateEnabled(false); - removeAllChildren(); - _renderer->removeAllChildrenWithCleanup(true); - _renderer->removeFromParentAndCleanup(true); - _renderer->release(); - - Layout::removeChild(_innerContainer); - - _children->release(); -} - bool UIScrollView::init() { - if (Layout::init()) + if (UILayout::init()) { setUpdateEnabled(true); setTouchEnabled(true); @@ -101,29 +107,36 @@ bool UIScrollView::init() void UIScrollView::initRenderer() { - Layout::initRenderer(); - _innerContainer = Layout::create(); - Layout::addChild(_innerContainer); + UILayout::initRenderer(); + _innerContainer = UILayout::create(); + UILayout::addChild(_innerContainer); } void UIScrollView::onSizeChanged() { - Layout::onSizeChanged(); + UILayout::onSizeChanged(); _topBoundary = _size.height; _rightBoundary = _size.width; - Size innerSize = _innerContainer->getSize(); + float bounceBoundaryParameterX = _size.width / 3.0f; + float bounceBoundaryParameterY = _size.height / 3.0f; + _bounceTopBoundary = _size.height - bounceBoundaryParameterY; + _bounceBottomBoundary = bounceBoundaryParameterY; + _bounceLeftBoundary = bounceBoundaryParameterX; + _bounceRightBoundary = _size.width - bounceBoundaryParameterX; + cocos2d::Size innerSize = _innerContainer->getSize(); float orginInnerSizeWidth = innerSize.width; float orginInnerSizeHeight = innerSize.height; float innerSizeWidth = MAX(orginInnerSizeWidth, _size.width); float innerSizeHeight = MAX(orginInnerSizeHeight, _size.height); - _innerContainer->setSize(Size(innerSizeWidth, innerSizeHeight)); - _innerContainer->setPosition(Point(0, _size.height - _innerContainer->getSize().height)); + _innerContainer->setSize(cocos2d::Size(innerSizeWidth, innerSizeHeight)); + _innerContainer->setPosition(cocos2d::Point(0, _size.height - _innerContainer->getSize().height)); } -void UIScrollView::setInnerContainerSize(const Size &size) +void UIScrollView::setInnerContainerSize(const cocos2d::Size &size) { float innerSizeWidth = _size.width; float innerSizeHeight = _size.height; + cocos2d::Size originalInnerSize = _innerContainer->getSize(); if (size.width < _size.width) { CCLOG("Inner width <= scrollview width, it will be force sized!"); @@ -140,11 +153,45 @@ void UIScrollView::setInnerContainerSize(const Size &size) { innerSizeHeight = size.height; } - _innerContainer->setSize(Size(innerSizeWidth, innerSizeHeight)); - _innerContainer->setPosition(Point(0, _size.height - _innerContainer->getSize().height)); + _innerContainer->setSize(cocos2d::Size(innerSizeWidth, innerSizeHeight)); + + switch (_direction) + { + case SCROLLVIEW_DIR_VERTICAL: + { + cocos2d::Size newInnerSize = _innerContainer->getSize(); + float offset = originalInnerSize.height - newInnerSize.height; + scrollChildren(0.0f, offset); + break; + } + case SCROLLVIEW_DIR_HORIZONTAL: + { + if (_innerContainer->getRightInParent() <= _size.width) + { + cocos2d::Size newInnerSize = _innerContainer->getSize(); + float offset = originalInnerSize.width - newInnerSize.width; + scrollChildren(offset, 0.0f); + } + break; + } + case SCROLLVIEW_DIR_BOTH: + { + cocos2d::Size newInnerSize = _innerContainer->getSize(); + float offsetY = originalInnerSize.height - newInnerSize.height; + float offsetX = 0.0f; + if (_innerContainer->getRightInParent() <= _size.width) + { + offsetX = originalInnerSize.width - newInnerSize.width; + } + scrollChildren(offsetX, offsetY); + break; + } + default: + break; + } } -const Size& UIScrollView::getInnerContainerSize() const +const cocos2d::Size& UIScrollView::getInnerContainerSize() const { return _innerContainer->getSize(); } @@ -164,378 +211,1192 @@ bool UIScrollView::removeChild(UIWidget* child) return _innerContainer->removeChild(child); } -Array* UIScrollView::getChildren() +cocos2d::Array* UIScrollView::getChildren() { return _innerContainer->getChildren(); } -void UIScrollView::moveChildren(float offset) +void UIScrollView::moveChildren(float offsetX, float offsetY) { - switch (_direction) - { - case SCROLLVIEW_DIR_VERTICAL: // vertical - { - _moveChildPoint.x = _innerContainer->getPosition().x; - _moveChildPoint.y = _innerContainer->getPosition().y + offset; - _innerContainer->setPosition(_moveChildPoint); - break; - } - case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - { - _moveChildPoint.x = _innerContainer->getPosition().x + offset; - _moveChildPoint.y = _innerContainer->getPosition().y; - _innerContainer->setPosition(_moveChildPoint); - break; - } - default: - break; - } + _moveChildPoint = _innerContainer->getPosition() + cocos2d::Point(offsetX, offsetY); + _innerContainer->setPosition(_moveChildPoint); } void UIScrollView::autoScrollChildren(float dt) { - switch (_direction) + float lastTime = _autoScrollAddUpTime; + _autoScrollAddUpTime += dt; + if (_isAutoScrollSpeedAttenuated) { - case SCROLLVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case SCROLLVIEW_MOVE_DIR_UP: // up - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(curDis)) - { - stopAutoScrollChildren(); - } - } - break; - case SCROLLVIEW_MOVE_DIR_DOWN: // down - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(-curDis)) - { - stopAutoScrollChildren(); - } - } - break; - default: - break; - } - break; - - case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) + float nowSpeed = _autoScrollOriginalSpeed + _autoScrollAcceleration * _autoScrollAddUpTime; + if (nowSpeed <= 0.0f) + { + stopAutoScrollChildren(); + checkNeedBounce(); + } + else + { + float timeParam = lastTime * 2 + dt; + float offset = (_autoScrollOriginalSpeed + _autoScrollAcceleration * timeParam * 0.5f) * dt; + float offsetX = offset * _autoScrollDir.x; + float offsetY = offset * _autoScrollDir.y; + if (!scrollChildren(offsetX, offsetY)) { - case SCROLLVIEW_MOVE_DIR_LEFT: // left - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(-curDis)) - { - stopAutoScrollChildren(); - } - } - break; - - case SCROLLVIEW_MOVE_DIR_RIGHT: // right - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(curDis)) - { - stopAutoScrollChildren(); - } - } - break; - - default: - break; + stopAutoScrollChildren(); + checkNeedBounce(); } - break; - - default: - break; + } + } + else + { + if (_needCheckAutoScrollDestination) + { + float xOffset = _autoScrollDir.x * dt * _autoScrollOriginalSpeed; + float yOffset = _autoScrollDir.y * dt * _autoScrollOriginalSpeed; + bool notDone = checkCustomScrollDestination(&xOffset, &yOffset); + bool scrollCheck = scrollChildren(xOffset, yOffset); + if (!notDone || !scrollCheck) + { + stopAutoScrollChildren(); + checkNeedBounce(); + } + } + else + { + if (!scrollChildren(_autoScrollDir.x * dt * _autoScrollOriginalSpeed, _autoScrollDir.y * dt * _autoScrollOriginalSpeed)) + { + stopAutoScrollChildren(); + checkNeedBounce(); + } + } } } -void UIScrollView::startAutoScrollChildren(float v) +void UIScrollView::bounceChildren(float dt) { + if (_bounceOriginalSpeed <= 0.0f) + { + stopBounceChildren(); + } + if (!bounceScrollChildren(_bounceDir.x * dt * _bounceOriginalSpeed, _bounceDir.y * dt * _bounceOriginalSpeed)) + { + stopBounceChildren(); + } +} + +bool UIScrollView::checkNeedBounce() +{ + if (!_bounceEnabled) + { + return false; + } + checkBounceBoundary(); + if (_topBounceNeeded || _bottomBounceNeeded || _leftBounceNeeded || _rightBounceNeeded) + { + if (_topBounceNeeded && _leftBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point(0.0f, _size.height) - cocos2d::Point(_innerContainer->getLeftInParent(), _innerContainer->getTopInParent()); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_topBounceNeeded && _rightBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point(_size.width, _size.height) - cocos2d::Point(_innerContainer->getRightInParent(), _innerContainer->getTopInParent()); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_bottomBounceNeeded && _leftBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point::ZERO - cocos2d::Point(_innerContainer->getLeftInParent(), _innerContainer->getBottomInParent()); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_bottomBounceNeeded && _rightBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point(_size.width, 0.0f) - cocos2d::Point(_innerContainer->getRightInParent(), _innerContainer->getBottomInParent()); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_topBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point(0.0f, _size.height) - cocos2d::Point(0.0f, _innerContainer->getTopInParent()); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_bottomBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point::ZERO - cocos2d::Point(0.0f, _innerContainer->getBottomInParent()); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_leftBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point::ZERO - cocos2d::Point(_innerContainer->getLeftInParent(), 0.0f); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_rightBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point(_size.width, 0.0f) - cocos2d::Point(_innerContainer->getRightInParent(), 0.0f); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + return true; + } + return false; +} + +void UIScrollView::checkBounceBoundary() +{ + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos > _bottomBoundary) + { + scrollToBottomEvent(); + _bottomBounceNeeded = true; + } + else + { + _bottomBounceNeeded = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos < _topBoundary) + { + scrollToTopEvent(); + _topBounceNeeded = true; + } + else + { + _topBounceNeeded = false; + } + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos < _rightBoundary) + { + scrollToRightEvent(); + _rightBounceNeeded = true; + } + else + { + _rightBounceNeeded = false; + } + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos > _leftBoundary) + { + scrollToLeftEvent(); + _leftBounceNeeded = true; + } + else + { + _leftBounceNeeded = false; + } +} + +void UIScrollView::startBounceChildren(float v) +{ + _bounceOriginalSpeed = v; + _bouncing = true; +} + +void UIScrollView::stopBounceChildren() +{ + _bouncing = false; + _bounceOriginalSpeed = 0.0f; + _leftBounceNeeded = false; + _rightBounceNeeded = false; + _topBounceNeeded = false; + _bottomBounceNeeded = false; +} + +void UIScrollView::startAutoScrollChildrenWithOriginalSpeed(const cocos2d::Point& dir, float v, bool attenuated, float acceleration) +{ + stopAutoScrollChildren(); + _autoScrollDir = dir; + _isAutoScrollSpeedAttenuated = attenuated; _autoScrollOriginalSpeed = v; _autoScroll = true; + _autoScrollAcceleration = acceleration; +} + +void UIScrollView::startAutoScrollChildrenWithDestination(const cocos2d::Point& des, float time, bool attenuated) +{ + _needCheckAutoScrollDestination = false; + _autoScrollDestination = des; + cocos2d::Point dis = des - _innerContainer->getPosition(); + cocos2d::Point dir = dis.normalize(); + float orSpeed = 0.0f; + float acceleration = -1000.0f; + if (attenuated) + { + acceleration = (-(2 * dis.getLength())) / (time * time); + orSpeed = 2 * dis.getLength() / time; + } + else + { + _needCheckAutoScrollDestination = true; + orSpeed = dis.getLength() / time; + } + startAutoScrollChildrenWithOriginalSpeed(dir, orSpeed, attenuated, acceleration); +} + +void UIScrollView::jumpToDestination(const cocos2d::Point &des) +{ + float finalOffsetX = des.x; + float finalOffsetY = des.y; + switch (_direction) + { + case SCROLLVIEW_DIR_VERTICAL: + if (des.y <= 0) + { + finalOffsetY = MAX(des.y, _size.height - _innerContainer->getSize().height); + } + break; + case SCROLLVIEW_DIR_HORIZONTAL: + if (des.x <= 0) + { + finalOffsetX = MAX(des.x, _size.width - _innerContainer->getSize().width); + } + break; + case SCROLLVIEW_DIR_BOTH: + if (des.y <= 0) + { + finalOffsetY = MAX(des.y, _size.height - _innerContainer->getSize().height); + } + if (des.x <= 0) + { + finalOffsetX = MAX(des.x, _size.width - _innerContainer->getSize().width); + } + break; + default: + break; + } + _innerContainer->setPosition(cocos2d::Point(finalOffsetX, finalOffsetY)); } void UIScrollView::stopAutoScrollChildren() { _autoScroll = false; _autoScrollOriginalSpeed = 0.0f; + _autoScrollAddUpTime = 0.0f; } -float UIScrollView::getCurAutoScrollDistance(float time) +bool UIScrollView::bounceScrollChildren(float touchOffsetX, float touchOffsetY) { - float dt = time; - _autoScrollOriginalSpeed -= _autoScrollAcceleration*dt; - return _autoScrollOriginalSpeed*dt; + bool scrollenabled = true; + if (touchOffsetX > 0.0f && touchOffsetY > 0.0f) //first quadrant //bounce to top-right + { + float realOffsetX = touchOffsetX; + float realOffsetY = touchOffsetY; + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + realOffsetX >= _rightBoundary) + { + realOffsetX = _rightBoundary - icRightPos; + bounceRightEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY >= _topBoundary) + { + realOffsetY = _topBoundary - icTopPos; + bounceTopEvent(); + scrollenabled = false; + } + moveChildren(realOffsetX, realOffsetY); + } + else if(touchOffsetX < 0.0f && touchOffsetY > 0.0f) //second quadrant //bounce to top-left + { + float realOffsetX = touchOffsetX; + float realOffsetY = touchOffsetY; + float icLefrPos = _innerContainer->getLeftInParent(); + if (icLefrPos + realOffsetX <= _leftBoundary) + { + realOffsetX = _leftBoundary - icLefrPos; + bounceLeftEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY >= _topBoundary) + { + realOffsetY = _topBoundary - icTopPos; + bounceTopEvent(); + scrollenabled = false; + } + moveChildren(realOffsetX, realOffsetY); + } + else if (touchOffsetX < 0.0f && touchOffsetY < 0.0f) //third quadrant //bounce to bottom-left + { + float realOffsetX = touchOffsetX; + float realOffsetY = touchOffsetY; + float icLefrPos = _innerContainer->getLeftInParent(); + if (icLefrPos + realOffsetX <= _leftBoundary) + { + realOffsetX = _leftBoundary - icLefrPos; + bounceLeftEvent(); + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY <= _bottomBoundary) + { + realOffsetY = _bottomBoundary - icBottomPos; + bounceBottomEvent(); + scrollenabled = false; + } + moveChildren(realOffsetX, realOffsetY); + } + else if (touchOffsetX > 0.0f && touchOffsetY < 0.0f) //forth quadrant //bounce to bottom-right + { + float realOffsetX = touchOffsetX; + float realOffsetY = touchOffsetY; + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + realOffsetX >= _rightBoundary) + { + realOffsetX = _rightBoundary - icRightPos; + bounceRightEvent(); + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY <= _bottomBoundary) + { + realOffsetY = _bottomBoundary - icBottomPos; + bounceBottomEvent(); + scrollenabled = false; + } + moveChildren(realOffsetX, realOffsetY); + } + else if (touchOffsetX == 0.0f && touchOffsetY > 0.0f) // bounce to top + { + float realOffsetY = touchOffsetY; + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY >= _topBoundary) + { + realOffsetY = _topBoundary - icTopPos; + bounceTopEvent(); + scrollenabled = false; + } + moveChildren(0.0f, realOffsetY); + } + else if (touchOffsetX == 0.0f && touchOffsetY < 0.0f) //bounce to bottom + { + float realOffsetY = touchOffsetY; + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY <= _bottomBoundary) + { + realOffsetY = _bottomBoundary - icBottomPos; + bounceBottomEvent(); + scrollenabled = false; + } + moveChildren(0.0f, realOffsetY); + } + else if (touchOffsetX > 0.0f && touchOffsetY == 0.0f) //bounce to right + { + float realOffsetX = touchOffsetX; + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + realOffsetX >= _rightBoundary) + { + realOffsetX = _rightBoundary - icRightPos; + bounceRightEvent(); + scrollenabled = false; + } + moveChildren(realOffsetX, 0.0f); + } + else if (touchOffsetX < 0.0f && touchOffsetY == 0.0f) //bounce to left + { + float realOffsetX = touchOffsetX; + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + realOffsetX <= _leftBoundary) + { + realOffsetX = _leftBoundary - icLeftPos; + bounceLeftEvent(); + scrollenabled = false; + } + moveChildren(realOffsetX, 0.0f); + } + return scrollenabled; } -bool UIScrollView::scrollChildren(float touchOffset) -{ - float realOffset = touchOffset; - +bool UIScrollView::checkCustomScrollDestination(float* touchOffsetX, float* touchOffsetY) +{ + bool scrollenabled = true; switch (_direction) { case SCROLLVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case SCROLLVIEW_MOVE_DIR_UP: // up - { - float icBottomPos = _innerContainer->getBottomInParent(); - if (icBottomPos + touchOffset >= _bottomBoundary) - { - realOffset = _bottomBoundary - icBottomPos; - moveChildren(realOffset); - _bottomEnd = true; - scrollToBottomEvent(); - return false; - } - break; - } - case SCROLLVIEW_MOVE_DIR_DOWN: // down - { - float icTopPos = _innerContainer->getTopInParent(); - if (icTopPos + touchOffset <= _topBoundary) - { - realOffset = _topBoundary - icTopPos; - moveChildren(realOffset); - _topEnd = true; - scrollToTopEvent(); - return false; - } - break; - } - default: - break; - } - moveChildren(realOffset); - _topEnd = false; - _bottomEnd = false; - return true; - break; - case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) + { + if (_autoScrollDir.y > 0) { - case SCROLLVIEW_MOVE_DIR_LEFT: // left + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + *touchOffsetY >= _autoScrollDestination.y) { - float icRightPos = _innerContainer->getRightInParent(); - if (icRightPos + touchOffset <= _rightBoundary) - { - realOffset = _rightBoundary - icRightPos; - moveChildren(realOffset); - _rightEnd = true; - scrollToRightEvent(); - return false; - } - break; + *touchOffsetY = _autoScrollDestination.y - icBottomPos; + scrollenabled = false; + } + } + else + { + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + *touchOffsetY <= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icBottomPos; + scrollenabled = false; } - case SCROLLVIEW_MOVE_DIR_RIGHT: // right - { - float icLeftPos = _innerContainer->getLeftInParent(); - if (icLeftPos + touchOffset >= _leftBoundary) - { - realOffset = _leftBoundary - icLeftPos; - moveChildren(realOffset); - _leftEnd = true; - scrollToLeftEvent(); - return false; - } - break; - } - default: - break; } - moveChildren(realOffset); - _leftEnd = false; - _rightEnd = false; - return true; break; - + } + case SCROLLVIEW_DIR_HORIZONTAL: // horizontal + { + if (_autoScrollDir.x > 0) + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + *touchOffsetX >= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icLeftPos; + scrollenabled = false; + } + } + else + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + *touchOffsetX <= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icLeftPos; + scrollenabled = false; + } + } + break; + } + case SCROLLVIEW_DIR_BOTH: + { + if (*touchOffsetX > 0.0f && *touchOffsetY > 0.0f) // up right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + *touchOffsetX >= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icLeftPos; + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + *touchOffsetY >= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icBottomPos; + scrollenabled = false; + } + } + else if (*touchOffsetX < 0.0f && *touchOffsetY > 0.0f) // up left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + *touchOffsetX <= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icRightPos; + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + *touchOffsetY >= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icBottomPos; + scrollenabled = false; + } + } + else if (*touchOffsetX < 0.0f && *touchOffsetY < 0.0f) // down left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + *touchOffsetX <= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icRightPos; + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + *touchOffsetY <= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icTopPos; + scrollenabled = false; + } + } + else if (*touchOffsetX > 0.0f && *touchOffsetY < 0.0f) // down right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + *touchOffsetX >= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icLeftPos; + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + *touchOffsetY <= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icTopPos; + scrollenabled = false; + } + } + else if (*touchOffsetX == 0.0f && *touchOffsetY > 0.0f) // up + { + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + *touchOffsetY >= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icBottomPos; + scrollenabled = false; + } + } + else if (*touchOffsetX < 0.0f && *touchOffsetY == 0.0f) // left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + *touchOffsetX <= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icRightPos; + scrollenabled = false; + } + } + else if (*touchOffsetX == 0.0f && *touchOffsetY < 0.0f) // down + { + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + *touchOffsetY <= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icTopPos; + scrollenabled = false; + } + } + else if (*touchOffsetX > 0.0f && *touchOffsetY == 0.0f) // right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + *touchOffsetX >= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icLeftPos; + scrollenabled = false; + } + } + break; + } default: break; } - - return false; + return scrollenabled; } -void UIScrollView::scrollToBottom() +bool UIScrollView::scrollChildren(float touchOffsetX, float touchOffsetY) { - _moveDirection = SCROLLVIEW_MOVE_DIR_UP; // up - scrollChildren(_innerContainer->getSize().height); + bool scrollenabled = true; + scrollingEvent(); + switch (_direction) + { + case SCROLLVIEW_DIR_VERTICAL: // vertical + { + float realOffset = touchOffsetY; + if (_bounceEnabled) + { + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bounceBottomBoundary) + { + realOffset = _bounceBottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _bounceTopBoundary) + { + realOffset = _bounceTopBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else + { + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bottomBoundary) + { + realOffset = _bottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _topBoundary) + { + realOffset = _topBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + moveChildren(0.0f, realOffset); + break; + } + case SCROLLVIEW_DIR_HORIZONTAL: // horizontal + { + float realOffset = touchOffsetX; + if (_bounceEnabled) + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _bounceRightBoundary) + { + realOffset = _bounceRightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _bounceLeftBoundary) + { + realOffset = _bounceLeftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + } + else + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _rightBoundary) + { + realOffset = _rightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _leftBoundary) + { + realOffset = _leftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + } + moveChildren(realOffset, 0.0f); + break; + } + case SCROLLVIEW_DIR_BOTH: + { + float realOffsetX = touchOffsetX; + float realOffsetY = touchOffsetY; + if (_bounceEnabled) + { + if (touchOffsetX > 0.0f && touchOffsetY > 0.0f) // up right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _bounceLeftBoundary) + { + realOffsetX = _bounceLeftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bounceBottomBoundary) + { + realOffsetY = _bounceBottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX < 0.0f && touchOffsetY > 0.0f) // up left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _bounceRightBoundary) + { + realOffsetX = _bounceRightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bounceBottomBoundary) + { + realOffsetY = _bounceBottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX < 0.0f && touchOffsetY < 0.0f) // down left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _bounceRightBoundary) + { + realOffsetX = _bounceRightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _bounceTopBoundary) + { + realOffsetY = _bounceTopBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX > 0.0f && touchOffsetY < 0.0f) // down right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _bounceLeftBoundary) + { + realOffsetX = _bounceLeftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _bounceTopBoundary) + { + realOffsetY = _bounceTopBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX == 0.0f && touchOffsetY > 0.0f) // up + { + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bounceBottomBoundary) + { + realOffsetY = _bounceBottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX < 0.0f && touchOffsetY == 0.0f) // left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _bounceRightBoundary) + { + realOffsetX = _bounceRightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX == 0.0f && touchOffsetY < 0.0f) // down + { + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _bounceTopBoundary) + { + realOffsetY = _bounceTopBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX > 0.0f && touchOffsetY == 0.0f) // right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _bounceLeftBoundary) + { + realOffsetX = _bounceLeftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + } + } + else + { + if (touchOffsetX > 0.0f && touchOffsetY > 0.0f) // up right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _leftBoundary) + { + realOffsetX = _leftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bottomBoundary) + { + realOffsetY = _bottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX < 0.0f && touchOffsetY > 0.0f) // up left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _rightBoundary) + { + realOffsetX = _rightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bottomBoundary) + { + realOffsetY = _bottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX < 0.0f && touchOffsetY < 0.0f) // down left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _rightBoundary) + { + realOffsetX = _rightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _topBoundary) + { + realOffsetY = _topBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX > 0.0f && touchOffsetY < 0.0f) // down right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _leftBoundary) + { + realOffsetX = _leftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _topBoundary) + { + realOffsetY = _topBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX == 0.0f && touchOffsetY > 0.0f) // up + { + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bottomBoundary) + { + realOffsetY = _bottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX < 0.0f && touchOffsetY == 0.0f) // left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _rightBoundary) + { + realOffsetX = _rightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX == 0.0f && touchOffsetY < 0.0f) // down + { + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _topBoundary) + { + realOffsetY = _topBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX > 0.0f && touchOffsetY == 0.0f) // right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _leftBoundary) + { + realOffsetX = _leftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + } + } + moveChildren(realOffsetX, realOffsetY); + break; + } + default: + break; + } + return scrollenabled; } -void UIScrollView::scrollToTop() +void UIScrollView::scrollToBottom(float time, bool attenuated) { - _moveDirection = SCROLLVIEW_MOVE_DIR_DOWN; // down - scrollChildren(-_innerContainer->getSize().height); + startAutoScrollChildrenWithDestination(cocos2d::Point(_innerContainer->getPosition().x, 0.0f), time, attenuated); +} + +void UIScrollView::scrollToTop(float time, bool attenuated) +{ + startAutoScrollChildrenWithDestination(cocos2d::Point(_innerContainer->getPosition().x, _size.height - _innerContainer->getSize().height), time, attenuated); +} + +void UIScrollView::scrollToLeft(float time, bool attenuated) +{ + startAutoScrollChildrenWithDestination(cocos2d::Point(0.0f, _innerContainer->getPosition().y), time, attenuated); +} + +void UIScrollView::scrollToRight(float time, bool attenuated) +{ + startAutoScrollChildrenWithDestination(cocos2d::Point(_size.width - _innerContainer->getSize().width, _innerContainer->getPosition().y), time, attenuated); +} + +void UIScrollView::scrollToTopLeft(float time, bool attenuated) +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + startAutoScrollChildrenWithDestination(cocos2d::Point(0.0f, _size.height - _innerContainer->getSize().height), time, attenuated); +} + +void UIScrollView::scrollToTopRight(float time, bool attenuated) +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + startAutoScrollChildrenWithDestination(cocos2d::Point(_size.width - _innerContainer->getSize().width, _size.height - _innerContainer->getSize().height), time, attenuated); +} + +void UIScrollView::scrollToBottomLeft(float time, bool attenuated) +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + startAutoScrollChildrenWithDestination(cocos2d::Point::ZERO, time, attenuated); +} + +void UIScrollView::scrollToBottomRight(float time, bool attenuated) +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + startAutoScrollChildrenWithDestination(cocos2d::Point(_size.width - _innerContainer->getSize().width, 0.0f), time, attenuated); +} + +void UIScrollView::scrollToPercentVertical(float percent, float time, bool attenuated) +{ + float minY = _size.height - _innerContainer->getSize().height; + float h = - minY; + startAutoScrollChildrenWithDestination(cocos2d::Point(_innerContainer->getPosition().x, minY + percent * h / 100.0f), time, attenuated); +} + +void UIScrollView::scrollToPercentHorizontal(float percent, float time, bool attenuated) +{ + float w = _innerContainer->getSize().width - _size.width; + startAutoScrollChildrenWithDestination(cocos2d::Point(-(percent * w / 100.0f), _innerContainer->getPosition().y), time, attenuated); +} + +void UIScrollView::scrollToPercentBothDirection(const cocos2d::Point& percent, float time, bool attenuated) +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + return; + } + float minY = _size.height - _innerContainer->getSize().height; + float h = - minY; + float w = _innerContainer->getSize().width - _size.width; + startAutoScrollChildrenWithDestination(cocos2d::Point(-(percent.x * w / 100.0f), minY + percent.y * h / 100.0f), time, attenuated); +} + +void UIScrollView::jumpToBottom() +{ + jumpToDestination(cocos2d::Point(_innerContainer->getPosition().x, 0.0f)); +} + +void UIScrollView::jumpToTop() +{ + jumpToDestination(cocos2d::Point(_innerContainer->getPosition().x, _size.height - _innerContainer->getSize().height)); +} + +void UIScrollView::jumpToLeft() +{ + jumpToDestination(cocos2d::Point(0.0f, _innerContainer->getPosition().y)); +} + +void UIScrollView::jumpToRight() +{ + jumpToDestination(cocos2d::Point(_size.width - _innerContainer->getSize().width, _innerContainer->getPosition().y)); +} + +void UIScrollView::jumpToTopLeft() +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + jumpToDestination(cocos2d::Point(0.0f, _size.height - _innerContainer->getSize().height)); +} + +void UIScrollView::jumpToTopRight() +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + jumpToDestination(cocos2d::Point(_size.width - _innerContainer->getSize().width, _size.height - _innerContainer->getSize().height)); +} + +void UIScrollView::jumpToBottomLeft() +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + jumpToDestination(cocos2d::Point::ZERO); +} + +void UIScrollView::jumpToBottomRight() +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + jumpToDestination(cocos2d::Point(_size.width - _innerContainer->getSize().width, 0.0f)); +} + +void UIScrollView::jumpToPercentVertical(float percent) +{ + float minY = _size.height - _innerContainer->getSize().height; + float h = - minY; + jumpToDestination(cocos2d::Point(_innerContainer->getPosition().x, minY + percent * h / 100.0f)); +} + +void UIScrollView::jumpToPercentHorizontal(float percent) +{ + float w = _innerContainer->getSize().width - _size.width; + jumpToDestination(cocos2d::Point(-(percent * w / 100.0f), _innerContainer->getPosition().y)); +} + +void UIScrollView::jumpToPercentBothDirection(const cocos2d::Point& percent) +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + return; + } + float minY = _size.height - _innerContainer->getSize().height; + float h = - minY; + float w = _innerContainer->getSize().width - _size.width; + jumpToDestination(cocos2d::Point(-(percent.x * w / 100.0f), minY + percent.y * h / 100.0f)); } void UIScrollView::startRecordSlidAction() { - if (_children->count() <= 0) + if (_autoScroll) { - return; - } - if (_autoScroll){ stopAutoScrollChildren(); } - _bePressed = true; - _slidTime = 0.0; + if (_bouncing) + { + stopBounceChildren(); + } + _slidTime = 0.0f; } void UIScrollView::endRecordSlidAction() { - if (_children->count() <= 0) + if (!checkNeedBounce() && _inertiaScrollEnabled) { - return; + if (_slidTime <= 0.016f) + { + return; + } + float totalDis = 0.0f; + cocos2d::Point dir; + switch (_direction) + { + case SCROLLVIEW_DIR_VERTICAL: + totalDis = _touchEndedPoint.y - _touchBeganPoint.y; + if (totalDis < 0.0f) + { + dir = SCROLLDIR_DOWN; + } + else + { + dir = SCROLLDIR_UP; + } + break; + case SCROLLVIEW_DIR_HORIZONTAL: + totalDis = _touchEndedPoint.x - _touchBeganPoint.x; + if (totalDis < 0.0f) + { + dir = SCROLLDIR_LEFT; + } + else + { + dir = SCROLLDIR_RIGHT; + } + break; + case SCROLLVIEW_DIR_BOTH: + { + cocos2d::Point subVector = _touchEndedPoint - _touchBeganPoint; + totalDis = subVector.getLength(); + dir = subVector.normalize(); + break; + } + default: + break; + } + float orSpeed = MIN(fabs(totalDis)/(_slidTime), AUTOSCROLLMAXSPEED); + startAutoScrollChildrenWithOriginalSpeed(dir, orSpeed, true, -1000); + _slidTime = 0.0f; } - if (_slidTime <= 0.016f) - { - return; - } - float totalDis = 0; - totalDis = _touchEndLocation-_touchStartLocation; - float orSpeed = fabs(totalDis)/(_slidTime); - startAutoScrollChildren(orSpeed); - - _bePressed = false; - _slidTime = 0.0; } -void UIScrollView::handlePressLogic(const Point &touchPoint) +void UIScrollView::handlePressLogic(const cocos2d::Point &touchPoint) { - Point nsp = _renderer->convertToNodeSpace(touchPoint); - switch (_direction) - { - case SCROLLVIEW_DIR_VERTICAL: // vertical - _touchMoveStartLocation = nsp.y; - _touchStartLocation = nsp.y; - break; - case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - _touchMoveStartLocation = nsp.x; - _touchStartLocation = nsp.x; - break; - default: - break; - } + _touchBeganPoint = _renderer->convertToNodeSpace(touchPoint); + _touchMovingPoint = _touchBeganPoint; startRecordSlidAction(); + _bePressed = true; } -void UIScrollView::handleMoveLogic(const Point &touchPoint) +void UIScrollView::handleMoveLogic(const cocos2d::Point &touchPoint) { - Point nsp = _renderer->convertToNodeSpace(touchPoint); - float offset = 0.0f; - + _touchMovedPoint = _renderer->convertToNodeSpace(touchPoint); + cocos2d::Point delta = _touchMovedPoint - _touchMovingPoint; + _touchMovingPoint = _touchMovedPoint; switch (_direction) { case SCROLLVIEW_DIR_VERTICAL: // vertical - { - float moveY = nsp.y; - offset = moveY - _touchMoveStartLocation; - _touchMoveStartLocation = moveY; - - if (offset < 0.0f) - { - _moveDirection = SCROLLVIEW_MOVE_DIR_DOWN; // down - } - else if (offset > 0.0f) - { - _moveDirection = SCROLLVIEW_MOVE_DIR_UP; // up - } - } + { + scrollChildren(0.0f, delta.y); break; - + } case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - { - float moveX = nsp.x; - offset = moveX - _touchMoveStartLocation; - _touchMoveStartLocation = moveX; - - if (offset < 0) - { - _moveDirection = SCROLLVIEW_MOVE_DIR_LEFT; // left - } - else if (offset > 0) - { - _moveDirection = SCROLLVIEW_MOVE_DIR_RIGHT; // right - } - } + { + scrollChildren(delta.x, 0.0f); break; - + } + case SCROLLVIEW_DIR_BOTH: // both + { + scrollChildren(delta.x, delta.y); + break; + } default: break; } - scrollChildren(offset); } -void UIScrollView::handleReleaseLogic(const Point &touchPoint) +void UIScrollView::handleReleaseLogic(const cocos2d::Point &touchPoint) { - Point nsp = _renderer->convertToNodeSpace(touchPoint); - switch (_direction) - { - case SCROLLVIEW_DIR_VERTICAL: // vertical - _touchEndLocation = nsp.y; - break; - - case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - _touchEndLocation = nsp.x; - break; - - default: - break; - } + _touchEndedPoint = _renderer->convertToNodeSpace(touchPoint); endRecordSlidAction(); + _bePressed = false; } -bool UIScrollView::onTouchBegan(const Point &touchPoint) +bool UIScrollView::onTouchBegan(const cocos2d::Point &touchPoint) { - bool pass = Layout::onTouchBegan(touchPoint); + bool pass = UILayout::onTouchBegan(touchPoint); handlePressLogic(touchPoint); return pass; } -void UIScrollView::onTouchMoved(const Point &touchPoint) +void UIScrollView::onTouchMoved(const cocos2d::Point &touchPoint) { - Layout::onTouchMoved(touchPoint); + UILayout::onTouchMoved(touchPoint); handleMoveLogic(touchPoint); } -void UIScrollView::onTouchEnded(const Point &touchPoint) +void UIScrollView::onTouchEnded(const cocos2d::Point &touchPoint) { - Layout::onTouchEnded(touchPoint); + UILayout::onTouchEnded(touchPoint); handleReleaseLogic(touchPoint); } -void UIScrollView::onTouchCancelled(const Point &touchPoint) +void UIScrollView::onTouchCancelled(const cocos2d::Point &touchPoint) { - Layout::onTouchCancelled(touchPoint); + UILayout::onTouchCancelled(touchPoint); + handleReleaseLogic(touchPoint); } -void UIScrollView::onTouchLongClicked(const Point &touchPoint) +void UIScrollView::onTouchLongClicked(const cocos2d::Point &touchPoint) { } @@ -546,6 +1407,10 @@ void UIScrollView::update(float dt) { autoScrollChildren(dt); } + if (_bouncing) + { + bounceChildren(dt); + } recordSlidTime(dt); } @@ -557,7 +1422,7 @@ void UIScrollView::recordSlidTime(float dt) } } -void UIScrollView::interceptTouchEvent(int handleState, UIWidget *sender, const Point &touchPoint) +void UIScrollView::interceptTouchEvent(int handleState, UIWidget *sender, const cocos2d::Point &touchPoint) { switch (handleState) { @@ -567,20 +1432,7 @@ void UIScrollView::interceptTouchEvent(int handleState, UIWidget *sender, const case 1: { - float offset = 0; - switch (_direction) - { - case SCROLLVIEW_DIR_VERTICAL: // vertical - offset = fabs(sender->getTouchStartPos().y - touchPoint.y); - break; - - case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - offset = fabs(sender->getTouchStartPos().x - touchPoint.x); - break; - - default: - break; - } + float offset = (sender->getTouchStartPos() - touchPoint).getLength(); if (offset > _childFocusCancelOffset) { sender->setFocused(false); @@ -594,11 +1446,12 @@ void UIScrollView::interceptTouchEvent(int handleState, UIWidget *sender, const break; case 3: + handleReleaseLogic(touchPoint); break; } } -void UIScrollView::checkChildInfo(int handleState,UIWidget* sender,const Point &touchPoint) +void UIScrollView::checkChildInfo(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint) { interceptTouchEvent(handleState, sender, touchPoint); } @@ -635,7 +1488,47 @@ void UIScrollView::scrollToRightEvent() } } -void UIScrollView::addEventListener(Object *target, SEL_ScrollViewEvent selector) +void UIScrollView::scrollingEvent() +{ + if (_eventListener && _eventSelector) + { + (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_SCROLLING); + } +} + +void UIScrollView::bounceTopEvent() +{ + if (_eventListener && _eventSelector) + { + (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_TOP); + } +} + +void UIScrollView::bounceBottomEvent() +{ + if (_eventListener && _eventSelector) + { + (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_BOTTOM); + } +} + +void UIScrollView::bounceLeftEvent() +{ + if (_eventListener && _eventSelector) + { + (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_LEFT); + } +} + +void UIScrollView::bounceRightEvent() +{ + if (_eventListener && _eventSelector) + { + (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_RIGHT); + } +} + +void UIScrollView::addEventListener(cocos2d::Object *target, SEL_ScrollViewEvent selector) { _eventListener = target; _eventSelector = selector; @@ -651,17 +1544,27 @@ SCROLLVIEW_DIR UIScrollView::getDirection() return _direction; } -void UIScrollView::setMoveDirection(SCROLLVIEW_MOVE_DIR dir) +void UIScrollView::setBounceEnabled(bool enabled) { - _moveDirection = dir; + _bounceEnabled = enabled; } -SCROLLVIEW_MOVE_DIR UIScrollView::getMoveDirection() +bool UIScrollView::isBounceEnabled() const { - return _moveDirection; + return _bounceEnabled; } -Layout* UIScrollView::getInnerContainer() +void UIScrollView::setInertiaScrollEnabled(bool enabled) +{ + _inertiaScrollEnabled = enabled; +} + +bool UIScrollView::isInertiaScrollEnabled() const +{ + return _inertiaScrollEnabled; +} + +UILayout* UIScrollView::getInnerContainer() { return _innerContainer; } @@ -686,4 +1589,27 @@ const char* UIScrollView::getDescription() const return "ScrollView"; } +UIWidget* UIScrollView::createCloneInstance() +{ + return UIScrollView::create(); +} + +void UIScrollView::copyClonedWidgetChildren(UIWidget* model) +{ + UILayout::copyClonedWidgetChildren(model); +} + +void UIScrollView::copySpecialProperties(UIWidget *widget) +{ + UIScrollView* scrollView = dynamic_cast(widget); + if (scrollView) + { + UILayout::copySpecialProperties(widget); + setInnerContainerSize(scrollView->getInnerContainerSize()); + setDirection(scrollView->_direction); + setBounceEnabled(scrollView->_bounceEnabled); + setInertiaScrollEnabled(scrollView->_inertiaScrollEnabled); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UIScrollView.h b/cocos/gui/UIScrollView.h index 1a6cf31f99..4d762930f8 100644 --- a/cocos/gui/UIScrollView.h +++ b/cocos/gui/UIScrollView.h @@ -25,7 +25,7 @@ #ifndef __UISCROLLVIEW_H__ #define __UISCROLLVIEW_H__ -#include "gui//Layout.h" +#include "gui/UILayout.h" #include "gui/UIScrollInterface.h" namespace gui { @@ -34,16 +34,8 @@ enum SCROLLVIEW_DIR { SCROLLVIEW_DIR_NONE, SCROLLVIEW_DIR_VERTICAL, - SCROLLVIEW_DIR_HORIZONTAL -}; - -enum SCROLLVIEW_MOVE_DIR -{ - SCROLLVIEW_MOVE_DIR_NONE, - SCROLLVIEW_MOVE_DIR_UP, - SCROLLVIEW_MOVE_DIR_DOWN, - SCROLLVIEW_MOVE_DIR_LEFT, - SCROLLVIEW_MOVE_DIR_RIGHT, + SCROLLVIEW_DIR_HORIZONTAL, + SCROLLVIEW_DIR_BOTH }; typedef enum @@ -52,13 +44,18 @@ typedef enum SCROLLVIEW_EVENT_SCROLL_TO_BOTTOM, SCROLLVIEW_EVENT_SCROLL_TO_LEFT, SCROLLVIEW_EVENT_SCROLL_TO_RIGHT, + SCROLLVIEW_EVENT_SCROLLING, + SCROLLVIEW_EVENT_BOUNCE_TOP, + SCROLLVIEW_EVENT_BOUNCE_BOTTOM, + SCROLLVIEW_EVENT_BOUNCE_LEFT, + SCROLLVIEW_EVENT_BOUNCE_RIGHT }ScrollviewEventType; -typedef void (cocos2d::Object::*SEL_ScrollViewEvent)(cocos2d::Object*, ScrollviewEventType); +typedef void (cocos2d::CCObject::*SEL_ScrollViewEvent)(cocos2d::Object*, ScrollviewEventType); #define scrollvieweventselector(_SELECTOR) (SEL_ScrollViewEvent)(&_SELECTOR) -class UIScrollView : public Layout , public UIScrollInterface +class UIScrollView : public UILayout , public UIScrollInterface { public: /** @@ -83,7 +80,7 @@ public: * * @param SCROLLVIEW_DIR */ - void setDirection(SCROLLVIEW_DIR dir); + virtual void setDirection(SCROLLVIEW_DIR dir); /** * Gets scroll direction of scrollview. @@ -101,17 +98,117 @@ public: * * @return inner container. */ - Layout* getInnerContainer(); + UILayout* getInnerContainer(); /** * Scroll inner container to bottom boundary of scrollview. */ - void scrollToBottom(); + void scrollToBottom(float time, bool attenuated); /** * Scroll inner container to top boundary of scrollview. */ - void scrollToTop(); + void scrollToTop(float time, bool attenuated); + + /** + * Scroll inner container to left boundary of scrollview. + */ + void scrollToLeft(float time, bool attenuated); + + /** + * Scroll inner container to right boundary of scrollview. + */ + void scrollToRight(float time, bool attenuated); + + /** + * Scroll inner container to top and left boundary of scrollview. + */ + void scrollToTopLeft(float time, bool attenuated); + + /** + * Scroll inner container to top and right boundary of scrollview. + */ + void scrollToTopRight(float time, bool attenuated); + + /** + * Scroll inner container to bottom and left boundary of scrollview. + */ + void scrollToBottomLeft(float time, bool attenuated); + + /** + * Scroll inner container to bottom and right boundary of scrollview. + */ + void scrollToBottomRight(float time, bool attenuated); + + /** + * Scroll inner container to vertical percent position of scrollview. + */ + void scrollToPercentVertical(float percent, float time, bool attenuated); + + /** + * Scroll inner container to horizontal percent position of scrollview. + */ + void scrollToPercentHorizontal(float percent, float time, bool attenuated); + + /** + * Scroll inner container to both direction percent position of scrollview. + */ + void scrollToPercentBothDirection(const cocos2d::Point& percent, float time, bool attenuated); + + /** + * Move inner container to bottom boundary of scrollview. + */ + void jumpToBottom(); + + /** + * Move inner container to top boundary of scrollview. + */ + void jumpToTop(); + + /** + * Move inner container to left boundary of scrollview. + */ + void jumpToLeft(); + + /** + * Move inner container to right boundary of scrollview. + */ + void jumpToRight(); + + /** + * Move inner container to top and left boundary of scrollview. + */ + void jumpToTopLeft(); + + /** + * Move inner container to top and right boundary of scrollview. + */ + void jumpToTopRight(); + + /** + * Move inner container to bottom and left boundary of scrollview. + */ + void jumpToBottomLeft(); + + /** + * Move inner container to bottom and right boundary of scrollview. + */ + void jumpToBottomRight(); + + /** + * Move inner container to vertical percent position of scrollview. + */ + void jumpToPercentVertical(float percent); + + /** + * Move inner container to horizontal percent position of scrollview. + */ + void jumpToPercentHorizontal(float percent); + + /** + * Move inner container to both direction percent position of scrollview. + */ + void jumpToPercentBothDirection(const cocos2d::Point& percent); /** * Changes inner container size of scrollview. @@ -134,7 +231,7 @@ public: /** * Add call back function called scrollview event triggered */ - void addEventListener(cocos2d::Object* target, SEL_ScrollViewEvent selector); + void addEventListener(cocos2d::Object* target, SEL_ScrollViewEvent selector); //override "addChild" method of widget. virtual bool addChild(UIWidget* widget); @@ -165,6 +262,14 @@ public: virtual void update(float dt); + void setBounceEnabled(bool enabled); + + bool isBounceEnabled() const; + + void setInertiaScrollEnabled(bool enabled); + + bool isInertiaScrollEnabled() const; + /** * Sets LayoutType. * @@ -192,12 +297,20 @@ public: protected: virtual bool init(); virtual void initRenderer(); - void moveChildren(float offset); + void moveChildren(float offsetX, float offsetY); void autoScrollChildren(float dt); - void startAutoScrollChildren(float v); + void bounceChildren(float dt); + void checkBounceBoundary(); + bool checkNeedBounce(); + void startAutoScrollChildrenWithOriginalSpeed(const cocos2d::Point& dir, float v, bool attenuated, float acceleration); + void startAutoScrollChildrenWithDestination(const cocos2d::Point& des, float time, bool attenuated); + void jumpToDestination(const cocos2d::Point& des); void stopAutoScrollChildren(); - float getCurAutoScrollDistance(float time); - virtual bool scrollChildren(float touchOffset); + void startBounceChildren(float v); + void stopBounceChildren(); + bool checkCustomScrollDestination(float* touchOffsetX, float* touchOffsetY); + virtual bool scrollChildren(float touchOffsetX, float touchOffsetY); + bool bounceScrollChildren(float touchOffsetX, float touchOffsetY); void startRecordSlidAction(); virtual void endRecordSlidAction(); virtual void handlePressLogic(const cocos2d::Point &touchPoint); @@ -206,48 +319,71 @@ protected: virtual void interceptTouchEvent(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint); virtual void checkChildInfo(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint); void recordSlidTime(float dt); - //override "releaseResoures" method of widget. - virtual void releaseResoures(); - void scrollToTopEvent(); void scrollToBottomEvent(); void scrollToLeftEvent(); void scrollToRightEvent(); - void setMoveDirection(SCROLLVIEW_MOVE_DIR dir); - SCROLLVIEW_MOVE_DIR getMoveDirection(); + void scrollingEvent(); + void bounceTopEvent(); + void bounceBottomEvent(); + void bounceLeftEvent(); + void bounceRightEvent(); virtual void onSizeChanged(); - virtual void setClippingEnabled(bool able){Layout::setClippingEnabled(able);}; + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); + virtual void copyClonedWidgetChildren(UIWidget* model); + virtual void setClippingEnabled(bool able){UILayout::setClippingEnabled(able);}; protected: - Layout* _innerContainer; + UILayout* _innerContainer; SCROLLVIEW_DIR _direction; - SCROLLVIEW_MOVE_DIR _moveDirection; - float _touchStartLocation; - float _touchEndLocation; - float _touchMoveStartLocation; - float _topBoundary;//test - float _bottomBoundary;//test + + cocos2d::Point _touchBeganPoint; + cocos2d::Point _touchMovedPoint; + cocos2d::Point _touchEndedPoint; + cocos2d::Point _touchMovingPoint; + cocos2d::Point _autoScrollDir; + + float _topBoundary; + float _bottomBoundary; float _leftBoundary; float _rightBoundary; - bool _topEnd; - bool _bottomEnd; - bool _leftEnd; - bool _rightEnd; + float _bounceTopBoundary; + float _bounceBottomBoundary; + float _bounceLeftBoundary; + float _bounceRightBoundary; + bool _autoScroll; + float _autoScrollAddUpTime; float _autoScrollOriginalSpeed; float _autoScrollAcceleration; + bool _isAutoScrollSpeedAttenuated; + bool _needCheckAutoScrollDestination; + cocos2d::Point _autoScrollDestination; bool _bePressed; float _slidTime; cocos2d::Point _moveChildPoint; float _childFocusCancelOffset; + bool _leftBounceNeeded; + bool _topBounceNeeded; + bool _rightBounceNeeded; + bool _bottomBounceNeeded; + + bool _bounceEnabled; + bool _bouncing; + cocos2d::Point _bounceDir; + float _bounceOriginalSpeed; + bool _inertiaScrollEnabled; + + + cocos2d::Object* _eventListener; SEL_ScrollViewEvent _eventSelector; - }; } diff --git a/cocos/gui/UISlider.cpp b/cocos/gui/UISlider.cpp index 425fc581e0..b5c90ccfb8 100644 --- a/cocos/gui/UISlider.cpp +++ b/cocos/gui/UISlider.cpp @@ -25,15 +25,12 @@ #include "gui/UISlider.h" #include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" -using namespace cocos2d; -using namespace cocos2d::extension; - namespace gui { UISlider::UISlider(): _barRenderer(NULL), _progressBarRenderer(NULL), -_progressBarTextureSize(Size::ZERO), +_progressBarTextureSize(cocos2d::Size::ZERO), _slidBallNormalRenderer(NULL), _slidBallPressedRenderer(NULL), _slidBallDisabledRenderer(NULL), @@ -47,8 +44,8 @@ _progressBarTextureFile(""), _slidBallNormalTextureFile(""), _slidBallPressedTextureFile(""), _slidBallDisabledTextureFile(""), -_capInsetsBarRenderer(Rect::ZERO), -_capInsetsProgressBarRenderer(Rect::ZERO), +_capInsetsBarRenderer(cocos2d::Rect::ZERO), +_capInsetsProgressBarRenderer(cocos2d::Rect::ZERO), _slidPercentListener(NULL), _slidPercentSelector(NULL), _barTexType(UI_TEX_TYPE_LOCAL), @@ -61,7 +58,8 @@ _ballDTexType(UI_TEX_TYPE_LOCAL) UISlider::~UISlider() { - + _slidPercentListener = NULL; + _slidPercentSelector = NULL; } UISlider* UISlider::create() @@ -79,17 +77,17 @@ UISlider* UISlider::create() void UISlider::initRenderer() { UIWidget::initRenderer(); - _barRenderer = CCSprite::create(); - _progressBarRenderer = CCSprite::create(); - _progressBarRenderer->setAnchorPoint(Point(0.0f, 0.5f)); + _barRenderer = cocos2d::Sprite::create(); + _progressBarRenderer = cocos2d::Sprite::create(); + _progressBarRenderer->setAnchorPoint(cocos2d::Point(0.0f, 0.5f)); _renderer->addChild(_barRenderer, -1); _renderer->addChild(_progressBarRenderer, -1); - _slidBallNormalRenderer = CCSprite::create(); - _slidBallPressedRenderer = CCSprite::create(); + _slidBallNormalRenderer = cocos2d::Sprite::create(); + _slidBallPressedRenderer = cocos2d::Sprite::create(); _slidBallPressedRenderer->setVisible(false); - _slidBallDisabledRenderer = CCSprite::create(); + _slidBallDisabledRenderer = cocos2d::Sprite::create(); _slidBallDisabledRenderer->setVisible(false); - _slidBallRenderer = CCNode::create(); + _slidBallRenderer = cocos2d::Node::create(); _slidBallRenderer->addChild(_slidBallNormalRenderer); _slidBallRenderer->addChild(_slidBallPressedRenderer); _slidBallRenderer->addChild(_slidBallDisabledRenderer); @@ -109,21 +107,21 @@ void UISlider::loadBarTexture(const char* fileName, TextureResType texType) case UI_TEX_TYPE_LOCAL: if (_scale9Enabled) { - dynamic_cast(_barRenderer)->initWithFile(fileName); + dynamic_cast(_barRenderer)->initWithFile(fileName); } else { - dynamic_cast(_barRenderer)->initWithFile(fileName); + dynamic_cast(_barRenderer)->initWithFile(fileName); } break; case UI_TEX_TYPE_PLIST: if (_scale9Enabled) { - dynamic_cast(_barRenderer)->initWithSpriteFrameName(fileName); + dynamic_cast(_barRenderer)->initWithSpriteFrameName(fileName); } else { - dynamic_cast(_barRenderer)->initWithSpriteFrameName(fileName); + dynamic_cast(_barRenderer)->initWithSpriteFrameName(fileName); } break; default: @@ -131,13 +129,13 @@ void UISlider::loadBarTexture(const char* fileName, TextureResType texType) } if (_scale9Enabled) { - dynamic_cast(_barRenderer)->setColor(getColor()); - dynamic_cast(_barRenderer)->setOpacity(getOpacity()); + dynamic_cast(_barRenderer)->setColor(getColor()); + dynamic_cast(_barRenderer)->setOpacity(getOpacity()); } else { - dynamic_cast(_barRenderer)->setColor(getColor()); - dynamic_cast(_barRenderer)->setOpacity(getOpacity()); + dynamic_cast(_barRenderer)->setColor(getColor()); + dynamic_cast(_barRenderer)->setOpacity(getOpacity()); } barRendererScaleChangedWithSize(); } @@ -155,21 +153,21 @@ void UISlider::loadProgressBarTexture(const char *fileName, TextureResType texTy case UI_TEX_TYPE_LOCAL: if (_scale9Enabled) { - dynamic_cast(_progressBarRenderer)->initWithFile(fileName); + dynamic_cast(_progressBarRenderer)->initWithFile(fileName); } else { - dynamic_cast(_progressBarRenderer)->initWithFile(fileName); + dynamic_cast(_progressBarRenderer)->initWithFile(fileName); } break; case UI_TEX_TYPE_PLIST: if (_scale9Enabled) { - dynamic_cast(_progressBarRenderer)->initWithSpriteFrameName(fileName); + dynamic_cast(_progressBarRenderer)->initWithSpriteFrameName(fileName); } else { - dynamic_cast(_progressBarRenderer)->initWithSpriteFrameName(fileName); + dynamic_cast(_progressBarRenderer)->initWithSpriteFrameName(fileName); } break; default: @@ -177,15 +175,15 @@ void UISlider::loadProgressBarTexture(const char *fileName, TextureResType texTy } if (_scale9Enabled) { - dynamic_cast(_progressBarRenderer)->setColor(getColor()); - dynamic_cast(_progressBarRenderer)->setOpacity(getOpacity()); + dynamic_cast(_progressBarRenderer)->setColor(getColor()); + dynamic_cast(_progressBarRenderer)->setOpacity(getOpacity()); } else { - dynamic_cast(_progressBarRenderer)->setColor(getColor()); - dynamic_cast(_progressBarRenderer)->setOpacity(getOpacity()); + dynamic_cast(_progressBarRenderer)->setColor(getColor()); + dynamic_cast(_progressBarRenderer)->setOpacity(getOpacity()); } - _progressBarRenderer->setAnchorPoint(Point(0.0f, 0.5f)); + _progressBarRenderer->setAnchorPoint(cocos2d::Point(0.0f, 0.5f)); _progressBarTextureSize = _progressBarRenderer->getContentSize(); progressBarRendererScaleChangedWithSize(); } @@ -204,13 +202,13 @@ void UISlider::setScale9Enabled(bool able) _progressBarRenderer = NULL; if (_scale9Enabled) { - _barRenderer = Scale9Sprite::create(); - _progressBarRenderer = Scale9Sprite::create(); + _barRenderer = cocos2d::extension::Scale9Sprite::create(); + _progressBarRenderer = cocos2d::extension::Scale9Sprite::create(); } else { - _barRenderer = CCSprite::create(); - _progressBarRenderer = CCSprite::create(); + _barRenderer = cocos2d::Sprite::create(); + _progressBarRenderer = cocos2d::Sprite::create(); } loadBarTexture(_textureFile.c_str(), _barTexType); loadProgressBarTexture(_progressBarTextureFile.c_str(), _progressBarTexType); @@ -239,30 +237,30 @@ void UISlider::ignoreContentAdaptWithSize(bool ignore) } } -void UISlider::setCapInsets(const Rect &capInsets) +void UISlider::setCapInsets(const cocos2d::Rect &capInsets) { setCapInsetsBarRenderer(capInsets); setCapInsetProgressBarRebderer(capInsets); } -void UISlider::setCapInsetsBarRenderer(const Rect &capInsets) +void UISlider::setCapInsetsBarRenderer(const cocos2d::Rect &capInsets) { _capInsetsBarRenderer = capInsets; if (!_scale9Enabled) { return; } - dynamic_cast(_barRenderer)->setCapInsets(capInsets); + dynamic_cast(_barRenderer)->setCapInsets(capInsets); } -void UISlider::setCapInsetProgressBarRebderer(const Rect &capInsets) +void UISlider::setCapInsetProgressBarRebderer(const cocos2d::Rect &capInsets) { _capInsetsProgressBarRenderer = capInsets; if (!_scale9Enabled) { return; } - dynamic_cast(_progressBarRenderer)->setCapInsets(capInsets); + dynamic_cast(_progressBarRenderer)->setCapInsets(capInsets); } void UISlider::loadSlidBallTextures(const char* normal,const char* pressed,const char* disabled,TextureResType texType) @@ -353,10 +351,10 @@ void UISlider::setPercent(int percent) } _percent = percent; float dis = _barLength*(percent/100.0f); - _slidBallRenderer->setPosition(Point(-_barLength/2.0f + dis, 0.0f)); + _slidBallRenderer->setPosition(cocos2d::Point(-_barLength/2.0f + dis, 0.0f)); if (_scale9Enabled) { - dynamic_cast(_progressBarRenderer)->setPreferredSize(Size(dis,_progressBarTextureSize.height)); + dynamic_cast(_progressBarRenderer)->setPreferredSize(cocos2d::Size(dis,_progressBarTextureSize.height)); } else { @@ -365,10 +363,10 @@ void UISlider::setPercent(int percent) { case UI_TEX_TYPE_PLIST: { - Sprite* barNode = dynamic_cast(_progressBarRenderer); + cocos2d::Sprite* barNode = dynamic_cast(_progressBarRenderer); if (barNode) { - Point to = barNode->getTextureRect().origin; + cocos2d::Point to = barNode->getTextureRect().origin; x = to.x; y = to.y; } @@ -377,33 +375,33 @@ void UISlider::setPercent(int percent) default: break; } - dynamic_cast(_progressBarRenderer)->setTextureRect(Rect(x, y, _progressBarTextureSize.width * (percent/100.0f), _progressBarTextureSize.height)); + dynamic_cast(_progressBarRenderer)->setTextureRect(cocos2d::Rect(x, y, _progressBarTextureSize.width * (percent/100.0f), _progressBarTextureSize.height)); } } -bool UISlider::onTouchBegan(const Point &touchPoint) +bool UISlider::onTouchBegan(const cocos2d::Point &touchPoint) { bool pass = UIWidget::onTouchBegan(touchPoint); - Point nsp = _renderer->convertToNodeSpace(touchPoint); + cocos2d::Point nsp = _renderer->convertToNodeSpace(touchPoint); setPercent(getPercentWithBallPos(nsp.x)); percentChangedEvent(); return pass; } -void UISlider::onTouchMoved(const Point &touchPoint) +void UISlider::onTouchMoved(const cocos2d::Point &touchPoint) { - Point nsp = _renderer->convertToNodeSpace(touchPoint); - _slidBallRenderer->setPosition(Point(nsp.x,0)); + cocos2d::Point nsp = _renderer->convertToNodeSpace(touchPoint); + _slidBallRenderer->setPosition(cocos2d::Point(nsp.x,0)); setPercent(getPercentWithBallPos(nsp.x)); percentChangedEvent(); } -void UISlider::onTouchEnded(const Point &touchPoint) +void UISlider::onTouchEnded(const cocos2d::Point &touchPoint) { UIWidget::onTouchEnded(touchPoint); } -void UISlider::onTouchCancelled(const Point &touchPoint) +void UISlider::onTouchCancelled(const cocos2d::Point &touchPoint) { UIWidget::onTouchCancelled(touchPoint); } @@ -413,7 +411,7 @@ float UISlider::getPercentWithBallPos(float px) return (((px-(-_barLength/2.0f))/_barLength)*100.0f); } -void UISlider::addEventListener(Object *target, SEL_SlidPercentChangedEvent selector) +void UISlider::addEventListener(cocos2d::Object *target, SEL_SlidPercentChangedEvent selector) { _slidPercentListener = target; _slidPercentSelector = selector; @@ -438,12 +436,12 @@ void UISlider::onSizeChanged() progressBarRendererScaleChangedWithSize(); } -const Size& UISlider::getContentSize() const +const cocos2d::Size& UISlider::getContentSize() const { return _barRenderer->getContentSize(); } -Node* UISlider::getVirtualRenderer() +cocos2d::Node* UISlider::getVirtualRenderer() { return _barRenderer; } @@ -462,11 +460,11 @@ void UISlider::barRendererScaleChangedWithSize() _barLength = _size.width; if (_scale9Enabled) { - dynamic_cast(_barRenderer)->setPreferredSize(_size); + dynamic_cast(_barRenderer)->setPreferredSize(_size); } else { - Size btextureSize = _barRenderer->getContentSize(); + cocos2d::Size btextureSize = _barRenderer->getContentSize(); if (btextureSize.width <= 0.0f || btextureSize.height <= 0.0f) { _barRenderer->setScale(1.0f); @@ -487,7 +485,7 @@ void UISlider::progressBarRendererScaleChangedWithSize() { if (!_scale9Enabled) { - Size ptextureSize = _progressBarTextureSize; + cocos2d::Size ptextureSize = _progressBarTextureSize; float pscaleX = _size.width / ptextureSize.width; float pscaleY = _size.height / ptextureSize.height; _progressBarRenderer->setScaleX(pscaleX); @@ -498,11 +496,11 @@ void UISlider::progressBarRendererScaleChangedWithSize() { if (_scale9Enabled) { - dynamic_cast(_progressBarRenderer)->setPreferredSize(_size); + dynamic_cast(_progressBarRenderer)->setPreferredSize(_size); } else { - Size ptextureSize = _progressBarTextureSize; + cocos2d::Size ptextureSize = _progressBarTextureSize; if (ptextureSize.width <= 0.0f || ptextureSize.height <= 0.0f) { _progressBarRenderer->setScale(1.0f); @@ -514,7 +512,7 @@ void UISlider::progressBarRendererScaleChangedWithSize() _progressBarRenderer->setScaleY(pscaleY); } } - _progressBarRenderer->setPosition(Point(-_barLength * 0.5f, 0.0f)); + _progressBarRenderer->setPosition(cocos2d::Point(-_barLength * 0.5f, 0.0f)); setPercent(_percent); } @@ -544,4 +542,25 @@ const char* UISlider::getDescription() const return "Slider"; } +UIWidget* UISlider::createCloneInstance() +{ + return UISlider::create(); +} + +void UISlider::copySpecialProperties(UIWidget *widget) +{ + UISlider* slider = dynamic_cast(widget); + if (slider) + { + _prevIgnoreSize = slider->_prevIgnoreSize; + setScale9Enabled(slider->_scale9Enabled); + loadBarTexture(slider->_textureFile.c_str(), slider->_barTexType); + loadProgressBarTexture(slider->_progressBarTextureFile.c_str(), slider->_progressBarTexType); + loadSlidBallTextureNormal(slider->_slidBallNormalTextureFile.c_str(), slider->_ballNTexType); + loadSlidBallTexturePressed(slider->_slidBallPressedTextureFile.c_str(), slider->_ballPTexType); + loadSlidBallTextureDisabled(slider->_slidBallDisabledTextureFile.c_str(), slider->_ballDTexType); + setPercent(slider->getPercent()); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UISlider.h b/cocos/gui/UISlider.h index 0654336600..186af44d45 100644 --- a/cocos/gui/UISlider.h +++ b/cocos/gui/UISlider.h @@ -34,9 +34,13 @@ typedef enum SLIDER_PERCENTCHANGED }SliderEventType; -typedef void (cocos2d::CCObject::*SEL_SlidPercentChangedEvent)(cocos2d::Object*,SliderEventType); +typedef void (cocos2d::Object::*SEL_SlidPercentChangedEvent)(cocos2d::Object*,SliderEventType); #define sliderpercentchangedselector(_SELECTOR) (SEL_SlidPercentChangedEvent)(&_SELECTOR) +/** +* @js NA +* @lua NA +*/ class UISlider : public UIWidget { public: @@ -185,6 +189,7 @@ public: * Returns the "class name" of widget. */ virtual const char* getDescription() const; + protected: virtual void initRenderer(); float getPercentWithBallPos(float location); @@ -195,6 +200,8 @@ protected: virtual void onSizeChanged(); void barRendererScaleChangedWithSize(); void progressBarRendererScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: cocos2d::Node* _barRenderer; cocos2d::Node* _progressBarRenderer; diff --git a/cocos/gui/UITextField.cpp b/cocos/gui/UITextField.cpp index 4e1365592d..6a95ac8605 100644 --- a/cocos/gui/UITextField.cpp +++ b/cocos/gui/UITextField.cpp @@ -24,19 +24,17 @@ #include "gui/UITextField.h" - using namespace cocos2d; - namespace gui { UICCTextField::UICCTextField() -: m_bMaxLengthEnabled(false) -, m_nMaxLength(0) -, m_bPasswordEnabled(false) -, m_strPasswordStyleText("*") -, m_bAttachWithIME(false) -, m_bDetachWithIME(false) -, m_bInsertText(false) -, m_bDeleteBackward(false) +: _maxLengthEnabled(false) +, _maxLength(0) +, _passwordEnabled(false) +, _passwordStyleText("*") +, _attachWithIME(false) +, _detachWithIME(false) +, _insertText(false) +, _deleteBackward(false) { } @@ -64,26 +62,26 @@ UICCTextField * UICCTextField::create(const char *placeholder, const char *fontN void UICCTextField::onEnter() { - CCTextFieldTTF::setDelegate(this); + cocos2d::TextFieldTTF::setDelegate(this); } -bool UICCTextField::onTextFieldAttachWithIME(TextFieldTTF *pSender) +bool UICCTextField::onTextFieldAttachWithIME(cocos2d::TextFieldTTF *pSender) { setAttachWithIME(true); return false; } -bool UICCTextField::onTextFieldInsertText(TextFieldTTF *pSender, const char *text, int nLen) +bool UICCTextField::onTextFieldInsertText(cocos2d::TextFieldTTF *pSender, const char *text, int nLen) { if (nLen == 1 && strcmp(text, "\n") == 0) { return false; } setInsertText(true); - if (m_bMaxLengthEnabled) + if (_maxLengthEnabled) { - if (CCTextFieldTTF::getCharCount() >= m_nMaxLength) + if (cocos2d::TextFieldTTF::getCharCount() >= _maxLength) { return true; } @@ -92,13 +90,13 @@ bool UICCTextField::onTextFieldInsertText(TextFieldTTF *pSender, const char *tex return false; } -bool UICCTextField::onTextFieldDeleteBackward(TextFieldTTF *pSender, const char *delText, int nLen) +bool UICCTextField::onTextFieldDeleteBackward(cocos2d::TextFieldTTF *pSender, const char *delText, int nLen) { setDeleteBackward(true); return false; } -bool UICCTextField::onTextFieldDetachWithIME(TextFieldTTF *pSender) +bool UICCTextField::onTextFieldDetachWithIME(cocos2d::TextFieldTTF *pSender) { setDetachWithIME(true); return false; @@ -107,11 +105,11 @@ bool UICCTextField::onTextFieldDetachWithIME(TextFieldTTF *pSender) void UICCTextField::insertText(const char * text, int len) { std::string str_text = text; - int str_len = strlen(CCTextFieldTTF::getString()); + int str_len = cocos2d::TextFieldTTF::getString().size(); if (strcmp(text, "\n") != 0) { - if (m_bMaxLengthEnabled) + if (_maxLengthEnabled) { int multiple = 1; char value = text[0]; @@ -120,89 +118,89 @@ void UICCTextField::insertText(const char * text, int len) multiple = 3; } - if (str_len + len > m_nMaxLength * multiple) + if (str_len + len > _maxLength * multiple) { - str_text = str_text.substr(0, m_nMaxLength * multiple); - len = m_nMaxLength * multiple; + str_text = str_text.substr(0, _maxLength * multiple); + len = _maxLength * multiple; /* int mod = str_len % 3; int offset = (mod == 0) ? 0 : (3 - mod); int amount = str_len + offset; - str_text = str_text.substr(0, m_nMaxLength - amount); + str_text = str_text.substr(0, _maxLength - amount); // CCLOG("str_test = %s", str_text.c_str()); */ } } } - CCTextFieldTTF::insertText(str_text.c_str(), len); + cocos2d::TextFieldTTF::insertText(str_text.c_str(), len); // password - if (m_bPasswordEnabled) + if (_passwordEnabled) { - if (CCTextFieldTTF::getCharCount() > 0) + if (cocos2d::TextFieldTTF::getCharCount() > 0) { - setPasswordText(_inputText->c_str()); + setPasswordText(_inputText.c_str()); } } } void UICCTextField::deleteBackward() { - CCTextFieldTTF::deleteBackward(); + cocos2d::TextFieldTTF::deleteBackward(); - if (CCTextFieldTTF::getCharCount() > 0) + if (cocos2d::TextFieldTTF::getCharCount() > 0) { // password - if (m_bPasswordEnabled) + if (_passwordEnabled) { - setPasswordText(_inputText->c_str()); + setPasswordText(_inputText.c_str()); } } } void UICCTextField::openIME() { - CCTextFieldTTF::attachWithIME(); + cocos2d::TextFieldTTF::attachWithIME(); } void UICCTextField::closeIME() { - CCTextFieldTTF::detachWithIME(); + cocos2d::TextFieldTTF::detachWithIME(); } void UICCTextField::setMaxLengthEnabled(bool enable) { - m_bMaxLengthEnabled = enable; + _maxLengthEnabled = enable; } bool UICCTextField::isMaxLengthEnabled() { - return m_bMaxLengthEnabled; + return _maxLengthEnabled; } void UICCTextField::setMaxLength(int length) { - m_nMaxLength = length; + _maxLength = length; } int UICCTextField::getMaxLength() { - return m_nMaxLength; + return _maxLength; } int UICCTextField::getCharCount() { - return CCTextFieldTTF::getCharCount(); + return cocos2d::TextFieldTTF::getCharCount(); } void UICCTextField::setPasswordEnabled(bool enable) { - m_bPasswordEnabled = enable; + _passwordEnabled = enable; } bool UICCTextField::isPasswordEnabled() { - return m_bPasswordEnabled; + return _passwordEnabled; } void UICCTextField::setPasswordStyleText(const char* styleText) @@ -216,7 +214,7 @@ void UICCTextField::setPasswordStyleText(const char* styleText) { return; } - m_strPasswordStyleText = styleText; + _passwordStyleText = styleText; } void UICCTextField::setPasswordText(const char *text) @@ -224,49 +222,49 @@ void UICCTextField::setPasswordText(const char *text) std::string tempStr; for (size_t i = 0; i < strlen(text); ++i) { - tempStr.append(m_strPasswordStyleText); + tempStr.append(_passwordStyleText); } - CCLabelTTF::setString(tempStr.c_str()); + cocos2d::LabelTTF::setString(tempStr.c_str()); } void UICCTextField::setAttachWithIME(bool attach) { - m_bAttachWithIME = attach; + _attachWithIME = attach; } bool UICCTextField::getAttachWithIME() { - return m_bAttachWithIME; + return _attachWithIME; } void UICCTextField::setDetachWithIME(bool detach) { - m_bDetachWithIME = detach; + _detachWithIME = detach; } bool UICCTextField::getDetachWithIME() { - return m_bDetachWithIME; + return _detachWithIME; } void UICCTextField::setInsertText(bool insert) { - m_bInsertText = insert; + _insertText = insert; } bool UICCTextField::getInsertText() { - return m_bInsertText; + return _insertText; } void UICCTextField::setDeleteBackward(bool deleteBackward) { - m_bDeleteBackward = deleteBackward; + _deleteBackward = deleteBackward; } bool UICCTextField::getDeleteBackward() { - return m_bDeleteBackward; + return _deleteBackward; } @@ -278,12 +276,15 @@ _touchWidth(0.0f), _touchHeight(0.0f), _useTouchArea(false), _eventListener(NULL), -_eventSelector(NULL) +_eventSelector(NULL), +_passwordStyleText("") { } UITextField::~UITextField() { + _eventListener = NULL; + _eventSelector = NULL; } UITextField* UITextField::create() @@ -315,25 +316,23 @@ void UITextField::initRenderer() _renderer->addChild(_textFieldRenderer); } -void UITextField::setTouchSize(const Size &size) +void UITextField::setTouchSize(const cocos2d::Size &size) { _useTouchArea = true; _touchWidth = size.width; _touchHeight = size.height; } -void UITextField::setText(const char* text) +void UITextField::setText(const std::string& text) { - if (!text) - { + if (text.size()==0) return; - } - std::string strText(text); - _textFieldRenderer->setString(strText.c_str()); + + _textFieldRenderer->setString(text); textfieldRendererScaleChangedWithSize(); } -void UITextField::setPlaceHolder(const char *value) +void UITextField::setPlaceHolder(const std::string& value) { _textFieldRenderer->setPlaceHolder(value); textfieldRendererScaleChangedWithSize(); @@ -345,7 +344,7 @@ void UITextField::setFontSize(int size) textfieldRendererScaleChangedWithSize(); } -void UITextField::setFontName(const char *name) +void UITextField::setFontName(const std::string& name) { _textFieldRenderer->setFontName(name); textfieldRendererScaleChangedWithSize(); @@ -356,12 +355,12 @@ void UITextField::didNotSelectSelf() _textFieldRenderer->detachWithIME(); } -const char* UITextField::getStringValue() +const std::string& UITextField::getStringValue() { return _textFieldRenderer->getString(); } -bool UITextField::onTouchBegan(const Point &touchPoint) +bool UITextField::onTouchBegan(const cocos2d::Point &touchPoint) { bool pass = UIWidget::onTouchBegan(touchPoint); _textFieldRenderer->attachWithIME(); @@ -401,6 +400,8 @@ bool UITextField::isPasswordEnabled() void UITextField::setPasswordStyleText(const char *styleText) { _textFieldRenderer->setPasswordStyleText(styleText); + + _passwordStyleText = styleText; } void UITextField::update(float dt) @@ -489,7 +490,7 @@ void UITextField::insertTextEvent() { if (_eventListener && _eventSelector) { - (_eventListener->*_eventSelector)(this, TEXTFIELD_EVENT_INDERT_TEXT); + (_eventListener->*_eventSelector)(this, TEXTFIELD_EVENT_INSERT_TEXT); } } @@ -501,19 +502,19 @@ void UITextField::deleteBackwardEvent() } } -void UITextField::addEventListener(Object *target, SEL_TextFieldEvent selecor) +void UITextField::addEventListener(cocos2d::Object *target, SEL_TextFieldEvent selecor) { _eventListener = target; _eventSelector = selecor; } -void UITextField::setAnchorPoint(const Point &pt) +void UITextField::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); _textFieldRenderer->setAnchorPoint(pt); } -void UITextField::setColor(const Color3B &color) +void UITextField::setColor(const cocos2d::Color3B &color) { UIWidget::setColor(color); _textFieldRenderer->setColor(color); @@ -539,7 +540,7 @@ void UITextField::textfieldRendererScaleChangedWithSize() } else { - Size textureSize = getContentSize(); + cocos2d::Size textureSize = getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _textFieldRenderer->setScale(1.0f); @@ -552,12 +553,12 @@ void UITextField::textfieldRendererScaleChangedWithSize() } } -const Size& UITextField::getContentSize() const +const cocos2d::Size& UITextField::getContentSize() const { return _textFieldRenderer->getContentSize(); } -Node* UITextField::getVirtualRenderer() +cocos2d::Node* UITextField::getVirtualRenderer() { return _textFieldRenderer; } @@ -567,4 +568,34 @@ const char* UITextField::getDescription() const return "TextField"; } +void UITextField::attachWithIME() +{ + _textFieldRenderer->attachWithIME(); +} + +UIWidget* UITextField::createCloneInstance() +{ + return UITextField::create(); +} + +void UITextField::copySpecialProperties(UIWidget *widget) +{ + UITextField* textField = dynamic_cast(widget); + if (textField) + { + setText(textField->_textFieldRenderer->getString()); + setPlaceHolder(textField->getStringValue()); + setFontSize(textField->_textFieldRenderer->getFontSize()); + setFontName(textField->_textFieldRenderer->getFontName().c_str()); + setMaxLengthEnabled(textField->isMaxLengthEnabled()); + setMaxLength(textField->getMaxLength()); + setPasswordEnabled(textField->isPasswordEnabled()); + setPasswordStyleText(textField->_passwordStyleText.c_str()); + setAttachWithIME(textField->getAttachWithIME()); + setDetachWithIME(textField->getDetachWithIME()); + setInsertText(textField->getInsertText()); + setDeleteBackward(textField->getDeleteBackward()); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UITextField.h b/cocos/gui/UITextField.h index 31b7052443..fc90ea9466 100644 --- a/cocos/gui/UITextField.h +++ b/cocos/gui/UITextField.h @@ -30,6 +30,10 @@ namespace gui { +/** + * @js NA + * @lua NA + */ class UICCTextField: public cocos2d::TextFieldTTF, public cocos2d::TextFieldDelegate { public: @@ -70,32 +74,32 @@ public: bool getInsertText(); void setDeleteBackward(bool deleteBackward); bool getDeleteBackward(); - - protected: - bool m_bMaxLengthEnabled; - int m_nMaxLength; - bool m_bPasswordEnabled; - std::string m_strPasswordStyleText; - bool m_bAttachWithIME; - bool m_bDetachWithIME; - bool m_bInsertText; - bool m_bDeleteBackward; + bool _maxLengthEnabled; + int _maxLength; + bool _passwordEnabled; + std::string _passwordStyleText; + bool _attachWithIME; + bool _detachWithIME; + bool _insertText; + bool _deleteBackward; }; - typedef enum { TEXTFIELD_EVENT_ATTACH_WITH_IME, TEXTFIELD_EVENT_DETACH_WITH_IME, - TEXTFIELD_EVENT_INDERT_TEXT, + TEXTFIELD_EVENT_INSERT_TEXT, TEXTFIELD_EVENT_DELETE_BACKWARD, }TextFiledEventType; typedef void (cocos2d::Object::*SEL_TextFieldEvent)(cocos2d::Object*, TextFiledEventType); #define textfieldeventselector(_SELECTOR) (SEL_TextFieldEvent)(&_SELECTOR) -//class UITextField : public UIWidget +/** class UITextField : public UIWidget +* @js NA +* @lua NA +*/ class UITextField : public UIWidget { public: @@ -105,12 +109,12 @@ public: virtual bool init(); virtual void initRenderer(); void setTouchSize(const cocos2d::Size &size); - void setText(const char* text); - void setPlaceHolder(const char* value); + void setText(const std::string& text); + void setPlaceHolder(const std::string& value); void setFontSize(int size); - void setFontName(const char* name); + void setFontName(const std::string& name); virtual void didNotSelectSelf(); - const char* getStringValue(); + const std::string& getStringValue(); virtual bool onTouchBegan(const cocos2d::Point &touchPoint); void setMaxLengthEnabled(bool enable); bool isMaxLengthEnabled(); @@ -129,22 +133,19 @@ public: bool getDeleteBackward(); void setDeleteBackward(bool deleteBackward); void addEventListener(cocos2d::Object* target, SEL_TextFieldEvent selecor); + virtual void setAnchorPoint(const cocos2d::Point &pt); virtual void setColor(const cocos2d::Color3B &color); virtual void setOpacity(int opacity); + /** * Returns the "class name" of widget. */ virtual const char* getDescription() const; - /*compatibel*/ - /** - * These methods will be removed - */ - void setMaxLengthEnable(bool is){setMaxLengthEnabled(is);}; - void setPasswordEnable(bool is){setPasswordEnabled(is);}; - /************/ + virtual const cocos2d::Size& getContentSize() const; virtual cocos2d::Node* getVirtualRenderer(); + void attachWithIME(); protected: // event void attachWithIMEEvent(); @@ -153,9 +154,11 @@ protected: void deleteBackwardEvent(); virtual void onSizeChanged(); void textfieldRendererScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: UICCTextField* _textFieldRenderer; - + float _touchWidth; float _touchHeight; bool _useTouchArea; @@ -163,6 +166,7 @@ protected: cocos2d::Object* _eventListener; SEL_TextFieldEvent _eventSelector; + std::string _passwordStyleText; }; } diff --git a/cocos/gui/UIWidget.cpp b/cocos/gui/UIWidget.cpp index ea9651582b..ad63b28451 100644 --- a/cocos/gui/UIWidget.cpp +++ b/cocos/gui/UIWidget.cpp @@ -24,11 +24,9 @@ #include "gui/UIWidget.h" #include "gui/UILayer.h" -#include "gui/Layout.h" +#include "gui/UILayout.h" #include "gui/UIHelper.h" - using namespace cocos2d; - namespace gui { #define DYNAMIC_CAST_CCBLENDPROTOCOL dynamic_cast(_renderer) @@ -45,42 +43,51 @@ _touchEnabled(false), _touchPassedEnabled(false), _focus(false), _widgetZOrder(0), -_anchorPoint(Point(0.5f, 0.5f)), +_anchorPoint(cocos2d::Point(0.5f, 0.5f)), _widgetParent(NULL), _brightStyle(BRIGHT_NONE), _updateEnabled(false), _renderer(NULL), -_touchStartPos(Point::ZERO), -_touchMovePos(Point::ZERO), -_touchEndPos(Point::ZERO), +_touchStartPos(cocos2d::Point::ZERO), +_touchMovePos(cocos2d::Point::ZERO), +_touchEndPos(cocos2d::Point::ZERO), _touchEventListener(NULL), _touchEventSelector(NULL), _widgetTag(-1), _name("default"), _widgetType(WidgetTypeWidget), _actionTag(0), -_size(Size::ZERO), -_customSize(Size::ZERO), -_layoutParameter(NULL), +_size(cocos2d::Size::ZERO), +_customSize(cocos2d::Size::ZERO), +_layoutParameterDictionary(NULL), _ignoreSize(false), _children(NULL), _affectByClipping(false), _scheduler(NULL), _sizeType(SIZE_ABSOLUTE), -_sizePercent(Point::ZERO), +_sizePercent(cocos2d::Point::ZERO), _positionType(POSITION_ABSOLUTE), -_positionPercent(Point::ZERO), -_isRunning(false) +_positionPercent(cocos2d::Point::ZERO), +_isRunning(false), +_userObject(NULL) { } UIWidget::~UIWidget() { - releaseResoures(); + _touchEventListener = NULL; + _touchEventSelector = NULL; + removeAllChildren(); + _children->release(); + _renderer->removeAllChildrenWithCleanup(true); + _renderer->removeFromParentAndCleanup(true); + _renderer->release(); setParent(NULL); - CC_SAFE_RELEASE_NULL(_layoutParameter); + _layoutParameterDictionary->removeAllObjects(); + CC_SAFE_RELEASE(_layoutParameterDictionary); CC_SAFE_RELEASE(_scheduler); + CC_SAFE_RELEASE(_userObject); } UIWidget* UIWidget::create() @@ -97,12 +104,14 @@ UIWidget* UIWidget::create() bool UIWidget::init() { - _children = Array::create(); + _children = cocos2d::Array::create(); _children->retain(); + _layoutParameterDictionary = cocos2d::Dictionary::create(); + CC_SAFE_RETAIN(_layoutParameterDictionary); initRenderer(); _renderer->retain(); _renderer->setZOrder(_widgetZOrder); - RGBAProtocol* renderRGBA = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* renderRGBA = DYNAMIC_CAST_CCRGBAPROTOCOL; if (renderRGBA) { renderRGBA->setCascadeColorEnabled(true); @@ -110,21 +119,11 @@ bool UIWidget::init() } setBright(true); ignoreContentAdaptWithSize(true); - _scheduler = Director::getInstance()->getScheduler(); + _scheduler = cocos2d::Director::getInstance()->getScheduler(); CC_SAFE_RETAIN(_scheduler); return true; } -void UIWidget::releaseResoures() -{ - setUpdateEnabled(false); - removeAllChildren(); - _children->release(); - _renderer->removeAllChildrenWithCleanup(true); - _renderer->removeFromParentAndCleanup(true); - _renderer->release(); -} - void UIWidget::onEnter() { arrayMakeObjectsPerformSelector(_children, onEnter, UIWidget*); @@ -137,6 +136,13 @@ void UIWidget::onExit() _isRunning = false; arrayMakeObjectsPerformSelector(_children, onExit, UIWidget*); } + +void UIWidget::setUserObject(cocos2d::Object *pUserObject) +{ + CC_SAFE_RETAIN(pUserObject); + CC_SAFE_RELEASE(_userObject); + _userObject = pUserObject; +} bool UIWidget::addChild(UIWidget *child) { @@ -157,7 +163,7 @@ bool UIWidget::addChild(UIWidget *child) else { bool seekSucceed = false; - ccArray* arrayChildren = _children->data; + cocos2d::ccArray* arrayChildren = _children->data; for (int i=childrenCount-1; i>=0; --i) { UIWidget* widget = (UIWidget*)(arrayChildren->arr[i]); @@ -203,7 +209,7 @@ bool UIWidget::removeChild(UIWidget *child) { child->onExit(); } - child->disableUpdate(); + child->setUpdateEnabled(false); child->setParent(NULL); _renderer->removeChild(child->getRenderer()); _children->removeObject(child); @@ -246,7 +252,7 @@ void UIWidget::reorderChild(UIWidget* child) else { bool seekSucceed = false; - ccArray* arrayChildren = _children->data; + cocos2d::ccArray* arrayChildren = _children->data; for (int i=childrenCount-1; i>=0; --i) { UIWidget* widget = (UIWidget*)(arrayChildren->arr[i]); @@ -274,21 +280,6 @@ void UIWidget::reorderChild(UIWidget* child) CC_SAFE_RELEASE(child); } -void UIWidget::disableUpdate() -{ - if (_scheduler) - { - _scheduler->unscheduleUpdateForTarget(this); - } - int childrenCount = _children->data->num; - ccArray* arrayChildren = _children->data; - for (int i=0; iarr[i]); - child->disableUpdate(); - } -} - void UIWidget::setEnabled(bool enabled) { _enabled = enabled; @@ -299,9 +290,9 @@ void UIWidget::setEnabled(bool enabled) } else { - dynamic_cast(_renderer)->setEnabled(enabled); + dynamic_cast(_renderer)->setEnabled(enabled); } - ccArray* arrayChildren = _children->data; + cocos2d::ccArray* arrayChildren = _children->data; int childrenCount = arrayChildren->num; for (int i = 0; i < childrenCount; i++) { @@ -312,15 +303,15 @@ void UIWidget::setEnabled(bool enabled) UIWidget* UIWidget::getChildByName(const char *name) { - return CCUIHELPER->seekWidgetByName(this, name); + return UIHelper::seekWidgetByName(this, name); } UIWidget* UIWidget::getChildByTag(int tag) { - return CCUIHELPER->seekWidgetByTag(this, tag); + return UIHelper::seekWidgetByTag(this, tag); } -Array* UIWidget::getChildren() +cocos2d::Array* UIWidget::getChildren() { return _children; } @@ -330,7 +321,7 @@ void UIWidget::initRenderer() _renderer = GUIRenderer::create(); } -void UIWidget::setSize(const Size &size) +void UIWidget::setSize(const cocos2d::Size &size) { _customSize = size; if (_ignoreSize) @@ -343,19 +334,19 @@ void UIWidget::setSize(const Size &size) } if (_isRunning) { - _sizePercent = (_widgetParent == NULL) ? Point::ZERO : Point(_customSize.width / _widgetParent->getSize().width, _customSize.height / _widgetParent->getSize().height); + _sizePercent = (_widgetParent == NULL) ? cocos2d::Point::ZERO : cocos2d::Point(_customSize.width / _widgetParent->getSize().width, _customSize.height / _widgetParent->getSize().height); } onSizeChanged(); } -void UIWidget::setSizePercent(const Point &percent) +void UIWidget::setSizePercent(const cocos2d::Point &percent) { _sizePercent = percent; if (!_isRunning) { return; } - Size cSize = (_widgetParent == NULL) ? Size::ZERO : Size(_widgetParent->getSize().width * percent.x , _widgetParent->getSize().height * percent.y); + cocos2d::Size cSize = (_widgetParent == NULL) ? cocos2d::Size::ZERO : cocos2d::Size(_widgetParent->getSize().width * percent.x , _widgetParent->getSize().height * percent.y); if (_ignoreSize) { _size = getContentSize(); @@ -381,11 +372,11 @@ void UIWidget::updateSizeAndPosition() { _size = _customSize; } - _sizePercent = (_widgetParent == NULL) ? Point::ZERO : Point(_customSize.width / _widgetParent->getSize().width, _customSize.height / _widgetParent->getSize().height); + _sizePercent = (_widgetParent == NULL) ? cocos2d::Point::ZERO : cocos2d::Point(_customSize.width / _widgetParent->getSize().width, _customSize.height / _widgetParent->getSize().height); break; case SIZE_PERCENT: { - Size cSize = (_widgetParent == NULL) ? Size::ZERO : Size(_widgetParent->getSize().width * _sizePercent.x , _widgetParent->getSize().height * _sizePercent.y); + cocos2d::Size cSize = (_widgetParent == NULL) ? cocos2d::Size::ZERO : cocos2d::Size(_widgetParent->getSize().width * _sizePercent.x , _widgetParent->getSize().height * _sizePercent.y); if (_ignoreSize) { _size = getContentSize(); @@ -401,16 +392,16 @@ void UIWidget::updateSizeAndPosition() break; } onSizeChanged(); - Point absPos = getPosition(); + cocos2d::Point absPos = getPosition(); switch (_positionType) { case POSITION_ABSOLUTE: - _positionPercent = (_widgetParent == NULL) ? Point::ZERO : Point(absPos.x / _widgetParent->getSize().width, absPos.y / _widgetParent->getSize().height); + _positionPercent = (_widgetParent == NULL) ? cocos2d::Point::ZERO : cocos2d::Point(absPos.x / _widgetParent->getSize().width, absPos.y / _widgetParent->getSize().height); break; case POSITION_PERCENT: { - Size parentSize = _widgetParent->getSize(); - absPos = Point(parentSize.width * _positionPercent.x, parentSize.height * _positionPercent.y); + cocos2d::Size parentSize = _widgetParent->getSize(); + absPos = cocos2d::Point(parentSize.width * _positionPercent.x, parentSize.height * _positionPercent.y); } break; default: @@ -434,7 +425,7 @@ void UIWidget::ignoreContentAdaptWithSize(bool ignore) _ignoreSize = ignore; if (_ignoreSize) { - Size s = getContentSize(); + cocos2d::Size s = getContentSize(); _size = s; } else @@ -449,27 +440,27 @@ bool UIWidget::isIgnoreContentAdaptWithSize() const return _ignoreSize; } -const Size& UIWidget::getSize() const +const cocos2d::Size& UIWidget::getSize() const { return _size; } -const Point& UIWidget::getSizePercent() const +const cocos2d::Point& UIWidget::getSizePercent() const { return _sizePercent; } -Point UIWidget::getWorldPosition() +cocos2d::Point UIWidget::getWorldPosition() { - return _renderer->convertToWorldSpace(Point::ZERO); + return _renderer->convertToWorldSpace(cocos2d::Point::ZERO); } -Point UIWidget::convertToWorldSpace(const Point& pt) +cocos2d::Point UIWidget::convertToWorldSpace(const cocos2d::Point& pt) { return _renderer->convertToWorldSpace(pt); } -Node* UIWidget::getVirtualRenderer() +cocos2d::Node* UIWidget::getVirtualRenderer() { return _renderer; } @@ -479,7 +470,7 @@ void UIWidget::onSizeChanged() } -const Size& UIWidget::getContentSize() const +const cocos2d::Size& UIWidget::getContentSize() const { return _size; } @@ -511,6 +502,10 @@ bool UIWidget::isTouchEnabled() const void UIWidget::setUpdateEnabled(bool enable) { + if (enable == _updateEnabled) + { + return; + } _updateEnabled = enable; if (enable) { @@ -616,7 +611,7 @@ void UIWidget::didNotSelectSelf() } -bool UIWidget::onTouchBegan(const Point &touchPoint) +bool UIWidget::onTouchBegan(const cocos2d::Point &touchPoint) { setFocused(true); _touchStartPos.x = touchPoint.x; @@ -629,7 +624,7 @@ bool UIWidget::onTouchBegan(const Point &touchPoint) return _touchPassedEnabled; } -void UIWidget::onTouchMoved(const Point &touchPoint) +void UIWidget::onTouchMoved(const cocos2d::Point &touchPoint) { _touchMovePos.x = touchPoint.x; _touchMovePos.y = touchPoint.y; @@ -641,7 +636,7 @@ void UIWidget::onTouchMoved(const Point &touchPoint) moveEvent(); } -void UIWidget::onTouchEnded(const Point &touchPoint) +void UIWidget::onTouchEnded(const cocos2d::Point &touchPoint) { _touchEndPos.x = touchPoint.x; _touchEndPos.y = touchPoint.y; @@ -661,13 +656,13 @@ void UIWidget::onTouchEnded(const Point &touchPoint) } } -void UIWidget::onTouchCancelled(const Point &touchPoint) +void UIWidget::onTouchCancelled(const cocos2d::Point &touchPoint) { setFocused(false); cancelUpEvent(); } -void UIWidget::onTouchLongClicked(const Point &touchPoint) +void UIWidget::onTouchLongClicked(const cocos2d::Point &touchPoint) { longClickEvent(); } @@ -709,31 +704,31 @@ void UIWidget::longClickEvent() } -void UIWidget::addTouchEventListener(Object *target, SEL_TouchEvent selector) +void UIWidget::addTouchEventListener(cocos2d::Object *target, SEL_TouchEvent selector) { _touchEventListener = target; _touchEventSelector = selector; } -Node* UIWidget::getRenderer() +cocos2d::Node* UIWidget::getRenderer() { return _renderer; } -void UIWidget::addRenderer(Node* renderer, int zOrder) +void UIWidget::addRenderer(cocos2d::Node* renderer, int zOrder) { _renderer->addChild(renderer, zOrder); } -void UIWidget::removeRenderer(Node* renderer, bool cleanup) +void UIWidget::removeRenderer(cocos2d::Node* renderer, bool cleanup) { _renderer->removeChild(renderer,cleanup); } -bool UIWidget::hitTest(const Point &pt) +bool UIWidget::hitTest(const cocos2d::Point &pt) { - Point nsp = _renderer->convertToNodeSpace(pt); - Rect bb = Rect(-_size.width * _anchorPoint.x, -_size.height * _anchorPoint.y, _size.width, _size.height); + cocos2d::Point nsp = _renderer->convertToNodeSpace(pt); + cocos2d::Rect bb = cocos2d::Rect(-_size.width * _anchorPoint.x, -_size.height * _anchorPoint.y, _size.width, _size.height); if (nsp.x >= bb.origin.x && nsp.x <= bb.origin.x + bb.size.width && nsp.y >= bb.origin.y && nsp.y <= bb.origin.y + bb.size.height) { return true; @@ -741,14 +736,14 @@ bool UIWidget::hitTest(const Point &pt) return false; } -bool UIWidget::clippingParentAreaContainPoint(const Point &pt) +bool UIWidget::clippingParentAreaContainPoint(const cocos2d::Point &pt) { _affectByClipping = false; UIWidget* parent = getParent(); UIWidget* clippingParent = NULL; while (parent) { - Layout* layoutParent = dynamic_cast(parent); + UILayout* layoutParent = dynamic_cast(parent); if (layoutParent) { if (layoutParent->isClippingEnabled()) @@ -783,7 +778,7 @@ bool UIWidget::clippingParentAreaContainPoint(const Point &pt) return true; } -void UIWidget::checkChildInfo(int handleState, UIWidget *sender, const Point &touchPoint) +void UIWidget::checkChildInfo(int handleState, UIWidget *sender, const cocos2d::Point &touchPoint) { if (_widgetParent) { @@ -791,27 +786,27 @@ void UIWidget::checkChildInfo(int handleState, UIWidget *sender, const Point &to } } -void UIWidget::setPosition(const Point &pos) +void UIWidget::setPosition(const cocos2d::Point &pos) { if (_isRunning) { - _positionPercent = (_widgetParent == NULL) ? Point::ZERO : Point(pos.x / _widgetParent->getSize().width, pos.y / _widgetParent->getSize().height); + _positionPercent = (_widgetParent == NULL) ? cocos2d::Point::ZERO : cocos2d::Point(pos.x / _widgetParent->getSize().width, pos.y / _widgetParent->getSize().height); } _renderer->setPosition(pos); } -void UIWidget::setPositionPercent(const Point &percent) +void UIWidget::setPositionPercent(const cocos2d::Point &percent) { _positionPercent = percent; if (_isRunning) { - Size parentSize = _widgetParent->getSize(); - Point absPos = Point(parentSize.width * _positionPercent.x, parentSize.height * _positionPercent.y); + cocos2d::Size parentSize = _widgetParent->getSize(); + cocos2d::Point absPos = cocos2d::Point(parentSize.width * _positionPercent.x, parentSize.height * _positionPercent.y); _renderer->setPosition(absPos); } } -void UIWidget::setAnchorPoint(const Point &pt) +void UIWidget::setAnchorPoint(const cocos2d::Point &pt) { _anchorPoint = pt; _renderer->setAnchorPoint(pt); @@ -822,12 +817,12 @@ void UIWidget::updateAnchorPoint() setAnchorPoint(_anchorPoint); } -const Point& UIWidget::getPosition() +const cocos2d::Point& UIWidget::getPosition() { return _renderer->getPosition(); } -const Point& UIWidget::getPositionPercent() +const cocos2d::Point& UIWidget::getPositionPercent() { return _positionPercent; } @@ -842,7 +837,7 @@ PositionType UIWidget::getPositionType() const return _positionType; } -const Point& UIWidget::getAnchorPoint() +const cocos2d::Point& UIWidget::getAnchorPoint() { return _anchorPoint; } @@ -930,36 +925,12 @@ bool UIWidget::isEnabled() const float UIWidget::getLeftInParent() { - float leftPos = 0.0f; - switch (_widgetType) - { - case WidgetTypeWidget: - leftPos = getPosition().x - getAnchorPoint().x * _size.width; - break; - case WidgetTypeContainer: - leftPos = getPosition().x; - break; - default: - break; - } - return leftPos; + return getPosition().x - getAnchorPoint().x * _size.width;; } float UIWidget::getBottomInParent() { - float bottomPos = 0.0f; - switch (_widgetType) - { - case WidgetTypeWidget: - bottomPos = getPosition().y - getAnchorPoint().y * _size.height; - break; - case WidgetTypeContainer: - bottomPos = getPosition().y; - break; - default: - break; - } - return bottomPos; + return getPosition().y - getAnchorPoint().y * _size.height;; } float UIWidget::getRightInParent() @@ -982,17 +953,17 @@ void UIWidget::setParent(UIWidget* parent) _widgetParent = parent; } -Action* UIWidget::runAction(Action *action) +cocos2d::Action* UIWidget::runAction(cocos2d::Action *action) { return _renderer->runAction(action); } -void UIWidget::setActionManager(ActionManager *actionManager) +void UIWidget::setActionManager(cocos2d::ActionManager *actionManager) { _renderer->setActionManager(actionManager); } -ActionManager* UIWidget::getActionManager() +cocos2d::ActionManager* UIWidget::getActionManager() { return _renderer->getActionManager(); } @@ -1002,7 +973,7 @@ void UIWidget::stopAllActions() _renderer->stopAllActions(); } -void UIWidget::stopAction(Action *action) +void UIWidget::stopAction(cocos2d::Action *action) { _renderer->stopAction(action); } @@ -1012,33 +983,33 @@ void UIWidget::stopActionByTag(int tag) _renderer->stopActionByTag(tag); } -Action* UIWidget::getActionByTag(int tag) +cocos2d::Action* UIWidget::getActionByTag(int tag) { return _renderer->getActionByTag(tag); } -void UIWidget::setColor(const Color3B &color) +void UIWidget::setColor(const cocos2d::Color3B &color) { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { rgbap->setColor(color); } } -const Color3B& UIWidget::getColor() +const cocos2d::Color3B& UIWidget::getColor() { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { return rgbap->getColor(); } - return Color3B::WHITE; + return cocos2d::Color3B::WHITE; } void UIWidget::setOpacity(int opacity) { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { rgbap->setOpacity(opacity); @@ -1047,7 +1018,7 @@ void UIWidget::setOpacity(int opacity) int UIWidget::getOpacity() { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { return rgbap->getOpacity(); @@ -1057,7 +1028,7 @@ int UIWidget::getOpacity() bool UIWidget::isCascadeOpacityEnabled() { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { return rgbap->isCascadeOpacityEnabled(); @@ -1067,7 +1038,7 @@ bool UIWidget::isCascadeOpacityEnabled() void UIWidget::setCascadeOpacityEnabled(bool cascadeOpacityEnabled) { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { rgbap->setCascadeOpacityEnabled(cascadeOpacityEnabled); @@ -1076,7 +1047,7 @@ void UIWidget::setCascadeOpacityEnabled(bool cascadeOpacityEnabled) bool UIWidget::isCascadeColorEnabled() { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { return rgbap->isCascadeColorEnabled(); @@ -1086,33 +1057,33 @@ bool UIWidget::isCascadeColorEnabled() void UIWidget::setCascadeColorEnabled(bool cascadeColorEnabled) { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { rgbap->setCascadeColorEnabled(cascadeColorEnabled); } } -void UIWidget::setBlendFunc(BlendFunc blendFunc) +void UIWidget::setBlendFunc(cocos2d::BlendFunc blendFunc) { - BlendProtocol * blendNode = DYNAMIC_CAST_CCBLENDPROTOCOL; + cocos2d::BlendProtocol * blendNode = DYNAMIC_CAST_CCBLENDPROTOCOL; if (blendNode) { blendNode->setBlendFunc(blendFunc); } } -const Point& UIWidget::getTouchStartPos() +const cocos2d::Point& UIWidget::getTouchStartPos() { return _touchStartPos; } -const Point& UIWidget::getTouchMovePos() +const cocos2d::Point& UIWidget::getTouchMovePos() { return _touchMovePos; } -const Point& UIWidget::getTouchEndPos() +const cocos2d::Point& UIWidget::getTouchEndPos() { return _touchEndPos; } @@ -1142,19 +1113,14 @@ WidgetType UIWidget::getWidgetType() const return _widgetType; } -void UIWidget::setLayoutParameter(LayoutParameter *parameter) +void UIWidget::setLayoutParameter(UILayoutParameter *parameter) { - if (_layoutParameter) - { - CC_SAFE_RELEASE_NULL(_layoutParameter); - } - _layoutParameter = parameter; - CC_SAFE_RETAIN(_layoutParameter); + _layoutParameterDictionary->setObject(parameter, parameter->getLayoutType()); } -LayoutParameter* UIWidget::getLayoutParameter() +UILayoutParameter* UIWidget::getLayoutParameter(LayoutParameterType type) { - return _layoutParameter; + return dynamic_cast(_layoutParameterDictionary->objectForKey(type)); } const char* UIWidget::getDescription() const @@ -1162,6 +1128,71 @@ const char* UIWidget::getDescription() const return "Widget"; } +UIWidget* UIWidget::clone() +{ + UIWidget* clonedWidget = createCloneInstance(); + clonedWidget->copyProperties(this); + clonedWidget->copyClonedWidgetChildren(this); + return clonedWidget; +} + +UIWidget* UIWidget::createCloneInstance() +{ + return UIWidget::create(); +} + +void UIWidget::copyClonedWidgetChildren(UIWidget* model) +{ + cocos2d::ccArray* arrayWidgetChildren = model->getChildren()->data; + int length = arrayWidgetChildren->num; + for (int i=0; iarr[i]); + addChild(child->clone()); + } +} + +void UIWidget::copySpecialProperties(UIWidget* model) +{ + +} + +void UIWidget::copyProperties(UIWidget *widget) +{ + setEnabled(widget->isEnabled()); + setVisible(widget->isVisible()); + setBright(widget->isBright()); + setTouchEnabled(widget->isTouchEnabled()); + _touchPassedEnabled = false; + setZOrder(widget->getZOrder()); + setUpdateEnabled(widget->isUpdateEnabled()); + setTag(widget->getTag()); + setName(widget->getName()); + setActionTag(widget->getActionTag()); + _ignoreSize = widget->_ignoreSize; + _size = widget->_size; + _customSize = widget->_customSize; + copySpecialProperties(widget); + _sizeType = widget->getSizeType(); + _sizePercent = widget->_sizePercent; + _positionType = widget->_positionType; + _positionPercent = widget->_positionPercent; + setPosition(widget->getPosition()); + setAnchorPoint(widget->getAnchorPoint()); + setScaleX(widget->getScaleX()); + setScaleY(widget->getScaleY()); + setRotation(widget->getRotation()); + setRotationX(widget->getRotationX()); + setRotationY(widget->getRotationY()); + setFlipX(widget->isFlipX()); + setFlipY(widget->isFlipY()); + setColor(widget->getColor()); + setOpacity(widget->getOpacity()); + setCascadeOpacityEnabled(widget->isCascadeOpacityEnabled()); + setCascadeColorEnabled(widget->isCascadeColorEnabled()); + onSizeChanged(); +} + /*temp action*/ void UIWidget::setActionTag(int tag) { @@ -1214,7 +1245,7 @@ void GUIRenderer::visit() { return; } - NodeRGBA::visit(); + cocos2d::NodeRGBA::visit(); } - + } diff --git a/cocos/gui/UIWidget.h b/cocos/gui/UIWidget.h index ebc7e8a665..02db42e731 100644 --- a/cocos/gui/UIWidget.h +++ b/cocos/gui/UIWidget.h @@ -27,9 +27,9 @@ #include "cocos2d.h" #include "gui/UILayoutDefine.h" -#include "gui/LayoutParameter.h" -namespace gui { +#include "gui/UILayoutParameter.h" +namespace gui { typedef enum { @@ -72,11 +72,10 @@ typedef enum typedef void (cocos2d::Object::*SEL_TouchEvent)(cocos2d::Object*,TouchEventType); #define toucheventselector(_SELECTOR) (SEL_TouchEvent)(&_SELECTOR) - -//class UILayer; -/*temp action*/ -class UIActionNode; - +/** +* @js NA +* @lua NA +*/ class UIWidget : public cocos2d::Object { public: @@ -260,12 +259,7 @@ public: * Removes all children from the container, and do a cleanup to all running actions depending on the cleanup parameter. */ virtual void removeAllChildren(); - - /** - * Unschedules the "update" method. - */ - void disableUpdate(); - + /** * Reorders a child according to a new z value. * @@ -304,27 +298,27 @@ public: /** * Gets the renderer of widget * - * renderer is a CCNode, it's for drawing + * renderer is a Node, it's for drawing * - * @return a CCNode object + * @return a Node object */ cocos2d::Node* getRenderer(); /** - * Add a CCNode for rendering. + * Add a Node for rendering. * - * renderer is a CCNode, it's for drawing + * renderer is a Node, it's for drawing * * @param renderer A render node * - * @param zOrder Z order for drawing priority. Please refer to CCNode::setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to Node::setZOrder(int) */ void addRenderer(cocos2d::Node* renderer, int zOrder); /** - * Remove a CCNode from widget. + * Remove a Node from widget. * - * renderer is a CCNode, it's for drawing + * renderer is a Node, it's for drawing * * @param renderer A render node which needs to be removed * @@ -359,7 +353,7 @@ public: /** * Changes the position (x,y) of the widget in OpenGL coordinates * - * Usually we use ccp(x,y) to compose Point object. + * Usually we use p(x,y) to compose Point object. * The original point (0,0) is at the left-bottom corner of screen. * * @param position The position (x,y) of the widget in OpenGL coordinates @@ -369,7 +363,7 @@ public: /** * Changes the position (x,y) of the widget in OpenGL coordinates * - * Usually we use ccp(x,y) to compose Point object. + * Usually we use p(x,y) to compose Point object. * The original point (0,0) is at the left-bottom corner of screen. * * @param percent The percent (x,y) of the widget in OpenGL coordinates @@ -809,15 +803,21 @@ public: * @see LayoutParameter * * @param LayoutParameter pointer + * + * @param type Relative or Linear */ - void setLayoutParameter(LayoutParameter* parameter); + void setLayoutParameter(UILayoutParameter* parameter); /** * Gets LayoutParameter of widget. * * @see LayoutParameter + * + * @param type Relative or Linear + * + * @return LayoutParameter */ - LayoutParameter* getLayoutParameter(); + UILayoutParameter* getLayoutParameter(LayoutParameterType type); /** * Ignore the widget size @@ -850,7 +850,7 @@ public: * * For example, a button's Virtual Renderer is it's texture renderer. * - * @return CCNode pointer. + * @return Node pointer. */ virtual cocos2d::Node* getVirtualRenderer(); @@ -871,14 +871,34 @@ public: */ virtual const cocos2d::Size& getContentSize() const; - virtual void onEnter(); - virtual void onExit(); - /** * Returns the "class name" of widget. */ virtual const char* getDescription() const; + UIWidget* clone(); + + virtual void onEnter(); + virtual void onExit(); + + virtual Object* getUserObject() { return _userObject; } + /** + * @js NA + * @lua NA + */ + virtual const Object* getUserObject() const { return _userObject; } + + /** + * Returns a user assigned Object + * + * Similar to UserData, but instead of holding a void* it holds an object. + * The UserObject will be retained once in this method, + * and the previous UserObject (if existed) will be relese. + * The UserObject will be released in Node's destructure. + * + * @param userObject A user assigned Object + */ + virtual void setUserObject(Object *userObject); /*temp action*/ void setActionTag(int tag); int getActionTag(); @@ -906,13 +926,11 @@ protected: void cancelUpEvent(); void longClickEvent(); void updateAnchorPoint(); - /** - * Release texture resoures of widget. - * Release renderer. - * If you override releaseResoures, you shall call its parent's one, e.g. UIWidget::releaseResoures(). - */ - virtual void releaseResoures(); void updateSizeAndPosition(); + void copyProperties(UIWidget* model); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); + virtual void copyClonedWidgetChildren(UIWidget* model); protected: bool _enabled; ///< Highest control of widget bool _visible; ///< is this widget visible @@ -930,7 +948,7 @@ protected: cocos2d::Point _touchMovePos; ///< touch moved point cocos2d::Point _touchEndPos; ///< touch ended point - cocos2d::Object* _touchEventListener; + Object* _touchEventListener; SEL_TouchEvent _touchEventSelector; @@ -941,7 +959,7 @@ protected: int _actionTag; cocos2d::Size _size; cocos2d::Size _customSize; - LayoutParameter* _layoutParameter; + cocos2d::Dictionary* _layoutParameterDictionary; bool _ignoreSize; cocos2d::Array* _children; bool _affectByClipping; @@ -953,8 +971,12 @@ protected: PositionType _positionType; cocos2d::Point _positionPercent; bool _isRunning; + cocos2d::Object* _userObject; }; - +/** +* @js NA +* @lua NA +*/ class GUIRenderer : public cocos2d::NodeRGBA { public: @@ -969,5 +991,4 @@ protected: }; } - #endif /* defined(__UIWidget__) */ diff --git a/cocos/gui/proj.win32/libGUI.vcxproj b/cocos/gui/proj.win32/libGUI.vcxproj index b225eaa127..2712ae3900 100644 --- a/cocos/gui/proj.win32/libGUI.vcxproj +++ b/cocos/gui/proj.win32/libGUI.vcxproj @@ -12,11 +12,8 @@ - - - @@ -24,7 +21,9 @@ + + @@ -37,11 +36,8 @@ - - - @@ -49,7 +45,9 @@ + + diff --git a/cocos/gui/proj.win32/libGUI.vcxproj.filters b/cocos/gui/proj.win32/libGUI.vcxproj.filters index 12f0d385ab..092f28f7e0 100644 --- a/cocos/gui/proj.win32/libGUI.vcxproj.filters +++ b/cocos/gui/proj.win32/libGUI.vcxproj.filters @@ -24,9 +24,6 @@ UIWidgets\ScrollWidget - - UIWidgets\ScrollWidget - UIWidgets\ScrollWidget @@ -72,12 +69,6 @@ System - - Layouts - - - Layouts - Layouts @@ -87,14 +78,17 @@ BaseClasses + + Layouts + + + Layouts + UIWidgets\ScrollWidget - - UIWidgets\ScrollWidget - UIWidgets\ScrollWidget @@ -140,12 +134,6 @@ System - - Layouts - - - Layouts - Layouts @@ -155,5 +143,11 @@ BaseClasses + + Layouts + + + Layouts + \ No newline at end of file diff --git a/cocos/math/kazmath/CMakeLists.txt b/cocos/math/kazmath/CMakeLists.txt new file mode 100644 index 0000000000..208b4a97c2 --- /dev/null +++ b/cocos/math/kazmath/CMakeLists.txt @@ -0,0 +1,23 @@ + +SET(KAZMATH_SOURCES + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/mat4.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/mat3.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/plane.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/vec4.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/quaternion.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/vec2.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/vec3.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/utility.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/aabb.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/ray2.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/GL/mat4stack.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/GL/matrix.c + ) + +ADD_SUBDIRECTORY(src) + +set_target_properties(kazmath + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) diff --git a/cocos/math/kazmath/src/mat4.c b/cocos/math/kazmath/src/mat4.c index 77495cfdaa..9c49b56071 100644 --- a/cocos/math/kazmath/src/mat4.c +++ b/cocos/math/kazmath/src/mat4.c @@ -216,7 +216,7 @@ kmMat4* const kmMat4Transpose(kmMat4* pOut, const kmMat4* pIn) */ kmMat4* const kmMat4Multiply(kmMat4* pOut, const kmMat4* pM1, const kmMat4* pM2) { -#if defined(__ARM_NEON__) +#if defined(__ARM_NEON__) && !defined(__arm64__) // It is possible to skip the memcpy() since "out" does not overwrite p1 or p2. // otherwise a temp must be needed. diff --git a/cocos/math/kazmath/src/neon_matrix_impl.c b/cocos/math/kazmath/src/neon_matrix_impl.c index 9790b73c92..b174ad0f87 100644 --- a/cocos/math/kazmath/src/neon_matrix_impl.c +++ b/cocos/math/kazmath/src/neon_matrix_impl.c @@ -23,7 +23,8 @@ #include "kazmath/neon_matrix_impl.h" -#if defined(__ARM_NEON__) +#if defined(__ARM_NEON__) && !defined(__arm64__) + void NEON_Matrix4Mul(const float* a, const float* b, float* output ) { diff --git a/cocos/network/CMakeLists.txt b/cocos/network/CMakeLists.txt new file mode 100644 index 0000000000..f2deb9b365 --- /dev/null +++ b/cocos/network/CMakeLists.txt @@ -0,0 +1,23 @@ +set(NETWORK_SRC + HttpClient.cpp + SocketIO.cpp +) + +add_library(network STATIC + ${NETWORK_SRC} +) + +target_link_libraries(network + curl + ldap + lber + idn + rtmp +) + +set_target_properties(network + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/cocos/network/Makefile b/cocos/network/Makefile deleted file mode 100644 index 029078722d..0000000000 --- a/cocos/network/Makefile +++ /dev/null @@ -1,22 +0,0 @@ -TARGET = libnetwork.a - -INCLUDES = -I.. - -SOURCES = HttpClient.cpp \ -SocketIO.cpp - -include ../2d/cocos2dx.mk - -CXXFLAGS += -Wno-multichar - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index f1eb18e754..9304e3652b 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -37,17 +37,16 @@ #include "CCPhysicsJoint.h" #include "CCPhysicsWorld.h" -#include "chipmunk/CCPhysicsBodyInfo.h" -#include "box2d/CCPhysicsBodyInfo.h" -#include "chipmunk/CCPhysicsJointInfo.h" -#include "box2d/CCPhysicsJointInfo.h" -#include "chipmunk/CCPhysicsWorldInfo.h" -#include "box2d/CCPhysicsWorldInfo.h" -#include "chipmunk/CCPhysicsShapeInfo.h" -#include "box2d/CCPhysicsShapeInfo.h" - -#include "chipmunk/CCPhysicsHelper.h" -#include "box2d/CCPhysicsHelper.h" +#include "chipmunk/CCPhysicsBodyInfo_chipmunk.h" +#include "box2d/CCPhysicsBodyInfo_box2d.h" +#include "chipmunk/CCPhysicsJointInfo_chipmunk.h" +#include "box2d/CCPhysicsJointInfo_box2d.h" +#include "chipmunk/CCPhysicsWorldInfo_chipmunk.h" +#include "box2d/CCPhysicsWorldInfo_box2d.h" +#include "chipmunk/CCPhysicsShapeInfo_chipmunk.h" +#include "box2d/CCPhysicsShapeInfo_box2d.h" +#include "chipmunk/CCPhysicsHelper_chipmunk.h" +#include "box2d/CCPhysicsHelper_box2d.h" NS_CC_BEGIN @@ -58,11 +57,11 @@ namespace { static const float MASS_DEFAULT = 1.0; static const float MOMENT_DEFAULT = 200; - static float GROUP_INDEX = 0; } PhysicsBody::PhysicsBody() -: _owner(nullptr) +: _node(nullptr) +, _shapes(nullptr) , _world(nullptr) , _info(nullptr) , _dynamic(true) @@ -80,24 +79,23 @@ PhysicsBody::PhysicsBody() , _tag(0) , _categoryBitmask(UINT_MAX) , _collisionBitmask(UINT_MAX) -, _contactTestBitmask(0) +, _contactTestBitmask(UINT_MAX) +, _group(0) { } PhysicsBody::~PhysicsBody() { - CC_SAFE_DELETE(_info); - - removeAllShapes(); - for (auto it = _joints.begin(); it != _joints.end(); ++it) { PhysicsJoint* joint = *it; - PhysicsBody* other = joint->getBodyA() == this ? joint->getBodyA() : joint->getBodyB(); - other->_joints.erase(std::find(other->_joints.begin(), other->_joints.end(), joint)); + PhysicsBody* other = joint->getBodyA() == this ? joint->getBodyB() : joint->getBodyA(); + other->removeJoint(joint); delete joint; } + + CC_SAFE_DELETE(_info); } PhysicsBody* PhysicsBody::create() @@ -113,12 +111,51 @@ PhysicsBody* PhysicsBody::create() return nullptr; } -PhysicsBody* PhysicsBody::createCircle(float radius, PhysicsMaterial material) +PhysicsBody* PhysicsBody::create(float mass) +{ + PhysicsBody* body = new PhysicsBody(); + if (body) + { + body->_mass = mass; + body->_massDefault = false; + if (body->init()) + { + body->autorelease(); + return body; + } + } + + CC_SAFE_DELETE(body); + return nullptr; +} + +PhysicsBody* PhysicsBody::create(float mass, float moment) +{ + PhysicsBody* body = new PhysicsBody(); + if (body) + { + body->_mass = mass; + body->_massDefault = false; + body->_moment = moment; + body->_momentDefault = false; + if (body->init()) + { + body->autorelease(); + return body; + } + } + + CC_SAFE_DELETE(body); + return nullptr; + +} + +PhysicsBody* PhysicsBody::createCircle(float radius, const PhysicsMaterial& material, const Point& offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapeCircle::create(radius, material)); + body->addShape(PhysicsShapeCircle::create(radius, material, offset)); body->autorelease(); return body; } @@ -127,12 +164,12 @@ PhysicsBody* PhysicsBody::createCircle(float radius, PhysicsMaterial material) return nullptr; } -PhysicsBody* PhysicsBody::createBox(Size size, PhysicsMaterial material) +PhysicsBody* PhysicsBody::createBox(const Size& size, const PhysicsMaterial& material, const Point& offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapeBox::create(size, material)); + body->addShape(PhysicsShapeBox::create(size, material, offset)); body->autorelease(); return body; } @@ -141,12 +178,12 @@ PhysicsBody* PhysicsBody::createBox(Size size, PhysicsMaterial material) return nullptr; } -PhysicsBody* PhysicsBody::createPolygon(Point* points, int count, PhysicsMaterial material) +PhysicsBody* PhysicsBody::createPolygon(const Point* points, int count, const PhysicsMaterial& material, const Point& offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapePolygon::create(points, count, material)); + body->addShape(PhysicsShapePolygon::create(points, count, material, offset)); body->autorelease(); return body; } @@ -155,7 +192,7 @@ PhysicsBody* PhysicsBody::createPolygon(Point* points, int count, PhysicsMateria return nullptr; } -PhysicsBody* PhysicsBody::createEdgeSegment(Point a, Point b, PhysicsMaterial material, float border/* = 1*/) +PhysicsBody* PhysicsBody::createEdgeSegment(const Point& a, const Point& b, const PhysicsMaterial& material, float border/* = 1*/) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) @@ -170,12 +207,12 @@ PhysicsBody* PhysicsBody::createEdgeSegment(Point a, Point b, PhysicsMaterial ma return nullptr; } -PhysicsBody* PhysicsBody::createEdgeBox(Size size, PhysicsMaterial material, float border/* = 1*/) +PhysicsBody* PhysicsBody::createEdgeBox(const Size& size, const PhysicsMaterial& material, float border/* = 1*/, const Point& offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapeEdgeBox::create(size, material, border)); + body->addShape(PhysicsShapeEdgeBox::create(size, material, border, offset)); body->_dynamic = false; body->autorelease(); return body; @@ -186,7 +223,7 @@ PhysicsBody* PhysicsBody::createEdgeBox(Size size, PhysicsMaterial material, flo return nullptr; } -PhysicsBody* PhysicsBody::createEdgePolygon(Point* points, int count, PhysicsMaterial material, float border/* = 1*/) +PhysicsBody* PhysicsBody::createEdgePolygon(const Point* points, int count, const PhysicsMaterial& material, float border/* = 1*/) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) @@ -202,7 +239,7 @@ PhysicsBody* PhysicsBody::createEdgePolygon(Point* points, int count, PhysicsMat return nullptr; } -PhysicsBody* PhysicsBody::createEdgeChain(Point* points, int count, PhysicsMaterial material, float border/* = 1*/) +PhysicsBody* PhysicsBody::createEdgeChain(const Point* points, int count, const PhysicsMaterial& material, float border/* = 1*/) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) @@ -224,11 +261,13 @@ bool PhysicsBody::init() { _info = new PhysicsBodyInfo(); CC_BREAK_IF(_info == nullptr); + _shapes = Array::create(); + CC_BREAK_IF(_shapes == nullptr); + _shapes->retain(); - _info->body = cpBodyNew(PhysicsHelper::float2cpfloat(_mass), PhysicsHelper::float2cpfloat(_moment)); - _info->group = ++GROUP_INDEX; + _info->setBody(cpBodyNew(PhysicsHelper::float2cpfloat(_mass), PhysicsHelper::float2cpfloat(_moment))); - CC_BREAK_IF(_info->body == nullptr); + CC_BREAK_IF(_info->getBody() == nullptr); return true; } while (false); @@ -236,19 +275,36 @@ bool PhysicsBody::init() return false; } +void PhysicsBody::removeJoint(PhysicsJoint* joint) +{ + auto it = std::find(_joints.begin(), _joints.end(), joint); + + if (it != _joints.end()) + { + _joints.erase(it); + } +} + void PhysicsBody::setDynamic(bool dynamic) { if (dynamic != _dynamic) { _dynamic = dynamic; - if (_world != nullptr) + if (dynamic) { - if (dynamic) + cpBodySetMass(_info->getBody(), _mass); + + if (_world != nullptr) { - cpSpaceAddBody(_world->_info->space, _info->body); - }else + cpSpaceAddBody(_world->_info->getSpace(), _info->getBody()); + } + }else + { + cpBodySetMass(_info->getBody(), PHYSICS_INFINITY); + + if (_world != nullptr) { - cpSpaceRemoveBody(_world->_info->space, _info->body); + cpSpaceRemoveBody(_world->_info->getSpace(), _info->getBody()); } } @@ -259,7 +315,7 @@ void PhysicsBody::setRotationEnable(bool enable) { if (_rotationEnable != enable) { - cpBodySetMoment(_info->body, enable ? _moment : PHYSICS_INFINITY); + cpBodySetMoment(_info->getBody(), enable ? _moment : PHYSICS_INFINITY); _rotationEnable = enable; } } @@ -274,10 +330,10 @@ void PhysicsBody::setGravityEnable(bool enable) { if (enable) { - applyForce(_world->getGravity()); + applyForce(_world->getGravity() * _mass); }else { - applyForce(-_world->getGravity()); + applyForce(-_world->getGravity() * _mass); } } } @@ -285,34 +341,33 @@ void PhysicsBody::setGravityEnable(bool enable) void PhysicsBody::setPosition(Point position) { - cpBodySetPos(_info->body, PhysicsHelper::point2cpv(position)); + cpBodySetPos(_info->getBody(), PhysicsHelper::point2cpv(position)); } void PhysicsBody::setRotation(float rotation) { - cpBodySetAngle(_info->body, PhysicsHelper::float2cpfloat(rotation)); + cpBodySetAngle(_info->getBody(), PhysicsHelper::float2cpfloat(rotation)); } Point PhysicsBody::getPosition() const { - cpVect vec = cpBodyGetPos(_info->body); + cpVect vec = cpBodyGetPos(_info->getBody()); return PhysicsHelper::cpv2point(vec); } float PhysicsBody::getRotation() const { - return -PhysicsHelper::cpfloat2float(cpBodyGetAngle(_info->body) / 3.14f * 180.0f); + return -PhysicsHelper::cpfloat2float(cpBodyGetAngle(_info->getBody()) / 3.14f * 180.0f); } -void PhysicsBody::addShape(PhysicsShape* shape) +PhysicsShape* PhysicsBody::addShape(PhysicsShape* shape) { - if (shape == nullptr) return; + if (shape == nullptr) return nullptr; // add shape to body - if (std::find(_shapes.begin(), _shapes.end(), shape) == _shapes.end()) + if (_shapes->getIndexOfObject(shape) == UINT_MAX) { shape->setBody(this); - _shapes.push_back(shape); // calculate the area, mass, and desity // area must update before mass, because the density changes depend on it. @@ -325,33 +380,40 @@ void PhysicsBody::addShape(PhysicsShape* shape) _world->addShape(shape); } - shape->retain(); + _shapes->addObject(shape); + + if (_group != CP_NO_GROUP && shape->getGroup() == CP_NO_GROUP) + { + shape->setGroup(_group); + } } + + return shape; } -void PhysicsBody::applyForce(Point force) +void PhysicsBody::applyForce(const Vect& force) { applyForce(force, Point::ZERO); } -void PhysicsBody::applyForce(Point force, Point offset) +void PhysicsBody::applyForce(const Vect& force, const Point& offset) { - cpBodyApplyForce(_info->body, PhysicsHelper::point2cpv(force), PhysicsHelper::point2cpv(offset)); + cpBodyApplyForce(_info->getBody(), PhysicsHelper::point2cpv(force), PhysicsHelper::point2cpv(offset)); } -void PhysicsBody::applyImpulse(Point impulse) +void PhysicsBody::applyImpulse(const Vect& impulse) { applyImpulse(impulse, Point()); } -void PhysicsBody::applyImpulse(Point impulse, Point offset) +void PhysicsBody::applyImpulse(const Vect& impulse, const Point& offset) { - cpBodyApplyImpulse(_info->body, PhysicsHelper::point2cpv(impulse), PhysicsHelper::point2cpv(offset)); + cpBodyApplyImpulse(_info->getBody(), PhysicsHelper::point2cpv(impulse), PhysicsHelper::point2cpv(offset)); } void PhysicsBody::applyTorque(float torque) { - cpBodySetTorque(_info->body, PhysicsHelper::float2cpfloat(torque)); + cpBodySetTorque(_info->getBody(), PhysicsHelper::float2cpfloat(torque)); } void PhysicsBody::setMass(float mass) @@ -380,7 +442,7 @@ void PhysicsBody::setMass(float mass) } } - cpBodySetMass(_info->body, PhysicsHelper::float2cpfloat(_mass)); + cpBodySetMass(_info->getBody(), PhysicsHelper::float2cpfloat(_mass)); } void PhysicsBody::addMass(float mass) @@ -422,7 +484,7 @@ void PhysicsBody::addMass(float mass) } } - cpBodySetMass(_info->body, PhysicsHelper::float2cpfloat(_mass)); + cpBodySetMass(_info->getBody(), PhysicsHelper::float2cpfloat(_mass)); } void PhysicsBody::addMoment(float moment) @@ -463,48 +525,58 @@ void PhysicsBody::addMoment(float moment) if (_rotationEnable) { - cpBodySetMoment(_info->body, PhysicsHelper::float2cpfloat(_moment)); + cpBodySetMoment(_info->getBody(), PhysicsHelper::float2cpfloat(_moment)); } } -void PhysicsBody::setVelocity(Point velocity) +void PhysicsBody::setVelocity(const Point& velocity) { - cpBodySetVel(_info->body, PhysicsHelper::point2cpv(velocity)); + cpBodySetVel(_info->getBody(), PhysicsHelper::point2cpv(velocity)); } Point PhysicsBody::getVelocity() { - return PhysicsHelper::cpv2point(cpBodyGetVel(_info->body)); + return PhysicsHelper::cpv2point(cpBodyGetVel(_info->getBody())); +} + +Point PhysicsBody::getVelocityAtLocalPoint(const Point& point) +{ + return PhysicsHelper::cpv2point(cpBodyGetVelAtLocalPoint(_info->getBody(), PhysicsHelper::point2cpv(point))); +} + +Point PhysicsBody::getVelocityAtWorldPoint(const Point& point) +{ + return PhysicsHelper::cpv2point(cpBodyGetVelAtWorldPoint(_info->getBody(), PhysicsHelper::point2cpv(point))); } void PhysicsBody::setAngularVelocity(float velocity) { - cpBodySetAngVel(_info->body, PhysicsHelper::float2cpfloat(velocity)); + cpBodySetAngVel(_info->getBody(), PhysicsHelper::float2cpfloat(velocity)); } float PhysicsBody::getAngularVelocity() { - return PhysicsHelper::cpfloat2float(cpBodyGetAngVel(_info->body)); + return PhysicsHelper::cpfloat2float(cpBodyGetAngVel(_info->getBody())); } void PhysicsBody::setVelocityLimit(float limit) { - cpBodySetVelLimit(_info->body, PhysicsHelper::float2cpfloat(limit)); + cpBodySetVelLimit(_info->getBody(), PhysicsHelper::float2cpfloat(limit)); } float PhysicsBody::getVelocityLimit() { - return PhysicsHelper::cpfloat2float(cpBodyGetVelLimit(_info->body)); + return PhysicsHelper::cpfloat2float(cpBodyGetVelLimit(_info->getBody())); } void PhysicsBody::setAngularVelocityLimit(float limit) { - cpBodySetVelLimit(_info->body, PhysicsHelper::float2cpfloat(limit)); + cpBodySetVelLimit(_info->getBody(), PhysicsHelper::float2cpfloat(limit)); } float PhysicsBody::getAngularVelocityLimit() { - return PhysicsHelper::cpfloat2float(cpBodyGetAngVelLimit(_info->body)); + return PhysicsHelper::cpfloat2float(cpBodyGetAngVelLimit(_info->getBody())); } void PhysicsBody::setMoment(float moment) @@ -514,14 +586,15 @@ void PhysicsBody::setMoment(float moment) if (_rotationEnable) { - cpBodySetMoment(_info->body, PhysicsHelper::float2cpfloat(_moment)); + cpBodySetMoment(_info->getBody(), PhysicsHelper::float2cpfloat(_moment)); } } -PhysicsShape* PhysicsBody::getShapeByTag(int tag) +PhysicsShape* PhysicsBody::getShape(int tag) const { - for (auto shape : _shapes) + for (auto child : *_shapes) { + PhysicsShape* shape = dynamic_cast(child); if (shape->getTag() == tag) { return shape; @@ -531,10 +604,11 @@ PhysicsShape* PhysicsBody::getShapeByTag(int tag) return nullptr; } -void PhysicsBody::removeShapeByTag(int tag) +void PhysicsBody::removeShape(int tag) { - for (auto shape : _shapes) + for (auto child : *_shapes) { + PhysicsShape* shape = dynamic_cast(child); if (shape->getTag() == tag) { removeShape(shape); @@ -545,9 +619,7 @@ void PhysicsBody::removeShapeByTag(int tag) void PhysicsBody::removeShape(PhysicsShape* shape) { - auto it = std::find(_shapes.begin(), _shapes.end(), shape); - - if (it != _shapes.end()) + if (_shapes->getIndexOfObject(shape) != UINT_MAX) { // deduce the area, mass and moment // area must update before mass, because the density changes depend on it. @@ -560,25 +632,45 @@ void PhysicsBody::removeShape(PhysicsShape* shape) { _world->removeShape(shape); } - _shapes.erase(it); + + // set shape->_body = nullptr make the shape->setBody will not trigger the _body->removeShape function call. + shape->_body = nullptr; shape->setBody(nullptr); - shape->release(); + _shapes->removeObject(shape); } } void PhysicsBody::removeAllShapes() { - for (auto shape : _shapes) + for (auto child : *_shapes) { + PhysicsShape* shape = dynamic_cast(child); + + // deduce the area, mass and moment + // area must update before mass, because the density changes depend on it. + _area -= shape->getArea(); + addMass(-shape->getMass()); + addMoment(-shape->getMoment()); + if (_world) { _world->removeShape(shape); } - delete shape; + // set shape->_body = nullptr make the shape->setBody will not trigger the _body->removeShape function call. + shape->_body = nullptr; + shape->setBody(nullptr); } - _shapes.clear(); + _shapes->removeAllObjects(); +} + +void PhysicsBody::removeFromWorld() +{ + if (_world) + { + _world->removeBody(this); + } } void PhysicsBody::setEnable(bool enable) @@ -591,18 +683,18 @@ void PhysicsBody::setEnable(bool enable) { if (enable) { - _world->addBody(this); + _world->addBodyOrDelay(this); }else { - _world->removeBody(this); + _world->removeBodyOrDelay(this); } } } } -bool PhysicsBody::isResting() +bool PhysicsBody::isResting() const { - return cpBodyIsSleeping(_info->body) == cpTrue; + return cpBodyIsSleeping(_info->getBody()) == cpTrue; } void PhysicsBody::update(float delta) @@ -610,20 +702,59 @@ void PhysicsBody::update(float delta) // damping compute if (_dynamic) { - _info->body->v.x *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f); - _info->body->v.y *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f); - _info->body->w *= cpfclamp(1.0f - delta * _angularDamping, 0.0f, 1.0f); + _info->getBody()->v.x *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f); + _info->getBody()->v.y *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f); + _info->getBody()->w *= cpfclamp(1.0f - delta * _angularDamping, 0.0f, 1.0f); } } -//Clonable* PhysicsBody::clone() const -//{ -// PhysicsBody* body = new PhysicsBody(); -// -// body->autorelease(); -// -// return body; -//} +void PhysicsBody::setCategoryBitmask(int bitmask) +{ + _categoryBitmask = bitmask; + + for (auto shape : *_shapes) + { + ((PhysicsShape*)shape)->setCategoryBitmask(bitmask); + } +} + +void PhysicsBody::setContactTestBitmask(int bitmask) +{ + _contactTestBitmask = bitmask; + + for (auto shape : *_shapes) + { + ((PhysicsShape*)shape)->setContactTestBitmask(bitmask); + } +} + +void PhysicsBody::setCollisionBitmask(int bitmask) +{ + _collisionBitmask = bitmask; + + for (auto shape : *_shapes) + { + ((PhysicsShape*)shape)->setCollisionBitmask(bitmask); + } +} + +void PhysicsBody::setGroup(int group) +{ + for (auto shape : *_shapes) + { + ((PhysicsShape*)shape)->setGroup(group); + } +} + +Point PhysicsBody::world2Local(const Point& point) +{ + return PhysicsHelper::cpv2point(cpBodyWorld2Local(_info->getBody(), PhysicsHelper::point2cpv(point))); +} + +Point PhysicsBody::local2World(const Point& point) +{ + return PhysicsHelper::cpv2point(cpBodyLocal2World(_info->getBody(), PhysicsHelper::point2cpv(point))); +} #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index f1715b0f1a..7f465d561c 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -22,14 +22,15 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - #ifndef __CCPHYSICS_BODY_H__ #define __CCPHYSICS_BODY_H__ +#include "CCPhysicsSetting.h" +#ifdef CC_USE_PHYSICS + #include "CCObject.h" #include "CCGeometry.h" +#include "CCArray.h" #include "CCPhysicsShape.h" @@ -43,7 +44,7 @@ class PhysicsJoint; class PhysicsBodyInfo; -const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT(1.0f, 1.0f, 1.0f); +const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT(0.1f, 0.5f, 0.5f); /** * A body affect by physics. @@ -53,63 +54,67 @@ class PhysicsBody : public Object//, public Clonable { public: static PhysicsBody* create(); + static PhysicsBody* create(float mass); + static PhysicsBody* create(float mass, float moment); /** * @brief Create a body contains a circle shape. */ - static PhysicsBody* createCircle(float radius, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + static PhysicsBody* createCircle(float radius, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); /** * @brief Create a body contains a box shape. */ - static PhysicsBody* createBox(Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + static PhysicsBody* createBox(const Size& size, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); /** * @brief Create a body contains a polygon shape. * points is an array of Point structs defining a convex hull with a clockwise winding. */ - static PhysicsBody* createPolygon(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + static PhysicsBody* createPolygon(const Point* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); /** * @brief Create a body contains a EdgeSegment shape. */ - static PhysicsBody* createEdgeSegment(Point a, Point b, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); + static PhysicsBody* createEdgeSegment(const Point& a, const Point& b, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); /** * @brief Create a body contains a EdgeBox shape. */ - static PhysicsBody* createEdgeBox(Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); + static PhysicsBody* createEdgeBox(const Size& size, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1, const Point& offset = Point::ZERO); /** * @brief Create a body contains a EdgePolygon shape. */ - static PhysicsBody* createEdgePolygon(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); + static PhysicsBody* createEdgePolygon(const Point* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); /** * @brief Create a body contains a EdgeChain shape. */ - static PhysicsBody* createEdgeChain(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); + static PhysicsBody* createEdgeChain(const Point* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); - virtual void addShape(PhysicsShape* shape); + virtual PhysicsShape* addShape(PhysicsShape* shape); /** * @brief Applies a immediate force to body. */ - virtual void applyForce(Point force); + virtual void applyForce(const Vect& force); /** * @brief Applies a immediate force to body. */ - virtual void applyForce(Point force, Point offset); + virtual void applyForce(const Vect& force, const Point& offset); /** * @brief Applies a continuous force to body. */ - virtual void applyImpulse(Point impulse); + virtual void applyImpulse(const Vect& impulse); /** * @brief Applies a continuous force to body. */ - virtual void applyImpulse(Point impulse, Point offset); + virtual void applyImpulse(const Vect& impulse, const Point& offset); /** * @brief Applies a torque force to body. */ virtual void applyTorque(float torque); - virtual void setVelocity(Point velocity); + virtual void setVelocity(const Vect& velocity); virtual Point getVelocity(); virtual void setAngularVelocity(float velocity); + virtual Point getVelocityAtLocalPoint(const Point& point); + virtual Point getVelocityAtWorldPoint(const Point& point); virtual float getAngularVelocity(); virtual void setVelocityLimit(float limit); virtual float getVelocityLimit(); @@ -119,22 +124,24 @@ public: /* * @brief get the body shapes. */ - inline std::vector& getShapes() { return _shapes; } + inline Array* getShapes() const { return _shapes; } /* * @brief get the first body shapes. */ - inline PhysicsShape* getShape() { return _shapes.size() >= 1 ? _shapes.front() : nullptr; } - PhysicsShape* getShapeByTag(int tag); + inline PhysicsShape* getFirstShape() const { return _shapes->count() >= 1 ? dynamic_cast(_shapes->getObjectAtIndex(0)) : nullptr; } + PhysicsShape* getShape(int tag) const; /* * @brief remove a shape from body */ void removeShape(PhysicsShape* shape); - void removeShapeByTag(int tag); + void removeShape(int tag); /* * @brief remove all shapes */ void removeAllShapes(); + void removeFromWorld(); + /* * @brief get the world body added to. */ @@ -142,20 +149,23 @@ public: /* * @brief get all joints the body have */ - inline const std::vector* getJoints() const { return &_joints; } + inline const std::vector& getJoints() const { return _joints; } /* * @brief get the sprite the body set to. */ - inline Sprite* getOwner() const { return _owner; } + inline Node* getNode() const { return _node; } - inline void setCategoryBitmask(int bitmask) { _categoryBitmask = bitmask; } + void setCategoryBitmask(int bitmask); + void setContactTestBitmask(int bitmask); + void setCollisionBitmask(int bitmask); inline int getCategoryBitmask() const { return _categoryBitmask; } - inline void setContactTestBitmask(int bitmask) { _contactTestBitmask = bitmask; } inline int getContactTestBitmask() const { return _contactTestBitmask; } - inline void setCollisionBitmask(int bitmask) { _collisionBitmask = bitmask; } inline int getCollisionBitmask() const { return _collisionBitmask; } + void setGroup(int group); + inline int getGroup() const { return _group; } + /* * @brief get the body position. */ @@ -169,7 +179,7 @@ public: * @brief test the body is dynamic or not. * a dynamic body will effect with gravity. */ - inline bool isDynamic() { return _dynamic; } + inline bool isDynamic() const { return _dynamic; } /* * @brief set dynamic to body. * a dynamic body will effect with gravity. @@ -184,7 +194,7 @@ public: /* * @brief get the body mass. */ - inline float getMass() { return _mass; } + inline float getMass() const { return _mass; } /* * @brief add mass to body. * if _mass(mass of the body) == PHYSICS_INFINITY, it remains. @@ -203,7 +213,7 @@ public: /* * @brief get the body moment of inertia. */ - inline float getMoment(float moment) { return _moment; } + inline float getMoment(float moment) const { return _moment; } /* * @brief add moment of inertia to body. * if _moment(moment of the body) == PHYSICS_INFINITY, it remains. @@ -220,27 +230,29 @@ public: /* * @brief get angular damping. */ - inline float getLinearDamping() { return _linearDamping; } + inline float getLinearDamping() const { return _linearDamping; } inline void setLinearDamping(float damping) { _linearDamping = damping; } - inline float getAngularDamping() { return _angularDamping; } + inline float getAngularDamping() const { return _angularDamping; } inline void setAngularDamping(float damping) { _angularDamping = damping; } //virtual Clonable* clone() const override; - bool isResting(); - inline bool isEnable() { return _enable; } + bool isResting() const; + inline bool isEnabled() const { return _enable; } void setEnable(bool enable); - inline bool isRotationEnable() { return _rotationEnable; } + inline bool isRotationEnabled() const { return _rotationEnable; } void setRotationEnable(bool enable); - inline bool isGravityEnable() { return _gravityEnable; } + inline bool isGravityEnabled() const { return _gravityEnable; } void setGravityEnable(bool enable); - inline int getTag() { return _tag; } + inline int getTag() const { return _tag; } inline void setTag(int tag) { _tag = tag; } + Point world2Local(const Point& point); + Point local2World(const Point& point); protected: @@ -251,14 +263,16 @@ protected: virtual void update(float delta) override; + void removeJoint(PhysicsJoint* joint); + protected: PhysicsBody(); virtual ~PhysicsBody(); protected: - Sprite* _owner; + Node* _node; std::vector _joints; - std::vector _shapes; + Array* _shapes; PhysicsWorld* _world; PhysicsBodyInfo* _info; bool _dynamic; @@ -275,9 +289,10 @@ protected: float _angularDamping; int _tag; - int _categoryBitmask; - int _collisionBitmask; - int _contactTestBitmask; + int _categoryBitmask; + int _collisionBitmask; + int _contactTestBitmask; + int _group; friend class PhysicsWorld; friend class PhysicsShape; @@ -287,6 +302,5 @@ protected: NS_CC_END -#endif // __CCPHYSICS_BODY_H__ - #endif // CC_USE_PHYSICS +#endif // __CCPHYSICS_BODY_H__ diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index 1ec9667d6f..9d6325c150 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -30,16 +30,32 @@ #include "Box2D.h" #endif -#include "chipmunk/CCPhysicsContactInfo.h" -#include "box2d/CCPhysicsContactInfo.h" +#include "CCPhysicsBody.h" + +#include "chipmunk/CCPhysicsContactInfo_chipmunk.h" +#include "box2d/CCPhysicsContactInfo_box2d.h" +#include "chipmunk/CCPhysicsHelper_chipmunk.h" +#include "box2d/CCPhysicsHelper_box2d.h" + +#include "CCEventCustom.h" NS_CC_BEGIN +const char* PHYSICSCONTACT_EVENT_NAME = "PhysicsContactEvent"; + PhysicsContact::PhysicsContact() -: _shapeA(nullptr) +: Event(Event::Type::CUSTOM) +, _world(nullptr) +, _shapeA(nullptr) , _shapeB(nullptr) +, _eventCode(EventCode::NONE) , _info(nullptr) +, _notificationEnable(true) +, _begin(false) , _data(nullptr) +, _contactInfo(nullptr) +, _contactData(nullptr) +, _result(true) { } @@ -47,6 +63,7 @@ PhysicsContact::PhysicsContact() PhysicsContact::~PhysicsContact() { CC_SAFE_DELETE(_info); + CC_SAFE_DELETE(_contactData); } PhysicsContact* PhysicsContact::create(PhysicsShape* a, PhysicsShape* b) @@ -78,37 +95,74 @@ bool PhysicsContact::init(PhysicsShape* a, PhysicsShape* b) return false; } -// PhysicsContactPreSolve implementation -PhysicsContactPreSolve::PhysicsContactPreSolve() +void PhysicsContact::generateContactData() { + if (_contactInfo == nullptr) + { + return; + } + cpArbiter* arb = static_cast(_contactInfo); + _contactData = new PhysicsContactData(); + _contactData->count = cpArbiterGetCount(arb); + for (int i=0; i<_contactData->count; ++i) + { + _contactData->points[i] = PhysicsHelper::cpv2point(cpArbiterGetPoint(arb, i)); + } + + _contactData->normal = _contactData->count > 0 ? PhysicsHelper::cpv2point(cpArbiterGetNormal(arb, 0)) : Point::ZERO; +} + +// PhysicsContactPreSolve implementation +PhysicsContactPreSolve::PhysicsContactPreSolve(PhysicsContactData* data, void* contactInfo) +: _preContactData(data) +, _contactInfo(contactInfo) +{ } PhysicsContactPreSolve::~PhysicsContactPreSolve() { - + CC_SAFE_DELETE(_preContactData); } -PhysicsContactPreSolve* PhysicsContactPreSolve::create() +float PhysicsContactPreSolve::getElasticity() const { - PhysicsContactPreSolve * solve = new PhysicsContactPreSolve(); - if(solve && solve->init()) - { - return solve; - } - - CC_SAFE_DELETE(solve); - return nullptr; + return static_cast(_contactInfo)->e; } -bool PhysicsContactPreSolve::init() +float PhysicsContactPreSolve::getFriciton() const { - return true; + return static_cast(_contactInfo)->u; } +Point PhysicsContactPreSolve::getSurfaceVelocity() const +{ + return PhysicsHelper::cpv2point(static_cast(_contactInfo)->surface_vr); +} + +void PhysicsContactPreSolve::setElasticity(float elasticity) +{ + static_cast(_contactInfo)->e = elasticity; +} + +void PhysicsContactPreSolve::setFriction(float friction) +{ + static_cast(_contactInfo)->u = friction; +} + +void PhysicsContactPreSolve::setSurfaceVelocity(const Vect& velocity) +{ + static_cast(_contactInfo)->surface_vr = PhysicsHelper::point2cpv(velocity); +} + +void PhysicsContactPreSolve::ignore() +{ + cpArbiterIgnore(static_cast(_contactInfo)); +} // PhysicsContactPostSolve implementation -PhysicsContactPostSolve::PhysicsContactPostSolve() +PhysicsContactPostSolve::PhysicsContactPostSolve(void* contactInfo) +: _contactInfo(contactInfo) { } @@ -118,36 +172,330 @@ PhysicsContactPostSolve::~PhysicsContactPostSolve() } -PhysicsContactPostSolve* PhysicsContactPostSolve::create() +float PhysicsContactPostSolve::getElasticity() const { - PhysicsContactPostSolve * solve = new PhysicsContactPostSolve(); - if(solve && solve->init()) - { - return solve; - } - - CC_SAFE_DELETE(solve); - return nullptr; + return static_cast(_contactInfo)->e; } -bool PhysicsContactPostSolve::init() +float PhysicsContactPostSolve::getFriciton() const { - return true; + return static_cast(_contactInfo)->u; } -PhysicsContactListener::PhysicsContactListener() +Point PhysicsContactPostSolve::getSurfaceVelocity() const +{ + return PhysicsHelper::cpv2point(static_cast(_contactInfo)->surface_vr); +} + +EventListenerPhysicsContact::EventListenerPhysicsContact() : onContactBegin(nullptr) , onContactPreSolve(nullptr) , onContactPostSolve(nullptr) -, onContactEnd(nullptr) +, onContactSeperate(nullptr) +{ +} + +bool EventListenerPhysicsContact::init() +{ + auto func = [this](EventCustom* event) -> void + { + onEvent(event); + }; + + return EventListenerCustom::init(std::hash()(PHYSICSCONTACT_EVENT_NAME), func); +} + +void EventListenerPhysicsContact::onEvent(EventCustom* event) +{ + PhysicsContact& contact = *(PhysicsContact*)(event->getUserData()); + + switch (contact.getEventCode()) + { + case PhysicsContact::EventCode::BEGIN: + { + bool ret = true; + + if (onContactBegin != nullptr + && test(contact.getShapeA(), contact.getShapeB())) + { + contact._begin = true; + contact.generateContactData(); + + // the mask has high priority than _listener->onContactBegin. + // so if the mask test is false, the two bodies won't have collision. + if (ret) + { + ret = onContactBegin(event, contact); + }else + { + onContactBegin(event, contact); + } + } + + contact.setResult(ret); + break; + } + case PhysicsContact::EventCode::PRESOLVE: + { + bool ret = true; + + if (onContactPreSolve != nullptr + && test(contact.getShapeA(), contact.getShapeB())) + { + PhysicsContactPreSolve solve(contact._begin ? nullptr : contact._contactData, contact._contactInfo); + contact._begin = false; + contact.generateContactData(); + + ret = onContactPreSolve(event, contact, solve); + } + + contact.setResult(ret); + break; + } + case PhysicsContact::EventCode::POSTSOLVE: + { + if (onContactPostSolve != nullptr + && test(contact.getShapeA(), contact.getShapeB())) + { + PhysicsContactPostSolve solve(contact._contactInfo); + onContactPostSolve(event, contact, solve); + } + break; + } + case PhysicsContact::EventCode::SEPERATE: + { + if (onContactSeperate != nullptr + && test(contact.getShapeA(), contact.getShapeB())) + { + onContactSeperate(event, contact); + } + break; + } + default: + break; + } +} + +EventListenerPhysicsContact::~EventListenerPhysicsContact() { } -PhysicsContactListener::~PhysicsContactListener() +EventListenerPhysicsContact* EventListenerPhysicsContact::create() +{ + EventListenerPhysicsContact* obj = new EventListenerPhysicsContact(); + + if (obj != nullptr && obj->init()) + { + obj->autorelease(); + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + +bool EventListenerPhysicsContact::test(PhysicsShape* shapeA, PhysicsShape* shapeB) +{ + CC_UNUSED_PARAM(shapeA); + CC_UNUSED_PARAM(shapeB); + return true; +} + +bool EventListenerPhysicsContact::checkAvailable() +{ + if (onContactBegin == nullptr && onContactPreSolve == nullptr + && onContactPostSolve == nullptr && onContactSeperate == nullptr) + { + CCASSERT(false, "Invalid PhysicsContactListener."); + return false; + } + + return true; +} + +EventListenerPhysicsContact* EventListenerPhysicsContact::clone() +{ + EventListenerPhysicsContact* obj = EventListenerPhysicsContact::create(); + + if (obj != nullptr) + { + obj->onContactBegin = onContactBegin; + obj->onContactPreSolve = onContactPreSolve; + obj->onContactPostSolve = onContactPostSolve; + obj->onContactSeperate = onContactSeperate; + + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + +EventListenerPhysicsContactWithBodies* EventListenerPhysicsContactWithBodies::create(PhysicsBody* bodyA, PhysicsBody* bodyB) +{ + EventListenerPhysicsContactWithBodies* obj = new EventListenerPhysicsContactWithBodies(); + + if (obj != nullptr && obj->init()) + { + obj->_a = bodyA; + obj->_b = bodyB; + obj->autorelease(); + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + +EventListenerPhysicsContactWithBodies::EventListenerPhysicsContactWithBodies() +: _a(nullptr) +, _b(nullptr) { } +EventListenerPhysicsContactWithBodies::~EventListenerPhysicsContactWithBodies() +{ + +} + + +bool EventListenerPhysicsContactWithBodies::test(PhysicsShape* shapeA, PhysicsShape* shapeB) +{ + if ((shapeA->getBody() == _a && shapeB->getBody() == _b) + || (shapeA->getBody() == _b && shapeB->getBody() == _a)) + { + return true; + } + + return false; +} + +EventListenerPhysicsContactWithBodies* EventListenerPhysicsContactWithBodies::clone() +{ + EventListenerPhysicsContactWithBodies* obj = EventListenerPhysicsContactWithBodies::create(_a, _b); + + if (obj != nullptr) + { + obj->onContactBegin = onContactBegin; + obj->onContactPreSolve = onContactPreSolve; + obj->onContactPostSolve = onContactPostSolve; + obj->onContactSeperate = onContactSeperate; + + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + +EventListenerPhysicsContactWithShapes::EventListenerPhysicsContactWithShapes() +: _a(nullptr) +, _b(nullptr) +{ +} + +EventListenerPhysicsContactWithShapes::~EventListenerPhysicsContactWithShapes() +{ +} + +EventListenerPhysicsContactWithShapes* EventListenerPhysicsContactWithShapes::create(PhysicsShape* shapeA, PhysicsShape* shapeB) +{ + EventListenerPhysicsContactWithShapes* obj = new EventListenerPhysicsContactWithShapes(); + + if (obj != nullptr && obj->init()) + { + obj->_a = shapeA; + obj->_b = shapeB; + obj->autorelease(); + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + +bool EventListenerPhysicsContactWithShapes::test(PhysicsShape* shapeA, PhysicsShape* shapeB) +{ + if ((shapeA == _a && shapeB == _b) + || (shapeA == _b && shapeB == _a)) + { + return true; + } + + return false; +} + +EventListenerPhysicsContactWithShapes* EventListenerPhysicsContactWithShapes::clone() +{ + EventListenerPhysicsContactWithShapes* obj = EventListenerPhysicsContactWithShapes::create(_a, _b); + + if (obj != nullptr) + { + obj->onContactBegin = onContactBegin; + obj->onContactPreSolve = onContactPreSolve; + obj->onContactPostSolve = onContactPostSolve; + obj->onContactSeperate = onContactSeperate; + + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + +EventListenerPhysicsContactWithGroup::EventListenerPhysicsContactWithGroup() +: _group(CP_NO_GROUP) +{ +} + +EventListenerPhysicsContactWithGroup::~EventListenerPhysicsContactWithGroup() +{ +} + +EventListenerPhysicsContactWithGroup* EventListenerPhysicsContactWithGroup::create(int group) +{ + EventListenerPhysicsContactWithGroup* obj = new EventListenerPhysicsContactWithGroup(); + + if (obj != nullptr && obj->init()) + { + obj->_group = group; + obj->autorelease(); + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + +bool EventListenerPhysicsContactWithGroup::test(PhysicsShape* shapeA, PhysicsShape* shapeB) +{ + if (shapeA->getGroup() == _group || shapeB->getGroup() == _group) + { + return true; + } + + return false; +} + +EventListenerPhysicsContactWithGroup* EventListenerPhysicsContactWithGroup::clone() +{ + EventListenerPhysicsContactWithGroup* obj = EventListenerPhysicsContactWithGroup::create(_group); + + if (obj != nullptr) + { + obj->onContactBegin = onContactBegin; + obj->onContactPreSolve = onContactPreSolve; + obj->onContactPostSolve = onContactPostSolve; + obj->onContactSeperate = onContactSeperate; + + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + NS_CC_END #endif // CC_USE_PHYSICS diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 9b9e3044c0..7117d746ce 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -22,28 +22,53 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - #ifndef __CCPHYSICS_CONTACT_H__ #define __CCPHYSICS_CONTACT_H__ +#include "CCPhysicsSetting.h" +#ifdef CC_USE_PHYSICS + #include "CCObject.h" #include "CCGeometry.h" +#include "CCEventListenerCustom.h" +#include "CCEvent.h" NS_CC_BEGIN class PhysicsShape; +class PhysicsBody; class PhysicsWorld; class PhysicsContactInfo; + +typedef struct PhysicsContactData +{ + Point points[PHYSICS_CONTACT_POINT_MAX]; + int count; + Point normal; + + PhysicsContactData() + : count(0) + {} +}PhysicsContactData; + /** * @brief Contact infomation. it will created automatically when two shape contact with each other. and it will destoried automatically when two shape separated. */ -class PhysicsContact +class PhysicsContact : Event { public: + + enum class EventCode + { + NONE, + BEGIN, + PRESOLVE, + POSTSOLVE, + SEPERATE + }; + /* * @brief get contact shape A. */ @@ -52,35 +77,53 @@ public: * @brief get contact shape B. */ inline PhysicsShape* getShapeB() const { return _shapeB; } + inline const PhysicsContactData* getContactData() const { return _contactData; } /* * @brief get data. */ - inline void* getData() { return _data; } + inline void* getData() const { return _data; } /* * @brief set data to contact. you must manage the memory yourself, Generally you can set data at contact begin, and distory it at contact end. */ inline void setData(void* data) { _data = data; } + EventCode getEventCode() const { return _eventCode; }; + private: static PhysicsContact* create(PhysicsShape* a, PhysicsShape* b); bool init(PhysicsShape* a, PhysicsShape* b); - inline bool getNotify() { return _notify; } - inline void setNotify(bool notify) { _notify = notify; } + void setEventCode(EventCode eventCode) { _eventCode = eventCode; }; + inline bool isNotificationEnabled() const { return _notificationEnable; } + inline void setNotificationEnable(bool enable) { _notificationEnable = enable; } + inline PhysicsWorld* getWorld() const { return _world; } + inline void setWorld(PhysicsWorld* world) { _world = world; } + inline void setResult(bool result) { _result = result; } + inline bool resetResult() { bool ret = _result; _result = true; return ret; } + + void generateContactData(); private: PhysicsContact(); ~PhysicsContact(); private: + PhysicsWorld* _world; PhysicsShape* _shapeA; PhysicsShape* _shapeB; + EventCode _eventCode; PhysicsContactInfo* _info; - void* _data; - bool _notify; + bool _notificationEnable; + bool _begin; + bool _result; - friend class PhysicsWorld; + void* _data; + void* _contactInfo; + PhysicsContactData* _contactData; + + friend class EventListenerPhysicsContact; friend class PhysicsWorldCallback; + friend class PhysicsWorld; }; /* @@ -88,14 +131,28 @@ private: */ class PhysicsContactPreSolve { +public: + // getter/setter + float getElasticity() const; + float getFriciton() const; + Point getSurfaceVelocity() const; + void setElasticity(float elasticity); + void setFriction(float friction); + void setSurfaceVelocity(const Vect& velocity); + void ignore(); + private: - PhysicsContactPreSolve(); + PhysicsContactPreSolve(PhysicsContactData* data, void* contactInfo); ~PhysicsContactPreSolve(); - static PhysicsContactPreSolve* create(); - bool init(); +private: + float _elasticity; + float _friction; + Point _surfaceVelocity; + PhysicsContactData* _preContactData; + void* _contactInfo; - friend class PhysicsWorldCallback; + friend class EventListenerPhysicsContact; }; /* @@ -103,46 +160,113 @@ private: */ class PhysicsContactPostSolve { +public: + // getter + float getElasticity() const; + float getFriciton() const; + Point getSurfaceVelocity() const; + private: - PhysicsContactPostSolve(); + PhysicsContactPostSolve(void* contactInfo); ~PhysicsContactPostSolve(); - static PhysicsContactPostSolve* create(); - bool init(); +private: + void* _contactInfo; - friend class PhysicsWorldCallback; + friend class EventListenerPhysicsContact; }; /* * @brief contact listener. */ -class PhysicsContactListener +class EventListenerPhysicsContact : public EventListenerCustom { public: - PhysicsContactListener(); - virtual ~PhysicsContactListener(); + static EventListenerPhysicsContact* create(); + + virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB); + virtual bool checkAvailable() override; + virtual EventListenerPhysicsContact* clone() override; public: /* * @brief it will called at two shapes start to contact, and only call it once. */ - std::function onContactBegin; + std::function onContactBegin; /* * @brief Two shapes are touching during this step. Return false from the callback to make world ignore the collision this step or true to process it normally. Additionally, you may override collision values, elasticity, or surface velocity values. */ - std::function onContactPreSolve; + std::function onContactPreSolve; /* * @brief Two shapes are touching and their collision response has been processed. You can retrieve the collision impulse or kinetic energy at this time if you want to use it to calculate sound volumes or damage amounts. See cpArbiter for more info */ - std::function onContactPostSolve; + std::function onContactPostSolve; /* * @brief it will called at two shapes separated, and only call it once. - * onContactBegin and onContactEnd will called in pairs. + * onContactBegin and onContactSeperate will called in pairs. */ - std::function onContactEnd; + std::function onContactSeperate; + +protected: + bool init(); + void onEvent(EventCustom* event); + +protected: + EventListenerPhysicsContact(); + virtual ~EventListenerPhysicsContact(); +}; + +class EventListenerPhysicsContactWithBodies : public EventListenerPhysicsContact +{ +public: + static EventListenerPhysicsContactWithBodies* create(PhysicsBody* bodyA, PhysicsBody* bodyB); + + virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB) override; + virtual EventListenerPhysicsContactWithBodies* clone() override; + +protected: + PhysicsBody* _a; + PhysicsBody* _b; + +protected: + EventListenerPhysicsContactWithBodies(); + virtual ~EventListenerPhysicsContactWithBodies(); +}; + +class EventListenerPhysicsContactWithShapes : public EventListenerPhysicsContact +{ +public: + static EventListenerPhysicsContactWithShapes* create(PhysicsShape* shapeA, PhysicsShape* shapeB); + + virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB) override; + virtual EventListenerPhysicsContactWithShapes* clone() override; + +protected: + PhysicsShape* _a; + PhysicsShape* _b; + +protected: + EventListenerPhysicsContactWithShapes(); + virtual ~EventListenerPhysicsContactWithShapes(); +}; + +class EventListenerPhysicsContactWithGroup : public EventListenerPhysicsContact +{ +public: + static EventListenerPhysicsContactWithGroup* create(int group); + + virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB) override; + virtual EventListenerPhysicsContactWithGroup* clone() override; + +protected: + int _group; + +protected: + EventListenerPhysicsContactWithGroup(); + virtual ~EventListenerPhysicsContactWithGroup(); }; NS_CC_END -#endif //__CCPHYSICS_CONTACT_H__ #endif // CC_USE_PHYSICS +#endif //__CCPHYSICS_CONTACT_H__ diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 6cca90dd5b..578b8fefc7 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -32,24 +32,28 @@ #endif #include "CCPhysicsBody.h" +#include "CCPhysicsWorld.h" -#include "chipmunk/CCPhysicsJointInfo.h" -#include "box2d/CCPhysicsJointInfo.h" -#include "chipmunk/CCPhysicsBodyInfo.h" -#include "box2d/CCPhysicsBodyInfo.h" -#include "chipmunk/CCPhysicsShapeInfo.h" -#include "box2d/CCPhysicsShapeInfo.h" -#include "chipmunk/CCPhysicsHelper.h" -#include "box2d/CCPhysicsHelper.h" +#include "chipmunk/CCPhysicsJointInfo_chipmunk.h" +#include "box2d/CCPhysicsJointInfo_box2d.h" +#include "chipmunk/CCPhysicsBodyInfo_chipmunk.h" +#include "box2d/CCPhysicsBodyInfo_box2d.h" +#include "chipmunk/CCPhysicsShapeInfo_chipmunk.h" +#include "box2d/CCPhysicsShapeInfo_box2d.h" +#include "chipmunk/CCPhysicsHelper_chipmunk.h" +#include "box2d/CCPhysicsHelper_box2d.h" +#include "CCNode.h" NS_CC_BEGIN PhysicsJoint::PhysicsJoint() : _bodyA(nullptr) , _bodyB(nullptr) +, _world(nullptr) , _info(nullptr) , _enable(false) , _collisionEnable(true) +, _destoryMark(false) , _tag(0) { @@ -61,9 +65,6 @@ PhysicsJoint::~PhysicsJoint() setCollisionEnable(true); CC_SAFE_DELETE(_info); - - CC_SAFE_RELEASE(_bodyA); - CC_SAFE_RELEASE(_bodyB); } bool PhysicsJoint::init(cocos2d::PhysicsBody *a, cocos2d::PhysicsBody *b) @@ -75,14 +76,12 @@ bool PhysicsJoint::init(cocos2d::PhysicsBody *a, cocos2d::PhysicsBody *b) if (a != nullptr) { _bodyA = a; - _bodyA->retain(); _bodyA->_joints.push_back(this); } if (b != nullptr) { _bodyB = b; - _bodyB->retain(); _bodyB->_joints.push_back(this); } @@ -98,12 +97,15 @@ void PhysicsJoint::setEnable(bool enable) { _enable = enable; - if (enable) + if (_world != nullptr) { - - }else - { - + if (enable) + { + _world->addJointOrDelay(this); + }else + { + _world->removeJointOrDelay(this); + } } } } @@ -148,33 +150,76 @@ PhysicsJointLimit::~PhysicsJointLimit() } +PhysicsJointDistance::PhysicsJointDistance() +{ + +} + +PhysicsJointDistance::~PhysicsJointDistance() +{ + +} + #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -PhysicsBodyInfo* PhysicsJoint::bodyInfo(PhysicsBody* body) const +PhysicsBodyInfo* PhysicsJoint::getBodyInfo(PhysicsBody* body) const { return body->_info; } +Node* PhysicsJoint::getBodyNode(PhysicsBody* body) const +{ + return body->_node; +} + void PhysicsJoint::setCollisionEnable(bool enable) { if (_collisionEnable != enable) { _collisionEnable = enable; - - for (auto shape : _bodyB->_shapes) + } +} + +void PhysicsJoint::removeFormWorld() +{ + if (_world) + { + _world->removeJoint(this, false); + } +} + +void PhysicsJoint::destroy(PhysicsJoint* joint) +{ + if (joint!= nullptr) + { + // remove the joint and delete it. + if (joint->_world != nullptr) { - shape->_info->setGroup(enable ? _bodyB->_info->group : _bodyA->_info->group); + joint->_world->removeJoint(joint, true); + } + else + { + if (joint->_bodyA != nullptr) + { + joint->_bodyA->removeJoint(joint); + } + + if (joint->_bodyB != nullptr) + { + joint->_bodyB->removeJoint(joint); + } + + delete joint; } } } -PhysicsJointFixed* PhysicsJointFixed::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr) +PhysicsJointFixed* PhysicsJointFixed::construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr) { PhysicsJointFixed* joint = new PhysicsJointFixed(); if (joint && joint->init(a, b, anchr)) { - joint->autorelease(); return joint; } @@ -188,15 +233,18 @@ bool PhysicsJointFixed::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr) { CC_BREAK_IF(!PhysicsJoint::init(a, b)); + getBodyNode(a)->setPosition(anchr); + getBodyNode(b)->setPosition(anchr); + // add a pivot joint to fixed two body together - cpConstraint* joint = cpPivotJointNew(bodyInfo(a)->body, bodyInfo(b)->body, + cpConstraint* joint = cpPivotJointNew(getBodyInfo(a)->getBody(), getBodyInfo(b)->getBody(), PhysicsHelper::point2cpv(anchr)); - CC_BREAK_IF(joint); + CC_BREAK_IF(joint == nullptr); _info->add(joint); // add a gear joint to make two body have the same rotation. - joint = cpGearJointNew(bodyInfo(a)->body, bodyInfo(b)->body, 0, 1); - CC_BREAK_IF(joint); + joint = cpGearJointNew(getBodyInfo(a)->getBody(), getBodyInfo(b)->getBody(), 0, 1); + CC_BREAK_IF(joint == nullptr); _info->add(joint); setCollisionEnable(false); @@ -207,13 +255,12 @@ bool PhysicsJointFixed::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr) return false; } -PhysicsJointPin* PhysicsJointPin::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr) +PhysicsJointPin* PhysicsJointPin::construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr) { PhysicsJointPin* joint = new PhysicsJointPin(); if (joint && joint->init(a, b, anchr)) { - joint->autorelease(); return joint; } @@ -226,23 +273,30 @@ bool PhysicsJointPin::init(PhysicsBody *a, PhysicsBody *b, const Point& anchr) do { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - - cpConstraint* joint = cpPivotJointNew(bodyInfo(a)->body, bodyInfo(b)->body, + cpConstraint* joint = cpPivotJointNew(getBodyInfo(a)->getBody(), getBodyInfo(b)->getBody(), PhysicsHelper::point2cpv(anchr)); - CC_BREAK_IF(joint); + CC_BREAK_IF(joint == nullptr); _info->add(joint); - setCollisionEnable(false); - return true; } while (false); return false; } -PhysicsJointSliding* PhysicsJointSliding::create(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr) +void PhysicsJointPin::setMaxForce(float force) +{ + _info->getJoints().front()->maxForce = PhysicsHelper::float2cpfloat(force); +} + +float PhysicsJointPin::getMaxForce() const +{ + return PhysicsHelper::cpfloat2float(_info->getJoints().front()->maxForce); +} + +PhysicsJointSliding* PhysicsJointSliding::construct(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr) { PhysicsJointSliding* joint = new PhysicsJointSliding(); @@ -261,12 +315,12 @@ bool PhysicsJointSliding::init(PhysicsBody* a, PhysicsBody* b, const Point& groo { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - cpConstraint* joint = cpGrooveJointNew(bodyInfo(a)->body, bodyInfo(b)->body, + cpConstraint* joint = cpGrooveJointNew(getBodyInfo(a)->getBody(), getBodyInfo(b)->getBody(), PhysicsHelper::point2cpv(grooveA), PhysicsHelper::point2cpv(grooveB), PhysicsHelper::point2cpv(anchr)); - CC_BREAK_IF(joint); + CC_BREAK_IF(joint == nullptr); _info->add(joint); @@ -277,7 +331,7 @@ bool PhysicsJointSliding::init(PhysicsBody* a, PhysicsBody* b, const Point& groo } -PhysicsJointLimit* PhysicsJointLimit::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) +PhysicsJointLimit* PhysicsJointLimit::construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) { PhysicsJointLimit* joint = new PhysicsJointLimit(); @@ -296,13 +350,13 @@ bool PhysicsJointLimit::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1 { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - cpConstraint* joint = cpSlideJointNew(bodyInfo(a)->body, bodyInfo(b)->body, + cpConstraint* joint = cpSlideJointNew(getBodyInfo(a)->getBody(), getBodyInfo(b)->getBody(), PhysicsHelper::point2cpv(anchr1), PhysicsHelper::point2cpv(anchr2), 0, PhysicsHelper::float2cpfloat(anchr1.getDistance(anchr2))); - CC_BREAK_IF(joint); + CC_BREAK_IF(joint == nullptr); _info->add(joint); @@ -312,24 +366,57 @@ bool PhysicsJointLimit::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1 return false; } -float PhysicsJointLimit::getMin() +float PhysicsJointLimit::getMin() const { - return PhysicsHelper::cpfloat2float(cpSlideJointGetMin(_info->joints.front())); + return PhysicsHelper::cpfloat2float(cpSlideJointGetMin(_info->getJoints().front())); } void PhysicsJointLimit::setMin(float min) { - cpSlideJointSetMin(_info->joints.front(), PhysicsHelper::float2cpfloat(min)); + cpSlideJointSetMin(_info->getJoints().front(), PhysicsHelper::float2cpfloat(min)); } -float PhysicsJointLimit::getMax() +float PhysicsJointLimit::getMax() const { - return PhysicsHelper::cpfloat2float(cpSlideJointGetMax(_info->joints.front())); + return PhysicsHelper::cpfloat2float(cpSlideJointGetMax(_info->getJoints().front())); } void PhysicsJointLimit::setMax(float max) { - cpSlideJointSetMax(_info->joints.front(), PhysicsHelper::float2cpfloat(max)); + cpSlideJointSetMax(_info->getJoints().front(), PhysicsHelper::float2cpfloat(max)); +} + +PhysicsJointDistance* PhysicsJointDistance::construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) +{ + PhysicsJointDistance* joint = new PhysicsJointDistance(); + + if (joint && joint->init(a, b, anchr1, anchr2)) + { + return joint; + } + + CC_SAFE_DELETE(joint); + return nullptr; +} + +bool PhysicsJointDistance::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) +{ + do + { + CC_BREAK_IF(!PhysicsJoint::init(a, b)); + + cpConstraint* joint = cpPinJointNew(getBodyInfo(a)->getBody(), + getBodyInfo(b)->getBody(), + PhysicsHelper::point2cpv(anchr1), PhysicsHelper::point2cpv(anchr2)); + + CC_BREAK_IF(joint == nullptr); + + _info->add(joint); + + return true; + } while (false); + + return false; } #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) diff --git a/cocos/physics/CCPhysicsJoint.h b/cocos/physics/CCPhysicsJoint.h index 04f85d0d0c..789d64a5b2 100644 --- a/cocos/physics/CCPhysicsJoint.h +++ b/cocos/physics/CCPhysicsJoint.h @@ -22,39 +22,43 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - #ifndef __CCPHYSICS_JOINT_H__ #define __CCPHYSICS_JOINT_H__ +#include "CCPhysicsSetting.h" +#ifdef CC_USE_PHYSICS + #include "CCObject.h" #include "CCGeometry.h" NS_CC_BEGIN class PhysicsBody; +class PhysicsWorld; class PhysicsJointInfo; class PhysicsBodyInfo; /* * @brief An PhysicsJoint object connects two physics bodies together. */ -class PhysicsJoint : public Object +class PhysicsJoint { protected: PhysicsJoint(); virtual ~PhysicsJoint() = 0; public: - PhysicsBody* getBodyA() { return _bodyA; } - PhysicsBody* getBodyB() { return _bodyB; } - inline int getTag() { return _tag; } + inline PhysicsBody* getBodyA() const { return _bodyA; } + inline PhysicsBody* getBodyB() const { return _bodyB; } + inline PhysicsWorld* getWorld() const { return _world; } + inline int getTag() const { return _tag; } inline void setTag(int tag) { _tag = tag; } - inline bool isEnable() { return _enable; } + inline bool isEnabled() const { return _enable; } void setEnable(bool enable); - inline bool isCollisionEnable() { return _collisionEnable; } + inline bool isCollisionEnabled() const { return _collisionEnable; } void setCollisionEnable(bool enable); + void removeFormWorld(); + static void destroy(PhysicsJoint* joint); protected: bool init(PhysicsBody* a, PhysicsBody* b); @@ -62,14 +66,17 @@ protected: /** * PhysicsShape is PhysicsBody's friend class, but all the subclasses isn't. so this method is use for subclasses to catch the bodyInfo from PhysicsBody. */ - PhysicsBodyInfo* bodyInfo(PhysicsBody* body) const; + PhysicsBodyInfo* getBodyInfo(PhysicsBody* body) const; + Node* getBodyNode(PhysicsBody* body) const; protected: PhysicsBody* _bodyA; PhysicsBody* _bodyB; + PhysicsWorld* _world; PhysicsJointInfo* _info; bool _enable; bool _collisionEnable; + bool _destoryMark; int _tag; friend class PhysicsBody; @@ -82,7 +89,7 @@ protected: class PhysicsJointFixed : public PhysicsJoint { public: - PhysicsJointFixed* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr); + static PhysicsJointFixed* construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr); protected: bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr); @@ -98,7 +105,7 @@ protected: class PhysicsJointSliding : public PhysicsJoint { public: - PhysicsJointSliding* create(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr); + static PhysicsJointSliding* construct(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr); protected: bool init(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr); @@ -114,7 +121,7 @@ protected: class PhysicsJointSpring : public PhysicsJoint { public: - PhysicsJointSpring* create(); + PhysicsJointSpring* construct(); protected: bool init(); @@ -130,11 +137,11 @@ protected: class PhysicsJointLimit : public PhysicsJoint { public: - PhysicsJointLimit* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); + PhysicsJointLimit* construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); - float getMin(); + float getMin() const; void setMin(float min); - float getMax(); + float getMax() const; void setMax(float max); protected: @@ -151,7 +158,10 @@ protected: class PhysicsJointPin : public PhysicsJoint { public: - static PhysicsJointPin* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr); + static PhysicsJointPin* construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr); + + void setMaxForce(float force); + float getMaxForce() const; protected: bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr); @@ -161,8 +171,21 @@ protected: virtual ~PhysicsJointPin(); }; +class PhysicsJointDistance : public PhysicsJoint +{ + +public: + static PhysicsJointDistance* construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); + +protected: + bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); + +protected: + PhysicsJointDistance(); + virtual ~PhysicsJointDistance(); +}; + NS_CC_END -#endif // __CCPHYSICS_JOINT_H__ - #endif // CC_USE_PHYSICS +#endif // __CCPHYSICS_JOINT_H__ diff --git a/cocos/physics/CCPhysicsSetting.h b/cocos/physics/CCPhysicsSetting.h index b29b12054d..9eb82f2fa2 100644 --- a/cocos/physics/CCPhysicsSetting.h +++ b/cocos/physics/CCPhysicsSetting.h @@ -46,6 +46,14 @@ namespace cocos2d { extern const float PHYSICS_INFINITY; + + class Point; + typedef Point Vect; + +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) + static const int PHYSICS_CONTACT_POINT_MAX = 4; +#else +#endif } #endif // __CCPHYSICS_SETTING_H__ diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index 6ffd7d86aa..bb043b027a 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -25,6 +25,8 @@ #include "CCPhysicsShape.h" #ifdef CC_USE_PHYSICS +#include + #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #elif (CC_PHYSICS_ENGINE == CCPHYSICS_BOX2D) @@ -34,11 +36,11 @@ #include "CCPhysicsBody.h" #include "CCPhysicsWorld.h" -#include "chipmunk/CCPhysicsBodyInfo.h" -#include "box2d/CCPhysicsBodyInfo.h" -#include "chipmunk/CCPhysicsShapeInfo.h" -#include "box2d/CCPhysicsShapeInfo.h" -#include "chipmunk/CCPhysicsHelper.h" +#include "chipmunk/CCPhysicsBodyInfo_chipmunk.h" +#include "box2d/CCPhysicsBodyInfo_box2d.h" +#include "chipmunk/CCPhysicsShapeInfo_chipmunk.h" +#include "box2d/CCPhysicsShapeInfo_box2d.h" +#include "chipmunk/CCPhysicsHelper_chipmunk.h" NS_CC_BEGIN @@ -50,6 +52,10 @@ PhysicsShape::PhysicsShape() , _mass(0) , _moment(0) , _tag(0) +, _categoryBitmask(UINT_MAX) +, _collisionBitmask(UINT_MAX) +, _contactTestBitmask(UINT_MAX) +, _group(0) { } @@ -101,7 +107,7 @@ void PhysicsShape::setMoment(float moment) _moment = moment; } -void PhysicsShape::setMaterial(PhysicsMaterial material) +void PhysicsShape::setMaterial(const PhysicsMaterial& material) { setDensity(material.density); setRestitution(material.restitution); @@ -212,7 +218,7 @@ void PhysicsShape::setRestitution(float restitution) { _material.restitution = restitution; - for (cpShape* shape : _info->shapes) + for (cpShape* shape : _info->getShapes()) { cpShapeSetElasticity(shape, PhysicsHelper::float2cpfloat(restitution)); } @@ -222,14 +228,14 @@ void PhysicsShape::setFriction(float friction) { _material.friction = friction; - for (cpShape* shape : _info->shapes) + for (cpShape* shape : _info->getShapes()) { cpShapeSetFriction(shape, PhysicsHelper::float2cpfloat(friction)); } } -Point* PhysicsShape::recenterPoints(Point* points, int count, Point center) +Point* PhysicsShape::recenterPoints(Point* points, int count, const Point& center) { cpVect* cpvs = new cpVect[count]; cpRecenterPoly(count, PhysicsHelper::points2cpvs(points, cpvs, count)); @@ -247,7 +253,7 @@ Point* PhysicsShape::recenterPoints(Point* points, int count, Point center) return points; } -Point PhysicsShape::getPolyonCenter(Point* points, int count) +Point PhysicsShape::getPolyonCenter(const Point* points, int count) { cpVect* cpvs = new cpVect[count]; cpVect center = cpCentroidForPoly(count, PhysicsHelper::points2cpvs(points, cpvs, count)); @@ -259,7 +265,7 @@ Point PhysicsShape::getPolyonCenter(Point* points, int count) void PhysicsShape::setBody(PhysicsBody *body) { // already added - if (_body == body) + if (body != nullptr && _body == body) { return; } @@ -272,18 +278,16 @@ void PhysicsShape::setBody(PhysicsBody *body) if (body == nullptr) { _info->setBody(nullptr); - _info->setGroup(CP_NO_GROUP); _body = nullptr; }else { - _info->setBody(body->_info->body); - _info->setGroup(body->_info->group); + _info->setBody(body->_info->getBody()); _body = body; } } // PhysicsShapeCircle -PhysicsShapeCircle* PhysicsShapeCircle::create(float radius, PhysicsMaterial material/* = MaterialDefault*/, Point offset/* = Point(0, 0)*/) +PhysicsShapeCircle* PhysicsShapeCircle::create(float radius, const PhysicsMaterial& material/* = MaterialDefault*/, const Point& offset/* = Point(0, 0)*/) { PhysicsShapeCircle* shape = new PhysicsShapeCircle(); if (shape && shape->init(radius, material, offset)) @@ -296,13 +300,13 @@ PhysicsShapeCircle* PhysicsShapeCircle::create(float radius, PhysicsMaterial mat return nullptr; } -bool PhysicsShapeCircle::init(float radius, PhysicsMaterial material/* = MaterialDefault*/, Point offset /*= Point(0, 0)*/) +bool PhysicsShapeCircle::init(float radius, const PhysicsMaterial& material/* = MaterialDefault*/, const Point& offset /*= Point(0, 0)*/) { do { CC_BREAK_IF(!PhysicsShape::init(Type::CIRCLE)); - cpShape* shape = cpCircleShapeNew(_info->shareBody, radius, PhysicsHelper::point2cpv(offset)); + cpShape* shape = cpCircleShapeNew(_info->getSharedBody(), radius, PhysicsHelper::point2cpv(offset)); CC_BREAK_IF(shape == nullptr); @@ -324,7 +328,7 @@ float PhysicsShapeCircle::calculateArea(float radius) return PhysicsHelper::cpfloat2float(cpAreaForCircle(0, radius)); } -float PhysicsShapeCircle::calculateMoment(float mass, float radius, Point offset) +float PhysicsShapeCircle::calculateMoment(float mass, float radius, const Point& offset) { return mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : PhysicsHelper::cpfloat2float(cpMomentForCircle(PhysicsHelper::float2cpfloat(mass), @@ -335,12 +339,12 @@ float PhysicsShapeCircle::calculateMoment(float mass, float radius, Point offset float PhysicsShapeCircle::calculateDefaultArea() { - return PhysicsHelper::cpfloat2float(cpAreaForCircle(0, cpCircleShapeGetRadius(_info->shapes.front()))); + return PhysicsHelper::cpfloat2float(cpAreaForCircle(0, cpCircleShapeGetRadius(_info->getShapes().front()))); } float PhysicsShapeCircle::calculateDefaultMoment() { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : PhysicsHelper::cpfloat2float(cpMomentForCircle(PhysicsHelper::float2cpfloat(_mass), @@ -349,18 +353,18 @@ float PhysicsShapeCircle::calculateDefaultMoment() cpCircleShapeGetOffset(shape))); } -float PhysicsShapeCircle::getRadius() +float PhysicsShapeCircle::getRadius() const { - return PhysicsHelper::cpfloat2float(cpCircleShapeGetRadius(_info->shapes.front())); + return PhysicsHelper::cpfloat2float(cpCircleShapeGetRadius(_info->getShapes().front())); } Point PhysicsShapeCircle::getOffset() { - return PhysicsHelper::cpv2point(cpCircleShapeGetOffset(_info->shapes.front())); + return PhysicsHelper::cpv2point(cpCircleShapeGetOffset(_info->getShapes().front())); } // PhysicsShapeEdgeSegment -PhysicsShapeEdgeSegment* PhysicsShapeEdgeSegment::create(Point a, Point b, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) +PhysicsShapeEdgeSegment* PhysicsShapeEdgeSegment::create(const Point& a, const Point& b, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/) { PhysicsShapeEdgeSegment* shape = new PhysicsShapeEdgeSegment(); if (shape && shape->init(a, b, material, border)) @@ -373,13 +377,13 @@ PhysicsShapeEdgeSegment* PhysicsShapeEdgeSegment::create(Point a, Point b, Physi return nullptr; } -bool PhysicsShapeEdgeSegment::init(Point a, Point b, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) +bool PhysicsShapeEdgeSegment::init(const Point& a, const Point& b, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/) { do { CC_BREAK_IF(!PhysicsShape::init(Type::EDGESEGMENT)); - cpShape* shape = cpSegmentShapeNew(_info->shareBody, + cpShape* shape = cpSegmentShapeNew(_info->getSharedBody(), PhysicsHelper::point2cpv(a), PhysicsHelper::point2cpv(b), PhysicsHelper::float2cpfloat(border)); @@ -401,14 +405,14 @@ bool PhysicsShapeEdgeSegment::init(Point a, Point b, PhysicsMaterial material/* return false; } -Point PhysicsShapeEdgeSegment::getPointA() +Point PhysicsShapeEdgeSegment::getPointA() const { - return PhysicsHelper::cpv2point(((cpSegmentShape*)(_info->shapes.front()))->ta); + return PhysicsHelper::cpv2point(((cpSegmentShape*)(_info->getShapes().front()))->ta); } -Point PhysicsShapeEdgeSegment::getPointB() +Point PhysicsShapeEdgeSegment::getPointB() const { - return PhysicsHelper::cpv2point(((cpSegmentShape*)(_info->shapes.front()))->tb); + return PhysicsHelper::cpv2point(((cpSegmentShape*)(_info->getShapes().front()))->tb); } Point PhysicsShapeEdgeSegment::getCenter() @@ -417,7 +421,7 @@ Point PhysicsShapeEdgeSegment::getCenter() } // PhysicsShapeBox -PhysicsShapeBox* PhysicsShapeBox::create(Size size, PhysicsMaterial material/* = MaterialDefault*/, Point offset/* = Point(0, 0)*/) +PhysicsShapeBox* PhysicsShapeBox::create(const Size& size, const PhysicsMaterial& material/* = MaterialDefault*/, const Point& offset/* = Point(0, 0)*/) { PhysicsShapeBox* shape = new PhysicsShapeBox(); if (shape && shape->init(size, material, offset)) @@ -430,7 +434,7 @@ PhysicsShapeBox* PhysicsShapeBox::create(Size size, PhysicsMaterial material/* = return nullptr; } -bool PhysicsShapeBox::init(Size size, PhysicsMaterial material/* = MaterialDefault*/, Point offset /*= Point(0, 0)*/) +bool PhysicsShapeBox::init(const Size& size, const PhysicsMaterial& material/* = MaterialDefault*/, const Point& offset /*= Point(0, 0)*/) { do { @@ -442,7 +446,7 @@ bool PhysicsShapeBox::init(Size size, PhysicsMaterial material/* = MaterialDefau {-wh.x/2.0f, -wh.y/2.0f}, {-wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, -wh.y/2.0f} }; - cpShape* shape = cpPolyShapeNew(_info->shareBody, 4, vec, PhysicsHelper::point2cpv(offset)); + cpShape* shape = cpPolyShapeNew(_info->getSharedBody(), 4, vec, PhysicsHelper::point2cpv(offset)); CC_BREAK_IF(shape == nullptr); @@ -461,7 +465,7 @@ bool PhysicsShapeBox::init(Size size, PhysicsMaterial material/* = MaterialDefau return false; } -float PhysicsShapeBox::calculateArea(Size size) +float PhysicsShapeBox::calculateArea(const Size& size) { cpVect wh = PhysicsHelper::size2cpv(size); cpVect vec[4] = @@ -471,7 +475,7 @@ float PhysicsShapeBox::calculateArea(Size size) return PhysicsHelper::cpfloat2float(cpAreaForPoly(4, vec)); } -float PhysicsShapeBox::calculateMoment(float mass, Size size, Point offset) +float PhysicsShapeBox::calculateMoment(float mass, const Size& size, const Point& offset) { cpVect wh = PhysicsHelper::size2cpv(size); cpVect vec[4] = @@ -488,34 +492,32 @@ float PhysicsShapeBox::calculateMoment(float mass, Size size, Point offset) float PhysicsShapeBox::calculateDefaultArea() { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return PhysicsHelper::cpfloat2float(cpAreaForPoly(((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts)); } float PhysicsShapeBox::calculateDefaultMoment() { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero)); } -Point* PhysicsShapeBox::getPoints(Point* points) +void PhysicsShapeBox::getPoints(Point* points) const { - cpShape* shape = _info->shapes.front(); - return PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); - - return points; + cpShape* shape = _info->getShapes().front(); + PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); } -Size PhysicsShapeBox::getSize() +Size PhysicsShapeBox::getSize() const { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return PhysicsHelper::cpv2size(cpv(cpvdist(cpPolyShapeGetVert(shape, 0), cpPolyShapeGetVert(shape, 1)), cpvdist(cpPolyShapeGetVert(shape, 1), cpPolyShapeGetVert(shape, 2)))); } // PhysicsShapePolygon -PhysicsShapePolygon* PhysicsShapePolygon::create(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, Point offset/* = Point(0, 0)*/) +PhysicsShapePolygon* PhysicsShapePolygon::create(const Point* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, const Point& offset/* = Point(0, 0)*/) { PhysicsShapePolygon* shape = new PhysicsShapePolygon(); if (shape && shape->init(points, count, material, offset)) @@ -528,7 +530,7 @@ PhysicsShapePolygon* PhysicsShapePolygon::create(Point* points, int count, Physi return nullptr; } -bool PhysicsShapePolygon::init(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, Point offset/* = Point(0, 0)*/) +bool PhysicsShapePolygon::init(const Point* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, const Point& offset/* = Point(0, 0)*/) { do { @@ -536,7 +538,7 @@ bool PhysicsShapePolygon::init(Point* points, int count, PhysicsMaterial materia cpVect* vecs = new cpVect[count]; PhysicsHelper::points2cpvs(points, vecs, count); - cpShape* shape = cpPolyShapeNew(_info->shareBody, count, vecs, PhysicsHelper::point2cpv(offset)); + cpShape* shape = cpPolyShapeNew(_info->getSharedBody(), count, vecs, PhysicsHelper::point2cpv(offset)); CC_SAFE_DELETE(vecs); CC_BREAK_IF(shape == nullptr); @@ -556,7 +558,7 @@ bool PhysicsShapePolygon::init(Point* points, int count, PhysicsMaterial materia return false; } -float PhysicsShapePolygon::calculateArea(Point* points, int count) +float PhysicsShapePolygon::calculateArea(const Point* points, int count) { cpVect* vecs = new cpVect[count]; PhysicsHelper::points2cpvs(points, vecs, count); @@ -566,7 +568,7 @@ float PhysicsShapePolygon::calculateArea(Point* points, int count) return area; } -float PhysicsShapePolygon::calculateMoment(float mass, Point* points, int count, Point offset) +float PhysicsShapePolygon::calculateMoment(float mass, const Point* points, int count, const Point& offset) { cpVect* vecs = new cpVect[count]; PhysicsHelper::points2cpvs(points, vecs, count); @@ -579,26 +581,31 @@ float PhysicsShapePolygon::calculateMoment(float mass, Point* points, int count, float PhysicsShapePolygon::calculateDefaultArea() { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return PhysicsHelper::cpfloat2float(cpAreaForPoly(((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts)); } float PhysicsShapePolygon::calculateDefaultMoment() { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero)); } -Point* PhysicsShapePolygon::getPoints(Point* points) +Point PhysicsShapePolygon::getPoint(int i) const { - cpShape* shape = _info->shapes.front(); - return PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); + return PhysicsHelper::cpv2point(cpPolyShapeGetVert(_info->getShapes().front(), i)); } -int PhysicsShapePolygon::getPointsCount() +void PhysicsShapePolygon::getPoints(Point* outPoints) const { - return ((cpPolyShape*)_info->shapes.front())->numVerts; + cpShape* shape = _info->getShapes().front(); + PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, outPoints, ((cpPolyShape*)shape)->numVerts); +} + +long PhysicsShapePolygon::getPointsCount() const +{ + return ((cpPolyShape*)_info->getShapes().front())->numVerts; } Point PhysicsShapePolygon::getCenter() @@ -607,7 +614,7 @@ Point PhysicsShapePolygon::getCenter() } // PhysicsShapeEdgeBox -PhysicsShapeEdgeBox* PhysicsShapeEdgeBox::create(Size size, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/, Point offset/* = Point(0, 0)*/) +PhysicsShapeEdgeBox* PhysicsShapeEdgeBox::create(const Size& size, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/, const Point& offset/* = Point(0, 0)*/) { PhysicsShapeEdgeBox* shape = new PhysicsShapeEdgeBox(); if (shape && shape->init(size, material, border, offset)) @@ -620,7 +627,7 @@ PhysicsShapeEdgeBox* PhysicsShapeEdgeBox::create(Size size, PhysicsMaterial mate return nullptr; } -bool PhysicsShapeEdgeBox::init(Size size, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/, Point offset/*= Point(0, 0)*/) +bool PhysicsShapeEdgeBox::init(const Size& size, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/, const Point& offset/*= Point(0, 0)*/) { do { @@ -635,7 +642,7 @@ bool PhysicsShapeEdgeBox::init(Size size, PhysicsMaterial material/* = MaterialD int i = 0; for (; i < 4; ++i) { - cpShape* shape = cpSegmentShapeNew(_info->shareBody, vec[i], vec[(i+1)%4], + cpShape* shape = cpSegmentShapeNew(_info->getSharedBody(), vec[i], vec[(i+1)%4], PhysicsHelper::float2cpfloat(border)); CC_BREAK_IF(shape == nullptr); _info->add(shape); @@ -655,7 +662,7 @@ bool PhysicsShapeEdgeBox::init(Size size, PhysicsMaterial material/* = MaterialD } // PhysicsShapeEdgeBox -PhysicsShapeEdgePolygon* PhysicsShapeEdgePolygon::create(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) +PhysicsShapeEdgePolygon* PhysicsShapeEdgePolygon::create(const Point* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/) { PhysicsShapeEdgePolygon* shape = new PhysicsShapeEdgePolygon(); if (shape && shape->init(points, count, material, border)) @@ -668,7 +675,7 @@ PhysicsShapeEdgePolygon* PhysicsShapeEdgePolygon::create(Point* points, int coun return nullptr; } -bool PhysicsShapeEdgePolygon::init(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) +bool PhysicsShapeEdgePolygon::init(const Point* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/) { cpVect* vec = nullptr; do @@ -682,7 +689,7 @@ bool PhysicsShapeEdgePolygon::init(Point* points, int count, PhysicsMaterial mat int i = 0; for (; i < count; ++i) { - cpShape* shape = cpSegmentShapeNew(_info->shareBody, vec[i], vec[(i+1)%count], + cpShape* shape = cpSegmentShapeNew(_info->getSharedBody(), vec[i], vec[(i+1)%count], PhysicsHelper::float2cpfloat(border)); CC_BREAK_IF(shape == nullptr); cpShapeSetElasticity(shape, 1.0f); @@ -711,13 +718,13 @@ Point PhysicsShapeEdgePolygon::getCenter() return _center; } -int PhysicsShapeEdgePolygon::getPointsCount() +long PhysicsShapeEdgePolygon::getPointsCount() const { - return _info->shapes.size() + 1; + return _info->getShapes().size() + 1; } // PhysicsShapeEdgeChain -PhysicsShapeEdgeChain* PhysicsShapeEdgeChain::create(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) +PhysicsShapeEdgeChain* PhysicsShapeEdgeChain::create(const Point* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/) { PhysicsShapeEdgeChain* shape = new PhysicsShapeEdgeChain(); if (shape && shape->init(points, count, material, border)) @@ -730,7 +737,7 @@ PhysicsShapeEdgeChain* PhysicsShapeEdgeChain::create(Point* points, int count, P return nullptr; } -bool PhysicsShapeEdgeChain::init(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) +bool PhysicsShapeEdgeChain::init(const Point* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/) { cpVect* vec = nullptr; do @@ -744,7 +751,7 @@ bool PhysicsShapeEdgeChain::init(Point* points, int count, PhysicsMaterial mater int i = 0; for (; i < count - 1; ++i) { - cpShape* shape = cpSegmentShapeNew(_info->shareBody, vec[i], vec[i+1], + cpShape* shape = cpSegmentShapeNew(_info->getSharedBody(), vec[i], vec[i+1], PhysicsHelper::float2cpfloat(border)); CC_BREAK_IF(shape == nullptr); cpShapeSetElasticity(shape, 1.0f); @@ -772,9 +779,33 @@ Point PhysicsShapeEdgeChain::getCenter() return _center; } -int PhysicsShapeEdgeChain::getPointsCount() +long PhysicsShapeEdgeChain::getPointsCount() const { - return _info->shapes.size() + 1; + return _info->getShapes().size() + 1; +} + +void PhysicsShape::setGroup(int group) +{ + if (group < 0) + { + for (auto shape : _info->getShapes()) + { + cpShapeSetGroup(shape, (cpGroup)group); + } + } +} + +bool PhysicsShape::containsPoint(const Point& point) const +{ + for (auto shape : _info->getShapes()) + { + if (cpShapePointQuery(shape, PhysicsHelper::point2cpv(point))) + { + return true; + } + } + + return false; } #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index 6cd5329f6d..71eeced1dc 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - #ifndef __CCPHYSICS_SHAPE_H__ #define __CCPHYSICS_SHAPE_H__ +#include "CCPhysicsSetting.h" +#ifdef CC_USE_PHYSICS + #include "CCObject.h" #include "CCGeometry.h" @@ -50,14 +50,14 @@ typedef struct PhysicsMaterial , friction(0.0f) {} - PhysicsMaterial(float density, float restitution, float friction) - : density(density) - , restitution(restitution) - , friction(friction) + PhysicsMaterial(float aDensity, float aRestitution, float aFriction) + : density(aDensity) + , restitution(aRestitution) + , friction(aFriction) {} }PhysicsMaterial; -const PhysicsMaterial PHYSICSSHAPE_MATERIAL_DEFAULT(0.0f, 1.0f, 1.0f); +const PhysicsMaterial PHYSICSSHAPE_MATERIAL_DEFAULT(0.0f, 0.5f, 0.5f); /** * @brief A shape for body. You do not create PhysicsWorld objects directly, instead, you can view PhysicsBody to see how to create it. @@ -92,15 +92,26 @@ public: void setDensity(float density); void setRestitution(float restitution); void setFriction(float friction); - void setMaterial(PhysicsMaterial material); + void setMaterial(const PhysicsMaterial& material); virtual float calculateDefaultMoment() { return 0; } virtual float calculateDefaultArea() { return 0; } virtual Point getOffset() { return Point::ZERO; } virtual Point getCenter() { return getOffset(); } + bool containsPoint(const Point& point) const; - static Point* recenterPoints(Point* points, int count, Point center = Point::ZERO); - static Point getPolyonCenter(Point* points, int count); + static Point* recenterPoints(Point* points, int count, const Point& center = Point::ZERO); + static Point getPolyonCenter(const Point* points, int count); + + inline void setCategoryBitmask(int bitmask) { _categoryBitmask = bitmask; } + inline int getCategoryBitmask() const { return _categoryBitmask; } + inline void setContactTestBitmask(int bitmask) { _contactTestBitmask = bitmask; } + inline int getContactTestBitmask() const { return _contactTestBitmask; } + inline void setCollisionBitmask(int bitmask) { _collisionBitmask = bitmask; } + inline int getCollisionBitmask() const { return _collisionBitmask; } + + void setGroup(int group); + inline int getGroup() { return _group; } protected: bool init(Type type); @@ -125,6 +136,10 @@ protected: float _moment; PhysicsMaterial _material; int _tag; + int _categoryBitmask; + int _collisionBitmask; + int _contactTestBitmask; + int _group; friend class PhysicsWorld; friend class PhysicsBody; @@ -135,40 +150,40 @@ protected: class PhysicsShapeCircle : public PhysicsShape { public: - static PhysicsShapeCircle* create(float radius, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); + static PhysicsShapeCircle* create(float radius, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point(0, 0)); static float calculateArea(float radius); - static float calculateMoment(float mass, float radius, Point offset = Point(0, 0)); + static float calculateMoment(float mass, float radius, const Point& offset = Point::ZERO); - float calculateDefaultArea() override; - float calculateDefaultMoment() override; + virtual float calculateDefaultArea() override; + virtual float calculateDefaultMoment() override; - float getRadius(); - Point getOffset(); + float getRadius() const; + virtual Point getOffset() override; protected: - bool init(float radius, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); + bool init(float radius, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); protected: PhysicsShapeCircle(); - ~PhysicsShapeCircle(); + virtual ~PhysicsShapeCircle(); }; /** A box shape */ class PhysicsShapeBox : public PhysicsShape { public: - static PhysicsShapeBox* create(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); - static float calculateArea(Size size); - static float calculateMoment(float mass, Size size, Point offset = Point(0, 0)); + static PhysicsShapeBox* create(const Size& size, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); + static float calculateArea(const Size& size); + static float calculateMoment(float mass, const Size& size, const Point& offset = Point::ZERO); - float calculateDefaultArea() override; - float calculateDefaultMoment() override; + virtual float calculateDefaultArea() override; + virtual float calculateDefaultMoment() override; - Point* getPoints(Point* points); - Size getSize(); - Point getOffset() override { return _offset; } + void getPoints(Point* outPoints) const; + Size getSize() const; + virtual Point getOffset() override { return _offset; } protected: - bool init(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); + bool init(const Size& size, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); protected: PhysicsShapeBox(); @@ -182,18 +197,19 @@ protected: class PhysicsShapePolygon : public PhysicsShape { public: - static PhysicsShapePolygon* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); - static float calculateArea(Point* points, int count); - static float calculateMoment(float mass, Point* points, int count, Point offset = Point(0, 0)); + static PhysicsShapePolygon* create(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); + static float calculateArea(const Point* points, int count); + static float calculateMoment(float mass, const Point* points, int count, const Point& offset = Point::ZERO); float calculateDefaultArea() override; float calculateDefaultMoment() override; - Point* getPoints(Point* points); - int getPointsCount(); - Point getCenter() override; + Point getPoint(int i) const; + void getPoints(Point* outPoints) const; + long getPointsCount() const; + virtual Point getCenter() override; protected: - bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); + bool init(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); protected: PhysicsShapePolygon(); @@ -207,14 +223,14 @@ protected: class PhysicsShapeEdgeSegment : public PhysicsShape { public: - static PhysicsShapeEdgeSegment* create(Point a, Point b, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + static PhysicsShapeEdgeSegment* create(const Point& a, const Point& b, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - Point getPointA(); - Point getPointB(); - Point getCenter() override; + Point getPointA() const; + Point getPointB() const; + virtual Point getCenter() override; protected: - bool init(Point a, Point b, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + bool init(const Point& a, const Point& b, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); protected: PhysicsShapeEdgeSegment(); @@ -230,13 +246,13 @@ protected: class PhysicsShapeEdgeBox : public PhysicsShape { public: - static PhysicsShapeEdgeBox* create(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 0, Point offset = Point(0, 0)); - Point getOffset() override { return _offset; } - Point* getPoints(Point* points); - int getPointsCount(); + static PhysicsShapeEdgeBox* create(const Size& size, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 0, const Point& offset = Point::ZERO); + virtual Point getOffset() override { return _offset; } + void getPoints(const Point* outPoints) const; + long getPointsCount() const; protected: - bool init(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1, Point offset = Point(0, 0)); + bool init(const Size& size, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1, const Point& offset = Point::ZERO); protected: PhysicsShapeEdgeBox(); @@ -252,13 +268,13 @@ protected: class PhysicsShapeEdgePolygon : public PhysicsShape { public: - static PhysicsShapeEdgePolygon* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - Point getCenter() override; - Point* getPoints(Point* points); - int getPointsCount(); + static PhysicsShapeEdgePolygon* create(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + virtual Point getCenter() override; + void getPoints(Point* outPoints) const; + long getPointsCount() const; protected: - bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + bool init(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); protected: PhysicsShapeEdgePolygon(); @@ -274,13 +290,13 @@ protected: class PhysicsShapeEdgeChain : public PhysicsShape { public: - static PhysicsShapeEdgeChain* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - Point getCenter() override; - Point* getPoints(Point* points); - int getPointsCount(); + static PhysicsShapeEdgeChain* create(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + virtual Point getCenter() override; + void getPoints(Point* outPoints) const; + long getPointsCount() const; protected: - bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + bool init(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); protected: PhysicsShapeEdgeChain(); @@ -293,6 +309,6 @@ protected: }; NS_CC_END -#endif // __CCPHYSICS_FIXTURE_H__ #endif // CC_USE_PHYSICS +#endif // __CCPHYSICS_FIXTURE_H__ diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 9085805e1d..837a2b30e3 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -25,6 +25,8 @@ #include "CCPhysicsWorld.h" #ifdef CC_USE_PHYSICS +#include + #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #elif (CC_PHYSICS_ENGINE == CCPHYSICS_BOX2D) @@ -37,35 +39,41 @@ #include "CCPhysicsJoint.h" #include "CCPhysicsContact.h" -#include "chipmunk/CCPhysicsWorldInfo.h" -#include "box2d/CCPhysicsWorldInfo.h" -#include "chipmunk/CCPhysicsBodyInfo.h" -#include "box2d/CCPhysicsBodyInfo.h" -#include "chipmunk/CCPhysicsShapeInfo.h" -#include "box2d/CCPhysicsShapeInfo.h" -#include "chipmunk/CCPhysicsContactInfo.h" -#include "box2d/CCPhysicsContactInfo.h" -#include "chipmunk/CCPhysicsJointInfo.h" -#include "box2d/CCPhysicsJointInfo.h" -#include "chipmunk/CCPhysicsHelper.h" +#include "chipmunk/CCPhysicsWorldInfo_chipmunk.h" +#include "box2d/CCPhysicsWorldInfo_box2d.h" +#include "chipmunk/CCPhysicsBodyInfo_chipmunk.h" +#include "box2d/CCPhysicsBodyInfo_box2d.h" +#include "chipmunk/CCPhysicsShapeInfo_chipmunk.h" +#include "box2d/CCPhysicsShapeInfo_box2d.h" +#include "chipmunk/CCPhysicsContactInfo_chipmunk.h" +#include "box2d/CCPhysicsContactInfo_box2d.h" +#include "chipmunk/CCPhysicsJointInfo_chipmunk.h" +#include "box2d/CCPhysicsJointInfo_box2d.h" +#include "chipmunk/CCPhysicsHelper_chipmunk.h" #include "CCDrawNode.h" #include "CCArray.h" #include "CCScene.h" #include "CCDirector.h" +#include "CCEventDispatcher.h" +#include "CCEventCustom.h" #include NS_CC_BEGIN +extern const char* PHYSICSCONTACT_EVENT_NAME; + #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) +const float PHYSICS_INFINITY = INFINITY; + namespace { typedef struct RayCastCallbackInfo { PhysicsWorld* world; - PhysicsRayCastCallback* callback; + PhysicsRayCastCallbackFunc func; Point p1; Point p2; void* data; @@ -74,7 +82,7 @@ namespace typedef struct RectQueryCallbackInfo { PhysicsWorld* world; - PhysicsRectQueryCallback* callback; + PhysicsRectQueryCallbackFunc func; void* data; }RectQueryCallbackInfo; } @@ -96,32 +104,29 @@ public: bool PhysicsWorldCallback::continues = true; -const float PHYSICS_INFINITY = INFINITY; - int PhysicsWorldCallback::collisionBeginCallbackFunc(cpArbiter *arb, struct cpSpace *space, PhysicsWorld *world) { CP_ARBITER_GET_SHAPES(arb, a, b); - auto ita = PhysicsShapeInfo::map.find(a); - auto itb = PhysicsShapeInfo::map.find(b); - CC_ASSERT(ita != PhysicsShapeInfo::map.end() && itb != PhysicsShapeInfo::map.end()); + auto ita = PhysicsShapeInfo::getMap().find(a); + auto itb = PhysicsShapeInfo::getMap().find(b); + CC_ASSERT(ita != PhysicsShapeInfo::getMap().end() && itb != PhysicsShapeInfo::getMap().end()); - PhysicsContact* contact = PhysicsContact::create(ita->second->shape, itb->second->shape); + PhysicsContact* contact = PhysicsContact::create(ita->second->getShape(), itb->second->getShape()); arb->data = contact; + contact->_contactInfo = arb; - return world->collisionBeginCallback(*static_cast(arb->data)); + return world->collisionBeginCallback(*contact); } int PhysicsWorldCallback::collisionPreSolveCallbackFunc(cpArbiter *arb, cpSpace *space, PhysicsWorld *world) { - return world->collisionPreSolveCallback(*static_cast(arb->data), - PhysicsContactPreSolve()); + return world->collisionPreSolveCallback(*static_cast(arb->data)); } void PhysicsWorldCallback::collisionPostSolveCallbackFunc(cpArbiter *arb, cpSpace *space, PhysicsWorld *world) { - world->collisionPostSolveCallback(*static_cast(arb->data), - PhysicsContactPostSolve()); + world->collisionPostSolveCallback(*static_cast(arb->data)); } void PhysicsWorldCallback::collisionSeparateCallbackFunc(cpArbiter *arb, cpSpace *space, PhysicsWorld *world) @@ -140,102 +145,290 @@ void PhysicsWorldCallback::rayCastCallbackFunc(cpShape *shape, cpFloat t, cpVect return; } - auto it = PhysicsShapeInfo::map.find(shape); - CC_ASSERT(it != PhysicsShapeInfo::map.end()); + auto it = PhysicsShapeInfo::getMap().find(shape); + CC_ASSERT(it != PhysicsShapeInfo::getMap().end()); - PhysicsWorldCallback::continues = info->callback->report(*info->world, - *it->second->shape, - Point(info->p1.x+(info->p2.x-info->p1.x)*t, info->p1.y+(info->p2.y-info->p1.y)*t), - Point(n.x, n.y), - (float)t, - info->data); + PhysicsRayCastInfo callbackInfo = + { + it->second->getShape(), + info->p1, + info->p2, + Point(info->p1.x+(info->p2.x-info->p1.x)*t, info->p1.y+(info->p2.y-info->p1.y)*t), + Point(n.x, n.y), + (float)t, + }; + + PhysicsWorldCallback::continues = info->func(*info->world, callbackInfo, info->data); } void PhysicsWorldCallback::rectQueryCallbackFunc(cpShape *shape, RectQueryCallbackInfo *info) { - auto it = PhysicsShapeInfo::map.find(shape); + auto it = PhysicsShapeInfo::getMap().find(shape); - CC_ASSERT(it != PhysicsShapeInfo::map.end()); + CC_ASSERT(it != PhysicsShapeInfo::getMap().end()); if (!PhysicsWorldCallback::continues) { return; } - PhysicsWorldCallback::continues = info->callback->report(*info->world, - *it->second->shape, - info->data); + PhysicsWorldCallback::continues = info->func(*info->world, *it->second->getShape(), info->data); } void PhysicsWorldCallback::nearestPointQueryFunc(cpShape *shape, cpFloat distance, cpVect point, Array *arr) { - auto it = PhysicsShapeInfo::map.find(shape); + auto it = PhysicsShapeInfo::getMap().find(shape); - CC_ASSERT(it != PhysicsShapeInfo::map.end()); + CC_ASSERT(it != PhysicsShapeInfo::getMap().end()); - arr->addObject(it->second->shape); + arr->addObject(it->second->getShape()); } -bool PhysicsWorld::init() +bool PhysicsWorld::init(Scene& scene) { - _info = new PhysicsWorldInfo(); + do + { + _delayAddBodies = Array::create(); + _delayRemoveBodies = Array::create(); + CC_BREAK_IF(_delayAddBodies == nullptr || _delayRemoveBodies == nullptr); + _delayAddBodies->retain(); + _delayRemoveBodies->retain(); + + _info = new PhysicsWorldInfo(); + CC_BREAK_IF(_info == nullptr); + _bodies = Array::create(); + CC_BREAK_IF(_bodies == nullptr); + _bodies->retain(); + + _scene = &scene; + + cpSpaceSetGravity(_info->getSpace(), PhysicsHelper::point2cpv(_gravity)); + + cpSpaceSetDefaultCollisionHandler(_info->getSpace(), + (cpCollisionBeginFunc)PhysicsWorldCallback::collisionBeginCallbackFunc, + (cpCollisionPreSolveFunc)PhysicsWorldCallback::collisionPreSolveCallbackFunc, + (cpCollisionPostSolveFunc)PhysicsWorldCallback::collisionPostSolveCallbackFunc, + (cpCollisionSeparateFunc)PhysicsWorldCallback::collisionSeparateCallbackFunc, + this); + + return true; + } while (false); - cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(_gravity)); + return false; +} + +void PhysicsWorld::addBodyOrDelay(PhysicsBody* body) +{ + if (_delayRemoveBodies->getIndexOfObject(body) != UINT_MAX) + { + _delayRemoveBodies->removeObject(body); + return; + } - cpSpaceSetDefaultCollisionHandler(_info->space, - (cpCollisionBeginFunc)PhysicsWorldCallback::collisionBeginCallbackFunc, - (cpCollisionPreSolveFunc)PhysicsWorldCallback::collisionPreSolveCallbackFunc, - (cpCollisionPostSolveFunc)PhysicsWorldCallback::collisionPostSolveCallbackFunc, - (cpCollisionSeparateFunc)PhysicsWorldCallback::collisionSeparateCallbackFunc, - this); + if (_info->getSpace()->locked_private) + { + if (_delayAddBodies->getIndexOfObject(body) == UINT_MAX) + { + _delayAddBodies->addObject(body); + _delayDirty = true; + } + }else + { + doAddBody(body); + } +} + +void PhysicsWorld::removeBodyOrDelay(PhysicsBody* body) +{ + if (_delayAddBodies->getIndexOfObject(body) != UINT_MAX) + { + _delayAddBodies->removeObject(body); + return; + } - return true; + if (_info->getSpace()->locked_private) + { + if (_delayRemoveBodies->getIndexOfObject(body) == UINT_MAX) + { + _delayRemoveBodies->addObject(body); + _delayDirty = true; + } + }else + { + doRemoveBody(body); + } +} + +void PhysicsWorld::addJointOrDelay(PhysicsJoint* joint) +{ + auto it = std::find(_delayRemoveJoints.begin(), _delayRemoveJoints.end(), joint); + if (it != _delayRemoveJoints.end()) + { + _delayRemoveJoints.erase(it); + return; + } + + if (_info->getSpace()->locked_private) + { + if (std::find(_delayAddJoints.begin(), _delayAddJoints.end(), joint) == _delayAddJoints.end()) + { + _delayAddJoints.push_back(joint); + _delayDirty = true; + } + }else + { + doAddJoint(joint); + } +} + +void PhysicsWorld::removeJointOrDelay(PhysicsJoint* joint) +{ + auto it = std::find(_delayAddJoints.begin(), _delayAddJoints.end(), joint); + if (it != _delayAddJoints.end()) + { + _delayAddJoints.erase(it); + return; + } + + if (_info->getSpace()->locked_private) + { + if (std::find(_delayRemoveJoints.begin(), _delayRemoveJoints.end(), joint) == _delayRemoveJoints.end()) + { + _delayRemoveJoints.push_back(joint); + _delayDirty = true; + } + }else + { + doRemoveJoint(joint); + } } void PhysicsWorld::addJoint(PhysicsJoint* joint) { - auto it = std::find(_joints.begin(), _joints.end(), joint); - - if (it == _joints.end()) + if (joint->getWorld() != nullptr && joint->getWorld() != this) { - _joints.push_back(joint); - - for (auto subjoint : joint->_info->joints) + joint->removeFormWorld(); + } + + addJointOrDelay(joint); + _joints.push_back(joint); + joint->_world = this; +} + +void PhysicsWorld::removeJoint(PhysicsJoint* joint, bool destroy) +{ + if (joint->getWorld() != this) + { + if (destroy) { - if (!cpSpaceContainsConstraint(_info->space, subjoint)) + CCLOG("physics warnning: the joint is not in this world, it won't be destoried utill the body it conntect is destoried"); + } + return; + } + + removeJointOrDelay(joint); + + _joints.remove(joint); + joint->_world = nullptr; + + // clean the connection to this joint + if (destroy) + { + if (joint->getBodyA() != nullptr) + { + joint->getBodyA()->removeJoint(joint); + } + + if (joint->getBodyB() != nullptr) + { + joint->getBodyB()->removeJoint(joint); + } + + // test the distraction is delaied or not + if (_delayRemoveJoints.size() > 0 && _delayRemoveJoints.back() == joint) + { + joint->_destoryMark = true; + } + else + { + delete joint; + } + } +} + +void PhysicsWorld::removeAllJoints(bool destroy) +{ + for (auto joint : _joints) + { + removeJointOrDelay(joint); + joint->_world = nullptr; + + // clean the connection to this joint + if (destroy) + { + if (joint->getBodyA() != nullptr) { - cpSpaceAddConstraint(_info->space, subjoint); + joint->getBodyA()->removeJoint(joint); + } + + if (joint->getBodyB() != nullptr) + { + joint->getBodyB()->removeJoint(joint); + } + + // test the distraction is delaied or not + if (_delayRemoveJoints.size() > 0 && _delayRemoveJoints.back() == joint) + { + joint->_destoryMark = true; + } + else + { + delete joint; } } } -} - -void PhysicsWorld::removeJoint(PhysicsJoint* joint) -{ - -} - -void PhysicsWorld::removeAllJoints() -{ - + _joints.clear(); } void PhysicsWorld::addShape(PhysicsShape* shape) { - for (auto cps : shape->_info->shapes) + for (auto cps : shape->_info->getShapes()) { - if (cpSpaceContainsShape(_info->space, cps)) + _info->addShape(cps); + } + + return; +} + +void PhysicsWorld::doAddJoint(PhysicsJoint *joint) +{ + for (auto subjoint : joint->_info->getJoints()) + { + _info->addJoint(subjoint); + } +} + +void PhysicsWorld::doAddBody(PhysicsBody* body) +{ + if (body->isEnabled()) + { + //is gravity enable + if (!body->isGravityEnabled()) { - continue; + body->applyForce(-_gravity); } - if (cpBodyIsStatic(shape->getBody()->_info->body)) + // add body to space + if (body->isDynamic()) { - cpSpaceAddStaticShape(_info->space, cps); - }else + _info->addBody(body->_info->getBody()); + } + + // add shapes to space + for (auto shape : *body->getShapes()) { - cpSpaceAddShape(_info->space, cps); + addShape(dynamic_cast(shape)); } } } @@ -244,77 +437,44 @@ void PhysicsWorld::addBody(PhysicsBody* body) { CCASSERT(body != nullptr, "the body can not be nullptr"); - if (body->isEnable()) + if (body->getWorld() == this) { - //is gravity enable - if (!body->isGravityEnable()) - { - body->applyForce(-_gravity); - } - - // add body to space - if (body->isDynamic()) - { - cpSpaceAddBody(_info->space, body->_info->body); - } - - // add shapes to space - for (auto shape : body->getShapes()) - { - addShape(shape); - } + return; } - if (_bodys == nullptr) + if (body->getWorld() != nullptr) { - _bodys = Array::create(body, NULL); - _bodys->retain(); - }else - { - _bodys->addObject(body); + body->removeFromWorld(); } + + addBodyOrDelay(body); + _bodies->addObject(body); + body->_world = this; } void PhysicsWorld::removeBody(PhysicsBody* body) { - CCASSERT(body != nullptr, "the body can not be nullptr"); - if (body->getWorld() == this) + if (body->getWorld() != this) { - // reset the gravity - if (!body->isGravityEnable()) - { - body->applyForce(-_gravity); - } + CCLOG("Physics Warnning: this body doesn't belong to this world"); + return; } - // remove shaps - for (auto shape : body->getShapes()) + // destory the body's joints + for (auto joint : body->_joints) { - for (auto cps : shape->_info->shapes) - { - if (cpSpaceContainsShape(_info->space, cps)) - { - cpSpaceRemoveShape(_info->space, cps); - } - } + removeJoint(joint, true); } - // remove body - if (cpSpaceContainsBody(_info->space, body->_info->body)) - { - cpSpaceRemoveBody(_info->space, body->_info->body); - } - - if (_bodys != nullptr) - { - _bodys->removeObject(body); - } + removeBodyOrDelay(body); + _bodies->removeObject(body); + body->_world = nullptr; } -void PhysicsWorld::removeBodyByTag(int tag) +void PhysicsWorld::removeBody(int tag) { - for (Object* obj : *_bodys) + for (Object* obj : *_bodies) { PhysicsBody* body = dynamic_cast(obj); if (body->getTag() == tag) @@ -325,25 +485,121 @@ void PhysicsWorld::removeBodyByTag(int tag) } } +void PhysicsWorld::doRemoveBody(PhysicsBody* body) +{ + CCASSERT(body != nullptr, "the body can not be nullptr"); + + // reset the gravity + if (!body->isGravityEnabled()) + { + body->applyForce(-_gravity); + } + + // remove shaps + for (auto shape : *body->getShapes()) + { + removeShape(dynamic_cast(shape)); + } + + // remove body + _info->removeBody(body->_info->getBody()); +} + +void PhysicsWorld::doRemoveJoint(PhysicsJoint* joint) +{ + for (auto subjoint : joint->_info->getJoints()) + { + _info->removeJoint(subjoint); + } +} + +void PhysicsWorld::removeAllBodies() +{ + for (Object* obj : *_bodies) + { + PhysicsBody* child = dynamic_cast(obj); + removeBodyOrDelay(child); + child->_world = nullptr; + } + + _bodies->removeAllObjects(); + CC_SAFE_RELEASE(_bodies); +} + void PhysicsWorld::removeShape(PhysicsShape* shape) { - for (auto cps : shape->_info->shapes) + for (auto cps : shape->_info->getShapes()) { - if (cpSpaceContainsShape(_info->space, cps)) + if (cpSpaceContainsShape(_info->getSpace(), cps)) { - cpSpaceRemoveShape(_info->space, cps); + cpSpaceRemoveShape(_info->getSpace(), cps); } } } +void PhysicsWorld::updateBodies() +{ + if (_info->getSpace()->locked_private) + { + return; + } + + for (auto body : *_delayAddBodies) + { + doAddBody(dynamic_cast(body)); + } + + for (auto body : *_delayRemoveBodies) + { + doRemoveBody(dynamic_cast(body)); + } + + _delayAddBodies->removeAllObjects(); + _delayRemoveBodies->removeAllObjects(); +} + +void PhysicsWorld::updateJoints() +{ + if (_info->getSpace()->locked_private) + { + return; + } + + for (auto joint : _delayAddJoints) + { + doAddJoint(joint); + } + + for (auto joint : _delayRemoveJoints) + { + doRemoveJoint(joint); + + if (joint->_destoryMark) + { + delete joint; + } + } + + _delayAddJoints.clear(); + _delayRemoveJoints.clear(); +} + void PhysicsWorld::update(float delta) { - for (auto body : *_bodys) + if (_delayDirty) + { + // the updateJoints must run before the updateBodies. + updateJoints(); + updateBodies(); + _delayDirty = !(_delayAddBodies->count() == 0 && _delayRemoveBodies->count() == 0 && _delayAddJoints.size() == 0 && _delayRemoveJoints.size() == 0); + } + + for (auto body : *_bodies) { body->update(delta); } - cpSpaceStep(_info->space, delta); + cpSpaceStep(_info->getSpace(), delta); if (_drawNode) { @@ -359,22 +615,25 @@ void PhysicsWorld::update(float delta) void PhysicsWorld::debugDraw() { - if (_debugDraw && _bodys != nullptr) + if (_debugDraw && _bodies != nullptr) { _drawNode= DrawNode::create(); - for (Object* obj : *_bodys) + for (Object* obj : *_bodies) { PhysicsBody* body = dynamic_cast(obj); - std::vector shapes = body->getShapes(); - - for (auto shape : shapes) + for (auto shape : *body->getShapes()) { - drawWithShape(_drawNode, shape); + drawWithShape(_drawNode, dynamic_cast(shape)); } } + for (auto joint : _joints) + { + drawWithJoint(_drawNode, joint); + } + if (_scene) { _scene->addChild(_drawNode); @@ -382,24 +641,80 @@ void PhysicsWorld::debugDraw() } } -void PhysicsWorld::setScene(Scene *scene) +void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) { - _scene = scene; + for (auto it = joint->_info->getJoints().begin(); it != joint->_info->getJoints().end(); ++it) + { + cpConstraint *constraint = *it; + + + cpBody *body_a = constraint->a; + cpBody *body_b = constraint->b; + + const cpConstraintClass *klass = constraint->klass_private; + if(klass == cpPinJointGetClass()) + { + cpPinJoint *subJoint = (cpPinJoint *)constraint; + + cpVect a = cpvadd(body_a->p, cpvrotate(subJoint->anchr1, body_a->rot)); + cpVect b = cpvadd(body_b->p, cpvrotate(subJoint->anchr2, body_b->rot)); + + node->drawSegment(PhysicsHelper::cpv2point(a), PhysicsHelper::cpv2point(b), 1, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); + node->drawDot(PhysicsHelper::cpv2point(a), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + node->drawDot(PhysicsHelper::cpv2point(b), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + } + else if(klass == cpSlideJointGetClass()) + { + cpSlideJoint *subJoint = (cpSlideJoint *)constraint; + + cpVect a = cpvadd(body_a->p, cpvrotate(subJoint->anchr1, body_a->rot)); + cpVect b = cpvadd(body_b->p, cpvrotate(subJoint->anchr2, body_b->rot)); + + node->drawSegment(PhysicsHelper::cpv2point(a), PhysicsHelper::cpv2point(b), 1, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); + node->drawDot(PhysicsHelper::cpv2point(a), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + node->drawDot(PhysicsHelper::cpv2point(b), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + } + else if(klass == cpPivotJointGetClass()) + { + cpPivotJoint *subJoint = (cpPivotJoint *)constraint; + + cpVect a = cpvadd(body_a->p, cpvrotate(subJoint->anchr1, body_a->rot)); + cpVect b = cpvadd(body_b->p, cpvrotate(subJoint->anchr2, body_b->rot)); + + node->drawDot(PhysicsHelper::cpv2point(a), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + node->drawDot(PhysicsHelper::cpv2point(b), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + } + else if(klass == cpGrooveJointGetClass()) + { + cpGrooveJoint *subJoint = (cpGrooveJoint *)constraint; + + cpVect a = cpvadd(body_a->p, cpvrotate(subJoint->grv_a, body_a->rot)); + cpVect b = cpvadd(body_a->p, cpvrotate(subJoint->grv_b, body_a->rot)); + cpVect c = cpvadd(body_b->p, cpvrotate(subJoint->anchr2, body_b->rot)); + + node->drawSegment(PhysicsHelper::cpv2point(a), PhysicsHelper::cpv2point(b), 1, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); + node->drawDot(PhysicsHelper::cpv2point(c), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + } + else if(klass == cpDampedSpringGetClass()) + { + + } + } } void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shape) { - for (auto it = shape->_info->shapes.begin(); it != shape->_info->shapes.end(); ++it) + for (auto it = shape->_info->getShapes().begin(); it != shape->_info->getShapes().end(); ++it) { - cpShape *shape = *it; + cpShape *subShape = *it; switch ((*it)->klass_private->type) { case CP_CIRCLE_SHAPE: { - float radius = PhysicsHelper::cpfloat2float(cpCircleShapeGetRadius(shape)); - Point centre = PhysicsHelper::cpv2point(cpBodyGetPos(cpShapeGetBody(shape))) - + PhysicsHelper::cpv2point(cpCircleShapeGetOffset(shape)); + float radius = PhysicsHelper::cpfloat2float(cpCircleShapeGetRadius(subShape)); + Point centre = PhysicsHelper::cpv2point(cpBodyGetPos(cpShapeGetBody(subShape))) + + PhysicsHelper::cpv2point(cpCircleShapeGetOffset(subShape)); static const int CIRCLE_SEG_NUM = 12; Point seg[CIRCLE_SEG_NUM] = {}; @@ -415,7 +730,7 @@ void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shape) } case CP_SEGMENT_SHAPE: { - cpSegmentShape *seg = (cpSegmentShape *)shape; + cpSegmentShape *seg = (cpSegmentShape *)subShape; node->drawSegment(PhysicsHelper::cpv2point(seg->ta), PhysicsHelper::cpv2point(seg->tb), PhysicsHelper::cpfloat2float(seg->r==0 ? 1 : seg->r), Color4F(1, 0, 0, 1)); @@ -423,7 +738,7 @@ void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shape) } case CP_POLY_SHAPE: { - cpPolyShape* poly = (cpPolyShape*)shape; + cpPolyShape* poly = (cpPolyShape*)subShape; int num = poly->numVerts; Point* seg = new Point[num]; @@ -443,88 +758,117 @@ void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shape) int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) { bool ret = true; - PhysicsBody* bodyA = contact.getShapeA()->getBody(); - PhysicsBody* bodyB = contact.getShapeB()->getBody(); - if ((bodyA->getCategoryBitmask() & bodyB->getContactTestBitmask()) == 0 - || (bodyB->getContactTestBitmask() & bodyA->getCategoryBitmask()) == 0) - { - contact.setNotify(false); - } + PhysicsShape* shapeA = contact.getShapeA(); + PhysicsShape* shapeB = contact.getShapeB(); + PhysicsBody* bodyA = shapeA->getBody(); + PhysicsBody* bodyB = shapeB->getBody(); + std::vector jointsA = bodyA->getJoints(); - if ((bodyA->getCategoryBitmask() & bodyB->getCollisionBitmask()) == 0 - || (bodyB->getCategoryBitmask() & bodyA->getCollisionBitmask()) == 0) + // check the joint is collision enable or not + for (PhysicsJoint* joint : jointsA) { - ret = false; - } - - if (contact.getNotify() && _listener && _listener->onContactBegin) - { - // the mask has high priority than _listener->onContactBegin. - // so if the mask test is false, the two bodies won't have collision. - if (ret) + if (std::find(_joints.begin(), _joints.end(), joint) == _joints.end()) { - ret = _listener->onContactBegin(*this, contact); - }else + continue; + } + + if (!joint->isCollisionEnabled()) { - _listener->onContactBegin(*this, contact); + PhysicsBody* body = joint->getBodyA() == bodyA ? joint->getBodyB() : joint->getBodyA(); + + if (body == bodyB) + { + contact.setNotificationEnable(false); + return false; + } } } - return ret; + // bitmask check + if ((shapeA->getCategoryBitmask() & shapeB->getContactTestBitmask()) == 0 + || (shapeB->getContactTestBitmask() & shapeA->getCategoryBitmask()) == 0) + { + contact.setNotificationEnable(false); + } + + if (shapeA->getGroup() != 0 && shapeA->getGroup() == shapeB->getGroup()) + { + ret = shapeA->getGroup() > 0; + } + else + { + if ((shapeA->getCategoryBitmask() & shapeB->getCollisionBitmask()) == 0 + || (shapeB->getCategoryBitmask() & shapeA->getCollisionBitmask()) == 0) + { + ret = false; + } + } + + contact.setEventCode(PhysicsContact::EventCode::BEGIN); + contact.setWorld(this); + EventCustom event(PHYSICSCONTACT_EVENT_NAME); + event.setUserData(&contact); + _scene->getEventDispatcher()->dispatchEvent(&event); + + return ret ? contact.resetResult() : false; } -int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact, const PhysicsContactPreSolve& solve) +int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact) { - if (!contact.getNotify()) + if (!contact.isNotificationEnabled()) { + cpArbiterIgnore(static_cast(contact._contactInfo)); return true; } - if (_listener && _listener->onContactPreSolve) - { - return _listener->onContactPreSolve(*this, contact, solve); - } + contact.setEventCode(PhysicsContact::EventCode::PRESOLVE); + contact.setWorld(this); + EventCustom event(PHYSICSCONTACT_EVENT_NAME); + event.setUserData(&contact); + _scene->getEventDispatcher()->dispatchEvent(&event); - return true; + return contact.resetResult(); } -void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact, const PhysicsContactPostSolve& solve) +void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact) { - if (!contact.getNotify()) + if (!contact.isNotificationEnabled()) { return; } - if (_listener && _listener->onContactPreSolve) - { - _listener->onContactPostSolve(*this, contact, solve); - } + contact.setEventCode(PhysicsContact::EventCode::POSTSOLVE); + contact.setWorld(this); + EventCustom event(PHYSICSCONTACT_EVENT_NAME); + event.setUserData(&contact); + _scene->getEventDispatcher()->dispatchEvent(&event); } void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact) { - if (!contact.getNotify()) + if (!contact.isNotificationEnabled()) { return; } - if (_listener && _listener->onContactEnd) - { - _listener->onContactEnd(*this, contact); - } + contact.setEventCode(PhysicsContact::EventCode::SEPERATE); + contact.setWorld(this); + EventCustom event(PHYSICSCONTACT_EVENT_NAME); + event.setUserData(&contact); + _scene->getEventDispatcher()->dispatchEvent(&event); } -void PhysicsWorld::setGravity(Point gravity) +void PhysicsWorld::setGravity(const Vect& gravity) { - if (_bodys != nullptr) + if (_bodies != nullptr) { - for (auto child : *_bodys) + for (auto child : *_bodies) { PhysicsBody* body = dynamic_cast(child); // reset gravity for body - if (!body->isGravityEnable()) + if (!body->isGravityEnabled()) { body->applyForce(-_gravity); body->applyForce(gravity); @@ -533,18 +877,20 @@ void PhysicsWorld::setGravity(Point gravity) } _gravity = gravity; - cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(gravity)); + cpSpaceSetGravity(_info->getSpace(), PhysicsHelper::point2cpv(gravity)); } -void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, Point point1, Point point2, void* data) +void PhysicsWorld::rayCast(PhysicsRayCastCallbackFunc func, const Point& point1, const Point& point2, void* data) { - if (callback.report != nullptr) + CCASSERT(func != nullptr, "callback.report shouldn't be nullptr"); + + if (func != nullptr) { - RayCastCallbackInfo info = {this, &callback, point1, point2, data}; + RayCastCallbackInfo info = { this, func, point1, point2, data }; PhysicsWorldCallback::continues = true; - cpSpaceSegmentQuery(this->_info->space, + cpSpaceSegmentQuery(this->_info->getSpace(), PhysicsHelper::point2cpv(point1), PhysicsHelper::point2cpv(point2), CP_ALL_LAYERS, @@ -555,14 +901,16 @@ void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, Point point1, Point } -void PhysicsWorld::rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void* data) +void PhysicsWorld::rectQuery(PhysicsRectQueryCallbackFunc func, const Rect& rect, void* data) { - if (callback.report != nullptr) + CCASSERT(func != nullptr, "callback.report shouldn't be nullptr"); + + if (func != nullptr) { - RectQueryCallbackInfo info = {this, &callback, data}; + RectQueryCallbackInfo info = {this, func, data}; PhysicsWorldCallback::continues = true; - cpSpaceBBQuery(this->_info->space, + cpSpaceBBQuery(this->_info->getSpace(), PhysicsHelper::rect2cpbb(rect), CP_ALL_LAYERS, CP_NO_GROUP, @@ -571,10 +919,10 @@ void PhysicsWorld::rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void } } -Array* PhysicsWorld::getShapesAtPoint(Point point) +Array* PhysicsWorld::getShapes(const Point& point) const { Array* arr = Array::create(); - cpSpaceNearestPointQuery(this->_info->space, + cpSpaceNearestPointQuery(this->_info->getSpace(), PhysicsHelper::point2cpv(point), 0, CP_ALL_LAYERS, @@ -585,31 +933,44 @@ Array* PhysicsWorld::getShapesAtPoint(Point point) return arr; } -PhysicsShape* PhysicsWorld::getShapeAtPoint(Point point) +PhysicsShape* PhysicsWorld::getShape(const Point& point) const { - cpShape* shape = cpSpaceNearestPointQueryNearest(this->_info->space, + cpShape* shape = cpSpaceNearestPointQueryNearest(this->_info->getSpace(), PhysicsHelper::point2cpv(point), 0, CP_ALL_LAYERS, CP_NO_GROUP, nullptr); - return shape == nullptr ? nullptr : PhysicsShapeInfo::map.find(shape)->second->shape; + return shape == nullptr ? nullptr : PhysicsShapeInfo::getMap().find(shape)->second->getShape(); } -Array* PhysicsWorld::getAllBody() const +Array* PhysicsWorld::getAllBodies() const { - return _bodys; + return _bodies; +} + +PhysicsBody* PhysicsWorld::getBody(int tag) const +{ + for (auto body : *_bodies) + { + if (((PhysicsBody*)body)->getTag() == tag) + { + return (PhysicsBody*)body; + } + } + + return nullptr; } #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) #endif -PhysicsWorld* PhysicsWorld::create() +PhysicsWorld* PhysicsWorld::create(Scene& scene) { PhysicsWorld * world = new PhysicsWorld(); - if(world && world->init()) + if(world && world->init(scene)) { return world; } @@ -622,19 +983,24 @@ PhysicsWorld::PhysicsWorld() : _gravity(Point(0.0f, -98.0f)) , _speed(1.0f) , _info(nullptr) -, _listener(nullptr) -, _bodys(nullptr) +, _bodies(nullptr) , _scene(nullptr) +, _delayDirty(false) , _debugDraw(false) , _drawNode(nullptr) +, _delayAddBodies(nullptr) +, _delayRemoveBodies(nullptr) { } PhysicsWorld::~PhysicsWorld() { + removeAllJoints(true); + removeAllBodies(); + CC_SAFE_RELEASE(_delayRemoveBodies); + CC_SAFE_RELEASE(_delayAddBodies); CC_SAFE_DELETE(_info); - CC_SAFE_RELEASE(_bodys); } NS_CC_END diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 63c841cc93..240e3fa660 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -22,13 +22,14 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - #ifndef __CCPHYSICS_WORLD_H__ #define __CCPHYSICS_WORLD_H__ +#include "CCPhysicsSetting.h" +#ifdef CC_USE_PHYSICS + #include +#include #include "CCObject.h" #include "CCGeometry.h" @@ -40,9 +41,6 @@ class PhysicsJoint; class PhysicsWorldInfo; class PhysicsShape; class PhysicsContact; -class PhysicsContactPreSolve; -class PhysicsContactPostSolve; -class PhysicsContactListener; class Array; class Sprite; @@ -50,37 +48,31 @@ class Scene; class DrawNode; class PhysicsWorld; -class PhysicsRayCastCallback -{ -public: - PhysicsRayCastCallback() - : report(nullptr) - {} - virtual ~PhysicsRayCastCallback(){} - /** - * @brief Called for each fixture found in the query. You control how the ray cast - * proceeds by returning a float: - * return true: continue - * return false: terminate the ray cast - * @param fixture the fixture hit by the ray - * @param point the point of initial intersection - * @param normal the normal vector at the point of intersection - * @return true to continue, false to terminate - */ - std::function report; -}; -class PhysicsRectQueryCallback + +typedef struct PhysicsRayCastInfo { -public: - PhysicsRectQueryCallback() - : report(nullptr) - {} - virtual ~PhysicsRectQueryCallback(){} - -public: - std::function report; -}; + PhysicsShape* shape; + Point start; + Point end; + Point contact; + Vect normal; + float fraction; + void* data; +}PhysicsRayCastInfo; + +/** + * @brief Called for each fixture found in the query. You control how the ray cast + * proceeds by returning a float: + * return true: continue + * return false: terminate the ray cast + * @param fixture the fixture hit by the ray + * @param point the point of initial intersection + * @param normal the normal vector at the point of intersection + * @return true to continue, false to terminate + */ +typedef std::function PhysicsRayCastCallbackFunc; +typedef std::function PhysicsRectQueryCallbackFunc; /** * @brief An PhysicsWorld object simulates collisions and other physical properties. You do not create PhysicsWorld objects directly; instead, you can get it from an Scene object. @@ -89,41 +81,42 @@ class PhysicsWorld { public: /** Adds a joint to the physics world.*/ - void addJoint(PhysicsJoint* joint); + virtual void addJoint(PhysicsJoint* joint); /** Removes a joint from the physics world.*/ - void removeJoint(PhysicsJoint* joint); + virtual void removeJoint(PhysicsJoint* joint, bool destroy); /** Remove all joints from the physics world.*/ - void removeAllJoints(); + virtual void removeAllJoints(bool destroy); - void rayCast(PhysicsRayCastCallback& callback, Point point1, Point point2, void* data); - void rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void* data); - Array* getShapesAtPoint(Point point); - PhysicsShape* getShapeAtPoint(Point point); - Array* getAllBody() const; + virtual void removeBody(PhysicsBody* body); + virtual void removeBody(int tag); + virtual void removeAllBodies(); + + void rayCast(PhysicsRayCastCallbackFunc func, const Point& point1, const Point& point2, void* data); + void rectQuery(PhysicsRectQueryCallbackFunc func, const Rect& rect, void* data); + Array* getShapes(const Point& point) const; + PhysicsShape* getShape(const Point& point) const; + Array* getAllBodies() const; + PhysicsBody* getBody(int tag) const; /** Register a listener to receive contact callbacks*/ - inline void registerContactListener(PhysicsContactListener* delegate) { _listener = delegate; } + //inline void registerContactListener(EventListenerPhysicsContact* delegate) { _listener = delegate; } /** Unregister a listener. */ - inline void unregisterContactListener() { _listener = nullptr; } + //inline void unregisterContactListener() { _listener = nullptr; } + inline Scene& getScene() const { return *_scene; } /** get the gravity value */ - inline Point getGravity() { return _gravity; } + inline Vect getGravity() const { return _gravity; } /** set the gravity value */ - void setGravity(Point gravity); + void setGravity(const Vect& gravity); /** test the debug draw is enabled */ - inline bool isDebugDraw() { return _debugDraw; } + inline bool isDebugDraw() const { return _debugDraw; } /** set the debug draw */ inline void setDebugDraw(bool debugDraw) { _debugDraw = debugDraw; } - virtual void removeBody(PhysicsBody* body); - virtual void removeBodyByTag(int tag); - protected: - static PhysicsWorld* create(); - bool init(); - - void setScene(Scene* scene); + static PhysicsWorld* create(Scene& scene); + bool init(Scene& scene); virtual void addBody(PhysicsBody* body); virtual void addShape(PhysicsShape* shape); @@ -132,27 +125,42 @@ protected: virtual void debugDraw(); virtual void drawWithShape(DrawNode* node, PhysicsShape* shape); - + virtual void drawWithJoint(DrawNode* node, PhysicsJoint* joint); virtual int collisionBeginCallback(PhysicsContact& contact); - virtual int collisionPreSolveCallback(PhysicsContact& contact, const PhysicsContactPreSolve& solve); - virtual void collisionPostSolveCallback(PhysicsContact& contact, const PhysicsContactPostSolve& solve); + virtual int collisionPreSolveCallback(PhysicsContact& contact); + virtual void collisionPostSolveCallback(PhysicsContact& contact); virtual void collisionSeparateCallback(PhysicsContact& contact); + virtual void doAddBody(PhysicsBody* body); + virtual void doRemoveBody(PhysicsBody* body); + virtual void doAddJoint(PhysicsJoint* joint); + virtual void doRemoveJoint(PhysicsJoint* joint); + virtual void addBodyOrDelay(PhysicsBody* body); + virtual void removeBodyOrDelay(PhysicsBody* body); + virtual void addJointOrDelay(PhysicsJoint* joint); + virtual void removeJointOrDelay(PhysicsJoint* joint); + virtual void updateBodies(); + virtual void updateJoints(); + protected: - Point _gravity; + Vect _gravity; float _speed; PhysicsWorldInfo* _info; - PhysicsContactListener* _listener; - - Array* _bodys; + Array* _bodies; std::list _joints; Scene* _scene; + bool _delayDirty; bool _debugDraw; DrawNode* _drawNode; + Array* _delayAddBodies; + Array* _delayRemoveBodies; + std::vector _delayAddJoints; + std::vector _delayRemoveJoints; + protected: PhysicsWorld(); virtual ~PhysicsWorld(); @@ -161,11 +169,11 @@ protected: friend class Scene; friend class PhysicsBody; friend class PhysicsShape; + friend class PhysicsJoint; friend class PhysicsWorldCallback; }; NS_CC_END -#endif // __CCPHYSICS_WORLD_H__ - #endif // CC_USE_PHYSICS +#endif // __CCPHYSICS_WORLD_H__ diff --git a/cocos/physics/CMakeLists.txt b/cocos/physics/CMakeLists.txt new file mode 100644 index 0000000000..1586db2379 --- /dev/null +++ b/cocos/physics/CMakeLists.txt @@ -0,0 +1,18 @@ +set(COCOS_PHYSICS_SRC + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsBody.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsContact.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsShape.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsJoint.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsWorld.cpp +) + diff --git a/cocos/physics/box2d/CCPhysicsBodyInfo.cpp b/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.cpp similarity index 97% rename from cocos/physics/box2d/CCPhysicsBodyInfo.cpp rename to cocos/physics/box2d/CCPhysicsBodyInfo_box2d.cpp index bfa20b616a..059619a264 100644 --- a/cocos/physics/box2d/CCPhysicsBodyInfo.cpp +++ b/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsBodyInfo.h" +#include "CCPhysicsBodyInfo_box2d.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsBodyInfo.h b/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h similarity index 92% rename from cocos/physics/box2d/CCPhysicsBodyInfo.h rename to cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h index 5c89ac5f19..f04076ffcf 100644 --- a/cocos/physics/box2d/CCPhysicsBodyInfo.h +++ b/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h @@ -22,12 +22,14 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_BODY_INFO_BOX2D_H__ +#define __CCPHYSICS_BODY_INFO_BOX2D_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#ifndef __CCPHYSICS_BODY_INFO_H__ -#define __CCPHYSICS_BODY_INFO_H__ #include "CCPlatformMacros.h" + NS_CC_BEGIN class PhysicsBodyInfo @@ -38,6 +40,6 @@ public: }; NS_CC_END -#endif // __CCPHYSICS_BODY_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D +#endif // __CCPHYSICS_BODY_INFO_BOX2D_H__ diff --git a/cocos/physics/box2d/CCPhysicsContactInfo.cpp b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp similarity index 97% rename from cocos/physics/box2d/CCPhysicsContactInfo.cpp rename to cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp index 41eaa4f831..4edb6ce3a2 100644 --- a/cocos/physics/box2d/CCPhysicsContactInfo.cpp +++ b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsContactInfo.h" +#include "CCPhysicsContactInfo_box2d.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsContactInfo.h b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h similarity index 92% rename from cocos/physics/box2d/CCPhysicsContactInfo.h rename to cocos/physics/box2d/CCPhysicsContactInfo_box2d.h index f1e41ef572..d66ed0e131 100644 --- a/cocos/physics/box2d/CCPhysicsContactInfo.h +++ b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h @@ -22,11 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_CONTACT_INFO_BOX2D_H__ +#define __CCPHYSICS_CONTACT_INFO_BOX2D_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#ifndef __CCPHYSICS_CONTACT_INFO_H__ -#define __CCPHYSICS_CONTACT_INFO_H__ #include "CCPlatformMacros.h" NS_CC_BEGIN @@ -38,6 +39,6 @@ public: }; NS_CC_END -#endif // __CCPHYSICS_CONTACT_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D +#endif // __CCPHYSICS_CONTACT_INFO_BOX2D_H__ diff --git a/cocos/physics/box2d/CCPhysicsHelper.h b/cocos/physics/box2d/CCPhysicsHelper_box2d.h similarity index 92% rename from cocos/physics/box2d/CCPhysicsHelper.h rename to cocos/physics/box2d/CCPhysicsHelper_box2d.h index 61dd2b6e4c..f14fcef36f 100644 --- a/cocos/physics/box2d/CCPhysicsHelper.h +++ b/cocos/physics/box2d/CCPhysicsHelper_box2d.h @@ -22,12 +22,11 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_HELPER_BOX2D_H__ +#define __CCPHYSICS_HELPER_BOX2D_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) - -#ifndef __CCPHYSICS_HELPER_H__ -#define __CCPHYSICS_HELPER_H__ - #include "CCPlatformMacros.h" #include "CCGeometry.h" @@ -38,6 +37,6 @@ class PhysicsHelper }; NS_CC_END -#endif // __CCPHYSICS_HELPER_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D +#endif // __CCPHYSICS_HELPER_BOX2D_H__ diff --git a/cocos/physics/box2d/CCPhysicsJointInfo.cpp b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp similarity index 97% rename from cocos/physics/box2d/CCPhysicsJointInfo.cpp rename to cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp index 753ba41534..a0b6363cde 100644 --- a/cocos/physics/box2d/CCPhysicsJointInfo.cpp +++ b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsJointInfo.h" +#include "CCPhysicsJointInfo_box2d.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsJointInfo.h b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h similarity index 92% rename from cocos/physics/box2d/CCPhysicsJointInfo.h rename to cocos/physics/box2d/CCPhysicsJointInfo_box2d.h index a60ecdb97e..e1404eec45 100644 --- a/cocos/physics/box2d/CCPhysicsJointInfo.h +++ b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h @@ -22,11 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_JOINT_INFO_BOX2D_H__ +#define __CCPHYSICS_JOINT_INFO_BOX2D_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#ifndef __CCPHYSICS_JOINT_INFO_H__ -#define __CCPHYSICS_JOINT_INFO_H__ #include "CCPlatformMacros.h" NS_CC_BEGIN @@ -38,6 +39,6 @@ public: }; NS_CC_END -#endif // __CCPHYSICS_JOINT_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D +#endif // __CCPHYSICS_JOINT_INFO_BOX2D_H__ diff --git a/cocos/physics/box2d/CCPhysicsShapeInfo.cpp b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp similarity index 97% rename from cocos/physics/box2d/CCPhysicsShapeInfo.cpp rename to cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp index a89ba7dae7..fc3aa61491 100644 --- a/cocos/physics/box2d/CCPhysicsShapeInfo.cpp +++ b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsShapeInfo.h" +#include "CCPhysicsShapeInfo_box2d.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsShapeInfo.h b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h similarity index 92% rename from cocos/physics/box2d/CCPhysicsShapeInfo.h rename to cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h index 8608f0bad1..15720797e0 100644 --- a/cocos/physics/box2d/CCPhysicsShapeInfo.h +++ b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h @@ -22,11 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_SHAPE_INFO_BOX2D_H__ +#define __CCPHYSICS_SHAPE_INFO_BOX2D_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#ifndef __CCPHYSICS_SHAPE_INFO_H__ -#define __CCPHYSICS_SHAPE_INFO_H__ #include "CCPlatformMacros.h" NS_CC_BEGIN @@ -38,6 +39,6 @@ public: }; NS_CC_END -#endif // __CCPHYSICS_SHAPE_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D +#endif // __CCPHYSICS_SHAPE_INFO_BOX2D_H__ diff --git a/cocos/physics/box2d/CCPhysicsWorldInfo.cpp b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp similarity index 97% rename from cocos/physics/box2d/CCPhysicsWorldInfo.cpp rename to cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp index 0de6c00d82..fbe3be06d4 100644 --- a/cocos/physics/box2d/CCPhysicsWorldInfo.cpp +++ b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsWorldInfo.h" +#include "CCPhysicsWorldInfo_box2d.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsWorldInfo.h b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h similarity index 92% rename from cocos/physics/box2d/CCPhysicsWorldInfo.h rename to cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h index 662fa19843..fac9fd5181 100644 --- a/cocos/physics/box2d/CCPhysicsWorldInfo.h +++ b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h @@ -22,11 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_WORLD_INFO_BOX2D_H__ +#define __CCPHYSICS_WORLD_INFO_BOX2D_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#ifndef __CCPHYSICS_WORLD_INFO_H__ -#define __CCPHYSICS_WORLD_INFO_H__ #include "CCPlatformMacros.h" NS_CC_BEGIN @@ -38,6 +39,6 @@ public: }; NS_CC_END -#endif // __CCPHYSICS_WORLD_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D +#endif // __CCPHYSICS_WORLD_INFO_BOX2D_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp similarity index 89% rename from cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp rename to cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp index 852dad1eeb..79ad011c17 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp @@ -22,24 +22,18 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsBodyInfo.h" +#include "CCPhysicsBodyInfo_chipmunk.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) NS_CC_BEGIN PhysicsBodyInfo::PhysicsBodyInfo() -: body(nullptr) -, group(CP_NO_GROUP) +: _body(nullptr) { } PhysicsBodyInfo::~PhysicsBodyInfo() { - if (body) cpBodyFree(body); -} - -Clonable* PhysicsBodyInfo::clone() const -{ - return nullptr; + if (_body) cpBodyFree(_body); } NS_CC_END diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo.h b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h similarity index 84% rename from cocos/physics/chipmunk/CCPhysicsBodyInfo.h rename to cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h index ec84526b59..143fec843c 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h @@ -22,33 +22,35 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_BODY_INFO_CHIPMUNK_H__ +#define __CCPHYSICS_BODY_INFO_CHIPMUNK_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -#ifndef __CCPHYSICS_BODY_INFO_H__ -#define __CCPHYSICS_BODY_INFO_H__ #include "chipmunk.h" #include "CCPlatformMacros.h" #include "CCObject.h" NS_CC_BEGIN -class PhysicsBodyInfo : public Clonable +class PhysicsBodyInfo { public: - cpBody* body; - cpGroup group; + inline cpBody* getBody() const { return _body; } + inline void setBody(cpBody* body) { _body = body; } private: PhysicsBodyInfo(); ~PhysicsBodyInfo(); - Clonable* clone() const override; +private: + cpBody* _body; friend class PhysicsBody; }; NS_CC_END -#endif // __CCPHYSICS_BODY_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // __CCPHYSICS_BODY_INFO_CHIPMUNK_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsContactInfo.cpp b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp similarity index 95% rename from cocos/physics/chipmunk/CCPhysicsContactInfo.cpp rename to cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp index 53b4f29b14..150c77a030 100644 --- a/cocos/physics/chipmunk/CCPhysicsContactInfo.cpp +++ b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsContactInfo.h" +#include "CCPhysicsContactInfo_chipmunk.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) NS_CC_BEGIN PhysicsContactInfo::PhysicsContactInfo(PhysicsContact* contact) -: contact(contact) +: _contact(contact) { } diff --git a/cocos/physics/chipmunk/CCPhysicsContactInfo.h b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h similarity index 86% rename from cocos/physics/chipmunk/CCPhysicsContactInfo.h rename to cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h index 6c302947b7..6cc0e189c1 100644 --- a/cocos/physics/chipmunk/CCPhysicsContactInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h @@ -22,11 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_CONTACT_INFO_CHIPMUNK_H__ +#define __CCPHYSICS_CONTACT_INFO_CHIPMUNK_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -#ifndef __CCPHYSICS_CONTACT_INFO_H__ -#define __CCPHYSICS_CONTACT_INFO_H__ #include "chipmunk.h" #include "CCPlatformMacros.h" NS_CC_BEGIN @@ -35,16 +36,19 @@ class PhysicsContact; class PhysicsContactInfo { public: - PhysicsContact* contact; + inline PhysicsContact* getContact() const { return _contact; } private: PhysicsContactInfo(PhysicsContact* contact); ~PhysicsContactInfo(); +private: + PhysicsContact* _contact; + friend class PhysicsContact; }; NS_CC_END -#endif // __CCPHYSICS_WORLD_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // __CCPHYSICS_CONTACT_INFO_CHIPMUNK_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsHelper.h b/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h similarity index 86% rename from cocos/physics/chipmunk/CCPhysicsHelper.h rename to cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h index bf6f6d14db..094a6b6c35 100644 --- a/cocos/physics/chipmunk/CCPhysicsHelper.h +++ b/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_HELPER_CHIPMUNK_H__ +#define __CCPHYSICS_HELPER_CHIPMUNK_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -#ifndef __CCPHYSICS_HELPER_H__ -#define __CCPHYSICS_HELPER_H__ - #include "chipmunk.h" #include "CCPlatformMacros.h" #include "CCGeometry.h" @@ -46,28 +46,28 @@ public: static cpBB rect2cpbb(const Rect& rect) { return cpBBNew(rect.origin.x, rect.origin.y, rect.origin.x + rect.size.width, rect.origin.y + rect.size.height); } static Rect cpbb2rect(const cpBB& bb) { return Rect(bb.l, bb.b, bb.r, bb.t); } - static Point* cpvs2points(const cpVect* cpvs, Point* points, int count) + static Point* cpvs2points(const cpVect* cpvs, Point* out, int count) { for (int i = 0; i < count; ++i) { - points[i] = cpv2point(cpvs[i]); + out[i] = cpv2point(cpvs[i]); } - return points; + return out; } - static cpVect* points2cpvs(const Point* points, cpVect* cpvs, int count) + static cpVect* points2cpvs(const Point* points, cpVect* out, int count) { for (int i = 0; i < count; ++i) { - cpvs[i] = point2cpv(points[i]); + out[i] = point2cpv(points[i]); } - return cpvs; + return out; } }; NS_CC_END -#endif // __CCPHYSICS_HELPER_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // __CCPHYSICS_HELPER_CHIPMUNK_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo.cpp b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp similarity index 75% rename from cocos/physics/chipmunk/CCPhysicsJointInfo.cpp rename to cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp index b3fc376710..2f8b7817cf 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo.cpp +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp @@ -22,21 +22,21 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsJointInfo.h" +#include "CCPhysicsJointInfo_chipmunk.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include NS_CC_BEGIN -std::map PhysicsJointInfo::map; +std::map PhysicsJointInfo::_map; PhysicsJointInfo::PhysicsJointInfo(PhysicsJoint* joint) -: joint(joint) +: _joint(joint) { } PhysicsJointInfo::~PhysicsJointInfo() { - for (cpConstraint* joint : joints) + for (cpConstraint* joint : _joints) { cpConstraintFree(joint); } @@ -46,21 +46,21 @@ void PhysicsJointInfo::add(cpConstraint* joint) { if (joint == nullptr) return; - joints.push_back(joint); - map.insert(std::pair(joint, this)); + _joints.push_back(joint); + _map.insert(std::pair(joint, this)); } void PhysicsJointInfo::remove(cpConstraint* joint) { if (joint == nullptr) return; - auto it = std::find(joints.begin(), joints.end(), joint); - if (it != joints.end()) + auto it = std::find(_joints.begin(), _joints.end(), joint); + if (it != _joints.end()) { - joints.erase(it); + _joints.erase(it); - auto mit = map.find(joint); - if (mit != map.end()) map.erase(mit); + auto mit = _map.find(joint); + if (mit != _map.end()) _map.erase(mit); cpConstraintFree(joint); } @@ -68,14 +68,14 @@ void PhysicsJointInfo::remove(cpConstraint* joint) void PhysicsJointInfo::removeAll() { - for (cpConstraint* joint : joints) + for (cpConstraint* joint : _joints) { - auto mit = map.find(joint); - if (mit != map.end()) map.erase(mit); + auto mit = _map.find(joint); + if (mit != _map.end()) _map.erase(mit); cpConstraintFree(joint); } - joints.clear(); + _joints.clear(); } NS_CC_END diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo.h b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h similarity index 78% rename from cocos/physics/chipmunk/CCPhysicsJointInfo.h rename to cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h index 04a2c716bf..bdd3f1e887 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h @@ -22,11 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_JOINT_INFO_CHIPMUNK_H__ +#define __CCPHYSICS_JOINT_INFO_CHIPMUNK_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -#ifndef __CCPHYSICS_JOINT_INFO_H__ -#define __CCPHYSICS_JOINT_INFO_H__ #include "chipmunk.h" #include "CCPlatformMacros.h" #include @@ -42,19 +43,23 @@ public: void remove(cpConstraint* shape); void removeAll(); -public: - std::vector joints; - PhysicsJoint* joint; - static std::map map; + PhysicsJoint* getJoint() const { return _joint; } + std::vector& getJoints() { return _joints; } + static std::map& getMap() { return _map; } private: PhysicsJointInfo(PhysicsJoint* joint); ~PhysicsJointInfo(); +private: + std::vector _joints; + PhysicsJoint* _joint; + static std::map _map; + friend class PhysicsJoint; }; NS_CC_END -#endif // __CCPHYSICS_SHAPE_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // __CCPHYSICS_JOINT_INFO_CHIPMUNK_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo.cpp b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp similarity index 65% rename from cocos/physics/chipmunk/CCPhysicsShapeInfo.cpp rename to cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp index 07e5c2f932..d12a053181 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo.cpp +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp @@ -22,32 +22,32 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsShapeInfo.h" +#include "CCPhysicsShapeInfo_chipmunk.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include NS_CC_BEGIN -std::map PhysicsShapeInfo::map; -cpBody* PhysicsShapeInfo::shareBody = nullptr; +std::map PhysicsShapeInfo::_map; +cpBody* PhysicsShapeInfo::_sharedBody = nullptr; PhysicsShapeInfo::PhysicsShapeInfo(PhysicsShape* shape) -: shape(shape) -, group(CP_NO_GROUP) +: _shape(shape) +, _group(CP_NO_GROUP) { - if (shareBody == nullptr) + if (_sharedBody == nullptr) { - shareBody = cpBodyNewStatic(); + _sharedBody = cpBodyNewStatic(); } - body = shareBody; + _body = _sharedBody; } PhysicsShapeInfo::~PhysicsShapeInfo() { - for (auto shape : shapes) + for (auto shape : _shapes) { - auto it = map.find(shape); - if (it != map.end()) map.erase(shape); + auto it = _map.find(shape); + if (it != _map.end()) _map.erase(shape); cpShapeFree(shape); } @@ -55,9 +55,9 @@ PhysicsShapeInfo::~PhysicsShapeInfo() void PhysicsShapeInfo::setGroup(cpGroup group) { - this->group = group; + this->_group = group; - for (cpShape* shape : shapes) + for (cpShape* shape : _shapes) { cpShapeSetGroup(shape, group); } @@ -65,12 +65,12 @@ void PhysicsShapeInfo::setGroup(cpGroup group) void PhysicsShapeInfo::setBody(cpBody* body) { - if (this->body != body) + if (this->_body != body) { - this->body = body; - for (cpShape* shape : shapes) + this->_body = body; + for (cpShape* shape : _shapes) { - cpShapeSetBody(shape, body == nullptr ? shareBody : body); + cpShapeSetBody(shape, body == nullptr ? _sharedBody : body); } } } @@ -79,22 +79,22 @@ void PhysicsShapeInfo::add(cpShape* shape) { if (shape == nullptr) return; - cpShapeSetGroup(shape, group); - shapes.push_back(shape); - map.insert(std::pair(shape, this)); + cpShapeSetGroup(shape, _group); + _shapes.push_back(shape); + _map.insert(std::pair(shape, this)); } void PhysicsShapeInfo::remove(cpShape* shape) { if (shape == nullptr) return; - auto it = std::find(shapes.begin(), shapes.end(), shape); - if (it != shapes.end()) + auto it = std::find(_shapes.begin(), _shapes.end(), shape); + if (it != _shapes.end()) { - shapes.erase(it); + _shapes.erase(it); - auto mit = map.find(shape); - if (mit != map.end()) map.erase(mit); + auto mit = _map.find(shape); + if (mit != _map.end()) _map.erase(mit); cpShapeFree(shape); } @@ -102,14 +102,14 @@ void PhysicsShapeInfo::remove(cpShape* shape) void PhysicsShapeInfo::removeAll() { - for (cpShape* shape : shapes) + for (cpShape* shape : _shapes) { - auto mit = map.find(shape); - if (mit != map.end()) map.erase(mit); + auto mit = _map.find(shape); + if (mit != _map.end()) _map.erase(mit); cpShapeFree(shape); } - shapes.clear(); + _shapes.clear(); } NS_CC_END diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo.h b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h similarity index 73% rename from cocos/physics/chipmunk/CCPhysicsShapeInfo.h rename to cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h index 83be655b02..2bdd55a7f9 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_SHAPE_INFO_CHIPMUNK_H__ +#define __CCPHYSICS_SHAPE_INFO_CHIPMUNK_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -#ifndef __CCPHYSICS_SHAPE_INFO_H__ -#define __CCPHYSICS_SHAPE_INFO_H__ - #include #include #include "chipmunk.h" @@ -47,21 +47,29 @@ public: void setBody(cpBody* body); public: - std::vector shapes; - PhysicsShape* shape; - cpBody* body; - cpGroup group; - static std::map map; - static cpBody* shareBody; + PhysicsShape* getShape() const { return _shape; } + std::vector& getShapes() { return _shapes; } + cpBody* getBody() const { return _body; } + cpGroup getGourp() const { return _group; } + static std::map& getMap() { return _map; } + static cpBody* getSharedBody() { return _sharedBody; } private: PhysicsShapeInfo(PhysicsShape* shape); ~PhysicsShapeInfo(); +private: + std::vector _shapes; + PhysicsShape* _shape; + cpBody* _body; + cpGroup _group; + static std::map _map; + static cpBody* _sharedBody; + friend class PhysicsShape; }; NS_CC_END -#endif // __CCPHYSICS_SHAPE_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // __CCPHYSICS_SHAPE_INFO_CHIPMUNK_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo.cpp b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp similarity index 70% rename from cocos/physics/chipmunk/CCPhysicsWorldInfo.cpp rename to cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp index 57f601ead7..a12e473ec1 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo.cpp +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp @@ -22,18 +22,33 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsWorldInfo.h" +#include "CCPhysicsWorldInfo_chipmunk.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) NS_CC_BEGIN +#define PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(name, type) \ +void PhysicsWorldInfo::add##name(cp##type* data) \ +{ \ + if (!cpSpaceContains##type(_space, data)) cpSpaceAdd##type(_space, data); \ +} \ +\ +void PhysicsWorldInfo::remove##name(cp##type* data) \ +{ \ + if (cpSpaceContains##type(_space, data)) cpSpaceRemove##type(_space, data); \ +} \ + +PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(Shape, Shape) +PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(Body, Body) +PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(Joint, Constraint) + PhysicsWorldInfo::PhysicsWorldInfo() { - space = cpSpaceNew(); + _space = cpSpaceNew(); } PhysicsWorldInfo::~PhysicsWorldInfo() { - cpSpaceFree(space); + cpSpaceFree(_space); } NS_CC_END diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo.h b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h similarity index 77% rename from cocos/physics/chipmunk/CCPhysicsWorldInfo.h rename to cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h index 71d56f0a5b..0c098d3d90 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h @@ -22,28 +22,39 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_WORLD_INFO_CHIPMUNK_H__ +#define __CCPHYSICS_WORLD_INFO_CHIPMUNK_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -#ifndef __CCPHYSICS_WORLD_INFO_H__ -#define __CCPHYSICS_WORLD_INFO_H__ #include "chipmunk.h" #include "CCPlatformMacros.h" +#include NS_CC_BEGIN class PhysicsWorldInfo { public: - cpSpace* space; + cpSpace* getSpace() const { return _space; } + void addShape(cpShape* shape); + void removeShape(cpShape* shape); + void addBody(cpBody* body); + void removeBody(cpBody* body); + void addJoint(cpConstraint* joint); + void removeJoint(cpConstraint* joint); private: PhysicsWorldInfo(); ~PhysicsWorldInfo(); +private: + cpSpace* _space; + friend class PhysicsWorld; }; NS_CC_END -#endif // __CCPHYSICS_WORLD_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // __CCPHYSICS_WORLD_INFO_CHIPMUNK_H__ diff --git a/cocos/scripting/CMakeLists.txt b/cocos/scripting/CMakeLists.txt new file mode 100644 index 0000000000..612d728162 --- /dev/null +++ b/cocos/scripting/CMakeLists.txt @@ -0,0 +1,44 @@ +set(LUABINDING_SRC + auto-generated/lua-bindings/lua_cocos2dx_auto.cpp + auto-generated/lua-bindings/lua_cocos2dx_extension_auto.cpp + auto-generated/lua-bindings/lua_cocos2dx_studio_auto.cpp + lua/bindings/tolua_fix.c + lua/bindings/CCLuaBridge.cpp + lua/bindings/CCLuaEngine.cpp + lua/bindings/CCLuaStack.cpp + lua/bindings/CCLuaValue.cpp + lua/bindings/Cocos2dxLuaLoader.cpp + lua/bindings/CCBProxy.cpp + lua/bindings/LuaOpengl.cpp + lua/bindings/LuaScriptHandlerMgr.cpp + lua/bindings/LuaBasicConversions.cpp + lua/bindings/lua_cocos2dx_manual.cpp + lua/bindings/lua_cocos2dx_extension_manual.cpp + lua/bindings/lua_cocos2dx_deprecated.cpp + lua/bindings/lua_xml_http_request.cpp +) + +include_directories( + auto-generated/lua-bindings + lua/bindings + ../../cocos/editor-support/cocosbuilder + ../../cocos/editor-support/cocostudio + ../../external/lua/lua + ../../external/lua/tolua +) + + +add_library(luabinding STATIC + ${LUABINDING_SRC} +) + +target_link_libraries(luabinding + tolua + lua +) + +set_target_properties(luabinding + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) diff --git a/cocos/scripting/javascript/bindings/Android.mk b/cocos/scripting/javascript/bindings/Android.mk index 8195fde121..ffb0167ce1 100644 --- a/cocos/scripting/javascript/bindings/Android.mk +++ b/cocos/scripting/javascript/bindings/Android.mk @@ -9,7 +9,6 @@ LOCAL_MODULE_FILENAME := libcocos2dxjsb LOCAL_SRC_FILES := ScriptingCore.cpp \ cocos2d_specifics.cpp \ js_manual_conversions.cpp \ - cocosjs_manual_conversions.cpp \ js_bindings_core.cpp \ js_bindings_opengl.cpp \ jsb_opengl_functions.cpp \ diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 5d902c1c23..86ddb4bd2e 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -60,14 +60,15 @@ static std::vector g_queue; static std::mutex g_qMutex; static std::mutex g_rwMutex; static int clientSocket = -1; -static unsigned long s_nestedLoopLevel = 0; +static uint32_t s_nestedLoopLevel = 0; // server entry point for the bg thread static void serverEntryPoint(void); js_proxy_t *_native_js_global_ht = NULL; js_proxy_t *_js_native_global_ht = NULL; -js_type_class_t *_js_global_type_ht = NULL; +std::unordered_map _js_global_type_map; + static char *_js_log_buf = NULL; static std::vector registrationList; @@ -96,6 +97,7 @@ static void executeJSFunctionFromReservedSpot(JSContext *cx, JSObject *obj, if (func == JSVAL_VOID) { return; } jsval thisObj = JS_GetReservedSlot(obj, 1); JSAutoCompartment ac(cx, obj); + if (thisObj == JSVAL_VOID) { JS_CallFunctionValue(cx, obj, func, 1, &dataVal, &retval); } else { @@ -245,7 +247,7 @@ JSBool JSBCore_version(JSContext *cx, uint32_t argc, jsval *vp) } char version[256]; - snprintf(version, sizeof(version)-1, "%s - %s", cocos2dVersion(), JSB_version); + snprintf(version, sizeof(version)-1, "%s", cocos2dVersion()); JSString * js_version = JS_InternString(cx, version); jsval ret = STRING_TO_JSVAL(js_version); @@ -376,7 +378,7 @@ void ScriptingCore::string_report(jsval val) { LOGD("val : return string is NULL"); } else { JSStringWrapper wrapper(str); - LOGD("val : return string =\n%s\n", (char *)wrapper); + LOGD("val : return string =\n%s\n", wrapper.get()); } } else if (JSVAL_IS_NUMBER(val)) { double number; @@ -527,7 +529,7 @@ JSBool ScriptingCore::runScript(const char *path, JSObject* global, JSContext* c // a) check jsc file first std::string byteCodePath = RemoveFileExt(std::string(path)) + BYTE_CODE_FILE_EXT; - unsigned long length = 0; + long length = 0; unsigned char* data = futil->getFileData(byteCodePath.c_str(), "rb", &length); @@ -604,14 +606,13 @@ void ScriptingCore::cleanup() _js_log_buf = NULL; } - js_type_class_t* current, *tmp; - HASH_ITER(hh, _js_global_type_ht, current, tmp) + for (auto iter = _js_global_type_map.begin(); iter != _js_global_type_map.end(); ++iter) { - HASH_DEL(_js_global_type_ht, current); - free(current->jsclass); - free(current); + free(iter->second->jsclass); + free(iter->second); } - HASH_CLEAR(hh, _js_global_type_ht); + + _js_global_type_map.clear(); } void ScriptingCore::reportError(JSContext *cx, const char *message, JSErrorReport *report) @@ -630,7 +631,7 @@ JSBool ScriptingCore::log(JSContext* cx, uint32_t argc, jsval *vp) JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "S", &string); if (string) { JSStringWrapper wrapper(string); - js_log("%s", (char *)wrapper); + js_log("%s", wrapper.get()); } } return JS_TRUE; @@ -670,14 +671,14 @@ JSBool ScriptingCore::executeScript(JSContext *cx, uint32_t argc, jsval *vp) // js::RootedObject* rootedGlobal = globals[name]; JSObject* debugObj = ScriptingCore::getInstance()->getDebugGlobal(); if (debugObj) { - res = ScriptingCore::getInstance()->runScript(path, debugObj); + res = ScriptingCore::getInstance()->runScript(path.get(), debugObj); } else { - JS_ReportError(cx, "Invalid global object: %s", (char*)name); + JS_ReportError(cx, "Invalid global object: %s", name.get()); return JS_FALSE; } } else { JSObject* glob = JS::CurrentGlobalOrNull(cx); - res = ScriptingCore::getInstance()->runScript(path, glob); + res = ScriptingCore::getInstance()->runScript(path.get(), glob); } return res; } @@ -763,12 +764,7 @@ void ScriptingCore::resumeSchedulesAndActions(js_proxy_t* p) void ScriptingCore::cleanupSchedulesAndActions(js_proxy_t* p) { - Array * arr = JSCallFuncWrapper::getTargetForNativeNode((Node*)p->ptr); - if (arr) { - arr->removeAllObjects(); - } - - arr = JSScheduleWrapper::getTargetForJSObject(p->obj); + Array* arr = JSScheduleWrapper::getTargetForJSObject(p->obj); if (arr) { Scheduler* pScheduler = Director::getInstance()->getScheduler(); Object* pObj = NULL; @@ -1163,803 +1159,6 @@ int ScriptingCore::sendEvent(ScriptEvent* evt) return 0; } -#pragma mark - Conversion Routines -JSBool jsval_to_int32( JSContext *cx, jsval vp, int32_t *outval ) -{ - JSBool ok = JS_TRUE; - double dp; - ok &= JS_ValueToNumber(cx, vp, &dp); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - ok &= !isnan(dp); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - *outval = (int32_t)dp; - - return ok; -} - -JSBool jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *outval ) -{ - JSBool ok = JS_TRUE; - double dp; - ok &= JS_ValueToNumber(cx, vp, &dp); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - ok &= !isnan(dp); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - *outval = (uint32_t)dp; - - return ok; -} - -JSBool jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *outval ) -{ - JSBool ok = JS_TRUE; - double dp; - ok &= JS_ValueToNumber(cx, vp, &dp); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - ok &= !isnan(dp); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - *outval = (uint16_t)dp; - - return ok; -} - -JSBool jsval_to_long_long(JSContext *cx, jsval vp, long long* r) { - JSObject *tmp_arg; - JSBool ok = JS_ValueToObject( cx, vp, &tmp_arg ); - JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); - JSB_PRECONDITION3( tmp_arg && JS_IsTypedArrayObject( tmp_arg ), cx, JS_FALSE, "Not a TypedArray object"); - JSB_PRECONDITION3( JS_GetTypedArrayByteLength( tmp_arg ) == sizeof(long long), cx, JS_FALSE, "Invalid Typed Array length"); - - uint32_t* arg_array = (uint32_t*)JS_GetArrayBufferViewData( tmp_arg ); - long long ret = arg_array[0]; - ret = ret << 32; - ret |= arg_array[1]; - - *r = ret; - return JS_TRUE; -} - -JSBool jsval_to_std_string(JSContext *cx, jsval v, std::string* ret) { - JSString *tmp = JS_ValueToString(cx, v); - JSB_PRECONDITION3(tmp, cx, JS_FALSE, "Error processing arguments"); - - JSStringWrapper str(tmp); - *ret = str.get(); - return JS_TRUE; -} - -JSBool jsval_to_ccpoint(JSContext *cx, jsval v, Point* ret) { - JSObject *tmp; - JS::RootedValue jsx(cx); - JS::RootedValue jsy(cx); - double x, y; - JSBool ok = v.isObject() && - JS_ValueToObject(cx, v, &tmp) && - JS_GetProperty(cx, tmp, "x", &jsx) && - JS_GetProperty(cx, tmp, "y", &jsy) && - JS_ValueToNumber(cx, jsx, &x) && - JS_ValueToNumber(cx, jsy, &y); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - ret->x = (float)x; - ret->y = (float)y; - return JS_TRUE; -} - -JSBool jsval_to_ccacceleration(JSContext* cx,jsval v, Acceleration* ret) { - JSObject *tmp; - JS::RootedValue jsx(cx); - JS::RootedValue jsy(cx); - JS::RootedValue jsz(cx); - JS::RootedValue jstimestamp(cx); - - double x, y, timestamp, z; - JSBool ok = v.isObject() && - JS_ValueToObject(cx, v, &tmp) && - JS_GetProperty(cx, tmp, "x", &jsx) && - JS_GetProperty(cx, tmp, "y", &jsy) && - JS_GetProperty(cx, tmp, "z", &jsz) && - JS_GetProperty(cx, tmp, "timestamp", &jstimestamp) && - JS_ValueToNumber(cx, jsx, &x) && - JS_ValueToNumber(cx, jsy, &y) && - JS_ValueToNumber(cx, jsz, &z) && - JS_ValueToNumber(cx, jstimestamp, ×tamp); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - ret->x = x; - ret->y = y; - ret->z = z; - ret->timestamp = timestamp; - return JS_TRUE; -} - -JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, Array** ret) -{ - JSBool ok = JS_TRUE; - Array* pArray = Array::create(); - for( int i=0; i < argc; i++ ) - { - double num = 0.0; - // optimization: JS_ValueToNumber is expensive. And can convert an string like "12" to a number - if ( JSVAL_IS_NUMBER(*vp)) { - ok &= JS_ValueToNumber(cx, *vp, &num ); - if (!ok) { - break; - } - pArray->addObject(Integer::create((int)num)); - } - else if (JSVAL_IS_STRING(*vp)) - { - JSStringWrapper str(JSVAL_TO_STRING(*vp), cx); - pArray->addObject(String::create(str)); - } - else - { - js_proxy_t* p; - JSObject* obj = JSVAL_TO_OBJECT(*vp); - p = jsb_get_js_proxy(obj); - if (p) { - pArray->addObject((Object*)p->ptr); - } - } - // next - vp++; - } - *ret = pArray; - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - return ok; -} - -JSBool jsval_to_ccrect(JSContext *cx, jsval v, Rect* ret) { - JSObject *tmp; - JS::RootedValue jsx(cx); - JS::RootedValue jsy(cx); - JS::RootedValue jswidth(cx); - JS::RootedValue jsheight(cx); - - double x, y, width, height; - JSBool ok = v.isObject() && - JS_ValueToObject(cx, v, &tmp) && - JS_GetProperty(cx, tmp, "x", &jsx) && - JS_GetProperty(cx, tmp, "y", &jsy) && - JS_GetProperty(cx, tmp, "width", &jswidth) && - JS_GetProperty(cx, tmp, "height", &jsheight) && - JS_ValueToNumber(cx, jsx, &x) && - JS_ValueToNumber(cx, jsy, &y) && - JS_ValueToNumber(cx, jswidth, &width) && - JS_ValueToNumber(cx, jsheight, &height); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - ret->origin.x = x; - ret->origin.y = y; - ret->size.width = width; - ret->size.height = height; - return JS_TRUE; -} - -JSBool jsval_to_ccsize(JSContext *cx, jsval v, Size* ret) { - JSObject *tmp; - JS::RootedValue jsw(cx); - JS::RootedValue jsh(cx); - double w, h; - JSBool ok = v.isObject() && - JS_ValueToObject(cx, v, &tmp) && - JS_GetProperty(cx, tmp, "width", &jsw) && - JS_GetProperty(cx, tmp, "height", &jsh) && - JS_ValueToNumber(cx, jsw, &w) && - JS_ValueToNumber(cx, jsh, &h); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - ret->width = w; - ret->height = h; - return JS_TRUE; -} - -JSBool jsval_to_cccolor4b(JSContext *cx, jsval v, Color4B* ret) { - JSObject *tmp; - JS::RootedValue jsr(cx); - JS::RootedValue jsg(cx); - JS::RootedValue jsb(cx); - JS::RootedValue jsa(cx); - - double r, g, b, a; - JSBool ok = v.isObject() && - JS_ValueToObject(cx, v, &tmp) && - JS_GetProperty(cx, tmp, "r", &jsr) && - JS_GetProperty(cx, tmp, "g", &jsg) && - JS_GetProperty(cx, tmp, "b", &jsb) && - JS_GetProperty(cx, tmp, "a", &jsa) && - JS_ValueToNumber(cx, jsr, &r) && - JS_ValueToNumber(cx, jsg, &g) && - JS_ValueToNumber(cx, jsb, &b) && - JS_ValueToNumber(cx, jsa, &a); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - ret->r = r; - ret->g = g; - ret->b = b; - ret->a = a; - return JS_TRUE; -} - -JSBool jsval_to_cccolor4f(JSContext *cx, jsval v, Color4F* ret) { - JSObject *tmp; - JS::RootedValue jsr(cx); - JS::RootedValue jsg(cx); - JS::RootedValue jsb(cx); - JS::RootedValue jsa(cx); - double r, g, b, a; - JSBool ok = v.isObject() && - JS_ValueToObject(cx, v, &tmp) && - JS_GetProperty(cx, tmp, "r", &jsr) && - JS_GetProperty(cx, tmp, "g", &jsg) && - JS_GetProperty(cx, tmp, "b", &jsb) && - JS_GetProperty(cx, tmp, "a", &jsa) && - JS_ValueToNumber(cx, jsr, &r) && - JS_ValueToNumber(cx, jsg, &g) && - JS_ValueToNumber(cx, jsb, &b) && - JS_ValueToNumber(cx, jsa, &a); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - ret->r = r; - ret->g = g; - ret->b = b; - ret->a = a; - return JS_TRUE; -} - -JSBool jsval_to_cccolor3b(JSContext *cx, jsval v, Color3B* ret) { - JSObject *tmp; - JS::RootedValue jsr(cx); - JS::RootedValue jsg(cx); - JS::RootedValue jsb(cx); - double r, g, b; - JSBool ok = v.isObject() && - JS_ValueToObject(cx, v, &tmp) && - JS_GetProperty(cx, tmp, "r", &jsr) && - JS_GetProperty(cx, tmp, "g", &jsg) && - JS_GetProperty(cx, tmp, "b", &jsb) && - JS_ValueToNumber(cx, jsr, &r) && - JS_ValueToNumber(cx, jsg, &g) && - JS_ValueToNumber(cx, jsb, &b); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - ret->r = r; - ret->g = g; - ret->b = b; - return JS_TRUE; -} - -JSBool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, Point **points, int *numPoints) { - // Parsing sequence - JSObject *jsobj; - JSBool ok = v.isObject() && JS_ValueToObject( cx, v, &jsobj ); - JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); - JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, JS_FALSE, "Object must be an array"); - - uint32_t len; - JS_GetArrayLength(cx, jsobj, &len); - - Point *array = (Point*)malloc( sizeof(Point) * len); - - for( uint32_t i=0; i< len;i++ ) { - jsval valarg; - JS_GetElement(cx, jsobj, i, &valarg); - - ok = jsval_to_ccpoint(cx, valarg, &array[i]); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - } - - *numPoints = len; - *points = array; - - return JS_TRUE; -} - - -JSBool jsval_to_ccarray(JSContext* cx, jsval v, Array** ret) { - JSObject *jsobj; - JSBool ok = v.isObject() && JS_ValueToObject( cx, v, &jsobj ); - JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); - JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, JS_FALSE, "Object must be an array"); - - uint32_t len = 0; - JS_GetArrayLength(cx, jsobj, &len); - Array* arr = Array::createWithCapacity(len); - for (uint32_t i=0; i < len; i++) { - jsval value; - if (JS_GetElement(cx, jsobj, i, &value)) { - if (value.isObject()) - { - js_proxy_t *proxy; - JSObject *tmp = JSVAL_TO_OBJECT(value); - proxy = jsb_get_js_proxy(tmp); - cocos2d::Object* cobj = (cocos2d::Object *)(proxy ? proxy->ptr : NULL); - // Don't test it. - //TEST_NATIVE_OBJECT(cx, cobj) - if (cobj) { - // It's a native js object. - arr->addObject(cobj); - } - else if (!JS_IsArrayObject(cx, tmp)){ - // It's a normal js object. - Dictionary* dictVal = NULL; - JSBool ok = jsval_to_ccdictionary(cx, value, &dictVal); - if (ok) { - arr->addObject(dictVal); - } - } - else { - // It's a js array object. - Array* arrVal = NULL; - JSBool ok = jsval_to_ccarray(cx, value, &arrVal); - if (ok) { - arr->addObject(arrVal); - } - } - } - else if (JSVAL_IS_STRING(value)) { - JSStringWrapper valueWapper(JSVAL_TO_STRING(value), cx); - arr->addObject(String::create(valueWapper.get())); -// CCLOG("iterate array: value = %s", valueWapper.get().c_str()); - } - else if (JSVAL_IS_NUMBER(value)) { - double number = 0.0; - JSBool ok = JS_ValueToNumber(cx, value, &number); - if (ok) { - arr->addObject(Double::create(number)); -// CCLOG("iterate array: value = %lf", number); - } - } - else if (JSVAL_IS_BOOLEAN(value)) { - JSBool boolVal = JS_FALSE; - JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); - if (ok) { - arr->addObject(Bool::create(boolVal)); -// CCLOG("iterate object: value = %d", boolVal); - } - } - else { - CCASSERT(false, "not supported type"); - } - } - } - *ret = arr; - return JS_TRUE; -} - - -jsval ccarray_to_jsval(JSContext* cx, Array *arr) -{ - JSObject *jsretArr = JS_NewArrayObject(cx, 0, NULL); - - Object* obj; - int i = 0; - CCARRAY_FOREACH(arr, obj) - { - jsval arrElement; - - //First, check whether object is associated with js object. - js_proxy_t* jsproxy = js_get_or_create_proxy(cx, obj); - if (jsproxy) { - arrElement = OBJECT_TO_JSVAL(jsproxy->obj); - } - else { - String* strVal = NULL; - Dictionary* dictVal = NULL; - Array* arrVal = NULL; - Double* doubleVal = NULL; - Bool* boolVal = NULL; - Float* floatVal = NULL; - Integer* intVal = NULL; - - if ((strVal = dynamic_cast(obj))) { - arrElement = c_string_to_jsval(cx, strVal->getCString()); - } else if ((dictVal = dynamic_cast(obj))) { - arrElement = ccdictionary_to_jsval(cx, dictVal); - } else if ((arrVal = dynamic_cast(obj))) { - arrElement = ccarray_to_jsval(cx, arrVal); - } else if ((doubleVal = dynamic_cast(obj))) { - arrElement = DOUBLE_TO_JSVAL(doubleVal->getValue()); - } else if ((floatVal = dynamic_cast(obj))) { - arrElement = DOUBLE_TO_JSVAL(floatVal->getValue()); - } else if ((intVal = dynamic_cast(obj))) { - arrElement = INT_TO_JSVAL(intVal->getValue()); - } else if ((boolVal = dynamic_cast(obj))) { - arrElement = BOOLEAN_TO_JSVAL(boolVal->getValue() ? JS_TRUE : JS_FALSE); - } else { - CCASSERT(false, "the type isn't suppored."); - } - } - if (!JS_SetElement(cx, jsretArr, i, &arrElement)) { - break; - } - ++i; - } - return OBJECT_TO_JSVAL(jsretArr); -} - -jsval ccdictionary_to_jsval(JSContext* cx, Dictionary* dict) -{ - JSObject* jsRet = JS_NewObject(cx, NULL, NULL, NULL); - DictElement* pElement = NULL; - CCDICT_FOREACH(dict, pElement) - { - JS::RootedValue dictElement(cx); - Object* obj = pElement->getObject(); - //First, check whether object is associated with js object. - js_proxy_t* jsproxy = js_get_or_create_proxy(cx, obj); - if (jsproxy) { - dictElement = OBJECT_TO_JSVAL(jsproxy->obj); - } - else { - String* strVal = NULL; - Dictionary* dictVal = NULL; - Array* arrVal = NULL; - Double* doubleVal = NULL; - Bool* boolVal = NULL; - Float* floatVal = NULL; - Integer* intVal = NULL; - - if ((strVal = dynamic_cast(obj))) { - dictElement = c_string_to_jsval(cx, strVal->getCString()); - } else if ((dictVal = dynamic_cast(obj))) { - dictElement = ccdictionary_to_jsval(cx, dictVal); - } else if ((arrVal = dynamic_cast(obj))) { - dictElement = ccarray_to_jsval(cx, arrVal); - } else if ((doubleVal = dynamic_cast(obj))) { - dictElement = DOUBLE_TO_JSVAL(doubleVal->getValue()); - } else if ((floatVal = dynamic_cast(obj))) { - dictElement = DOUBLE_TO_JSVAL(floatVal->getValue()); - } else if ((intVal = dynamic_cast(obj))) { - dictElement = INT_TO_JSVAL(intVal->getValue()); - } else if ((boolVal = dynamic_cast(obj))) { - dictElement = BOOLEAN_TO_JSVAL(boolVal->getValue() ? JS_TRUE : JS_FALSE); - } else { - CCASSERT(false, "the type isn't suppored."); - } - } - const char* key = pElement->getStrKey(); - if (key && strlen(key) > 0) - { - JS_SetProperty(cx, jsRet, key, dictElement); - } - } - return OBJECT_TO_JSVAL(jsRet); -} - -JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, Dictionary** ret) { - - if (JSVAL_IS_NULL(v) || JSVAL_IS_VOID(v)) - { - *ret = NULL; - return JS_TRUE; - } - - JSObject* tmp = JSVAL_TO_OBJECT(v); - if (!tmp) { - LOGD("jsval_to_ccdictionary: the jsval is not an object."); - return JS_FALSE; - } - - JSObject* it = JS_NewPropertyIterator(cx, tmp); - Dictionary* dict = NULL; - - while (true) - { - jsid idp; - jsval key; - if (! JS_NextProperty(cx, it, &idp) || ! JS_IdToValue(cx, idp, &key)) { - return JS_FALSE; // error - } - - if (key == JSVAL_VOID) { - break; // end of iteration - } - - if (!JSVAL_IS_STRING(key)) { - continue; // ignore integer properties - } - - JSStringWrapper keyWrapper(JSVAL_TO_STRING(key), cx); - if (!dict) { - dict = Dictionary::create(); - } - - JS::RootedValue value(cx); - JS_GetPropertyById(cx, tmp, idp, &value); - if (value.isObject()) - { - js_proxy_t *proxy; - JSObject *tmp = JSVAL_TO_OBJECT(value); - proxy = jsb_get_js_proxy(tmp); - cocos2d::Object* cobj = (cocos2d::Object *)(proxy ? proxy->ptr : NULL); - // Don't test it. - //TEST_NATIVE_OBJECT(cx, cobj) - if (cobj) { - // It's a native <-> js glue object. - dict->setObject(cobj, keyWrapper.get()); - } - else if (!JS_IsArrayObject(cx, tmp)){ - // It's a normal js object. - Dictionary* dictVal = NULL; - JSBool ok = jsval_to_ccdictionary(cx, value, &dictVal); - if (ok) { - dict->setObject(dictVal, keyWrapper.get()); - } - } - else { - // It's a js array object. - Array* arrVal = NULL; - JSBool ok = jsval_to_ccarray(cx, value, &arrVal); - if (ok) { - dict->setObject(arrVal, keyWrapper.get()); - } - } - } - else if (JSVAL_IS_STRING(value)) { - JSStringWrapper valueWapper(JSVAL_TO_STRING(value), cx); - dict->setObject(String::create(valueWapper.get()), keyWrapper.get()); -// CCLOG("iterate object: key = %s, value = %s", keyWrapper.get().c_str(), valueWapper.get().c_str()); - } - else if (JSVAL_IS_NUMBER(value)) { - double number = 0.0; - JSBool ok = JS_ValueToNumber(cx, value, &number); - if (ok) { - dict->setObject(Double::create(number), keyWrapper.get()); -// CCLOG("iterate object: key = %s, value = %lf", keyWrapper.get().c_str(), number); - } - } - else if (JSVAL_IS_BOOLEAN(value)) { - JSBool boolVal = JS_FALSE; - JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); - if (ok) { - dict->setObject(Bool::create(boolVal), keyWrapper.get()); -// CCLOG("iterate object: key = %s, value = %d", keyWrapper.get().c_str(), boolVal); - } - } - else { - CCASSERT(false, "not supported type"); - } - } - - *ret = dict; - return JS_TRUE; -} - -JSBool jsval_to_ccaffinetransform(JSContext* cx, jsval v, AffineTransform* ret) -{ - JSObject *tmp; - JS::RootedValue jsa(cx); - JS::RootedValue jsb(cx); - JS::RootedValue jsc(cx); - JS::RootedValue jsd(cx); - JS::RootedValue jstx(cx); - JS::RootedValue jsty(cx); - double a, b, c, d, tx, ty; - JSBool ok = JS_ValueToObject(cx, v, &tmp) && - JS_GetProperty(cx, tmp, "a", &jsa) && - JS_GetProperty(cx, tmp, "b", &jsb) && - JS_GetProperty(cx, tmp, "c", &jsc) && - JS_GetProperty(cx, tmp, "d", &jsd) && - JS_GetProperty(cx, tmp, "tx", &jstx) && - JS_GetProperty(cx, tmp, "ty", &jsty) && - JS_ValueToNumber(cx, jsa, &a) && - JS_ValueToNumber(cx, jsb, &b) && - JS_ValueToNumber(cx, jsc, &c) && - JS_ValueToNumber(cx, jsd, &d) && - JS_ValueToNumber(cx, jstx, &tx) && - JS_ValueToNumber(cx, jsty, &ty); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - *ret = AffineTransformMake(a, b, c, d, tx, ty); - return JS_TRUE; -} - -// From native type to jsval -jsval int32_to_jsval( JSContext *cx, int32_t number ) -{ - return INT_TO_JSVAL(number); -} - -jsval uint32_to_jsval( JSContext *cx, uint32_t number ) -{ - return UINT_TO_JSVAL(number); -} - -jsval long_long_to_jsval(JSContext* cx, long long v) { - JSObject *tmp = JS_NewUint32Array(cx, 2); - uint32_t *data = (uint32_t *)JS_GetArrayBufferViewData(tmp); - data[0] = ((uint32_t *)(&v))[0]; - data[1] = ((uint32_t *)(&v))[1]; - return OBJECT_TO_JSVAL(tmp); -} - -jsval std_string_to_jsval(JSContext* cx, const std::string& v) -{ - return c_string_to_jsval(cx, v.c_str(), v.size()); -} - -jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length /* = -1 */) -{ - if (v == NULL) - { - return JSVAL_NULL; - } - - JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET - - if (0 == length) - { - auto emptyStr = JS_NewStringCopyZ(cx, ""); - return STRING_TO_JSVAL(emptyStr); - } - - jsval ret = JSVAL_NULL; - int utf16_size = 0; - jschar* strUTF16 = (jschar*)cc_utf8_to_utf16(v, length, &utf16_size); - - if (strUTF16 && utf16_size > 0) { - JSString* str = JS_NewUCStringCopyN(cx, strUTF16, utf16_size); - if (str) { - ret = STRING_TO_JSVAL(str); - } - delete[] strUTF16; - } - return ret; -} - -jsval ccpoint_to_jsval(JSContext* cx, const Point& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval ccacceleration_to_jsval(JSContext* cx, const Acceleration& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "z", DOUBLE_TO_JSVAL(v.z), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "timestamp", DOUBLE_TO_JSVAL(v.timestamp), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval ccrect_to_jsval(JSContext* cx, const Rect& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.origin.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.origin.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "width", DOUBLE_TO_JSVAL(v.size.width), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "height", DOUBLE_TO_JSVAL(v.size.height), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval ccsize_to_jsval(JSContext* cx, const Size& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "width", DOUBLE_TO_JSVAL(v.width), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "height", DOUBLE_TO_JSVAL(v.height), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval cccolor4b_to_jsval(JSContext* cx, const Color4B& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "r", INT_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "g", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "b", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "a", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval cccolor4f_to_jsval(JSContext* cx, const Color4F& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "r", DOUBLE_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "g", DOUBLE_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "b", DOUBLE_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "a", DOUBLE_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval cccolor3b_to_jsval(JSContext* cx, const Color3B& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "r", INT_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "g", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "b", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval ccaffinetransform_to_jsval(JSContext* cx, const AffineTransform& t) -{ - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "a", DOUBLE_TO_JSVAL(t.a), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "b", DOUBLE_TO_JSVAL(t.b), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "c", DOUBLE_TO_JSVAL(t.c), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "d", DOUBLE_TO_JSVAL(t.d), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "tx", DOUBLE_TO_JSVAL(t.tx), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "ty", DOUBLE_TO_JSVAL(t.ty), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval FontDefinition_to_jsval(JSContext* cx, const FontDefinition& t) -{ - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_TRUE; - - ok &= JS_DefineProperty(cx, tmp, "fontName", std_string_to_jsval(cx, t._fontName), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "fontSize", int32_to_jsval(cx, t._fontSize), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "fontAlignmentH", int32_to_jsval(cx, (int32_t)t._alignment), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "fontAlignmentV", int32_to_jsval(cx, (int32_t)t._vertAlignment), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "fontFillColor", cccolor3b_to_jsval(cx, t._fontFillColor), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "fontDimensions", ccsize_to_jsval(cx, t._dimensions), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - // Shadow - ok &= JS_DefineProperty(cx, tmp, "shadowEnabled", BOOLEAN_TO_JSVAL(t._shadow._shadowEnabled), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "shadowOffset", ccsize_to_jsval(cx, t._shadow._shadowOffset), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "shadowBlur", DOUBLE_TO_JSVAL(t._shadow._shadowBlur), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "shadowOpacity", DOUBLE_TO_JSVAL(t._shadow._shadowOpacity), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - // Stroke - ok &= JS_DefineProperty(cx, tmp, "strokeEnabled", BOOLEAN_TO_JSVAL(t._stroke._strokeEnabled), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "strokeColor", cccolor3b_to_jsval(cx, t._stroke._strokeColor), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "strokeSize", DOUBLE_TO_JSVAL(t._stroke._strokeSize), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - #pragma mark - Debug void SimpleRunLoop::update(float dt) @@ -2301,240 +1500,58 @@ void jsb_remove_proxy(js_proxy_t* nativeProxy, js_proxy_t* jsProxy) JS_REMOVE_PROXY(nativeProxy, jsProxy); } -static Color3B getColorFromJSObject(JSContext *cx, JSObject *colorObject) +// JSStringWrapper +JSStringWrapper::JSStringWrapper() +: _buffer(nullptr) { - JS::RootedValue jsr(cx); - Color3B out; - JS_GetProperty(cx, colorObject, "r", &jsr); - double fontR = 0.0; - JS_ValueToNumber(cx, jsr, &fontR); - - JS_GetProperty(cx, colorObject, "g", &jsr); - double fontG = 0.0; - JS_ValueToNumber(cx, jsr, &fontG); - - JS_GetProperty(cx, colorObject, "b", &jsr); - double fontB = 0.0; - JS_ValueToNumber(cx, jsr, &fontB); - - // the out - out.r = (unsigned char)fontR; - out.g = (unsigned char)fontG; - out.b = (unsigned char)fontB; - - return out; } -Size getSizeFromJSObject(JSContext *cx, JSObject *sizeObject) +JSStringWrapper::JSStringWrapper(JSString* str, JSContext* cx/* = NULL*/) +: _buffer(nullptr) { - JS::RootedValue jsr(cx); - Size out; - JS_GetProperty(cx, sizeObject, "width", &jsr); - double width = 0.0; - JS_ValueToNumber(cx, jsr, &width); - - JS_GetProperty(cx, sizeObject, "height", &jsr); - double height = 0.0; - JS_ValueToNumber(cx, jsr, &height); - - - // the out - out.width = width; - out.height = height; - - return out; + set(str, cx); } -JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) +JSStringWrapper::JSStringWrapper(jsval val, JSContext* cx/* = NULL*/) +: _buffer(nullptr) { - JSObject *jsobj; - - if (!JS_ValueToObject( cx, vp, &jsobj ) ) - return JS_FALSE; - - JSB_PRECONDITION( jsobj, "Not a valid JS object"); - - // defaul values - const char * defautlFontName = "Arial"; - const int defaultFontSize = 32; - TextHAlignment defaultTextAlignment = TextHAlignment::LEFT; - TextVAlignment defaultTextVAlignment = TextVAlignment::TOP; - - // by default shadow and stroke are off - out->_shadow._shadowEnabled = false; - out->_stroke._strokeEnabled = false; - - // white text by default - out->_fontFillColor = Color3B::WHITE; - - // font name - JS::RootedValue jsr(cx); - JS_GetProperty(cx, jsobj, "fontName", &jsr); - JS_ValueToString(cx, jsr); - JSStringWrapper wrapper(jsr); - if ( wrapper ) - { - out->_fontName = (char*)wrapper; - } - else - { - out->_fontName = defautlFontName; - } - - // font size - JSBool hasProperty; - JS_HasProperty(cx, jsobj, "fontSize", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "fontSize", &jsr); - double fontSize = 0.0; - JS_ValueToNumber(cx, jsr, &fontSize); - out->_fontSize = fontSize; - } - else - { - out->_fontSize = defaultFontSize; - } - - // font alignment horizontal - JS_HasProperty(cx, jsobj, "fontAlignmentH", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "fontAlignmentH", &jsr); - double fontAlign = 0.0; - JS_ValueToNumber(cx, jsr, &fontAlign); - out->_alignment = (TextHAlignment)(int)fontAlign; - } - else - { - out->_alignment = defaultTextAlignment; - } - - // font alignment vertical - JS_HasProperty(cx, jsobj, "fontAlignmentV", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "fontAlignmentV", &jsr); - double fontAlign = 0.0; - JS_ValueToNumber(cx, jsr, &fontAlign); - out->_vertAlignment = (TextVAlignment)(int)fontAlign; - } - else - { - out->_vertAlignment = defaultTextVAlignment; - } - - // font fill color - JS_HasProperty(cx, jsobj, "fontFillColor", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "fontFillColor", &jsr); - - JSObject *jsobjColor; - if (!JS_ValueToObject( cx, jsr, &jsobjColor ) ) - return JS_FALSE; - - out->_fontFillColor = getColorFromJSObject(cx, jsobjColor); - } - - // font rendering box dimensions - JS_HasProperty(cx, jsobj, "fontDimensions", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "fontDimensions", &jsr); - - JSObject *jsobjSize; - if (!JS_ValueToObject( cx, jsr, &jsobjSize ) ) - return JS_FALSE; - - out->_dimensions = getSizeFromJSObject(cx, jsobjSize); - } - - // shadow - JS_HasProperty(cx, jsobj, "shadowEnabled", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "shadowEnabled", &jsr); - out->_shadow._shadowEnabled = ToBoolean(jsr); - - if ( out->_shadow._shadowEnabled ) - { - // default shadow values - out->_shadow._shadowOffset = Size(5, 5); - out->_shadow._shadowBlur = 1; - out->_shadow._shadowOpacity = 1; - - // shado offset - JS_HasProperty(cx, jsobj, "shadowOffset", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "shadowOffset", &jsr); - - JSObject *jsobjShadowOffset; - if (!JS_ValueToObject( cx, jsr, &jsobjShadowOffset ) ) - return JS_FALSE; - out->_shadow._shadowOffset = getSizeFromJSObject(cx, jsobjShadowOffset); - } - - // shadow blur - JS_HasProperty(cx, jsobj, "shadowBlur", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "shadowBlur", &jsr); - double shadowBlur = 0.0; - JS_ValueToNumber(cx, jsr, &shadowBlur); - out->_shadow._shadowBlur = shadowBlur; - } - - // shadow intensity - JS_HasProperty(cx, jsobj, "shadowOpacity", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "shadowOpacity", &jsr); - double shadowOpacity = 0.0; - JS_ValueToNumber(cx, jsr, &shadowOpacity); - out->_shadow._shadowOpacity = shadowOpacity; - } - } - } - - // stroke - JS_HasProperty(cx, jsobj, "strokeEnabled", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "strokeEnabled", &jsr); - out->_stroke._strokeEnabled = ToBoolean(jsr); - - if ( out->_stroke._strokeEnabled ) - { - // default stroke values - out->_stroke._strokeSize = 1; - out->_stroke._strokeColor = Color3B::BLUE; - - // stroke color - JS_HasProperty(cx, jsobj, "strokeColor", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "strokeColor", &jsr); - - JSObject *jsobjStrokeColor; - if (!JS_ValueToObject( cx, jsr, &jsobjStrokeColor ) ) - return JS_FALSE; - out->_stroke._strokeColor = getColorFromJSObject(cx, jsobjStrokeColor); - } - - // stroke size - JS_HasProperty(cx, jsobj, "strokeSize", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "strokeSize", &jsr); - double strokeSize = 0.0; - JS_ValueToNumber(cx, jsr, &strokeSize); - out->_stroke._strokeSize = strokeSize; - } - } - } - - // we are done here - return JS_TRUE; + set(val, cx); } + +JSStringWrapper::~JSStringWrapper() +{ + CC_SAFE_DELETE_ARRAY(_buffer); +} + +void JSStringWrapper::set(jsval val, JSContext* cx) +{ + if (val.isString()) + { + this->set(val.toString(), cx); + } + else + { + CC_SAFE_DELETE_ARRAY(_buffer); + } +} + +void JSStringWrapper::set(JSString* str, JSContext* cx) +{ + CC_SAFE_DELETE_ARRAY(_buffer); + + if (!cx) + { + cx = ScriptingCore::getInstance()->getGlobalContext(); + } + // JS_EncodeString isn't supported in SpiderMonkey ff19.0. + //buffer = JS_EncodeString(cx, string); + unsigned short* pStrUTF16 = (unsigned short*)JS_GetStringCharsZ(cx, str); + + _buffer = cc_utf16_to_utf8(pStrUTF16, -1, NULL, NULL); +} + +const char* JSStringWrapper::get() +{ + return _buffer ? _buffer : ""; +} + diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.h b/cocos/scripting/javascript/bindings/ScriptingCore.h index 8df12fddc6..b0c6c45acb 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.h +++ b/cocos/scripting/javascript/bindings/ScriptingCore.h @@ -17,6 +17,7 @@ #include "jsapi.h" #include "jsfriendapi.h" #include "spidermonkey_specifics.h" +#include "js_manual_conversions.h" void js_log(const char *format, ...); @@ -204,98 +205,25 @@ public: int handleKeypadEvent(void* data); }; -// some utility functions -// to native -JSBool jsval_to_int32( JSContext *cx, jsval vp, int32_t *ret ); -JSBool jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *ret ); -JSBool jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *ret ); -JSBool jsval_to_long_long(JSContext *cx, jsval v, long long* ret); -JSBool jsval_to_std_string(JSContext *cx, jsval v, std::string* ret); -JSBool jsval_to_ccpoint(JSContext *cx, jsval v, Point* ret); -JSBool jsval_to_ccrect(JSContext *cx, jsval v, Rect* ret); -JSBool jsval_to_ccsize(JSContext *cx, jsval v, Size* ret); -JSBool jsval_to_cccolor4b(JSContext *cx, jsval v, Color4B* ret); -JSBool jsval_to_cccolor4f(JSContext *cx, jsval v, Color4F* ret); -JSBool jsval_to_cccolor3b(JSContext *cx, jsval v, Color3B* ret); -JSBool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, Point **points, int *numPoints); -JSBool jsval_to_ccarray(JSContext* cx, jsval v, Array** ret); -JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, Dictionary** ret); -JSBool jsval_to_ccacceleration(JSContext* cx,jsval v, Acceleration* ret); -JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, Array** ret); -JSBool jsval_to_ccaffinetransform(JSContext* cx, jsval v, AffineTransform* ret); -JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition* ret ); - -// from native -jsval int32_to_jsval( JSContext *cx, int32_t l); -jsval uint32_to_jsval( JSContext *cx, uint32_t number ); -jsval long_long_to_jsval(JSContext* cx, long long v); -jsval std_string_to_jsval(JSContext* cx, const std::string& v); -jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length = -1); -jsval ccpoint_to_jsval(JSContext* cx, const Point& v); -jsval ccrect_to_jsval(JSContext* cx, const Rect& v); -jsval ccsize_to_jsval(JSContext* cx, const Size& v); -jsval cccolor4b_to_jsval(JSContext* cx, const Color4B& v); -jsval cccolor4f_to_jsval(JSContext* cx, const Color4F& v); -jsval cccolor3b_to_jsval(JSContext* cx, const Color3B& v); -jsval ccdictionary_to_jsval(JSContext* cx, Dictionary *dict); -jsval ccarray_to_jsval(JSContext* cx, Array *arr); -jsval ccacceleration_to_jsval(JSContext* cx, const Acceleration& v); -jsval ccaffinetransform_to_jsval(JSContext* cx, const AffineTransform& t); -jsval FontDefinition_to_jsval(JSContext* cx, const FontDefinition& t); - JSObject* NewGlobalObject(JSContext* cx, bool debug = false); // just a simple utility to avoid mem leaking when using JSString class JSStringWrapper { - JSString* string; - const char* buffer; public: - JSStringWrapper() { - buffer = NULL; - } - JSStringWrapper(JSString* str, JSContext* cx = NULL) { - set(str, cx); - } - JSStringWrapper(jsval val, JSContext* cx = NULL) { - set(val, cx); - } - ~JSStringWrapper() { - if (buffer) { - //JS_free(ScriptingCore::getInstance()->getGlobalContext(), (void*)buffer); - delete[] buffer; - } - } - void set(jsval val, JSContext* cx) { - if (val.isString()) { - this->set(val.toString(), cx); - } else { - buffer = NULL; - } - } - void set(JSString* str, JSContext* cx) { - string = str; - if (!cx) { - cx = ScriptingCore::getInstance()->getGlobalContext(); - - } - // JS_EncodeString isn't supported in SpiderMonkey ff19.0. - //buffer = JS_EncodeString(cx, string); - unsigned short* pStrUTF16 = (unsigned short*)JS_GetStringCharsZ(cx, str); - buffer = cc_utf16_to_utf8(pStrUTF16, -1, NULL, NULL); - } - std::string get() { - return buffer; - } + JSStringWrapper(); + JSStringWrapper(JSString* str, JSContext* cx = NULL); + JSStringWrapper(jsval val, JSContext* cx = NULL); + ~JSStringWrapper(); + + void set(jsval val, JSContext* cx); + void set(JSString* str, JSContext* cx); + const char* get(); - operator std::string() { - return std::string(buffer); - } - operator char*() { - return (char*)buffer; - } private: - /* Copy and assignment are not supported. */ + const char* _buffer; + + /* Copy and assignment are not supported. */ JSStringWrapper(const JSStringWrapper &another); JSStringWrapper &operator=(const JSStringWrapper &another); }; @@ -320,6 +248,8 @@ public: JS_RemoveObjectRoot(this->_cx, &this->_jsthis); } JSBool invoke(unsigned int argc, jsval *argv, jsval &rval) { + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + return JS_CallFunctionValue(this->_cx, this->_jsthis, this->_fval, argc, argv, &rval); } private: diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id index c8c345c32c..0e67c34489 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id @@ -1 +1 @@ -6558be4f421be9227dc4fabf1b682d479825bd18 \ No newline at end of file +2a8f07a22574900290f772ad5a580ef9fc57a9b8 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.cpp.REMOVED.git-id index 5cf2a4495d..264696d780 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.cpp.REMOVED.git-id @@ -1 +1 @@ -1c5eb9cd58c82de77374cdfa5c9ff647cc8b2f02 \ No newline at end of file +ac3eca550f3b923d03d042ed63edf3b66cc183b7 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp index 197a270e91..d7c9f94f57 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp @@ -42,9 +42,13 @@ static JSBool dummy_constructor(JSContext *cx, uint32_t argc, jsval *vp) { T* cobj = new T(); cobj->autorelease(); js_type_class_t *p; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, p); - assert(p); + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + p = typeMapIter->second; + CCASSERT(p, "The value is null."); + JSObject *_tmp = JS_NewObject(cx, p->jsclass, p->proto, p->parentProto); js_proxy_t *pp = jsb_new_proxy(cobj, _tmp); JS_AddObjectRoot(cx, &pp->obj); @@ -179,10 +183,14 @@ JSBool JSB_CCPhysicsDebugNode_debugNodeForCPSpace__static(JSContext *cx, uint32_ do { if (ret) { TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); + JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); jsret = OBJECT_TO_JSVAL(obj); js_proxy_t *p = jsb_new_proxy(ret, obj); @@ -265,24 +273,27 @@ void JSB_CCPhysicsDebugNode_createClass(JSContext *cx, JSObject* globalObj, cons }; TypeTest t1; - js_type_class_t *typeClass; - uint32_t typeId = t1.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t1.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); JSB_CCPhysicsDebugNode_object = JS_InitClass(cx, globalObj, typeClass->proto, JSB_CCPhysicsDebugNode_class, dummy_constructor, 0,properties,funcs,NULL,st_funcs); TypeTest t; js_type_class_t *p; typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, p); - if (!p) { + + if (_js_global_type_map.find(typeId) == _js_global_type_map.end()) + { p = (js_type_class_t *)malloc(sizeof(js_type_class_t)); - p->type = typeId; p->jsclass = JSB_CCPhysicsDebugNode_class; p->proto = JSB_CCPhysicsDebugNode_object; p->parentProto = typeClass->proto; - HASH_ADD_INT(_js_global_type_ht, type, p); + _js_global_type_map.insert(std::make_pair(typeId, p)); } } @@ -305,10 +316,13 @@ JSBool JSPROXY_CCPhysicsSprite_spriteWithFile_rect__static(JSContext *cx, uint32 do { if (ret) { TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); + JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); jsret = OBJECT_TO_JSVAL(obj); js_proxy_t *p = jsb_new_proxy(ret, obj); @@ -331,10 +345,12 @@ JSBool JSPROXY_CCPhysicsSprite_spriteWithFile_rect__static(JSContext *cx, uint32 do { if (ret) { TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); jsret = OBJECT_TO_JSVAL(obj); js_proxy_t *p = jsb_new_proxy(ret, obj); @@ -370,10 +386,12 @@ JSBool JSPROXY_CCPhysicsSprite_spriteWithSpriteFrame__static(JSContext *cx, uint do { if (ret) { TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); jsret = OBJECT_TO_JSVAL(obj); js_proxy_t *p = jsb_new_proxy(ret, obj); @@ -393,29 +411,35 @@ JSBool JSPROXY_CCPhysicsSprite_spriteWithSpriteFrameName__static(JSContext *cx, JSBool ok = JS_TRUE; const char* arg0; std::string arg0_tmp; - if (argc >= 1) { + if (argc == 1) { ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); - } - PhysicsSprite* ret = PhysicsSprite::createWithSpriteFrameName(arg0); - jsval jsret; - do { - if (ret) { - TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); - JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); - jsret = OBJECT_TO_JSVAL(obj); - js_proxy_t *p = jsb_new_proxy(ret, obj); - JS_AddNamedObjectRoot(cx, &p->obj, "CCPhysicsSprite"); - } else { - jsret = JSVAL_NULL; - } - } while (0); - JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; + PhysicsSprite* ret = PhysicsSprite::createWithSpriteFrameName(arg0); + + jsval jsret; + do { + if (ret) { + TypeTest t; + js_type_class_t *typeClass = nullptr; + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); + JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); + jsret = OBJECT_TO_JSVAL(obj); + js_proxy_t *p = jsb_new_proxy(ret, obj); + JS_AddNamedObjectRoot(cx, &p->obj, "CCPhysicsSprite"); + } else { + jsret = JSVAL_NULL; + } + } while (0); + JS_SET_RVAL(cx, vp, jsret); + return JS_TRUE; + } + + JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 1); + return JS_FALSE; } void JSPROXY_CCPhysicsSprite_createClass(JSContext *cx, JSObject* globalObj) @@ -450,24 +474,25 @@ void JSPROXY_CCPhysicsSprite_createClass(JSContext *cx, JSObject* globalObj) }; TypeTest t1; - js_type_class_t *typeClass; - uint32_t typeId = t1.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t1.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); JSPROXY_CCPhysicsSprite_object = JS_InitClass(cx, globalObj, typeClass->proto, JSPROXY_CCPhysicsSprite_class, dummy_constructor, 0,properties,funcs,NULL,st_funcs); TypeTest t; js_type_class_t *p; typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, p); - if (!p) { + if (_js_global_type_map.find(typeId) == _js_global_type_map.end()) + { p = (js_type_class_t *)malloc(sizeof(js_type_class_t)); - p->type = typeId; p->jsclass = JSPROXY_CCPhysicsSprite_class; p->proto = JSPROXY_CCPhysicsSprite_object; p->parentProto = typeClass->proto; - HASH_ADD_INT(_js_global_type_ht, type, p); + _js_global_type_map.insert(std::make_pair(typeId, p)); } } @@ -638,6 +663,8 @@ static cpBool myCollisionBegin(cpArbiter *arb, cpSpace *space, void *data) args[0] = opaque_to_jsval( handler->cx, arb); args[1] = opaque_to_jsval( handler->cx, space ); } + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval rval; JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->begin), 2, args, &rval); @@ -662,6 +689,8 @@ static cpBool myCollisionPre(cpArbiter *arb, cpSpace *space, void *data) args[0] = opaque_to_jsval( handler->cx, arb); args[1] = opaque_to_jsval( handler->cx, space ); } + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval rval; JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->pre), 2, args, &rval); @@ -687,6 +716,8 @@ static void myCollisionPost(cpArbiter *arb, cpSpace *space, void *data) args[0] = opaque_to_jsval( handler->cx, arb); args[1] = opaque_to_jsval( handler->cx, space ); } + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval ignore; JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->post), 2, args, &ignore); @@ -705,6 +736,8 @@ static void myCollisionSeparate(cpArbiter *arb, cpSpace *space, void *data) args[0] = opaque_to_jsval( handler->cx, arb); args[1] = opaque_to_jsval( handler->cx, space ); } + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval ignore; JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->separate), 2, args, &ignore); diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.h b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.h index c6b40ca757..6807bd63e1 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.h +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.h @@ -27,7 +27,6 @@ #define __js_bindings_chipmunk_manual #include "js_bindings_config.h" -#include "cocosjs_manual_conversions.h" #include "js_manual_conversions.h" #include "ScriptingCore.h" #ifdef JSB_INCLUDE_CHIPMUNK diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 39e01fd1ef..bbc36bbe5b 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -c93df276adb92b5e076db49c4f9482b8eb37d45c \ No newline at end of file +36a6cc6177c059364c6ccc3b1151b6475219b396 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp b/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp index f7e9f2bdb4..9c03489007 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp @@ -39,14 +39,23 @@ extern callfuncTarget_proxy_t *_callfuncTarget_native_ht; */ template inline js_type_class_t *js_get_type_from_native(T* native_obj) { - js_type_class_t *typeProxy; + bool found = false; long typeId = typeid(*native_obj).hash_code(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeProxy); - if (!typeProxy) { + auto typeProxyIter = _js_global_type_map.find(typeId); + if (typeProxyIter == _js_global_type_map.end()) + { typeId = typeid(T).hash_code(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeProxy); + typeProxyIter = _js_global_type_map.find(typeId); + if (typeProxyIter != _js_global_type_map.end()) + { + found = true; + } } - return typeProxy; + else + { + found = true; + } + return found ? typeProxyIter->second : nullptr; } /** @@ -101,19 +110,6 @@ protected: jsval _extraData; }; -class JSCallFuncWrapper: public JSCallbackWrapper { -public: - JSCallFuncWrapper() {} - virtual ~JSCallFuncWrapper(void) { - return; - } - - static void setTargetForNativeNode(Node *pNode, JSCallFuncWrapper *target); - static Array * getTargetForNativeNode(Node *pNode); - - void callbackFunc(Node *node); -}; - class JSScheduleWrapper: public JSCallbackWrapper { diff --git a/cocos/scripting/javascript/bindings/cocosbuilder/cocosbuilder_specifics.hpp b/cocos/scripting/javascript/bindings/cocosbuilder/cocosbuilder_specifics.hpp index f6b3252c57..774c75820b 100644 --- a/cocos/scripting/javascript/bindings/cocosbuilder/cocosbuilder_specifics.hpp +++ b/cocos/scripting/javascript/bindings/cocosbuilder/cocosbuilder_specifics.hpp @@ -14,6 +14,8 @@ public: jsval retval = JSVAL_NULL; if(!JSVAL_IS_VOID(_jsCallback) && !JSVAL_IS_VOID(_jsThisObj)) { + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + JS_CallFunctionValue(cx, JSVAL_TO_OBJECT(_jsThisObj), _jsCallback, 0, NULL, &retval); } } diff --git a/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.cpp b/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.cpp deleted file mode 100644 index 56bd017069..0000000000 --- a/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.cpp +++ /dev/null @@ -1,134 +0,0 @@ -#include "jsapi.h" -#include "jsfriendapi.h" -#include "ScriptingCore.h" -#include "js_bindings_config.h" -#include "cocosjs_manual_conversions.h" - -#define JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - -using namespace cocos2d; - -JSBool jsval_to_CCPoint( JSContext *cx, jsval vp, Point *ret ) -{ -#ifdef JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - - JSObject *jsobj; - if( ! JS_ValueToObject( cx, vp, &jsobj ) ) - return JS_FALSE; - - JSB_PRECONDITION( jsobj, "Not a valid JS object"); - - JS::RootedValue valx(cx); - JS::RootedValue valy(cx); - JSBool ok = JS_TRUE; - ok &= JS_GetProperty(cx, jsobj, "x", &valx); - ok &= JS_GetProperty(cx, jsobj, "y", &valy); - - if( ! ok ) - return JS_FALSE; - - double x, y; - ok &= JS_ValueToNumber(cx, valx, &x); - ok &= JS_ValueToNumber(cx, valy, &y); - - if( ! ok ) - return JS_FALSE; - - ret->x = x; - ret->y = y; - - return JS_TRUE; - -#else // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - - JSObject *tmp_arg; - if( ! JS_ValueToObject( cx, vp, &tmp_arg ) ) - return JS_FALSE; - - JSB_PRECONDITION( tmp_arg && JS_IsTypedArrayObject( tmp_arg, cx ), "Not a TypedArray object"); - - JSB_PRECONDITION( JS_GetTypedArrayByteLength( tmp_arg, cx ) == sizeof(cpVect), "Invalid length"); - - *ret = *(Point*)JS_GetArrayBufferViewData( tmp_arg, cx ); - - return JS_TRUE; -#endif // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES -} - - -JSBool jsval_to_CGPoint( JSContext *cx, jsval vp, cpVect *ret ) -{ -#ifdef JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - - JSObject *jsobj; - if( ! JS_ValueToObject( cx, vp, &jsobj ) ) - return JS_FALSE; - - JSB_PRECONDITION( jsobj, "Not a valid JS object"); - - JS::RootedValue valx(cx); - JS::RootedValue valy(cx); - JSBool ok = JS_TRUE; - ok &= JS_GetProperty(cx, jsobj, "x", &valx); - ok &= JS_GetProperty(cx, jsobj, "y", &valy); - - if( ! ok ) - return JS_FALSE; - - double x, y; - ok &= JS_ValueToNumber(cx, valx, &x); - ok &= JS_ValueToNumber(cx, valy, &y); - - if( ! ok ) - return JS_FALSE; - - ret->x = x; - ret->y = y; - - return JS_TRUE; - -#else // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - - JSObject *tmp_arg; - if( ! JS_ValueToObject( cx, vp, &tmp_arg ) ) - return JS_FALSE; - - JSB_PRECONDITION( tmp_arg && JS_IsTypedArrayObject( tmp_arg, cx ), "Not a TypedArray object"); - - JSB_PRECONDITION( JS_GetTypedArrayByteLength( tmp_arg, cx ) == sizeof(cpVect), "Invalid length"); - - *ret = *(cpVect*)JS_GetArrayBufferViewData( tmp_arg, cx ); - - return JS_TRUE; -#endif // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES -} - - -jsval CGPoint_to_jsval( JSContext *cx, cpVect p) -{ - -#ifdef JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - - JSObject *object = JS_NewObject(cx, NULL, NULL, NULL ); - if (!object) - return JSVAL_VOID; - - if (!JS_DefineProperty(cx, object, "x", DOUBLE_TO_JSVAL(p.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) || - !JS_DefineProperty(cx, object, "y", DOUBLE_TO_JSVAL(p.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) ) - return JSVAL_VOID; - - return OBJECT_TO_JSVAL(object); - -#else // JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - -#ifdef __LP64__ - JSObject *typedArray = JS_NewFloat64Array( cx, 2 ); -#else - JSObject *typedArray = JS_NewFloat32Array( cx, 2 ); -#endif - - cpVect *buffer = (cpVect*)JS_GetArrayBufferViewData(typedArray, cx ); - *buffer = p; - return OBJECT_TO_JSVAL(typedArray); -#endif // ! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES -} diff --git a/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.h b/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.h deleted file mode 100644 index 339ac7da9c..0000000000 --- a/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef __COCOSJS_MANUAL_CONVERSIONS_H__ -#define __COCOSJS_MANUAL_CONVERSIONS_H__ - -#include "chipmunk.h" -#include "cocos2d.h" -#include "js_manual_conversions.h" - -//#ifdef __cplusplus -//extern "C" { -//#endif - -JSBool jsval_to_CGPoint( JSContext *cx, jsval vp, cpVect *out ); -jsval CGPoint_to_jsval( JSContext *cx, cpVect p ); - - -//#ifdef __cplusplus -//} -//#endif - -#define cpVect_to_jsval CGPoint_to_jsval -#define jsval_to_cpVect jsval_to_CGPoint - -#endif /* __COCOSJS_MANUAL_CONVERSIONS_H__ */ - diff --git a/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp b/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp index 34ecbca985..4838fbcab2 100644 --- a/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp +++ b/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp @@ -73,6 +73,9 @@ void JSArmatureWrapper::movementCallbackFunc(cocostudio::Armature *pArmature, co valArr[2] = idVal; JS_AddValueRoot(cx, valArr); + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + JS_CallFunctionValue(cx, thisObj, _jsCallback, 3, valArr, &retval); JS_RemoveValueRoot(cx, valArr); } @@ -88,6 +91,9 @@ void JSArmatureWrapper::addArmatureFileInfoAsyncCallbackFunc(float percent) jsval percentVal = DOUBLE_TO_JSVAL(percent); JS_AddValueRoot(cx, &percentVal); + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + JS_CallFunctionValue(cx, thisObj, _jsCallback, 1, &percentVal, &retval); JS_RemoveValueRoot(cx, &percentVal); } @@ -113,6 +119,9 @@ void JSArmatureWrapper::frameCallbackFunc(cocostudio::Bone *pBone, const char *f valArr[3] = currentIndexVal; JS_AddValueRoot(cx, valArr); + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + JS_CallFunctionValue(cx, thisObj, _jsCallback, 4, valArr, &retval); JS_RemoveValueRoot(cx, valArr); } diff --git a/cocos/scripting/javascript/bindings/js_bindings_core.cpp b/cocos/scripting/javascript/bindings/js_bindings_core.cpp index fbb6e808fb..19d63c30e3 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_core.cpp +++ b/cocos/scripting/javascript/bindings/js_bindings_core.cpp @@ -43,17 +43,6 @@ typedef struct _hashJSObject static tHashJSObject *hash = NULL; static tHashJSObject *reverse_hash = NULL; -// Globals -char* JSB_association_proxy_key = NULL; - -const char* JSB_version = "0.3-beta"; - - -static void its_finalize(JSFreeOp *fop, JSObject *obj) -{ - CCLOGINFO("Finalizing global class"); -} - //#pragma mark JSBCore - Helper free functions static void reportError(JSContext *cx, const char *message, JSErrorReport *report) { @@ -68,7 +57,7 @@ static void reportError(JSContext *cx, const char *message, JSErrorReport *repor void* jsb_get_proxy_for_jsobject(JSObject *obj) { tHashJSObject *element = NULL; - HASH_FIND_INT(hash, &obj, element); + HASH_FIND_PTR(hash, &obj, element); if( element ) return element->proxy; @@ -88,13 +77,13 @@ void jsb_set_proxy_for_jsobject(void *proxy, JSObject *obj) element->proxy = proxy; element->jsObject = obj; - HASH_ADD_INT( hash, jsObject, element ); + HASH_ADD_PTR( hash, jsObject, element ); } void jsb_del_proxy_for_jsobject(JSObject *obj) { tHashJSObject *element = NULL; - HASH_FIND_INT(hash, &obj, element); + HASH_FIND_PTR(hash, &obj, element); if( element ) { HASH_DEL(hash, element); free(element); @@ -107,7 +96,7 @@ void jsb_del_proxy_for_jsobject(JSObject *obj) JSObject* jsb_get_jsobject_for_proxy(void *proxy) { tHashJSObject *element = NULL; - HASH_FIND_INT(reverse_hash, &proxy, element); + HASH_FIND_PTR(reverse_hash, &proxy, element); if( element ) return element->jsObject; @@ -123,13 +112,13 @@ void jsb_set_jsobject_for_proxy(JSObject *jsobj, void* proxy) element->proxy = proxy; element->jsObject = jsobj; - HASH_ADD_INT( reverse_hash, proxy, element ); + HASH_ADD_PTR( reverse_hash, proxy, element ); } void jsb_del_jsobject_for_proxy(void* proxy) { tHashJSObject *element = NULL; - HASH_FIND_INT(reverse_hash, &proxy, element); + HASH_FIND_PTR(reverse_hash, &proxy, element); if( element ) { HASH_DEL(reverse_hash, element); free(element); diff --git a/cocos/scripting/javascript/bindings/js_bindings_core.h b/cocos/scripting/javascript/bindings/js_bindings_core.h index 958b969b2a..33553a9287 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_core.h +++ b/cocos/scripting/javascript/bindings/js_bindings_core.h @@ -30,10 +30,6 @@ #include "chipmunk.h" #include "SimpleAudioEngine.h" -// Globals -// one shared key for associations -extern char * JSB_association_proxy_key; - #ifdef __cplusplus extern "C" { #endif @@ -77,7 +73,6 @@ extern "C" { // needed for callbacks. It does nothing. JSBool JSB_do_nothing(JSContext *cx, uint32_t argc, jsval *vp); - extern const char* JSB_version; #ifdef __cplusplus } #endif diff --git a/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp b/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp index 9fbf145647..3a35eab630 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp +++ b/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp @@ -32,24 +32,27 @@ JSBool js_cocos2dx_GLNode_constructor(JSContext *cx, uint32_t argc, jsval *vp) if (argc == 0) { GLNode* cobj = new GLNode(); -#ifdef COCOS2D_JAVASCRIPT cocos2d::Object *_ccobj = dynamic_cast(cobj); if (_ccobj) { _ccobj->autorelease(); } -#endif + TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); + JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(obj)); // link the native object with the javascript object js_proxy_t *p = jsb_new_proxy(cobj, obj); -#ifdef COCOS2D_JAVASCRIPT + JS_AddNamedObjectRoot(cx, &p->obj, "cocos2d::GLNode"); -#endif + return JS_TRUE; } JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 0); @@ -131,14 +134,13 @@ void js_register_cocos2dx_GLNode(JSContext *cx, JSObject *global) { // add the proto and JSClass to the type->js info hash table TypeTest t; js_type_class_t *p; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, p); - if (!p) { + long typeId = t.s_id(); + if (_js_global_type_map.find(typeId) == _js_global_type_map.end()) + { p = (js_type_class_t *)malloc(sizeof(js_type_class_t)); - p->type = typeId; p->jsclass = js_cocos2dx_GLNode_class; p->proto = js_cocos2dx_GLNode_prototype; p->parentProto = jsb_Node_prototype; - HASH_ADD_INT(_js_global_type_ht, type, p); + _js_global_type_map.insert(std::make_pair(typeId, p)); } } diff --git a/cocos/scripting/javascript/bindings/js_manual_conversions.cpp b/cocos/scripting/javascript/bindings/js_manual_conversions.cpp index 521d1be2aa..0e3e20b617 100644 --- a/cocos/scripting/javascript/bindings/js_manual_conversions.cpp +++ b/cocos/scripting/javascript/bindings/js_manual_conversions.cpp @@ -8,6 +8,53 @@ #include "ScriptingCore.h" #include "js_bindings_config.h" #include "js_manual_conversions.h" +#include "cocos2d_specifics.hpp" + +USING_NS_CC; + +static Color3B getColorFromJSObject(JSContext *cx, JSObject *colorObject) +{ + JS::RootedValue jsr(cx); + Color3B out; + JS_GetProperty(cx, colorObject, "r", &jsr); + double fontR = 0.0; + JS_ValueToNumber(cx, jsr, &fontR); + + JS_GetProperty(cx, colorObject, "g", &jsr); + double fontG = 0.0; + JS_ValueToNumber(cx, jsr, &fontG); + + JS_GetProperty(cx, colorObject, "b", &jsr); + double fontB = 0.0; + JS_ValueToNumber(cx, jsr, &fontB); + + // the out + out.r = (unsigned char)fontR; + out.g = (unsigned char)fontG; + out.b = (unsigned char)fontB; + + return out; +} + +static Size getSizeFromJSObject(JSContext *cx, JSObject *sizeObject) +{ + JS::RootedValue jsr(cx); + Size out; + JS_GetProperty(cx, sizeObject, "width", &jsr); + double width = 0.0; + JS_ValueToNumber(cx, jsr, &width); + + JS_GetProperty(cx, sizeObject, "height", &jsr); + double height = 0.0; + JS_ValueToNumber(cx, jsr, &height); + + + // the out + out.width = width; + out.height = height; + + return out; +} JSBool jsval_to_opaque( JSContext *cx, jsval vp, void **r) { @@ -74,24 +121,6 @@ JSBool jsval_to_long( JSContext *cx, jsval vp, long *r ) return JS_TRUE; } -JSBool jsval_to_longlong( JSContext *cx, jsval vp, long long *r ) -{ - JSObject *tmp_arg; - JSBool ok = JS_ValueToObject( cx, vp, &tmp_arg ); - JSB_PRECONDITION2( ok, cx, JS_FALSE, "Error converting value to object"); - JSB_PRECONDITION2( tmp_arg && JS_IsTypedArrayObject( tmp_arg ), cx, JS_FALSE, "Not a TypedArray object"); - JSB_PRECONDITION2( JS_GetTypedArrayByteLength( tmp_arg ) == sizeof(long long), cx, JS_FALSE, "Invalid Typed Array length"); - - uint32_t* arg_array = (uint32_t*)JS_GetArrayBufferViewData( tmp_arg ); - long long ret = arg_array[0]; - ret = ret << 32; - ret |= arg_array[1]; - - *r = ret; - return JS_TRUE; -} - - jsval opaque_to_jsval( JSContext *cx, void *opaque ) { #ifdef __LP64__ @@ -147,53 +176,6 @@ JSBool jsval_to_uint( JSContext *cx, jsval vp, unsigned int *ret ) return jsval_to_int32(cx, vp, (int32_t*)ret); } - -JSBool JSB_jsval_to_int32( JSContext *cx, jsval vp, int32_t *outval ) -{ - JSBool ret = JS_FALSE; - double dp; - if( (ret=JS_ValueToNumber(cx, vp, &dp)) ) { - if( isnan(dp)) - return JS_FALSE; - *outval = (int32_t)dp; - } - return ret; -} - -JSBool JSB_jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *outval ) -{ - JSBool ret = JS_FALSE; - double dp; - if( (ret=JS_ValueToNumber(cx, vp, &dp)) ) { - if( isnan(dp)) - return JS_FALSE; - *outval = (uint32_t)dp; - } - return ret; -} - -JSBool JSB_jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *outval ) -{ - JSBool ret = JS_FALSE; - double dp; - if( (ret=JS_ValueToNumber(cx, vp, &dp)) ) { - if( isnan(dp)) - return JS_FALSE; - *outval = (uint16_t)dp; - } - return ret; -} - -jsval int_to_jsval( JSContext *cx, int number ) -{ - return INT_TO_JSVAL(number); -} - -jsval uint_to_jsval( JSContext *cx, unsigned int number ) -{ - return UINT_TO_JSVAL(number); -} - jsval long_to_jsval( JSContext *cx, long number ) { #ifdef __LP64__ @@ -249,12 +231,9 @@ JSBool jsval_to_charptr( JSContext *cx, jsval vp, const char **ret ) jsval charptr_to_jsval( JSContext *cx, const char *str) { - JSString *ret_obj = JS_NewStringCopyZ(cx, str); - return STRING_TO_JSVAL(ret_obj); + return c_string_to_jsval(cx, str); } - - JSBool JSB_jsval_typedarray_to_dataptr( JSContext *cx, jsval vp, GLsizei *count, void **data, JSArrayBufferViewType t) { JSObject *jsobj; @@ -345,4 +324,1114 @@ JSBool JSB_get_arraybufferview_dataptr( JSContext *cx, jsval vp, GLsizei *count, } +#pragma mark - Conversion Routines +JSBool jsval_to_int32( JSContext *cx, jsval vp, int32_t *outval ) +{ + JSBool ok = JS_TRUE; + double dp; + ok &= JS_ValueToNumber(cx, vp, &dp); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + ok &= !isnan(dp); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + *outval = (int32_t)dp; + + return ok; +} +JSBool jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *outval ) +{ + JSBool ok = JS_TRUE; + double dp; + ok &= JS_ValueToNumber(cx, vp, &dp); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + ok &= !isnan(dp); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + *outval = (uint32_t)dp; + + return ok; +} + +JSBool jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *outval ) +{ + JSBool ok = JS_TRUE; + double dp; + ok &= JS_ValueToNumber(cx, vp, &dp); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + ok &= !isnan(dp); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + *outval = (uint16_t)dp; + + return ok; +} + +JSBool jsval_to_long_long(JSContext *cx, jsval vp, long long* r) { + JSObject *tmp_arg; + JSBool ok = JS_ValueToObject( cx, vp, &tmp_arg ); + JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); + JSB_PRECONDITION3( tmp_arg && JS_IsTypedArrayObject( tmp_arg ), cx, JS_FALSE, "Not a TypedArray object"); + JSB_PRECONDITION3( JS_GetTypedArrayByteLength( tmp_arg ) == sizeof(long long), cx, JS_FALSE, "Invalid Typed Array length"); + + uint32_t* arg_array = (uint32_t*)JS_GetArrayBufferViewData( tmp_arg ); + long long ret = arg_array[0]; + ret = ret << 32; + ret |= arg_array[1]; + + *r = ret; + return JS_TRUE; +} + +JSBool jsval_to_std_string(JSContext *cx, jsval v, std::string* ret) { + JSString *tmp = JS_ValueToString(cx, v); + JSB_PRECONDITION3(tmp, cx, JS_FALSE, "Error processing arguments"); + + JSStringWrapper str(tmp); + *ret = str.get(); + return JS_TRUE; +} + +JSBool jsval_to_ccpoint(JSContext *cx, jsval v, Point* ret) { + JSObject *tmp; + JS::RootedValue jsx(cx); + JS::RootedValue jsy(cx); + double x, y; + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && + JS_GetProperty(cx, tmp, "x", &jsx) && + JS_GetProperty(cx, tmp, "y", &jsy) && + JS_ValueToNumber(cx, jsx, &x) && + JS_ValueToNumber(cx, jsy, &y); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + ret->x = (float)x; + ret->y = (float)y; + return JS_TRUE; +} + +JSBool jsval_to_ccacceleration(JSContext* cx,jsval v, Acceleration* ret) { + JSObject *tmp; + JS::RootedValue jsx(cx); + JS::RootedValue jsy(cx); + JS::RootedValue jsz(cx); + JS::RootedValue jstimestamp(cx); + + double x, y, timestamp, z; + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && + JS_GetProperty(cx, tmp, "x", &jsx) && + JS_GetProperty(cx, tmp, "y", &jsy) && + JS_GetProperty(cx, tmp, "z", &jsz) && + JS_GetProperty(cx, tmp, "timestamp", &jstimestamp) && + JS_ValueToNumber(cx, jsx, &x) && + JS_ValueToNumber(cx, jsy, &y) && + JS_ValueToNumber(cx, jsz, &z) && + JS_ValueToNumber(cx, jstimestamp, ×tamp); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + ret->x = x; + ret->y = y; + ret->z = z; + ret->timestamp = timestamp; + return JS_TRUE; +} + +JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, Array** ret) +{ + JSBool ok = JS_TRUE; + Array* pArray = Array::create(); + for( int i=0; i < argc; i++ ) + { + double num = 0.0; + // optimization: JS_ValueToNumber is expensive. And can convert an string like "12" to a number + if ( JSVAL_IS_NUMBER(*vp)) { + ok &= JS_ValueToNumber(cx, *vp, &num ); + if (!ok) { + break; + } + pArray->addObject(Integer::create((int)num)); + } + else if (JSVAL_IS_STRING(*vp)) + { + JSStringWrapper str(JSVAL_TO_STRING(*vp), cx); + pArray->addObject(String::create(str.get())); + } + else + { + js_proxy_t* p; + JSObject* obj = JSVAL_TO_OBJECT(*vp); + p = jsb_get_js_proxy(obj); + if (p) { + pArray->addObject((Object*)p->ptr); + } + } + // next + vp++; + } + *ret = pArray; + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + return ok; +} + +JSBool jsval_to_ccrect(JSContext *cx, jsval v, Rect* ret) { + JSObject *tmp; + JS::RootedValue jsx(cx); + JS::RootedValue jsy(cx); + JS::RootedValue jswidth(cx); + JS::RootedValue jsheight(cx); + + double x, y, width, height; + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && + JS_GetProperty(cx, tmp, "x", &jsx) && + JS_GetProperty(cx, tmp, "y", &jsy) && + JS_GetProperty(cx, tmp, "width", &jswidth) && + JS_GetProperty(cx, tmp, "height", &jsheight) && + JS_ValueToNumber(cx, jsx, &x) && + JS_ValueToNumber(cx, jsy, &y) && + JS_ValueToNumber(cx, jswidth, &width) && + JS_ValueToNumber(cx, jsheight, &height); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + ret->origin.x = x; + ret->origin.y = y; + ret->size.width = width; + ret->size.height = height; + return JS_TRUE; +} + +JSBool jsval_to_ccsize(JSContext *cx, jsval v, Size* ret) { + JSObject *tmp; + JS::RootedValue jsw(cx); + JS::RootedValue jsh(cx); + double w, h; + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && + JS_GetProperty(cx, tmp, "width", &jsw) && + JS_GetProperty(cx, tmp, "height", &jsh) && + JS_ValueToNumber(cx, jsw, &w) && + JS_ValueToNumber(cx, jsh, &h); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + ret->width = w; + ret->height = h; + return JS_TRUE; +} + +JSBool jsval_to_cccolor4b(JSContext *cx, jsval v, Color4B* ret) { + JSObject *tmp; + JS::RootedValue jsr(cx); + JS::RootedValue jsg(cx); + JS::RootedValue jsb(cx); + JS::RootedValue jsa(cx); + + double r, g, b, a; + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && + JS_GetProperty(cx, tmp, "r", &jsr) && + JS_GetProperty(cx, tmp, "g", &jsg) && + JS_GetProperty(cx, tmp, "b", &jsb) && + JS_GetProperty(cx, tmp, "a", &jsa) && + JS_ValueToNumber(cx, jsr, &r) && + JS_ValueToNumber(cx, jsg, &g) && + JS_ValueToNumber(cx, jsb, &b) && + JS_ValueToNumber(cx, jsa, &a); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + ret->r = r; + ret->g = g; + ret->b = b; + ret->a = a; + return JS_TRUE; +} + +JSBool jsval_to_cccolor4f(JSContext *cx, jsval v, Color4F* ret) { + JSObject *tmp; + JS::RootedValue jsr(cx); + JS::RootedValue jsg(cx); + JS::RootedValue jsb(cx); + JS::RootedValue jsa(cx); + double r, g, b, a; + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && + JS_GetProperty(cx, tmp, "r", &jsr) && + JS_GetProperty(cx, tmp, "g", &jsg) && + JS_GetProperty(cx, tmp, "b", &jsb) && + JS_GetProperty(cx, tmp, "a", &jsa) && + JS_ValueToNumber(cx, jsr, &r) && + JS_ValueToNumber(cx, jsg, &g) && + JS_ValueToNumber(cx, jsb, &b) && + JS_ValueToNumber(cx, jsa, &a); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + ret->r = r; + ret->g = g; + ret->b = b; + ret->a = a; + return JS_TRUE; +} + +JSBool jsval_to_cccolor3b(JSContext *cx, jsval v, Color3B* ret) { + JSObject *tmp; + JS::RootedValue jsr(cx); + JS::RootedValue jsg(cx); + JS::RootedValue jsb(cx); + double r, g, b; + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && + JS_GetProperty(cx, tmp, "r", &jsr) && + JS_GetProperty(cx, tmp, "g", &jsg) && + JS_GetProperty(cx, tmp, "b", &jsb) && + JS_ValueToNumber(cx, jsr, &r) && + JS_ValueToNumber(cx, jsg, &g) && + JS_ValueToNumber(cx, jsb, &b); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + ret->r = r; + ret->g = g; + ret->b = b; + return JS_TRUE; +} + +JSBool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, Point **points, int *numPoints) { + // Parsing sequence + JSObject *jsobj; + JSBool ok = v.isObject() && JS_ValueToObject( cx, v, &jsobj ); + JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); + JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, JS_FALSE, "Object must be an array"); + + uint32_t len; + JS_GetArrayLength(cx, jsobj, &len); + + Point *array = (Point*)malloc( sizeof(Point) * len); + + for( uint32_t i=0; i< len;i++ ) { + jsval valarg; + JS_GetElement(cx, jsobj, i, &valarg); + + ok = jsval_to_ccpoint(cx, valarg, &array[i]); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + } + + *numPoints = len; + *points = array; + + return JS_TRUE; +} + + +JSBool jsval_to_ccarray(JSContext* cx, jsval v, Array** ret) { + JSObject *jsobj; + JSBool ok = v.isObject() && JS_ValueToObject( cx, v, &jsobj ); + JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); + JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, JS_FALSE, "Object must be an array"); + + uint32_t len = 0; + JS_GetArrayLength(cx, jsobj, &len); + Array* arr = Array::createWithCapacity(len); + for (uint32_t i=0; i < len; i++) { + jsval value; + if (JS_GetElement(cx, jsobj, i, &value)) { + if (value.isObject()) + { + js_proxy_t *proxy; + JSObject *tmp = JSVAL_TO_OBJECT(value); + proxy = jsb_get_js_proxy(tmp); + cocos2d::Object* cobj = (cocos2d::Object *)(proxy ? proxy->ptr : NULL); + // Don't test it. + //TEST_NATIVE_OBJECT(cx, cobj) + if (cobj) { + // It's a native js object. + arr->addObject(cobj); + } + else if (!JS_IsArrayObject(cx, tmp)){ + // It's a normal js object. + Dictionary* dictVal = NULL; + JSBool ok = jsval_to_ccdictionary(cx, value, &dictVal); + if (ok) { + arr->addObject(dictVal); + } + } + else { + // It's a js array object. + Array* arrVal = NULL; + JSBool ok = jsval_to_ccarray(cx, value, &arrVal); + if (ok) { + arr->addObject(arrVal); + } + } + } + else if (JSVAL_IS_STRING(value)) { + JSStringWrapper valueWapper(JSVAL_TO_STRING(value), cx); + arr->addObject(String::create(valueWapper.get())); + // CCLOG("iterate array: value = %s", valueWapper.get().c_str()); + } + else if (JSVAL_IS_NUMBER(value)) { + double number = 0.0; + JSBool ok = JS_ValueToNumber(cx, value, &number); + if (ok) { + arr->addObject(Double::create(number)); + // CCLOG("iterate array: value = %lf", number); + } + } + else if (JSVAL_IS_BOOLEAN(value)) { + JSBool boolVal = JS_FALSE; + JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); + if (ok) { + arr->addObject(Bool::create(boolVal)); + // CCLOG("iterate object: value = %d", boolVal); + } + } + else { + CCASSERT(false, "not supported type"); + } + } + } + *ret = arr; + return JS_TRUE; +} + + +jsval ccarray_to_jsval(JSContext* cx, Array *arr) +{ + JSObject *jsretArr = JS_NewArrayObject(cx, 0, NULL); + + Object* obj; + int i = 0; + CCARRAY_FOREACH(arr, obj) + { + jsval arrElement; + + //First, check whether object is associated with js object. + js_proxy_t* jsproxy = js_get_or_create_proxy(cx, obj); + if (jsproxy) { + arrElement = OBJECT_TO_JSVAL(jsproxy->obj); + } + else { + String* strVal = NULL; + Dictionary* dictVal = NULL; + Array* arrVal = NULL; + Double* doubleVal = NULL; + Bool* boolVal = NULL; + Float* floatVal = NULL; + Integer* intVal = NULL; + + if ((strVal = dynamic_cast(obj))) { + arrElement = c_string_to_jsval(cx, strVal->getCString()); + } else if ((dictVal = dynamic_cast(obj))) { + arrElement = ccdictionary_to_jsval(cx, dictVal); + } else if ((arrVal = dynamic_cast(obj))) { + arrElement = ccarray_to_jsval(cx, arrVal); + } else if ((doubleVal = dynamic_cast(obj))) { + arrElement = DOUBLE_TO_JSVAL(doubleVal->getValue()); + } else if ((floatVal = dynamic_cast(obj))) { + arrElement = DOUBLE_TO_JSVAL(floatVal->getValue()); + } else if ((intVal = dynamic_cast(obj))) { + arrElement = INT_TO_JSVAL(intVal->getValue()); + } else if ((boolVal = dynamic_cast(obj))) { + arrElement = BOOLEAN_TO_JSVAL(boolVal->getValue() ? JS_TRUE : JS_FALSE); + } else { + CCASSERT(false, "the type isn't suppored."); + } + } + if (!JS_SetElement(cx, jsretArr, i, &arrElement)) { + break; + } + ++i; + } + return OBJECT_TO_JSVAL(jsretArr); +} + +jsval ccdictionary_to_jsval(JSContext* cx, Dictionary* dict) +{ + JSObject* jsRet = JS_NewObject(cx, NULL, NULL, NULL); + DictElement* pElement = NULL; + CCDICT_FOREACH(dict, pElement) + { + JS::RootedValue dictElement(cx); + Object* obj = pElement->getObject(); + //First, check whether object is associated with js object. + js_proxy_t* jsproxy = js_get_or_create_proxy(cx, obj); + if (jsproxy) { + dictElement = OBJECT_TO_JSVAL(jsproxy->obj); + } + else { + String* strVal = NULL; + Dictionary* dictVal = NULL; + Array* arrVal = NULL; + Double* doubleVal = NULL; + Bool* boolVal = NULL; + Float* floatVal = NULL; + Integer* intVal = NULL; + + if ((strVal = dynamic_cast(obj))) { + dictElement = c_string_to_jsval(cx, strVal->getCString()); + } else if ((dictVal = dynamic_cast(obj))) { + dictElement = ccdictionary_to_jsval(cx, dictVal); + } else if ((arrVal = dynamic_cast(obj))) { + dictElement = ccarray_to_jsval(cx, arrVal); + } else if ((doubleVal = dynamic_cast(obj))) { + dictElement = DOUBLE_TO_JSVAL(doubleVal->getValue()); + } else if ((floatVal = dynamic_cast(obj))) { + dictElement = DOUBLE_TO_JSVAL(floatVal->getValue()); + } else if ((intVal = dynamic_cast(obj))) { + dictElement = INT_TO_JSVAL(intVal->getValue()); + } else if ((boolVal = dynamic_cast(obj))) { + dictElement = BOOLEAN_TO_JSVAL(boolVal->getValue() ? JS_TRUE : JS_FALSE); + } else { + CCASSERT(false, "the type isn't suppored."); + } + } + const char* key = pElement->getStrKey(); + if (key && strlen(key) > 0) + { + JS_SetProperty(cx, jsRet, key, dictElement); + } + } + return OBJECT_TO_JSVAL(jsRet); +} + +JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, Dictionary** ret) +{ + if (JSVAL_IS_NULL(v) || JSVAL_IS_VOID(v)) + { + *ret = NULL; + return JS_TRUE; + } + + JSObject* tmp = JSVAL_TO_OBJECT(v); + if (!tmp) { + CCLOG("%s", "jsval_to_ccdictionary: the jsval is not an object."); + return JS_FALSE; + } + + JSObject* it = JS_NewPropertyIterator(cx, tmp); + Dictionary* dict = NULL; + + while (true) + { + jsid idp; + jsval key; + if (! JS_NextProperty(cx, it, &idp) || ! JS_IdToValue(cx, idp, &key)) { + return JS_FALSE; // error + } + + if (key == JSVAL_VOID) { + break; // end of iteration + } + + if (!JSVAL_IS_STRING(key)) { + continue; // ignore integer properties + } + + JSStringWrapper keyWrapper(JSVAL_TO_STRING(key), cx); + if (!dict) { + dict = Dictionary::create(); + } + + JS::RootedValue value(cx); + JS_GetPropertyById(cx, tmp, idp, &value); + if (value.isObject()) + { + js_proxy_t *proxy; + JSObject *tmp = JSVAL_TO_OBJECT(value); + proxy = jsb_get_js_proxy(tmp); + cocos2d::Object* cobj = (cocos2d::Object *)(proxy ? proxy->ptr : NULL); + // Don't test it. + //TEST_NATIVE_OBJECT(cx, cobj) + if (cobj) { + // It's a native <-> js glue object. + dict->setObject(cobj, keyWrapper.get()); + } + else if (!JS_IsArrayObject(cx, tmp)){ + // It's a normal js object. + Dictionary* dictVal = NULL; + JSBool ok = jsval_to_ccdictionary(cx, value, &dictVal); + if (ok) { + dict->setObject(dictVal, keyWrapper.get()); + } + } + else { + // It's a js array object. + Array* arrVal = NULL; + JSBool ok = jsval_to_ccarray(cx, value, &arrVal); + if (ok) { + dict->setObject(arrVal, keyWrapper.get()); + } + } + } + else if (JSVAL_IS_STRING(value)) { + JSStringWrapper valueWapper(JSVAL_TO_STRING(value), cx); + dict->setObject(String::create(valueWapper.get()), keyWrapper.get()); + // CCLOG("iterate object: key = %s, value = %s", keyWrapper.get().c_str(), valueWapper.get().c_str()); + } + else if (JSVAL_IS_NUMBER(value)) { + double number = 0.0; + JSBool ok = JS_ValueToNumber(cx, value, &number); + if (ok) { + dict->setObject(Double::create(number), keyWrapper.get()); + // CCLOG("iterate object: key = %s, value = %lf", keyWrapper.get().c_str(), number); + } + } + else if (JSVAL_IS_BOOLEAN(value)) { + JSBool boolVal = JS_FALSE; + JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); + if (ok) { + dict->setObject(Bool::create(boolVal), keyWrapper.get()); + // CCLOG("iterate object: key = %s, value = %d", keyWrapper.get().c_str(), boolVal); + } + } + else { + CCASSERT(false, "not supported type"); + } + } + + *ret = dict; + return JS_TRUE; +} + +JSBool jsval_to_ccaffinetransform(JSContext* cx, jsval v, AffineTransform* ret) +{ + JSObject *tmp; + JS::RootedValue jsa(cx); + JS::RootedValue jsb(cx); + JS::RootedValue jsc(cx); + JS::RootedValue jsd(cx); + JS::RootedValue jstx(cx); + JS::RootedValue jsty(cx); + double a, b, c, d, tx, ty; + JSBool ok = JS_ValueToObject(cx, v, &tmp) && + JS_GetProperty(cx, tmp, "a", &jsa) && + JS_GetProperty(cx, tmp, "b", &jsb) && + JS_GetProperty(cx, tmp, "c", &jsc) && + JS_GetProperty(cx, tmp, "d", &jsd) && + JS_GetProperty(cx, tmp, "tx", &jstx) && + JS_GetProperty(cx, tmp, "ty", &jsty) && + JS_ValueToNumber(cx, jsa, &a) && + JS_ValueToNumber(cx, jsb, &b) && + JS_ValueToNumber(cx, jsc, &c) && + JS_ValueToNumber(cx, jsd, &d) && + JS_ValueToNumber(cx, jstx, &tx) && + JS_ValueToNumber(cx, jsty, &ty); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + *ret = AffineTransformMake(a, b, c, d, tx, ty); + return JS_TRUE; +} + +// From native type to jsval +jsval int32_to_jsval( JSContext *cx, int32_t number ) +{ + return INT_TO_JSVAL(number); +} + +jsval uint32_to_jsval( JSContext *cx, uint32_t number ) +{ + return UINT_TO_JSVAL(number); +} + +jsval std_string_to_jsval(JSContext* cx, const std::string& v) +{ + return c_string_to_jsval(cx, v.c_str(), v.size()); +} + +jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length /* = -1 */) +{ + if (v == NULL) + { + return JSVAL_NULL; + } + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + + if (0 == length) + { + auto emptyStr = JS_NewStringCopyZ(cx, ""); + return STRING_TO_JSVAL(emptyStr); + } + + jsval ret = JSVAL_NULL; + int utf16_size = 0; + jschar* strUTF16 = (jschar*)cc_utf8_to_utf16(v, length, &utf16_size); + + if (strUTF16 && utf16_size > 0) { + JSString* str = JS_NewUCStringCopyN(cx, strUTF16, utf16_size); + if (str) { + ret = STRING_TO_JSVAL(str); + } + delete[] strUTF16; + } + return ret; +} + +jsval ccpoint_to_jsval(JSContext* cx, const Point& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval ccacceleration_to_jsval(JSContext* cx, const Acceleration& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "z", DOUBLE_TO_JSVAL(v.z), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "timestamp", DOUBLE_TO_JSVAL(v.timestamp), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval ccrect_to_jsval(JSContext* cx, const Rect& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.origin.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.origin.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "width", DOUBLE_TO_JSVAL(v.size.width), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "height", DOUBLE_TO_JSVAL(v.size.height), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval ccsize_to_jsval(JSContext* cx, const Size& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "width", DOUBLE_TO_JSVAL(v.width), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "height", DOUBLE_TO_JSVAL(v.height), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval cccolor4b_to_jsval(JSContext* cx, const Color4B& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "r", INT_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "g", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "b", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "a", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval cccolor4f_to_jsval(JSContext* cx, const Color4F& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "r", DOUBLE_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "g", DOUBLE_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "b", DOUBLE_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "a", DOUBLE_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval cccolor3b_to_jsval(JSContext* cx, const Color3B& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "r", INT_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "g", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "b", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval ccaffinetransform_to_jsval(JSContext* cx, const AffineTransform& t) +{ + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "a", DOUBLE_TO_JSVAL(t.a), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "b", DOUBLE_TO_JSVAL(t.b), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "c", DOUBLE_TO_JSVAL(t.c), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "d", DOUBLE_TO_JSVAL(t.d), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "tx", DOUBLE_TO_JSVAL(t.tx), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "ty", DOUBLE_TO_JSVAL(t.ty), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval FontDefinition_to_jsval(JSContext* cx, const FontDefinition& t) +{ + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_TRUE; + + ok &= JS_DefineProperty(cx, tmp, "fontName", std_string_to_jsval(cx, t._fontName), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "fontSize", int32_to_jsval(cx, t._fontSize), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "fontAlignmentH", int32_to_jsval(cx, (int32_t)t._alignment), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "fontAlignmentV", int32_to_jsval(cx, (int32_t)t._vertAlignment), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "fontFillColor", cccolor3b_to_jsval(cx, t._fontFillColor), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "fontDimensions", ccsize_to_jsval(cx, t._dimensions), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + // Shadow + ok &= JS_DefineProperty(cx, tmp, "shadowEnabled", BOOLEAN_TO_JSVAL(t._shadow._shadowEnabled), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "shadowOffset", ccsize_to_jsval(cx, t._shadow._shadowOffset), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "shadowBlur", DOUBLE_TO_JSVAL(t._shadow._shadowBlur), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "shadowOpacity", DOUBLE_TO_JSVAL(t._shadow._shadowOpacity), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + // Stroke + ok &= JS_DefineProperty(cx, tmp, "strokeEnabled", BOOLEAN_TO_JSVAL(t._stroke._strokeEnabled), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "strokeColor", cccolor3b_to_jsval(cx, t._stroke._strokeColor), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "strokeSize", DOUBLE_TO_JSVAL(t._stroke._strokeSize), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) +{ + JSObject *jsobj; + + if (!JS_ValueToObject( cx, vp, &jsobj ) ) + return JS_FALSE; + + JSB_PRECONDITION( jsobj, "Not a valid JS object"); + + // defaul values + const char * defautlFontName = "Arial"; + const int defaultFontSize = 32; + TextHAlignment defaultTextAlignment = TextHAlignment::LEFT; + TextVAlignment defaultTextVAlignment = TextVAlignment::TOP; + + // by default shadow and stroke are off + out->_shadow._shadowEnabled = false; + out->_stroke._strokeEnabled = false; + + // white text by default + out->_fontFillColor = Color3B::WHITE; + + // font name + JS::RootedValue jsr(cx); + JS_GetProperty(cx, jsobj, "fontName", &jsr); + JS_ValueToString(cx, jsr); + JSStringWrapper wrapper(jsr); + const char* fontName = wrapper.get(); + + if (fontName && strlen(fontName) > 0) + { + out->_fontName = fontName; + } + else + { + out->_fontName = defautlFontName; + } + + // font size + JSBool hasProperty; + JS_HasProperty(cx, jsobj, "fontSize", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "fontSize", &jsr); + double fontSize = 0.0; + JS_ValueToNumber(cx, jsr, &fontSize); + out->_fontSize = fontSize; + } + else + { + out->_fontSize = defaultFontSize; + } + + // font alignment horizontal + JS_HasProperty(cx, jsobj, "fontAlignmentH", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "fontAlignmentH", &jsr); + double fontAlign = 0.0; + JS_ValueToNumber(cx, jsr, &fontAlign); + out->_alignment = (TextHAlignment)(int)fontAlign; + } + else + { + out->_alignment = defaultTextAlignment; + } + + // font alignment vertical + JS_HasProperty(cx, jsobj, "fontAlignmentV", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "fontAlignmentV", &jsr); + double fontAlign = 0.0; + JS_ValueToNumber(cx, jsr, &fontAlign); + out->_vertAlignment = (TextVAlignment)(int)fontAlign; + } + else + { + out->_vertAlignment = defaultTextVAlignment; + } + + // font fill color + JS_HasProperty(cx, jsobj, "fontFillColor", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "fontFillColor", &jsr); + + JSObject *jsobjColor; + if (!JS_ValueToObject( cx, jsr, &jsobjColor ) ) + return JS_FALSE; + + out->_fontFillColor = getColorFromJSObject(cx, jsobjColor); + } + + // font rendering box dimensions + JS_HasProperty(cx, jsobj, "fontDimensions", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "fontDimensions", &jsr); + + JSObject *jsobjSize; + if (!JS_ValueToObject( cx, jsr, &jsobjSize ) ) + return JS_FALSE; + + out->_dimensions = getSizeFromJSObject(cx, jsobjSize); + } + + // shadow + JS_HasProperty(cx, jsobj, "shadowEnabled", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "shadowEnabled", &jsr); + out->_shadow._shadowEnabled = ToBoolean(jsr); + + if ( out->_shadow._shadowEnabled ) + { + // default shadow values + out->_shadow._shadowOffset = Size(5, 5); + out->_shadow._shadowBlur = 1; + out->_shadow._shadowOpacity = 1; + + // shado offset + JS_HasProperty(cx, jsobj, "shadowOffset", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "shadowOffset", &jsr); + + JSObject *jsobjShadowOffset; + if (!JS_ValueToObject( cx, jsr, &jsobjShadowOffset ) ) + return JS_FALSE; + out->_shadow._shadowOffset = getSizeFromJSObject(cx, jsobjShadowOffset); + } + + // shadow blur + JS_HasProperty(cx, jsobj, "shadowBlur", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "shadowBlur", &jsr); + double shadowBlur = 0.0; + JS_ValueToNumber(cx, jsr, &shadowBlur); + out->_shadow._shadowBlur = shadowBlur; + } + + // shadow intensity + JS_HasProperty(cx, jsobj, "shadowOpacity", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "shadowOpacity", &jsr); + double shadowOpacity = 0.0; + JS_ValueToNumber(cx, jsr, &shadowOpacity); + out->_shadow._shadowOpacity = shadowOpacity; + } + } + } + + // stroke + JS_HasProperty(cx, jsobj, "strokeEnabled", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "strokeEnabled", &jsr); + out->_stroke._strokeEnabled = ToBoolean(jsr); + + if ( out->_stroke._strokeEnabled ) + { + // default stroke values + out->_stroke._strokeSize = 1; + out->_stroke._strokeColor = Color3B::BLUE; + + // stroke color + JS_HasProperty(cx, jsobj, "strokeColor", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "strokeColor", &jsr); + + JSObject *jsobjStrokeColor; + if (!JS_ValueToObject( cx, jsr, &jsobjStrokeColor ) ) + return JS_FALSE; + out->_stroke._strokeColor = getColorFromJSObject(cx, jsobjStrokeColor); + } + + // stroke size + JS_HasProperty(cx, jsobj, "strokeSize", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "strokeSize", &jsr); + double strokeSize = 0.0; + JS_ValueToNumber(cx, jsr, &strokeSize); + out->_stroke._strokeSize = strokeSize; + } + } + } + + // we are done here + return JS_TRUE; +} + +#define JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + +JSBool jsval_to_CCPoint( JSContext *cx, jsval vp, Point *ret ) +{ +#ifdef JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + + JSObject *jsobj; + if( ! JS_ValueToObject( cx, vp, &jsobj ) ) + return JS_FALSE; + + JSB_PRECONDITION( jsobj, "Not a valid JS object"); + + JS::RootedValue valx(cx); + JS::RootedValue valy(cx); + JSBool ok = JS_TRUE; + ok &= JS_GetProperty(cx, jsobj, "x", &valx); + ok &= JS_GetProperty(cx, jsobj, "y", &valy); + + if( ! ok ) + return JS_FALSE; + + double x, y; + ok &= JS_ValueToNumber(cx, valx, &x); + ok &= JS_ValueToNumber(cx, valy, &y); + + if( ! ok ) + return JS_FALSE; + + ret->x = x; + ret->y = y; + + return JS_TRUE; + +#else // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + + JSObject *tmp_arg; + if( ! JS_ValueToObject( cx, vp, &tmp_arg ) ) + return JS_FALSE; + + JSB_PRECONDITION( tmp_arg && JS_IsTypedArrayObject( tmp_arg, cx ), "Not a TypedArray object"); + + JSB_PRECONDITION( JS_GetTypedArrayByteLength( tmp_arg, cx ) == sizeof(cpVect), "Invalid length"); + + *ret = *(Point*)JS_GetArrayBufferViewData( tmp_arg, cx ); + + return JS_TRUE; +#endif // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES +} + + +JSBool jsval_to_CGPoint( JSContext *cx, jsval vp, cpVect *ret ) +{ +#ifdef JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + + JSObject *jsobj; + if( ! JS_ValueToObject( cx, vp, &jsobj ) ) + return JS_FALSE; + + JSB_PRECONDITION( jsobj, "Not a valid JS object"); + + JS::RootedValue valx(cx); + JS::RootedValue valy(cx); + JSBool ok = JS_TRUE; + ok &= JS_GetProperty(cx, jsobj, "x", &valx); + ok &= JS_GetProperty(cx, jsobj, "y", &valy); + + if( ! ok ) + return JS_FALSE; + + double x, y; + ok &= JS_ValueToNumber(cx, valx, &x); + ok &= JS_ValueToNumber(cx, valy, &y); + + if( ! ok ) + return JS_FALSE; + + ret->x = x; + ret->y = y; + + return JS_TRUE; + +#else // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + + JSObject *tmp_arg; + if( ! JS_ValueToObject( cx, vp, &tmp_arg ) ) + return JS_FALSE; + + JSB_PRECONDITION( tmp_arg && JS_IsTypedArrayObject( tmp_arg, cx ), "Not a TypedArray object"); + + JSB_PRECONDITION( JS_GetTypedArrayByteLength( tmp_arg, cx ) == sizeof(cpVect), "Invalid length"); + + *ret = *(cpVect*)JS_GetArrayBufferViewData( tmp_arg, cx ); + + return JS_TRUE; +#endif // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES +} + + +jsval CGPoint_to_jsval( JSContext *cx, cpVect p) +{ + +#ifdef JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + + JSObject *object = JS_NewObject(cx, NULL, NULL, NULL ); + if (!object) + return JSVAL_VOID; + + if (!JS_DefineProperty(cx, object, "x", DOUBLE_TO_JSVAL(p.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) || + !JS_DefineProperty(cx, object, "y", DOUBLE_TO_JSVAL(p.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) ) + return JSVAL_VOID; + + return OBJECT_TO_JSVAL(object); + +#else // JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + +#ifdef __LP64__ + JSObject *typedArray = JS_NewFloat64Array( cx, 2 ); +#else + JSObject *typedArray = JS_NewFloat32Array( cx, 2 ); +#endif + + cpVect *buffer = (cpVect*)JS_GetArrayBufferViewData(typedArray, cx ); + *buffer = p; + return OBJECT_TO_JSVAL(typedArray); +#endif // ! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES +} diff --git a/cocos/scripting/javascript/bindings/js_manual_conversions.h b/cocos/scripting/javascript/bindings/js_manual_conversions.h index 7a4999ae80..b3d15c86e1 100644 --- a/cocos/scripting/javascript/bindings/js_manual_conversions.h +++ b/cocos/scripting/javascript/bindings/js_manual_conversions.h @@ -7,37 +7,70 @@ #include "jsapi.h" #include "js_bindings_core.h" - -//#ifdef __cplusplus -//extern "C" { -//#endif +#include "cocos2d.h" extern JSBool jsval_to_opaque( JSContext *cx, jsval vp, void **out ); extern JSBool jsval_to_int( JSContext *cx, jsval vp, int *out); extern JSBool jsval_to_uint( JSContext *cx, jsval vp, unsigned int *out); extern JSBool jsval_to_long( JSContext *cx, jsval vp, long *out); -extern JSBool jsval_to_longlong( JSContext *cx, jsval vp, long long *out); -extern jsval opaque_to_jsval( JSContext *cx, void* opaque); -extern jsval c_class_to_jsval( JSContext *cx, void* handle, JSObject* object, JSClass *klass, const char* class_name); extern JSBool jsval_to_c_class( JSContext *cx, jsval vp, void **out_native, struct jsb_c_proxy_s **out_proxy); -extern jsval int_to_jsval( JSContext *cx, int number ); -extern jsval uint_to_jsval( JSContext *cx, unsigned int number ); -extern jsval long_to_jsval( JSContext *cx, long number ); -extern jsval longlong_to_jsval( JSContext *cx, long long number ); /** converts a jsval (JS string) into a char */ extern JSBool jsval_to_charptr( JSContext *cx, jsval vp, const char **out); + +extern jsval opaque_to_jsval( JSContext *cx, void* opaque); +extern jsval c_class_to_jsval( JSContext *cx, void* handle, JSObject* object, JSClass *klass, const char* class_name); +extern jsval long_to_jsval( JSContext *cx, long number ); +extern jsval longlong_to_jsval( JSContext *cx, long long number ); + /* Converts a char ptr into a jsval (using JS string) */ extern jsval charptr_to_jsval( JSContext *cx, const char *str); - -extern JSBool JSB_jsval_to_int32( JSContext *cx, jsval vp, int32_t *outval ); -extern JSBool JSB_jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *outval); extern JSBool JSB_jsval_typedarray_to_dataptr( JSContext *cx, jsval vp, GLsizei *count, void **data, JSArrayBufferViewType t); extern JSBool JSB_get_arraybufferview_dataptr( JSContext *cx, jsval vp, GLsizei *count, GLvoid **data ); -extern JSBool JSB_jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *outval ); -//#ifdef __cplusplus -//} -//#endif +// some utility functions +// to native +JSBool jsval_to_int32( JSContext *cx, jsval vp, int32_t *ret ); +JSBool jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *ret ); +JSBool jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *ret ); +JSBool jsval_to_long_long(JSContext *cx, jsval v, long long* ret); +JSBool jsval_to_std_string(JSContext *cx, jsval v, std::string* ret); +JSBool jsval_to_ccpoint(JSContext *cx, jsval v, cocos2d::Point* ret); +JSBool jsval_to_ccrect(JSContext *cx, jsval v, cocos2d::Rect* ret); +JSBool jsval_to_ccsize(JSContext *cx, jsval v, cocos2d::Size* ret); +JSBool jsval_to_cccolor4b(JSContext *cx, jsval v, cocos2d::Color4B* ret); +JSBool jsval_to_cccolor4f(JSContext *cx, jsval v, cocos2d::Color4F* ret); +JSBool jsval_to_cccolor3b(JSContext *cx, jsval v, cocos2d::Color3B* ret); +JSBool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, cocos2d::Point **points, int *numPoints); +JSBool jsval_to_ccarray(JSContext* cx, jsval v, cocos2d::Array** ret); +JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, cocos2d::Dictionary** ret); +JSBool jsval_to_ccacceleration(JSContext* cx,jsval v, cocos2d::Acceleration* ret); +JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, cocos2d::Array** ret); +JSBool jsval_to_ccaffinetransform(JSContext* cx, jsval v, cocos2d::AffineTransform* ret); +JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, cocos2d::FontDefinition* ret ); + +// from native +jsval int32_to_jsval( JSContext *cx, int32_t l); +jsval uint32_to_jsval( JSContext *cx, uint32_t number ); +jsval long_long_to_jsval(JSContext* cx, long long v); +jsval std_string_to_jsval(JSContext* cx, const std::string& v); +jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length = -1); +jsval ccpoint_to_jsval(JSContext* cx, const cocos2d::Point& v); +jsval ccrect_to_jsval(JSContext* cx, const cocos2d::Rect& v); +jsval ccsize_to_jsval(JSContext* cx, const cocos2d::Size& v); +jsval cccolor4b_to_jsval(JSContext* cx, const cocos2d::Color4B& v); +jsval cccolor4f_to_jsval(JSContext* cx, const cocos2d::Color4F& v); +jsval cccolor3b_to_jsval(JSContext* cx, const cocos2d::Color3B& v); +jsval ccdictionary_to_jsval(JSContext* cx, cocos2d::Dictionary *dict); +jsval ccarray_to_jsval(JSContext* cx, cocos2d::Array *arr); +jsval ccacceleration_to_jsval(JSContext* cx, const cocos2d::Acceleration& v); +jsval ccaffinetransform_to_jsval(JSContext* cx, const cocos2d::AffineTransform& t); +jsval FontDefinition_to_jsval(JSContext* cx, const cocos2d::FontDefinition& t); + +JSBool jsval_to_CGPoint( JSContext *cx, jsval vp, cpVect *out ); +jsval CGPoint_to_jsval( JSContext *cx, cpVect p ); + +#define cpVect_to_jsval CGPoint_to_jsval +#define jsval_to_cpVect jsval_to_CGPoint #endif /* __JS_MANUAL_CONVERSIONS_H__ */ diff --git a/cocos/scripting/javascript/bindings/jsb_opengl_functions.cpp b/cocos/scripting/javascript/bindings/jsb_opengl_functions.cpp index 1d99cff3b3..878191adfd 100644 --- a/cocos/scripting/javascript/bindings/jsb_opengl_functions.cpp +++ b/cocos/scripting/javascript/bindings/jsb_opengl_functions.cpp @@ -12,7 +12,6 @@ //#include "jsb_config.h" #include "js_bindings_core.h" #include "js_manual_conversions.h" -#include "cocosjs_manual_conversions.h" #include "jsb_opengl_functions.h" // Arguments: GLenum @@ -23,7 +22,7 @@ JSBool JSB_glActiveTexture(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glActiveTexture((GLenum)arg0 ); @@ -39,8 +38,8 @@ JSBool JSB_glAttachShader(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glAttachShader((GLuint)arg0 , (GLuint)arg1 ); @@ -56,8 +55,8 @@ JSBool JSB_glBindAttribLocation(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; const char* arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); ok &= jsval_to_charptr(cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -74,8 +73,8 @@ JSBool JSB_glBindBuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBindBuffer((GLenum)arg0 , (GLuint)arg1 ); @@ -91,8 +90,8 @@ JSBool JSB_glBindFramebuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBindFramebuffer((GLenum)arg0 , (GLuint)arg1 ); @@ -108,8 +107,8 @@ JSBool JSB_glBindRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBindRenderbuffer((GLenum)arg0 , (GLuint)arg1 ); @@ -125,8 +124,8 @@ JSBool JSB_glBindTexture(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBindTexture((GLenum)arg0 , (GLuint)arg1 ); @@ -142,10 +141,10 @@ JSBool JSB_glBlendColor(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBlendColor((GLclampf)arg0 , (GLclampf)arg1 , (GLclampf)arg2 , (GLclampf)arg3 ); @@ -161,7 +160,7 @@ JSBool JSB_glBlendEquation(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBlendEquation((GLenum)arg0 ); @@ -177,8 +176,8 @@ JSBool JSB_glBlendEquationSeparate(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBlendEquationSeparate((GLenum)arg0 , (GLenum)arg1 ); @@ -194,8 +193,8 @@ JSBool JSB_glBlendFunc(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBlendFunc((GLenum)arg0 , (GLenum)arg1 ); @@ -211,10 +210,10 @@ JSBool JSB_glBlendFuncSeparate(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; uint32_t arg2; uint32_t arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBlendFuncSeparate((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 , (GLenum)arg3 ); @@ -230,10 +229,10 @@ JSBool JSB_glBufferData(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; void* arg1; uint32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg1); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBufferData((GLenum)arg0 , count, (GLvoid*)arg1 , (GLenum)arg2 ); @@ -249,8 +248,8 @@ JSBool JSB_glBufferSubData(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg2); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -268,7 +267,7 @@ JSBool JSB_glCheckFramebufferStatus(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLenum ret_val; @@ -285,7 +284,7 @@ JSBool JSB_glClear(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glClear((GLbitfield)arg0 ); @@ -301,10 +300,10 @@ JSBool JSB_glClearColor(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glClearColor((GLclampf)arg0 , (GLclampf)arg1 , (GLclampf)arg2 , (GLclampf)arg3 ); @@ -320,7 +319,7 @@ JSBool JSB_glClearDepthf(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glClearDepthf((GLclampf)arg0 ); @@ -336,7 +335,7 @@ JSBool JSB_glClearStencil(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glClearStencil((GLint)arg0 ); @@ -352,10 +351,10 @@ JSBool JSB_glColorMask(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint16_t arg0; uint16_t arg1; uint16_t arg2; uint16_t arg3; - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glColorMask((GLboolean)arg0 , (GLboolean)arg1 , (GLboolean)arg2 , (GLboolean)arg3 ); @@ -371,7 +370,7 @@ JSBool JSB_glCompileShader(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glCompileShader((GLuint)arg0 ); @@ -387,13 +386,13 @@ JSBool JSB_glCompressedTexImage2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; uint32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; int32_t arg6; void* arg7; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg6 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_int32( cx, *argvp++, &arg6 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg7); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -411,14 +410,14 @@ JSBool JSB_glCompressedTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; uint32_t arg6; int32_t arg7; void* arg8; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg6 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg7 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg6 ); + ok &= jsval_to_int32( cx, *argvp++, &arg7 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg8); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -436,14 +435,14 @@ JSBool JSB_glCopyTexImage2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; uint32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; int32_t arg6; int32_t arg7; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg6 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg7 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_int32( cx, *argvp++, &arg6 ); + ok &= jsval_to_int32( cx, *argvp++, &arg7 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glCopyTexImage2D((GLenum)arg0 , (GLint)arg1 , (GLenum)arg2 , (GLint)arg3 , (GLint)arg4 , (GLsizei)arg5 , (GLsizei)arg6 , (GLint)arg7 ); @@ -459,14 +458,14 @@ JSBool JSB_glCopyTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; int32_t arg6; int32_t arg7; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg6 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg7 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_int32( cx, *argvp++, &arg6 ); + ok &= jsval_to_int32( cx, *argvp++, &arg7 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glCopyTexSubImage2D((GLenum)arg0 , (GLint)arg1 , (GLint)arg2 , (GLint)arg3 , (GLint)arg4 , (GLint)arg5 , (GLsizei)arg6 , (GLsizei)arg7 ); @@ -493,7 +492,7 @@ JSBool JSB_glCreateShader(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLuint ret_val; @@ -510,7 +509,7 @@ JSBool JSB_glCullFace(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glCullFace((GLenum)arg0 ); @@ -526,7 +525,7 @@ JSBool JSB_glDeleteProgram(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDeleteProgram((GLuint)arg0 ); @@ -542,7 +541,7 @@ JSBool JSB_glDeleteShader(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDeleteShader((GLuint)arg0 ); @@ -558,7 +557,7 @@ JSBool JSB_glDepthFunc(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDepthFunc((GLenum)arg0 ); @@ -574,7 +573,7 @@ JSBool JSB_glDepthMask(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint16_t arg0; - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDepthMask((GLboolean)arg0 ); @@ -590,8 +589,8 @@ JSBool JSB_glDepthRangef(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDepthRangef((GLclampf)arg0 , (GLclampf)arg1 ); @@ -607,8 +606,8 @@ JSBool JSB_glDetachShader(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDetachShader((GLuint)arg0 , (GLuint)arg1 ); @@ -624,7 +623,7 @@ JSBool JSB_glDisable(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDisable((GLenum)arg0 ); @@ -640,7 +639,7 @@ JSBool JSB_glDisableVertexAttribArray(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDisableVertexAttribArray((GLuint)arg0 ); @@ -656,9 +655,9 @@ JSBool JSB_glDrawArrays(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDrawArrays((GLenum)arg0 , (GLint)arg1 , (GLsizei)arg2 ); @@ -674,9 +673,9 @@ JSBool JSB_glDrawElements(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; uint32_t arg2; void* arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg3); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -694,7 +693,7 @@ JSBool JSB_glEnable(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glEnable((GLenum)arg0 ); @@ -710,7 +709,7 @@ JSBool JSB_glEnableVertexAttribArray(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glEnableVertexAttribArray((GLuint)arg0 ); @@ -746,10 +745,10 @@ JSBool JSB_glFramebufferRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; uint32_t arg2; uint32_t arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glFramebufferRenderbuffer((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 , (GLuint)arg3 ); @@ -765,11 +764,11 @@ JSBool JSB_glFramebufferTexture2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; uint32_t arg2; uint32_t arg3; int32_t arg4; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glFramebufferTexture2D((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 , (GLuint)arg3 , (GLint)arg4 ); @@ -785,7 +784,7 @@ JSBool JSB_glFrontFace(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glFrontFace((GLenum)arg0 ); @@ -801,7 +800,7 @@ JSBool JSB_glGenerateMipmap(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glGenerateMipmap((GLenum)arg0 ); @@ -817,7 +816,7 @@ JSBool JSB_glGetAttribLocation(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; const char* arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_charptr( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); int ret_val; @@ -846,7 +845,7 @@ JSBool JSB_glGetUniformLocation(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; const char* arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_charptr( cx, *argvp++, &arg1 ); printf("%s ", arg1); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -865,8 +864,8 @@ JSBool JSB_glHint(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glHint((GLenum)arg0 , (GLenum)arg1 ); @@ -882,7 +881,7 @@ JSBool JSB_glIsBuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -899,7 +898,7 @@ JSBool JSB_glIsEnabled(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -916,7 +915,7 @@ JSBool JSB_glIsFramebuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -933,7 +932,7 @@ JSBool JSB_glIsProgram(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -950,7 +949,7 @@ JSBool JSB_glIsRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -967,7 +966,7 @@ JSBool JSB_glIsShader(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -984,7 +983,7 @@ JSBool JSB_glIsTexture(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -1001,7 +1000,7 @@ JSBool JSB_glLineWidth(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glLineWidth((GLfloat)arg0 ); @@ -1017,7 +1016,7 @@ JSBool JSB_glLinkProgram(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glLinkProgram((GLuint)arg0 ); @@ -1033,8 +1032,8 @@ JSBool JSB_glPixelStorei(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glPixelStorei((GLenum)arg0 , (GLint)arg1 ); @@ -1050,8 +1049,8 @@ JSBool JSB_glPolygonOffset(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glPolygonOffset((GLfloat)arg0 , (GLfloat)arg1 ); @@ -1067,12 +1066,12 @@ JSBool JSB_glReadPixels(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; uint32_t arg4; uint32_t arg5; void* arg6; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg5 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg4 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg5 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg6); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1100,10 +1099,10 @@ JSBool JSB_glRenderbufferStorage(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glRenderbufferStorage((GLenum)arg0 , (GLenum)arg1 , (GLsizei)arg2 , (GLsizei)arg3 ); @@ -1119,8 +1118,8 @@ JSBool JSB_glSampleCoverage(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; uint16_t arg1; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glSampleCoverage((GLclampf)arg0 , (GLboolean)arg1 ); @@ -1136,10 +1135,10 @@ JSBool JSB_glScissor(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glScissor((GLint)arg0 , (GLint)arg1 , (GLsizei)arg2 , (GLsizei)arg3 ); @@ -1155,9 +1154,9 @@ JSBool JSB_glStencilFunc(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; uint32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glStencilFunc((GLenum)arg0 , (GLint)arg1 , (GLuint)arg2 ); @@ -1173,10 +1172,10 @@ JSBool JSB_glStencilFuncSeparate(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; int32_t arg2; uint32_t arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glStencilFuncSeparate((GLenum)arg0 , (GLenum)arg1 , (GLint)arg2 , (GLuint)arg3 ); @@ -1192,7 +1191,7 @@ JSBool JSB_glStencilMask(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glStencilMask((GLuint)arg0 ); @@ -1208,8 +1207,8 @@ JSBool JSB_glStencilMaskSeparate(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glStencilMaskSeparate((GLenum)arg0 , (GLuint)arg1 ); @@ -1225,9 +1224,9 @@ JSBool JSB_glStencilOp(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; uint32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glStencilOp((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 ); @@ -1243,10 +1242,10 @@ JSBool JSB_glStencilOpSeparate(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; uint32_t arg2; uint32_t arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glStencilOpSeparate((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 , (GLenum)arg3 ); @@ -1262,14 +1261,14 @@ JSBool JSB_glTexImage2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; uint32_t arg6; uint32_t arg7; void* arg8; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg6 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg7 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg6 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg7 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg8); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1287,9 +1286,9 @@ JSBool JSB_glTexParameterf(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; int32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glTexParameterf((GLenum)arg0 , (GLenum)arg1 , (GLfloat)arg2 ); @@ -1305,9 +1304,9 @@ JSBool JSB_glTexParameteri(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; int32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glTexParameteri((GLenum)arg0 , (GLenum)arg1 , (GLint)arg2 ); @@ -1323,14 +1322,14 @@ JSBool JSB_glTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; uint32_t arg6; uint32_t arg7; void* arg8; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg6 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg7 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg6 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg7 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg8); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1348,8 +1347,8 @@ JSBool JSB_glUniform1f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform1f((GLint)arg0 , (GLfloat)arg1 ); @@ -1365,8 +1364,8 @@ JSBool JSB_glUniform1fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1384,8 +1383,8 @@ JSBool JSB_glUniform1i(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform1i((GLint)arg0 , (GLint)arg1 ); @@ -1401,8 +1400,8 @@ JSBool JSB_glUniform1iv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_INT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1420,9 +1419,9 @@ JSBool JSB_glUniform2f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform2f((GLint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 ); @@ -1438,8 +1437,8 @@ JSBool JSB_glUniform2fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1457,9 +1456,9 @@ JSBool JSB_glUniform2i(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform2i((GLint)arg0 , (GLint)arg1 , (GLint)arg2 ); @@ -1475,8 +1474,8 @@ JSBool JSB_glUniform2iv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_INT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1494,10 +1493,10 @@ JSBool JSB_glUniform3f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform3f((GLint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 , (GLfloat)arg3 ); @@ -1513,8 +1512,8 @@ JSBool JSB_glUniform3fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1532,10 +1531,10 @@ JSBool JSB_glUniform3i(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform3i((GLint)arg0 , (GLint)arg1 , (GLint)arg2 , (GLint)arg3 ); @@ -1551,8 +1550,8 @@ JSBool JSB_glUniform3iv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_INT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1570,11 +1569,11 @@ JSBool JSB_glUniform4f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform4f((GLint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 , (GLfloat)arg3 , (GLfloat)arg4 ); @@ -1590,8 +1589,8 @@ JSBool JSB_glUniform4fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1609,11 +1608,11 @@ JSBool JSB_glUniform4i(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform4i((GLint)arg0 , (GLint)arg1 , (GLint)arg2 , (GLint)arg3 , (GLint)arg4 ); @@ -1629,8 +1628,8 @@ JSBool JSB_glUniform4iv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_INT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1648,8 +1647,8 @@ JSBool JSB_glUniformMatrix2fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; uint16_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1667,8 +1666,8 @@ JSBool JSB_glUniformMatrix3fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; uint16_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1686,8 +1685,8 @@ JSBool JSB_glUniformMatrix4fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; uint16_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1705,7 +1704,7 @@ JSBool JSB_glUseProgram(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUseProgram((GLuint)arg0 ); @@ -1721,7 +1720,7 @@ JSBool JSB_glValidateProgram(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glValidateProgram((GLuint)arg0 ); @@ -1737,8 +1736,8 @@ JSBool JSB_glVertexAttrib1f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glVertexAttrib1f((GLuint)arg0 , (GLfloat)arg1 ); @@ -1754,7 +1753,7 @@ JSBool JSB_glVertexAttrib1fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; void* arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg1, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1772,9 +1771,9 @@ JSBool JSB_glVertexAttrib2f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glVertexAttrib2f((GLuint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 ); @@ -1790,7 +1789,7 @@ JSBool JSB_glVertexAttrib2fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; void* arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg1, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1808,10 +1807,10 @@ JSBool JSB_glVertexAttrib3f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glVertexAttrib3f((GLuint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 , (GLfloat)arg3 ); @@ -1827,7 +1826,7 @@ JSBool JSB_glVertexAttrib3fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; void* arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg1, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1845,11 +1844,11 @@ JSBool JSB_glVertexAttrib4f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glVertexAttrib4f((GLuint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 , (GLfloat)arg3 , (GLfloat)arg4 ); @@ -1865,7 +1864,7 @@ JSBool JSB_glVertexAttrib4fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; void* arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg1, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1883,12 +1882,12 @@ JSBool JSB_glVertexAttribPointer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; uint32_t arg2; uint16_t arg3; int32_t arg4; int32_t arg5; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glVertexAttribPointer((GLuint)arg0 , (GLint)arg1 , (GLenum)arg2 , (GLboolean)arg3 , (GLsizei)arg4 , (GLvoid*)arg5 ); @@ -1904,10 +1903,10 @@ JSBool JSB_glViewport(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glViewport((GLint)arg0 , (GLint)arg1 , (GLsizei)arg2 , (GLsizei)arg3 ); diff --git a/cocos/scripting/javascript/bindings/jsb_opengl_manual.cpp b/cocos/scripting/javascript/bindings/jsb_opengl_manual.cpp index 38a168b935..fa4e2d31c8 100644 --- a/cocos/scripting/javascript/bindings/jsb_opengl_manual.cpp +++ b/cocos/scripting/javascript/bindings/jsb_opengl_manual.cpp @@ -31,7 +31,6 @@ #include "jsb_opengl_manual.h" #include "js_manual_conversions.h" -#include "cocosjs_manual_conversions.h" #include "js_bindings_core.h" #include "jsb_opengl_functions.h" diff --git a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp index e3a0ba5b18..cb33e9d413 100644 --- a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp +++ b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp @@ -609,8 +609,8 @@ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, open) JSStringWrapper w1(jsMethod); JSStringWrapper w2(jsURL); - method = w1; - urlstr = w2; + method = w1.get(); + urlstr = w2.get(); _url = urlstr; _meth = method; @@ -771,8 +771,8 @@ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, setRequestHeader) JSStringWrapper w1(jsField); JSStringWrapper w2(jsValue); - field = w1; - value = w2; + field = w1.get(); + value = w2.get(); // Populate the request_header map. _setRequestHeader(field, value); diff --git a/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj b/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj index 11085f336c..a4cbbd4d50 100644 --- a/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj +++ b/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj @@ -13,7 +13,6 @@ - @@ -25,7 +24,6 @@ - diff --git a/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj.filters b/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj.filters index 1d1e1d400a..85bb2eccd3 100644 --- a/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj.filters +++ b/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj.filters @@ -17,9 +17,6 @@ manual - - manual - manual @@ -49,9 +46,6 @@ manual - - manual - manual diff --git a/cocos/scripting/javascript/bindings/spidermonkey_specifics.h b/cocos/scripting/javascript/bindings/spidermonkey_specifics.h index be9c709c49..e526ad7e7a 100644 --- a/cocos/scripting/javascript/bindings/spidermonkey_specifics.h +++ b/cocos/scripting/javascript/bindings/spidermonkey_specifics.h @@ -3,6 +3,7 @@ #include "jsapi.h" #include "uthash.h" +#include typedef struct js_proxy { void *ptr; @@ -14,20 +15,18 @@ extern js_proxy_t *_native_js_global_ht; extern js_proxy_t *_js_native_global_ht; typedef struct js_type_class { - uint32_t type; JSClass *jsclass; JSObject *proto; JSObject *parentProto; - UT_hash_handle hh; } js_type_class_t; -extern js_type_class_t *_js_global_type_ht; +extern std::unordered_map _js_global_type_map; template< typename DERIVED > class TypeTest { public: - static int s_id() + static long s_id() { // return id unique for DERIVED // NOT SURE IT WILL BE REALLY UNIQUE FOR EACH CLASS!! diff --git a/cocos/scripting/javascript/script/jsb_deprecated.js b/cocos/scripting/javascript/script/jsb_deprecated.js index 2c7a7b1ed1..cf2065152f 100644 --- a/cocos/scripting/javascript/script/jsb_deprecated.js +++ b/cocos/scripting/javascript/script/jsb_deprecated.js @@ -14,6 +14,10 @@ var cc = cc || {}; cc.AnimationCache.destroyInstance(); }; + cc.TextureCache.getInstance = function() { + return cc.Director.getInstance().getTextureCache(); + }; + // Deprecated member functions cc.Action.prototype.copy = function() { logW("cc.Action.copy", "cc.Action.clone"); diff --git a/cocos/scripting/lua/bindings/Android.mk b/cocos/scripting/lua/bindings/Android.mk index b39ee5f6a5..f198157af9 100644 --- a/cocos/scripting/lua/bindings/Android.mk +++ b/cocos/scripting/lua/bindings/Android.mk @@ -17,6 +17,7 @@ LOCAL_SRC_FILES := CCLuaBridge.cpp \ LuaBasicConversions.cpp \ ../../auto-generated/lua-bindings/lua_cocos2dx_auto.cpp \ ../../auto-generated/lua-bindings/lua_cocos2dx_extension_auto.cpp \ + ../../auto-generated/lua-bindings/lua_cocos2dx_studio_auto.cpp \ lua_cocos2dx_manual.cpp \ lua_cocos2dx_extension_manual.cpp \ lua_cocos2dx_deprecated.cpp \ diff --git a/cocos/scripting/lua/bindings/CCLuaStack.cpp b/cocos/scripting/lua/bindings/CCLuaStack.cpp index bad774b677..a0269bf318 100644 --- a/cocos/scripting/lua/bindings/CCLuaStack.cpp +++ b/cocos/scripting/lua/bindings/CCLuaStack.cpp @@ -54,6 +54,7 @@ extern "C" { #include "lua_cocos2dx_extension_manual.h" #include "lua_cocos2dx_deprecated.h" #include "lua_xml_http_request.h" +#include "lua_cocos2dx_studio_auto.hpp" namespace { int lua_print(lua_State * luastate) @@ -135,6 +136,7 @@ bool LuaStack::init(void) register_all_cocos2dx_deprecated(_state); register_cocos2dx_extension_CCBProxy(_state); tolua_opengl_open(_state); + register_all_cocos2dx_studio(_state); register_all_cocos2dx_manual(_state); register_all_cocos2dx_extension_manual(_state); register_all_cocos2dx_manual_deprecated(_state); diff --git a/cocos/scripting/lua/bindings/Cocos2dxLuaLoader.cpp b/cocos/scripting/lua/bindings/Cocos2dxLuaLoader.cpp index a3ae0474d8..69967031a8 100644 --- a/cocos/scripting/lua/bindings/Cocos2dxLuaLoader.cpp +++ b/cocos/scripting/lua/bindings/Cocos2dxLuaLoader.cpp @@ -46,7 +46,7 @@ extern "C" } filename.append(".lua"); - unsigned long codeBufferSize = 0; + long codeBufferSize = 0; unsigned char* codeBuffer = FileUtils::getInstance()->getFileData(filename.c_str(), "rb", &codeBufferSize); if (codeBuffer) diff --git a/cocos/scripting/lua/bindings/LuaBasicConversions.cpp b/cocos/scripting/lua/bindings/LuaBasicConversions.cpp index 1914d3a930..4c91daa42b 100644 --- a/cocos/scripting/lua/bindings/LuaBasicConversions.cpp +++ b/cocos/scripting/lua/bindings/LuaBasicConversions.cpp @@ -283,6 +283,30 @@ bool luaval_to_point(lua_State* L,int lo,Point* outValue) return ok; } +bool luaval_to_long(lua_State* L,int lo, long* outValue) +{ + if (NULL == L || NULL == outValue) + return false; + + bool ok = true; + + tolua_Error tolua_err; + if (!tolua_isnumber(L,lo,0,&tolua_err)) + { +#if COCOS2D_DEBUG >=1 + luaval_to_native_err(L,"#ferror:",&tolua_err); +#endif + ok = false; + } + + if (ok) + { + *outValue = (long)tolua_tonumber(L, lo, 0); + } + + return ok; +} + bool luaval_to_size(lua_State* L,int lo,Size* outValue) { if (NULL == L || NULL == outValue) diff --git a/cocos/scripting/lua/bindings/LuaBasicConversions.h b/cocos/scripting/lua/bindings/LuaBasicConversions.h index 20167170df..2e2e525993 100644 --- a/cocos/scripting/lua/bindings/LuaBasicConversions.h +++ b/cocos/scripting/lua/bindings/LuaBasicConversions.h @@ -30,6 +30,7 @@ extern bool luaval_to_boolean(lua_State* L,int lo,bool* outValue); extern bool luaval_to_number(lua_State* L,int lo,double* outValue); extern bool luaval_to_long_long(lua_State* L,int lo,long long* outValue); extern bool luaval_to_std_string(lua_State* L, int lo, std::string* outValue); +extern bool luaval_to_long(lua_State* L,int lo, long* outValue); extern bool luaval_to_point(lua_State* L,int lo,Point* outValue); extern bool luaval_to_size(lua_State* L,int lo,Size* outValue); diff --git a/cocos/scripting/lua/bindings/Makefile b/cocos/scripting/lua/bindings/Makefile deleted file mode 100644 index c797ce3b9e..0000000000 --- a/cocos/scripting/lua/bindings/Makefile +++ /dev/null @@ -1,93 +0,0 @@ -TARGET = liblua.so - -INCLUDES += -I../../../../external/lua/tolua \ --I../../../../external/lua/lua \ --I../../auto-generated/lua-bindings \ --I../../../../extensions \ --I../../../editor-support \ --I. \ --I../../../editor-support/cocosbuilder \ --I../../../editor-support/cocostudio \ --I../../../../external \ --I../../../ - -SOURCES = ../../../../external/lua/lua/lapi.c \ - ../../../../external/lua/lua/lauxlib.c \ - ../../../../external/lua/lua/lbaselib.c \ - ../../../../external/lua/lua/lcode.c \ - ../../../../external/lua/lua/ldblib.c \ - ../../../../external/lua/lua/ldebug.c \ - ../../../../external/lua/lua/ldo.c \ - ../../../../external/lua/lua/ldump.c \ - ../../../../external/lua/lua/lfunc.c \ - ../../../../external/lua/lua/lgc.c \ - ../../../../external/lua/lua/linit.c \ - ../../../../external/lua/lua/liolib.c \ - ../../../../external/lua/lua/llex.c \ - ../../../../external/lua/lua/lmathlib.c \ - ../../../../external/lua/lua/lmem.c \ - ../../../../external/lua/lua/loadlib.c \ - ../../../../external/lua/lua/lobject.c \ - ../../../../external/lua/lua/lopcodes.c \ - ../../../../external/lua/lua/loslib.c \ - ../../../../external/lua/lua/lparser.c \ - ../../../../external/lua/lua/lstate.c \ - ../../../../external/lua/lua/lstring.c \ - ../../../../external/lua/lua/lstrlib.c \ - ../../../../external/lua/lua/ltable.c \ - ../../../../external/lua/lua/ltablib.c \ - ../../../../external/lua/lua/ltm.c \ - ../../../../external/lua/lua/lundump.c \ - ../../../../external/lua/lua/lvm.c \ - ../../../../external/lua/lua/lzio.c \ - ../../../../external/lua/lua/print.c \ - ../../../../external/lua/tolua/tolua_event.c \ - ../../../../external/lua/tolua/tolua_is.c \ - ../../../../external/lua/tolua/tolua_map.c \ - ../../../../external/lua/tolua/tolua_push.c \ - ../../../../external/lua/tolua/tolua_to.c \ - tolua_fix.c \ - ../../auto-generated/lua-bindings/lua_cocos2dx_auto.cpp \ - ../../auto-generated/lua-bindings/lua_cocos2dx_extension_auto.cpp \ - CCLuaBridge.cpp \ - CCLuaEngine.cpp \ - CCLuaStack.cpp \ - CCLuaValue.cpp \ - Cocos2dxLuaLoader.cpp \ - CCBProxy.cpp \ - LuaOpengl.cpp \ - LuaScriptHandlerMgr.cpp \ - LuaBasicConversions.cpp \ - lua_cocos2dx_manual.cpp \ - lua_cocos2dx_extension_manual.cpp \ - lua_cocos2dx_deprecated.cpp \ - lua_xml_http_request.cpp - - -include ../../../2d/cocos2dx.mk - -TARGET := $(LIB_DIR)/$(TARGET) -SHAREDLIBS += -lextension -lcocostudio -lcocosbuilder -STATICLIBS += $(LIB_DIR)/libbox2d.a - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_LINK)$(CXX) $(CXXFLAGS) $(OBJECTS) -shared -o $@ $(SHAREDLIBS) $(STATICLIBS) - -$(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 $@ diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp index 7e5a38abb1..39083ae1e3 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp @@ -51,8 +51,8 @@ static int tolua_cocos2d_MenuItemImage_create(lua_State* tolua_S) ok = true; break; } - const char* normalImage = ((const char*) tolua_tostring(tolua_S,2,0)); - const char* selectedImage = ((const char*) tolua_tostring(tolua_S,3,0)); + const std::string normalImage = ((const std::string) tolua_tocppstring(tolua_S,2,0)); + const std::string selectedImage = ((const std::string) tolua_tocppstring(tolua_S,3,0)); MenuItemImage* tolua_ret = (MenuItemImage*) MenuItemImage::create(normalImage,selectedImage); int nID = (tolua_ret) ? (int)tolua_ret->_ID : -1; int* pLuaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; @@ -70,9 +70,9 @@ static int tolua_cocos2d_MenuItemImage_create(lua_State* tolua_S) break; } #endif - const char* normalImage = ((const char*) tolua_tostring(tolua_S,2,0)); - const char* selectedImage = ((const char*) tolua_tostring(tolua_S,3,0)); - const char* disabledImage = ((const char*) tolua_tostring(tolua_S,4,0)); + const std::string normalImage = ((const std::string) tolua_tocppstring(tolua_S,2,0)); + const std::string selectedImage = ((const std::string) tolua_tocppstring(tolua_S,3,0)); + const std::string disabledImage = ((const std::string) tolua_tocppstring(tolua_S,4,0)); MenuItemImage* tolua_ret = (MenuItemImage*) MenuItemImage::create(normalImage,selectedImage,disabledImage); int nID = (tolua_ret) ? (int)tolua_ret->_ID : -1; @@ -155,7 +155,7 @@ static int tolua_cocos2d_MenuItemFont_create(lua_State* tolua_S) goto tolua_lerror; } #endif - const char* value = ((const char*) tolua_tostring(tolua_S,2,0)); + const std::string value = ((const std::string) tolua_tocppstring(tolua_S,2,0)); MenuItemFont* tolua_ret = (MenuItemFont*) MenuItemFont::create(value); int nID = (tolua_ret) ? (int)tolua_ret->_ID : -1; int* pLuaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; diff --git a/cocos/scripting/lua/bindings/tolua_fix.c b/cocos/scripting/lua/bindings/tolua_fix.c index 870db00d75..f03dd59b5f 100644 --- a/cocos/scripting/lua/bindings/tolua_fix.c +++ b/cocos/scripting/lua/bindings/tolua_fix.c @@ -9,7 +9,7 @@ TOLUA_API void toluafix_open(lua_State* L) lua_pushstring(L, TOLUA_REFID_PTR_MAPPING); lua_newtable(L); lua_rawset(L, LUA_REGISTRYINDEX); - + lua_pushstring(L, TOLUA_REFID_TYPE_MAPPING); lua_newtable(L); lua_rawset(L, LUA_REGISTRYINDEX); @@ -30,29 +30,29 @@ TOLUA_API int toluafix_pushusertype_ccobject(lua_State* L, lua_pushnil(L); return -1; } - + if (*p_refid == 0) { *p_refid = refid; - + lua_pushstring(L, TOLUA_REFID_PTR_MAPPING); lua_rawget(L, LUA_REGISTRYINDEX); /* stack: refid_ptr */ lua_pushinteger(L, refid); /* stack: refid_ptr refid */ lua_pushlightuserdata(L, ptr); /* stack: refid_ptr refid ptr */ - + lua_rawset(L, -3); /* refid_ptr[refid] = ptr, stack: refid_ptr */ lua_pop(L, 1); /* stack: - */ - + lua_pushstring(L, TOLUA_REFID_TYPE_MAPPING); lua_rawget(L, LUA_REGISTRYINDEX); /* stack: refid_type */ lua_pushinteger(L, refid); /* stack: refid_type refid */ lua_pushstring(L, type); /* stack: refid_type refid type */ lua_rawset(L, -3); /* refid_type[refid] = type, stack: refid_type */ lua_pop(L, 1); /* stack: - */ - + //printf("[LUA] push CCObject OK - refid: %d, ptr: %x, type: %s\n", *p_refid, (int)ptr, type); } - + tolua_pushusertype(L, ptr, type); return 0; } @@ -63,7 +63,7 @@ TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) const char* type = NULL; void** ud = NULL; if (refid == 0) return -1; - + // get ptr from tolua_refid_ptr_mapping lua_pushstring(L, TOLUA_REFID_PTR_MAPPING); lua_rawget(L, LUA_REGISTRYINDEX); /* stack: refid_ptr */ @@ -78,14 +78,14 @@ TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) // printf("[LUA ERROR] remove CCObject with NULL ptr, refid: %d\n", refid); return -2; } - + // remove ptr from tolua_refid_ptr_mapping lua_pushinteger(L, refid); /* stack: refid_ptr refid */ lua_pushnil(L); /* stack: refid_ptr refid nil */ lua_rawset(L, -3); /* delete refid_ptr[refid], stack: refid_ptr */ lua_pop(L, 1); /* stack: - */ - - + + // get type from tolua_refid_type_mapping lua_pushstring(L, TOLUA_REFID_TYPE_MAPPING); lua_rawget(L, LUA_REGISTRYINDEX); /* stack: refid_type */ @@ -97,16 +97,16 @@ TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) printf("[LUA ERROR] remove CCObject with NULL type, refid: %d, ptr: %p\n", refid, ptr); return -1; } - + type = lua_tostring(L, -1); lua_pop(L, 1); /* stack: refid_type */ - + // remove type from tolua_refid_type_mapping lua_pushinteger(L, refid); /* stack: refid_type refid */ lua_pushnil(L); /* stack: refid_type refid nil */ lua_rawset(L, -3); /* delete refid_type[refid], stack: refid_type */ lua_pop(L, 1); /* stack: - */ - + // get ubox luaL_getmetatable(L, type); /* stack: mt */ lua_pushstring(L, "tolua_ubox"); /* stack: mt key */ @@ -118,7 +118,7 @@ TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) lua_pushstring(L, "tolua_ubox"); /* stack: mt key */ lua_rawget(L, LUA_REGISTRYINDEX); /* stack: mt ubox */ }; - + lua_pushlightuserdata(L, ptr); /* stack: mt ubox ptr */ lua_rawget(L,-2); /* stack: mt ubox ud */ if (lua_isnil(L, -1)) @@ -128,7 +128,11 @@ TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) lua_pop(L, 3); return -3; } - + + // cleanup peertable + lua_pushvalue(L, LUA_REGISTRYINDEX); + lua_setfenv(L, -2); + ud = (void**)lua_touserdata(L, -1); lua_pop(L, 1); /* stack: mt ubox */ if (ud == NULL) @@ -137,14 +141,14 @@ TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) lua_pop(L, 2); return -1; } - + // clean userdata *ud = NULL; - + lua_pushlightuserdata(L, ptr); /* stack: mt ubox ptr */ lua_pushnil(L); /* stack: mt ubox ptr nil */ lua_rawset(L, -3); /* ubox[ptr] = nil, stack: mt ubox */ - + lua_pop(L, 2); //printf("[LUA] remove CCObject, refid: %d, ptr: %x, type: %s\n", refid, (int)ptr, type); return 0; @@ -154,19 +158,19 @@ TOLUA_API int toluafix_ref_function(lua_State* L, int lo, int def) { // function at lo if (!lua_isfunction(L, lo)) return 0; - + s_function_ref_id++; - + lua_pushstring(L, TOLUA_REFID_FUNCTION_MAPPING); lua_rawget(L, LUA_REGISTRYINDEX); /* stack: fun ... refid_fun */ lua_pushinteger(L, s_function_ref_id); /* stack: fun ... refid_fun refid */ lua_pushvalue(L, lo); /* stack: fun ... refid_fun refid fun */ - + lua_rawset(L, -3); /* refid_fun[refid] = fun, stack: fun ... refid_ptr */ lua_pop(L, 1); /* stack: fun ... */ - + return s_function_ref_id; - + // lua_pushvalue(L, lo); /* stack: ... func */ // return luaL_ref(L, LUA_REGISTRYINDEX); } diff --git a/cocos/scripting/lua/script/json.lua b/cocos/scripting/lua/script/json.lua old mode 100755 new mode 100644 diff --git a/docs/CODING_STYLE.md b/docs/CODING_STYLE.md deleted file mode 100644 index 4b7bf2a7c8..0000000000 --- a/docs/CODING_STYLE.md +++ /dev/null @@ -1,131 +0,0 @@ -# cocos2d-x C++ coding sytle - - -## Detailed information - -Please, refer to this document for a detailed version of the cocos2d-x C++ coding sytle: - -* [cocos2d-x c++ coding style](http://www.cocos2d-x.org/wiki/Cocos2d_c++_coding_style) - - -## Quick Sample - -Use this sample as a quick reference. But DO READ the detailed doc for more info. - -Header file: - -```c++ -/** - * We use Doxygen strings for documentation. - * All public classes, methods, structs should be documented using Doxygen Strings - */ -class CC_DLL Sprite : public NodeRGBA, public TextureProtocol -{ /* class braces start in a new line */ - -/* no indentation here for public, protected or private */ -/* First add all the "public" stuff, then all the "protected" stuff, and finally all the "private" stuff -public: - - /* we don't use tabs, we use spaces, and we use a 4 space identation */ - /* 1st add all static const */ - static const int INDEX_NOT_INITIALIZED = -1; - - /* then add all the creators and other relevant static methods */ - static Sprite* create(); - static Sprite* create(const char *filename); - static Sprite* create(const char *filename, const Rect& rect); - - /* if applicable, then add the consturctors / destructors */ - Sprite(); - virtual ~Sprite(void); - - /* then add all the initialization methods */ - /* notice that they are in the same order as the creators */ - virtual bool init(void); - virtual bool initWithTexture(Texture2D *texture); - virtual bool initWithTexture(Texture2D *texture, const Rect& rect); - - - - /* then add the regular instace methods */ - virtual void updateTransform(void); - virtual SpriteBatchNode* getBatchNode(void); - virtual void setBatchNode(SpriteBatchNode *spriteBatchNode); - - - /* then add all the overriden methods */ - /* notice that all overriden methods must use the 'override' keyword */ - /* overriden methods are not forced to have doxygen strings UNLESS they change the behavior in a non obvios way */ - virtual void setPosition(const Point& pos) override; - virtual void setRotation(float rotation) override; - virtual void setRotationX(float rotationX) override; - - - /* once you finish with the 'public' methods, start with the 'protected' ones */ -protected: - - /* protected methods are not forced to have Doxygen strings, but if they have it, better */ - void updateColor(void); - virtual void setTextureCoords(Rect rect); - - /* After adding all the methods, add the ivars */ - /* all ivars must start with _ */ - /* Do not use Hungarian notation */ - TextureAtlas* _textureAtlas; - int _atlasIndex; - SpriteBatchNode* _batchNode; -}; - -``` - -Implementation file: - -```c++ -/* Do not use doxygen comments on the implementation file */ - -/* The methos MUST be in the same order as where declared in the header file */ - -Sprite* Sprite::create(const char *filename) -{ - /* Don't use tabs. Use spaces. Use 4-space indentation */ - Sprite *sprite = new Sprite(); - - /* put curly braces in the same line as in the 'if'*/ - /* leave a space between the 'if' and the '(' */ - /* don't leave spaces between '()' */ - if (sprite && sprite->initWithFile(filename)) { - sprite->autorelease(); - return sprite; - } - CC_SAFE_DELETE(sprite); - return NULL; -} - -/* Initialization list can be indented to 0 spaces, or to 4 spaces. If in doubt, be consistent with the indentation already used in the file */ -/* Only use the Initialization lists for types that can't fail when initialized */ -Sprite::Sprite() -: _shouldBeHidden(false) -, _texture(nullptr) -, _physicsBody(nullptr) -{ -} - -/* use the 'initXXX' methods to initialize types that might fail */ -bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect, bool rotated) -{ - /* it ok not use use curly braces */ - if (something) - do_something(); - else - something_else(); - - /* but if you use curly branches in one branch, all the branches should use curly branches */ - if (something) { - do_something1(); - do_something2(); - } else { - so_something_else(); - } -} - -``` diff --git a/docs/CODING_STYLE.md.REMOVED.git-id b/docs/CODING_STYLE.md.REMOVED.git-id new file mode 100644 index 0000000000..2a00974e4b --- /dev/null +++ b/docs/CODING_STYLE.md.REMOVED.git-id @@ -0,0 +1 @@ +f86eb12e6d4835f93bd6f59d860970bcd2f74128 \ No newline at end of file diff --git a/extensions/CMakeLists.txt b/extensions/CMakeLists.txt new file mode 100644 index 0000000000..176cd831ce --- /dev/null +++ b/extensions/CMakeLists.txt @@ -0,0 +1,41 @@ +set(EXTENSIONS_SRC + assets-manager/AssetsManager.cpp + GUI/CCControlExtension/CCControl.cpp + GUI/CCControlExtension/CCControlButton.cpp + GUI/CCControlExtension/CCControlColourPicker.cpp + GUI/CCControlExtension/CCControlHuePicker.cpp + GUI/CCControlExtension/CCControlPotentiometer.cpp + GUI/CCControlExtension/CCControlSaturationBrightnessPicker.cpp + GUI/CCControlExtension/CCControlSlider.cpp + GUI/CCControlExtension/CCControlStepper.cpp + GUI/CCControlExtension/CCControlSwitch.cpp + GUI/CCControlExtension/CCControlUtils.cpp + GUI/CCControlExtension/CCInvocation.cpp + GUI/CCControlExtension/CCScale9Sprite.cpp + GUI/CCEditBox/CCEditBox.cpp + GUI/CCEditBox/CCEditBoxImplAndroid.cpp + GUI/CCEditBox/CCEditBoxImplNone.cpp + GUI/CCEditBox/CCEditBoxImplTizen.cpp + GUI/CCEditBox/CCEditBoxImplWin.cpp + GUI/CCScrollView/CCScrollView.cpp + GUI/CCScrollView/CCSorting.cpp + GUI/CCScrollView/CCTableView.cpp + GUI/CCScrollView/CCTableViewCell.cpp + physics-nodes/CCPhysicsDebugNode.cpp + physics-nodes/CCPhysicsSprite.cpp +) + +include_directories( + .. +) + +add_library(extensions STATIC + ${EXTENSIONS_SRC} +) + +set_target_properties(extensions + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/extensions/GUI/CCControlExtension/CCControl.cpp b/extensions/GUI/CCControlExtension/CCControl.cpp index 13d86e629c..15fe7b1a8d 100644 --- a/extensions/GUI/CCControlExtension/CCControl.cpp +++ b/extensions/GUI/CCControlExtension/CCControl.cpp @@ -326,4 +326,9 @@ bool Control::hasVisibleParents() const } return true; } + +Control::EventType operator|(Control::EventType a, Control::EventType b) { + return static_cast(static_cast(a) | static_cast(b)); +} + NS_CC_EXT_END diff --git a/extensions/GUI/CCControlExtension/CCControl.h b/extensions/GUI/CCControlExtension/CCControl.h index d8644a516f..12533f7041 100644 --- a/extensions/GUI/CCControlExtension/CCControl.h +++ b/extensions/GUI/CCControlExtension/CCControl.h @@ -262,6 +262,8 @@ protected: CC_SYNTHESIZE_READONLY(State, _state, State); }; +Control::EventType operator|(Control::EventType a, Control::EventType b); + // end of GUI group /// @} /// @} diff --git a/extensions/GUI/CCControlExtension/CCControlButton.cpp b/extensions/GUI/CCControlExtension/CCControlButton.cpp index 5e4e102aba..e747dfe24c 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.cpp +++ b/extensions/GUI/CCControlExtension/CCControlButton.cpp @@ -404,7 +404,7 @@ const char * ControlButton::getTitleTTFForState(State state) LabelTTF* labelTTF = dynamic_cast(label); if(labelTTF != 0) { - return labelTTF->getFontName(); + return labelTTF->getFontName().c_str(); } else { diff --git a/extensions/GUI/CCScrollView/CCSorting.cpp b/extensions/GUI/CCScrollView/CCSorting.cpp index fd9d80f32c..412aa157e1 100644 --- a/extensions/GUI/CCScrollView/CCSorting.cpp +++ b/extensions/GUI/CCScrollView/CCSorting.cpp @@ -33,7 +33,7 @@ class SortedObject : public Object, public SortableObject { public: SortedObject() : objectID(0) {} - virtual void setObjectID(unsigned int objectID) { this->objectID = objectID; } + virtual void setObjectID(unsigned int id) { this->objectID = id; } virtual unsigned int getObjectID() { return objectID; } private: unsigned int objectID; diff --git a/extensions/assets-manager/AssetsManager.cpp b/extensions/assets-manager/AssetsManager.cpp index 31795c4f39..4913e5efd0 100644 --- a/extensions/assets-manager/AssetsManager.cpp +++ b/extensions/assets-manager/AssetsManager.cpp @@ -651,8 +651,8 @@ AssetsManager* AssetsManager::create(const char* packageUrl, const char* version class DelegateProtocolImpl : public AssetsManagerDelegateProtocol { public : - DelegateProtocolImpl(ErrorCallback errorCallback, ProgressCallback progressCallback, SuccessCallback successCallback) - : errorCallback(errorCallback), progressCallback(progressCallback), successCallback(successCallback) + DelegateProtocolImpl(ErrorCallback aErrorCallback, ProgressCallback aProgressCallback, SuccessCallback aSuccessCallback) + : errorCallback(aErrorCallback), progressCallback(aProgressCallback), successCallback(aSuccessCallback) {} virtual void onError(AssetsManager::ErrorCode errorCode) { errorCallback(int(errorCode)); } diff --git a/extensions/assets-manager/AssetsManager.h b/extensions/assets-manager/AssetsManager.h index 80f0ae5d81..f3e413f4bd 100644 --- a/extensions/assets-manager/AssetsManager.h +++ b/extensions/assets-manager/AssetsManager.h @@ -145,7 +145,7 @@ public: * @js NA * @lua NA */ - AssetsManagerDelegateProtocol* getDelegate() { return _delegate ;} + AssetsManagerDelegateProtocol* getDelegate() const { return _delegate ;} /** @brief Sets connection time out in seconds */ diff --git a/extensions/proj.linux/.cproject b/extensions/proj.linux/.cproject deleted file mode 100644 index 696f0898ce..0000000000 --- a/extensions/proj.linux/.cproject +++ /dev/null @@ -1,404 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/extensions/proj.linux/.project b/extensions/proj.linux/.project deleted file mode 100644 index 37e93964dd..0000000000 --- a/extensions/proj.linux/.project +++ /dev/null @@ -1,90 +0,0 @@ - - - libextension - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - clean,full,incremental, - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - CCBReader - 2 - PARENT-1-PROJECT_LOC/CCBReader - - - CCArmature - 2 - PARENT-1-PROJECT_LOC/CCArmature - - - Components - 2 - PARENT-1-PROJECT_LOC/Components - - - spine - 2 - PARENT-1-PROJECT_LOC/spine - - - ExtensionMacros.h - 1 - PARENT-1-PROJECT_LOC/ExtensionMacros.h - - - GUI - 2 - PARENT-1-PROJECT_LOC/GUI - - - LocalStorage - 2 - PARENT-1-PROJECT_LOC/LocalStorage - - - cocos-ext.h - 1 - PARENT-1-PROJECT_LOC/cocos-ext.h - - - network - 2 - PARENT-1-PROJECT_LOC/network - - - physics_nodes - 2 - PARENT-1-PROJECT_LOC/physics_nodes - - - - - 1373359750543 - - 22 - - org.eclipse.ui.ide.multiFilter - 1.0-name-matches-false-false-WebSocket.* - - - - diff --git a/extensions/proj.linux/Makefile b/extensions/proj.linux/Makefile deleted file mode 100644 index fe07e988e5..0000000000 --- a/extensions/proj.linux/Makefile +++ /dev/null @@ -1,49 +0,0 @@ -TARGET = libextension.a - -INCLUDES = -I.. - -SOURCES = \ -assets-manager/AssetsManager.cpp \ -GUI/CCControlExtension/CCControl.cpp \ -GUI/CCControlExtension/CCControlButton.cpp \ -GUI/CCControlExtension/CCControlColourPicker.cpp \ -GUI/CCControlExtension/CCControlHuePicker.cpp \ -GUI/CCControlExtension/CCControlPotentiometer.cpp \ -GUI/CCControlExtension/CCControlSaturationBrightnessPicker.cpp \ -GUI/CCControlExtension/CCControlSlider.cpp \ -GUI/CCControlExtension/CCControlStepper.cpp \ -GUI/CCControlExtension/CCControlSwitch.cpp \ -GUI/CCControlExtension/CCControlUtils.cpp \ -GUI/CCControlExtension/CCInvocation.cpp \ -GUI/CCControlExtension/CCScale9Sprite.cpp \ -GUI/CCEditBox/CCEditBox.cpp \ -GUI/CCEditBox/CCEditBoxImplAndroid.cpp \ -GUI/CCEditBox/CCEditBoxImplNone.cpp \ -GUI/CCEditBox/CCEditBoxImplTizen.cpp \ -GUI/CCEditBox/CCEditBoxImplWin.cpp \ -GUI/CCScrollView/CCScrollView.cpp \ -GUI/CCScrollView/CCSorting.cpp \ -GUI/CCScrollView/CCTableView.cpp \ -GUI/CCScrollView/CCTableViewCell.cpp \ -physics-nodes/CCPhysicsDebugNode.cpp \ -physics-nodes/CCPhysicsSprite.cpp - -include ../../cocos/2d/cocos2dx.mk - -CXXFLAGS += -Wno-multichar -Wno-unused-result - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) - -$(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 $@ diff --git a/external/Box2D/CMakeLists.txt b/external/Box2D/CMakeLists.txt new file mode 100644 index 0000000000..fd1f63dc64 --- /dev/null +++ b/external/Box2D/CMakeLists.txt @@ -0,0 +1,61 @@ +set(BOX2D_SRC + Collision/Shapes/b2ChainShape.cpp + Collision/Shapes/b2CircleShape.cpp + Collision/Shapes/b2EdgeShape.cpp + Collision/Shapes/b2PolygonShape.cpp + Collision/b2BroadPhase.cpp + Collision/b2CollideCircle.cpp + Collision/b2CollideEdge.cpp + Collision/b2CollidePolygon.cpp + Collision/b2Collision.cpp + Collision/b2Distance.cpp + Collision/b2DynamicTree.cpp + Collision/b2TimeOfImpact.cpp + Common/b2BlockAllocator.cpp + Common/b2Draw.cpp + Common/b2Math.cpp + Common/b2Settings.cpp + Common/b2StackAllocator.cpp + Common/b2Timer.cpp + Dynamics/Contacts/b2ChainAndCircleContact.cpp + Dynamics/Contacts/b2ChainAndPolygonContact.cpp + Dynamics/Contacts/b2CircleContact.cpp + Dynamics/Contacts/b2Contact.cpp + Dynamics/Contacts/b2ContactSolver.cpp + Dynamics/Contacts/b2EdgeAndCircleContact.cpp + Dynamics/Contacts/b2EdgeAndPolygonContact.cpp + Dynamics/Contacts/b2PolygonAndCircleContact.cpp + Dynamics/Contacts/b2PolygonContact.cpp + Dynamics/Joints/b2DistanceJoint.cpp + Dynamics/Joints/b2FrictionJoint.cpp + Dynamics/Joints/b2GearJoint.cpp + Dynamics/Joints/b2Joint.cpp + Dynamics/Joints/b2MouseJoint.cpp + Dynamics/Joints/b2PrismaticJoint.cpp + Dynamics/Joints/b2PulleyJoint.cpp + Dynamics/Joints/b2RevoluteJoint.cpp + Dynamics/Joints/b2RopeJoint.cpp + Dynamics/Joints/b2WeldJoint.cpp + Dynamics/Joints/b2WheelJoint.cpp + Dynamics/b2Body.cpp + Dynamics/b2ContactManager.cpp + Dynamics/b2Fixture.cpp + Dynamics/b2Island.cpp + Dynamics/b2World.cpp + Dynamics/b2WorldCallbacks.cpp + Rope/b2Rope.cpp +) + +include_directories( + .. +) + +add_library(box2d STATIC + ${BOX2D_SRC} +) + +set_target_properties(box2d + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) diff --git a/external/Box2D/proj.linux/.cproject b/external/Box2D/proj.linux/.cproject deleted file mode 100644 index 5aa092cac3..0000000000 --- a/external/Box2D/proj.linux/.cproject +++ /dev/null @@ -1,267 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/external/Box2D/proj.linux/.project b/external/Box2D/proj.linux/.project deleted file mode 100644 index 164d50f52a..0000000000 --- a/external/Box2D/proj.linux/.project +++ /dev/null @@ -1,110 +0,0 @@ - - - libBox2D - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - clean,full,incremental, - - - ?name? - - - - org.eclipse.cdt.make.core.append_environment - true - - - org.eclipse.cdt.make.core.autoBuildTarget - all - - - org.eclipse.cdt.make.core.buildArguments - - - - org.eclipse.cdt.make.core.buildCommand - make - - - org.eclipse.cdt.make.core.buildLocation - ${workspace_loc:/libBox2D/Debug} - - - org.eclipse.cdt.make.core.cleanBuildTarget - clean - - - org.eclipse.cdt.make.core.contents - org.eclipse.cdt.make.core.activeConfigSettings - - - org.eclipse.cdt.make.core.enableAutoBuild - false - - - org.eclipse.cdt.make.core.enableCleanBuild - true - - - org.eclipse.cdt.make.core.enableFullBuild - true - - - org.eclipse.cdt.make.core.fullBuildTarget - all - - - org.eclipse.cdt.make.core.stopOnError - true - - - org.eclipse.cdt.make.core.useDefaultBuildCmd - true - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - Box2D.h - 1 - PARENT-1-PROJECT_LOC/Box2D.h - - - Collision - 2 - PARENT-1-PROJECT_LOC/Collision - - - Common - 2 - PARENT-1-PROJECT_LOC/Common - - - Dynamics - 2 - PARENT-1-PROJECT_LOC/Dynamics - - - Rope - 2 - PARENT-1-PROJECT_LOC/Rope - - - diff --git a/external/Box2D/proj.linux/Makefile b/external/Box2D/proj.linux/Makefile deleted file mode 100644 index b43814ccef..0000000000 --- a/external/Box2D/proj.linux/Makefile +++ /dev/null @@ -1,72 +0,0 @@ -TARGET = libbox2d.a - -SOURCES = ../Collision/Shapes/b2ChainShape.cpp \ -../Collision/Shapes/b2CircleShape.cpp \ -../Collision/Shapes/b2EdgeShape.cpp \ -../Collision/Shapes/b2PolygonShape.cpp \ -../Collision/b2BroadPhase.cpp \ -../Collision/b2CollideCircle.cpp \ -../Collision/b2CollideEdge.cpp \ -../Collision/b2CollidePolygon.cpp \ -../Collision/b2Collision.cpp \ -../Collision/b2Distance.cpp \ -../Collision/b2DynamicTree.cpp \ -../Collision/b2TimeOfImpact.cpp \ -../Common/b2BlockAllocator.cpp \ -../Common/b2Draw.cpp \ -../Common/b2Math.cpp \ -../Common/b2Settings.cpp \ -../Common/b2StackAllocator.cpp \ -../Common/b2Timer.cpp \ -../Dynamics/Contacts/b2ChainAndCircleContact.cpp \ -../Dynamics/Contacts/b2ChainAndPolygonContact.cpp \ -../Dynamics/Contacts/b2CircleContact.cpp \ -../Dynamics/Contacts/b2Contact.cpp \ -../Dynamics/Contacts/b2ContactSolver.cpp \ -../Dynamics/Contacts/b2EdgeAndCircleContact.cpp \ -../Dynamics/Contacts/b2EdgeAndPolygonContact.cpp \ -../Dynamics/Contacts/b2PolygonAndCircleContact.cpp \ -../Dynamics/Contacts/b2PolygonContact.cpp \ -../Dynamics/Joints/b2DistanceJoint.cpp \ -../Dynamics/Joints/b2FrictionJoint.cpp \ -../Dynamics/Joints/b2GearJoint.cpp \ -../Dynamics/Joints/b2Joint.cpp \ -../Dynamics/Joints/b2MouseJoint.cpp \ -../Dynamics/Joints/b2PrismaticJoint.cpp \ -../Dynamics/Joints/b2PulleyJoint.cpp \ -../Dynamics/Joints/b2RevoluteJoint.cpp \ -../Dynamics/Joints/b2RopeJoint.cpp \ -../Dynamics/Joints/b2WeldJoint.cpp \ -../Dynamics/Joints/b2WheelJoint.cpp \ -../Dynamics/b2Body.cpp \ -../Dynamics/b2ContactManager.cpp \ -../Dynamics/b2Fixture.cpp \ -../Dynamics/b2Island.cpp \ -../Dynamics/b2World.cpp \ -../Dynamics/b2WorldCallbacks.cpp \ -../Rope/b2Rope.cpp - -include ../../../cocos/2d/cocos2dx.mk - -INCLUDES = -I../.. - -# Cocos2d is not responsible for warnings in external projects -CXXFLAGS += -w - -ifeq ($(DEBUG), 1) -DEFINES = -D_DEBUG -else -DEFINES = -endif - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $(TARGET) $(OBJECTS) - -$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/external/Box2D/proj.linux/box2d.prf b/external/Box2D/proj.linux/box2d.prf deleted file mode 100644 index 434ad88406..0000000000 --- a/external/Box2D/proj.linux/box2d.prf +++ /dev/null @@ -1,19 +0,0 @@ -################################################################################ -# Do not include this file in your project: see cocos2dx.pri. -################################################################################ - -linux { - # We will compile box2d on demand using Makefile. - build_box2d.name = Build box2d static library - build_box2d.input = $$PWD/Makefile - build_box2d.output = $$CC_LIBRARY_DIR/libbox2d.a - build_box2d.target = $$CC_LIBRARY_DIR/libbox2d.a - build_box2d.CONFIG = no_link target_predeps - build_box2d.commands = cd $$PWD && make $$CC_MAKE_FLAGS - - QMAKE_EXTRA_COMPILERS += build_box2d - QMAKE_EXTRA_TARGETS += build_box2d - - PRE_TARGETDEPS += $$CC_LIBRARY_DIR/libbox2d.a - LIBS += -Wl,-Bstatic -lbox2d -Wl,-Bdynamic -} diff --git a/external/chipmunk/proj.linux/.cproject b/external/chipmunk/proj.linux/.cproject deleted file mode 100644 index 18467c15ca..0000000000 --- a/external/chipmunk/proj.linux/.cproject +++ /dev/null @@ -1,236 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/external/chipmunk/proj.linux/.project b/external/chipmunk/proj.linux/.project deleted file mode 100644 index 2f42dedf9b..0000000000 --- a/external/chipmunk/proj.linux/.project +++ /dev/null @@ -1,95 +0,0 @@ - - - libChipmunk - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - clean,full,incremental, - - - ?name? - - - - org.eclipse.cdt.make.core.append_environment - true - - - org.eclipse.cdt.make.core.autoBuildTarget - all - - - org.eclipse.cdt.make.core.buildArguments - - - - org.eclipse.cdt.make.core.buildCommand - make - - - org.eclipse.cdt.make.core.buildLocation - ${workspace_loc:/libChipmunk/Debug} - - - org.eclipse.cdt.make.core.cleanBuildTarget - clean - - - org.eclipse.cdt.make.core.contents - org.eclipse.cdt.make.core.activeConfigSettings - - - org.eclipse.cdt.make.core.enableAutoBuild - false - - - org.eclipse.cdt.make.core.enableCleanBuild - true - - - org.eclipse.cdt.make.core.enableFullBuild - true - - - org.eclipse.cdt.make.core.fullBuildTarget - all - - - org.eclipse.cdt.make.core.stopOnError - true - - - org.eclipse.cdt.make.core.useDefaultBuildCmd - true - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - include - 2 - PARENT-1-PROJECT_LOC/include - - - src - 2 - PARENT-1-PROJECT_LOC/src - - - diff --git a/external/chipmunk/proj.linux/Makefile b/external/chipmunk/proj.linux/Makefile deleted file mode 100644 index a2cb985b7c..0000000000 --- a/external/chipmunk/proj.linux/Makefile +++ /dev/null @@ -1,47 +0,0 @@ -SOURCES = ../src/chipmunk.c \ - ../src/cpBody.c \ - ../src/cpSpace.c \ - ../src/cpSpatialIndex.c \ - ../src/cpArbiter.c \ - ../src/cpCollision.c \ - ../src/cpSpaceComponent.c \ - ../src/cpSweep1D.c \ - ../src/cpArray.c \ - ../src/cpHashSet.c \ - ../src/cpSpaceHash.c \ - ../src/cpVect.c \ - ../src/cpBB.c \ - ../src/cpPolyShape.c \ - ../src/cpSpaceQuery.c \ - ../src/cpBBTree.c \ - ../src/cpShape.c \ - ../src/cpSpaceStep.c \ - ../src/constraints/cpConstraint.c \ - ../src/constraints/cpPivotJoint.c \ - ../src/constraints/cpDampedRotarySpring.c \ - ../src/constraints/cpRatchetJoint.c \ - ../src/constraints/cpDampedSpring.c \ - ../src/constraints/cpRotaryLimitJoint.c \ - ../src/constraints/cpGearJoint.c \ - ../src/constraints/cpSimpleMotor.c \ - ../src/constraints/cpGrooveJoint.c \ - ../src/constraints/cpSlideJoint.c \ - ../src/constraints/cpPinJoint.c \ - -include ../../../cocos/2d/cocos2dx.mk - -TARGET = $(LIB_DIR)/libchipmunk.a -INCLUDES = -I../include/chipmunk -DEFINES = -DLINUX -CCFLAGS += -std=gnu99 -OBJECTS := $(subst src/,,$(OBJECTS)) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $(TARGET) $(OBJECTS) - -$(OBJ_DIR)/%.o: ../src/%.c $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/external/chipmunk/proj.linux/chipmunk.prf b/external/chipmunk/proj.linux/chipmunk.prf deleted file mode 100644 index a807b0ab99..0000000000 --- a/external/chipmunk/proj.linux/chipmunk.prf +++ /dev/null @@ -1,19 +0,0 @@ -################################################################################ -# Do not include this file in your project: see cocos2dx.pri. -################################################################################ - -linux { - # We will compile chipmunk on demand using Makefile. - build_chipmunk.name = Build chipmunk static library - build_chipmunk.input = $$PWD/Makefile - build_chipmunk.output = $$CC_LIBRARY_DIR/libchipmunk.a - build_chipmunk.target = $$CC_LIBRARY_DIR/libchipmunk.a - build_chipmunk.CONFIG = no_link target_predeps - build_chipmunk.commands = cd $$PWD && make $$CC_MAKE_FLAGS - - QMAKE_EXTRA_COMPILERS += build_chipmunk - QMAKE_EXTRA_TARGETS += build_chipmunk - - PRE_TARGETDEPS += $$CC_LIBRARY_DIR/libchipmunk.a - LIBS += -Wl,-Bstatic -lchipmunk -Wl,-Bdynamic -} diff --git a/external/chipmunk/src/CMakeLists.txt b/external/chipmunk/src/CMakeLists.txt index 6f10d0177d..a0d15b7b8a 100644 --- a/external/chipmunk/src/CMakeLists.txt +++ b/external/chipmunk/src/CMakeLists.txt @@ -1,3 +1,5 @@ +set(BUILD_STATIC 1) + file(GLOB chipmunk_source_files "*.c" "constraints/*.c") file(GLOB chipmunk_public_header "${chipmunk_SOURCE_DIR}/include/chipmunk/*.h") file(GLOB chipmunk_constraint_header "${chipmunk_SOURCE_DIR}/include/chipmunk/constraints/*.h") @@ -39,3 +41,10 @@ if(BUILD_SHARED OR INSTALL_STATIC) install(FILES ${chipmunk_public_header} DESTINATION include/chipmunk) install(FILES ${chipmunk_constraint_header} DESTINATION include/chipmunk/constraints) endif(BUILD_SHARED OR INSTALL_STATIC) + +set_target_properties(chipmunk_static + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/external/curl/include/ios/curl/curlbuild.h b/external/curl/include/ios/curl/curlbuild.h index 98ede6eef7..c24099a90a 100644 --- a/external/curl/include/ios/curl/curlbuild.h +++ b/external/curl/include/ios/curl/curlbuild.h @@ -153,7 +153,7 @@ #endif /* The size of `long', as computed by sizeof. */ -#define CURL_SIZEOF_LONG 4 +#define CURL_SIZEOF_LONG sizeof(long) /* Integral data type used for curl_socklen_t. */ #define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t diff --git a/external/json/CMakeLists.txt b/external/json/CMakeLists.txt new file mode 100644 index 0000000000..87018744ef --- /dev/null +++ b/external/json/CMakeLists.txt @@ -0,0 +1,20 @@ +set(JSONCPP_SRC + json_reader.cpp + json_value.cpp + json_writer.cpp +) + +include_directories( + +) + +add_library(jsoncpp STATIC + ${JSONCPP_SRC} +) + +set_target_properties(jsoncpp + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/cocos/audio/third-party/fmod/api/inc/fmod.h.REMOVED.git-id b/external/linux-specific/fmod/include/32-bit/fmod.h.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod.h.REMOVED.git-id rename to external/linux-specific/fmod/include/32-bit/fmod.h.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/api/inc/fmod.hpp b/external/linux-specific/fmod/include/32-bit/fmod.hpp similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod.hpp rename to external/linux-specific/fmod/include/32-bit/fmod.hpp diff --git a/cocos/audio/third-party/fmod/api/inc/fmod_codec.h b/external/linux-specific/fmod/include/32-bit/fmod_codec.h similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod_codec.h rename to external/linux-specific/fmod/include/32-bit/fmod_codec.h diff --git a/cocos/audio/third-party/fmod/api/inc/fmod_dsp.h b/external/linux-specific/fmod/include/32-bit/fmod_dsp.h similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod_dsp.h rename to external/linux-specific/fmod/include/32-bit/fmod_dsp.h diff --git a/cocos/audio/third-party/fmod/api/inc/fmod_errors.h b/external/linux-specific/fmod/include/32-bit/fmod_errors.h similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod_errors.h rename to external/linux-specific/fmod/include/32-bit/fmod_errors.h diff --git a/cocos/audio/third-party/fmod/api/inc/fmod_memoryinfo.h b/external/linux-specific/fmod/include/32-bit/fmod_memoryinfo.h similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod_memoryinfo.h rename to external/linux-specific/fmod/include/32-bit/fmod_memoryinfo.h diff --git a/cocos/audio/third-party/fmod/api/inc/fmod_output.h b/external/linux-specific/fmod/include/32-bit/fmod_output.h similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod_output.h rename to external/linux-specific/fmod/include/32-bit/fmod_output.h diff --git a/cocos/audio/third-party/fmod/api/inc/fmodlinux.h b/external/linux-specific/fmod/include/32-bit/fmodlinux.h similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmodlinux.h rename to external/linux-specific/fmod/include/32-bit/fmodlinux.h diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod.h.REMOVED.git-id b/external/linux-specific/fmod/include/64-bit/fmod.h.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod.h.REMOVED.git-id rename to external/linux-specific/fmod/include/64-bit/fmod.h.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod.hpp b/external/linux-specific/fmod/include/64-bit/fmod.hpp similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod.hpp rename to external/linux-specific/fmod/include/64-bit/fmod.hpp diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod_codec.h b/external/linux-specific/fmod/include/64-bit/fmod_codec.h similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod_codec.h rename to external/linux-specific/fmod/include/64-bit/fmod_codec.h diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod_dsp.h b/external/linux-specific/fmod/include/64-bit/fmod_dsp.h similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod_dsp.h rename to external/linux-specific/fmod/include/64-bit/fmod_dsp.h diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod_errors.h b/external/linux-specific/fmod/include/64-bit/fmod_errors.h similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod_errors.h rename to external/linux-specific/fmod/include/64-bit/fmod_errors.h diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod_memoryinfo.h b/external/linux-specific/fmod/include/64-bit/fmod_memoryinfo.h similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod_memoryinfo.h rename to external/linux-specific/fmod/include/64-bit/fmod_memoryinfo.h diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod_output.h b/external/linux-specific/fmod/include/64-bit/fmod_output.h similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod_output.h rename to external/linux-specific/fmod/include/64-bit/fmod_output.h diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmodlinux.h b/external/linux-specific/fmod/include/64-bit/fmodlinux.h similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmodlinux.h rename to external/linux-specific/fmod/include/64-bit/fmodlinux.h diff --git a/cocos/audio/third-party/fmod/api/lib/libfmodex-4.36.01.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/32-bit/libfmodex-4.36.01.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/api/lib/libfmodex-4.36.01.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/32-bit/libfmodex-4.36.01.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/api/lib/libfmodex.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/32-bit/libfmodex.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/api/lib/libfmodex.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/32-bit/libfmodex.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/api/lib/libfmodexL-4.36.01.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/32-bit/libfmodexL-4.36.01.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/api/lib/libfmodexL-4.36.01.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/32-bit/libfmodexL-4.36.01.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/api/lib/libfmodexL.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/32-bit/libfmodexL.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/api/lib/libfmodexL.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/32-bit/libfmodexL.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/lib64/api/lib/libfmodex64-4.38.00.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/64-bit/libfmodex64-4.38.00.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/lib/libfmodex64-4.38.00.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/64-bit/libfmodex64-4.38.00.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/lib64/api/lib/libfmodex64.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/64-bit/libfmodex64.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/lib/libfmodex64.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/64-bit/libfmodex64.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/lib64/api/lib/libfmodexL64-4.38.00.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/64-bit/libfmodexL64-4.38.00.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/lib/libfmodexL64-4.38.00.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/64-bit/libfmodexL64-4.38.00.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/lib64/api/lib/libfmodexL64.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/64-bit/libfmodexL64.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/lib/libfmodexL64.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/64-bit/libfmodexL64.so.REMOVED.git-id diff --git a/external/lua/lua/CMakeLists.txt b/external/lua/lua/CMakeLists.txt new file mode 100644 index 0000000000..c63d80a7b2 --- /dev/null +++ b/external/lua/lua/CMakeLists.txt @@ -0,0 +1,42 @@ +set(LUA_SRC + lapi.c + lauxlib.c + lbaselib.c + lcode.c + ldblib.c + ldebug.c + ldo.c + ldump.c + lfunc.c + lgc.c + linit.c + liolib.c + llex.c + lmathlib.c + lmem.c + loadlib.c + lobject.c + lopcodes.c + loslib.c + lparser.c + lstate.c + lstring.c + lstrlib.c + ltable.c + ltablib.c + ltm.c + lundump.c + lvm.c + lzio.c + print.c +) + +add_library(lua STATIC + ${LUA_SRC} +) + +set_target_properties(lua + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) diff --git a/external/lua/tolua/CMakeLists.txt b/external/lua/tolua/CMakeLists.txt new file mode 100644 index 0000000000..b12e144e75 --- /dev/null +++ b/external/lua/tolua/CMakeLists.txt @@ -0,0 +1,22 @@ +set(TOLUA_SRC + tolua_event.c + tolua_is.c + tolua_map.c + tolua_push.c + tolua_to.c +) + +include_directories( + ../lua +) + + +add_library(tolua STATIC + ${TOLUA_SRC} +) + +set_target_properties(tolua + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) diff --git a/external/tinyxml2/CMakeLists.txt b/external/tinyxml2/CMakeLists.txt new file mode 100644 index 0000000000..6877779b2c --- /dev/null +++ b/external/tinyxml2/CMakeLists.txt @@ -0,0 +1,14 @@ +set(TINYXML2_SRC + tinyxml2.cpp +) + +add_library(tinyxml2 STATIC + ${TINYXML2_SRC} +) + +set_target_properties(tinyxml2 + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/external/unzip/CMakeLists.txt b/external/unzip/CMakeLists.txt new file mode 100644 index 0000000000..ae98584279 --- /dev/null +++ b/external/unzip/CMakeLists.txt @@ -0,0 +1,15 @@ +set(UNZIP_SRC + ioapi.cpp + unzip.cpp +) + +add_library(unzip STATIC + ${UNZIP_SRC} +) + +set_target_properties(unzip + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/samples/CMakeLists.txt b/samples/CMakeLists.txt new file mode 100644 index 0000000000..198764a991 --- /dev/null +++ b/samples/CMakeLists.txt @@ -0,0 +1,15 @@ +if(BUILD_HelloCpp) +add_subdirectory(Cpp/HelloCpp) +endif(BUILD_HelloCpp) + +if(BUILD_TestCpp) +add_subdirectory(Cpp/TestCpp) +endif(BUILD_TestCpp) + +if(BUILD_HelloLua) +add_subdirectory(Lua/HelloLua) +endif(BUILD_HelloLua) + +if(BUILD_TestLua) +add_subdirectory(Lua/TestLua) +endif(BUILD_TestLua) \ No newline at end of file diff --git a/samples/Cpp/AssetsManagerTest/proj.android/jni/Application.mk b/samples/Cpp/AssetsManagerTest/proj.android/jni/Application.mk index 5273ceb9dd..74af9626ab 100644 --- a/samples/Cpp/AssetsManagerTest/proj.android/jni/Application.mk +++ b/samples/Cpp/AssetsManagerTest/proj.android/jni/Application.mk @@ -1,6 +1,5 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT=1 -std=c++11 # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Cpp/HelloCpp/CMakeLists.txt b/samples/Cpp/HelloCpp/CMakeLists.txt new file mode 100644 index 0000000000..667bf7cd18 --- /dev/null +++ b/samples/Cpp/HelloCpp/CMakeLists.txt @@ -0,0 +1,25 @@ +set(APP_NAME hellocpp) + +set(SAMPLE_SRC + proj.linux/main.cpp + Classes/AppDelegate.cpp + Classes/HelloWorldScene.cpp +) + +# add the executable +add_executable(${APP_NAME} + ${SAMPLE_SRC} +) + +target_link_libraries(${APP_NAME} audio cocos2d) + +set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${APP_NAME}") + +set_target_properties(${APP_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") + +pre_build(${APP_NAME} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources + ) + diff --git a/samples/Cpp/HelloCpp/Resources/app.icf b/samples/Cpp/HelloCpp/Resources/app.icf deleted file mode 100644 index 74755b2099..0000000000 --- a/samples/Cpp/HelloCpp/Resources/app.icf +++ /dev/null @@ -1,17 +0,0 @@ -# This file is for configuration settings for your -# application. -# -# The syntax is similar to windows .ini files ie -# -# [GroupName] -# Setting = Value -# -# Which can be read by your application using -# e.g s3eConfigGetString("GroupName", "Setting", string) -# -# All settings must be documented in .config.txt files. -# New settings specific to this application should be -# documented in app.config.txt -# -# Some conditional operations are also permitted, see the -# S3E documentation for details. diff --git a/samples/Cpp/HelloCpp/Resources/development.icf b/samples/Cpp/HelloCpp/Resources/development.icf deleted file mode 100644 index 09e69865f0..0000000000 --- a/samples/Cpp/HelloCpp/Resources/development.icf +++ /dev/null @@ -1,107 +0,0 @@ -# Settings ICF file automatically generated by S3E development environment - -AccelEnabled = Type=bool, Default="true", Value = "true" -AudioAAC = Type=bool, Default="false", Value = "false" -AudioAACPlus = Type=bool, Default="false", Value = "false" -AudioMIDI = Type=bool, Default="true", Value = "true" -AudioMP3 = Type=bool, Default="true", Value = "true" -AudioPCM = Type=bool, Default="true", Value = "true" -AudioQCP = Type=bool, Default="false", Value = "false" -AudioVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -BacklightTimeout = Type=int, Min=0.000000, Max=120000.000000, Default="10000", Value = "10000" -CompassEnabled = Type=bool, Default="true", Value = "true" -ContactsFromAddrBook = Type=bool, Default="false", Value = "false" -DeviceAdvanceSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Left", Value = "Bottom Left" -DeviceArch = Type=string, Allowed="" "ARM4T" "ARM4" "ARM5T" "ARM5TE" "ARM5TEJ" "ARM6" "ARM6K" "ARM6T2" "ARM6Z" "X86" "PPC" "AMD64" "ARM7", Default="", Value = "" -DeviceBackSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Right", Value = "Bottom Right" -DeviceBatteryLevel = Type=int, Min=0.000000, Max=100.000000, Default="50", Value = "50" -DeviceClass = Type=string, Allowed="UNKNOWN" "SYMBIAN_GENERIC" "SYMBIAN_SERIES60" "SYMBIAN_SERIES60_EMULATOR" "SYMBIAN_UIQ" "SYMBIAN_UIQ_EMULATOR" "BREW_GENERIC" "BREW_QCIF_3D" "BREW_QCIF_25G" "BREW_SQCIF_256" "BREW_QVGA_3G" "WINDOWS_GENERIC" "WINMOBILE_GENERIC" "WINMOBILE_SP" "WINMOBILE_PPC" "LINUX_GENERIC" "LINUX_DESKTOP" "LINUX_EMBED" "WIPI_GENERIC" "NDS_GENERIC" "ARM_SEMIH_GENERIC" "NULCUES_GENERIC" "NGI_GENERIC", Default="WINDOWS_GENERIC", Value = "WINDOWS_GENERIC" -DeviceFPU = Type=string, Allowed="None" "VFP Present", Default="VFP Present", Value = "VFP Present" -DeviceFreeRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceIDInt = Type=int, Default="0", Value = "0" -DeviceIDString = Type=string, Default="", Value = "" -DeviceIMSI = Type=string, Default="SIMULATOR_IMSI", Value = "SIMULATOR_IMSI" -DeviceLSKIsBack = Type=bool, Default="false", Value = "false" -DeviceLanguage = Type=string, Allowed="UNKNOWN" "ENGLISH" "FRENCH" "GERMAN" "SPANISH" "ITALIAN" "PORTUGUESE" "DUTCH" "TURKISH" "CROATIAN" "CZECH" "DANISH" "FINNISH" "HUNGARIAN" "NORWEGIAN" "POLISH" "RUSSIAN" "SERBIAN" "SLOVAK" "SLOVENIAN" "SWEDISH" "UKRAINIAN" "GREEK" "JAPANESE" "SIMPL_CHINESE" "TRAD_CHINESE" "KOREAN" "ICELANDIC" "FLEMISH" "THAI" "AFRIKAANS" "ALBANIAN" "AMHARIC" "ARABIC" "ARMENIAN" "AZERBAIJANI" "TAGALOG" "BELARUSSIAN" "BENGALI" "BULGARIAN" "BURMESE" "CATALAN" "ESTONIAN" "FARSI" "GAELIC" "GEORGIAN" "GUJARATI" "HEBREW" "HINDI" "INDONESIAN" "IRISH" "KANNADA" "KAZAKH" "KHMER" "LAO" "LATVIAN" "LITHUANIAN" "MACEDONIAN" "MALAY" "MALAYALAM" "MARATHI" "MOLDOVIAN" "MONGOLIAN" "PUNJABI" "ROMANIAN" "SINHALESE" "SOMALI" "SWAHILI" "TAJIK" "TAMIL" "TELUGU" "TIBETAN" "TIGRINYA" "TURKMEN" "URDU" "UZBEK" "VIETNAMESE" "WELSH" "ZULU" "", Default="", Value = "" -DeviceMainsPower = Type=bool, Default="false", Value = "false" -DeviceName = Type=string, Default="My Computer", Value = "My Computer" -DeviceOS = Type=string, Allowed="NONE" "SYMBIAN" "BREW" "WINDOWS" "WINMOBILE" "LINUX" "WIPI" "NDS" "ARM_SEMIH" "NUCLEUS" "NGI" "WINCE" "SHARPEMP" "OSX" "IPHONE" "UIQ" "PS3" "X360" "BADA" "ANDROID" "WEBOS" "QNX", Default="NONE", Value = "NONE" -DeviceOSVersion = Type=string, Default="", Value = "" -DeviceOSVersionNumber = Type=int, Default="0", Value = "0" -DevicePhoneNumber = Type=string, Default="0044123456789", Value = "0044123456789" -DeviceTimezone = Type=string, Default="SYSTEM", Value = "SYSTEM" -DeviceTotalRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceUniqueID = Type=string, Default="SIMULATOR_ID", Value = "SIMULATOR_ID" -DeviceUniqueIDInt = Type=int, Default="01234567890", Value = "01234567890" -FileTotalStorageSize = Type=int, Min=0.000000, Max=2147483648.000000, Default="67108864", Value = "67108864" -FileUseSeparateRomRam = Type=bool, Default="true", Value = "true" -FileUseTotalStorageSize = Type=bool, Default="false", Value = "false" -GLAPI = Type=string, Allowed="None" "GLES 1.0 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.1 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.0 Common Profile from Imagination POWERVR(TM)" "GLES 1.1 Common Profile from Imagination POWERVR(TM)" "GLES 2.0 from Imagination POWERVR(TM)" "Obey [S3E] SysGlesVersion .icf setting" "GLES 1.1 Common Profile from Qualcomm Snapdragon(TM)" "GLES 2.0 from Qualcomm Snapdragon(TM)" "GLES 2.0 ANGLE", Default="Obey [S3E] SysGlesVersion .icf setting", Value = "Obey [S3E] SysGlesVersion .icf setting" -GLDontUseHiddenWindow = Type=bool, Default="false", Value = "false" -GLTerminateOnSuspend = Type=bool, Default="false", Value = "false" -GLUsePVRVFrame = Type=bool, Default="false", Value = "false" -KeyboardHasAlpha = Type=bool, Default="true", Value = "true" -KeyboardHasDirection = Type=bool, Default="true", Value = "true" -KeyboardHasKeypad = Type=bool, Default="true", Value = "true" -KeyboardNumpadRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -LicenseExpiryDate = Type=int, Min=0.000000, Max=999999995904.000000, Default="0", Value = "0" -LicenseMinutesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LicenseStatus = Type=string, Allowed="EXPIRED" "DEMO" "USECOUNT" "EXPIRYDATE" "EXPIRYMINSUSE" "PURCHASE" "SUBSCRIPTION" "UPGRADE" "NONCOMMERCIAL", Default="NONCOMMERCIAL", Value = "NONCOMMERCIAL" -LicenseUsesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LocationAltitude = Type=float, Min=-2000.000000, Max=100000.000000, Default="60.0", Value = "60.0" -LocationAvailable = Type=bool, Default="true", Value = "true" -LocationHeading = Type=float, Min=0.000000, Max=359.000000, Default="0.0", Value = "0.0" -LocationHorizontalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="20.0", Value = "20.0" -LocationLatitude = Type=float, Min=-90.000000, Max=90.000000, Default="51.511791", Value = "51.511791" -LocationLongitude = Type=float, Min=-180.000000, Max=180.000000, Default="-0.191084", Value = "-0.191084" -LocationSpeed = Type=float, Min=0.000000, Max=10000.000000, Default="0", Value = "0" -LocationVerticalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="100.0", Value = "100.0" -MacOSSimulatorCustomSettings = Type=string, Default="", Value = "" -MacOSSimulatorDevices_ANDROID = Type=string, Allowed="Samsung Galaxy S:480x800:512" "HTC Sensation XL:480x800:768" "Samsung Galaxy Note:800x1280:1024" "Motorola Droid Razr:540x960:1024" "Kindle Fire:1024x600:512" "Samsung Galaxy Tab:1024x600:512", Default="Samsung Galaxy S:480x800:512", Value = "Samsung Galaxy S:480x800:512" -MacOSSimulatorDevices_IPHONE = Type=string, Allowed="iPhone 3GS:320x480:256" "iPhone 4:640x960:512" "iPhone 5:640x1136:1024" "iPad:768x1024:256" "iPad 2:768x1024:512" "iPad 3:1536x2048:1024", Default="iPhone 3GS:320x480:256", Value = "iPhone 3GS:320x480:256" -MacOSSimulatorPlatforms = Type=string, Allowed="IPHONE" "ANDROID", Default="IPHONE", Value = "IPHONE" -MacOSSimulatorUseCustomSettings = Type=bool, Default="true", Value = "true" -MemoryPoison = Type=bool, Default="true", Value = "true" -MemoryPoisonAlloc = Type=int, Min=0.000000, Max=255.000000, Default="170", Value = "170" -MemoryPoisonFree = Type=int, Min=0.000000, Max=255.000000, Default="221", Value = "221" -MemoryPoisonInit = Type=int, Min=0.000000, Max=255.000000, Default="204", Value = "204" -PointerAvailable = Type=bool, Default="true", Value = "true" -PointerMultiSimulationMode = Type=bool, Default="false", Value = "false" -PointerMultiTouchAvailable = Type=bool, Default="false", Value = "false" -PointerStylusType = Type=string, Allowed="INVALID" "STYLUS" "FINGER", Default="INVALID", Value = "INVALID" -PointerType = Type=string, Allowed="INVALID" "MOUSE" "STYLUS", Default="MOUSE", Value = "MOUSE" -SMSEnabled = Type=bool, Default="true", Value = "true" -SMSReceiveEnabled = Type=bool, Default="true", Value = "true" -SocketDNSDelay = Type=int, Min=0.000000, Max=30000.000000, Default="0", Value = "0" -SocketHTTPProxy = Type=string, Default="", Value = "" -SocketHostName = Type=string, Default="", Value = "" -SocketNetworkAvailable = Type=bool, Default="true", Value = "true" -SocketNetworkLoss = Type=bool, Default="false", Value = "false" -SocketNetworkType = Type=string, Allowed="NONE" "UNKNOWN" "LAN" "WLAN" "GPRS" "UMTS" "EVDO" "CDMA2000" "HSDPA" "WIMAX" "BLUETOOTH" "EDGE" "CDMA" "IDEN" "LTE" "EHRPD" "HSPAPLUS", Default="LAN", Value = "LAN" -SocketRecvLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SocketSendLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SoundEnabled = Type=bool, Default="true", Value = "true" -SoundRecordEnabled = Type=bool, Default="true", Value = "true" -SoundSampleRate = Type=int, Allowed="8192" "11025" "16000" "22050" "44100", Default="22050", Value = "22050" -SoundStereo = Type=bool, Default="true", Value = "true" -SoundVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -SurfaceDisableWhenGLIsActive = Type=bool, Default="false", Value = "false" -SurfaceDoubleBuffer = Type=bool, Default="false", Value = "false" -SurfaceHeight = Type=int, Min=128.000000, Max=4096.000000, Default="480", Value = "320" -SurfacePitch = Type=int, Min=0.000000, Max=8192.000000, Default="0", Value = "0" -SurfacePixelType = Type=string, Allowed="RGB444" "RGB555" "RGB565" "RGB666" "RGB888" "BGR444" "BGR555" "BGR565" "BGR666" "BGR888", Default="RGB565", Value = "RGB565" -SurfacePredefinedResolution = Type=string, Allowed="176x200" "176x208" "240x320 (QVGA Portrait)" "240x400" "320x240 (QVGA Landscape)" "320x400" "320x480 (iPhone Portrait)" "400x240" "480x320 (iPhone Landscape)" "360x640 (qHD Portrait)" "640x360 (qHD Landscape)" "480x640 (VGA Portrait)" "480x800 (WVGA Portrait)" "640x480 (VGA Landscape)" "800x400" "800x480 (WVGA Landscape)" "640x960 (iPhone 4 Portrait)" "960x640 (iPhone 4 Landscape)" "640x1136 (iPhone 5 Portrait)" "1136x640 (iPhone 5 Landscape)" "1024x600 (Playbook Landscape)" "600x1024 (Playbook Portrait)" "768x1024 (iPad Portrait)" "1024x768 (iPad Landscape)" "2048x1536 (iPad Retina Landscape)" "1536x2048 (iPad Retina Portrait)", Default="320x480 (iPhone Portrait)", Value = "176x200" -SurfaceRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -SurfaceUnalign = Type=bool, Default="true", Value = "true" -SurfaceUseMultiBuffers = Type=bool, Default="true", Value = "true" -SurfaceWidth = Type=int, Min=128.000000, Max=4096.000000, Default="320", Value = "480" -SymbianSoundLatency = Type=int, Min=20.000000, Max=1400.000000, Default="120", Value = "120" -ThreadEnabled = Type=bool, Default="true", Value = "true" -TimerAccuracy = Type=int, Min=0.000000, Max=1000.000000, Default="0", Value = "0" -TimerHiRes = Type=bool, Default="false", Value = "false" -TimerLocaltimeOffsetHours = Type=string, Allowed="-12" "-11" "-10" "-9" "-8" "-7" "-6" "-5" "-4" "-3" "-2" "-1" "0" "+1" "+2" "+3" "+4" "+5" "+6" "+7" "+8" "+9" "+10" "+11" "+12" "+13" "SYSTEM", Default="SYSTEM", Value = "SYSTEM" -VibraEnabled = Type=bool, Default="true", Value = "true" -Video3GPP = Type=bool, Default="false", Value = "false" -VideoJPEG = Type=bool, Default="true", Value = "true" -VideoMPEG4 = Type=bool, Default="true", Value = "true" -VideoVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" diff --git a/samples/Cpp/HelloCpp/proj.android/jni/Application.mk b/samples/Cpp/HelloCpp/proj.android/jni/Application.mk index 0e9d025fba..74af9626ab 100644 --- a/samples/Cpp/HelloCpp/proj.android/jni/Application.mk +++ b/samples/Cpp/HelloCpp/proj.android/jni/Application.mk @@ -2,4 +2,4 @@ APP_STL := gnustl_static # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Cpp/SimpleGame/Resources/app.icf b/samples/Cpp/SimpleGame/Resources/app.icf deleted file mode 100644 index 1ae216d665..0000000000 --- a/samples/Cpp/SimpleGame/Resources/app.icf +++ /dev/null @@ -1,20 +0,0 @@ -# This file is for configuration settings for your -# application. -# -# The syntax is similar to windows .ini files ie -# -# [GroupName] -# Setting = Value -# -# Which can be read by your application using -# e.g s3eConfigGetString("GroupName", "Setting", string) -# -# All settings must be documented in .config.txt files. -# New settings specific to this application should be -# documented in app.config.txt -# -# Some conditional operations are also permitted, see the -# S3E documentation for details. - -[S3E] -DispFixRot=Landscape \ No newline at end of file diff --git a/samples/Cpp/SimpleGame/Resources/development.icf b/samples/Cpp/SimpleGame/Resources/development.icf deleted file mode 100644 index c9d1b773f1..0000000000 --- a/samples/Cpp/SimpleGame/Resources/development.icf +++ /dev/null @@ -1,107 +0,0 @@ -# Settings ICF file automatically generated by S3E development environment - -AccelEnabled = Type=bool, Default="true", Value = "true" -AudioAAC = Type=bool, Default="false", Value = "false" -AudioAACPlus = Type=bool, Default="false", Value = "false" -AudioMIDI = Type=bool, Default="true", Value = "true" -AudioMP3 = Type=bool, Default="true", Value = "true" -AudioPCM = Type=bool, Default="true", Value = "true" -AudioQCP = Type=bool, Default="false", Value = "false" -AudioVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -BacklightTimeout = Type=int, Min=0.000000, Max=120000.000000, Default="10000", Value = "10000" -CompassEnabled = Type=bool, Default="true", Value = "true" -ContactsFromAddrBook = Type=bool, Default="false", Value = "false" -DeviceAdvanceSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Left", Value = "Bottom Left" -DeviceArch = Type=string, Allowed="" "ARM4T" "ARM4" "ARM5T" "ARM5TE" "ARM5TEJ" "ARM6" "ARM6K" "ARM6T2" "ARM6Z" "X86" "PPC" "AMD64" "ARM7", Default="", Value = "" -DeviceBackSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Right", Value = "Bottom Right" -DeviceBatteryLevel = Type=int, Min=0.000000, Max=100.000000, Default="50", Value = "50" -DeviceClass = Type=string, Allowed="UNKNOWN" "SYMBIAN_GENERIC" "SYMBIAN_SERIES60" "SYMBIAN_SERIES60_EMULATOR" "SYMBIAN_UIQ" "SYMBIAN_UIQ_EMULATOR" "BREW_GENERIC" "BREW_QCIF_3D" "BREW_QCIF_25G" "BREW_SQCIF_256" "BREW_QVGA_3G" "WINDOWS_GENERIC" "WINMOBILE_GENERIC" "WINMOBILE_SP" "WINMOBILE_PPC" "LINUX_GENERIC" "LINUX_DESKTOP" "LINUX_EMBED" "WIPI_GENERIC" "NDS_GENERIC" "ARM_SEMIH_GENERIC" "NULCUES_GENERIC" "NGI_GENERIC", Default="WINDOWS_GENERIC", Value = "WINDOWS_GENERIC" -DeviceFPU = Type=string, Allowed="None" "VFP Present", Default="VFP Present", Value = "VFP Present" -DeviceFreeRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceIDInt = Type=int, Default="0", Value = "0" -DeviceIDString = Type=string, Default="", Value = "" -DeviceIMSI = Type=string, Default="SIMULATOR_IMSI", Value = "SIMULATOR_IMSI" -DeviceLSKIsBack = Type=bool, Default="false", Value = "false" -DeviceLanguage = Type=string, Allowed="UNKNOWN" "ENGLISH" "FRENCH" "GERMAN" "SPANISH" "ITALIAN" "PORTUGUESE" "DUTCH" "TURKISH" "CROATIAN" "CZECH" "DANISH" "FINNISH" "HUNGARIAN" "NORWEGIAN" "POLISH" "RUSSIAN" "SERBIAN" "SLOVAK" "SLOVENIAN" "SWEDISH" "UKRAINIAN" "GREEK" "JAPANESE" "SIMPL_CHINESE" "TRAD_CHINESE" "KOREAN" "ICELANDIC" "FLEMISH" "THAI" "AFRIKAANS" "ALBANIAN" "AMHARIC" "ARABIC" "ARMENIAN" "AZERBAIJANI" "TAGALOG" "BELARUSSIAN" "BENGALI" "BULGARIAN" "BURMESE" "CATALAN" "ESTONIAN" "FARSI" "GAELIC" "GEORGIAN" "GUJARATI" "HEBREW" "HINDI" "INDONESIAN" "IRISH" "KANNADA" "KAZAKH" "KHMER" "LAO" "LATVIAN" "LITHUANIAN" "MACEDONIAN" "MALAY" "MALAYALAM" "MARATHI" "MOLDOVIAN" "MONGOLIAN" "PUNJABI" "ROMANIAN" "SINHALESE" "SOMALI" "SWAHILI" "TAJIK" "TAMIL" "TELUGU" "TIBETAN" "TIGRINYA" "TURKMEN" "URDU" "UZBEK" "VIETNAMESE" "WELSH" "ZULU" "", Default="", Value = "" -DeviceMainsPower = Type=bool, Default="false", Value = "false" -DeviceName = Type=string, Default="My Computer", Value = "My Computer" -DeviceOS = Type=string, Allowed="NONE" "SYMBIAN" "BREW" "WINDOWS" "WINMOBILE" "LINUX" "WIPI" "NDS" "ARM_SEMIH" "NUCLEUS" "NGI" "WINCE" "SHARPEMP" "OSX" "IPHONE" "UIQ" "PS3" "X360" "BADA" "ANDROID" "WEBOS" "QNX", Default="NONE", Value = "NONE" -DeviceOSVersion = Type=string, Default="", Value = "" -DeviceOSVersionNumber = Type=int, Default="0", Value = "0" -DevicePhoneNumber = Type=string, Default="0044123456789", Value = "0044123456789" -DeviceTimezone = Type=string, Default="SYSTEM", Value = "SYSTEM" -DeviceTotalRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceUniqueID = Type=string, Default="SIMULATOR_ID", Value = "SIMULATOR_ID" -DeviceUniqueIDInt = Type=int, Default="01234567890", Value = "01234567890" -FileTotalStorageSize = Type=int, Min=0.000000, Max=2147483648.000000, Default="67108864", Value = "67108864" -FileUseSeparateRomRam = Type=bool, Default="true", Value = "true" -FileUseTotalStorageSize = Type=bool, Default="false", Value = "false" -GLAPI = Type=string, Allowed="None" "GLES 1.0 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.1 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.0 Common Profile from Imagination POWERVR(TM)" "GLES 1.1 Common Profile from Imagination POWERVR(TM)" "GLES 2.0 from Imagination POWERVR(TM)" "Obey [S3E] SysGlesVersion .icf setting" "GLES 1.1 Common Profile from Qualcomm Snapdragon(TM)" "GLES 2.0 from Qualcomm Snapdragon(TM)" "GLES 2.0 ANGLE", Default="Obey [S3E] SysGlesVersion .icf setting", Value = "Obey [S3E] SysGlesVersion .icf setting" -GLDontUseHiddenWindow = Type=bool, Default="false", Value = "false" -GLTerminateOnSuspend = Type=bool, Default="false", Value = "false" -GLUsePVRVFrame = Type=bool, Default="false", Value = "false" -KeyboardHasAlpha = Type=bool, Default="true", Value = "true" -KeyboardHasDirection = Type=bool, Default="true", Value = "true" -KeyboardHasKeypad = Type=bool, Default="true", Value = "true" -KeyboardNumpadRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -LicenseExpiryDate = Type=int, Min=0.000000, Max=999999995904.000000, Default="0", Value = "0" -LicenseMinutesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LicenseStatus = Type=string, Allowed="EXPIRED" "DEMO" "USECOUNT" "EXPIRYDATE" "EXPIRYMINSUSE" "PURCHASE" "SUBSCRIPTION" "UPGRADE" "NONCOMMERCIAL", Default="NONCOMMERCIAL", Value = "NONCOMMERCIAL" -LicenseUsesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LocationAltitude = Type=float, Min=-2000.000000, Max=100000.000000, Default="60.0", Value = "60.0" -LocationAvailable = Type=bool, Default="true", Value = "true" -LocationHeading = Type=float, Min=0.000000, Max=359.000000, Default="0.0", Value = "0.0" -LocationHorizontalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="20.0", Value = "20.0" -LocationLatitude = Type=float, Min=-90.000000, Max=90.000000, Default="51.511791", Value = "51.511791" -LocationLongitude = Type=float, Min=-180.000000, Max=180.000000, Default="-0.191084", Value = "-0.191084" -LocationSpeed = Type=float, Min=0.000000, Max=10000.000000, Default="0", Value = "0" -LocationVerticalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="100.0", Value = "100.0" -MacOSSimulatorCustomSettings = Type=string, Default="", Value = "" -MacOSSimulatorDevices_ANDROID = Type=string, Allowed="Samsung Galaxy S:480x800:512" "HTC Sensation XL:480x800:768" "Samsung Galaxy Note:800x1280:1024" "Motorola Droid Razr:540x960:1024" "Kindle Fire:1024x600:512" "Samsung Galaxy Tab:1024x600:512", Default="Samsung Galaxy S:480x800:512", Value = "Samsung Galaxy S:480x800:512" -MacOSSimulatorDevices_IPHONE = Type=string, Allowed="iPhone 3GS:320x480:256" "iPhone 4:640x960:512" "iPhone 5:640x1136:1024" "iPad:768x1024:256" "iPad 2:768x1024:512" "iPad 3:1536x2048:1024", Default="iPhone 3GS:320x480:256", Value = "iPhone 3GS:320x480:256" -MacOSSimulatorPlatforms = Type=string, Allowed="IPHONE" "ANDROID", Default="IPHONE", Value = "IPHONE" -MacOSSimulatorUseCustomSettings = Type=bool, Default="true", Value = "true" -MemoryPoison = Type=bool, Default="true", Value = "true" -MemoryPoisonAlloc = Type=int, Min=0.000000, Max=255.000000, Default="170", Value = "170" -MemoryPoisonFree = Type=int, Min=0.000000, Max=255.000000, Default="221", Value = "221" -MemoryPoisonInit = Type=int, Min=0.000000, Max=255.000000, Default="204", Value = "204" -PointerAvailable = Type=bool, Default="true", Value = "true" -PointerMultiSimulationMode = Type=bool, Default="false", Value = "false" -PointerMultiTouchAvailable = Type=bool, Default="false", Value = "false" -PointerStylusType = Type=string, Allowed="INVALID" "STYLUS" "FINGER", Default="INVALID", Value = "INVALID" -PointerType = Type=string, Allowed="INVALID" "MOUSE" "STYLUS", Default="MOUSE", Value = "MOUSE" -SMSEnabled = Type=bool, Default="true", Value = "true" -SMSReceiveEnabled = Type=bool, Default="true", Value = "true" -SocketDNSDelay = Type=int, Min=0.000000, Max=30000.000000, Default="0", Value = "0" -SocketHTTPProxy = Type=string, Default="", Value = "" -SocketHostName = Type=string, Default="", Value = "" -SocketNetworkAvailable = Type=bool, Default="true", Value = "true" -SocketNetworkLoss = Type=bool, Default="false", Value = "false" -SocketNetworkType = Type=string, Allowed="NONE" "UNKNOWN" "LAN" "WLAN" "GPRS" "UMTS" "EVDO" "CDMA2000" "HSDPA" "WIMAX" "BLUETOOTH" "EDGE" "CDMA" "IDEN" "LTE" "EHRPD" "HSPAPLUS", Default="LAN", Value = "LAN" -SocketRecvLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SocketSendLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SoundEnabled = Type=bool, Default="true", Value = "true" -SoundRecordEnabled = Type=bool, Default="true", Value = "true" -SoundSampleRate = Type=int, Allowed="8192" "11025" "16000" "22050" "44100", Default="22050", Value = "22050" -SoundStereo = Type=bool, Default="true", Value = "true" -SoundVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -SurfaceDisableWhenGLIsActive = Type=bool, Default="false", Value = "false" -SurfaceDoubleBuffer = Type=bool, Default="false", Value = "false" -SurfaceHeight = Type=int, Min=128.000000, Max=4096.000000, Default="480", Value = "640" -SurfacePitch = Type=int, Min=0.000000, Max=8192.000000, Default="0", Value = "0" -SurfacePixelType = Type=string, Allowed="RGB444" "RGB555" "RGB565" "RGB666" "RGB888" "BGR444" "BGR555" "BGR565" "BGR666" "BGR888", Default="RGB565", Value = "RGB565" -SurfacePredefinedResolution = Type=string, Allowed="176x200" "176x208" "240x320 (QVGA Portrait)" "240x400" "320x240 (QVGA Landscape)" "320x400" "320x480 (iPhone Portrait)" "400x240" "480x320 (iPhone Landscape)" "360x640 (qHD Portrait)" "640x360 (qHD Landscape)" "480x640 (VGA Portrait)" "480x800 (WVGA Portrait)" "640x480 (VGA Landscape)" "800x400" "800x480 (WVGA Landscape)" "640x960 (iPhone 4 Portrait)" "960x640 (iPhone 4 Landscape)" "640x1136 (iPhone 5 Portrait)" "1136x640 (iPhone 5 Landscape)" "1024x600 (Playbook Landscape)" "600x1024 (Playbook Portrait)" "768x1024 (iPad Portrait)" "1024x768 (iPad Landscape)" "2048x1536 (iPad Retina Landscape)" "1536x2048 (iPad Retina Portrait)", Default="320x480 (iPhone Portrait)", Value = "176x200" -SurfaceRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -SurfaceUnalign = Type=bool, Default="true", Value = "true" -SurfaceUseMultiBuffers = Type=bool, Default="true", Value = "true" -SurfaceWidth = Type=int, Min=128.000000, Max=4096.000000, Default="320", Value = "960" -SymbianSoundLatency = Type=int, Min=20.000000, Max=1400.000000, Default="120", Value = "120" -ThreadEnabled = Type=bool, Default="true", Value = "true" -TimerAccuracy = Type=int, Min=0.000000, Max=1000.000000, Default="0", Value = "0" -TimerHiRes = Type=bool, Default="false", Value = "false" -TimerLocaltimeOffsetHours = Type=string, Allowed="-12" "-11" "-10" "-9" "-8" "-7" "-6" "-5" "-4" "-3" "-2" "-1" "0" "+1" "+2" "+3" "+4" "+5" "+6" "+7" "+8" "+9" "+10" "+11" "+12" "+13" "SYSTEM", Default="SYSTEM", Value = "SYSTEM" -VibraEnabled = Type=bool, Default="true", Value = "true" -Video3GPP = Type=bool, Default="false", Value = "false" -VideoJPEG = Type=bool, Default="true", Value = "true" -VideoMPEG4 = Type=bool, Default="true", Value = "true" -VideoVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" diff --git a/samples/Cpp/SimpleGame/Resources/sd/app.icf b/samples/Cpp/SimpleGame/Resources/sd/app.icf deleted file mode 100644 index dbc72b4d77..0000000000 --- a/samples/Cpp/SimpleGame/Resources/sd/app.icf +++ /dev/null @@ -1,26 +0,0 @@ -# This file is for configuration settings for your -# application. -# -# The syntax is similar to windows .ini files ie -# -# [GroupName] -# Setting = Value -# -# Which can be read by your application using -# e.g s3eConfigGetString("GroupName", "Setting", string) -# -# All settings must be documented in .config.txt files. -# New settings specific to this application should be -# documented in app.config.txt -# -# Some conditional operations are also permitted, see the -# S3E documentation for details. -[S3E] -MemSize = 10000000 -# Sample only compatible with 480x320 display resolution -WinWidth=480 -WinHeight=320 - -[GL] -AllowNegativeUniformLocation=1 - diff --git a/samples/Cpp/SimpleGame/proj.android/jni/Application.mk b/samples/Cpp/SimpleGame/proj.android/jni/Application.mk index 0e9d025fba..74af9626ab 100644 --- a/samples/Cpp/SimpleGame/proj.android/jni/Application.mk +++ b/samples/Cpp/SimpleGame/proj.android/jni/Application.mk @@ -2,4 +2,4 @@ APP_STL := gnustl_static # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Cpp/TestCpp/CMakeLists.txt b/samples/Cpp/TestCpp/CMakeLists.txt new file mode 100644 index 0000000000..e5493d194c --- /dev/null +++ b/samples/Cpp/TestCpp/CMakeLists.txt @@ -0,0 +1,166 @@ +set(APP_NAME testcpp) + +set(SAMPLE_SRC + Classes/AccelerometerTest/AccelerometerTest.cpp + Classes/ActionManagerTest/ActionManagerTest.cpp + Classes/ActionsEaseTest/ActionsEaseTest.cpp + Classes/ActionsProgressTest/ActionsProgressTest.cpp + Classes/ActionsTest/ActionsTest.cpp + Classes/Box2DTest/Box2dTest.cpp + Classes/Box2DTestBed/Box2dView.cpp + Classes/Box2DTestBed/GLES-Render.cpp + Classes/Box2DTestBed/Test.cpp + Classes/Box2DTestBed/TestEntries.cpp + Classes/BugsTest/Bug-1159.cpp + Classes/BugsTest/Bug-1174.cpp + Classes/BugsTest/Bug-350.cpp + Classes/BugsTest/Bug-422.cpp + Classes/BugsTest/Bug-458/Bug-458.cpp + Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp + Classes/BugsTest/Bug-624.cpp + Classes/BugsTest/Bug-886.cpp + Classes/BugsTest/Bug-899.cpp + Classes/BugsTest/Bug-914.cpp + Classes/BugsTest/BugsTest.cpp + Classes/ChipmunkTest/ChipmunkTest.cpp + Classes/ClickAndMoveTest/ClickAndMoveTest.cpp + Classes/ClippingNodeTest/ClippingNodeTest.cpp + Classes/CocosDenshionTest/CocosDenshionTest.cpp + Classes/CurlTest/CurlTest.cpp + Classes/CurrentLanguageTest/CurrentLanguageTest.cpp + Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp + Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp + Classes/EffectsTest/EffectsTest.cpp + Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp + Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.cpp + Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp + Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.cpp + Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp + Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp + Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.cpp + Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp + Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp + Classes/ExtensionsTest/ExtensionsTest.cpp + Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp + Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp + Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp + Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp + Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp + Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp + Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp + Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp + Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp + Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UISceneManager.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UILabelAtlasTest/UILabelAtlasTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UILabelBMFontTest/UILabelBMFontTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UILabelTest/UILabelTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UINodeContainerTest/UINodeContainerTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UITextAreaTest/UITextAreaTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UITextButtonTest/UITextButtonTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp + Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp + Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp + Classes/FontTest/FontTest.cpp + Classes/IntervalTest/IntervalTest.cpp + Classes/KeyboardTest/KeyboardTest.cpp + Classes/InputTest/MouseTest.cpp + Classes/KeypadTest/KeypadTest.cpp + Classes/LabelTest/LabelTest.cpp + Classes/LabelTest/LabelTestNew.cpp + Classes/LayerTest/LayerTest.cpp + Classes/MenuTest/MenuTest.cpp + Classes/MotionStreakTest/MotionStreakTest.cpp + Classes/MutiTouchTest/MutiTouchTest.cpp + Classes/NodeTest/NodeTest.cpp + Classes/ParallaxTest/ParallaxTest.cpp + Classes/ParticleTest/ParticleTest.cpp + Classes/PerformanceTest/PerformanceAllocTest.cpp + Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp + Classes/PerformanceTest/PerformanceParticleTest.cpp + Classes/PerformanceTest/PerformanceSpriteTest.cpp + Classes/PerformanceTest/PerformanceTest.cpp + Classes/PerformanceTest/PerformanceTextureTest.cpp + Classes/PerformanceTest/PerformanceTouchesTest.cpp + Classes/PhysicsTest/PhysicsTest.cpp + Classes/RenderTextureTest/RenderTextureTest.cpp + Classes/RotateWorldTest/RotateWorldTest.cpp + Classes/SceneTest/SceneTest.cpp + Classes/SchedulerTest/SchedulerTest.cpp + Classes/ShaderTest/ShaderTest.cpp + Classes/ShaderTest/ShaderTest2.cpp + Classes/SpriteTest/SpriteTest.cpp + Classes/TextInputTest/TextInputTest.cpp + Classes/Texture2dTest/Texture2dTest.cpp + Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp + Classes/TextureCacheTest/TextureCacheTest.cpp + Classes/TileMapTest/TileMapTest.cpp + Classes/TouchesTest/Ball.cpp + Classes/TouchesTest/Paddle.cpp + Classes/TouchesTest/TouchesTest.cpp + Classes/TransitionsTest/TransitionsTest.cpp + Classes/UserDefaultTest/UserDefaultTest.cpp + Classes/ZwoptexTest/ZwoptexTest.cpp + Classes/FileUtilsTest/FileUtilsTest.cpp + Classes/SpineTest/SpineTest.cpp + Classes/DataVisitorTest/DataVisitorTest.cpp + Classes/ConfigurationTest/ConfigurationTest.cpp + Classes/controller.cpp + Classes/testBasic.cpp + Classes/AppDelegate.cpp + Classes/BaseTest.cpp + Classes/VisibleRect.cpp + proj.linux/main.cpp +) + +include_directories( + Classes +) + +# add the executable +add_executable(${APP_NAME} + ${SAMPLE_SRC} +) + +target_link_libraries(${APP_NAME} + gui + network + spine + cocostudio + cocosbuilder + extensions + audio + cocos2d + box2d +) + +set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${APP_NAME}") + +set_target_properties(${APP_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") + +pre_build(${APP_NAME} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources + ) + diff --git a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp b/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp index db535fe321..b1a8dcfcf9 100644 --- a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp @@ -21,6 +21,7 @@ AccelerometerTest::AccelerometerTest(void) AccelerometerTest::~AccelerometerTest(void) { _ball->release(); + Device::setAccelerometerEnabled(false); } std::string AccelerometerTest::title() @@ -32,6 +33,7 @@ void AccelerometerTest::onEnter() { Layer::onEnter(); + Device::setAccelerometerEnabled(true); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(AccelerometerTest::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); diff --git a/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp b/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp index ca75a9efe3..ba9d1982fe 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp +++ b/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp @@ -29,7 +29,7 @@ Box2DTestLayer::Box2DTestLayer() _spriteTexture = parent->getTexture(); #else // doesn't use batch node. Slower - _spriteTexture = TextureCache::getInstance()->addImage("Images/blocks.png"); + _spriteTexture = Director::getInstance()->getTextureCache()->addImage("Images/blocks.png"); auto parent = Node::create(); #endif addChild(parent, 0, kTagParentNode); diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp index e0c4ba23ed..7fa35c81d1 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp +++ b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp @@ -10,6 +10,11 @@ // Bug624Layer // //////////////////////////////////////////////////////// +Bug624Layer::~Bug624Layer() +{ + Device::setAccelerometerEnabled(false); +} + bool Bug624Layer::init() { if(BugsTestBaseLayer::init()) @@ -20,6 +25,7 @@ bool Bug624Layer::init() label->setPosition(Point(size.width/2, size.height/2)); addChild(label); + Device::setAccelerometerEnabled(true); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); @@ -50,6 +56,11 @@ void Bug624Layer::onAcceleration(Acceleration* acc, Event* event) // Bug624Layer2 // //////////////////////////////////////////////////////// +Bug624Layer2::~Bug624Layer2() +{ + Device::setAccelerometerEnabled(false); +} + bool Bug624Layer2::init() { if(BugsTestBaseLayer::init()) @@ -60,6 +71,7 @@ bool Bug624Layer2::init() label->setPosition(Point(size.width/2, size.height/2)); addChild(label); + Device::setAccelerometerEnabled(true); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer2::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.h b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.h index b5db348e67..6542ad95ba 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.h +++ b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.h @@ -6,6 +6,7 @@ class Bug624Layer : public BugsTestBaseLayer { public: + virtual ~Bug624Layer(); virtual bool init(); void switchLayer(float dt); virtual void onAcceleration(Acceleration* acc, Event* event); @@ -16,6 +17,7 @@ public: class Bug624Layer2 : public BugsTestBaseLayer { public: + virtual ~Bug624Layer2(); virtual bool init(); void switchLayer(float dt); virtual void onAcceleration(Acceleration* acc, Event* event); diff --git a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp index 50d5dc7252..3faf685bf1 100644 --- a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp @@ -26,6 +26,7 @@ ChipmunkTestLayer::ChipmunkTestLayer() touchListener->onTouchesEnded = CC_CALLBACK_2(ChipmunkTestLayer::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); + Device::setAccelerometerEnabled(true); auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(ChipmunkTestLayer::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(accListener, this); @@ -46,7 +47,7 @@ ChipmunkTestLayer::ChipmunkTestLayer() _spriteTexture = parent->getTexture(); #else // doesn't use batch node. Slower - _spriteTexture = TextureCache::getInstance()->addImage("Images/grossini_dance_atlas.png"); + _spriteTexture = Director::getInstance()->getTextureCache()->addImage("Images/grossini_dance_atlas.png"); auto parent = Node::create(); #endif addChild(parent, 0, kTagParentNode); @@ -90,6 +91,8 @@ ChipmunkTestLayer::~ChipmunkTestLayer() } cpSpaceFree( _space ); + + Device::setAccelerometerEnabled(false); } diff --git a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp index 93e26514a2..f69ba49240 100644 --- a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp @@ -107,7 +107,7 @@ bool BaseClippingNodeTest::init() BaseClippingNodeTest::~BaseClippingNodeTest() { - TextureCache::getInstance()->removeUnusedTextures(); + Director::getInstance()->getTextureCache()->removeUnusedTextures(); } std::string BaseClippingNodeTest::title() diff --git a/samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.cpp b/samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.cpp index 4f8a1fb932..aeed903837 100644 --- a/samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.cpp +++ b/samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.cpp @@ -71,7 +71,7 @@ void PrettyPrinterDemo::onEnter() vistor.clear(); addSprite(); -// dict = TextureCache::getInstance()->snapshotTextures(); +// dict = Director::getInstance()->getTextureCache()->snapshotTextures(); // dict->acceptVisitor(vistor); // log("%s", vistor.getResult().c_str()); } diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index 1cd233ffd2..65cd9044ef 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -15,12 +15,15 @@ static int s_nActionIdx = -1; Layer *CreateLayer(int index) { - Layer *pLayer = NULL; + Layer *pLayer = nullptr; switch(index) { case TEST_ASYNCHRONOUS_LOADING: pLayer = new TestAsynchronousLoading(); break; + case TEST_DIRECT_LOADING: + pLayer = new TestDirectLoading(); + break; case TEST_DRAGON_BONES_2_0: pLayer = new TestDragonBones20(); break; @@ -30,12 +33,18 @@ Layer *CreateLayer(int index) case TEST_PERFORMANCE: pLayer = new TestPerformance(); break; + case TEST_PERFORMANCE_BATCHNODE: + pLayer = new TestPerformanceBatchNode(); + break; case TEST_CHANGE_ZORDER: pLayer = new TestChangeZorder(); break; case TEST_ANIMATION_EVENT: pLayer = new TestAnimationEvent(); break; + case TEST_FRAME_EVENT: + pLayer = new TestFrameEvent(); + break; case TEST_PARTICLE_DISPLAY: pLayer = new TestParticleDisplay(); break; @@ -54,6 +63,9 @@ Layer *CreateLayer(int index) case TEST_ARMATURE_NESTING: pLayer = new TestArmatureNesting(); break; + case TEST_ARMATURE_NESTING_2: + pLayer = new TestArmatureNesting2(); + break; default: break; } @@ -155,7 +167,7 @@ void ArmatureTestLayer::onEnter() restartItem = MenuItemImage::create(s_pathR1, s_pathR2, CC_CALLBACK_1(ArmatureTestLayer::restartCallback, this) ); nextItem = MenuItemImage::create(s_pathF1, s_pathF2, CC_CALLBACK_1(ArmatureTestLayer::nextCallback, this) ); - Menu *menu = Menu::create(backItem, restartItem, nextItem, NULL); + Menu *menu = Menu::create(backItem, restartItem, nextItem, nullptr); menu->setPosition(Point::ZERO); backItem->setPosition(Point(VisibleRect::center().x - restartItem->getContentSize().width * 2, VisibleRect::bottom().y + restartItem->getContentSize().height / 2)); @@ -171,7 +183,7 @@ void ArmatureTestLayer::onExit() { removeAllChildren(); - backItem = restartItem = nextItem = NULL; + backItem = restartItem = nextItem = nullptr; Layer::onExit(); } @@ -235,6 +247,10 @@ void TestAsynchronousLoading::onEnter() ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/cyborg.png", "armature/cyborg.plist", "armature/cyborg.xml", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/Dragon.png", "armature/Dragon.plist", "armature/Dragon.xml", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/Cowboy.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); + ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/hero.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); + ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/horse.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); + ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/bear.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); + ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/HeroAnimation.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); //! load data directly // ArmatureDataManager::getInstance()->addArmatureFileInfo("armature/knight.png", "armature/knight.plist", "armature/knight.xml"); @@ -254,6 +270,12 @@ std::string TestAsynchronousLoading::subtitle() { return "current percent : "; } + +void TestAsynchronousLoading::restartCallback(Object* pSender) +{ + ArmatureDataManager::getInstance()->destoryInstance(); + ArmatureTestLayer::restartCallback(pSender); +} void TestAsynchronousLoading::dataLoaded(float percent) { LabelTTF *label = (LabelTTF *)getChildByTag(10001); @@ -273,11 +295,31 @@ void TestAsynchronousLoading::dataLoaded(float percent) } +void TestDirectLoading::onEnter() +{ + ArmatureTestLayer::onEnter(); + + // remove sigle resource + ArmatureDataManager::getInstance()->removeArmatureFileInfo("armature/bear.ExportJson"); + + // load resource directly + ArmatureDataManager::getInstance()->addArmatureFileInfo("armature/bear.ExportJson"); + + Armature *armature = Armature::create("bear"); + armature->getAnimation()->playByIndex(0); + armature->setPosition(Point(VisibleRect::center().x, VisibleRect::center().y)); + addChild(armature); +} +std::string TestDirectLoading::title() +{ + return "Test Direct Loading"; +} + void TestCSWithSkeleton::onEnter() { ArmatureTestLayer::onEnter(); - Armature *armature = NULL; + Armature *armature = nullptr; armature = Armature::create("Cowboy"); armature->getAnimation()->playByIndex(0); armature->setScale(0.2f); @@ -298,7 +340,7 @@ void TestDragonBones20::onEnter() { ArmatureTestLayer::onEnter(); - Armature *armature = NULL; + Armature *armature = nullptr; armature = Armature::create("Dragon"); armature->getAnimation()->playByIndex(1); armature->getAnimation()->setSpeedScale(0.4f); @@ -314,6 +356,8 @@ std::string TestDragonBones20::title() +#define ArmaturePerformanceTag 20000 + TestPerformance::~TestPerformance() { } @@ -321,10 +365,22 @@ void TestPerformance::onEnter() { ArmatureTestLayer::onEnter(); + + MenuItemFont::setFontSize(65); + MenuItemFont *decrease = MenuItemFont::create(" - ", CC_CALLBACK_1(TestPerformance::onDecrease, this)); + decrease->setColor(Color3B(0,200,20)); + MenuItemFont *increase = MenuItemFont::create(" + ", CC_CALLBACK_1(TestPerformance::onIncrease, this)); + increase->setColor(Color3B(0,200,20)); + + Menu *menu = Menu::create(decrease, increase, nullptr); + menu->alignItemsHorizontally(); + menu->setPosition(Point(VisibleRect::getVisibleRect().size.width/2, VisibleRect::getVisibleRect().size.height-100)); + addChild(menu, 10000); + armatureCount = frames = times = lastTimes = 0; generated = false; - scheduleUpdate(); + addArmature(100); } std::string TestPerformance::title() @@ -335,44 +391,83 @@ std::string TestPerformance::subtitle() { return "Current Armature Count : "; } -void TestPerformance::addArmature(Armature *armature) +void TestPerformance::onIncrease(Object* pSender) { - armatureCount++; - addChild(armature, armatureCount); + addArmature(20); } -void TestPerformance::update(float delta) +void TestPerformance::onDecrease(Object* pSender) { - frames ++; - times += delta; + if (armatureCount == 0) + return; - if (frames / times > 58) + for (int i = 0; i<20; i++) { - Armature *armature = NULL; + removeArmatureFromParent(ArmaturePerformanceTag + armatureCount); + armatureCount --; + refreshTitile(); + } +} +void TestPerformance::addArmature(int number) +{ + for (int i = 0; iinit("Knight_f/Knight"); armature->getAnimation()->playByIndex(0); armature->setPosition(50 + armatureCount * 2, 150); armature->setScale(0.6f); - addArmature(armature); + addArmatureToParent(armature); armature->release(); - - char pszCount[255]; - sprintf(pszCount, "%s %i", subtitle().c_str(), armatureCount); - LabelTTF *label = (LabelTTF *)getChildByTag(10001); - label->setString(pszCount); } + + refreshTitile(); +} +void TestPerformance::addArmatureToParent(cocostudio::Armature *armature) +{ + addChild(armature, 0, ArmaturePerformanceTag + armatureCount); +} +void TestPerformance::removeArmatureFromParent(int tag) +{ + removeChildByTag(ArmaturePerformanceTag + armatureCount); +} +void TestPerformance::refreshTitile() +{ + char pszCount[255]; + sprintf(pszCount, "%s %i", subtitle().c_str(), armatureCount); + LabelTTF *label = (LabelTTF *)getChildByTag(10001); + label->setString(pszCount); } +void TestPerformanceBatchNode::onEnter() +{ + batchNode = BatchNode::create(); + addChild(batchNode); - + TestPerformance::onEnter(); +} +std::string TestPerformanceBatchNode::title() +{ + return "Test Performance of using BatchNode"; +} +void TestPerformanceBatchNode::addArmatureToParent(cocostudio::Armature *armature) +{ + batchNode->addChild(armature, 0, ArmaturePerformanceTag + armatureCount); +} +void TestPerformanceBatchNode::removeArmatureFromParent(int tag) +{ + batchNode->removeChildByTag(ArmaturePerformanceTag + armatureCount); +} void TestChangeZorder::onEnter() { ArmatureTestLayer::onEnter(); - Armature *armature = NULL; + Armature *armature = nullptr; currentTag = -1; armature = Armature::create("Knight_f/Knight"); @@ -429,7 +524,7 @@ void TestAnimationEvent::onEnter() /* * Set armature's movement event callback function - * To disconnect this event, just setMovementEventCallFunc(NULL, NULL); + * To disconnect this event, just setMovementEventCallFunc(nullptr, nullptr); */ armature->getAnimation()->setMovementEventCallFunc(this, movementEvent_selector(TestAnimationEvent::animationEvent)); addChild(armature); @@ -448,14 +543,14 @@ void TestAnimationEvent::animationEvent(Armature *armature, MovementEventType mo { ActionInterval *actionToRight = MoveTo::create(2, Point(VisibleRect::right().x - 50, VisibleRect::right().y)); armature->stopAllActions(); - armature->runAction(Sequence::create(actionToRight, CallFunc::create( CC_CALLBACK_0(TestAnimationEvent::callback1, this)), NULL)); + armature->runAction(Sequence::create(actionToRight, CallFunc::create( CC_CALLBACK_0(TestAnimationEvent::callback1, this)), nullptr)); armature->getAnimation()->play("Walk"); } else if (id.compare("FireMax") == 0) { ActionInterval *actionToLeft = MoveTo::create(2, Point(VisibleRect::left().x + 50, VisibleRect::left().y)); armature->stopAllActions(); - armature->runAction(Sequence::create(actionToLeft, CallFunc::create( CC_CALLBACK_0(TestAnimationEvent::callback2, this)), NULL)); + armature->runAction(Sequence::create(actionToLeft, CallFunc::create( CC_CALLBACK_0(TestAnimationEvent::callback2, this)), nullptr)); armature->getAnimation()->play("Walk"); } } @@ -473,6 +568,51 @@ void TestAnimationEvent::callback2() +#define FRAME_EVENT_ACTION_TAG 10000 + +void TestFrameEvent::onEnter() +{ + ArmatureTestLayer::onEnter(); + Armature *armature = Armature::create("HeroAnimation"); + armature->getAnimation()->play("attack"); + armature->getAnimation()->setSpeedScale(0.5); + armature->setPosition(Point(VisibleRect::center().x - 50, VisibleRect::center().y -100)); + + /* + * Set armature's frame event callback function + * To disconnect this event, just setFrameEventCallFunc(nullptr, nullptr); + */ + armature->getAnimation()->setFrameEventCallFunc(this, frameEvent_selector(TestFrameEvent::onFrameEvent)); + + addChild(armature); + + schedule( schedule_selector(TestFrameEvent::checkAction) ); +} +std::string TestFrameEvent::title() +{ + return "Test Frame Event"; +} +void TestFrameEvent::onFrameEvent(Bone *bone, const char *evt, int originFrameIndex, int currentFrameIndex) +{ + CCLOG("(%s) emit a frame event (%s) at frame index (%d).", bone->getName().c_str(), evt, currentFrameIndex); + + + if (!this->getActionByTag(FRAME_EVENT_ACTION_TAG) || this->getActionByTag(FRAME_EVENT_ACTION_TAG)->isDone()) + { + this->stopAllActions(); + + ActionInterval *action = ShatteredTiles3D::create(0.2f, Size(16,12), 5, false); + action->setTag(FRAME_EVENT_ACTION_TAG); + this->runAction(action); + } +} +void TestFrameEvent::checkAction(float dt) +{ + if ( this->getNumberOfRunningActions() == 0 && this->getGrid() != nullptr) + this->setGrid(nullptr); +} + + void TestParticleDisplay::onEnter() { @@ -610,7 +750,7 @@ void TestColliderDetector::onEnter() /* * Set armature's frame event callback function - * To disconnect this event, just setFrameEventCallFunc(NULL, NULL); + * To disconnect this event, just setFrameEventCallFunc(nullptr, nullptr); */ armature->getAnimation()->setFrameEventCallFunc(this, frameEvent_selector(TestColliderDetector::onFrameEvent)); @@ -864,19 +1004,14 @@ void TestColliderDetector::initWorld() bullet->setCPBody(body); - body = cpBodyNew(INFINITY, INFINITY); + body = cpBodyNew(1.0f, INFINITY); cpSpaceAddBody(space, body); armature2->setBody(body); - shape = armature2->getShapeList(); - while(shape) - { - cpShape *next = shape->next_private; - shape->collision_type = eEnemyTag; - shape = next; - } + ColliderFilter filter = ColliderFilter(eEnemyTag); + armature2->setColliderFilter(&filter); - cpSpaceAddCollisionHandler(space, eEnemyTag, eBulletTag, beginHit, NULL, NULL, endHit, NULL); + cpSpaceAddCollisionHandler(space, eEnemyTag, eBulletTag, beginHit, nullptr, nullptr, endHit, nullptr); } #endif @@ -905,7 +1040,7 @@ void TestBoundingBox::draw() { CC_NODE_DRAW_SETUP(); - rect = RectApplyAffineTransform(armature->getBoundingBox(), armature->getNodeToParentTransform()); + rect = armature->getBoundingBox(); DrawPrimitives::setDrawColor4B(100, 100, 100, 255); DrawPrimitives::drawRect(rect.origin, Point(rect.getMaxX(), rect.getMaxY())); @@ -971,9 +1106,190 @@ void TestArmatureNesting::onTouchesEnded(const std::vector& touches, Eve ++weaponIndex; weaponIndex = weaponIndex % 4; - if(armature != NULL) + if(armature != nullptr) { armature->getBone("armInside")->getChildArmature()->getAnimation()->playByIndex(weaponIndex); armature->getBone("armOutside")->getChildArmature()->getAnimation()->playByIndex(weaponIndex); } } + + + + +Hero *Hero::create(const char *name) +{ + Hero *hero = new Hero(); + if (hero && hero->init(name)) + { + hero->autorelease(); + return hero; + } + CC_SAFE_DELETE(hero); + return nullptr; +} + +Hero::Hero() + : m_pMount(nullptr) + , m_pLayer(nullptr) +{ +} + +void Hero::changeMount(Armature *armature) +{ + if (armature == nullptr) + { + retain(); + + playByIndex(0); + //Remove hero from display list + m_pMount->getBone("hero")->removeDisplay(0); + m_pMount->stopAllActions(); + + //Set position to current position + setPosition(m_pMount->getPosition()); + //Add to layer + m_pLayer->addChild(this); + + release(); + + setMount(armature); + } + else + { + setMount(armature); + + retain(); + //Remove from layer + removeFromParentAndCleanup(false); + + //Get the hero bone + Bone *bone = armature->getBone("hero"); + //Add hero as a display to this bone + bone->addDisplay(this, 0); + //Change this bone's display + bone->changeDisplayByIndex(0, true); + bone->setIgnoreMovementBoneData(true); + + setPosition(Point(0,0)); + //Change animation + playByIndex(1); + + setScale(1); + + release(); + } + +} + +void Hero::playByIndex(int index) +{ + _animation->playByIndex(index); + if (m_pMount) + { + m_pMount->getAnimation()->playByIndex(index); + } +} + +void TestArmatureNesting2::onEnter() +{ + ArmatureTestLayer::onEnter(); + + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesEnded = CC_CALLBACK_2(TestArmatureNesting2::onTouchesEnded, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); + + touchedMenu = false; + + LabelTTF* label = CCLabelTTF::create("Change Mount", "Arial", 20); + MenuItemLabel* pMenuItem = CCMenuItemLabel::create(label, CC_CALLBACK_1(TestArmatureNesting2::ChangeMountCallback, this)); + + Menu* pMenu =Menu::create(pMenuItem, nullptr); + + pMenu->setPosition( Point() ); + pMenuItem->setPosition( Point( VisibleRect::right().x - 67, VisibleRect::bottom().y + 50) ); + + addChild(pMenu, 2); + + //Create a hero + hero = Hero::create("hero"); + hero->setLayer(this); + hero->playByIndex(0); + hero->setPosition(Point(VisibleRect::left().x + 20, VisibleRect::left().y)); + addChild(hero); + + //Create 3 mount + horse = createMount("horse", VisibleRect::center()); + + horse2 = createMount("horse", Point(120, 200)); + horse2->setOpacity(200); + + bear = createMount("bear", Point(300,70)); +} +void TestArmatureNesting2::onExit() +{ + ArmatureTestLayer::onExit(); +} +std::string TestArmatureNesting2::title() +{ + return "Test CCArmature Nesting 2"; +} +std::string TestArmatureNesting2::subtitle() +{ + return "Move to a mount and press the ChangeMount Button."; +} +void TestArmatureNesting2::onTouchesEnded(const std::vector& touches, Event* event) +{ + Point point = touches[0]->getLocation(); + + Armature *armature = hero->getMount() == nullptr ? hero : hero->getMount(); + + //Set armature direction + if (point.x < armature->getPositionX()) + { + armature->setScaleX(-1); + } + else + { + armature->setScaleX(1); + } + + ActionInterval *move = CCMoveTo::create(2, point); + armature->stopAllActions(); + armature->runAction(Sequence::create(move, nullptr)); +} + +void TestArmatureNesting2::ChangeMountCallback(Object* pSender) +{ + hero->stopAllActions(); + + if (hero->getMount()) + { + hero->changeMount(nullptr); + } + else + { + if (hero->getPosition().getDistance(horse->getPosition()) < 20) + { + hero->changeMount(horse); + } + else if (hero->getPosition().getDistance(horse2->getPosition()) < 20) + { + hero->changeMount(horse2); + } + else if (hero->getPosition().getDistance(bear->getPosition()) < 30) + { + hero->changeMount(bear); + } + } +} + +Armature * TestArmatureNesting2::createMount(const char *name, Point position) +{ + Armature *armature = Armature::create(name); + armature->getAnimation()->playByIndex(0); + armature->setPosition(position); + addChild(armature); + + return armature; +} + diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h index 51b47085b5..79e29b61dc 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h @@ -27,17 +27,21 @@ public: enum { TEST_ASYNCHRONOUS_LOADING = 0, + TEST_DIRECT_LOADING, TEST_COCOSTUDIO_WITH_SKELETON, TEST_DRAGON_BONES_2_0, TEST_PERFORMANCE, + TEST_PERFORMANCE_BATCHNODE, TEST_CHANGE_ZORDER, TEST_ANIMATION_EVENT, + TEST_FRAME_EVENT, TEST_PARTICLE_DISPLAY, TEST_USE_DIFFERENT_PICTURE, TEST_BCOLLIDER_DETECTOR, TEST_BOUDINGBOX, TEST_ANCHORPOINT, TEST_ARMATURE_NESTING, + TEST_ARMATURE_NESTING_2, TEST_LAYER_COUNT }; @@ -70,10 +74,18 @@ public: virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); + virtual void restartCallback(Object* pSender); void dataLoaded(float percent); }; +class TestDirectLoading : public ArmatureTestLayer +{ +public: + virtual void onEnter(); + virtual std::string title(); +}; + class TestCSWithSkeleton : public ArmatureTestLayer { virtual void onEnter(); @@ -97,8 +109,12 @@ public: virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); - virtual void addArmature(cocostudio::Armature *armature); - void update(float delta); + virtual void onIncrease(Object* pSender); + virtual void onDecrease(Object* pSender); + virtual void addArmature(int number); + virtual void addArmatureToParent(cocostudio::Armature *armature); + virtual void removeArmatureFromParent(int tag); + virtual void refreshTitile(); int armatureCount; @@ -108,6 +124,15 @@ public: bool generated; }; +class TestPerformanceBatchNode : public TestPerformance +{ + virtual void onEnter(); + virtual std::string title(); + virtual void addArmatureToParent(cocostudio::Armature *armature); + virtual void removeArmatureFromParent(int tag); + + cocostudio::BatchNode *batchNode; +}; class TestChangeZorder : public ArmatureTestLayer { @@ -132,6 +157,17 @@ public: cocostudio::Armature *armature; }; + +class TestFrameEvent : public ArmatureTestLayer +{ +public: + virtual void onEnter(); + virtual std::string title(); + void onFrameEvent(cocostudio::Bone *bone, const char *evt, int originFrameIndex, int currentFrameIndex); + void checkAction(float dt); +}; + + class TestUseMutiplePicture : public ArmatureTestLayer { virtual void onEnter(); @@ -256,4 +292,39 @@ public: cocostudio::Armature *armature; int weaponIndex; }; + +class Hero : public cocostudio::Armature +{ +public: + static Hero *create(const char *name); + Hero(); + + virtual void changeMount(cocostudio::Armature *armature); + virtual void playByIndex(int index); + + CC_SYNTHESIZE(cocostudio::Armature*, m_pMount, Mount); + CC_SYNTHESIZE(cocos2d::Layer*, m_pLayer, Layer); +}; + +class TestArmatureNesting2 : public ArmatureTestLayer +{ +public: + virtual void onEnter(); + virtual void onExit(); + virtual std::string title(); + virtual std::string subtitle(); + void onTouchesEnded(const std::vector& touches, Event* event); + + virtual void ChangeMountCallback(Object* pSender); + virtual cocostudio::Armature *createMount(const char *name, Point position); + + Hero *hero; + + cocostudio::Armature *horse; + cocostudio::Armature *horse2; + cocostudio::Armature *bear; + + + bool touchedMenu; +}; #endif // __HELLOWORLD_SCENE_H__ \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp index 1ba28914df..43a15715c8 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp @@ -19,24 +19,13 @@ CocosGUITestScene::~CocosGUITestScene() { cocostudio::SceneReader::getInstance()->purgeSceneReader(); cocostudio::ActionManagerEx::purgeActionManager(); - gui::UIHelper::purgeUIHelper(); } void CocosGUITestScene::runThisTest() { Director::getInstance()->replaceScene(this); - - ul = UILayer::create(); - ul->scheduleUpdate(); - this->addChild(ul); - - /* - Layout* layout = static_cast(CCUIHELPER->createWidgetFromJsonFile("cocosgui/UI/UI01.json")); - ul->addWidget(layout); - */ - -// /* + Size s = CCDirector::getInstance()->getWinSize(); _itemMenu = CCMenu::create(); @@ -57,7 +46,6 @@ void CocosGUITestScene::runThisTest() } void CocosGUITestScene::MainMenuCallback(Object* pSender) { - ul->removeFromParent(); ExtensionsTestScene *pScene = new ExtensionsTestScene(); pScene->runThisTest(); pScene->release(); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp index e80ff2fd01..dacec9ba84 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp @@ -44,78 +44,25 @@ bool UIDragPanelTest::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); - - // Create the dragpanel - UIDragPanel* dragPanel = UIDragPanel::create(); - dragPanel->setTouchEnabled(true); - dragPanel->setBackGroundImageScale9Enabled(true); - dragPanel->setBackGroundImage("cocosgui/scrollviewbg.png"); - dragPanel->setSize(Size(210, 122.5)); - Size backgroundSize = background->getContentSize(); - dragPanel->setPosition(Point((widgetSize.width - backgroundSize.width) / 2 + - (backgroundSize.width - dragPanel->getSize().width) / 2, - (widgetSize.height - backgroundSize.height) / 2 + - (backgroundSize.height - dragPanel->getSize().height) / 2)); - dragPanel->addEventListener(this, dragpaneleventselector(UIDragPanelTest::dragPanelEvent)); - - UIImageView* imageView = UIImageView::create(); - imageView->setTouchEnabled(true); - imageView->loadTexture("cocosgui/b11.png"); - dragPanel->addChild(imageView); - - dragPanel->setInnerContainerSize(imageView->getContentSize()); - Size innerSize = dragPanel->getInnerContainerSize(); - imageView->setPosition(Point(innerSize.width / 2, innerSize.height / 2)); - - m_pUiLayer->addWidget(dragPanel); + UIScrollView* sc = UIScrollView::create(); + sc->setBackGroundColor(Color3B::GREEN); + sc->setBackGroundColorType(LAYOUT_COLOR_SOLID); + sc->setDirection(SCROLLVIEW_DIR_BOTH); + sc->setInnerContainerSize(Size(480, 320)); + sc->setSize(Size(100,100)); + sc->setPosition(Point(100,100)); + sc->scrollToPercentBothDirection(Point(50, 50), 1, true); + UIImageView* iv = UIImageView::create(); + iv->loadTexture("cocosgui/Hello.png"); + iv->setPosition(Point(240, 160)); + sc->addChild(iv); + m_pUiLayer->addWidget(sc); return true; } return false; } -void UIDragPanelTest::dragPanelEvent(Object *pSender, DragPanelEventType type) -{ - switch (type) - { - case DRAGPANEL_EVENT_BERTH_LEFTBOTTOM: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Left Bottom")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_LFETTOP: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Left Top")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_RIGHTBOTTOM: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Right Bottom")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_RIGHTTOP: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Right Top")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_LEFT: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Left")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_TOP: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Top")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_RIGHT: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Right")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_BOTTOM: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Bottom")->getCString()); - break; - - default: - break; - } -} - // UIDragPanelTest_Bounce UIDragPanelTest_Bounce::UIDragPanelTest_Bounce() : m_pDisplayValueLabel(NULL) @@ -151,76 +98,23 @@ bool UIDragPanelTest_Bounce::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); - - // Create the dragpanel - UIDragPanel* dragPanel = UIDragPanel::create(); - dragPanel->setTouchEnabled(true); - dragPanel->setBounceEnable(true); - dragPanel->setBackGroundImageScale9Enabled(true); - dragPanel->setBackGroundImage("cocosgui/green_edit.png"); - dragPanel->setSize(Size(210, 122.5)); - Size backgroundSize = background->getContentSize(); - dragPanel->setPosition(Point((widgetSize.width - backgroundSize.width) / 2 + - (backgroundSize.width - dragPanel->getSize().width) / 2, - (widgetSize.height - backgroundSize.height) / 2 + - (backgroundSize.height - dragPanel->getSize().height) / 2)); - dragPanel->addEventListener(this, dragpaneleventselector(UIDragPanelTest_Bounce::dragPanelEvent)); - - UIImageView* imageView = UIImageView::create(); - imageView->setTouchEnabled(true); - imageView->loadTexture("cocosgui/b11.png"); - dragPanel->addChild(imageView); - - dragPanel->setInnerContainerSize(imageView->getContentSize()); - Size innerSize = dragPanel->getInnerContainerSize(); - imageView->setPosition(Point(innerSize.width / 2, innerSize.height / 2)); - - m_pUiLayer->addWidget(dragPanel); - + UIScrollView* sc = UIScrollView::create(); + sc->setBackGroundColor(Color3B::GREEN); + sc->setBackGroundColorType(LAYOUT_COLOR_SOLID); + sc->setBounceEnabled(true); + sc->setDirection(SCROLLVIEW_DIR_BOTH); + sc->setInnerContainerSize(Size(480, 320)); + sc->setSize(Size(100,100)); + sc->setPosition(Point(100,100)); + sc->scrollToPercentBothDirection(Point(50, 50), 1, true); + UIImageView* iv = UIImageView::create(); + iv->loadTexture("cocosgui/Hello.png"); + iv->setPosition(Point(240, 160)); + sc->addChild(iv); + m_pUiLayer->addWidget(sc); return true; } return false; } -void UIDragPanelTest_Bounce::dragPanelEvent(Object *pSender, DragPanelEventType type) -{ - switch (type) - { - case DRAGPANEL_EVENT_BOUNCE_LEFTBOTTOM: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Left Bottom")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_LEFTTOP: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Left Top")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_RIGHTBOTTOM: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Right Bottom")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_RIGHTTOP: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Right Top")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_LEFT: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Left")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_TOP: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Top")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_RIGHT: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Right")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_BOTTOM: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Bottom")->getCString()); - break; - - default: - break; - } -} diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.h index 76f8469154..b8967247f3 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.h @@ -33,7 +33,6 @@ public: UIDragPanelTest(); ~UIDragPanelTest(); bool init(); - void dragPanelEvent(Object* pSender, DragPanelEventType type); protected: UI_SCENE_CREATE_FUNC(UIDragPanelTest) @@ -46,7 +45,6 @@ public: UIDragPanelTest_Bounce(); ~UIDragPanelTest_Bounce(); bool init(); - void dragPanelEvent(Object* pSender, DragPanelEventType type); protected: UI_SCENE_CREATE_FUNC(UIDragPanelTest_Bounce) diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp index 6681c744ee..c2163e8059 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp @@ -45,54 +45,23 @@ bool UIListViewTest_Vertical::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); - // Create the list view - m_nCount = 0; - m_array = CCArray::create(); - m_array->retain(); - for (int i = 0; i < 20; ++i) + UIListView* lv = UIListView::create(); + UIButton* model = UIButton::create(); + model->loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", ""); + lv->setItemModel(model); + + for (int i=0; i<20; i++) { - String* ccstr = String::createWithFormat("object_%d", i); - m_array->addObject(ccstr); + lv->pushBackDefaultItem(); } - - UIListView *listView = UIListView::create(); - listView->setTouchEnabled(true); - listView->setBackGroundImageScale9Enabled(true); - listView->setBackGroundImage("cocosgui/green_edit.png"); - listView->setSize(Size(240, 130)); - Size backgroundSize = background->getContentSize(); - listView->setPosition(Point((widgetSize.width - backgroundSize.width) / 2 + - (backgroundSize.width - listView->getSize().width) / 2, - (widgetSize.height - backgroundSize.height) / 2 + - (backgroundSize.height - listView->getSize().height) / 2)); - - float listWidth = listView->getSize().width; - float listHeight = listView->getSize().height; - - for (int i = 0; i < 5; ++i) - { - UIButton* textButton = UIButton::create(); - textButton->setName("TextButton"); - textButton->setTouchEnabled(true); - textButton->loadTextures("cocosgui/backtotoppressed.png", "cocosgui/backtotopnormal.png", ""); - - Layout *layout = Layout::create(); - layout->setName(String::createWithFormat("panel_%i", i)->getCString()); - layout->setSize(Size(textButton->getSize().width, textButton->getSize().height)); - textButton->setPosition(Point(layout->getSize().width / 2, layout->getSize().height / 2)); - layout->addChild(textButton); - - Size panel_size = layout->getSize(); - layout->setPosition(Point((listWidth - panel_size.width) / 2, - (listHeight - (panel_size.height + panel_size.height * 0.25)) - i * (panel_size.height + panel_size.height * 0.25))); - - listView->addChild(layout); - } - listView->addEventListenter(this, listvieweventselector(UIListViewTest_Vertical::listViewEvent)); - listView->initChildWithDataLength(m_array->count()); - m_pUiLayer->addWidget(listView); + lv->setItemsMargin(10); + lv->setGravity(LISTVIEW_GRAVITY_CENTER_HORIZONTAL); + lv->setSize(Size(100, 100)); + lv->setBackGroundColorType(LAYOUT_COLOR_SOLID); + lv->setBackGroundColor(Color3B::GREEN); + lv->setPosition(Point(100, 100)); + m_pUiLayer->addWidget(lv); return true; } @@ -100,46 +69,6 @@ bool UIListViewTest_Vertical::init() return false; } -void UIListViewTest_Vertical::listViewEvent(Object *pSender, ListViewEventType type) -{ - switch (type) - { - case LISTVIEW_EVENT_INIT_CHILD: - { - String* ccstr = static_cast(m_array->getObjectAtIndex(m_nCount)); - UIListView* list = dynamic_cast(pSender); - - Layout* layout = dynamic_cast(list->getUpdateChild()); - UIButton* textButton = dynamic_cast(layout->getChildByName("TextButton")); - textButton->setTitleText(ccstr->getCString()); - - m_nCount++; - } - break; - - case LISTVIEW_EVENT_UPDATE_CHILD: - { - UIListView* list = dynamic_cast(pSender); - int index = list->getUpdateDataIndex(); - - if (index < 0 || index >= list->getDataLength()) - { - list->setUpdateSuccess(false); - } - - String* ccstr = static_cast(m_array->getObjectAtIndex(index)); - Layout* layout = dynamic_cast(list->getUpdateChild()); - UIButton* textButton = dynamic_cast(layout->getChildByName("TextButton")); - textButton->setTitleText(ccstr->getCString()); - list->setUpdateSuccess(true); - } - break; - - default: - break; - } -} - // UIListViewTest_Horizontal UIListViewTest_Horizontal::UIListViewTest_Horizontal() @@ -176,97 +105,26 @@ bool UIListViewTest_Horizontal::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + + UIListView* lv = UIListView::create(); + lv->setDirection(SCROLLVIEW_DIR_HORIZONTAL); + UIButton* model = UIButton::create(); + model->loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", ""); + lv->setItemModel(model); - // Create the list view - m_nCount = 0; - m_array = CCArray::create(); - m_array->retain(); - for (int i = 0; i < 20; ++i) + for (int i=0; i<20; i++) { - String* ccstr = String::createWithFormat("object_%d", i); - m_array->addObject(ccstr); + lv->pushBackDefaultItem(); } - - UIListView *listView = UIListView::create(); - listView->setDirection(LISTVIEW_DIR_HORIZONTAL); - listView->setTouchEnabled(true); - listView->setBackGroundImageScale9Enabled(true); - listView->setBackGroundImage("cocosgui/green_edit.png"); - listView->setSize(Size(240, 130)); - Size backgroundSize = background->getContentSize(); - listView->setPosition(Point((widgetSize.width - backgroundSize.width) / 2 + - (backgroundSize.width - listView->getSize().width) / 2, - (widgetSize.height - backgroundSize.height) / 2 + - (backgroundSize.height - listView->getSize().height) / 2)); - - float listHeight = listView->getSize().height; - - for (int i = 0; i < 3; ++i) - { - UIButton* textButton = UIButton::create(); - textButton->setName("TextButton"); - textButton->setTouchEnabled(true); - textButton->loadTextures("cocosgui/backtotoppressed.png", "cocosgui/backtotopnormal.png", ""); - - Layout *layout = Layout::create(); - layout->setName(String::createWithFormat("panel_%i", i)->getCString()); - layout->setSize(Size(textButton->getSize().width, textButton->getSize().height)); - textButton->setPosition(Point(layout->getSize().width / 2, layout->getSize().height / 2)); - layout->addChild(textButton); - - Size layout_size = layout->getSize(); - layout->setPosition(Point(0 + (layout_size.width * 0.2) + i * (layout_size.width + layout_size.width * 0.2), - (listHeight - layout_size.height) / 2)); - - listView->addChild(layout); - } - listView->addEventListenter(this, listvieweventselector(UIListViewTest_Horizontal::listViewEvent)); - listView->initChildWithDataLength(m_array->count()); - m_pUiLayer->addWidget(listView); - + lv->setItemsMargin(10); + lv->setGravity(LISTVIEW_GRAVITY_CENTER_VERTICAL); + lv->setSize(Size(100, 100)); + lv->setBackGroundColorType(LAYOUT_COLOR_SOLID); + lv->setBackGroundColor(Color3B::GREEN); + lv->setPosition(Point(100, 100)); + m_pUiLayer->addWidget(lv); return true; } return false; -} - -void UIListViewTest_Horizontal::listViewEvent(Object *pSender, ListViewEventType type) -{ - switch (type) - { - case LISTVIEW_EVENT_INIT_CHILD: - { - String* ccstr = static_cast(m_array->getObjectAtIndex(m_nCount)); - UIListView* list = dynamic_cast(pSender); - - Layout* layout = dynamic_cast(list->getUpdateChild()); - UIButton* textButton = dynamic_cast(layout->getChildByName("TextButton")); - textButton->setTitleText(ccstr->getCString()); - - m_nCount++; - } - break; - - case LISTVIEW_EVENT_UPDATE_CHILD: - { - UIListView* list = dynamic_cast(pSender); - int index = list->getUpdateDataIndex(); - - if (index < 0 || index >= list->getDataLength()) - { - list->setUpdateSuccess(false); - } - - String* ccstr = static_cast(m_array->getObjectAtIndex(index)); - Layout* layout = dynamic_cast(list->getUpdateChild()); - UIButton* textButton = dynamic_cast(layout->getChildByName("TextButton")); - textButton->setTitleText(ccstr->getCString()); - list->setUpdateSuccess(true); - } - break; - - default: - break; - } -} +} \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.h index b2725e33ee..4dee33553c 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.h @@ -33,7 +33,6 @@ public: UIListViewTest_Vertical(); ~UIListViewTest_Vertical(); bool init(); - void listViewEvent(Object* pSender, ListViewEventType type); protected: UI_SCENE_CREATE_FUNC(UIListViewTest_Vertical) @@ -49,7 +48,6 @@ public: UIListViewTest_Horizontal(); ~UIListViewTest_Horizontal(); bool init(); - void listViewEvent(Object* pSender, ListViewEventType type); protected: UI_SCENE_CREATE_FUNC(UIListViewTest_Horizontal) diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp index 18b150ef6d..f031bc87e8 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp @@ -67,20 +67,29 @@ void UILoadingBarTest_Left::update(float delta) void UILoadingBarTest_Left::previousCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::previousCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::previousCallback(sender, type); + } } void UILoadingBarTest_Left::restartCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::restartCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::restartCallback(sender, type); + } } void UILoadingBarTest_Left::nextCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::nextCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::nextCallback(sender, type); + } } // UILoadingBarTest_Right @@ -142,20 +151,29 @@ void UILoadingBarTest_Right::update(float delta) void UILoadingBarTest_Right::previousCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::previousCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::previousCallback(sender, type); + } } void UILoadingBarTest_Right::restartCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::restartCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::restartCallback(sender, type); + } } void UILoadingBarTest_Right::nextCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::nextCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::nextCallback(sender, type); + } } // UILoadingBarTest_Left_Scale9 @@ -219,20 +237,29 @@ void UILoadingBarTest_Left_Scale9::update(float delta) void UILoadingBarTest_Left_Scale9::previousCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::previousCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::previousCallback(sender, type); + } } void UILoadingBarTest_Left_Scale9::restartCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::restartCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::restartCallback(sender, type); + } } void UILoadingBarTest_Left_Scale9::nextCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::nextCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::nextCallback(sender, type); + } } // UILoadingBarTest_Right_Scale9 @@ -290,22 +317,34 @@ void UILoadingBarTest_Right_Scale9::update(float delta) { m_nCount = 0; } - + CCLOG("wocao"); UILoadingBar* loadingBar = dynamic_cast(m_pUiLayer->getWidgetByName("LoadingBar")); loadingBar->setPercent(m_nCount); } void UILoadingBarTest_Right_Scale9::previousCallback(Object* sender, TouchEventType type) { - UIScene::previousCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::previousCallback(sender, type); + } } void UILoadingBarTest_Right_Scale9::restartCallback(Object* sender, TouchEventType type) { - UIScene::restartCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::restartCallback(sender, type); + } } void UILoadingBarTest_Right_Scale9::nextCallback(Object* sender, TouchEventType type) { - UIScene::nextCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::nextCallback(sender, type); + } } \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp index 22b97ef9e6..ce5028ae35 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp @@ -44,7 +44,7 @@ bool UIPageViewTest::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the page view UIPageView* pageView = UIPageView::create(); @@ -58,7 +58,7 @@ bool UIPageViewTest::init() for (int i = 0; i < 3; ++i) { - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setSize(Size(240, 130)); UIImageView* imageView = UIImageView::create(); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp index 49674298bc..94dbb02819 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp @@ -34,10 +34,10 @@ bool UIPanelTest::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setSize(Size(280, 150)); Size backgroundSize = background->getSize(); layout->setPosition(Point((widgetSize.width - backgroundSize.width) / 2 + @@ -98,10 +98,10 @@ bool UIPanelTest_Color::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout with color render - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setBackGroundColorType(LAYOUT_COLOR_SOLID); layout->setBackGroundColor(Color3B(128, 128, 128)); layout->setSize(Size(280, 150)); @@ -163,10 +163,10 @@ bool UIPanelTest_Gradient::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout with gradient render - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setBackGroundColorType(LAYOUT_COLOR_GRADIENT); layout->setBackGroundColor(Color3B(64, 64, 64), Color3B(192, 192, 192)); layout->setSize(Size(280, 150)); @@ -228,10 +228,10 @@ bool UIPanelTest_BackGroundImage::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout with background image - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setClippingEnabled(true); layout->setBackGroundImage("cocosgui/Hello.png"); layout->setSize(Size(280, 150)); @@ -293,10 +293,10 @@ bool UIPanelTest_BackGroundImage_Scale9::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout with background image - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setBackGroundImageScale9Enabled(true); layout->setBackGroundImage("cocosgui/green_edit.png"); layout->setSize(Size(280, 150)); @@ -358,10 +358,10 @@ bool UIPanelTest_Layout_Linear_Vertical::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setLayoutType(LAYOUT_LINEAR_VERTICAL); layout->setSize(Size(280, 150)); Size backgroundSize = background->getSize(); @@ -377,7 +377,7 @@ bool UIPanelTest_Layout_Linear_Vertical::init() button->loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", ""); layout->addChild(button); - LinearLayoutParameter* lp1 = LinearLayoutParameter::create(); + UILinearLayoutParameter* lp1 = UILinearLayoutParameter::create(); button->setLayoutParameter(lp1); lp1->setGravity(LINEAR_GRAVITY_CENTER_HORIZONTAL); lp1->setMargin(UIMargin(0, 5, 0, 10)); @@ -389,7 +389,7 @@ bool UIPanelTest_Layout_Linear_Vertical::init() textButton->setTitleText("Text Button"); layout->addChild(textButton); - LinearLayoutParameter* lp2 = LinearLayoutParameter::create(); + UILinearLayoutParameter* lp2 = UILinearLayoutParameter::create(); textButton->setLayoutParameter(lp2); lp2->setGravity(LINEAR_GRAVITY_CENTER_HORIZONTAL); lp2->setMargin(UIMargin(0, 10, 0, 10)); @@ -402,7 +402,7 @@ bool UIPanelTest_Layout_Linear_Vertical::init() button_scale9->setSize(Size(100, button_scale9->getContentSize().height)); layout->addChild(button_scale9); - LinearLayoutParameter* lp3 = LinearLayoutParameter::create(); + UILinearLayoutParameter* lp3 = UILinearLayoutParameter::create(); button_scale9->setLayoutParameter(lp3); lp3->setGravity(LINEAR_GRAVITY_CENTER_HORIZONTAL); lp3->setMargin(UIMargin(0, 10, 0, 10)); @@ -441,10 +441,10 @@ bool UIPanelTest_Layout_Linear_Horizontal::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setLayoutType(LAYOUT_LINEAR_HORIZONTAL); layout->setClippingEnabled(true); layout->setSize(Size(280, 150)); @@ -460,7 +460,7 @@ bool UIPanelTest_Layout_Linear_Horizontal::init() button->loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", ""); layout->addChild(button); - LinearLayoutParameter* lp1 = LinearLayoutParameter::create(); + UILinearLayoutParameter* lp1 = UILinearLayoutParameter::create(); button->setLayoutParameter(lp1); lp1->setGravity(LINEAR_GRAVITY_CENTER_VERTICAL); lp1->setMargin(UIMargin(0, 10, 0, 10)); @@ -472,7 +472,7 @@ bool UIPanelTest_Layout_Linear_Horizontal::init() textButton->setTitleText("Text Button"); layout->addChild(textButton); - LinearLayoutParameter* lp2 = LinearLayoutParameter::create(); + UILinearLayoutParameter* lp2 = UILinearLayoutParameter::create(); textButton->setLayoutParameter(lp2); lp2->setGravity(LINEAR_GRAVITY_CENTER_VERTICAL); lp2->setMargin(UIMargin(0, 10, 0, 10)); @@ -485,7 +485,7 @@ bool UIPanelTest_Layout_Linear_Horizontal::init() button_scale9->setSize(Size(100, button_scale9->getContentSize().height)); layout->addChild(button_scale9); - LinearLayoutParameter* lp3 = LinearLayoutParameter::create(); + UILinearLayoutParameter* lp3 = UILinearLayoutParameter::create(); button_scale9->setLayoutParameter(lp3); lp3->setGravity(LINEAR_GRAVITY_CENTER_VERTICAL); lp3->setMargin(UIMargin(0, 10, 0, 10)); @@ -524,10 +524,10 @@ bool UIPanelTest_Layout_Relative::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setLayoutType(LAYOUT_RELATIVE); layout->setSize(Size(280, 150)); layout->setBackGroundColorType(LAYOUT_COLOR_SOLID); @@ -544,9 +544,9 @@ bool UIPanelTest_Layout_Relative::init() button->loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", ""); layout->addChild(button); - RelativeLayoutParameter* rp1 = RelativeLayoutParameter::create(); + UIRelativeLayoutParameter* rp1 = UIRelativeLayoutParameter::create(); button->setLayoutParameter(rp1); - rp1->setAlign(RELATIVE_ALIGN_PARENT_BOTTOM); + rp1->setAlign(RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL); // rp1->setMargin(UIMargin(0, 10, 0, 10)); @@ -556,9 +556,9 @@ bool UIPanelTest_Layout_Relative::init() textButton->setTitleText("Text Button"); layout->addChild(textButton); - RelativeLayoutParameter* rp2 = RelativeLayoutParameter::create(); + UIRelativeLayoutParameter* rp2 = UIRelativeLayoutParameter::create(); textButton->setLayoutParameter(rp2); - rp2->setAlign(RELATIVE_ALIGN_PARENT_LEFT); + rp2->setAlign(RELATIVE_ALIGN_PARENT_LEFT_BOTTOM); UIButton* button_scale9 = UIButton::create(); @@ -568,9 +568,9 @@ bool UIPanelTest_Layout_Relative::init() button_scale9->setSize(Size(100, button_scale9->getContentSize().height)); layout->addChild(button_scale9); - RelativeLayoutParameter* rp3 = RelativeLayoutParameter::create(); + UIRelativeLayoutParameter* rp3 = UIRelativeLayoutParameter::create(); textButton->setLayoutParameter(rp3); - rp3->setAlign(RELATIVE_ALIGN_PARENT_RIGHT); + rp3->setAlign(RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM); layout->doLayout(); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp index a57787dfb1..a2a3ddcf42 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp @@ -3,6 +3,7 @@ #include "UIScene.h" #include "UISceneManager.h" #include "../ExtensionsTest.h" +#include "editor-support/cocostudio/CCSGUIReader.h" using namespace gui; @@ -25,7 +26,7 @@ bool UIScene::init() m_pUiLayer = UILayer::create(); addChild(m_pUiLayer); - m_pWidget = dynamic_cast(CCUIHELPER->createWidgetFromJsonFile("cocosgui/UITest/UITest.json")); + m_pWidget = dynamic_cast(cocostudio::CCSGUIReader::shareReader()->widgetFromJsonFile("cocosgui/UITest/UITest.json")); m_pUiLayer->addWidget(m_pWidget); m_pSceneTitle = dynamic_cast(m_pUiLayer->getWidgetByName("UItest")); @@ -63,6 +64,7 @@ void UIScene::menuCloseCallback(Object* pSender, TouchEventType type) { if (type == TOUCH_EVENT_ENDED) { + m_pUiLayer->removeFromParent(); auto scene = new ExtensionsTestScene(); scene->runThisTest(); scene->release(); @@ -73,6 +75,7 @@ void UIScene::previousCallback(Object* sender, TouchEventType type) { if (type == TOUCH_EVENT_ENDED) { + m_pUiLayer->removeFromParent(); CCDirector::getInstance()->replaceScene(UISceneManager::sharedUISceneManager()->previousUIScene()); } } @@ -81,6 +84,7 @@ void UIScene::restartCallback(Object* sender, TouchEventType type) { if (type == TOUCH_EVENT_ENDED) { + m_pUiLayer->removeFromParent(); CCDirector::getInstance()->replaceScene(UISceneManager::sharedUISceneManager()->currentUIScene()); } } @@ -89,6 +93,7 @@ void UIScene::nextCallback(Object* sender, TouchEventType type) { if (type == TOUCH_EVENT_ENDED) { + m_pUiLayer->removeFromParent(); CCDirector::getInstance()->replaceScene(UISceneManager::sharedUISceneManager()->nextUIScene()); } } diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h index bf10ffa76b..720fdd4224 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h @@ -95,7 +95,7 @@ protected: protected: UILayer *m_pUiLayer; - Layout *m_pWidget; + UILayout *m_pWidget; }; #endif /* defined(__TestCpp__UIScene__) */ diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp index c7a13fd225..01b3b83278 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp @@ -44,7 +44,7 @@ bool UIScrollViewTest_Vertical::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the scrollview by vertical UIScrollView* scrollView = UIScrollView::create(); @@ -129,10 +129,11 @@ bool UIScrollViewTest_Horizontal::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the scrollview by horizontal - UIScrollView* scrollView = UIScrollView::create(); + UIScrollView* scrollView = UIScrollView::create(); + scrollView->setBounceEnabled(true); scrollView->setDirection(SCROLLVIEW_DIR_HORIZONTAL); scrollView->setTouchEnabled(true); scrollView->setSize(Size(280, 150)); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp index bba53b0444..c486c5be3a 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp @@ -82,7 +82,7 @@ void UITextFieldTest::textFieldEvent(Object *pSender, TextFiledEventType type) } break; - case TEXTFIELD_EVENT_INDERT_TEXT: + case TEXTFIELD_EVENT_INSERT_TEXT: m_pDisplayValueLabel->setText(CCString::createWithFormat("insert words")->getCString()); break; @@ -132,7 +132,7 @@ bool UITextFieldTest_MaxLength::init() // Create the textfield UITextField* textField = UITextField::create(); - textField->setMaxLengthEnable(true); + textField->setMaxLengthEnabled(true); textField->setMaxLength(3); textField->setTouchEnabled(true); textField->setFontName(font_UITextFieldTest); @@ -170,7 +170,7 @@ void UITextFieldTest_MaxLength::textFieldEvent(Object *pSender, TextFiledEventTy } break; - case TEXTFIELD_EVENT_INDERT_TEXT: + case TEXTFIELD_EVENT_INSERT_TEXT: { UITextField* textField = dynamic_cast(pSender); m_pDisplayValueLabel->setText(CCString::createWithFormat("insert words max length %d", textField->getMaxLength())->getCString()); @@ -226,7 +226,7 @@ bool UITextFieldTest_Password::init() // Create the textfield UITextField* textField = UITextField::create(); - textField->setPasswordEnable(true); + textField->setPasswordEnabled(true); textField->setPasswordStyleText("*"); textField->setTouchEnabled(true); textField->setFontName(font_UITextFieldTest); @@ -264,7 +264,7 @@ void UITextFieldTest_Password::textFieldEvent(Object *pSender, TextFiledEventTyp } break; - case TEXTFIELD_EVENT_INDERT_TEXT: + case TEXTFIELD_EVENT_INSERT_TEXT: m_pDisplayValueLabel->setText(CCString::createWithFormat("insert words password")->getCString()); break; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp index 0ce946c5a6..f7ddf0c777 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp @@ -14,7 +14,6 @@ SceneEditorTestLayer::~SceneEditorTestLayer() ArmatureDataManager::getInstance()->destoryInstance(); SceneReader::getInstance()->purgeSceneReader(); ActionManagerEx::shareManager()->purgeActionManager(); - UIHelper::instance()->purgeUIHelper(); } SceneEditorTestLayer::SceneEditorTestLayer() diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp index a7fe134383..d5914b2db1 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp @@ -110,6 +110,7 @@ ControlButton *ControlButtonTest_HelloVariableSize::standardButtonWithTitle(cons ControlButtonTest_Event::ControlButtonTest_Event() : _displayValueLabel(NULL) +, _displayBitmaskLabel(NULL) { } @@ -117,6 +118,7 @@ ControlButtonTest_Event::ControlButtonTest_Event() ControlButtonTest_Event::~ControlButtonTest_Event() { CC_SAFE_RELEASE_NULL(_displayValueLabel); + CC_SAFE_RELEASE_NULL(_displayBitmaskLabel); } bool ControlButtonTest_Event::init() @@ -130,7 +132,13 @@ bool ControlButtonTest_Event::init() _displayValueLabel->setAnchorPoint(Point(0.5f, -1)); _displayValueLabel->setPosition(Point(screenSize.width / 2.0f, screenSize.height / 2.0f)); addChild(_displayValueLabel, 1); - + + setDisplayBitmaskLabel(LabelTTF::create("No bitmask event", "Marker Felt", 24)); + _displayBitmaskLabel->setAnchorPoint(Point(0.5f, -1)); + Point bitmaskLabelPos = _displayValueLabel->getPosition() - Point(0, _displayBitmaskLabel->getBoundingBox().size.height); + _displayBitmaskLabel->setPosition(bitmaskLabelPos); + addChild(_displayBitmaskLabel, 1); + // Add the button auto backgroundButton = Scale9Sprite::create("extensions/button.png"); auto backgroundHighlightedButton = Scale9Sprite::create("extensions/buttonHighlighted.png"); @@ -162,11 +170,20 @@ bool ControlButtonTest_Event::init() controlButton->addTargetWithActionForControlEvents(this, cccontrol_selector(ControlButtonTest_Event::touchUpInsideAction), Control::EventType::TOUCH_UP_INSIDE); controlButton->addTargetWithActionForControlEvents(this, cccontrol_selector(ControlButtonTest_Event::touchUpOutsideAction), Control::EventType::TOUCH_UP_OUTSIDE); controlButton->addTargetWithActionForControlEvents(this, cccontrol_selector(ControlButtonTest_Event::touchCancelAction), Control::EventType::TOUCH_CANCEL); + // test for issue 2882 + controlButton->addTargetWithActionForControlEvents(this, cccontrol_selector(ControlButtonTest_Event::touchBitmaskAction), + Control::EventType::TOUCH_DOWN | Control::EventType::DRAG_INSIDE | Control::EventType::DRAG_OUTSIDE | Control::EventType::DRAG_ENTER | Control::EventType::DRAG_EXIT | Control::EventType::TOUCH_UP_INSIDE | Control::EventType::TOUCH_UP_OUTSIDE | Control::EventType::TOUCH_CANCEL | Control::EventType::VALUE_CHANGED); + return true; } return false; } +void ControlButtonTest_Event::touchBitmaskAction(Object *senderz, Control::EventType controlEvent) +{ + _displayBitmaskLabel->setString(String::createWithFormat("using bitmask (%d)", controlEvent)->getCString()); +} + void ControlButtonTest_Event::touchDownAction(Object *senderz, Control::EventType controlEvent) { _displayValueLabel->setString(String::createWithFormat("Touch Down")->getCString()); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.h index 6e4d602107..1efbf9c604 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.h @@ -54,8 +54,10 @@ public: void touchUpInsideAction(Object *sender, Control::EventType controlEvent); void touchUpOutsideAction(Object *sender, Control::EventType controlEvent); void touchCancelAction(Object *sender, Control::EventType controlEvent); + void touchBitmaskAction(Object *sender, Control::EventType controlEvent); protected: CC_SYNTHESIZE_RETAIN(LabelTTF *, _displayValueLabel, DisplayValueLabel) + CC_SYNTHESIZE_RETAIN(LabelTTF *, _displayBitmaskLabel, DisplayBitmaskLabel) CONTROL_SCENE_CREATE_FUNC(ControlButtonTest_Event) }; diff --git a/samples/Cpp/TestCpp/Classes/IntervalTest/IntervalTest.cpp b/samples/Cpp/TestCpp/Classes/IntervalTest/IntervalTest.cpp index da9fefdca9..3771b1e2aa 100644 --- a/samples/Cpp/TestCpp/Classes/IntervalTest/IntervalTest.cpp +++ b/samples/Cpp/TestCpp/Classes/IntervalTest/IntervalTest.cpp @@ -16,7 +16,7 @@ IntervalLayer::IntervalLayer() auto s = Director::getInstance()->getWinSize(); // sun auto sun = ParticleSun::create(); - sun->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + sun->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); sun->setPosition( Point(VisibleRect::rightTop().x-32,VisibleRect::rightTop().y-32) ); sun->setTotalParticles(130); diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp index 82a8a6ebcb..1b2655680f 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp @@ -359,7 +359,7 @@ void StressTest1::shouldNotCrash(float dt) // if the node has timers, it crashes auto explosion = ParticleSun::create(); - explosion->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + explosion->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); // if it doesn't, it works Ok. // auto explosion = [Sprite create:@"grossinis_sister2.png"); @@ -409,7 +409,7 @@ StressTest2::StressTest2() sublayer->addChild(sp1, 1); auto fire = ParticleFire::create(); - fire->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + fire->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); fire->setPosition( Point(80, s.height/2-50) ); auto copy_seq3 = seq3->clone(); diff --git a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp index d238482244..c4e3b15bad 100644 --- a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp @@ -22,7 +22,7 @@ void DemoFirework::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_stars1) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars1) ); setEmitterPosition(); } @@ -46,7 +46,7 @@ void DemoFire::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) );//.pvr"); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) );//.pvr"); auto p = _emitter->getPosition(); _emitter->setPosition( Point(p.x, 100) ); @@ -71,7 +71,7 @@ void DemoSun::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); setEmitterPosition(); } @@ -94,7 +94,7 @@ void DemoGalaxy::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); setEmitterPosition(); } @@ -116,7 +116,7 @@ void DemoFlower::onEnter() _emitter = ParticleFlower::create(); _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_stars1) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars1) ); setEmitterPosition(); } @@ -141,7 +141,7 @@ void DemoBigFlower::onEnter() _background->addChild(_emitter, 10); ////_emitter->release(); // win32 : use this line or remove this line and use autorelease() - _emitter->setTexture( TextureCache::getInstance()->addImage(s_stars1) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars1) ); _emitter->setDuration(-1); @@ -225,7 +225,7 @@ void DemoRotFlower::onEnter() _background->addChild(_emitter, 10); ////_emitter->release(); // win32 : Remove this line - _emitter->setTexture( TextureCache::getInstance()->addImage(s_stars2) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars2) ); // duration _emitter->setDuration(-1); @@ -308,7 +308,7 @@ void DemoMeteor::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); setEmitterPosition(); } @@ -331,7 +331,7 @@ void DemoSpiral::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); setEmitterPosition(); } @@ -354,7 +354,7 @@ void DemoExplosion::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_stars1) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars1) ); _emitter->setAutoRemoveOnFinish(true); @@ -378,7 +378,7 @@ void DemoSmoke::onEnter() _emitter = ParticleSmoke::create(); _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); auto p = _emitter->getPosition(); _emitter->setPosition( Point( p.x, 100) ); @@ -429,7 +429,7 @@ void DemoSnow::onEnter() _emitter->setEmissionRate(_emitter->getTotalParticles()/_emitter->getLife()); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_snow) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_snow) ); setEmitterPosition(); } @@ -456,7 +456,7 @@ void DemoRain::onEnter() _emitter->setPosition( Point( p.x, p.y-100) ); _emitter->setLife(4); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); setEmitterPosition(); } @@ -540,7 +540,7 @@ void DemoModernArt::onEnter() _emitter->setEndSizeVar(8.0f); // texture - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); // additive _emitter->setBlendAdditive(false); @@ -567,7 +567,7 @@ void DemoRing::onEnter() _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_stars1) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars1) ); _emitter->setLifeVar(0); _emitter->setLife(10); _emitter->setSpeed(100); @@ -605,14 +605,14 @@ void ParallaxParticle::onEnter() _emitter = ParticleFlower::create(); _emitter->retain(); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); p1->addChild(_emitter, 10); _emitter->setPosition( Point(250,200) ); auto par = ParticleSun::create(); p2->addChild(par, 10); - par->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + par->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); auto move = MoveBy::create(4, Point(300,0)); auto move_back = move->reverse(); @@ -641,7 +641,7 @@ void RadiusMode1::onEnter() _emitter = new ParticleSystemQuad(); _emitter->initWithTotalParticles(200); addChild(_emitter, 10); - _emitter->setTexture(TextureCache::getInstance()->addImage("Images/stars-grayscale.png")); + _emitter->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/stars-grayscale.png")); // duration _emitter->setDuration(ParticleSystem::DURATION_INFINITY); @@ -725,7 +725,7 @@ void RadiusMode2::onEnter() _emitter = new ParticleSystemQuad(); _emitter->initWithTotalParticles(200); addChild(_emitter, 10); - _emitter->setTexture(TextureCache::getInstance()->addImage("Images/stars-grayscale.png")); + _emitter->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/stars-grayscale.png")); // duration _emitter->setDuration(ParticleSystem::DURATION_INFINITY); @@ -809,7 +809,7 @@ void Issue704::onEnter() _emitter = new ParticleSystemQuad(); _emitter->initWithTotalParticles(100); addChild(_emitter, 10); - _emitter->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + _emitter->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); // duration _emitter->setDuration(ParticleSystem::DURATION_INFINITY); @@ -900,7 +900,7 @@ void Issue870::onEnter() auto system = new ParticleSystemQuad(); system->initWithFile("Particles/SpinningPeas.plist"); - system->setTextureWithRect(TextureCache::getInstance()->addImage("Images/particles.png"), Rect(0,0,32,32)); + system->setTextureWithRect(Director::getInstance()->getTextureCache()->addImage("Images/particles.png"), Rect(0,0,32,32)); addChild(system, 10); _emitter = system; @@ -1452,7 +1452,7 @@ bool RainbowEffect::initWithTotalParticles(unsigned int numberOfParticles) _endColorVar.b = 0.0f; _endColorVar.a = 0.0f; - setTexture(TextureCache::getInstance()->addImage("Images/particles.png")); + setTexture(Director::getInstance()->getTextureCache()->addImage("Images/particles.png")); return true; } @@ -1504,7 +1504,7 @@ void MultipleParticleSystems::onEnter() removeChild(_background, true); _background = NULL; - TextureCache::getInstance()->addImage("Images/particles.png"); + Director::getInstance()->getTextureCache()->addImage("Images/particles.png"); for (int i = 0; i<5; i++) { auto particleSystem = ParticleSystemQuad::create("Particles/SpinningPeas.plist"); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceParticleTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceParticleTest.cpp index b72ad00da5..b6878a5b22 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceParticleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceParticleTest.cpp @@ -187,8 +187,8 @@ void ParticleMainScene::createParticleSystem() removeChildByTag(kTagParticleSystem, true); // remove the "fire.png" from the TextureCache cache. - auto texture = TextureCache::getInstance()->addImage("Images/fire.png"); - TextureCache::getInstance()->removeTexture(texture); + auto texture = Director::getInstance()->getTextureCache()->addImage("Images/fire.png"); + Director::getInstance()->getTextureCache()->removeTexture(texture); //TODO: if (subtestNumber <= 3) // { @@ -204,42 +204,42 @@ void ParticleMainScene::createParticleSystem() case 1: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); particleSystem->initWithTotalParticles(quantityParticles); - particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); break; case 2: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); particleSystem->initWithTotalParticles(quantityParticles); - particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); break; case 3: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::A8); particleSystem->initWithTotalParticles(quantityParticles); - particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); break; // case 4: // particleSystem->initWithTotalParticles(quantityParticles); // ////---- particleSystem.texture = [[TextureCache sharedTextureCache] addImage:@"fire.pvr"]; -// particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); +// particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); // break; case 4: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); particleSystem->initWithTotalParticles(quantityParticles); - particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); break; case 5: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); particleSystem->initWithTotalParticles(quantityParticles); - particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); break; case 6: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::A8); particleSystem->initWithTotalParticles(quantityParticles); - particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); break; // case 8: // particleSystem->initWithTotalParticles(quantityParticles); // ////---- particleSystem.texture = [[TextureCache sharedTextureCache] addImage:@"fire.pvr"]; -// particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); +// particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); // break; default: particleSystem = NULL; diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp index 7e290e5e5b..ccf4ca602d 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp @@ -52,7 +52,7 @@ void SubTest::initWithSubTest(int nSubTest, Node* p) */ // purge textures - auto mgr = TextureCache::getInstance(); + auto mgr = Director::getInstance()->getTextureCache(); // [mgr removeAllTextures]; mgr->removeTexture(mgr->addImage("Images/grossinis_sister1.png")); mgr->removeTexture(mgr->addImage("Images/grossini_dance_atlas.png")); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTextureTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTextureTest.cpp index bcbae20aa1..0da9efd0ec 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTextureTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTextureTest.cpp @@ -84,7 +84,7 @@ void TextureTest::performTestsPNG(const char* filename) { struct timeval now; Texture2D *texture; - auto cache = TextureCache::getInstance(); + auto cache = Director::getInstance()->getTextureCache(); log("RGBA 8888"); Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); @@ -131,7 +131,7 @@ void TextureTest::performTests() { // Texture2D *texture; // struct timeval now; -// auto cache = TextureCache::getInstance(); +// auto cache = Director::getInstance()->getTextureCache(); log("--------"); diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index fab2a82437..29f4b68e6d 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -1,4 +1,5 @@ #include "PhysicsTest.h" +#include #include "../testResource.h" USING_NS_CC; @@ -6,10 +7,14 @@ namespace { static std::function createFunctions[] = { CL(PhysicsDemoLogoSmash), - CL(PhysicsDemoPyramidStack), CL(PhysicsDemoPlink), CL(PhysicsDemoClickAdd), CL(PhysicsDemoRayCast), + CL(PhysicsDemoJoints), + CL(PhysicsDemoActions), + CL(PhysicsDemoPump), + CL(PhysicsDemoOneWayPlatform), + CL(PhysicsDemoSlice), }; static int sceneIdx=-1; @@ -51,6 +56,7 @@ namespace } static const Color4F STATIC_COLOR(1.0f, 0.0f, 0.0f, 1.0f); + static const int DRAG_BODYS_TAG = 0x80; } @@ -92,7 +98,6 @@ PhysicsDemo::PhysicsDemo() : _scene(nullptr) , _ball(nullptr) , _spriteTexture(nullptr) -, _mouse(nullptr) { } @@ -160,7 +165,7 @@ void PhysicsDemo::onEnter() #endif } -void PhysicsDemo::addGrossiniAtPosition(Point p, float scale/* = 1.0*/) +Sprite* PhysicsDemo::addGrossiniAtPosition(Point p, float scale/* = 1.0*/) { #ifdef CC_USE_PHYSICS CCLOG("Add sprite %0.2f x %02.f",p.x,p.y); @@ -178,6 +183,8 @@ void PhysicsDemo::addGrossiniAtPosition(Point p, float scale/* = 1.0*/) sp->setPhysicsBody(PhysicsBody::createBox(Size(48.0f * scale, 108.0f * scale))); this->addChild(sp); sp->setPosition(p); + + return sp; #endif } @@ -192,6 +199,11 @@ void PhysicsDemo::toggleDebugCallback(Object* sender) #endif } +PhysicsDemoClickAdd::~PhysicsDemoClickAdd() +{ + Device::setAccelerometerEnabled(false); +} + void PhysicsDemoClickAdd::onEnter() { PhysicsDemo::onEnter(); @@ -202,6 +214,7 @@ void PhysicsDemoClickAdd::onEnter() touchListener->onTouchesEnded = CC_CALLBACK_2(PhysicsDemoClickAdd::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); + Device::setAccelerometerEnabled(true); auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(PhysicsDemoClickAdd::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(accListener, this); @@ -316,7 +329,7 @@ namespace } } -Sprite* PhysicsDemo::makeBall(float x, float y, float radius, PhysicsMaterial material) +Sprite* PhysicsDemo::makeBall(Point point, float radius, PhysicsMaterial material) { Sprite* ball = nullptr; if (_ball != nullptr) @@ -331,12 +344,12 @@ Sprite* PhysicsDemo::makeBall(float x, float y, float radius, PhysicsMaterial ma auto body = PhysicsBody::createCircle(radius, material); ball->setPhysicsBody(body); - ball->setPosition(Point(x, y)); + ball->setPosition(Point(point.x, point.y)); return ball; } -Sprite* PhysicsDemo::makeBox(float x, float y, Size size, PhysicsMaterial material) +Sprite* PhysicsDemo::makeBox(Point point, Size size, PhysicsMaterial material) { auto box = CCRANDOM_0_1() > 0.5f ? Sprite::create("Images/YellowSquare.png") : Sprite::create("Images/CyanSquare.png"); @@ -345,12 +358,12 @@ Sprite* PhysicsDemo::makeBox(float x, float y, Size size, PhysicsMaterial materi auto body = PhysicsBody::createBox(size); box->setPhysicsBody(body); - box->setPosition(Point(x, y)); + box->setPosition(Point(point.x, point.y)); return box; } -Sprite* PhysicsDemo::makeTriangle(float x, float y, Size size, PhysicsMaterial material) +Sprite* PhysicsDemo::makeTriangle(Point point, Size size, PhysicsMaterial material) { auto triangle = CCRANDOM_0_1() > 0.5f ? Sprite::create("Images/YellowTriangle.png") : Sprite::create("Images/CyanTriangle.png"); @@ -367,33 +380,66 @@ Sprite* PhysicsDemo::makeTriangle(float x, float y, Size size, PhysicsMaterial m auto body = PhysicsBody::createPolygon(vers, 3); triangle->setPhysicsBody(body); - triangle->setPosition(Point(x, y)); + triangle->setPosition(Point(point.x, point.y)); return triangle; } -void PhysicsDemo::onTouchesBegan(const std::vector& touches, Event* event) +bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) { - for( auto &touch: touches) + auto location = touch->getLocation(); + Array* arr = _scene->getPhysicsWorld()->getShapes(location); + + PhysicsShape* shape = nullptr; + for (Object* obj : *arr) { - auto location = touch->getLocation(); - Array* arr = _scene->getPhysicsWorld()->getShapesAtPoint(location); + shape = dynamic_cast(obj); - PhysicsShape* shape = nullptr; - for (Object* obj : *arr) + if ((shape->getTag() & DRAG_BODYS_TAG) != 0) { - + break; } } + + if (shape != nullptr) + { + + Node* mouse = Node::create(); + mouse->setPhysicsBody(PhysicsBody::create(PHYSICS_INFINITY, PHYSICS_INFINITY)); + mouse->getPhysicsBody()->setDynamic(false); + mouse->setPosition(location); + this->addChild(mouse); + PhysicsJointPin* joint = PhysicsJointPin::construct(mouse->getPhysicsBody(), shape->getBody(), location); + joint->setMaxForce(5000.0f * shape->getBody()->getMass()); + _scene->getPhysicsWorld()->addJoint(joint); + _mouses.insert(std::make_pair(touch->getID(), mouse)); + + return true; + } + + return false; +} + +void PhysicsDemo::onTouchMoved(Touch* touch, Event* event) +{ + auto it = _mouses.find(touch->getID()); + + if (it != _mouses.end()) + { + it->second->getPhysicsBody()->setVelocity((touch->getLocation() - it->second->getPosition()) * 60.0f); + it->second->setPosition(touch->getLocation()); + } } -void PhysicsDemo::onTouchesMoved(const std::vector& touches, Event* event) +void PhysicsDemo::onTouchEnded(Touch* touch, Event* event) { + auto it = _mouses.find(touch->getID()); -} - -void PhysicsDemo::onTouchesEnded(const std::vector& touches, Event* event) -{ + if (it != _mouses.end()) + { + this->removeChild(it->second); + _mouses.erase(it); + } } @@ -414,9 +460,9 @@ void PhysicsDemoLogoSmash::onEnter() float x_jitter = 0.05*frand(); float y_jitter = 0.05*frand(); - Node* ball = makeBall(2*(x - logo_width/2 + x_jitter) + VisibleRect::getVisibleRect().size.width/2, - 2*(logo_height-y + y_jitter) + VisibleRect::getVisibleRect().size.height/2 - logo_height/2, - 0.95f, PhysicsMaterial(1.0f, 0.0f, 0.0f)); + Node* ball = makeBall(Point(2*(x - logo_width/2 + x_jitter) + VisibleRect::getVisibleRect().size.width/2, + 2*(logo_height-y + y_jitter) + VisibleRect::getVisibleRect().size.height/2 - logo_height/2), + 0.95f, PhysicsMaterial(0.01f, 0.0f, 0.0f)); ball->getPhysicsBody()->setMass(1.0); ball->getPhysicsBody()->setMoment(PHYSICS_INFINITY); @@ -428,7 +474,7 @@ void PhysicsDemoLogoSmash::onEnter() } - auto bullet = makeBall(400, 0, 10, PhysicsMaterial(PHYSICS_INFINITY, 0, 0)); + auto bullet = makeBall(Point(400, 0), 10, PhysicsMaterial(PHYSICS_INFINITY, 0, 0)); bullet->getPhysicsBody()->setVelocity(Point(400, 0)); bullet->setPosition(Point(-1000, VisibleRect::getVisibleRect().size.height/2)); @@ -441,34 +487,6 @@ std::string PhysicsDemoLogoSmash::title() return "Logo Smash"; } -void PhysicsDemoPyramidStack::onEnter() -{ - PhysicsDemo::onEnter(); - - auto node = Node::create(); - node->setPhysicsBody(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50))); - this->addChild(node); - - auto ball = Sprite::create("Images/ball.png"); - ball->setScale(1); - ball->setPhysicsBody(PhysicsBody::createCircle(10)); - ball->setPosition(VisibleRect::bottom() + Point(0, 60)); - this->addChild(ball); - - for(int i=0; i<14; i++) - { - for(int j=0; j<=i; j++) - { - addGrossiniAtPosition(VisibleRect::bottom() + Point((i/2 - j) * 11, (14 - i) * 23 + 100), 0.2f); - } - } -} -std::string PhysicsDemoPyramidStack::title() -{ - return "Pyramid Stack"; -} - - void PhysicsDemoPlink::onEnter() { PhysicsDemo::onEnter(); @@ -554,65 +572,12 @@ void PhysicsDemoRayCast::changeModeCallback(Object* sender) } } -bool PhysicsDemoRayCast::anyRay(PhysicsWorld& world, PhysicsShape& shape, Point point, Point normal, float fraction, void* data) +bool PhysicsDemoRayCast::anyRay(PhysicsWorld& world, const PhysicsRayCastInfo& info, void* data) { - *((Point*)data) = point; + *((Point*)data) = info.contact; return false; } -class PhysicsDemoNearestRayCastCallback : public PhysicsRayCastCallback -{ -public: - PhysicsDemoNearestRayCastCallback(); - -private: - float _friction; -}; - -PhysicsDemoNearestRayCastCallback::PhysicsDemoNearestRayCastCallback() -: _friction(1.0f) -{ - report = [this](PhysicsWorld& world, PhysicsShape& shape, Point point, Point normal, float fraction, void* data)->bool - { - if (_friction > fraction) - { - *((Point*)data) = point; - _friction = fraction; - } - - return true; - }; -} - -namespace -{ - static const int MAX_MULTI_RAYCAST_NUM = 5; -} - -class PhysicsDemoMultiRayCastCallback : public PhysicsRayCastCallback -{ -public: - PhysicsDemoMultiRayCastCallback(); - -public: - Point points[MAX_MULTI_RAYCAST_NUM]; - int num; -}; - -PhysicsDemoMultiRayCastCallback::PhysicsDemoMultiRayCastCallback() -: num(0) -{ - report = [this](PhysicsWorld& world, PhysicsShape& shape, Point point, Point normal, float fraction, void* data)->bool - { - if (num < MAX_MULTI_RAYCAST_NUM) - { - points[num++] = point; - } - - return true; - }; -} - void PhysicsDemoRayCast::update(float delta) { float L = 150.0f; @@ -626,11 +591,10 @@ void PhysicsDemoRayCast::update(float delta) { case 0: { - PhysicsRayCastCallback callback; Point point3 = point2; - callback.report = anyRay; + auto func = CC_CALLBACK_3(PhysicsDemoRayCast::anyRay, this); - _scene->getPhysicsWorld()->rayCast(callback, point1, point2, &point3); + _scene->getPhysicsWorld()->rayCast(func, point1, point2, &point3); _node->drawSegment(point1, point3, 1, STATIC_COLOR); if (point2 != point3) @@ -643,10 +607,20 @@ void PhysicsDemoRayCast::update(float delta) } case 1: { - PhysicsDemoNearestRayCastCallback callback; Point point3 = point2; + float friction = 1.0f; + PhysicsRayCastCallbackFunc func = [&point3, &friction](PhysicsWorld& world, const PhysicsRayCastInfo& info, void* data)->bool + { + if (friction > info.fraction) + { + point3 = info.contact; + friction = info.fraction; + } + + return true; + }; - _scene->getPhysicsWorld()->rayCast(callback, point1, point2, &point3); + _scene->getPhysicsWorld()->rayCast(func, point1, point2, nullptr); _node->drawSegment(point1, point3, 1, STATIC_COLOR); if (point2 != point3) @@ -659,15 +633,27 @@ void PhysicsDemoRayCast::update(float delta) } case 2: { - PhysicsDemoMultiRayCastCallback callback; +#define MAX_MULTI_RAYCAST_NUM 5 + Point points[MAX_MULTI_RAYCAST_NUM]; + int num = 0; - _scene->getPhysicsWorld()->rayCast(callback, point1, point2, nullptr); + PhysicsRayCastCallbackFunc func = [&points, &num](PhysicsWorld& world, const PhysicsRayCastInfo& info, void* data)->bool + { + if (num < MAX_MULTI_RAYCAST_NUM) + { + points[num++] = info.contact; + } + + return true; + }; + + _scene->getPhysicsWorld()->rayCast(func, point1, point2, nullptr); _node->drawSegment(point1, point2, 1, STATIC_COLOR); - for (int i = 0; i < callback.num; ++i) + for (int i = 0; i < num; ++i) { - _node->drawDot(callback.points[i], 2, Color4F(1.0f, 1.0f, 1.0f, 1.0f)); + _node->drawDot(points[i], 2, Color4F(1.0f, 1.0f, 1.0f, 1.0f)); } addChild(_node); @@ -694,13 +680,13 @@ void PhysicsDemoRayCast::onTouchesEnded(const std::vector& touches, Even if (r < 1.0f/3.0f) { - addChild(makeBall(location.x, location.y, 5 + CCRANDOM_0_1()*10)); + addChild(makeBall(location, 5 + CCRANDOM_0_1()*10)); }else if(r < 2.0f/3.0f) { - addChild(makeBox(location.x, location.y, Size(10 + CCRANDOM_0_1()*15, 10 + CCRANDOM_0_1()*15))); + addChild(makeBox(location, Size(10 + CCRANDOM_0_1()*15, 10 + CCRANDOM_0_1()*15))); }else { - addChild(makeTriangle(location.x, location.y, Size(10 + CCRANDOM_0_1()*20, 10 + CCRANDOM_0_1()*20))); + addChild(makeTriangle(location, Size(10 + CCRANDOM_0_1()*20, 10 + CCRANDOM_0_1()*20))); } } } @@ -710,26 +696,419 @@ std::string PhysicsDemoRayCast::title() return "Ray Cast"; } - void PhysicsDemoJoints::onEnter() { PhysicsDemo::onEnter(); - auto listener = EventListenerTouchAllAtOnce::create(); - listener->onTouchesEnded = CC_CALLBACK_2(PhysicsDemoJoints::onTouchesEnded, this); + auto listener = EventListenerTouchOneByOne::create(); + listener->onTouchBegan = CC_CALLBACK_2(PhysicsDemoJoints::onTouchBegan, this); + listener->onTouchMoved = CC_CALLBACK_2(PhysicsDemoJoints::onTouchMoved, this); + listener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoJoints::onTouchEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - _scene->getPhysicsWorld()->setGravity(Point::ZERO); + //_scene->getPhysicsWorld()->setGravity(Point::ZERO); + float width = (VisibleRect::getVisibleRect().size.width - 10) / 4; + float height = (VisibleRect::getVisibleRect().size.height - 50) / 4; -} - -void PhysicsDemoJoints::onTouchesEnded(const std::vector& touches, Event* event) -{ + Node* node = Node::create(); + PhysicsBody* box = PhysicsBody::create(); + node->setPhysicsBody(box); + box->setDynamic(false); + node->setPosition(Point::ZERO); + this->addChild(node); + + for (int i = 0; i < 4; ++i) + { + for (int j = 0; j < 4; ++j) + { + Point offset(VisibleRect::leftBottom().x + 5 + j * width + width/2, VisibleRect::leftBottom().y + 50 + i * height + height/2); + box->addShape(PhysicsShapeEdgeBox::create(Size(width, height), PHYSICSSHAPE_MATERIAL_DEFAULT, 1, offset)); + + switch (i*4 + j) + { + case 0: + { + auto sp1 = makeBall(offset - Point(30, 0), 10); + sp1->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + auto sp2 = makeBall(offset + Point(30, 0), 10); + sp2->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + + PhysicsJointPin* joint = PhysicsJointPin::construct(sp1->getPhysicsBody(), sp2->getPhysicsBody(), offset); + _scene->getPhysicsWorld()->addJoint(joint); + + this->addChild(sp1); + this->addChild(sp2); + break; + } + case 1: + { + + auto sp1 = makeBall(offset - Point(30, 0), 10); + sp1->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + auto sp2 = makeBox(offset + Point(30, 0), Size(30, 10)); + sp2->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + + PhysicsJointFixed* joint = PhysicsJointFixed::construct(sp1->getPhysicsBody(), sp2->getPhysicsBody(), offset); + _scene->getPhysicsWorld()->addJoint(joint); + + this->addChild(sp1); + this->addChild(sp2); + break; + } + default: + break; + } + } + } } std::string PhysicsDemoJoints::title() { return "Joints"; +} + +void PhysicsDemoActions::onEnter() +{ + PhysicsDemo::onEnter(); + + auto touchListener = EventListenerTouchOneByOne::create(); + touchListener->onTouchBegan = CC_CALLBACK_2(PhysicsDemoActions::onTouchBegan, this); + touchListener->onTouchMoved = CC_CALLBACK_2(PhysicsDemoActions::onTouchMoved, this); + touchListener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoActions::onTouchEnded, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); + + auto node = Node::create(); + node->setPhysicsBody(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size)); + node->setPosition(VisibleRect::center()); + this->addChild(node); + + Sprite* sp1 = addGrossiniAtPosition(VisibleRect::center()); + Sprite* sp2 = addGrossiniAtPosition(VisibleRect::left() + Point(50, 0)); + Sprite* sp3 = addGrossiniAtPosition(VisibleRect::right() - Point(20, 0)); + Sprite* sp4 = addGrossiniAtPosition(VisibleRect::leftTop() + Point(50, -50)); + sp4->getPhysicsBody()->setGravityEnable(false); + + + auto actionTo = JumpTo::create(2, Point(100,100), 50, 4); + auto actionBy = JumpBy::create(2, Point(300,0), 50, 4); + auto actionUp = JumpBy::create(2, Point(0,50), 80, 4); + auto actionByBack = actionBy->reverse(); + + sp1->runAction(RepeatForever::create(actionUp)); + sp2->runAction(RepeatForever::create(Sequence::create(actionBy, actionByBack, NULL))); + sp3->runAction(actionTo); + sp4->runAction(RepeatForever::create(Sequence::create(actionBy->clone(), actionByBack->clone(), NULL))); +} + +std::string PhysicsDemoActions::title() +{ + return "Actions"; +} + +void PhysicsDemoPump::onEnter() +{ + PhysicsDemo::onEnter(); + + _distance = 0.0f; + _rotationV = 0.0f; + auto touchListener = EventListenerTouchOneByOne::create(); + touchListener->onTouchBegan = CC_CALLBACK_2(PhysicsDemoPump::onTouchBegan, this); + touchListener->onTouchMoved = CC_CALLBACK_2(PhysicsDemoPump::onTouchMoved, this); + touchListener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoPump::onTouchEnded, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); + scheduleUpdate(); + + auto node = Node::create(); + auto body = PhysicsBody::create(); + body->setDynamic(false); + + PhysicsMaterial staticMaterial(PHYSICS_INFINITY, 0, 0.5f); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(50, 0), VisibleRect::leftTop() + Point(50, -130), staticMaterial, 2.0f)); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(190, 0), VisibleRect::leftTop() + Point(100, -50), staticMaterial, 2.0f)); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(100, -50), VisibleRect::leftTop() + Point(100, -90), staticMaterial, 2.0f)); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(50, -130), VisibleRect::leftTop() + Point(100, -145), staticMaterial, 2.0f)); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(100, -145), VisibleRect::leftBottom() + Point(100, 80), staticMaterial, 2.0f)); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(150, -80), VisibleRect::leftBottom() + Point(150, 80), staticMaterial, 2.0f)); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(150, -80), VisibleRect::rightTop() + Point(-100, -150), staticMaterial, 2.0f)); + + body->setCategoryBitmask(0x01); + + // balls + for (int i = 0; i < 6; ++i) + { + auto ball = makeBall(VisibleRect::leftTop() + Point(75 + CCRANDOM_0_1() * 90, 0), 22, PhysicsMaterial(0.05f, 0.0f, 0.1f)); + ball->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + addChild(ball); + } + + node->setPhysicsBody(body); + this->addChild(node); + + Point vec[4] = + { + VisibleRect::leftTop() + Point(102, -148), + VisibleRect::leftTop() + Point(148, -161), + VisibleRect::leftBottom() + Point(148, 20), + VisibleRect::leftBottom() + Point(102, 20) + }; + + auto _world = _scene->getPhysicsWorld(); + + // small gear + auto sgear = Node::create(); + auto sgearB = PhysicsBody::createCircle(44); + sgear->setPhysicsBody(sgearB); + sgear->setPosition(VisibleRect::leftBottom() + Point(125, 0)); + this->addChild(sgear); + sgearB->setCategoryBitmask(0x04); + sgearB->setCollisionBitmask(0x04); + sgearB->setTag(1); + _world->addJoint(PhysicsJointPin::construct(body, sgearB, sgearB->getPosition())); + + + // big gear + auto bgear = Node::create(); + auto bgearB = PhysicsBody::createCircle(100); + bgear->setPhysicsBody(bgearB); + bgear->setPosition(VisibleRect::leftBottom() + Point(275, 0)); + this->addChild(bgear); + bgearB->setCategoryBitmask(0x04); + _world->addJoint(PhysicsJointPin::construct(body, bgearB, bgearB->getPosition())); + + + // pump + auto pump = Node::create(); + auto center = PhysicsShape::getPolyonCenter(vec, 4); + pump->setPosition(center); + auto pumpB = PhysicsBody::createPolygon(vec, 4, PHYSICSBODY_MATERIAL_DEFAULT, -center); + pump->setPhysicsBody(pumpB); + this->addChild(pump); + pumpB->setCategoryBitmask(0x02); + pumpB->setGravityEnable(false); + _world->addJoint(PhysicsJointDistance::construct(pumpB, sgearB, Point(0, 0), Point(0, -44))); + + // plugger + Point seg[] = {VisibleRect::leftTop() + Point(75, -120), VisibleRect::leftBottom() + Point(75, -100)}; + Point segCenter = (seg[1] + seg[0])/2; + seg[1] -= segCenter; + seg[0] -= segCenter; + auto plugger = Node::create(); + auto pluggerB = PhysicsBody::createEdgeSegment(seg[0], seg[1], PhysicsMaterial(0.01f, 0.0f, 0.5f), 20); + pluggerB->setDynamic(true); + pluggerB->setMass(30); + pluggerB->setMoment(100000); + plugger->setPhysicsBody(pluggerB); + plugger->setPosition(segCenter); + this->addChild(plugger); + pluggerB->setCategoryBitmask(0x02); + sgearB->setCollisionBitmask(0x04 | 0x01); + _world->addJoint(PhysicsJointPin::construct(body, pluggerB, VisibleRect::leftBottom() + Point(75, -90))); + _world->addJoint(PhysicsJointDistance::construct(pluggerB, sgearB, pluggerB->world2Local(VisibleRect::leftBottom() + Point(75, 0)), Point(44, 0))); +} + +void PhysicsDemoPump::update(float delta) +{ + for (auto obj : *_scene->getPhysicsWorld()->getAllBodies()) + { + PhysicsBody* body = dynamic_cast(obj); + if (body->getTag() == DRAG_BODYS_TAG && body->getPosition().y < 0.0f) + { + body->getNode()->setPosition(VisibleRect::leftTop() + Point(75 + CCRANDOM_0_1() * 90, 0)); + body->setVelocity(Point(0, 0)); + } + } + + PhysicsBody* gear = _scene->getPhysicsWorld()->getBody(1); + + if (gear != nullptr) + { + if (_distance != 0.0f) + { + _rotationV += _distance/2500.0f; + + if (_rotationV > 30) _rotationV = 30.0f; + if (_rotationV < -30) _rotationV = -30.0f; + } + + gear->setAngularVelocity(_rotationV); + _rotationV *= 0.995f; + } +} + +bool PhysicsDemoPump::onTouchBegan(Touch* touch, Event* event) +{ + PhysicsDemo::onTouchBegan(touch, event); + + _distance = touch->getLocation().x - VisibleRect::center().x; + + return true; +} + +void PhysicsDemoPump::onTouchMoved(Touch* touch, Event* event) +{ + PhysicsDemo::onTouchMoved(touch, event); + + _distance = touch->getLocation().x - VisibleRect::center().x; +} + +void PhysicsDemoPump::onTouchEnded(Touch* touch, Event* event) +{ + PhysicsDemo::onTouchEnded(touch, event); + + _distance = 0; +} + +std::string PhysicsDemoPump::title() +{ + return "Pump"; +} + +std::string PhysicsDemoPump::subtitle() +{ + return "open debug to see it"; +} + +void PhysicsDemoOneWayPlatform::onEnter() +{ + PhysicsDemo::onEnter(); + + auto touchListener = EventListenerTouchOneByOne::create(); + touchListener->onTouchBegan = CC_CALLBACK_2(PhysicsDemoOneWayPlatform::onTouchBegan, this); + touchListener->onTouchMoved = CC_CALLBACK_2(PhysicsDemoOneWayPlatform::onTouchMoved, this); + touchListener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoOneWayPlatform::onTouchEnded, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); + + auto ground = Node::create(); + ground->setPhysicsBody(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50))); + this->addChild(ground); + + auto platform = makeBox(VisibleRect::center(), Size(200, 50)); + platform->getPhysicsBody()->setDynamic(false); + this->addChild(platform); + + auto ball = makeBall(VisibleRect::center() - Point(0, 50), 20); + ball->getPhysicsBody()->setVelocity(Point(0, 150)); + ball->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + ball->getPhysicsBody()->setMass(1.0f); + this->addChild(ball); + + auto contactListener = EventListenerPhysicsContactWithBodies::create(platform->getPhysicsBody(), ball->getPhysicsBody()); + contactListener->onContactBegin = CC_CALLBACK_2(PhysicsDemoOneWayPlatform::onContactBegin, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this); +} + +bool PhysicsDemoOneWayPlatform::onContactBegin(EventCustom* event, const PhysicsContact& contact) +{ + return contact.getContactData()->normal.y < 0; +} + +std::string PhysicsDemoOneWayPlatform::title() +{ + return "One Way Platform"; +} + +void PhysicsDemoSlice::onEnter() +{ + PhysicsDemo::onEnter(); + + _sliceTag = 1; + + auto touchListener = EventListenerTouchOneByOne::create(); + touchListener->onTouchBegan = [](Touch* touch, Event* event)->bool{ return true; }; + touchListener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoSlice::onTouchEnded, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); + + auto ground = Node::create(); + ground->setPhysicsBody(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50))); + this->addChild(ground); + + auto box = Node::create(); + Point points[4] = {Point(-100, -100), Point(-100, 100), Point(100, 100), Point(100, -100)}; + box->setPhysicsBody(PhysicsBody::createPolygon(points, 4)); + box->setPosition(VisibleRect::center()); + box->getPhysicsBody()->setTag(_sliceTag); + addChild(box); +} + +bool PhysicsDemoSlice::slice(PhysicsWorld &world, const PhysicsRayCastInfo& info, void *data) +{ + if (info.shape->getBody()->getTag() != _sliceTag) + { + return true; + } + + if (!info.shape->containsPoint(info.start) && !info.shape->containsPoint(info.end)) + { + Point normal = info.end - info.start; + normal = normal.getPerp().normalize(); + float dist = info.start.dot(normal); + dist = dist; + + clipPoly(dynamic_cast(info.shape), normal, dist); + clipPoly(dynamic_cast(info.shape), -normal, -dist); + + info.shape->getBody()->removeFromWorld(); + } + + return true; +} + +void PhysicsDemoSlice::clipPoly(PhysicsShapePolygon* shape, Point normal, float distance) +{ + PhysicsBody* body = shape->getBody(); + int count = shape->getPointsCount(); + int pointsCount = 0; + Point* points = new Point[count + 1]; + + for (int i=0, j=count-1; ilocal2World(shape->getPoint(j)); + float aDist = a.dot(normal) - distance; + + if (aDist < 0.0f) + { + points[pointsCount] = a; + ++pointsCount; + } + + Point b = body->local2World(shape->getPoint(i)); + float bDist = b.dot(normal) - distance; + + if (aDist*bDist < 0.0f) + { + float t = std::fabs(aDist)/(std::fabs(aDist) + std::fabs(bDist)); + points[pointsCount] = a.lerp(b, t); + ++pointsCount; + } + } + + Point center = PhysicsShape::getPolyonCenter(points, pointsCount); + Node* node = Node::create(); + PhysicsBody* polyon = PhysicsBody::createPolygon(points, pointsCount, PHYSICSBODY_MATERIAL_DEFAULT, -center); + node->setPosition(center); + node->setPhysicsBody(polyon); + polyon->setVelocity(body->getVelocityAtWorldPoint(center)); + polyon->setAngularVelocity(body->getAngularVelocity()); + polyon->setTag(_sliceTag); + addChild(node); + + delete[] points; +} + +void PhysicsDemoSlice::onTouchEnded(Touch *touch, Event *event) +{ + auto func = CC_CALLBACK_3(PhysicsDemoSlice::slice, this); + _scene->getPhysicsWorld()->rayCast(func, touch->getStartLocation(), touch->getLocation(), nullptr); +} + +std::string PhysicsDemoSlice::title() +{ + return "Slice"; +} + +std::string PhysicsDemoSlice::subtitle() +{ + return "click and drag to slice up the block, open debug to see it"; } \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index bb737b497d..a3ccc76e57 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -5,6 +5,8 @@ #include "../testBasic.h" #include "../BaseTest.h" +#include + class PhysicsTestScene : public TestScene { @@ -36,24 +38,25 @@ public: void backCallback(Object* sender); void toggleDebugCallback(Object* sender); - void addGrossiniAtPosition(Point p, float scale = 1.0); - Sprite* makeBall(float x, float y, float radius, PhysicsMaterial material = PhysicsMaterial(1.0f, 1.0f, 1.0f)); - Sprite* makeBox(float x, float y, Size size, PhysicsMaterial material = PhysicsMaterial(1.0f, 1.0f, 1.0f)); - Sprite* makeTriangle(float x, float y, Size size, PhysicsMaterial material = PhysicsMaterial(1.0f, 1.0f, 1.0f)); + Sprite* addGrossiniAtPosition(Point p, float scale = 1.0); + Sprite* makeBall(Point point, float radius, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + Sprite* makeBox(Point point, Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + Sprite* makeTriangle(Point point, Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); - void onTouchesBegan(const std::vector& touches, Event* event); - void onTouchesMoved(const std::vector& touches, Event* event); - void onTouchesEnded(const std::vector& touches, Event* event); + bool onTouchBegan(Touch* touch, Event* event); + void onTouchMoved(Touch* touch, Event* event); + void onTouchEnded(Touch* touch, Event* event); protected: Texture2D* _spriteTexture; // weak ref SpriteBatchNode* _ball; - DrawNode* _mouse; + std::map _mouses; }; class PhysicsDemoClickAdd : public PhysicsDemo { public: + virtual ~PhysicsDemoClickAdd(); void onEnter() override; std::string subtitle() override; @@ -68,13 +71,6 @@ public: std::string title() override; }; -class PhysicsDemoPyramidStack : public PhysicsDemo -{ -public: - void onEnter() override; - std::string title() override; -}; - class PhysicsDemoPlink : public PhysicsDemo { public: @@ -94,7 +90,7 @@ public: void changeModeCallback(Object* sender); - static bool anyRay(PhysicsWorld& world, PhysicsShape& shape, Point point, Point normal, float fraction, void* data); + bool anyRay(PhysicsWorld& world, const PhysicsRayCastInfo& info, void* data); private: float _angle; @@ -105,12 +101,59 @@ private: class PhysicsDemoJoints : public PhysicsDemo { public: - PhysicsDemoJoints(); - + void onEnter() override; + std::string title() override; +}; + +class PhysicsDemoActions : public PhysicsDemo +{ public: void onEnter() override; std::string title() override; - void onTouchesEnded(const std::vector& touches, Event* event); +}; + +class PhysicsDemoPump : public PhysicsDemo +{ +public: + void onEnter() override; + void update(float delta) override; + std::string title() override; + std::string subtitle() override; + + bool onTouchBegan(Touch* touch, Event* event); + void onTouchMoved(Touch* touch, Event* event); + void onTouchEnded(Touch* touch, Event* event); + +private: + float _distance; + float _rotationV; +}; + +class PhysicsDemoOneWayPlatform : public PhysicsDemo +{ +public: + void onEnter() override; + std::string title() override; + + bool onContactBegin(EventCustom* event, const PhysicsContact& contact); +}; + +class PhysicsDemoSlice : public PhysicsDemo +{ +public: + void onEnter() override; + std::string title() override; + std::string subtitle() override; + + bool slice(PhysicsWorld& world, const PhysicsRayCastInfo& info, void* data); + void clipPoly(PhysicsShapePolygon* shape, Point normal, float distance); + + bool onTouchBegan(Touch *touch, Event *event); + void onTouchMoved(Touch *touch, Event *event); + void onTouchEnded(Touch *touch, Event *event); + +private: + int _sliceTag; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp index baf174ac9b..987d8b8f05 100644 --- a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp +++ b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp @@ -156,7 +156,7 @@ void RenderTextureSave::saveImage(cocos2d::Object *sender) auto image = _target->newImage(); - auto tex = TextureCache::getInstance()->addImage(image, png); + auto tex = Director::getInstance()->getTextureCache()->addImage(image, png); CC_SAFE_DELETE(image); @@ -176,7 +176,7 @@ RenderTextureSave::~RenderTextureSave() { _brush->release(); _target->release(); - TextureCache::getInstance()->removeUnusedTextures(); + Director::getInstance()->getTextureCache()->removeUnusedTextures(); } void RenderTextureSave::onTouchesMoved(const std::vector& touches, Event* event) diff --git a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp index 96ee66292b..d225e1c8f8 100644 --- a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp @@ -924,7 +924,7 @@ void SchedulerTimeScale::onEnter() kathia->runAction(Speed::create(action3, 1.0f)); auto emitter = ParticleFireworks::create(); - emitter->setTexture( TextureCache::getInstance()->addImage(s_stars1) ); + emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars1) ); addChild(emitter); _sliderCtl = sliderCtl(); diff --git a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id index 499b1b8dfe..cade29ab94 100644 --- a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id +++ b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id @@ -1 +1 @@ -71aa9486e8535b9bd65cae247bb86de59c83f522 \ No newline at end of file +c37b913119295ed7f6bcbb7e04cce322722ea1a5 \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp index 8184bc1467..6245237ca8 100644 --- a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp +++ b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp @@ -129,18 +129,18 @@ void TextureDemo::onEnter() { BaseTest::onEnter(); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); auto col = LayerColor::create(Color4B(128,128,128,255)); addChild(col, -10); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } TextureDemo::~TextureDemo() { - TextureCache::getInstance()->removeUnusedTextures(); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->removeUnusedTextures(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } void TextureDemo::restartCallback(Object* sender) @@ -191,7 +191,7 @@ void TextureTIFF::onEnter() auto img = Sprite::create("Images/test_image.tiff"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); this->addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureTIFF::title() @@ -213,7 +213,7 @@ void TexturePNG::onEnter() auto img = Sprite::create("Images/test_image.png"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePNG::title() @@ -234,7 +234,7 @@ void TextureJPEG::onEnter() auto img = Sprite::create("Images/test_image.jpeg"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureJPEG::title() @@ -255,7 +255,7 @@ void TextureWEBP::onEnter() auto img = Sprite::create("Images/test_image.webp"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureWEBP::title() @@ -273,12 +273,12 @@ void TextureMipMap::onEnter() TextureDemo::onEnter(); auto s = Director::getInstance()->getWinSize(); - auto texture0 = TextureCache::getInstance()->addImage("Images/grossini_dance_atlas.png"); + auto texture0 = Director::getInstance()->getTextureCache()->addImage("Images/grossini_dance_atlas.png"); texture0->generateMipmap(); Texture2D::TexParams texParams = { GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE }; texture0->setTexParameters(texParams); - auto texture1 = TextureCache::getInstance()->addImage("Images/grossini_dance_atlas_nomipmap.png"); + auto texture1 = Director::getInstance()->getTextureCache()->addImage("Images/grossini_dance_atlas_nomipmap.png"); auto img0 = Sprite::createWithTexture(texture0); img0->setTextureRect(Rect(85, 121, 85, 121)); @@ -299,7 +299,7 @@ void TextureMipMap::onEnter() img0->runAction(RepeatForever::create(Sequence::create(scale1, sc_back, NULL))); img1->runAction(RepeatForever::create(Sequence::create(scale2, sc_back2, NULL))); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureMipMap::title() @@ -350,7 +350,7 @@ void TexturePVRMipMap::onEnter() imgMipMap->runAction(RepeatForever::create(Sequence::create(scale1, sc_back, NULL))); img->runAction(RepeatForever::create(Sequence::create(scale2, sc_back2, NULL))); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRMipMap::title() @@ -392,7 +392,7 @@ void TexturePVRMipMap2::onEnter() imgMipMap->runAction(RepeatForever::create(Sequence::create(scale1, sc_back, NULL))); img->runAction(RepeatForever::create(Sequence::create(scale2, sc_back2, NULL))); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRMipMap2::title() @@ -424,7 +424,7 @@ void TexturePVR2BPP::onEnter() img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVR2BPP::title() @@ -455,7 +455,7 @@ void TexturePVRTest::onEnter() { log("This test is not supported."); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } @@ -487,7 +487,7 @@ void TexturePVR4BPP::onEnter() { log("This test is not supported in cocos2d-mac"); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVR4BPP::title() @@ -510,7 +510,7 @@ void TexturePVRRGBA8888::onEnter() auto img = Sprite::create("Images/test_image_rgba8888.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGBA8888::title() @@ -540,7 +540,7 @@ void TexturePVRBGRA8888::onEnter() { log("BGRA8888 images are not supported"); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRBGRA8888::title() @@ -563,7 +563,7 @@ void TexturePVRRGBA5551::onEnter() auto img = Sprite::create("Images/test_image_rgba5551.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGBA5551::title() @@ -586,7 +586,7 @@ void TexturePVRRGBA4444::onEnter() auto img = Sprite::create("Images/test_image_rgba4444.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGBA4444::title() @@ -614,7 +614,7 @@ void TexturePVRRGBA4444GZ::onEnter() #endif img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGBA4444GZ::title() @@ -642,7 +642,7 @@ void TexturePVRRGBA4444CCZ::onEnter() auto img = Sprite::create("Images/test_image_rgba4444.pvr.ccz"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGBA4444CCZ::title() @@ -670,7 +670,7 @@ void TexturePVRRGB565::onEnter() auto img = Sprite::create("Images/test_image_rgb565.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGB565::title() @@ -693,7 +693,7 @@ void TexturePVRRGB888::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGB888::title() @@ -716,7 +716,7 @@ void TexturePVRA8::onEnter() auto img = Sprite::create("Images/test_image_a8.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } @@ -740,7 +740,7 @@ void TexturePVRI8::onEnter() auto img = Sprite::create("Images/test_image_i8.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRI8::title() @@ -763,7 +763,7 @@ void TexturePVRAI88::onEnter() auto img = Sprite::create("Images/test_image_ai88.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRAI88::title() @@ -785,7 +785,7 @@ void TexturePVR2BPPv3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVR2BPPv3::title() @@ -812,7 +812,7 @@ void TexturePVRII2BPPv3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRII2BPPv3::title() @@ -843,7 +843,7 @@ void TexturePVR4BPPv3::onEnter() log("This test is not supported"); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVR4BPPv3::title() @@ -878,7 +878,7 @@ void TexturePVRII4BPPv3::onEnter() log("This test is not supported"); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRII4BPPv3::title() @@ -905,7 +905,7 @@ void TexturePVRRGBA8888v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRRGBA8888v3::title() @@ -936,7 +936,7 @@ void TexturePVRBGRA8888v3::onEnter() log("BGRA images are not supported"); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRBGRA8888v3::title() @@ -963,7 +963,7 @@ void TexturePVRRGBA5551v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRRGBA5551v3::title() @@ -990,7 +990,7 @@ void TexturePVRRGBA4444v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRRGBA4444v3::title() @@ -1017,7 +1017,7 @@ void TexturePVRRGB565v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRRGB565v3::title() @@ -1044,7 +1044,7 @@ void TexturePVRRGB888v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRRGB888v3::title() @@ -1071,7 +1071,7 @@ void TexturePVRA8v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRA8v3::title() @@ -1098,7 +1098,7 @@ void TexturePVRI8v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRI8v3::title() @@ -1125,7 +1125,7 @@ void TexturePVRAI88v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRAI88v3::title() @@ -1181,7 +1181,7 @@ void TexturePVRNonSquare::onEnter() auto img = Sprite::create("Images/grossini_128x256_mipmap.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRNonSquare::title() @@ -1210,7 +1210,7 @@ void TexturePVRNPOT4444::onEnter() img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRNPOT4444::title() @@ -1239,7 +1239,7 @@ void TexturePVRNPOT8888::onEnter() img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRNPOT8888::title() @@ -1293,7 +1293,7 @@ void TextureAlias::onEnter() sprite2->runAction(scaleforever); sprite->runAction(scaleToo); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureAlias::title() @@ -1334,7 +1334,7 @@ void TexturePixelFormat::onEnter() addChild(sprite1, 0); // remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite1->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite1->getTexture()); // RGBA 4444 image (16-bit) Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); @@ -1343,7 +1343,7 @@ void TexturePixelFormat::onEnter() addChild(sprite2, 0); // remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite2->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite2->getTexture()); // RGB5A1 image (16-bit) Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGB5A1); @@ -1352,7 +1352,7 @@ void TexturePixelFormat::onEnter() addChild(sprite3, 0); // remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite3->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite3->getTexture()); // RGB888 image Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGB888); @@ -1361,7 +1361,7 @@ void TexturePixelFormat::onEnter() addChild(sprite4, 0); // remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite4->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite4->getTexture()); // RGB565 image (16-bit) Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGB565); @@ -1370,7 +1370,7 @@ void TexturePixelFormat::onEnter() addChild(sprite5, 0); // remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite5->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite5->getTexture()); // A8 image (8-bit) Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::A8); @@ -1379,7 +1379,7 @@ void TexturePixelFormat::onEnter() addChild(sprite6, 0); // remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite6->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite6->getTexture()); auto fadeout = FadeOut::create(2); auto fadein = FadeIn::create(2); @@ -1398,7 +1398,7 @@ void TexturePixelFormat::onEnter() // restore default Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePixelFormat::title() @@ -1486,7 +1486,7 @@ void TextureAsync::onEnter() TextureAsync::~TextureAsync() { - TextureCache::getInstance()->removeAllTextures(); + Director::getInstance()->getTextureCache()->removeAllTextures(); } void TextureAsync::loadImages(float dt) @@ -1495,15 +1495,15 @@ void TextureAsync::loadImages(float dt) for( int j=0;j < 8; j++) { char szSpriteName[100] = {0}; sprintf(szSpriteName, "Images/sprites_test/sprite-%d-%d.png", i, j); - TextureCache::getInstance()->addImageAsync(szSpriteName,this, callfuncO_selector(TextureAsync::imageLoaded)); + Director::getInstance()->getTextureCache()->addImageAsync(szSpriteName,this, callfuncO_selector(TextureAsync::imageLoaded)); } } - TextureCache::getInstance()->addImageAsync("Images/background1.jpg",this, callfuncO_selector(TextureAsync::imageLoaded)); - TextureCache::getInstance()->addImageAsync("Images/background2.jpg",this, callfuncO_selector(TextureAsync::imageLoaded)); - TextureCache::getInstance()->addImageAsync("Images/background.png",this, callfuncO_selector(TextureAsync::imageLoaded)); - TextureCache::getInstance()->addImageAsync("Images/atlastest.png",this, callfuncO_selector(TextureAsync::imageLoaded)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_atlas.png",this, callfuncO_selector(TextureAsync::imageLoaded)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/background1.jpg",this, callfuncO_selector(TextureAsync::imageLoaded)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/background2.jpg",this, callfuncO_selector(TextureAsync::imageLoaded)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/background.png",this, callfuncO_selector(TextureAsync::imageLoaded)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/atlastest.png",this, callfuncO_selector(TextureAsync::imageLoaded)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_atlas.png",this, callfuncO_selector(TextureAsync::imageLoaded)); } @@ -1576,7 +1576,7 @@ std::string TextureGlClamp::title() TextureGlClamp::~TextureGlClamp() { - TextureCache::getInstance()->removeUnusedTextures(); + Director::getInstance()->getTextureCache()->removeUnusedTextures(); } //------------------------------------------------------------------ @@ -1613,7 +1613,7 @@ std::string TextureGlRepeat::title() TextureGlRepeat::~TextureGlRepeat() { - TextureCache::getInstance()->removeUnusedTextures(); + Director::getInstance()->getTextureCache()->removeUnusedTextures(); } //------------------------------------------------------------------ @@ -1684,7 +1684,7 @@ void TextureCache1::onEnter() sprite->setScale(2); addChild(sprite); - TextureCache::getInstance()->removeTexture(sprite->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite->getTexture()); sprite = Sprite::create("Images/grossinis_sister1.png"); sprite->setPosition(Point(s.width/5*2, s.height/2)); @@ -1700,7 +1700,7 @@ void TextureCache1::onEnter() sprite->setScale(2); addChild(sprite); - TextureCache::getInstance()->removeTextureForKey("Images/grossinis_sister2.png"); + Director::getInstance()->getTextureCache()->removeTextureForKey("Images/grossinis_sister2.png"); sprite = Sprite::create("Images/grossinis_sister2.png"); sprite->setPosition(Point(s.width/5*4, s.height/2)); @@ -1724,8 +1724,8 @@ void TextureDrawAtPoint::onEnter() { TextureDemo::onEnter(); - _tex1 = TextureCache::getInstance()->addImage("Images/grossinis_sister1.png"); - _Tex2F = TextureCache::getInstance()->addImage("Images/grossinis_sister2.png"); + _tex1 = Director::getInstance()->getTextureCache()->addImage("Images/grossinis_sister1.png"); + _Tex2F = Director::getInstance()->getTextureCache()->addImage("Images/grossinis_sister2.png"); _tex1->retain(); _Tex2F->retain(); @@ -1763,8 +1763,8 @@ void TextureDrawAtPoint::draw() void TextureDrawInRect::onEnter() { TextureDemo::onEnter(); - _tex1 = TextureCache::getInstance()->addImage("Images/grossinis_sister1.png"); - _Tex2F = TextureCache::getInstance()->addImage("Images/grossinis_sister2.png"); + _tex1 = Director::getInstance()->getTextureCache()->addImage("Images/grossinis_sister1.png"); + _Tex2F = Director::getInstance()->getTextureCache()->addImage("Images/grossinis_sister2.png"); _tex1->retain(); _Tex2F->retain(); @@ -1871,7 +1871,7 @@ void TextureMemoryAlloc::updateImage(cocos2d::Object *sender) _background->removeFromParentAndCleanup(true); } - TextureCache::getInstance()->removeUnusedTextures(); + Director::getInstance()->getTextureCache()->removeUnusedTextures(); int tag = ((Node*)sender)->getTag(); string file; @@ -1952,7 +1952,7 @@ TexturePVRv3Premult::TexturePVRv3Premult() // PNG Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - TextureCache::getInstance()->removeTextureForKey("Images/grossinis_sister1-testalpha.png"); + Director::getInstance()->getTextureCache()->removeTextureForKey("Images/grossinis_sister1-testalpha.png"); auto png = Sprite::create("Images/grossinis_sister1-testalpha.png"); addChild(png, 0); png->setPosition(Point(size.width/4*3, size.height/2)); @@ -2132,7 +2132,7 @@ static void addImageToDemo(TextureDemo& demo, float x, float y, const char* path demo.addChild(sprite, 0); //remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite->getTexture()); } //TextureConvertRGB888 @@ -2157,7 +2157,7 @@ void TextureConvertRGB888::onEnter() // restore default Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureConvertRGB888::title() @@ -2191,7 +2191,7 @@ void TextureConvertRGBA8888::onEnter() // restore default Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureConvertRGBA8888::title() @@ -2225,7 +2225,7 @@ void TextureConvertI8::onEnter() // restore default Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureConvertI8::title() @@ -2259,7 +2259,7 @@ void TextureConvertAI88::onEnter() // restore default Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureConvertAI88::title() diff --git a/samples/Cpp/TestCpp/Classes/TextureCacheTest/TextureCacheTest.cpp b/samples/Cpp/TestCpp/Classes/TextureCacheTest/TextureCacheTest.cpp index 32d9660ce4..698a2935fd 100644 --- a/samples/Cpp/TestCpp/Classes/TextureCacheTest/TextureCacheTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TextureCacheTest/TextureCacheTest.cpp @@ -21,26 +21,26 @@ TextureCacheTest::TextureCacheTest() this->addChild(_labelPercent); // load textrues - TextureCache::getInstance()->addImageAsync("Images/HelloWorld.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_01.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_02.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_03.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_04.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_05.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_06.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_07.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_08.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_09.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_10.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_11.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_12.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_13.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_14.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/background1.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/background2.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/background3.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/blocks.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/HelloWorld.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_01.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_02.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_03.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_04.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_05.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_06.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_07.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_08.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_09.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_10.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_11.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_12.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_13.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_14.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/background1.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/background2.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/background3.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/blocks.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); } void TextureCacheTest::loadingCallBack(Object *obj) diff --git a/samples/Cpp/TestCpp/Classes/TouchesTest/TouchesTest.cpp b/samples/Cpp/TestCpp/Classes/TouchesTest/TouchesTest.cpp index 6c57cac1b5..ef695368ff 100644 --- a/samples/Cpp/TestCpp/Classes/TouchesTest/TouchesTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TouchesTest/TouchesTest.cpp @@ -39,13 +39,13 @@ PongLayer::PongLayer() { _ballStartingVelocity = Point(20.0f, -100.0f); - _ball = Ball::ballWithTexture( TextureCache::getInstance()->addImage(s_Ball) ); + _ball = Ball::ballWithTexture( Director::getInstance()->getTextureCache()->addImage(s_Ball) ); _ball->setPosition( VisibleRect::center() ); _ball->setVelocity( _ballStartingVelocity ); addChild( _ball ); _ball->retain(); - auto paddleTexture = TextureCache::getInstance()->addImage(s_Paddle); + auto paddleTexture = Director::getInstance()->getTextureCache()->addImage(s_Paddle); auto paddlesM = Array::createWithCapacity(4); diff --git a/samples/Cpp/TestCpp/Classes/controller.cpp b/samples/Cpp/TestCpp/Classes/controller.cpp index fa87e4c9e5..1f18b31118 100644 --- a/samples/Cpp/TestCpp/Classes/controller.cpp +++ b/samples/Cpp/TestCpp/Classes/controller.cpp @@ -14,6 +14,11 @@ struct { const char *test_name; std::function callback; } g_aTestNames[] = { + + // + // TESTS MUST BE ORDERED ALPHABETICALLY + // violators will be prosecuted + // { "Accelerometer", []() { return new AccelerometerTestScene(); } }, { "ActionManagerTest", [](){return new ActionManagerTestScene(); } }, { "ActionsEaseTest", [](){return new ActionsEaseTestScene();} }, @@ -50,7 +55,6 @@ struct { { "FontTest", []() { return new FontTestScene(); } }, { "IntervalTest", [](){return new IntervalTestScene(); } }, { "KeyboardTest", []() { return new KeyboardTestScene(); } }, - { "MouseTest", []() { return new MouseTestScene(); } }, #if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA) { "KeypadTest", []() { return new KeypadTestScene(); } }, #endif @@ -59,6 +63,7 @@ struct { { "LayerTest", [](){return new LayerTestScene();} }, { "MenuTest", [](){return new MenuTestScene();} }, { "MotionStreakTest", [](){return new MotionStreakTestScene();} }, + { "MouseTest", []() { return new MouseTestScene(); } }, { "MutiTouchTest", []() { return new MutiTouchTestScene(); } }, { "NodeTest", [](){return new CocosNodeTestScene();} }, { "ParallaxTest", [](){return new ParallaxTestScene(); } }, diff --git a/samples/Cpp/TestCpp/Resources/app.icf b/samples/Cpp/TestCpp/Resources/app.icf deleted file mode 100644 index 7fdabcd1f2..0000000000 --- a/samples/Cpp/TestCpp/Resources/app.icf +++ /dev/null @@ -1,26 +0,0 @@ -# This file is for configuration settings for your -# application. -# -# The syntax is similar to windows .ini files ie -# -# [GroupName] -# Setting = Value -# -# Which can be read by your application using -# e.g s3eConfigGetString("GroupName", "Setting", string) -# -# All settings must be documented in .config.txt files. -# New settings specific to this application should be -# documented in app.config.txt -# -# Some conditional operations are also permitted, see the -# S3E documentation for details. -[S3E] -MemSize = 100000000 -# Sample only compatible with 480x320 display resolution -WinWidth=480 -WinHeight=320 - -[GL] -AllowNegativeUniformLocation=1 - diff --git a/samples/Cpp/TestCpp/Resources/armature/Dragon.xml b/samples/Cpp/TestCpp/Resources/armature/Dragon.xml index 0b4f52cf06..f531349f7c 100644 --- a/samples/Cpp/TestCpp/Resources/armature/Dragon.xml +++ b/samples/Cpp/TestCpp/Resources/armature/Dragon.xml @@ -1,56 +1,56 @@ - + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + @@ -58,158 +58,286 @@ - - - + + + - + - + - + - - - + + + - - - + + + - + - - - + + + - - - + + + - - - + + + - + - + - + - + - + - - - + + + - + - - - + + + - + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - + - - - + + + - - - + + + - - - + + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/Cpp/TestCpp/Resources/armature/HeroAnimation.ExportJson.REMOVED.git-id b/samples/Cpp/TestCpp/Resources/armature/HeroAnimation.ExportJson.REMOVED.git-id new file mode 100644 index 0000000000..43ba518703 --- /dev/null +++ b/samples/Cpp/TestCpp/Resources/armature/HeroAnimation.ExportJson.REMOVED.git-id @@ -0,0 +1 @@ +d73c3774258671e491d1579a4991bba7c4b4c24c \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Resources/development.icf b/samples/Cpp/TestCpp/Resources/development.icf deleted file mode 100644 index 363d486f04..0000000000 --- a/samples/Cpp/TestCpp/Resources/development.icf +++ /dev/null @@ -1,107 +0,0 @@ -# Settings ICF file automatically generated by S3E development environment - -AccelEnabled = Type=bool, Default="true", Value = "true" -AudioAAC = Type=bool, Default="false", Value = "false" -AudioAACPlus = Type=bool, Default="false", Value = "false" -AudioMIDI = Type=bool, Default="true", Value = "true" -AudioMP3 = Type=bool, Default="true", Value = "true" -AudioPCM = Type=bool, Default="true", Value = "true" -AudioQCP = Type=bool, Default="false", Value = "false" -AudioVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -BacklightTimeout = Type=int, Min=0.000000, Max=120000.000000, Default="10000", Value = "10000" -CompassEnabled = Type=bool, Default="true", Value = "true" -ContactsFromAddrBook = Type=bool, Default="false", Value = "false" -DeviceAdvanceSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Left", Value = "Bottom Left" -DeviceArch = Type=string, Allowed="" "ARM4T" "ARM4" "ARM5T" "ARM5TE" "ARM5TEJ" "ARM6" "ARM6K" "ARM6T2" "ARM6Z" "X86" "PPC" "AMD64" "ARM7", Default="", Value = "" -DeviceBackSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Right", Value = "Bottom Right" -DeviceBatteryLevel = Type=int, Min=0.000000, Max=100.000000, Default="50", Value = "50" -DeviceClass = Type=string, Allowed="UNKNOWN" "SYMBIAN_GENERIC" "SYMBIAN_SERIES60" "SYMBIAN_SERIES60_EMULATOR" "SYMBIAN_UIQ" "SYMBIAN_UIQ_EMULATOR" "BREW_GENERIC" "BREW_QCIF_3D" "BREW_QCIF_25G" "BREW_SQCIF_256" "BREW_QVGA_3G" "WINDOWS_GENERIC" "WINMOBILE_GENERIC" "WINMOBILE_SP" "WINMOBILE_PPC" "LINUX_GENERIC" "LINUX_DESKTOP" "LINUX_EMBED" "WIPI_GENERIC" "NDS_GENERIC" "ARM_SEMIH_GENERIC" "NULCUES_GENERIC" "NGI_GENERIC", Default="WINDOWS_GENERIC", Value = "WINDOWS_GENERIC" -DeviceFPU = Type=string, Allowed="None" "VFP Present", Default="VFP Present", Value = "VFP Present" -DeviceFreeRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceIDInt = Type=int, Default="0", Value = "0" -DeviceIDString = Type=string, Default="", Value = "Samsung Galaxy S" -DeviceIMSI = Type=string, Default="SIMULATOR_IMSI", Value = "SIMULATOR_IMSI" -DeviceLSKIsBack = Type=bool, Default="false", Value = "false" -DeviceLanguage = Type=string, Allowed="UNKNOWN" "ENGLISH" "FRENCH" "GERMAN" "SPANISH" "ITALIAN" "PORTUGUESE" "DUTCH" "TURKISH" "CROATIAN" "CZECH" "DANISH" "FINNISH" "HUNGARIAN" "NORWEGIAN" "POLISH" "RUSSIAN" "SERBIAN" "SLOVAK" "SLOVENIAN" "SWEDISH" "UKRAINIAN" "GREEK" "JAPANESE" "SIMPL_CHINESE" "TRAD_CHINESE" "KOREAN" "ICELANDIC" "FLEMISH" "THAI" "AFRIKAANS" "ALBANIAN" "AMHARIC" "ARABIC" "ARMENIAN" "AZERBAIJANI" "TAGALOG" "BELARUSSIAN" "BENGALI" "BULGARIAN" "BURMESE" "CATALAN" "ESTONIAN" "FARSI" "GAELIC" "GEORGIAN" "GUJARATI" "HEBREW" "HINDI" "INDONESIAN" "IRISH" "KANNADA" "KAZAKH" "KHMER" "LAO" "LATVIAN" "LITHUANIAN" "MACEDONIAN" "MALAY" "MALAYALAM" "MARATHI" "MOLDOVIAN" "MONGOLIAN" "PUNJABI" "ROMANIAN" "SINHALESE" "SOMALI" "SWAHILI" "TAJIK" "TAMIL" "TELUGU" "TIBETAN" "TIGRINYA" "TURKMEN" "URDU" "UZBEK" "VIETNAMESE" "WELSH" "ZULU" "", Default="", Value = "" -DeviceMainsPower = Type=bool, Default="false", Value = "false" -DeviceName = Type=string, Default="My Computer", Value = "My Computer" -DeviceOS = Type=string, Allowed="NONE" "SYMBIAN" "BREW" "WINDOWS" "WINMOBILE" "LINUX" "WIPI" "NDS" "ARM_SEMIH" "NUCLEUS" "NGI" "WINCE" "SHARPEMP" "OSX" "IPHONE" "UIQ" "PS3" "X360" "BADA" "ANDROID" "WEBOS" "QNX", Default="NONE", Value = "ANDROID" -DeviceOSVersion = Type=string, Default="", Value = "" -DeviceOSVersionNumber = Type=int, Default="0", Value = "0" -DevicePhoneNumber = Type=string, Default="0044123456789", Value = "0044123456789" -DeviceTimezone = Type=string, Default="SYSTEM", Value = "SYSTEM" -DeviceTotalRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceUniqueID = Type=string, Default="SIMULATOR_ID", Value = "SIMULATOR_ID" -DeviceUniqueIDInt = Type=int, Default="01234567890", Value = "01234567890" -FileTotalStorageSize = Type=int, Min=0.000000, Max=2147483648.000000, Default="67108864", Value = "67108864" -FileUseSeparateRomRam = Type=bool, Default="true", Value = "true" -FileUseTotalStorageSize = Type=bool, Default="false", Value = "false" -GLAPI = Type=string, Allowed="None" "GLES 1.0 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.1 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.0 Common Profile from Imagination POWERVR(TM)" "GLES 1.1 Common Profile from Imagination POWERVR(TM)" "GLES 2.0 from Imagination POWERVR(TM)" "Obey [S3E] SysGlesVersion .icf setting" "GLES 1.1 Common Profile from Qualcomm Snapdragon(TM)" "GLES 2.0 from Qualcomm Snapdragon(TM)" "GLES 2.0 ANGLE", Default="Obey [S3E] SysGlesVersion .icf setting", Value = "Obey [S3E] SysGlesVersion .icf setting" -GLDontUseHiddenWindow = Type=bool, Default="false", Value = "false" -GLTerminateOnSuspend = Type=bool, Default="false", Value = "false" -GLUsePVRVFrame = Type=bool, Default="false", Value = "false" -KeyboardHasAlpha = Type=bool, Default="true", Value = "true" -KeyboardHasDirection = Type=bool, Default="true", Value = "true" -KeyboardHasKeypad = Type=bool, Default="true", Value = "true" -KeyboardNumpadRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -LicenseExpiryDate = Type=int, Min=0.000000, Max=999999995904.000000, Default="0", Value = "0" -LicenseMinutesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LicenseStatus = Type=string, Allowed="EXPIRED" "DEMO" "USECOUNT" "EXPIRYDATE" "EXPIRYMINSUSE" "PURCHASE" "SUBSCRIPTION" "UPGRADE" "NONCOMMERCIAL", Default="NONCOMMERCIAL", Value = "NONCOMMERCIAL" -LicenseUsesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LocationAltitude = Type=float, Min=-2000.000000, Max=100000.000000, Default="60.0", Value = "60.0" -LocationAvailable = Type=bool, Default="true", Value = "true" -LocationHeading = Type=float, Min=0.000000, Max=359.000000, Default="0.0", Value = "0.0" -LocationHorizontalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="20.0", Value = "20.0" -LocationLatitude = Type=float, Min=-90.000000, Max=90.000000, Default="51.511791", Value = "51.511791" -LocationLongitude = Type=float, Min=-180.000000, Max=180.000000, Default="-0.191084", Value = "-0.191084" -LocationSpeed = Type=float, Min=0.000000, Max=10000.000000, Default="0", Value = "0" -LocationVerticalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="100.0", Value = "100.0" -MacOSSimulatorCustomSettings = Type=string, Default="", Value = "NONE:OSX:480x320" -MacOSSimulatorDevices_ANDROID = Type=string, Allowed="Samsung Galaxy S:480x800:512" "HTC Sensation XL:480x800:768" "Samsung Galaxy Note:800x1280:1024" "Motorola Droid Razr:540x960:1024" "Kindle Fire:1024x600:512" "Samsung Galaxy Tab:1024x600:512", Default="Samsung Galaxy S:480x800:512", Value = "Samsung Galaxy S:480x800:512" -MacOSSimulatorDevices_IPHONE = Type=string, Allowed="iPhone 3GS:320x480:256" "iPhone 4:640x960:512" "iPhone 5:640x1136:1024" "iPad:768x1024:256" "iPad 2:768x1024:512" "iPad 3:1536x2048:1024", Default="iPhone 3GS:320x480:256", Value = "iPhone 3GS:320x480:256" -MacOSSimulatorPlatforms = Type=string, Allowed="IPHONE" "ANDROID", Default="IPHONE", Value = "ANDROID" -MacOSSimulatorUseCustomSettings = Type=bool, Default="true", Value = "false" -MemoryPoison = Type=bool, Default="true", Value = "true" -MemoryPoisonAlloc = Type=int, Min=0.000000, Max=255.000000, Default="170", Value = "170" -MemoryPoisonFree = Type=int, Min=0.000000, Max=255.000000, Default="221", Value = "221" -MemoryPoisonInit = Type=int, Min=0.000000, Max=255.000000, Default="204", Value = "204" -PointerAvailable = Type=bool, Default="true", Value = "true" -PointerMultiSimulationMode = Type=bool, Default="false", Value = "false" -PointerMultiTouchAvailable = Type=bool, Default="false", Value = "false" -PointerStylusType = Type=string, Allowed="INVALID" "STYLUS" "FINGER", Default="INVALID", Value = "INVALID" -PointerType = Type=string, Allowed="INVALID" "MOUSE" "STYLUS", Default="MOUSE", Value = "MOUSE" -SMSEnabled = Type=bool, Default="true", Value = "true" -SMSReceiveEnabled = Type=bool, Default="true", Value = "true" -SocketDNSDelay = Type=int, Min=0.000000, Max=30000.000000, Default="0", Value = "0" -SocketHTTPProxy = Type=string, Default="", Value = "" -SocketHostName = Type=string, Default="", Value = "" -SocketNetworkAvailable = Type=bool, Default="true", Value = "true" -SocketNetworkLoss = Type=bool, Default="false", Value = "false" -SocketNetworkType = Type=string, Allowed="NONE" "UNKNOWN" "LAN" "WLAN" "GPRS" "UMTS" "EVDO" "CDMA2000" "HSDPA" "WIMAX" "BLUETOOTH" "EDGE" "CDMA" "IDEN" "LTE" "EHRPD" "HSPAPLUS", Default="LAN", Value = "LAN" -SocketRecvLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SocketSendLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SoundEnabled = Type=bool, Default="true", Value = "true" -SoundRecordEnabled = Type=bool, Default="true", Value = "true" -SoundSampleRate = Type=int, Allowed="8192" "11025" "16000" "22050" "44100", Default="22050", Value = "22050" -SoundStereo = Type=bool, Default="true", Value = "true" -SoundVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -SurfaceDisableWhenGLIsActive = Type=bool, Default="false", Value = "false" -SurfaceDoubleBuffer = Type=bool, Default="false", Value = "false" -SurfaceHeight = Type=int, Min=128.000000, Max=4096.000000, Default="480", Value = "800" -SurfacePitch = Type=int, Min=0.000000, Max=8192.000000, Default="0", Value = "0" -SurfacePixelType = Type=string, Allowed="RGB444" "RGB555" "RGB565" "RGB666" "RGB888" "BGR444" "BGR555" "BGR565" "BGR666" "BGR888", Default="RGB565", Value = "RGB565" -SurfacePredefinedResolution = Type=string, Allowed="176x200" "176x208" "240x320 (QVGA Portrait)" "240x400" "320x240 (QVGA Landscape)" "320x400" "320x480 (iPhone Portrait)" "400x240" "480x320 (iPhone Landscape)" "360x640 (qHD Portrait)" "640x360 (qHD Landscape)" "480x640 (VGA Portrait)" "480x800 (WVGA Portrait)" "640x480 (VGA Landscape)" "800x400" "800x480 (WVGA Landscape)" "640x960 (iPhone 4 Portrait)" "960x640 (iPhone 4 Landscape)" "640x1136 (iPhone 5 Portrait)" "1136x640 (iPhone 5 Landscape)" "1024x600 (Playbook Landscape)" "600x1024 (Playbook Portrait)" "768x1024 (iPad Portrait)" "1024x768 (iPad Landscape)" "2048x1536 (iPad Retina Landscape)" "1536x2048 (iPad Retina Portrait)", Default="320x480 (iPhone Portrait)", Value = "176x200" -SurfaceRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot90" -SurfaceUnalign = Type=bool, Default="true", Value = "true" -SurfaceUseMultiBuffers = Type=bool, Default="true", Value = "true" -SurfaceWidth = Type=int, Min=128.000000, Max=4096.000000, Default="320", Value = "480" -SymbianSoundLatency = Type=int, Min=20.000000, Max=1400.000000, Default="120", Value = "120" -ThreadEnabled = Type=bool, Default="true", Value = "true" -TimerAccuracy = Type=int, Min=0.000000, Max=1000.000000, Default="0", Value = "0" -TimerHiRes = Type=bool, Default="false", Value = "false" -TimerLocaltimeOffsetHours = Type=string, Allowed="-12" "-11" "-10" "-9" "-8" "-7" "-6" "-5" "-4" "-3" "-2" "-1" "0" "+1" "+2" "+3" "+4" "+5" "+6" "+7" "+8" "+9" "+10" "+11" "+12" "+13" "SYSTEM", Default="SYSTEM", Value = "SYSTEM" -VibraEnabled = Type=bool, Default="true", Value = "true" -Video3GPP = Type=bool, Default="false", Value = "false" -VideoJPEG = Type=bool, Default="true", Value = "true" -VideoMPEG4 = Type=bool, Default="true", Value = "true" -VideoVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" diff --git a/samples/Cpp/TestCpp/Resources/hd/armature/HeroAnimation0.png.REMOVED.git-id b/samples/Cpp/TestCpp/Resources/hd/armature/HeroAnimation0.png.REMOVED.git-id new file mode 100644 index 0000000000..f92a9b8f72 --- /dev/null +++ b/samples/Cpp/TestCpp/Resources/hd/armature/HeroAnimation0.png.REMOVED.git-id @@ -0,0 +1 @@ +ac19b290421fc75a284f603891442ab9796c132a \ No newline at end of file diff --git a/samples/Cpp/TestCpp/proj.android/jni/Application.mk b/samples/Cpp/TestCpp/proj.android/jni/Application.mk index 9761d1692d..47d8add103 100644 --- a/samples/Cpp/TestCpp/proj.android/jni/Application.mk +++ b/samples/Cpp/TestCpp/proj.android/jni/Application.mk @@ -2,4 +2,4 @@ APP_STL := gnustl_static # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Javascript/CocosDragonJS/proj.android/jni/Application.mk b/samples/Javascript/CocosDragonJS/proj.android/jni/Application.mk index 24a7a8cbb3..3666985a1f 100644 --- a/samples/Javascript/CocosDragonJS/proj.android/jni/Application.mk +++ b/samples/Javascript/CocosDragonJS/proj.android/jni/Application.mk @@ -1,7 +1,6 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT=1 -std=c++11 # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Javascript/CrystalCraze/proj.android/jni/Application.mk b/samples/Javascript/CrystalCraze/proj.android/jni/Application.mk index 24a7a8cbb3..3666985a1f 100644 --- a/samples/Javascript/CrystalCraze/proj.android/jni/Application.mk +++ b/samples/Javascript/CrystalCraze/proj.android/jni/Application.mk @@ -1,7 +1,6 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT=1 -std=c++11 # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Javascript/MoonWarriors/proj.android/jni/Application.mk b/samples/Javascript/MoonWarriors/proj.android/jni/Application.mk index 6608c6e10e..47d8add103 100644 --- a/samples/Javascript/MoonWarriors/proj.android/jni/Application.mk +++ b/samples/Javascript/MoonWarriors/proj.android/jni/Application.mk @@ -1,6 +1,5 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT= -std=c++11 # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Javascript/TestJavascript/proj.android/jni/Application.mk b/samples/Javascript/TestJavascript/proj.android/jni/Application.mk index dc8b56b0ac..47d8add103 100644 --- a/samples/Javascript/TestJavascript/proj.android/jni/Application.mk +++ b/samples/Javascript/TestJavascript/proj.android/jni/Application.mk @@ -1,6 +1,5 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT=1 -std=c++11 # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Javascript/WatermelonWithMe/proj.android/jni/Application.mk b/samples/Javascript/WatermelonWithMe/proj.android/jni/Application.mk index dc8b56b0ac..47d8add103 100644 --- a/samples/Javascript/WatermelonWithMe/proj.android/jni/Application.mk +++ b/samples/Javascript/WatermelonWithMe/proj.android/jni/Application.mk @@ -1,6 +1,5 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT=1 -std=c++11 # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Lua/HelloLua/CMakeLists.txt b/samples/Lua/HelloLua/CMakeLists.txt new file mode 100644 index 0000000000..e0d1f3a753 --- /dev/null +++ b/samples/Lua/HelloLua/CMakeLists.txt @@ -0,0 +1,40 @@ +set(APP_NAME hellolua) + +set(SAMPLE_SRC + proj.linux/main.cpp + Classes/AppDelegate.cpp +) + +include_directories( + Classes + ../../../cocos/scripting/lua/bindings + ../../../external/lua/lua + ../../../external/lua/tolua +) + +# add the executable +add_executable(${APP_NAME} + ${SAMPLE_SRC} +) + +target_link_libraries(${APP_NAME} + luabinding + gui + network + cocostudio + cocosbuilder + extensions + audio + cocos2d +) + +set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${APP_NAME}") + +set_target_properties(${APP_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") + +pre_build(${APP_NAME} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/cocos/scripting/lua/script ${APP_BIN_DIR}/Resources + ) diff --git a/samples/Lua/HelloLua/Resources/app.icf b/samples/Lua/HelloLua/Resources/app.icf deleted file mode 100644 index dec7c07959..0000000000 --- a/samples/Lua/HelloLua/Resources/app.icf +++ /dev/null @@ -1,23 +0,0 @@ -# This file is for configuration settings for your -# application. -# -# The syntax is similar to windows .ini files ie -# -# [GroupName] -# Setting = Value -# -# Which can be read by your application using -# e.g s3eConfigGetString("GroupName", "Setting", string) -# -# All settings must be documented in .config.txt files. -# New settings specific to this application should be -# documented in app.config.txt -# -# Some conditional operations are also permitted, see the -# S3E documentation for details. -[S3E] -MemSize = 10000000 - -[GL] -AllowNegativeUniformLocation=1 - diff --git a/samples/Lua/HelloLua/Resources/development.icf b/samples/Lua/HelloLua/Resources/development.icf deleted file mode 100644 index 09e69865f0..0000000000 --- a/samples/Lua/HelloLua/Resources/development.icf +++ /dev/null @@ -1,107 +0,0 @@ -# Settings ICF file automatically generated by S3E development environment - -AccelEnabled = Type=bool, Default="true", Value = "true" -AudioAAC = Type=bool, Default="false", Value = "false" -AudioAACPlus = Type=bool, Default="false", Value = "false" -AudioMIDI = Type=bool, Default="true", Value = "true" -AudioMP3 = Type=bool, Default="true", Value = "true" -AudioPCM = Type=bool, Default="true", Value = "true" -AudioQCP = Type=bool, Default="false", Value = "false" -AudioVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -BacklightTimeout = Type=int, Min=0.000000, Max=120000.000000, Default="10000", Value = "10000" -CompassEnabled = Type=bool, Default="true", Value = "true" -ContactsFromAddrBook = Type=bool, Default="false", Value = "false" -DeviceAdvanceSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Left", Value = "Bottom Left" -DeviceArch = Type=string, Allowed="" "ARM4T" "ARM4" "ARM5T" "ARM5TE" "ARM5TEJ" "ARM6" "ARM6K" "ARM6T2" "ARM6Z" "X86" "PPC" "AMD64" "ARM7", Default="", Value = "" -DeviceBackSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Right", Value = "Bottom Right" -DeviceBatteryLevel = Type=int, Min=0.000000, Max=100.000000, Default="50", Value = "50" -DeviceClass = Type=string, Allowed="UNKNOWN" "SYMBIAN_GENERIC" "SYMBIAN_SERIES60" "SYMBIAN_SERIES60_EMULATOR" "SYMBIAN_UIQ" "SYMBIAN_UIQ_EMULATOR" "BREW_GENERIC" "BREW_QCIF_3D" "BREW_QCIF_25G" "BREW_SQCIF_256" "BREW_QVGA_3G" "WINDOWS_GENERIC" "WINMOBILE_GENERIC" "WINMOBILE_SP" "WINMOBILE_PPC" "LINUX_GENERIC" "LINUX_DESKTOP" "LINUX_EMBED" "WIPI_GENERIC" "NDS_GENERIC" "ARM_SEMIH_GENERIC" "NULCUES_GENERIC" "NGI_GENERIC", Default="WINDOWS_GENERIC", Value = "WINDOWS_GENERIC" -DeviceFPU = Type=string, Allowed="None" "VFP Present", Default="VFP Present", Value = "VFP Present" -DeviceFreeRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceIDInt = Type=int, Default="0", Value = "0" -DeviceIDString = Type=string, Default="", Value = "" -DeviceIMSI = Type=string, Default="SIMULATOR_IMSI", Value = "SIMULATOR_IMSI" -DeviceLSKIsBack = Type=bool, Default="false", Value = "false" -DeviceLanguage = Type=string, Allowed="UNKNOWN" "ENGLISH" "FRENCH" "GERMAN" "SPANISH" "ITALIAN" "PORTUGUESE" "DUTCH" "TURKISH" "CROATIAN" "CZECH" "DANISH" "FINNISH" "HUNGARIAN" "NORWEGIAN" "POLISH" "RUSSIAN" "SERBIAN" "SLOVAK" "SLOVENIAN" "SWEDISH" "UKRAINIAN" "GREEK" "JAPANESE" "SIMPL_CHINESE" "TRAD_CHINESE" "KOREAN" "ICELANDIC" "FLEMISH" "THAI" "AFRIKAANS" "ALBANIAN" "AMHARIC" "ARABIC" "ARMENIAN" "AZERBAIJANI" "TAGALOG" "BELARUSSIAN" "BENGALI" "BULGARIAN" "BURMESE" "CATALAN" "ESTONIAN" "FARSI" "GAELIC" "GEORGIAN" "GUJARATI" "HEBREW" "HINDI" "INDONESIAN" "IRISH" "KANNADA" "KAZAKH" "KHMER" "LAO" "LATVIAN" "LITHUANIAN" "MACEDONIAN" "MALAY" "MALAYALAM" "MARATHI" "MOLDOVIAN" "MONGOLIAN" "PUNJABI" "ROMANIAN" "SINHALESE" "SOMALI" "SWAHILI" "TAJIK" "TAMIL" "TELUGU" "TIBETAN" "TIGRINYA" "TURKMEN" "URDU" "UZBEK" "VIETNAMESE" "WELSH" "ZULU" "", Default="", Value = "" -DeviceMainsPower = Type=bool, Default="false", Value = "false" -DeviceName = Type=string, Default="My Computer", Value = "My Computer" -DeviceOS = Type=string, Allowed="NONE" "SYMBIAN" "BREW" "WINDOWS" "WINMOBILE" "LINUX" "WIPI" "NDS" "ARM_SEMIH" "NUCLEUS" "NGI" "WINCE" "SHARPEMP" "OSX" "IPHONE" "UIQ" "PS3" "X360" "BADA" "ANDROID" "WEBOS" "QNX", Default="NONE", Value = "NONE" -DeviceOSVersion = Type=string, Default="", Value = "" -DeviceOSVersionNumber = Type=int, Default="0", Value = "0" -DevicePhoneNumber = Type=string, Default="0044123456789", Value = "0044123456789" -DeviceTimezone = Type=string, Default="SYSTEM", Value = "SYSTEM" -DeviceTotalRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceUniqueID = Type=string, Default="SIMULATOR_ID", Value = "SIMULATOR_ID" -DeviceUniqueIDInt = Type=int, Default="01234567890", Value = "01234567890" -FileTotalStorageSize = Type=int, Min=0.000000, Max=2147483648.000000, Default="67108864", Value = "67108864" -FileUseSeparateRomRam = Type=bool, Default="true", Value = "true" -FileUseTotalStorageSize = Type=bool, Default="false", Value = "false" -GLAPI = Type=string, Allowed="None" "GLES 1.0 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.1 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.0 Common Profile from Imagination POWERVR(TM)" "GLES 1.1 Common Profile from Imagination POWERVR(TM)" "GLES 2.0 from Imagination POWERVR(TM)" "Obey [S3E] SysGlesVersion .icf setting" "GLES 1.1 Common Profile from Qualcomm Snapdragon(TM)" "GLES 2.0 from Qualcomm Snapdragon(TM)" "GLES 2.0 ANGLE", Default="Obey [S3E] SysGlesVersion .icf setting", Value = "Obey [S3E] SysGlesVersion .icf setting" -GLDontUseHiddenWindow = Type=bool, Default="false", Value = "false" -GLTerminateOnSuspend = Type=bool, Default="false", Value = "false" -GLUsePVRVFrame = Type=bool, Default="false", Value = "false" -KeyboardHasAlpha = Type=bool, Default="true", Value = "true" -KeyboardHasDirection = Type=bool, Default="true", Value = "true" -KeyboardHasKeypad = Type=bool, Default="true", Value = "true" -KeyboardNumpadRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -LicenseExpiryDate = Type=int, Min=0.000000, Max=999999995904.000000, Default="0", Value = "0" -LicenseMinutesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LicenseStatus = Type=string, Allowed="EXPIRED" "DEMO" "USECOUNT" "EXPIRYDATE" "EXPIRYMINSUSE" "PURCHASE" "SUBSCRIPTION" "UPGRADE" "NONCOMMERCIAL", Default="NONCOMMERCIAL", Value = "NONCOMMERCIAL" -LicenseUsesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LocationAltitude = Type=float, Min=-2000.000000, Max=100000.000000, Default="60.0", Value = "60.0" -LocationAvailable = Type=bool, Default="true", Value = "true" -LocationHeading = Type=float, Min=0.000000, Max=359.000000, Default="0.0", Value = "0.0" -LocationHorizontalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="20.0", Value = "20.0" -LocationLatitude = Type=float, Min=-90.000000, Max=90.000000, Default="51.511791", Value = "51.511791" -LocationLongitude = Type=float, Min=-180.000000, Max=180.000000, Default="-0.191084", Value = "-0.191084" -LocationSpeed = Type=float, Min=0.000000, Max=10000.000000, Default="0", Value = "0" -LocationVerticalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="100.0", Value = "100.0" -MacOSSimulatorCustomSettings = Type=string, Default="", Value = "" -MacOSSimulatorDevices_ANDROID = Type=string, Allowed="Samsung Galaxy S:480x800:512" "HTC Sensation XL:480x800:768" "Samsung Galaxy Note:800x1280:1024" "Motorola Droid Razr:540x960:1024" "Kindle Fire:1024x600:512" "Samsung Galaxy Tab:1024x600:512", Default="Samsung Galaxy S:480x800:512", Value = "Samsung Galaxy S:480x800:512" -MacOSSimulatorDevices_IPHONE = Type=string, Allowed="iPhone 3GS:320x480:256" "iPhone 4:640x960:512" "iPhone 5:640x1136:1024" "iPad:768x1024:256" "iPad 2:768x1024:512" "iPad 3:1536x2048:1024", Default="iPhone 3GS:320x480:256", Value = "iPhone 3GS:320x480:256" -MacOSSimulatorPlatforms = Type=string, Allowed="IPHONE" "ANDROID", Default="IPHONE", Value = "IPHONE" -MacOSSimulatorUseCustomSettings = Type=bool, Default="true", Value = "true" -MemoryPoison = Type=bool, Default="true", Value = "true" -MemoryPoisonAlloc = Type=int, Min=0.000000, Max=255.000000, Default="170", Value = "170" -MemoryPoisonFree = Type=int, Min=0.000000, Max=255.000000, Default="221", Value = "221" -MemoryPoisonInit = Type=int, Min=0.000000, Max=255.000000, Default="204", Value = "204" -PointerAvailable = Type=bool, Default="true", Value = "true" -PointerMultiSimulationMode = Type=bool, Default="false", Value = "false" -PointerMultiTouchAvailable = Type=bool, Default="false", Value = "false" -PointerStylusType = Type=string, Allowed="INVALID" "STYLUS" "FINGER", Default="INVALID", Value = "INVALID" -PointerType = Type=string, Allowed="INVALID" "MOUSE" "STYLUS", Default="MOUSE", Value = "MOUSE" -SMSEnabled = Type=bool, Default="true", Value = "true" -SMSReceiveEnabled = Type=bool, Default="true", Value = "true" -SocketDNSDelay = Type=int, Min=0.000000, Max=30000.000000, Default="0", Value = "0" -SocketHTTPProxy = Type=string, Default="", Value = "" -SocketHostName = Type=string, Default="", Value = "" -SocketNetworkAvailable = Type=bool, Default="true", Value = "true" -SocketNetworkLoss = Type=bool, Default="false", Value = "false" -SocketNetworkType = Type=string, Allowed="NONE" "UNKNOWN" "LAN" "WLAN" "GPRS" "UMTS" "EVDO" "CDMA2000" "HSDPA" "WIMAX" "BLUETOOTH" "EDGE" "CDMA" "IDEN" "LTE" "EHRPD" "HSPAPLUS", Default="LAN", Value = "LAN" -SocketRecvLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SocketSendLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SoundEnabled = Type=bool, Default="true", Value = "true" -SoundRecordEnabled = Type=bool, Default="true", Value = "true" -SoundSampleRate = Type=int, Allowed="8192" "11025" "16000" "22050" "44100", Default="22050", Value = "22050" -SoundStereo = Type=bool, Default="true", Value = "true" -SoundVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -SurfaceDisableWhenGLIsActive = Type=bool, Default="false", Value = "false" -SurfaceDoubleBuffer = Type=bool, Default="false", Value = "false" -SurfaceHeight = Type=int, Min=128.000000, Max=4096.000000, Default="480", Value = "320" -SurfacePitch = Type=int, Min=0.000000, Max=8192.000000, Default="0", Value = "0" -SurfacePixelType = Type=string, Allowed="RGB444" "RGB555" "RGB565" "RGB666" "RGB888" "BGR444" "BGR555" "BGR565" "BGR666" "BGR888", Default="RGB565", Value = "RGB565" -SurfacePredefinedResolution = Type=string, Allowed="176x200" "176x208" "240x320 (QVGA Portrait)" "240x400" "320x240 (QVGA Landscape)" "320x400" "320x480 (iPhone Portrait)" "400x240" "480x320 (iPhone Landscape)" "360x640 (qHD Portrait)" "640x360 (qHD Landscape)" "480x640 (VGA Portrait)" "480x800 (WVGA Portrait)" "640x480 (VGA Landscape)" "800x400" "800x480 (WVGA Landscape)" "640x960 (iPhone 4 Portrait)" "960x640 (iPhone 4 Landscape)" "640x1136 (iPhone 5 Portrait)" "1136x640 (iPhone 5 Landscape)" "1024x600 (Playbook Landscape)" "600x1024 (Playbook Portrait)" "768x1024 (iPad Portrait)" "1024x768 (iPad Landscape)" "2048x1536 (iPad Retina Landscape)" "1536x2048 (iPad Retina Portrait)", Default="320x480 (iPhone Portrait)", Value = "176x200" -SurfaceRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -SurfaceUnalign = Type=bool, Default="true", Value = "true" -SurfaceUseMultiBuffers = Type=bool, Default="true", Value = "true" -SurfaceWidth = Type=int, Min=128.000000, Max=4096.000000, Default="320", Value = "480" -SymbianSoundLatency = Type=int, Min=20.000000, Max=1400.000000, Default="120", Value = "120" -ThreadEnabled = Type=bool, Default="true", Value = "true" -TimerAccuracy = Type=int, Min=0.000000, Max=1000.000000, Default="0", Value = "0" -TimerHiRes = Type=bool, Default="false", Value = "false" -TimerLocaltimeOffsetHours = Type=string, Allowed="-12" "-11" "-10" "-9" "-8" "-7" "-6" "-5" "-4" "-3" "-2" "-1" "0" "+1" "+2" "+3" "+4" "+5" "+6" "+7" "+8" "+9" "+10" "+11" "+12" "+13" "SYSTEM", Default="SYSTEM", Value = "SYSTEM" -VibraEnabled = Type=bool, Default="true", Value = "true" -Video3GPP = Type=bool, Default="false", Value = "false" -VideoJPEG = Type=bool, Default="true", Value = "true" -VideoMPEG4 = Type=bool, Default="true", Value = "true" -VideoVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" diff --git a/samples/Lua/HelloLua/proj.android/jni/Application.mk b/samples/Lua/HelloLua/proj.android/jni/Application.mk index a829fc0f48..540e49c358 100644 --- a/samples/Lua/HelloLua/proj.android/jni/Application.mk +++ b/samples/Lua/HelloLua/proj.android/jni/Application.mk @@ -2,7 +2,7 @@ APP_STL := gnustl_static # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char -APP_CPPFLAGS += -fexceptions +APP_CPPFLAGS += -fexceptions diff --git a/samples/Lua/TestLua/CMakeLists.txt b/samples/Lua/TestLua/CMakeLists.txt new file mode 100644 index 0000000000..743f3eeb3f --- /dev/null +++ b/samples/Lua/TestLua/CMakeLists.txt @@ -0,0 +1,42 @@ +set(APP_NAME testlua) + +set(SAMPLE_SRC + proj.linux/main.cpp + Classes/AppDelegate.cpp +) + +include_directories( + Classes + ../../../cocos/scripting/lua/bindings + ../../../external/lua/lua + ../../../external/lua/tolua +) + +# add the executable +add_executable(${APP_NAME} + ${SAMPLE_SRC} +) + +target_link_libraries(${APP_NAME} + luabinding + gui + network + cocostudio + cocosbuilder + extensions + audio + cocos2d +) + +set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${APP_NAME}") + +set_target_properties(${APP_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") + +pre_build(${APP_NAME} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/cocos/scripting/lua/script ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/samples/Cpp/TestCpp/Resources ${APP_BIN_DIR}/Resources + ) + diff --git a/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp b/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp index e3d6377f0b..a254c2cbbd 100644 --- a/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp +++ b/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp @@ -26,10 +26,7 @@ static int lua_cocos2dx_createDownloadDir(lua_State* L) return 0; int argc = lua_gettop(L); -#if COCOS2D_DEBUG >= 1 - tolua_Error tolua_err; -#endif - + if (0 == argc) { std::string pathToSave = FileUtils::getInstance()->getWritablePath(); @@ -50,18 +47,11 @@ static int lua_cocos2dx_createDownloadDir(lua_State* L) } #endif tolua_pushstring(L, pathToSave.c_str()); - CCLOG("the path to save is %s",pathToSave.c_str()); return 1; } CCLOG("'createDownloadDir' function wrong number of arguments: %d, was expecting %d\n", argc, 0); return 0; - -#if COCOS2D_DEBUG >= 1 -tolua_lerror: - tolua_error(L,"#ferror in function 'createDownloadDir'.",&tolua_err); - return 0; -#endif } static int lua_cocos2dx_deleteDownloadDir(lua_State* L) diff --git a/samples/Lua/TestLua/Resources/app.icf b/samples/Lua/TestLua/Resources/app.icf deleted file mode 100644 index dbc72b4d77..0000000000 --- a/samples/Lua/TestLua/Resources/app.icf +++ /dev/null @@ -1,26 +0,0 @@ -# This file is for configuration settings for your -# application. -# -# The syntax is similar to windows .ini files ie -# -# [GroupName] -# Setting = Value -# -# Which can be read by your application using -# e.g s3eConfigGetString("GroupName", "Setting", string) -# -# All settings must be documented in .config.txt files. -# New settings specific to this application should be -# documented in app.config.txt -# -# Some conditional operations are also permitted, see the -# S3E documentation for details. -[S3E] -MemSize = 10000000 -# Sample only compatible with 480x320 display resolution -WinWidth=480 -WinHeight=320 - -[GL] -AllowNegativeUniformLocation=1 - diff --git a/samples/Lua/TestLua/Resources/development.icf b/samples/Lua/TestLua/Resources/development.icf deleted file mode 100644 index 09e69865f0..0000000000 --- a/samples/Lua/TestLua/Resources/development.icf +++ /dev/null @@ -1,107 +0,0 @@ -# Settings ICF file automatically generated by S3E development environment - -AccelEnabled = Type=bool, Default="true", Value = "true" -AudioAAC = Type=bool, Default="false", Value = "false" -AudioAACPlus = Type=bool, Default="false", Value = "false" -AudioMIDI = Type=bool, Default="true", Value = "true" -AudioMP3 = Type=bool, Default="true", Value = "true" -AudioPCM = Type=bool, Default="true", Value = "true" -AudioQCP = Type=bool, Default="false", Value = "false" -AudioVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -BacklightTimeout = Type=int, Min=0.000000, Max=120000.000000, Default="10000", Value = "10000" -CompassEnabled = Type=bool, Default="true", Value = "true" -ContactsFromAddrBook = Type=bool, Default="false", Value = "false" -DeviceAdvanceSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Left", Value = "Bottom Left" -DeviceArch = Type=string, Allowed="" "ARM4T" "ARM4" "ARM5T" "ARM5TE" "ARM5TEJ" "ARM6" "ARM6K" "ARM6T2" "ARM6Z" "X86" "PPC" "AMD64" "ARM7", Default="", Value = "" -DeviceBackSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Right", Value = "Bottom Right" -DeviceBatteryLevel = Type=int, Min=0.000000, Max=100.000000, Default="50", Value = "50" -DeviceClass = Type=string, Allowed="UNKNOWN" "SYMBIAN_GENERIC" "SYMBIAN_SERIES60" "SYMBIAN_SERIES60_EMULATOR" "SYMBIAN_UIQ" "SYMBIAN_UIQ_EMULATOR" "BREW_GENERIC" "BREW_QCIF_3D" "BREW_QCIF_25G" "BREW_SQCIF_256" "BREW_QVGA_3G" "WINDOWS_GENERIC" "WINMOBILE_GENERIC" "WINMOBILE_SP" "WINMOBILE_PPC" "LINUX_GENERIC" "LINUX_DESKTOP" "LINUX_EMBED" "WIPI_GENERIC" "NDS_GENERIC" "ARM_SEMIH_GENERIC" "NULCUES_GENERIC" "NGI_GENERIC", Default="WINDOWS_GENERIC", Value = "WINDOWS_GENERIC" -DeviceFPU = Type=string, Allowed="None" "VFP Present", Default="VFP Present", Value = "VFP Present" -DeviceFreeRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceIDInt = Type=int, Default="0", Value = "0" -DeviceIDString = Type=string, Default="", Value = "" -DeviceIMSI = Type=string, Default="SIMULATOR_IMSI", Value = "SIMULATOR_IMSI" -DeviceLSKIsBack = Type=bool, Default="false", Value = "false" -DeviceLanguage = Type=string, Allowed="UNKNOWN" "ENGLISH" "FRENCH" "GERMAN" "SPANISH" "ITALIAN" "PORTUGUESE" "DUTCH" "TURKISH" "CROATIAN" "CZECH" "DANISH" "FINNISH" "HUNGARIAN" "NORWEGIAN" "POLISH" "RUSSIAN" "SERBIAN" "SLOVAK" "SLOVENIAN" "SWEDISH" "UKRAINIAN" "GREEK" "JAPANESE" "SIMPL_CHINESE" "TRAD_CHINESE" "KOREAN" "ICELANDIC" "FLEMISH" "THAI" "AFRIKAANS" "ALBANIAN" "AMHARIC" "ARABIC" "ARMENIAN" "AZERBAIJANI" "TAGALOG" "BELARUSSIAN" "BENGALI" "BULGARIAN" "BURMESE" "CATALAN" "ESTONIAN" "FARSI" "GAELIC" "GEORGIAN" "GUJARATI" "HEBREW" "HINDI" "INDONESIAN" "IRISH" "KANNADA" "KAZAKH" "KHMER" "LAO" "LATVIAN" "LITHUANIAN" "MACEDONIAN" "MALAY" "MALAYALAM" "MARATHI" "MOLDOVIAN" "MONGOLIAN" "PUNJABI" "ROMANIAN" "SINHALESE" "SOMALI" "SWAHILI" "TAJIK" "TAMIL" "TELUGU" "TIBETAN" "TIGRINYA" "TURKMEN" "URDU" "UZBEK" "VIETNAMESE" "WELSH" "ZULU" "", Default="", Value = "" -DeviceMainsPower = Type=bool, Default="false", Value = "false" -DeviceName = Type=string, Default="My Computer", Value = "My Computer" -DeviceOS = Type=string, Allowed="NONE" "SYMBIAN" "BREW" "WINDOWS" "WINMOBILE" "LINUX" "WIPI" "NDS" "ARM_SEMIH" "NUCLEUS" "NGI" "WINCE" "SHARPEMP" "OSX" "IPHONE" "UIQ" "PS3" "X360" "BADA" "ANDROID" "WEBOS" "QNX", Default="NONE", Value = "NONE" -DeviceOSVersion = Type=string, Default="", Value = "" -DeviceOSVersionNumber = Type=int, Default="0", Value = "0" -DevicePhoneNumber = Type=string, Default="0044123456789", Value = "0044123456789" -DeviceTimezone = Type=string, Default="SYSTEM", Value = "SYSTEM" -DeviceTotalRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceUniqueID = Type=string, Default="SIMULATOR_ID", Value = "SIMULATOR_ID" -DeviceUniqueIDInt = Type=int, Default="01234567890", Value = "01234567890" -FileTotalStorageSize = Type=int, Min=0.000000, Max=2147483648.000000, Default="67108864", Value = "67108864" -FileUseSeparateRomRam = Type=bool, Default="true", Value = "true" -FileUseTotalStorageSize = Type=bool, Default="false", Value = "false" -GLAPI = Type=string, Allowed="None" "GLES 1.0 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.1 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.0 Common Profile from Imagination POWERVR(TM)" "GLES 1.1 Common Profile from Imagination POWERVR(TM)" "GLES 2.0 from Imagination POWERVR(TM)" "Obey [S3E] SysGlesVersion .icf setting" "GLES 1.1 Common Profile from Qualcomm Snapdragon(TM)" "GLES 2.0 from Qualcomm Snapdragon(TM)" "GLES 2.0 ANGLE", Default="Obey [S3E] SysGlesVersion .icf setting", Value = "Obey [S3E] SysGlesVersion .icf setting" -GLDontUseHiddenWindow = Type=bool, Default="false", Value = "false" -GLTerminateOnSuspend = Type=bool, Default="false", Value = "false" -GLUsePVRVFrame = Type=bool, Default="false", Value = "false" -KeyboardHasAlpha = Type=bool, Default="true", Value = "true" -KeyboardHasDirection = Type=bool, Default="true", Value = "true" -KeyboardHasKeypad = Type=bool, Default="true", Value = "true" -KeyboardNumpadRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -LicenseExpiryDate = Type=int, Min=0.000000, Max=999999995904.000000, Default="0", Value = "0" -LicenseMinutesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LicenseStatus = Type=string, Allowed="EXPIRED" "DEMO" "USECOUNT" "EXPIRYDATE" "EXPIRYMINSUSE" "PURCHASE" "SUBSCRIPTION" "UPGRADE" "NONCOMMERCIAL", Default="NONCOMMERCIAL", Value = "NONCOMMERCIAL" -LicenseUsesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LocationAltitude = Type=float, Min=-2000.000000, Max=100000.000000, Default="60.0", Value = "60.0" -LocationAvailable = Type=bool, Default="true", Value = "true" -LocationHeading = Type=float, Min=0.000000, Max=359.000000, Default="0.0", Value = "0.0" -LocationHorizontalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="20.0", Value = "20.0" -LocationLatitude = Type=float, Min=-90.000000, Max=90.000000, Default="51.511791", Value = "51.511791" -LocationLongitude = Type=float, Min=-180.000000, Max=180.000000, Default="-0.191084", Value = "-0.191084" -LocationSpeed = Type=float, Min=0.000000, Max=10000.000000, Default="0", Value = "0" -LocationVerticalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="100.0", Value = "100.0" -MacOSSimulatorCustomSettings = Type=string, Default="", Value = "" -MacOSSimulatorDevices_ANDROID = Type=string, Allowed="Samsung Galaxy S:480x800:512" "HTC Sensation XL:480x800:768" "Samsung Galaxy Note:800x1280:1024" "Motorola Droid Razr:540x960:1024" "Kindle Fire:1024x600:512" "Samsung Galaxy Tab:1024x600:512", Default="Samsung Galaxy S:480x800:512", Value = "Samsung Galaxy S:480x800:512" -MacOSSimulatorDevices_IPHONE = Type=string, Allowed="iPhone 3GS:320x480:256" "iPhone 4:640x960:512" "iPhone 5:640x1136:1024" "iPad:768x1024:256" "iPad 2:768x1024:512" "iPad 3:1536x2048:1024", Default="iPhone 3GS:320x480:256", Value = "iPhone 3GS:320x480:256" -MacOSSimulatorPlatforms = Type=string, Allowed="IPHONE" "ANDROID", Default="IPHONE", Value = "IPHONE" -MacOSSimulatorUseCustomSettings = Type=bool, Default="true", Value = "true" -MemoryPoison = Type=bool, Default="true", Value = "true" -MemoryPoisonAlloc = Type=int, Min=0.000000, Max=255.000000, Default="170", Value = "170" -MemoryPoisonFree = Type=int, Min=0.000000, Max=255.000000, Default="221", Value = "221" -MemoryPoisonInit = Type=int, Min=0.000000, Max=255.000000, Default="204", Value = "204" -PointerAvailable = Type=bool, Default="true", Value = "true" -PointerMultiSimulationMode = Type=bool, Default="false", Value = "false" -PointerMultiTouchAvailable = Type=bool, Default="false", Value = "false" -PointerStylusType = Type=string, Allowed="INVALID" "STYLUS" "FINGER", Default="INVALID", Value = "INVALID" -PointerType = Type=string, Allowed="INVALID" "MOUSE" "STYLUS", Default="MOUSE", Value = "MOUSE" -SMSEnabled = Type=bool, Default="true", Value = "true" -SMSReceiveEnabled = Type=bool, Default="true", Value = "true" -SocketDNSDelay = Type=int, Min=0.000000, Max=30000.000000, Default="0", Value = "0" -SocketHTTPProxy = Type=string, Default="", Value = "" -SocketHostName = Type=string, Default="", Value = "" -SocketNetworkAvailable = Type=bool, Default="true", Value = "true" -SocketNetworkLoss = Type=bool, Default="false", Value = "false" -SocketNetworkType = Type=string, Allowed="NONE" "UNKNOWN" "LAN" "WLAN" "GPRS" "UMTS" "EVDO" "CDMA2000" "HSDPA" "WIMAX" "BLUETOOTH" "EDGE" "CDMA" "IDEN" "LTE" "EHRPD" "HSPAPLUS", Default="LAN", Value = "LAN" -SocketRecvLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SocketSendLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SoundEnabled = Type=bool, Default="true", Value = "true" -SoundRecordEnabled = Type=bool, Default="true", Value = "true" -SoundSampleRate = Type=int, Allowed="8192" "11025" "16000" "22050" "44100", Default="22050", Value = "22050" -SoundStereo = Type=bool, Default="true", Value = "true" -SoundVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -SurfaceDisableWhenGLIsActive = Type=bool, Default="false", Value = "false" -SurfaceDoubleBuffer = Type=bool, Default="false", Value = "false" -SurfaceHeight = Type=int, Min=128.000000, Max=4096.000000, Default="480", Value = "320" -SurfacePitch = Type=int, Min=0.000000, Max=8192.000000, Default="0", Value = "0" -SurfacePixelType = Type=string, Allowed="RGB444" "RGB555" "RGB565" "RGB666" "RGB888" "BGR444" "BGR555" "BGR565" "BGR666" "BGR888", Default="RGB565", Value = "RGB565" -SurfacePredefinedResolution = Type=string, Allowed="176x200" "176x208" "240x320 (QVGA Portrait)" "240x400" "320x240 (QVGA Landscape)" "320x400" "320x480 (iPhone Portrait)" "400x240" "480x320 (iPhone Landscape)" "360x640 (qHD Portrait)" "640x360 (qHD Landscape)" "480x640 (VGA Portrait)" "480x800 (WVGA Portrait)" "640x480 (VGA Landscape)" "800x400" "800x480 (WVGA Landscape)" "640x960 (iPhone 4 Portrait)" "960x640 (iPhone 4 Landscape)" "640x1136 (iPhone 5 Portrait)" "1136x640 (iPhone 5 Landscape)" "1024x600 (Playbook Landscape)" "600x1024 (Playbook Portrait)" "768x1024 (iPad Portrait)" "1024x768 (iPad Landscape)" "2048x1536 (iPad Retina Landscape)" "1536x2048 (iPad Retina Portrait)", Default="320x480 (iPhone Portrait)", Value = "176x200" -SurfaceRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -SurfaceUnalign = Type=bool, Default="true", Value = "true" -SurfaceUseMultiBuffers = Type=bool, Default="true", Value = "true" -SurfaceWidth = Type=int, Min=128.000000, Max=4096.000000, Default="320", Value = "480" -SymbianSoundLatency = Type=int, Min=20.000000, Max=1400.000000, Default="120", Value = "120" -ThreadEnabled = Type=bool, Default="true", Value = "true" -TimerAccuracy = Type=int, Min=0.000000, Max=1000.000000, Default="0", Value = "0" -TimerHiRes = Type=bool, Default="false", Value = "false" -TimerLocaltimeOffsetHours = Type=string, Allowed="-12" "-11" "-10" "-9" "-8" "-7" "-6" "-5" "-4" "-3" "-2" "-1" "0" "+1" "+2" "+3" "+4" "+5" "+6" "+7" "+8" "+9" "+10" "+11" "+12" "+13" "SYSTEM", Default="SYSTEM", Value = "SYSTEM" -VibraEnabled = Type=bool, Default="true", Value = "true" -Video3GPP = Type=bool, Default="false", Value = "false" -VideoJPEG = Type=bool, Default="true", Value = "true" -VideoMPEG4 = Type=bool, Default="true", Value = "true" -VideoVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" diff --git a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua index 66a224d9e2..446854de11 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua @@ -4,16 +4,15 @@ local scheduler = cc.Director:getInstance():getScheduler() local ArmatureTestIndex = { TEST_COCOSTUDIO_WITH_SKELETON = 1, - TEST_COCOSTUDIO_WITHOUT_SKELETON = 2, - TEST_DRAGON_BONES_2_0 = 3, - TEST_PERFORMANCE = 4, - TEST_CHANGE_ZORDER = 5, - TEST_ANIMATION_EVENT = 6, - TEST_PARTICLE_DISPLAY = 7, - TEST_USE_DIFFERENT_PICTURE = 8, - TEST_BOUDINGBOX = 9, - TEST_ANCHORPOINT = 10, - TEST_ARMATURE_NESTING = 11, + TEST_DRAGON_BONES_2_0 = 2, + TEST_PERFORMANCE = 3, + TEST_CHANGE_ZORDER = 4, + TEST_ANIMATION_EVENT = 5, + TEST_PARTICLE_DISPLAY = 6, + TEST_USE_DIFFERENT_PICTURE = 7, + TEST_BOUDINGBOX = 8, + TEST_ANCHORPOINT = 9, + TEST_ARMATURE_NESTING = 10, } local armatureSceneIdx = ArmatureTestIndex.TEST_COCOSTUDIO_WITH_SKELETON @@ -31,13 +30,13 @@ function ArmatureTestScene.extend(target) end function ArmatureTestScene:runThisTest() - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/TestBone0.png", "armature/TestBone0.plist", "armature/TestBone.json") - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/Cowboy0.png", "armature/Cowboy0.plist", "armature/Cowboy.ExportJson") - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/knight.png", "armature/knight.plist", "armature/knight.xml") - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/weapon.png", "armature/weapon.plist", "armature/weapon.xml") - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/robot.png", "armature/robot.plist", "armature/robot.xml") - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/cyborg.png", "armature/cyborg.plist", "armature/cyborg.xml") - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/Dragon.png", "armature/Dragon.plist", "armature/Dragon.xml") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/TestBone0.png", "armature/TestBone0.plist", "armature/TestBone.json") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/Cowboy0.png", "armature/Cowboy0.plist", "armature/Cowboy.ExportJson") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/knight.png", "armature/knight.plist", "armature/knight.xml") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/weapon.png", "armature/weapon.plist", "armature/weapon.xml") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/robot.png", "armature/robot.plist", "armature/robot.xml") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/cyborg.png", "armature/cyborg.plist", "armature/cyborg.xml") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/Dragon.png", "armature/Dragon.plist", "armature/Dragon.xml") armatureSceneIdx = ArmatureTestIndex.TEST_COCOSTUDIO_WITH_SKELETON self:addChild(restartArmatureTest()) @@ -59,7 +58,7 @@ function ArmatureTestScene.create() end function ArmatureTestScene.toMainMenuCallback() - cc.ArmatureDataManager:purgeArmatureSystem() + ccs.ArmatureDataManager:purgeArmatureSystem() end local ArmatureTestLayer = class("ArmatureTestLayer") @@ -72,8 +71,6 @@ end function ArmatureTestLayer.title(idx) if ArmatureTestIndex.TEST_COCOSTUDIO_WITH_SKELETON == idx then return "Test Export From CocoStudio With Skeleton Effect" - elseif ArmatureTestIndex.TEST_COCOSTUDIO_WITHOUT_SKELETON == idx then - return "Test Export From CocoStudio Without Skeleton Effect" elseif ArmatureTestIndex.TEST_DRAGON_BONES_2_0 == idx then return "Test Export From DragonBones version 2.0" elseif ArmatureTestIndex.TEST_PERFORMANCE == idx then @@ -209,7 +206,7 @@ function TestCSWithSkeleton.extend(target) end function TestCSWithSkeleton:onEnter() - local armature = cc.Armature:create("Cowboy") + local armature = ccs.Armature:create("Cowboy") armature:getAnimation():playByIndex(0) armature:setScale(0.2) armature:setAnchorPoint(cc.p(0.5, 0.5)) @@ -230,40 +227,6 @@ function TestCSWithSkeleton.create() return layer end -local TestCSWithoutSkeleton = class("TestCSWithoutSkeleton",ArmatureTestLayer) -TestCSWithoutSkeleton.__index = TestCSWithoutSkeleton - -function TestCSWithoutSkeleton.extend(target) - local t = tolua.getpeer(target) - if not t then - t = {} - tolua.setpeer(target, t) - end - setmetatable(t, TestCSWithoutSkeleton) - return target -end - -function TestCSWithoutSkeleton:onEnter() - local armature = cc.Armature:create("TestBone") - armature:getAnimation():playByIndex(0) - armature:setScale(0.2) - armature:setAnchorPoint(cc.p(0.5, 0.5)) - armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2)) - self:addChild(armature) -end - -function TestCSWithoutSkeleton.create() - local layer = TestCSWithoutSkeleton.extend(cc.Layer:create()) - - if nil ~= layer then - layer:createMenu() - layer:createToExtensionMenu() - layer:onEnter() - layer:creatTitleAndSubTitle(armatureSceneIdx) - end - return layer -end - local TestDragonBones20 = class("TestDragonBones20",ArmatureTestLayer) TestDragonBones20.__index = TestDragonBones20 @@ -278,7 +241,7 @@ function TestDragonBones20.extend(target) end function TestDragonBones20:onEnter() - local armature = cc.Armature:create("Dragon") + local armature = ccs.Armature:create("Dragon") armature:getAnimation():playByIndex(1) armature:getAnimation():setAnimationScale(0.4) armature:setScale(0.6) @@ -320,7 +283,7 @@ function TestPerformance.update(delta) TestPerformance.times = TestPerformance.times + delta if TestPerformance.times > 0.25 then TestPerformance.time = 0 - local armature = cc.Armature:create("Knight_f/Knight") + local armature = ccs.Armature:create("Knight_f/Knight") armature:getAnimation():playByIndex(0) armature:setPosition(cc.p(50 + TestPerformance.armatureCount * 5, winSize.height / 2)) armature:setScale(0.6) @@ -363,40 +326,6 @@ function TestPerformance.create() return layer end -local TestCSWithoutSkeleton = class("TestCSWithoutSkeleton",ArmatureTestLayer) -TestCSWithoutSkeleton.__index = TestCSWithoutSkeleton - -function TestCSWithoutSkeleton.extend(target) - local t = tolua.getpeer(target) - if not t then - t = {} - tolua.setpeer(target, t) - end - setmetatable(t, TestCSWithoutSkeleton) - return target -end - -function TestCSWithoutSkeleton:onEnter() - local armature = cc.Armature:create("TestBone") - armature:getAnimation():playByIndex(0) - armature:setScale(0.2) - armature:setAnchorPoint(cc.p(0.5, 0.5)) - armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2)) - self:addChild(armature) -end - -function TestCSWithoutSkeleton.create() - local layer = TestCSWithoutSkeleton.extend(cc.Layer:create()) - - if nil ~= layer then - layer:createMenu() - layer:createToExtensionMenu() - layer:onEnter() - layer:creatTitleAndSubTitle(armatureSceneIdx) - end - return layer -end - local TestChangeZorder = class("TestChangeZorder",ArmatureTestLayer) TestChangeZorder.__index = TestChangeZorder TestChangeZorder.currentTag = -1 @@ -414,21 +343,21 @@ end function TestChangeZorder:onEnter() self.currentTag = -1 - local armature = cc.Armature:create("Knight_f/Knight") + local armature = ccs.Armature:create("Knight_f/Knight") armature:getAnimation():playByIndex(0) armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2 - 100 )) armature:setScale(0.6) self.currentTag = self.currentTag + 1 self:addChild(armature, self.currentTag, self.currentTag) - armature = cc.Armature:create("TestBone") + armature = ccs.Armature:create("Cowboy") armature:getAnimation():playByIndex(0) armature:setScale(0.24) armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2 - 100)) self.currentTag = self.currentTag + 1 self:addChild(armature, self.currentTag, self.currentTag) - armature = cc.Armature:create("Dragon") + armature = ccs.Armature:create("Dragon") armature:getAnimation():playByIndex(0) armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2 - 100)) armature:setScale(0.6) @@ -471,7 +400,7 @@ function TestAnimationEvent.extend(target) end function TestAnimationEvent:onEnter() - local armature = cc.Armature:create("Cowboy") + local armature = ccs.Armature:create("Cowboy") armature:getAnimation():play("Fire") armature:setScaleX(-0.24) armature:setScaleY(0.24) @@ -511,25 +440,25 @@ function TestParticleDisplay:onEnter() self:setTouchEnabled(true) self.animationID = 0 - self.armature = cc.Armature:create("robot") + self.armature = ccs.Armature:create("robot") self.armature:getAnimation():playByIndex(0) self.armature:setPosition(VisibleRect:center()) self.armature:setScale(0.48) self:addChild(self.armature) - local displayData = cc.ParticleDisplayData:create() - displayData:setParam("Particles/SmallSun.plist") + local p1 = cc.ParticleSystemQuad:create("Particles/SmallSun.plist") + local p2 = cc.ParticleSystemQuad:create("Particles/SmallSun.plist") - local bone = cc.Bone:create("p1") - bone:addDisplay(displayData, 0) + local bone = ccs.Bone:create("p1") + bone:addDisplay(p1, 0) bone:changeDisplayByIndex(0, true) bone:setIgnoreMovementBoneData(true) bone:setZOrder(100) bone:setScale(1.2) self.armature:addBone(bone, "bady-a3") - bone = cc.Bone:create("p2") - bone:addDisplay(displayData, 0) + bone = ccs.Bone:create("p2") + bone:addDisplay(p2, 0) bone:changeDisplayByIndex(0, true) bone:setIgnoreMovementBoneData(true) bone:setZOrder(100) @@ -583,7 +512,7 @@ function TestUseMutiplePicture:onEnter() self:setTouchEnabled(true) self.displayIndex = 1 - self.armature = cc.Armature:create("Knight_f/Knight") + self.armature = ccs.Armature:create("Knight_f/Knight") self.armature:getAnimation():playByIndex(0) self.armature:setPosition(cc.p(VisibleRect:left().x + 70, VisibleRect:left().y)) self.armature:setScale(1.2) @@ -600,11 +529,10 @@ function TestUseMutiplePicture:onEnter() "weapon_f-hammer.png", }; - local spriteDisplayData = cc.SpriteDisplayData:create() local i = 1 for i = 1,table.getn(weapon) do - spriteDisplayData:setParam(weapon[i]) - self.armature:getBone("weapon"):addDisplay(spriteDisplayData, i - 1) + local skin = ccs.Skin:createWithSpriteFrameName(weapon[i]) + self.armature:getBone("weapon"):addDisplay(skin, i - 1) end local function onTouchBegan(x, y) @@ -649,7 +577,7 @@ function TestBoundingBox.extend(target) end function TestBoundingBox:onEnter() - local armature = cc.Armature:create("Cowboy") + local armature = ccs.Armature:create("Cowboy") armature:getAnimation():playByIndex(0) armature:setPosition(VisibleRect:center()) armature:setScale(0.2) @@ -685,7 +613,7 @@ end function TestAnchorPoint:onEnter() local i = 1 for i = 1 , 5 do - local armature = cc.Armature:create("Cowboy") + local armature = ccs.Armature:create("Cowboy") armature:getAnimation():playByIndex(0); armature:setPosition(VisibleRect:center()) armature:setScale(0.2) @@ -731,7 +659,7 @@ function TestArmatureNesting:onEnter() self:setTouchEnabled(true) self.weaponIndex = 0 - self.armature = cc.Armature:create("cyborg") + self.armature = ccs.Armature:create("cyborg") self.armature:getAnimation():playByIndex(1) self.armature:setPosition(VisibleRect:center()) self.armature:setScale(1.2) @@ -770,7 +698,6 @@ end local armatureSceneArr = { TestCSWithSkeleton.create, - TestCSWithoutSkeleton.create, TestDragonBones20.create, TestPerformance.create, TestChangeZorder.create, diff --git a/samples/Lua/TestLua/proj.android/jni/Application.mk b/samples/Lua/TestLua/proj.android/jni/Application.mk index a829fc0f48..3961feba34 100644 --- a/samples/Lua/TestLua/proj.android/jni/Application.mk +++ b/samples/Lua/TestLua/proj.android/jni/Application.mk @@ -2,7 +2,7 @@ APP_STL := gnustl_static # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char APP_CPPFLAGS += -fexceptions diff --git a/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj b/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj index f70904ac2f..b95a8da2f8 100644 --- a/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj +++ b/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj @@ -66,7 +66,7 @@ - $(ProjectDir)..\Classes;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\scripting\lua\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\lua\lua;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\scripting\lua\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\lua\lua;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;$(EngineRoot);%(AdditionalIncludeDirectories) Level3 @@ -115,7 +115,7 @@ xcopy /Y /Q "$(EngineRoot)external\websockets\prebuilt\\win32\*.*" "$(OutDir)" - $(ProjectDir)..\Classes;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\scripting\lua\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\lua\lua;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\scripting\lua\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\lua\lua;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;$(EngineRoot);%(AdditionalIncludeDirectories) Level3 @@ -131,7 +131,7 @@ xcopy /Y /Q "$(EngineRoot)external\websockets\prebuilt\\win32\*.*" "$(OutDir)"Windows MachineX86 $(OutDir);%(AdditionalLibraryDirectories) - lua51.lib;websockets.lib;%(AdditionalDependencies) + libcurl_imp.lib;lua51.lib;websockets.lib;%(AdditionalDependencies) true @@ -163,10 +163,12 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ + + diff --git a/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj.filters b/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj.filters index 7517b68f2b..12f4b9ee7c 100644 --- a/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj.filters +++ b/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj.filters @@ -15,6 +15,9 @@ win32 + + Classes + @@ -23,5 +26,8 @@ win32 + + Classes + \ No newline at end of file diff --git a/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id b/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id deleted file mode 100644 index 06123eec12..0000000000 --- a/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -3275ac270645139eb273b2a47c215f39bcb0e0d5 \ No newline at end of file diff --git a/template/multi-platform-cpp/CMakeLists.txt b/template/multi-platform-cpp/CMakeLists.txt new file mode 100644 index 0000000000..88299d0d83 --- /dev/null +++ b/template/multi-platform-cpp/CMakeLists.txt @@ -0,0 +1,143 @@ +cmake_minimum_required(VERSION 2.6) + +set(APP_NAME HelloCpp) +project (${APP_NAME}) + +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) + +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() + + +set(GAME_SRC + proj.linux/main.cpp + Classes/AppDelegate.cpp + Classes/HelloWorldScene.cpp +) + +set(COCOS2D_ROOT ${CMAKE_SOURCE_DIR}/../..) + +include_directories( + ${COCOS2D_ROOT} + ${COCOS2D_ROOT}/cocos + ${COCOS2D_ROOT}/cocos/audio/include + ${COCOS2D_ROOT}/cocos/2d + ${COCOS2D_ROOT}/cocos/2d/platform + ${COCOS2D_ROOT}/cocos/2d/platform/linux + ${COCOS2D_ROOT}/cocos/base + ${COCOS2D_ROOT}/cocos/physics + ${COCOS2D_ROOT}/cocos/editor-support + ${COCOS2D_ROOT}/cocos/math/kazmath/include + ${COCOS2D_ROOT}/extensions + ${COCOS2D_ROOT}/external + ${COCOS2D_ROOT}/external/jpeg/include/linux + ${COCOS2D_ROOT}/external/tiff/include/linux + ${COCOS2D_ROOT}/external/webp/include/linux + ${COCOS2D_ROOT}/external/glfw3/include/linux + ${COCOS2D_ROOT}/external/curl/include/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/tinyxml2 + ${COCOS2D_ROOT}/external/unzip + ${COCOS2D_ROOT}/external/chipmunk/include/chipmunk + ${COCOS2D_ROOT}/external/freetype2/include/linux + ${COCOS2D_ROOT}/external/linux-specific/fmod/include/${ARCH_DIR} +) + +link_directories( + /usr/local/lib + ${COCOS2D_ROOT}/lib + ${COCOS2D_ROOT}/external/jpeg/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/tiff/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/webp/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/freetype2/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/curl/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/linux-specific/fmod/prebuilt/${ARCH_DIR} +) + +# add the executable +add_executable(${APP_NAME} + ${GAME_SRC} +) + +if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) +set(FMOD_LIB "fmodex64") +else() +set(FMOD_LIB "fmodex") +endif() + +target_link_libraries(${APP_NAME} + gui + network + curl + ldap + lber + idn + rtmp + spine + cocostudio + jsoncpp + cocosbuilder + extensions + box2d + audio + ${FMOD_LIB} + cocos2d + cocosbase + chipmunk + tinyxml2 + kazmath + unzip + jpeg + webp + tiff + freetype + fontconfig + png + pthread + glfw + GLEW + GL + X11 + rt + z + ) + +set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin") + +set_target_properties(${APP_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") + +pre_build(${APP_NAME} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources + ) + diff --git a/template/multi-platform-cpp/proj.android/build_native.cmd b/template/multi-platform-cpp/proj.android/build_native.cmd deleted file mode 100644 index 5b25ec4817..0000000000 --- a/template/multi-platform-cpp/proj.android/build_native.cmd +++ /dev/null @@ -1,83 +0,0 @@ -@echo off - -set APPNAME="HelloCpp" - -set buildexternalsfromsource= -set PARALLEL_BUILD_FLAG= - -goto :getopts - -:usage - echo Build C/C++ code for %APPNAME% using Android NDK - echo OPTIONS: - echo -s Build externals from source - echo -h this help - pause - exit /b 1 - -:def - echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment." - pause - exit /b 1 - -:getopts - set "par=%~1" - if "%par%"=="" (goto :L) - if "%~1"=="-s" set /a buildexternalsfromsource=1 - if "%~1"=="-h" goto :usage - shift - goto :getopts - -:L -set NDK_ROOT=%NDK_ROOT% -if "%NDK_ROOT%"=="" goto:def - -rem check toolchains -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.8 (goto :toolchains48) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.7 (goto :toolchains47) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.6 (goto :toolchains46) -echo "Couldn't find the gcc toolchain." -pause -exit /b 1 - -:toolchains48 - set NDK_TOOLCHAIN_VERSION=4.8 - goto :InitPath -:toolchains47 - set NDK_TOOLCHAIN_VERSION=4.7 - goto :InitPath -:toolchains46 - set NDK_TOOLCHAIN_VERSION=4.6 - -:InitPath - -set COCOS2DX_ROOT=%~dp0..\..\.. -set APP_ROOT=%~dp0.. -set APP_ANDROID_ROOT=%~dp0 - -if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) -:MODULE1 - echo "Building external dependencies from source" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\source - goto :COPY_RES -:MODULE2 - echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external - -:COPY_RES -echo NDK_ROOT = %NDK_ROOT% -echo COCOS2DX_ROOT=%COCOS2DX_ROOT% -echo APP_ROOT=%APP_ROOT% -echo APP_ANDROID_ROOT=%APP_ANDROID_ROOT% -echo NDK_TOOLCHAIN_VERSION=%NDK_TOOLCHAIN_VERSION% - -rem make sure assets is exist -if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets - -mkdir %APP_ANDROID_ROOT%\assets - -rem copy Resources/* into assets' root -xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets - -call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 %* -pause \ No newline at end of file diff --git a/template/multi-platform-cpp/proj.android/build_native.py b/template/multi-platform-cpp/proj.android/build_native.py new file mode 100755 index 0000000000..e426c2c0ec --- /dev/null +++ b/template/multi-platform-cpp/proj.android/build_native.py @@ -0,0 +1,100 @@ +#!/usr/bin/python +# build_native.py +# Build native codes + + +import sys +import os, os.path +import shutil + + +def check_environment_variables(): + ''' Checking the environment NDK_ROOT, which will be used for building + ''' + + try: + NDK_ROOT = os.environ['NDK_ROOT'] + except Exception: + print "NDK_ROOT not defined. Please define NDK_ROOT in your environment" + sys.exit(1) + + return NDK_ROOT + +def select_toolchain_version(): + '''Because ndk-r8e uses gcc4.6 as default. gcc4.6 doesn't support c++11. So we should select gcc4.7 when + using ndk-r8e. But gcc4.7 is removed in ndk-r9, so we should determine whether gcc4.7 exist. + Conclution: + ndk-r8e -> use gcc4.7 + ndk-r9 -> use gcc4.8 + ''' + + ndk_root = check_environment_variables() + if os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.8")): + os.environ['NDK_TOOLCHAIN_VERSION'] = '4.8' + print "The Selected NDK toolchain version was 4.8 !" + elif os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.7")): + os.environ['NDK_TOOLCHAIN_VERSION'] = '4.7' + print "The Selected NDK toolchain version was 4.7 !" + else: + print "Couldn't find the gcc toolchain." + exit(1) + +def do_build(cocos_root, ndk_root, app_android_root): + + ndk_path = os.path.join(ndk_root, "ndk-build") + + # windows should use ";" to seperate module paths + platform = sys.platform + if platform == 'win32': + ndk_module_path = 'NDK_MODULE_PATH=%s;%s/external;%s/cocos' % (cocos_root, cocos_root, cocos_root) + else: + ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root) + + ndk_build_param = sys.argv[1:] + if len(ndk_build_param) == 0: + command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path) + else: + command = '%s -C %s %s %s' % (ndk_path, app_android_root, ''.join(str(e) for e in ndk_build_param), ndk_module_path) + os.system(command) + +def copy_files(src, dst): + + for item in os.listdir(src): + path = os.path.join(src, item) + # Android can not package the file that ends with ".gz" + if not item.startswith('.') and not item.endswith('.gz') and os.path.isfile(path): + shutil.copy(path, dst) + if os.path.isdir(path): + new_dst = os.path.join(dst, item) + os.mkdir(new_dst) + copy_files(path, new_dst) + +def copy_resources(app_android_root): + + # remove app_android_root/assets if it exists + assets_dir = os.path.join(app_android_root, "assets") + if os.path.isdir(assets_dir): + shutil.rmtree(assets_dir) + + # copy resources + os.mkdir(assets_dir) + resources_dir = os.path.join(app_android_root, "../Resources") + if os.path.isdir(resources_dir): + copy_files(resources_dir, assets_dir) + +def build(): + + ndk_root = check_environment_variables() + select_toolchain_version() + + current_dir = os.path.dirname(os.path.realpath(__file__)) + cocos_root = os.path.join(current_dir, "../../..") + + app_android_root = current_dir + copy_resources(app_android_root) + do_build(cocos_root, ndk_root, app_android_root) + +# -------------- main -------------- +if __name__ == '__main__': + + build() diff --git a/template/multi-platform-cpp/proj.android/build_native.sh b/template/multi-platform-cpp/proj.android/build_native.sh deleted file mode 100755 index 47c3c53564..0000000000 --- a/template/multi-platform-cpp/proj.android/build_native.sh +++ /dev/null @@ -1,91 +0,0 @@ -APPNAME="HelloCpp" - -# options - -buildexternalsfromsource= - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --s Build externals from source --h this help -EOF -} - -while getopts "sh" OPTION; do -case "$OPTION" in -s) -buildexternalsfromsource=1 -;; -h) -usage -exit 0 -;; -esac -done - -# paths - -if [ -z "${NDK_ROOT+aaa}" ];then -echo "please define NDK_ROOT" -exit 1 -fi - -# For compatibility of android-ndk-r9, 4.7 was removed from r9 -if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then - export NDK_TOOLCHAIN_VERSION=4.7 - echo "The Selected NDK toolchain version was 4.7 !" -else - if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then - export NDK_TOOLCHAIN_VERSION=4.8 - echo "The Selected NDK toolchain version was 4.8 !" - else - echo "Couldn't find the gcc toolchain." - exit 1 - fi -fi - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory -COCOS2DX_ROOT="$DIR/../../.." -APP_ROOT="$DIR/.." -APP_ANDROID_ROOT="$DIR" - -echo "NDK_ROOT = $NDK_ROOT" -echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo "APP_ROOT = $APP_ROOT" -echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" - -# make sure assets is exist -if [ -d "$APP_ANDROID_ROOT"/assets ]; then - rm -rf "$APP_ANDROID_ROOT"/assets -fi - -mkdir "$APP_ANDROID_ROOT"/assets - -# copy resources -for file in "$APP_ROOT"/Resources/* -do -if [ -d "$file" ]; then - cp -rf "$file" "$APP_ANDROID_ROOT"/assets -fi - -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/assets -fi -done - -# run ndk-build -if [[ "$buildexternalsfromsource" ]]; then - echo "Building external dependencies from source" - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" -else - echo "Using prebuilt externals" - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" -fi diff --git a/template/multi-platform-cpp/proj.android/jni/Application.mk b/template/multi-platform-cpp/proj.android/jni/Application.mk index b20df4f373..ae98b275c1 100644 --- a/template/multi-platform-cpp/proj.android/jni/Application.mk +++ b/template/multi-platform-cpp/proj.android/jni/Application.mk @@ -1,2 +1,2 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -fsigned-char diff --git a/template/multi-platform-cpp/proj.ios_mac/ios/RootViewController.mm b/template/multi-platform-cpp/proj.ios_mac/ios/RootViewController.mm index 906aeaf082..187b274b91 100644 --- a/template/multi-platform-cpp/proj.ios_mac/ios/RootViewController.mm +++ b/template/multi-platform-cpp/proj.ios_mac/ios/RootViewController.mm @@ -1,5 +1,6 @@ #import "RootViewController.h" - +#import "cocos2d.h" +#import "EAGLView.h" @implementation RootViewController @@ -43,6 +44,14 @@ return YES; } +- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { + [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; + + CGSize s = CGSizeMake([[CCEAGLView sharedEGLView] getWidth], [[CCEAGLView sharedEGLView] getHeight]); + + cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height); +} + //fix not hide status on ios7 - (BOOL)prefersStatusBarHidden { diff --git a/template/multi-platform-js/Classes/AppDelegate.cpp b/template/multi-platform-js/Classes/AppDelegate.cpp index 4c2fea3abf..e409b974b5 100644 --- a/template/multi-platform-js/Classes/AppDelegate.cpp +++ b/template/multi-platform-js/Classes/AppDelegate.cpp @@ -47,7 +47,7 @@ bool AppDelegate::applicationDidFinishLaunching() ScriptEngineProtocol *engine = ScriptingCore::getInstance(); ScriptEngineManager::getInstance()->setScriptEngine(engine); - ScriptingCore::getInstance()->runScript("main.js"); + ScriptingCore::getInstance()->runScript("cocos2d-jsb.js"); return true; } diff --git a/template/multi-platform-js/Resources/main.js b/template/multi-platform-js/Resources/cocos2d-jsb.js similarity index 100% rename from template/multi-platform-js/Resources/main.js rename to template/multi-platform-js/Resources/cocos2d-jsb.js diff --git a/template/multi-platform-js/proj.android/build_native.cmd b/template/multi-platform-js/proj.android/build_native.cmd deleted file mode 100644 index 82eb0151a5..0000000000 --- a/template/multi-platform-js/proj.android/build_native.cmd +++ /dev/null @@ -1,90 +0,0 @@ -@echo off - -set APPNAME="HelloJavascript" - -set buildexternalsfromsource= -set PARALLEL_BUILD_FLAG= - -goto :getopts - -:usage - echo Build C/C++ code for %APPNAME% using Android NDK - echo OPTIONS: - echo -s Build externals from source - echo -p Run make with -j8 option to take advantage of multiple processors - echo -h this help - pause - exit /b 1 - -:def - echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment." - pause - exit /b 1 - -:getopts - set "par=%~1" - if "%par%"=="" (goto :L) - if "%~1"=="-s" set /a buildexternalsfromsource=1 - if "%~1"=="-p" set PARALLEL_BUILD_FLAG=\-j8 - if "%~1"=="-h" goto :usage - shift - goto :getopts - -:L -set NDK_ROOT=%NDK_ROOT% -if "%NDK_ROOT%"=="" goto:def - -rem check toolchains -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.8 (goto :toolchains48) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.7 (goto :toolchains47) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.6 (goto :toolchains46) -echo "Couldn't find the gcc toolchain." -pause -exit /b 1 - -:toolchains48 - set NDK_TOOLCHAIN_VERSION=4.8 - goto :InitPath -:toolchains47 - set NDK_TOOLCHAIN_VERSION=4.7 - goto :InitPath -:toolchains46 - set NDK_TOOLCHAIN_VERSION=4.6 - -:InitPath - -set COCOS2DX_ROOT=%~dp0..\..\.. -set APP_ROOT=%~dp0.. -set APP_ANDROID_ROOT=%~dp0 -set BINDINGS_JS_ROOT=%COCOS2DX_ROOT%\cocos\scripting\javascript\script - -if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) -:MODULE1 - echo "Building external dependencies from source" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\source - goto :COPY_RES -:MODULE2 - echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external - -:COPY_RES -echo NDK_ROOT = %NDK_ROOT% -echo COCOS2DX_ROOT=%COCOS2DX_ROOT% -echo APP_ROOT=%APP_ROOT% -echo APP_ANDROID_ROOT=%APP_ANDROID_ROOT% -echo NDK_TOOLCHAIN_VERSION=%NDK_TOOLCHAIN_VERSION% - -rem make sure assets is exist -if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets - -mkdir %APP_ANDROID_ROOT%\assets -mkdir %APP_ANDROID_ROOT%\assets\res - -rem copy Resources/* into assets' root -xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets - -rem copy bindings/*.js into assets' root -xcopy /e /q /r /y %BINDINGS_JS_ROOT%\* %APP_ANDROID_ROOT%\assets - -call %NDK_ROOT%\ndk-build.cmd %PARALLEL_BUILD_FLAG% NDK_LOG=0 V=0 %* -pause \ No newline at end of file diff --git a/template/multi-platform-js/proj.android/build_native.py b/template/multi-platform-js/proj.android/build_native.py new file mode 100755 index 0000000000..4e67dd7cfb --- /dev/null +++ b/template/multi-platform-js/proj.android/build_native.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# build_native.py +# Build native codes + + +import sys +import os, os.path +import shutil + + +def check_environment_variables(): + ''' Checking the environment NDK_ROOT, which will be used for building + ''' + + try: + NDK_ROOT = os.environ['NDK_ROOT'] + except Exception: + print "NDK_ROOT not defined. Please define NDK_ROOT in your environment" + sys.exit(1) + + return NDK_ROOT + +def select_toolchain_version(): + '''Because ndk-r8e uses gcc4.6 as default. gcc4.6 doesn't support c++11. So we should select gcc4.7 when + using ndk-r8e. But gcc4.7 is removed in ndk-r9, so we should determine whether gcc4.7 exist. + Conclution: + ndk-r8e -> use gcc4.7 + ndk-r9 -> use gcc4.8 + ''' + + ndk_root = check_environment_variables() + if os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.8")): + os.environ['NDK_TOOLCHAIN_VERSION'] = '4.8' + print "The Selected NDK toolchain version was 4.8 !" + elif os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.7")): + os.environ['NDK_TOOLCHAIN_VERSION'] = '4.7' + print "The Selected NDK toolchain version was 4.7 !" + else: + print "Couldn't find the gcc toolchain." + exit(1) + +def do_build(cocos_root, ndk_root, app_android_root): + + ndk_path = os.path.join(ndk_root, "ndk-build") + + # windows should use ";" to seperate module paths + platform = sys.platform + if platform == 'win32': + ndk_module_path = 'NDK_MODULE_PATH=%s;%s/external;%s/cocos' % (cocos_root, cocos_root, cocos_root) + else: + ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root) + + ndk_build_param = sys.argv[1:] + if len(ndk_build_param) == 0: + command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path) + else: + command = '%s -C %s %s %s' % (ndk_path, app_android_root, ''.join(str(e) for e in ndk_build_param), ndk_module_path) + os.system(command) + +def copy_files(src, dst): + + for item in os.listdir(src): + path = os.path.join(src, item) + # Android can not package the file that ends with ".gz" + if not item.startswith('.') and not item.endswith('.gz') and os.path.isfile(path): + shutil.copy(path, dst) + if os.path.isdir(path): + new_dst = os.path.join(dst, item) + os.mkdir(new_dst) + copy_files(path, new_dst) + +def copy_resources(app_android_root): + + # remove app_android_root/assets if it exists + assets_dir = os.path.join(app_android_root, "assets") + if os.path.isdir(assets_dir): + shutil.rmtree(assets_dir) + + # copy resources + os.mkdir(assets_dir) + resources_dir = os.path.join(app_android_root, "../Resources") + if os.path.isdir(resources_dir): + copy_files(resources_dir, assets_dir) + + # jsb project should copy javascript files and resources(shared with cocos2d-html5) + resources_dir = os.path.join(app_android_root, "../../../cocos/scripting/javascript/script") + copy_files(resources_dir, assets_dir) + +def build(): + + ndk_root = check_environment_variables() + select_toolchain_version() + + current_dir = os.path.dirname(os.path.realpath(__file__)) + cocos_root = os.path.join(current_dir, "../../..") + + app_android_root = current_dir + copy_resources(app_android_root) + do_build(cocos_root, ndk_root, app_android_root) + +# -------------- main -------------- +if __name__ == '__main__': + + build() diff --git a/template/multi-platform-js/proj.android/build_native.sh b/template/multi-platform-js/proj.android/build_native.sh deleted file mode 100755 index 5a008713a3..0000000000 --- a/template/multi-platform-js/proj.android/build_native.sh +++ /dev/null @@ -1,100 +0,0 @@ -APPNAME="HelloJavascript" - -# options - -buildexternalsfromsource= -PARALLEL_BUILD_FLAG= - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --s Build externals from source --p Run make with -j8 option to take advantage of multiple processors --h this help -EOF -} - -while getopts "sph" OPTION; do -case "$OPTION" in -s) -buildexternalsfromsource=1 -;; -p) -PARALLEL_BUILD_FLAG=\-j8 -;; -h) -usage -exit 0 -;; -esac -done - -# exit this script if any commmand fails -set -e - -# paths - -if [ -z "${NDK_ROOT+aaa}" ];then -echo "please define NDK_ROOT" -exit 1 -fi - -# For compatibility of android-ndk-r9, 4.7 was removed from r9 -if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then - export NDK_TOOLCHAIN_VERSION=4.7 - echo "The Selected NDK toolchain version was 4.7 !" -else - if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then - export NDK_TOOLCHAIN_VERSION=4.8 - echo "The Selected NDK toolchain version was 4.8 !" - else - echo "Couldn't find the gcc toolchain." - exit 1 - fi -fi - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory -COCOS2DX_ROOT="$DIR/../../.." -APP_ROOT="$DIR/.." -APP_ANDROID_ROOT="$DIR" -BINDINGS_JS_ROOT="$APP_ROOT/../../cocos/scripting/javascript/script" - -echo -echo "Paths" -echo " NDK_ROOT = $NDK_ROOT" -echo " COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo " APP_ROOT = $APP_ROOT" -echo " APP_ANDROID_ROOT = $APP_ANDROID_ROOT" -echo - -# Debug -set -x - -# make sure assets is exist -if [ -d "$APP_ANDROID_ROOT"/assets ]; then - rm -rf "$APP_ANDROID_ROOT"/assets -fi - -mkdir "$APP_ANDROID_ROOT"/assets -mkdir "$APP_ANDROID_ROOT"/assets/res - -# copy Resources/* into assets' root -cp -rf "$APP_ROOT"/Resources/* "$APP_ANDROID_ROOT"/assets - - -# copy bindings/*.js into assets' root -cp -rf "$BINDINGS_JS_ROOT"/* "$APP_ANDROID_ROOT"/assets - -echo "Using prebuilt externals" -echo - -set -x - -"$NDK_ROOT"/ndk-build $PARALLEL_BUILD_FLAG -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" \ - NDK_LOG=0 V=0 diff --git a/template/multi-platform-js/proj.android/jni/Application.mk b/template/multi-platform-js/proj.android/jni/Application.mk index ee36f34b40..76c0f20fca 100644 --- a/template/multi-platform-js/proj.android/jni/Application.mk +++ b/template/multi-platform-js/proj.android/jni/Application.mk @@ -1,4 +1,4 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT=1 -APP_CPPFLAGS += -DCOCOS2D_DEBUG=1 -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -std=c++11 +APP_CPPFLAGS := -frtti +APP_CPPFLAGS += -DCOCOS2D_DEBUG=1 -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -std=c++11 -fsigned-char diff --git a/template/multi-platform-js/proj.ios_mac/ios/RootViewController.mm b/template/multi-platform-js/proj.ios_mac/ios/RootViewController.mm index a0f626dcd6..187b274b91 100644 --- a/template/multi-platform-js/proj.ios_mac/ios/RootViewController.mm +++ b/template/multi-platform-js/proj.ios_mac/ios/RootViewController.mm @@ -1,6 +1,6 @@ - #import "RootViewController.h" - +#import "cocos2d.h" +#import "EAGLView.h" @implementation RootViewController @@ -44,6 +44,14 @@ return YES; } +- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { + [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; + + CGSize s = CGSizeMake([[CCEAGLView sharedEGLView] getWidth], [[CCEAGLView sharedEGLView] getHeight]); + + cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height); +} + //fix not hide status on ios7 - (BOOL)prefersStatusBarHidden { diff --git a/template/multi-platform-lua/CMakeLists.txt b/template/multi-platform-lua/CMakeLists.txt new file mode 100644 index 0000000000..a3cf368403 --- /dev/null +++ b/template/multi-platform-lua/CMakeLists.txt @@ -0,0 +1,149 @@ +cmake_minimum_required(VERSION 2.6) + +set(APP_NAME HelloLua) +project (${APP_NAME}) + +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) + +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() + + +set(GAME_SRC + proj.linux/main.cpp + Classes/AppDelegate.cpp +) + +set(COCOS2D_ROOT ${CMAKE_SOURCE_DIR}/../..) + +include_directories( + Classes + ${COCOS2D_ROOT}/cocos/scripting/lua/bindings + ${COCOS2D_ROOT}/external/lua/lua + ${COCOS2D_ROOT}/external/lua/tolua + ${COCOS2D_ROOT} + ${COCOS2D_ROOT}/cocos + ${COCOS2D_ROOT}/cocos/audio/include + ${COCOS2D_ROOT}/cocos/2d + ${COCOS2D_ROOT}/cocos/2d/platform + ${COCOS2D_ROOT}/cocos/2d/platform/linux + ${COCOS2D_ROOT}/cocos/base + ${COCOS2D_ROOT}/cocos/physics + ${COCOS2D_ROOT}/cocos/editor-support + ${COCOS2D_ROOT}/cocos/math/kazmath/include + ${COCOS2D_ROOT}/extensions + ${COCOS2D_ROOT}/external + ${COCOS2D_ROOT}/external/jpeg/include/linux + ${COCOS2D_ROOT}/external/tiff/include/linux + ${COCOS2D_ROOT}/external/webp/include/linux + ${COCOS2D_ROOT}/external/glfw3/include/linux + ${COCOS2D_ROOT}/external/curl/include/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/tinyxml2 + ${COCOS2D_ROOT}/external/unzip + ${COCOS2D_ROOT}/external/chipmunk/include/chipmunk + ${COCOS2D_ROOT}/external/freetype2/include/linux + ${COCOS2D_ROOT}/external/linux-specific/fmod/include/${ARCH_DIR} +) + +link_directories( + /usr/local/lib + ${COCOS2D_ROOT}/lib + ${COCOS2D_ROOT}/external/jpeg/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/tiff/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/webp/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/freetype2/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/curl/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/linux-specific/fmod/prebuilt/${ARCH_DIR} +) + +# add the executable +add_executable(${APP_NAME} + ${GAME_SRC} +) + +if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) +set(FMOD_LIB "fmodex64") +else() +set(FMOD_LIB "fmodex") +endif() + +target_link_libraries(${APP_NAME} + luabinding + tolua + lua + gui + network + curl + ldap + lber + idn + rtmp + spine + cocostudio + jsoncpp + cocosbuilder + extensions + box2d + audio + ${FMOD_LIB} + cocos2d + cocosbase + chipmunk + tinyxml2 + kazmath + unzip + jpeg + webp + tiff + freetype + fontconfig + png + pthread + glfw + GLEW + GL + X11 + rt + z + ) + +set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin") + +set_target_properties(${APP_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") + +pre_build(${APP_NAME} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources + ) + diff --git a/template/multi-platform-lua/proj.android/build_native.cmd b/template/multi-platform-lua/proj.android/build_native.cmd deleted file mode 100644 index 0177685738..0000000000 --- a/template/multi-platform-lua/proj.android/build_native.cmd +++ /dev/null @@ -1,86 +0,0 @@ -@echo off - -set APPNAME="HelloLua" - -set buildexternalsfromsource= -set PARALLEL_BUILD_FLAG= - -goto :getopts - -:usage - echo Build C/C++ code for %APPNAME% using Android NDK - echo OPTIONS: - echo -s Build externals from source - echo -h this help - pause - exit /b 1 - -:def - echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment." - pause - exit /b 1 - -:getopts - set "par=%~1" - if "%par%"=="" (goto :L) - if "%~1"=="-s" set /a buildexternalsfromsource=1 - if "%~1"=="-h" goto :usage - shift - goto :getopts - -:L -set NDK_ROOT=%NDK_ROOT% -if "%NDK_ROOT%"=="" goto:def - -rem check toolchains -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.8 (goto :toolchains48) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.7 (goto :toolchains47) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.6 (goto :toolchains46) -echo "Couldn't find the gcc toolchain." -pause -exit /b 1 - -:toolchains48 - set NDK_TOOLCHAIN_VERSION=4.8 - goto :InitPath -:toolchains47 - set NDK_TOOLCHAIN_VERSION=4.7 - goto :InitPath -:toolchains46 - set NDK_TOOLCHAIN_VERSION=4.6 - -:InitPath - -set COCOS2DX_ROOT=%~dp0..\..\.. -set APP_ROOT=%~dp0.. -set APP_ANDROID_ROOT=%~dp0 - -if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) -:MODULE1 - echo "Building external dependencies from source" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\source - goto :COPY_RES -:MODULE2 - echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external - -:COPY_RES -echo NDK_ROOT = %NDK_ROOT% -echo COCOS2DX_ROOT=%COCOS2DX_ROOT% -echo APP_ROOT=%APP_ROOT% -echo APP_ANDROID_ROOT=%APP_ANDROID_ROOT% -echo NDK_TOOLCHAIN_VERSION=%NDK_TOOLCHAIN_VERSION% - -rem make sure assets is exist -if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets - -mkdir %APP_ANDROID_ROOT%\assets - -rem copy Resources/* into assets' root -xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets - -rem copy common luaScript -xcopy /e /q /r /y %COCOS2DX_ROOT%\cocos\scripting\lua\script\* %APP_ANDROID_ROOT%\assets - -call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 %* -pause \ No newline at end of file diff --git a/template/multi-platform-lua/proj.android/build_native.py b/template/multi-platform-lua/proj.android/build_native.py new file mode 100755 index 0000000000..c1fe04ac28 --- /dev/null +++ b/template/multi-platform-lua/proj.android/build_native.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# build_native.py +# Build native codes + + +import sys +import os, os.path +import shutil + + +def check_environment_variables(): + ''' Checking the environment NDK_ROOT, which will be used for building + ''' + + try: + NDK_ROOT = os.environ['NDK_ROOT'] + except Exception: + print "NDK_ROOT not defined. Please define NDK_ROOT in your environment" + sys.exit(1) + + return NDK_ROOT + +def select_toolchain_version(): + '''Because ndk-r8e uses gcc4.6 as default. gcc4.6 doesn't support c++11. So we should select gcc4.7 when + using ndk-r8e. But gcc4.7 is removed in ndk-r9, so we should determine whether gcc4.7 exist. + Conclution: + ndk-r8e -> use gcc4.7 + ndk-r9 -> use gcc4.8 + ''' + + ndk_root = check_environment_variables() + if os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.8")): + os.environ['NDK_TOOLCHAIN_VERSION'] = '4.8' + print "The Selected NDK toolchain version was 4.8 !" + elif os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.7")): + os.environ['NDK_TOOLCHAIN_VERSION'] = '4.7' + print "The Selected NDK toolchain version was 4.7 !" + else: + print "Couldn't find the gcc toolchain." + exit(1) + +def do_build(cocos_root, ndk_root, app_android_root): + + ndk_path = os.path.join(ndk_root, "ndk-build") + + # windows should use ";" to seperate module paths + platform = sys.platform + if platform == 'win32': + ndk_module_path = 'NDK_MODULE_PATH=%s;%s/external;%s/cocos' % (cocos_root, cocos_root, cocos_root) + else: + ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root) + + ndk_build_param = sys.argv[1:] + if len(ndk_build_param) == 0: + command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path) + else: + command = '%s -C %s %s %s' % (ndk_path, app_android_root, ''.join(str(e) for e in ndk_build_param), ndk_module_path) + os.system(command) + +def copy_files(src, dst): + + for item in os.listdir(src): + path = os.path.join(src, item) + # Android can not package the file that ends with ".gz" + if not item.startswith('.') and not item.endswith('.gz') and os.path.isfile(path): + shutil.copy(path, dst) + if os.path.isdir(path): + new_dst = os.path.join(dst, item) + os.mkdir(new_dst) + copy_files(path, new_dst) + +def copy_resources(app_android_root): + + # remove app_android_root/assets if it exists + assets_dir = os.path.join(app_android_root, "assets") + if os.path.isdir(assets_dir): + shutil.rmtree(assets_dir) + + # copy resources + os.mkdir(assets_dir) + resources_dir = os.path.join(app_android_root, "../Resources") + if os.path.isdir(resources_dir): + copy_files(resources_dir, assets_dir) + + # lua project should copy lua script + resources_dir = os.path.join(app_android_root, "../../../cocos/scripting/lua/script") + copy_files(resources_dir, assets_dir) + +def build(): + + ndk_root = check_environment_variables() + select_toolchain_version() + + current_dir = os.path.dirname(os.path.realpath(__file__)) + cocos_root = os.path.join(current_dir, "../../..") + + app_android_root = current_dir + copy_resources(app_android_root) + do_build(cocos_root, ndk_root, app_android_root) + +# -------------- main -------------- +if __name__ == '__main__': + + build() diff --git a/template/multi-platform-lua/proj.android/build_native.sh b/template/multi-platform-lua/proj.android/build_native.sh deleted file mode 100755 index 930a9e5249..0000000000 --- a/template/multi-platform-lua/proj.android/build_native.sh +++ /dev/null @@ -1,102 +0,0 @@ -APPNAME="HelloLua" - -# options - -buildexternalsfromsource= - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --s Build externals from source --h this help -EOF -} - -while getopts "sh" OPTION; do -case "$OPTION" in -s) -buildexternalsfromsource=1 -;; -h) -usage -exit 0 -;; -esac -done - -# paths - -if [ -z "${NDK_ROOT+aaa}" ];then -echo "please define NDK_ROOT" -exit 1 -fi - -# For compatibility of android-ndk-r9, 4.7 was removed from r9 -if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then - export NDK_TOOLCHAIN_VERSION=4.7 - echo "The Selected NDK toolchain version was 4.7 !" -else - if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then - export NDK_TOOLCHAIN_VERSION=4.8 - echo "The Selected NDK toolchain version was 4.8 !" - else - echo "Couldn't find the gcc toolchain." - exit 1 - fi -fi - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory -COCOS2DX_ROOT="$DIR/../../.." -APP_ROOT="$DIR/.." -APP_ANDROID_ROOT="$DIR" - -echo "NDK_ROOT = $NDK_ROOT" -echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo "APP_ROOT = $APP_ROOT" -echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" - -# make sure assets is exist -if [ -d "$APP_ANDROID_ROOT"/assets ]; then - rm -rf "$APP_ANDROID_ROOT"/assets -fi - -mkdir "$APP_ANDROID_ROOT"/assets - -# copy resources -for file in "$APP_ROOT"/Resources/* -do -if [ -d "$file" ]; then - cp -rf "$file" "$APP_ANDROID_ROOT"/assets -fi - -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/assets -fi -done - -# copy common luaScript -for file in "$APP_ROOT"/../../cocos/scripting/lua/script/* -do -if [ -d "$file" ]; then - cp -rf "$file" "$APP_ANDROID_ROOT"/assets -fi - -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/assets -fi -done - -if [[ "$buildexternalsfromsource" ]]; then - echo "Building external dependencies from source" - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" -else - echo "Using prebuilt externals" - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" -fi \ No newline at end of file diff --git a/template/multi-platform-lua/proj.android/jni/Application.mk b/template/multi-platform-lua/proj.android/jni/Application.mk index 95acd5331a..de85c24eda 100644 --- a/template/multi-platform-lua/proj.android/jni/Application.mk +++ b/template/multi-platform-lua/proj.android/jni/Application.mk @@ -1,4 +1,4 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -std=c++11 +APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -std=c++11 -fsigned-char APP_CPPFLAGS += -fexceptions diff --git a/template/multi-platform-lua/proj.ios_mac/ios/RootViewController.mm b/template/multi-platform-lua/proj.ios_mac/ios/RootViewController.mm index a00da00584..093a9b4c3a 100644 --- a/template/multi-platform-lua/proj.ios_mac/ios/RootViewController.mm +++ b/template/multi-platform-lua/proj.ios_mac/ios/RootViewController.mm @@ -24,7 +24,8 @@ ****************************************************************************/ #import "RootViewController.h" - +#import "cocos2d.h" +#import "EAGLView.h" @implementation RootViewController @@ -68,6 +69,14 @@ return YES; } +- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { + [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; + + CGSize s = CGSizeMake([[CCEAGLView sharedEGLView] getWidth], [[CCEAGLView sharedEGLView] getHeight]); + + cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height); +} + //fix not hide status on ios7 - (BOOL)prefersStatusBarHidden { diff --git a/tools/project-creator/create_project.py b/tools/project-creator/create_project.py index be6e38babc..640fa4e038 100755 --- a/tools/project-creator/create_project.py +++ b/tools/project-creator/create_project.py @@ -30,7 +30,7 @@ def checkParams(): metavar="PROGRAMMING_NAME", type="choice", choices=["cpp", "lua", "javascript"], - help="Major programing language you want to used, should be [cpp | lua | javascript]") + help="Major programming language you want to use, should be [cpp | lua | javascript]") #parse the params (opts, args) = parser.parse_args() diff --git a/tools/tolua/cocos2dx_extension.ini b/tools/tolua/cocos2dx_extension.ini index dd5aa433aa..5940e44111 100644 --- a/tools/tolua/cocos2dx_extension.ini +++ b/tools/tolua/cocos2dx_extension.ini @@ -13,7 +13,8 @@ android_flags = -D_SIZE_T_DEFINED_ clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include clang_flags = -nostdinc -x c++ -std=c++11 -cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/gui -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s +cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s + cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT cxxgenerator_headers = @@ -22,11 +23,11 @@ cxxgenerator_headers = extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s # what headers to parse -headers = %(cocosdir)s/extensions/cocos-ext.h %(cocosdir)s/cocos/editor-support/cocosbuilder/CocosBuilder.h %(cocosdir)s/cocos/editor-support/cocostudio/CocoStudio.h +headers = %(cocosdir)s/extensions/cocos-ext.h %(cocosdir)s/cocos/editor-support/cocosbuilder/CocosBuilder.h # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". -classes = AssetsManager.* CCBReader.* CCBAnimationManager.* Scale9Sprite Control.* ControlButton.* ScrollView$ TableView$ TableViewCell$ EditBox$ Armature ArmatureAnimation Skin Bone ArmatureDataManager \w+Data$ +classes = AssetsManager.* CCBReader.* CCBAnimationManager.* Scale9Sprite Control.* ControlButton.* ScrollView$ TableView$ TableViewCell$ EditBox$ # what should we skip? in the format ClassName::[function function] # ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also @@ -47,16 +48,10 @@ skip = CCBReader::[^CCBReader$ addOwnerCallbackName isJSControlled readByte getC AssetsManagerDelegateProtocol::[*], Control::[removeHandleOfControlEvent addHandleOfControlEvent], ControlUtils::[*], - ControlSwitchSprite::[*], - ArmatureDataManager::[CCArmatureDataManager ~CCArmatureDataManager], - Armature::[createBone updateBlendType getCPBody setCPBody (s|g)etBlendFunc getShapeList ^getBody$], - Skin::[getSkinData setSkinData], - ArmatureAnimation::[updateHandler updateFrameData frameEvent], - Bone::[(s|g)etIgnoreMovementBoneData] + ControlSwitchSprite::[*] -rename_functions = CCBReader::[getAnimationManager=getActionManager setAnimationManager=setActionManager], - ArmatureDataManager::[sharedArmatureDataManager=getInstance] +rename_functions = CCBReader::[getAnimationManager=getActionManager setAnimationManager=setActionManager] rename_classes = CCBReader::_Reader, CCBAnimationManager::AnimationManager diff --git a/tools/tolua/cocos2dx_studio.ini b/tools/tolua/cocos2dx_studio.ini new file mode 100644 index 0000000000..8959fd0005 --- /dev/null +++ b/tools/tolua/cocos2dx_studio.ini @@ -0,0 +1,67 @@ +[cocos2dx_studio] +# the prefix to be added to the generated functions. You might or might not use this in your own +# templates +prefix = cocos2dx_studio + +# create a target namespace (in javascript, this would create some code like the equiv. to `ns = ns || {}`) +# all classes will be embedded in that namespace +target_namespace = ccs + +android_headers = -I%(androidndkdir)s/platforms/android-14/arch-arm/usr/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/include +android_flags = -D_SIZE_T_DEFINED_ + +clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include +clang_flags = -nostdinc -x c++ -std=c++11 + +cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/gui -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s + +cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT + +cxxgenerator_headers = + +# extra arguments for clang +extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s + +# what headers to parse +headers = %(cocosdir)s/cocos/editor-support/cocostudio/CocoStudio.h + +# what classes to produce code for. You can use regular expressions here. When testing the regular +# expression, it will be enclosed in "^$", like this: "^Menu*$". +classes = Armature ArmatureAnimation Skin Bone ArmatureDataManager \w+Data$ + +# what should we skip? in the format ClassName::[function function] +# ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also +# regular expressions, they will not be surrounded by "^$". If you want to skip a whole class, just +# add a single "*" as functions. See bellow for several examples. A special class name is "*", which +# will apply to all class names. This is a convenience wildcard to be able to skip similar named +# functions from all classes. + +skip = .*Delegate::[*], + .*Loader.*::[*], + *::[^visit$ copyWith.* onEnter.* onExit.* ^description$ getObjectType .*HSV onTouch.* onAcc.* onKey.* onRegisterTouchListener], + ArmatureDataManager::[CCArmatureDataManager ~CCArmatureDataManager], + Armature::[createBone updateBlendType getCPBody setCPBody (s|g)etBlendFunc getShapeList ^getBody$], + Skin::[(s|g)etSkinData], + ArmatureAnimation::[updateHandler updateFrameData frameEvent], + Bone::[(s|g)etIgnoreMovementBoneData] + +rename_functions = ArmatureDataManager::[sharedArmatureDataManager=getInstance] + +rename_classes = + +# for all class names, should we remove something when registering in the target VM? +remove_prefix = + +# classes for which there will be no "parent" lookup +classes_have_no_parents = + +# base classes which will be skipped when their sub-classes found them. +base_classes_to_skip = Object ProcessBase + +# classes that create no constructor +# Set is special and we will use a hand-written constructor +abstract_classes = ArmatureDataManager + +# Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'. +script_control_cpp = no + diff --git a/tools/tolua/genbindings.sh b/tools/tolua/genbindings.sh index b236c43ae8..9dc005d4a0 100755 --- a/tools/tolua/genbindings.sh +++ b/tools/tolua/genbindings.sh @@ -84,3 +84,6 @@ LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py echo "Generating bindings for cocos2dx_extension..." LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_extension_auto + +echo "Generating bindings for cocos2dx_studio..." +LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_studio.ini -s cocos2dx_studio -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_studio_auto diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index f9e5e0ff6b..b609c7cc43 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -42,7 +42,7 @@ elif [ "$PLATFORM"x = "android"x ]; then # Create a directory for temporary objects mkdir android_build_objs - PROJECTS=("Cpp/HelloCpp" "Cpp/TestCpp" "Cpp/AssetsManagerTest" "Javascript/TestJavascript" "Javascript/CocosDragonJS" "Javascript/CrystalCraze" "Javascript/MoonWarriors" "Javascript/WatermelonWithMe" "Lua/HelloLua" "Lua/TestLua") + PROJECTS=("Cpp/HelloCpp" "Cpp/TestCpp" "Cpp/SimpleGame" "Cpp/AssetsManagerTest" "Javascript/TestJavascript" "Javascript/CocosDragonJS" "Javascript/CrystalCraze" "Javascript/MoonWarriors" "Javascript/WatermelonWithMe" "Lua/HelloLua" "Lua/TestLua") for i in ${PROJECTS[*]}; do ln -s $COCOS2DX_ROOT/android_build_objs $COCOS2DX_ROOT/samples/$i/proj.android/obj done @@ -50,7 +50,7 @@ elif [ "$PLATFORM"x = "android"x ]; then # Build all samples echo "Building all samples ..." cd $COCOS2DX_ROOT/build - ./android-build.py -n NDK_DEBUG=0 all + ./android-build.py -n "NDK_BUG=0 -j10" all # Build template # echo "Building template ..." @@ -72,7 +72,17 @@ elif [ "$PLATFORM"x = "linux"x ]; then ./generate-jsbindings.sh cd $COCOS2DX_ROOT/build - make -j4 + mkdir -p linux-build + cd linux-build + cmake ../.. + make -j10 + cd ../../template/multi-platform-cpp + cmake . + make -j10 + cd ../multi-platform-lua + cmake . + make -j10 + elif [ "$PLATFORM"x = "emscripten"x ]; then # Generate binding glue codes echo "Generating bindings glue codes ..."