diff --git a/.appveyor.yml b/.appveyor.yml deleted file mode 100644 index 08b58326bd85..000000000000 --- a/.appveyor.yml +++ /dev/null @@ -1,42 +0,0 @@ -version: 1.0.{build} -skip_tags: true -skip_branch_with_pr: true -image: - - Visual Studio 2019 -environment: - PYTHON: "C:\\Python27" - PYTHON_VERSION: "2.7.13" - PYTHON_ARCH: "32" - matrix: - - build_type: windows32_cmake_test -# - build_type: android_cpp_tests -# - build_type: android_lua_tests -# - build_type: android_cocos_new_test -# - build_type: android_cpp_empty_test -# - build_type: android_gen_libs - - -platform: - - x86 - -configuration: - - Release - -before_build: - - ps: ./tools/appveyor-scripts/before-build.ps1 - -build_script: - - ps: ./tools/appveyor-scripts/build.ps1 - -branches: - except: - - v1 - - v2 - - v4-develop - - v3-doc - - v3.11_backup - - v35-for-tizen - -clone_depth: 50 - -test: off diff --git a/.github/workflows/android-ci.yml b/.github/workflows/android-ci.yml index a6d7a75b0138..30e2da959a43 100644 --- a/.github/workflows/android-ci.yml +++ b/.github/workflows/android-ci.yml @@ -16,12 +16,9 @@ on: env: # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) - TRAVIS_OS_NAME: linux + GH_OS_NAME: linux BUILD_TARGET: android - # Simple let github action to build all (TODO: optimize in the future) - TRAVIS_PULL_REQUEST: true BUILD_TYPE: Release - GITHUB_CI: true PYENV_VERSION: 2.7.18 jobs: @@ -51,8 +48,8 @@ jobs: - name: Create Build Environment # Some projects don't allow in-source building, so create a separate build directory # We'll use this as our working directory for all - run: tools/travis-scripts/before-install.sh + run: tools/unix-ci/before-install.sh - name: Build # Execute the build. You can specify a specific target with "--target " - run: tools/travis-scripts/run-script.sh + run: tools/unix-ci/run-script.sh diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 51ce1bc9a5e7..007d1e0325c8 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -7,7 +7,7 @@ on: # actions run ID description: 'Commit clang-format changes?' # Default value if no value is explicitly provided - default: false + default: 'false' # Input has to be provided for the workflow to run required: false @@ -21,9 +21,9 @@ jobs: - name: Run clang-format lint uses: DoozyX/clang-format-lint-action@v0.13 with: - source: './cocos ./extensions' - exclude: './thidrparty ./extensions/fairygui ./extensions/scripting/lua-bindings/auto ./extensions/spine' - extensions: 'h,cpp,c' + source: './cocos ./extensions ./tests ./templates' + exclude: './thidrparty ./extensions/fairygui ./extensions/scripting/lua-bindings/auto ./extensions/spine ./tests/fairygui-tests' + extensions: 'h,cpp,c,mm' clangFormatVersion: 13 inplace: True - name: Commit clang-format changes diff --git a/.github/workflows/genbindings-ci.yml b/.github/workflows/genbindings-ci.yml new file mode 100644 index 000000000000..9e2857817be9 --- /dev/null +++ b/.github/workflows/genbindings-ci.yml @@ -0,0 +1,36 @@ +name: genbindings + +on: + push: + branches: + - dev + - main + paths: + - cocos/**/* + - extensions/**/* + - .github/workflows/genbindings-ci.yml + +jobs: + build: + if: ${{ !startsWith(github.event.commits[0].message, 'Merge pull request') }} + # The CMake configure and build commands are platform agnostic and should work equally + # well on Windows or Mac. You can convert this to a matrix build if you need + # cross-platform coverage. + # See: https://docs.github.com/en/actions/configuring-and-managing-workflows/configuring-a-workflow#configuring-a-build-matrix + runs-on: windows-latest + + steps: + - uses: actions/checkout@v2 + with: + submodules: 'recursive' + lfs: 'true' + + - name: Setup Python + uses: actions/setup-python@v2 + + - uses: ilammy/msvc-dev-cmd@v1.9.0 + with: + arch: ${{ env.BUILD_ARCH }} + + - name: Build + run: tools\win-ci\genbindings.ps1 diff --git a/.github/workflows/ios-ci.yml b/.github/workflows/ios-ci.yml index 276438373fc1..ed204106b8a4 100644 --- a/.github/workflows/ios-ci.yml +++ b/.github/workflows/ios-ci.yml @@ -16,12 +16,9 @@ on: env: # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) - TRAVIS_OS_NAME: osx + GH_OS_NAME: osx BUILD_TARGET: ios - # Simple let github action to build all (TODO: optimize in the future) - TRAVIS_PULL_REQUEST: true BUILD_TYPE: Release - GITHUB_CI: true jobs: build: @@ -41,8 +38,8 @@ jobs: - name: Create Build Environment # Some projects don't allow in-source building, so create a separate build directory # We'll use this as our working directory for all - run: tools/travis-scripts/before-install.sh + run: tools/unix-ci/before-install.sh - name: Build # Execute the build. You can specify a specific target with "--target " - run: tools/travis-scripts/run-script.sh + run: tools/unix-ci/run-script.sh diff --git a/.github/workflows/linux-ci.yml b/.github/workflows/linux-ci.yml index a8b17e6bb348..086aecbe2026 100644 --- a/.github/workflows/linux-ci.yml +++ b/.github/workflows/linux-ci.yml @@ -16,12 +16,10 @@ on: env: # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) - TRAVIS_OS_NAME: linux + GH_OS_NAME: linux BUILD_TARGET: linux - # Simple let github action to build all (TODO: optimize in the future) - TRAVIS_PULL_REQUEST: true BUILD_TYPE: Release - GITHUB_CI: true + PYENV_VERSION: 2.7.18 jobs: build: @@ -41,8 +39,8 @@ jobs: - name: Create Build Environment # Some projects don't allow in-source building, so create a separate build directory # We'll use this as our working directory for all subsequent commands - run: tools/travis-scripts/before-install.sh + run: tools/unix-ci/before-install.sh - name: Build # Execute the build. You can specify a specific target with "--target " - run: tools/travis-scripts/run-script.sh + run: tools/unix-ci/run-script.sh diff --git a/.github/workflows/osx-ci.yml b/.github/workflows/osx-ci.yml index edd9ff2ca26c..8c925befa212 100644 --- a/.github/workflows/osx-ci.yml +++ b/.github/workflows/osx-ci.yml @@ -16,12 +16,9 @@ on: env: # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) - TRAVIS_OS_NAME: osx + GH_OS_NAME: osx BUILD_TARGET: osx - # Simple let github action to build all (TODO: optimize in the future) - TRAVIS_PULL_REQUEST: true BUILD_TYPE: Release - GITHUB_CI: true jobs: build: @@ -41,8 +38,8 @@ jobs: - name: Create Build Environment # Some projects don't allow in-source building, so create a separate build directory # We'll use this as our working directory for all - run: tools/travis-scripts/before-install.sh + run: tools/unix-ci/before-install.sh - name: Build # Execute the build. You can specify a specific target with "--target " - run: tools/travis-scripts/run-script.sh + run: tools/unix-ci/run-script.sh diff --git a/.github/workflows/pr-ci.yml b/.github/workflows/pr-ci.yml index 2a27801caca0..23cc0f8019fa 100644 --- a/.github/workflows/pr-ci.yml +++ b/.github/workflows/pr-ci.yml @@ -8,9 +8,7 @@ on: env: # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) BUILD_TYPE: Release - # Simple let github action to build all (TODO: optimize in the future) - TRAVIS_PULL_REQUEST: true - GITHUB_CI: true + PYENV_VERSION: 2.7.18 jobs: build-windows: @@ -31,13 +29,13 @@ jobs: - name: Setup Python uses: actions/setup-python@v2 - name: Build - run: tools\windows-ci\build.ps1 $env:BUILD_ARCH + run: tools\win-ci\build.ps1 $env:BUILD_ARCH build-linux: name: build-linux runs-on: ubuntu-latest env: - TRAVIS_OS_NAME: linux + GH_OS_NAME: linux BUILD_TARGET: linux steps: - uses: actions/checkout@v2 @@ -46,8 +44,8 @@ jobs: lfs: 'true' - name: Build run: | - tools/travis-scripts/before-install.sh - tools/travis-scripts/run-script.sh + tools/unix-ci/before-install.sh + tools/unix-ci/run-script.sh build-android: name: build-android @@ -59,9 +57,8 @@ jobs: - arm64-v8a - x86 env: - TRAVIS_OS_NAME: linux + GH_OS_NAME: linux BUILD_TARGET: android - PYENV_VERSION: 2.7.18 BUILD_ARCH: ${{ matrix.arch }} steps: - uses: actions/checkout@v2 @@ -70,14 +67,14 @@ jobs: lfs: 'true' - name: Build run: | - tools/travis-scripts/before-install.sh - tools/travis-scripts/run-script.sh + tools/unix-ci/before-install.sh + tools/unix-ci/run-script.sh build-osx: name: build-osx runs-on: macos-latest env: - TRAVIS_OS_NAME: osx + GH_OS_NAME: osx BUILD_TARGET: osx steps: - uses: actions/checkout@v2 @@ -86,14 +83,14 @@ jobs: lfs: 'true' - name: Build run: | - tools/travis-scripts/before-install.sh - tools/travis-scripts/run-script.sh + tools/unix-ci/before-install.sh + tools/unix-ci/run-script.sh build-ios: name: build-ios runs-on: macos-latest env: - TRAVIS_OS_NAME: osx + GH_OS_NAME: osx BUILD_TARGET: ios steps: - uses: actions/checkout@v2 @@ -102,5 +99,5 @@ jobs: lfs: 'true' - name: Build run: | - tools/travis-scripts/before-install.sh - tools/travis-scripts/run-script.sh + tools/unix-ci/before-install.sh + tools/unix-ci/run-script.sh diff --git a/.github/workflows/windows-ci.yml b/.github/workflows/windows-ci.yml index 6ed0450144f8..0abb5b8b8a69 100644 --- a/.github/workflows/windows-ci.yml +++ b/.github/workflows/windows-ci.yml @@ -44,4 +44,4 @@ jobs: arch: ${{ env.BUILD_ARCH }} - name: Build - run: tools\windows-ci\build.ps1 $env:BUILD_ARCH + run: tools\win-ci\build.ps1 $env:BUILD_ARCH diff --git a/README.md b/README.md index c85f86c3332e..b27f735bfbd9 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,9 @@ # adxe -[![Codacy Badge](https://api.codacy.com/project/badge/Grade/1c5628dea478449ea0c6e1b0e30c3be9)](https://app.codacy.com/gh/adxeproject/adxe?utm_source=github.com&utm_medium=referral&utm_content=adxeproject/adxe&utm_campaign=Badge_Grade_Settings) -[![dev](https://img.shields.io/badge/v1.0.0-beta4-yellow.svg)](https://github.com/adxeproject/adxe/releases) + +[![dev](https://img.shields.io/badge/v1.0.0-beta5-yellow.svg)](https://github.com/adxeproject/adxe/releases) [![LICENSE](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/adxeproject/adxe/blob/master/LICENSE) +[![Codacy Badge](https://api.codacy.com/project/badge/Grade/1c5628dea478449ea0c6e1b0e30c3be9)](https://app.codacy.com/gh/adxeproject/adxe?utm_source=github.com&utm_medium=referral&utm_content=adxeproject/adxe&utm_campaign=Badge_Grade_Settings) +[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-blue.svg)](https://github.com/adxeproject/adxe/pulls) [![Windows Build Status](https://github.com/adxeproject/adxe/actions/workflows/windows-ci.yml/badge.svg)](https://github.com/adxeproject/adxe/actions/workflows/windows-ci.yml) [![Android Build Status](https://github.com/adxeproject/adxe/workflows/android/badge.svg)](https://github.com/adxeproject/adxe/actions?query=workflow%3Aandroid) @@ -9,7 +11,7 @@ [![Linux Build Status](https://github.com/adxeproject/adxe/workflows/linux/badge.svg)](https://github.com/adxeproject/adxe/actions?query=workflow%3Alinux) [![macOS Build Status](https://github.com/adxeproject/adxe/workflows/osx/badge.svg)](https://github.com/adxeproject/adxe/actions?query=workflow%3Aosx) -**This is another more radical fork of *Cocos2d-x-4.0*, use OpenAL for all platforms, single texture multi GPU texture handler, C++ 14/17 and some more (see 'Highlight Features' for more info).** +**This is another more radical fork of *Cocos2d-x-4.0*, use OpenAL for all platforms, single texture multi GPU texture handler, C++ 17 and some more (see 'Highlight Features' for more info).** ### View code with vscode online: - [![github1s](https://img.shields.io/badge/github1s-green.svg)](https://github1s.com/adxeproject/adxe) @@ -19,10 +21,9 @@ **[简体中文](README_CN.md)** ### Purpose Summary -* C++ 14/17 +* C++ 17 * Focus on native game dev (quick starting, easy to use, fast) * Bugfixes ASAP -* Usefull PRs from **you** are welcome (review/merge ASAP) ### Highlight Features * Windows x64 build support @@ -36,7 +37,7 @@ * Implement all .wav formats supported by ```OpenAL Soft```, such as MS-ADPCM, ADPCM, ... * Use modern GL loader ```Glad``` * Google [angle](https://github.com/google/angle) renderer backend support -* C++ 14 standard +* C++ 17 standard * IOS SDK 9.0 as minimal deployment * Use fast pugixml * Use [curl](https://github.com/curl/curl) for transferring data with URL syntax @@ -136,7 +137,7 @@ https://github.com/adxeproject/adxe/discussions/411 - @aismann - @weiwest -### Fullly changes since cocos2d-x-4.0 +### Fully changes since cocos2d-x-4.0 - [HIGHLIGHT] Implement Windows WebView using WebView2 Edge Chromium, thanks to @rh101 - [HIGHLIGHT] Windows x64 build support diff --git a/README_CN.md b/README_CN.md index d52c00e6a883..8784b18e7480 100644 --- a/README_CN.md +++ b/README_CN.md @@ -1,8 +1,9 @@ # adxe -[![Codacy Badge](https://api.codacy.com/project/badge/Grade/1c5628dea478449ea0c6e1b0e30c3be9)](https://app.codacy.com/gh/adxeproject/adxe?utm_source=github.com&utm_medium=referral&utm_content=adxeproject/adxe&utm_campaign=Badge_Grade_Settings) -[![dev](https://img.shields.io/badge/v1.0.0-beta4-yellow.svg)](https://github.com/adxeproject/adxe/releases) +[![dev](https://img.shields.io/badge/v1.0.0-beta5-yellow.svg)](https://github.com/adxeproject/adxe/releases) [![LICENSE](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/adxeproject/adxe/blob/master/LICENSE) +[![Codacy Badge](https://api.codacy.com/project/badge/Grade/1c5628dea478449ea0c6e1b0e30c3be9)](https://app.codacy.com/gh/adxeproject/adxe?utm_source=github.com&utm_medium=referral&utm_content=adxeproject/adxe&utm_campaign=Badge_Grade_Settings) +[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-blue.svg)](https://github.com/adxeproject/adxe/pulls) [![Windows Build Status](https://github.com/adxeproject/adxe/actions/workflows/windows-ci.yml/badge.svg)](https://github.com/adxeproject/adxe/actions/workflows/windows-ci.yml) [![Android Build Status](https://github.com/adxeproject/adxe/workflows/android/badge.svg)](https://github.com/adxeproject/adxe/actions?query=workflow%3Aandroid) @@ -11,16 +12,15 @@ [![macOS Build Status](https://github.com/adxeproject/adxe/workflows/osx/badge.svg)](https://github.com/adxeproject/adxe/actions?query=workflow%3Aosx) -**这是另外一个基于 *Cocos2d-x-4.0* 持续维护的分支, 全平台基于OpenAL, c++14/17...** +**这是另外一个基于 *Cocos2d-x-4.0* 持续维护的分支, 全平台基于OpenAL, c++17...** **[English](README.md)** ### 宗旨: -* C++14/17 +* C++17 * Focus on native game dev only * Fix bugs ASAP * Review PR ASAP -* Excellent PRs from any guys are welcome, we will review & merge ASAP ### 主要特性: * Windows x64编译支持 @@ -33,7 +33,7 @@ * AudioEngine实现wav所有 ```openal-soft``` 支持的封装格式, 例如MS-ADPCM, ADPCM等 * 使用现代化的GL加载器glad代替glew * 增加google angle渲染后端支持 -* 设置默认C++标准为C++14 +* C++最低标准要求: C++17 * 设置ios下最低目标平台为ios9.0 * 使用更快的xml解析库pugixml代替tinyxml2 * Downloader全平台统一实现,均基于curl diff --git a/cocos/2d/CCActionTiledGrid.cpp b/cocos/2d/CCActionTiledGrid.cpp index 85558d98e3f0..74665cd9b41f 100644 --- a/cocos/2d/CCActionTiledGrid.cpp +++ b/cocos/2d/CCActionTiledGrid.cpp @@ -247,7 +247,7 @@ Vec2 ShuffleTiles::getDelta(const Vec2& pos) const pos2.x = (float)(_tilesOrder[idx] / (int)_gridSize.height); pos2.y = (float)(_tilesOrder[idx] % (int)_gridSize.height); - return Vec2((int)(pos2.x - pos.width), (int)(pos2.y - pos.height)); + return Vec2(static_cast((int)(pos2.x - pos.width)), static_cast((int)(pos2.y - pos.height))); } void ShuffleTiles::placeTile(const Vec2& pos, Tile* t) diff --git a/cocos/2d/CCActionTween.cpp b/cocos/2d/CCActionTween.cpp index 37f93ffae189..68b84f63ba44 100644 --- a/cocos/2d/CCActionTween.cpp +++ b/cocos/2d/CCActionTween.cpp @@ -29,7 +29,7 @@ THE SOFTWARE. NS_CC_BEGIN -ActionTween* ActionTween::create(float duration, const std::string& key, float from, float to) +ActionTween* ActionTween::create(float duration, std::string_view key, float from, float to) { ActionTween* ret = new ActionTween(); if (ret->initWithDuration(duration, key, from, to)) @@ -42,7 +42,7 @@ ActionTween* ActionTween::create(float duration, const std::string& key, float f return nullptr; } -bool ActionTween::initWithDuration(float duration, const std::string& key, float from, float to) +bool ActionTween::initWithDuration(float duration, std::string_view key, float from, float to) { if (ActionInterval::initWithDuration(duration)) { diff --git a/cocos/2d/CCActionTween.h b/cocos/2d/CCActionTween.h index 4890f07a93bb..c0d1b7454f71 100644 --- a/cocos/2d/CCActionTween.h +++ b/cocos/2d/CCActionTween.h @@ -59,7 +59,7 @@ class CC_DLL ActionTweenDelegate @param value The new value of the specified key. @param key The key of property which should be updated. */ - virtual void updateTweenAction(float value, const std::string& key) = 0; + virtual void updateTweenAction(float value, std::string_view key) = 0; }; /** ActionTween @@ -93,7 +93,7 @@ class CC_DLL ActionTween : public ActionInterval * @param to The value of the specified property when the action end. * @return If the creation success, return a pointer of ActionTween; otherwise, return nil. */ - static ActionTween* create(float duration, const std::string& key, float from, float to); + static ActionTween* create(float duration, std::string_view key, float from, float to); // Overrides void startWithTarget(Node* target) override; @@ -111,7 +111,7 @@ class CC_DLL ActionTween : public ActionInterval * @return If the initialization success, return true; otherwise, return false. */ bool - initWithDuration(float duration, const std::string& key, float from, float to); + initWithDuration(float duration, std::string_view key, float from, float to); protected: std::string _key; diff --git a/cocos/2d/CCAnimation.cpp b/cocos/2d/CCAnimation.cpp index 7909c0e9a36b..7f0887964509 100644 --- a/cocos/2d/CCAnimation.cpp +++ b/cocos/2d/CCAnimation.cpp @@ -165,7 +165,7 @@ void Animation::addSpriteFrame(SpriteFrame* spriteFrame) _totalDelayUnits++; } -void Animation::addSpriteFrameWithFile(const std::string& filename) +void Animation::addSpriteFrameWithFile(std::string_view filename) { Texture2D* texture = Director::getInstance()->getTextureCache()->addImage(filename); Rect rect = Rect::ZERO; diff --git a/cocos/2d/CCAnimation.h b/cocos/2d/CCAnimation.h index 1a312fc3f7ae..b9b266c61739 100644 --- a/cocos/2d/CCAnimation.h +++ b/cocos/2d/CCAnimation.h @@ -199,7 +199,7 @@ class CC_DLL Animation : public Ref, public Clonable * Added to facilitate the migration from v0.8 to v0.9. * @param filename The path of SpriteFrame. */ - void addSpriteFrameWithFile(const std::string& filename); + void addSpriteFrameWithFile(std::string_view filename); /** Adds a frame with a texture and a rect. Internally it will create a SpriteFrame and it will add it. * The frame will be added with one "delay unit". diff --git a/cocos/2d/CCAnimationCache.cpp b/cocos/2d/CCAnimationCache.cpp index 6c3f62eecb0d..eefbf411d7c5 100644 --- a/cocos/2d/CCAnimationCache.cpp +++ b/cocos/2d/CCAnimationCache.cpp @@ -63,12 +63,12 @@ AnimationCache::~AnimationCache() CCLOGINFO("deallocing AnimationCache: %p", this); } -void AnimationCache::addAnimation(Animation* animation, const std::string& name) +void AnimationCache::addAnimation(Animation* animation, std::string_view name) { - _animations.insert(name, animation); + _animations.insert(std::string{name}, animation); } -void AnimationCache::removeAnimation(const std::string& name) +void AnimationCache::removeAnimation(std::string_view name) { if (name.empty()) return; @@ -76,7 +76,7 @@ void AnimationCache::removeAnimation(const std::string& name) _animations.erase(name); } -Animation* AnimationCache::getAnimation(const std::string& name) +Animation* AnimationCache::getAnimation(std::string_view name) { return _animations.at(name); } @@ -205,7 +205,7 @@ void AnimationCache::parseVersion2(const ValueMap& animations) } } -void AnimationCache::addAnimationsWithDictionary(const ValueMap& dictionary, const std::string& plist) +void AnimationCache::addAnimationsWithDictionary(const ValueMap& dictionary, std::string_view plist) { auto anisItr = dictionary.find("animations"); if (anisItr == dictionary.end()) @@ -245,7 +245,7 @@ void AnimationCache::addAnimationsWithDictionary(const ValueMap& dictionary, con } /** Read an NSDictionary from a plist file and parse it automatically for animations */ -void AnimationCache::addAnimationsWithFile(const std::string& plist) +void AnimationCache::addAnimationsWithFile(std::string_view plist) { CCASSERT(!plist.empty(), "Invalid texture file name"); if (plist.empty()) @@ -259,7 +259,7 @@ void AnimationCache::addAnimationsWithFile(const std::string& plist) CCASSERT(!dict.empty(), "CCAnimationCache: File could not be found"); if (dict.empty()) { - log("AnimationCache::addAnimationsWithFile error:%s not exist!", plist.c_str()); + log("AnimationCache::addAnimationsWithFile error:%s not exist!", plist.data()); } addAnimationsWithDictionary(dict, plist); diff --git a/cocos/2d/CCAnimationCache.h b/cocos/2d/CCAnimationCache.h index 0c41b66454ab..35ae26a737e6 100644 --- a/cocos/2d/CCAnimationCache.h +++ b/cocos/2d/CCAnimationCache.h @@ -81,13 +81,13 @@ class CC_DLL AnimationCache : public Ref * @param animation An animation. * @param name The name of animation. */ - void addAnimation(Animation* animation, const std::string& name); + void addAnimation(Animation* animation, std::string_view name); /** Deletes a Animation from the cache. * * @param name The name of animation. */ - void removeAnimation(const std::string& name); + void removeAnimation(std::string_view name); /** Returns a Animation that was previously added. * If the name is not found it will return nil. @@ -95,7 +95,7 @@ class CC_DLL AnimationCache : public Ref * * @return A Animation that was previously added. If the name is not found it will return nil. */ - Animation* getAnimation(const std::string& name); + Animation* getAnimation(std::string_view name); /** Adds an animation from an NSDictionary. * Make sure that the frames were previously loaded in the SpriteFrameCache. @@ -104,7 +104,7 @@ class CC_DLL AnimationCache : public Ref * @since v1.1 @js NA */ - void addAnimationsWithDictionary(const ValueMap& dictionary, const std::string& plist); + void addAnimationsWithDictionary(const ValueMap& dictionary, std::string_view plist); /** Adds an animation from a plist file. * Make sure that the frames were previously loaded in the SpriteFrameCache. @@ -113,14 +113,14 @@ class CC_DLL AnimationCache : public Ref * @lua addAnimations * @param plist An animation from a plist file. */ - void addAnimationsWithFile(const std::string& plist); + void addAnimationsWithFile(std::string_view plist); private: void parseVersion1(const ValueMap& animations); void parseVersion2(const ValueMap& animations); private: - Map _animations; + StringMap _animations; static AnimationCache* s_sharedAnimationCache; }; diff --git a/cocos/2d/CCAtlasNode.cpp b/cocos/2d/CCAtlasNode.cpp index d1448ebdb439..6f38d8935076 100644 --- a/cocos/2d/CCAtlasNode.cpp +++ b/cocos/2d/CCAtlasNode.cpp @@ -47,7 +47,7 @@ AtlasNode::~AtlasNode() CC_SAFE_RELEASE(_textureAtlas); } -AtlasNode* AtlasNode::create(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender) +AtlasNode* AtlasNode::create(std::string_view tile, int tileWidth, int tileHeight, int itemsToRender) { AtlasNode* ret = new AtlasNode(); if (ret->initWithTileFile(tile, tileWidth, tileHeight, itemsToRender)) @@ -59,7 +59,7 @@ AtlasNode* AtlasNode::create(const std::string& tile, int tileWidth, int tileHei return nullptr; } -bool AtlasNode::initWithTileFile(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender) +bool AtlasNode::initWithTileFile(std::string_view tile, int tileWidth, int tileHeight, int itemsToRender) { CCASSERT(!tile.empty(), "file size should not be empty"); Texture2D* texture = _director->getTextureCache()->addImage(tile); @@ -222,7 +222,7 @@ void AtlasNode::setIgnoreContentScaleFactor(bool ignoreContentScaleFactor) auto label = dynamic_cast(this); if (label) { - Vec2 s = Vec2(label->getString().size() * _itemWidth, _itemHeight); + Vec2 s = Vec2(static_cast(label->getString().size() * _itemWidth), static_cast(_itemHeight)); this->setContentSize(s); } } diff --git a/cocos/2d/CCAtlasNode.h b/cocos/2d/CCAtlasNode.h index e35c14942df9..63125c6d336d 100644 --- a/cocos/2d/CCAtlasNode.h +++ b/cocos/2d/CCAtlasNode.h @@ -57,7 +57,7 @@ class CC_DLL AtlasNode : public Node, public TextureProtocol * @param tileHeight The height of the item. * @param itemsToRender The quantity of items to render. */ - static AtlasNode* create(const std::string& filename, int tileWidth, int tileHeight, int itemsToRender); + static AtlasNode* create(std::string_view filename, int tileWidth, int tileHeight, int itemsToRender); /** updates the Atlas (indexed vertex array). * Shall be overridden in subclasses. @@ -106,7 +106,7 @@ class CC_DLL AtlasNode : public Node, public TextureProtocol /** Initializes an AtlasNode with an Atlas file the width and height of each item and the quantity of items to * render*/ - bool initWithTileFile(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender); + bool initWithTileFile(std::string_view tile, int tileWidth, int tileHeight, int itemsToRender); /** Initializes an AtlasNode with a texture the width and height of each item measured in points and the quantity * of items to render*/ diff --git a/cocos/2d/CCAutoPolygon.cpp b/cocos/2d/CCAutoPolygon.cpp index 6becd122ecbf..6cec4151315e 100644 --- a/cocos/2d/CCAutoPolygon.cpp +++ b/cocos/2d/CCAutoPolygon.cpp @@ -168,7 +168,7 @@ float PolygonInfo::getArea() const return area; } -AutoPolygon::AutoPolygon(const std::string& filename) +AutoPolygon::AutoPolygon(std::string_view filename) : _image(nullptr), _data(nullptr), _filename(""), _width(0), _height(0), _scaleFactor(0) { _filename = filename; @@ -714,7 +714,7 @@ PolygonInfo AutoPolygon::generateTriangles(const Rect& rect, float epsilon, floa return ret; } -PolygonInfo AutoPolygon::generatePolygon(const std::string& filename, const Rect& rect, float epsilon, float threshold) +PolygonInfo AutoPolygon::generatePolygon(std::string_view filename, const Rect& rect, float epsilon, float threshold) { AutoPolygon ap(filename); return ap.generateTriangles(rect, epsilon, threshold); diff --git a/cocos/2d/CCAutoPolygon.h b/cocos/2d/CCAutoPolygon.h index 1552ab99afff..676c6bd03b2c 100644 --- a/cocos/2d/CCAutoPolygon.h +++ b/cocos/2d/CCAutoPolygon.h @@ -117,8 +117,8 @@ class CC_DLL PolygonInfo const Rect& getRect() const { return _rect; } void setRect(const Rect& rect) { _rect = rect; } - const std::string& getFilename() const { return _filename; } - void setFilename(const std::string& filename) { _filename = filename; } + std::string_view getFilename() const { return _filename; } + void setFilename(std::string_view filename) { _filename = filename; } // FIXME: this should be a property, not a public ivar TrianglesCommand::Triangles triangles; @@ -147,7 +147,7 @@ class CC_DLL AutoPolygon * @param filename a path to image file, e.g., "scene1/monster.png". * @return an AutoPolygon object; */ - AutoPolygon(const std::string& filename); + AutoPolygon(std::string_view filename); /** * Destructor of AutoPolygon. @@ -254,7 +254,7 @@ class CC_DLL AutoPolygon * auto sp = Sprite::create(AutoPolygon::generatePolygon("grossini.png")); * @endcode */ - static PolygonInfo generatePolygon(const std::string& filename, + static PolygonInfo generatePolygon(std::string_view filename, const Rect& rect = Rect::ZERO, float epsilon = 2.0f, float threshold = 0.05f); diff --git a/cocos/2d/CCCameraBackgroundBrush.cpp b/cocos/2d/CCCameraBackgroundBrush.cpp index 442ca25bcb32..f983bfa87f03 100644 --- a/cocos/2d/CCCameraBackgroundBrush.cpp +++ b/cocos/2d/CCCameraBackgroundBrush.cpp @@ -71,12 +71,12 @@ CameraBackgroundDepthBrush* CameraBackgroundBrush::createDepthBrush(float depth) return CameraBackgroundDepthBrush::create(depth); } -CameraBackgroundSkyBoxBrush* CameraBackgroundBrush::createSkyboxBrush(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z) +CameraBackgroundSkyBoxBrush* CameraBackgroundBrush::createSkyboxBrush(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z) { return CameraBackgroundSkyBoxBrush::create(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z); } @@ -303,12 +303,12 @@ CameraBackgroundSkyBoxBrush::~CameraBackgroundSkyBoxBrush() #endif } -CameraBackgroundSkyBoxBrush* CameraBackgroundSkyBoxBrush::create(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z) +CameraBackgroundSkyBoxBrush* CameraBackgroundSkyBoxBrush::create(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z) { CameraBackgroundSkyBoxBrush* ret = nullptr; diff --git a/cocos/2d/CCCameraBackgroundBrush.h b/cocos/2d/CCCameraBackgroundBrush.h index 1f884cff8554..630b1a87e373 100644 --- a/cocos/2d/CCCameraBackgroundBrush.h +++ b/cocos/2d/CCCameraBackgroundBrush.h @@ -105,12 +105,12 @@ class CC_DLL CameraBackgroundBrush : public Ref @param negative_z texture for the rear side of the texture cube face. @return A new brush inited with given parameters. */ - static CameraBackgroundSkyBoxBrush* createSkyboxBrush(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z); + static CameraBackgroundSkyBoxBrush* createSkyboxBrush(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z); /** * draw the background */ @@ -253,12 +253,12 @@ class CC_DLL CameraBackgroundSkyBoxBrush : public CameraBackgroundBrush @param negative_z texture for the rear side of the texture cube face. @return A new brush inited with given parameters. */ - static CameraBackgroundSkyBoxBrush* create(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z); + static CameraBackgroundSkyBoxBrush* create(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z); /** Creates a Skybox brush with 6 textures. */ diff --git a/cocos/2d/CCComponent.h b/cocos/2d/CCComponent.h index d780a665e63c..6fa5ff0859ca 100644 --- a/cocos/2d/CCComponent.h +++ b/cocos/2d/CCComponent.h @@ -60,8 +60,8 @@ class CC_DLL Component : public Ref bool isEnabled() const { return _enabled; } virtual void setEnabled(bool enabled); - const std::string& getName() const { return _name; } - virtual void setName(const std::string& name) { _name = name; } + std::string_view getName() const { return _name; } + virtual void setName(std::string_view name) { _name = name; } Node* getOwner() const { return _owner; } virtual void setOwner(Node* owner); diff --git a/cocos/2d/CCComponentContainer.cpp b/cocos/2d/CCComponentContainer.cpp index 92f57884155c..456fcb8783fd 100644 --- a/cocos/2d/CCComponentContainer.cpp +++ b/cocos/2d/CCComponentContainer.cpp @@ -33,7 +33,7 @@ ComponentContainer::ComponentContainer(Node* node) : _owner(node) {} ComponentContainer::~ComponentContainer() {} -Component* ComponentContainer::get(const std::string& name) const +Component* ComponentContainer::get(std::string_view name) const { Component* ret = nullptr; @@ -60,7 +60,7 @@ bool ComponentContainer::add(Component* com) CCASSERT(false, "ComponentContainer already have this kind of component"); break; } - _componentMap[componentName] = com; + hlookup::set_item(_componentMap, componentName, com); //_componentMap[componentName] = com; com->retain(); com->setOwner(_owner); com->onAdd(); @@ -70,7 +70,7 @@ bool ComponentContainer::add(Component* com) return ret; } -bool ComponentContainer::remove(const std::string& componentName) +bool ComponentContainer::remove(std::string_view componentName) { bool ret = false; do diff --git a/cocos/2d/CCComponentContainer.h b/cocos/2d/CCComponentContainer.h index caba0e1a2420..bdc08df7593e 100644 --- a/cocos/2d/CCComponentContainer.h +++ b/cocos/2d/CCComponentContainer.h @@ -54,10 +54,10 @@ class CC_DLL ComponentContainer /** * @js getComponent */ - Component* get(const std::string& name) const; + Component* get(std::string_view name) const; bool add(Component* com); - bool remove(const std::string& name); + bool remove(std::string_view name); bool remove(Component* com); void removeAll(); void visit(float delta); @@ -68,7 +68,7 @@ class CC_DLL ComponentContainer bool isEmpty() const { return _componentMap.empty(); } private: - std::unordered_map _componentMap; + hlookup::string_map _componentMap; Node* _owner; friend class Node; diff --git a/cocos/2d/CCFastTMXLayer.cpp b/cocos/2d/CCFastTMXLayer.cpp index c3f82291a9b5..566eae82230c 100644 --- a/cocos/2d/CCFastTMXLayer.cpp +++ b/cocos/2d/CCFastTMXLayer.cpp @@ -799,7 +799,7 @@ void FastTMXLayer::removeChild(Node* node, bool cleanup) } // TMXLayer - Properties -Value FastTMXLayer::getProperty(const std::string& propertyName) const +Value FastTMXLayer::getProperty(std::string_view propertyName) const { auto propItr = _properties.find(propertyName); if (propItr != _properties.end()) diff --git a/cocos/2d/CCFastTMXLayer.h b/cocos/2d/CCFastTMXLayer.h index 0c69484ed8fa..0da9a39e8d07 100644 --- a/cocos/2d/CCFastTMXLayer.h +++ b/cocos/2d/CCFastTMXLayer.h @@ -152,7 +152,7 @@ class CC_DLL FastTMXLayer : public Node * @param propertyName The value for the specific property name. * @return The value for the specific property name. */ - Value getProperty(const std::string& propertyName) const; + Value getProperty(std::string_view propertyName) const; /** Creates the tiles. */ void setupTiles(); @@ -161,13 +161,13 @@ class CC_DLL FastTMXLayer : public Node * * @return The tile layer name. */ - const std::string& getLayerName() { return _layerName; } + std::string_view getLayerName() { return _layerName; } /** Set the tile layer name. * * @param layerName The new layer name. */ - void setLayerName(const std::string& layerName) { _layerName = layerName; } + void setLayerName(std::string_view layerName) { _layerName = layerName; } /** Gets the size of the layer in tiles. * diff --git a/cocos/2d/CCFastTMXTiledMap.cpp b/cocos/2d/CCFastTMXTiledMap.cpp index b17ff6328f92..d06d483a7c48 100644 --- a/cocos/2d/CCFastTMXTiledMap.cpp +++ b/cocos/2d/CCFastTMXTiledMap.cpp @@ -33,7 +33,7 @@ NS_CC_BEGIN // implementation FastTMXTiledMap -FastTMXTiledMap* FastTMXTiledMap::create(const std::string& tmxFile) +FastTMXTiledMap* FastTMXTiledMap::create(std::string_view tmxFile) { FastTMXTiledMap* ret = new FastTMXTiledMap(); if (ret->initWithTMXFile(tmxFile)) @@ -45,7 +45,7 @@ FastTMXTiledMap* FastTMXTiledMap::create(const std::string& tmxFile) return nullptr; } -FastTMXTiledMap* FastTMXTiledMap::createWithXML(const std::string& tmxString, const std::string& resourcePath) +FastTMXTiledMap* FastTMXTiledMap::createWithXML(std::string_view tmxString, std::string_view resourcePath) { FastTMXTiledMap* ret = new FastTMXTiledMap(); if (ret->initWithXML(tmxString, resourcePath)) @@ -57,7 +57,7 @@ FastTMXTiledMap* FastTMXTiledMap::createWithXML(const std::string& tmxString, co return nullptr; } -bool FastTMXTiledMap::initWithTMXFile(const std::string& tmxFile) +bool FastTMXTiledMap::initWithTMXFile(std::string_view tmxFile) { CCASSERT(tmxFile.size() > 0, "FastTMXTiledMap: tmx file should not be empty"); @@ -77,7 +77,7 @@ bool FastTMXTiledMap::initWithTMXFile(const std::string& tmxFile) return true; } -bool FastTMXTiledMap::initWithXML(const std::string& tmxString, const std::string& resourcePath) +bool FastTMXTiledMap::initWithXML(std::string_view tmxString, std::string_view resourcePath) { setContentSize(Vec2::ZERO); @@ -194,7 +194,7 @@ void FastTMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo) } // public -FastTMXLayer* FastTMXTiledMap::getLayer(const std::string& layerName) const +FastTMXLayer* FastTMXTiledMap::getLayer(std::string_view layerName) const { CCASSERT(!layerName.empty(), "Invalid layer name!"); @@ -214,7 +214,7 @@ FastTMXLayer* FastTMXTiledMap::getLayer(const std::string& layerName) const return nullptr; } -TMXObjectGroup* FastTMXTiledMap::getObjectGroup(const std::string& groupName) const +TMXObjectGroup* FastTMXTiledMap::getObjectGroup(std::string_view groupName) const { CCASSERT(!groupName.empty(), "Invalid group name!"); @@ -233,7 +233,7 @@ TMXObjectGroup* FastTMXTiledMap::getObjectGroup(const std::string& groupName) co return nullptr; } -Value FastTMXTiledMap::getProperty(const std::string& propertyName) const +Value FastTMXTiledMap::getProperty(std::string_view propertyName) const { auto propsItr = _properties.find(propertyName); if (propsItr != _properties.end()) diff --git a/cocos/2d/CCFastTMXTiledMap.h b/cocos/2d/CCFastTMXTiledMap.h index da7a0273ac31..9790ea746ba5 100644 --- a/cocos/2d/CCFastTMXTiledMap.h +++ b/cocos/2d/CCFastTMXTiledMap.h @@ -101,7 +101,7 @@ class CC_DLL FastTMXTiledMap : public Node * * @return An autorelease object. */ - static FastTMXTiledMap* create(const std::string& tmxFile); + static FastTMXTiledMap* create(std::string_view tmxFile); /** Initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources. * @@ -109,25 +109,25 @@ class CC_DLL FastTMXTiledMap : public Node * @param resourcePath A path to TMX resources. * @return An autorelease object. */ - static FastTMXTiledMap* createWithXML(const std::string& tmxString, const std::string& resourcePath); + static FastTMXTiledMap* createWithXML(std::string_view tmxString, std::string_view resourcePath); /** Return the FastTMXLayer for the specific layer. * * @return Return the FastTMXLayer for the specific layer. */ - FastTMXLayer* getLayer(const std::string& layerName) const; + FastTMXLayer* getLayer(std::string_view layerName) const; /** Return the TMXObjectGroup for the specific group. * * @return Return the TMXObjectGroup for the specific group. */ - TMXObjectGroup* getObjectGroup(const std::string& groupName) const; + TMXObjectGroup* getObjectGroup(std::string_view groupName) const; /** Return the value for the specific property name. * * @return Return the value for the specific property name. */ - Value getProperty(const std::string& propertyName) const; + Value getProperty(std::string_view propertyName) const; /** Return properties dictionary for tile GID. * @@ -207,7 +207,7 @@ class CC_DLL FastTMXTiledMap : public Node int getLayerCount() const { return _layerCount; } - const std::string& getResourceFile() const { return _tmxFile; } + std::string_view getResourceFile() const { return _tmxFile; } CC_CONSTRUCTOR_ACCESS : /** @@ -221,10 +221,10 @@ class CC_DLL FastTMXTiledMap : public Node virtual ~FastTMXTiledMap(); /** initializes a TMX Tiled Map with a TMX file */ - bool initWithTMXFile(const std::string& tmxFile); + bool initWithTMXFile(std::string_view tmxFile); /** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ - bool initWithXML(const std::string& tmxString, const std::string& resourcePath); + bool initWithXML(std::string_view tmxString, std::string_view resourcePath); protected: FastTMXLayer* parseLayer(TMXLayerInfo* layerInfo, TMXMapInfo* mapInfo); diff --git a/cocos/2d/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp index df0db9bc0208..fc1aabd928f2 100644 --- a/cocos/2d/CCFontAtlas.cpp +++ b/cocos/2d/CCFontAtlas.cpp @@ -520,9 +520,9 @@ void FontAtlas::setLineHeight(float newHeight) _lineHeight = newHeight; } -std::string FontAtlas::getFontName() const +std::string_view FontAtlas::getFontName() const { - std::string fontName = _fontFreeType ? _fontFreeType->getFontName() : ""; + std::string_view fontName = _fontFreeType ? _fontFreeType->getFontName() : ""sv; if (fontName.empty()) return fontName; auto idx = fontName.rfind('/'); diff --git a/cocos/2d/CCFontAtlas.h b/cocos/2d/CCFontAtlas.h index 384aecb2548a..16bcfc72a81e 100644 --- a/cocos/2d/CCFontAtlas.h +++ b/cocos/2d/CCFontAtlas.h @@ -86,7 +86,7 @@ class CC_DLL FontAtlas : public Ref float getLineHeight() const { return _lineHeight; } void setLineHeight(float newHeight); - std::string getFontName() const; + std::string_view getFontName() const; Texture2D* getTexture(int slot); const Font* getFont() const { return _font; } diff --git a/cocos/2d/CCFontAtlasCache.cpp b/cocos/2d/CCFontAtlasCache.cpp index d9df5ab56683..4ab977172066 100644 --- a/cocos/2d/CCFontAtlasCache.cpp +++ b/cocos/2d/CCFontAtlasCache.cpp @@ -36,7 +36,7 @@ NS_CC_BEGIN -std::unordered_map FontAtlasCache::_atlasMap; +hlookup::string_map FontAtlasCache::_atlasMap; #define ATLAS_MAP_KEY_PREFIX_BUFFER_SIZE 255 void FontAtlasCache::purgeCachedData() @@ -80,8 +80,7 @@ FontAtlas* FontAtlasCache::getFontAtlasTTF(const _ttfConfig* config) auto tempAtlas = font->newFontAtlas(); if (tempAtlas) { - _atlasMap[atlasName] = tempAtlas; - return _atlasMap[atlasName]; + return _atlasMap.emplace(atlasName, tempAtlas).first->second; } } } @@ -91,16 +90,17 @@ FontAtlas* FontAtlasCache::getFontAtlasTTF(const _ttfConfig* config) return nullptr; } -FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName) +FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName) { return getFontAtlasFNT(fontFileName, Rect::ZERO, false); } -FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName, const std::string& subTextureKey) +FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName, std::string_view subTextureKey) { const auto realFontFilename = FileUtils::getInstance()->getNewFilename( fontFileName); // resolves real file path, to prevent storing multiple atlases for the same file. - std::string atlasName = subTextureKey + " " + realFontFilename; + std::string atlasName{subTextureKey}; + atlasName.append(" ", 1).append(realFontFilename); const auto it = _atlasMap.find(atlasName); if (it == _atlasMap.end()) @@ -123,7 +123,7 @@ FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName, cons return nullptr; } -FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName, const Rect& imageRect, bool imageRotated) +FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName, const Rect& imageRect, bool imageRotated) { const auto realFontFilename = FileUtils::getInstance()->getNewFilename( fontFileName); // resolves real file path, to prevent storing multiple atlases for the same file. @@ -153,14 +153,14 @@ FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName, cons return nullptr; } -FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName, const Vec2& imageOffset) +FontAtlas* FontAtlasCache::getFontAtlasFNT(std::string_view fontFileName, const Vec2& imageOffset) { return getFontAtlasFNT(fontFileName, Rect(imageOffset.x, imageOffset.y, 0, 0), false); } -FontAtlas* FontAtlasCache::getFontAtlasCharMap(const std::string& plistFile) +FontAtlas* FontAtlasCache::getFontAtlasCharMap(std::string_view plistFile) { - const std::string& atlasName = plistFile; + std::string_view atlasName = plistFile; auto it = _atlasMap.find(atlasName); if (it == _atlasMap.end()) @@ -172,8 +172,8 @@ FontAtlas* FontAtlasCache::getFontAtlasCharMap(const std::string& plistFile) auto tempAtlas = font->newFontAtlas(); if (tempAtlas) { - _atlasMap[atlasName] = tempAtlas; - return _atlasMap[atlasName]; + hlookup::set_item(_atlasMap, atlasName, tempAtlas); // _atlasMap[atlasName] = tempAtlas; + return tempAtlas; } } } @@ -210,7 +210,7 @@ FontAtlas* FontAtlasCache::getFontAtlasCharMap(Texture2D* texture, int itemWidth return nullptr; } -FontAtlas* FontAtlasCache::getFontAtlasCharMap(const std::string& charMapFile, +FontAtlas* FontAtlasCache::getFontAtlasCharMap(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap) @@ -263,7 +263,7 @@ bool FontAtlasCache::releaseFontAtlas(FontAtlas* atlas) return false; } -void FontAtlasCache::reloadFontAtlasFNT(const std::string& fontFileName, const Rect& imageRect, bool imageRotated) +void FontAtlasCache::reloadFontAtlasFNT(std::string_view fontFileName, const Rect& imageRect, bool imageRotated) { char keyPrefix[ATLAS_MAP_KEY_PREFIX_BUFFER_SIZE]; snprintf(keyPrefix, ATLAS_MAP_KEY_PREFIX_BUFFER_SIZE, "%.2f %.2f ", imageRect.origin.x, imageRect.origin.y); @@ -288,12 +288,12 @@ void FontAtlasCache::reloadFontAtlasFNT(const std::string& fontFileName, const R } } -void FontAtlasCache::reloadFontAtlasFNT(const std::string& fontFileName, const Vec2& imageOffset) +void FontAtlasCache::reloadFontAtlasFNT(std::string_view fontFileName, const Vec2& imageOffset) { reloadFontAtlasFNT(fontFileName, Rect(imageOffset.x, imageOffset.y, 0, 0), false); } -void FontAtlasCache::unloadFontAtlasTTF(const std::string& fontFileName) +void FontAtlasCache::unloadFontAtlasTTF(std::string_view fontFileName) { auto item = _atlasMap.begin(); while (item != _atlasMap.end()) diff --git a/cocos/2d/CCFontAtlasCache.h b/cocos/2d/CCFontAtlasCache.h index d995d2a92ffb..f02e41ad2219 100644 --- a/cocos/2d/CCFontAtlasCache.h +++ b/cocos/2d/CCFontAtlasCache.h @@ -43,17 +43,17 @@ class CC_DLL FontAtlasCache public: static FontAtlas* getFontAtlasTTF(const _ttfConfig* config); - static FontAtlas* getFontAtlasFNT(const std::string& fontFileName); - static FontAtlas* getFontAtlasFNT(const std::string& fontFileName, const std::string& subTextureKey); - static FontAtlas* getFontAtlasFNT(const std::string& fontFileName, const Rect& imageRect, bool imageRotated); - CC_DEPRECATED_ATTRIBUTE static FontAtlas* getFontAtlasFNT(const std::string& fontFileName, const Vec2& imageOffset); + static FontAtlas* getFontAtlasFNT(std::string_view fontFileName); + static FontAtlas* getFontAtlasFNT(std::string_view fontFileName, std::string_view subTextureKey); + static FontAtlas* getFontAtlasFNT(std::string_view fontFileName, const Rect& imageRect, bool imageRotated); + CC_DEPRECATED_ATTRIBUTE static FontAtlas* getFontAtlasFNT(std::string_view fontFileName, const Vec2& imageOffset); - static FontAtlas* getFontAtlasCharMap(const std::string& charMapFile, + static FontAtlas* getFontAtlasCharMap(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap); static FontAtlas* getFontAtlasCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); - static FontAtlas* getFontAtlasCharMap(const std::string& plistFile); + static FontAtlas* getFontAtlasCharMap(std::string_view plistFile); static bool releaseFontAtlas(FontAtlas* atlas); @@ -66,19 +66,19 @@ class CC_DLL FontAtlasCache CAUTION : All component use this font texture should be reset font name, though the file name is same! otherwise, it will cause program crash! */ - static void reloadFontAtlasFNT(const std::string& fontFileName, const Rect& imageRect, bool imageRotated); + static void reloadFontAtlasFNT(std::string_view fontFileName, const Rect& imageRect, bool imageRotated); - CC_DEPRECATED_ATTRIBUTE static void reloadFontAtlasFNT(const std::string& fontFileName, + CC_DEPRECATED_ATTRIBUTE static void reloadFontAtlasFNT(std::string_view fontFileName, const Vec2& imageOffset = Vec2::ZERO); /** Unload all texture atlas texture create by special file name. CAUTION : All component use this font texture should be reset font name, though the file name is same! otherwise, it will cause program crash! */ - static void unloadFontAtlasTTF(const std::string& fontFileName); + static void unloadFontAtlasTTF(std::string_view fontFileName); private: - static std::unordered_map _atlasMap; + static hlookup::string_map _atlasMap; }; NS_CC_END diff --git a/cocos/2d/CCFontCharMap.cpp b/cocos/2d/CCFontCharMap.cpp index c8625143b92a..8eb4986c8380 100644 --- a/cocos/2d/CCFontCharMap.cpp +++ b/cocos/2d/CCFontCharMap.cpp @@ -33,7 +33,7 @@ NS_CC_BEGIN -FontCharMap* FontCharMap::create(const std::string& plistFile) +FontCharMap* FontCharMap::create(std::string_view plistFile) { std::string pathStr = FileUtils::getInstance()->fullPathForFilename(plistFile); std::string relPathStr = pathStr.substr(0, pathStr.find_last_of('/')) + "/"; @@ -64,7 +64,7 @@ FontCharMap* FontCharMap::create(const std::string& plistFile) return tempFont; } -FontCharMap* FontCharMap::create(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) +FontCharMap* FontCharMap::create(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap) { Texture2D* tempTexture = Director::getInstance()->getTextureCache()->addImage(charMapFile); diff --git a/cocos/2d/CCFontCharMap.h b/cocos/2d/CCFontCharMap.h index 1c576571968e..436290471d07 100644 --- a/cocos/2d/CCFontCharMap.h +++ b/cocos/2d/CCFontCharMap.h @@ -38,9 +38,9 @@ class Texture2D; class FontCharMap : public Font { public: - static FontCharMap* create(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); + static FontCharMap* create(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap); static FontCharMap* create(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); - static FontCharMap* create(const std::string& plistFile); + static FontCharMap* create(std::string_view plistFile); virtual int* getHorizontalKerningForTextUTF32(const std::u32string& text, int& outNumLetters) const override; virtual FontAtlas* newFontAtlas() override; diff --git a/cocos/2d/CCFontFNT.cpp b/cocos/2d/CCFontFNT.cpp index d3b252a4b280..87fa76440de5 100644 --- a/cocos/2d/CCFontFNT.cpp +++ b/cocos/2d/CCFontFNT.cpp @@ -56,15 +56,15 @@ struct _FontDefHashElement; // // FNTConfig Cache - free functions // -static Map* s_configurations = nullptr; +static StringMap* s_configurations = nullptr; -BMFontConfiguration* FNTConfigLoadFile(const std::string& fntFile) +BMFontConfiguration* FNTConfigLoadFile(std::string_view fntFile) { BMFontConfiguration* ret = nullptr; if (s_configurations == nullptr) { - s_configurations = new Map(); + s_configurations = new StringMap(); } ret = s_configurations->at(fntFile); @@ -84,7 +84,7 @@ BMFontConfiguration* FNTConfigLoadFile(const std::string& fntFile) // BitmapFontConfiguration // -BMFontConfiguration* BMFontConfiguration::create(const std::string& FNTfile) +BMFontConfiguration* BMFontConfiguration::create(std::string_view FNTfile) { BMFontConfiguration* ret = new BMFontConfiguration(); if (ret->initWithFNTfile(FNTfile)) @@ -96,7 +96,7 @@ BMFontConfiguration* BMFontConfiguration::create(const std::string& FNTfile) return nullptr; } -bool BMFontConfiguration::initWithFNTfile(const std::string& FNTfile) +bool BMFontConfiguration::initWithFNTfile(std::string_view FNTfile) { _characterSet = this->parseConfigFile(FNTfile); @@ -141,7 +141,7 @@ void BMFontConfiguration::purgeFontDefDictionary() _fontDefDictionary.clear(); } -std::set* BMFontConfiguration::parseConfigFile(const std::string& controlFile) +std::set* BMFontConfiguration::parseConfigFile(std::string_view controlFile) { std::string data = FileUtils::getInstance()->getStringFromFile(controlFile); if (data.empty()) @@ -156,7 +156,7 @@ std::set* BMFontConfiguration::parseConfigFile(const std::string& } if (data[0] == 0) { - CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.c_str()); + CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.data()); return nullptr; } auto contents = data.c_str(); @@ -223,7 +223,7 @@ std::set* BMFontConfiguration::parseConfigFile(const std::string& std::set* BMFontConfiguration::parseBinaryConfigFile(unsigned char* pData, uint32_t size, - const std::string& controlFile) + std::string_view controlFile) { /* based on http://www.angelcode.com/products/bmfont/doc/file_format.html file format */ @@ -399,7 +399,7 @@ std::set* BMFontConfiguration::parseBinaryConfigFile(unsigned char return validCharsString; } -void BMFontConfiguration::parseImageFileName(const char* line, const std::string& fntFile) +void BMFontConfiguration::parseImageFileName(const char* line, std::string_view fntFile) { ////////////////////////////////////////////////////////////////////////// // line to parse: @@ -528,7 +528,7 @@ void BMFontConfiguration::parseKerningEntry(const char* line) _kerningDictionary[key] = amount; } -FontFNT* FontFNT::create(const std::string& fntFilePath, const Rect& imageRect, bool imageRotated) +FontFNT* FontFNT::create(std::string_view fntFilePath, const Rect& imageRect, bool imageRotated) { const auto newConf = FNTConfigLoadFile(fntFilePath); if (!newConf) @@ -545,7 +545,7 @@ FontFNT* FontFNT::create(const std::string& fntFilePath, const Rect& imageRect, return tempFont; } -FontFNT* FontFNT::create(const std::string& fntFilePath, const std::string& subTextureKey) +FontFNT* FontFNT::create(std::string_view fntFilePath, std::string_view subTextureKey) { const auto newConf = FNTConfigLoadFile(fntFilePath); if (!newConf) @@ -567,7 +567,7 @@ FontFNT* FontFNT::create(const std::string& fntFilePath, const std::string& subT return tempFont; } -FontFNT* FontFNT::create(const std::string& fntFilePath) +FontFNT* FontFNT::create(std::string_view fntFilePath) { const auto newConf = FNTConfigLoadFile(fntFilePath); if (!newConf) @@ -590,7 +590,7 @@ FontFNT* FontFNT::create(const std::string& fntFilePath) return tempFont; } -FontFNT* FontFNT::create(const std::string& fntFilePath, const Vec2& imageOffset) +FontFNT* FontFNT::create(std::string_view fntFilePath, const Vec2& imageOffset) { return create(fntFilePath, Rect(imageOffset.x, imageOffset.y, 0, 0), false); } @@ -762,11 +762,11 @@ FontAtlas* FontFNT::newFontAtlas() return tempAtlas; } -void FontFNT::reloadBMFontResource(const std::string& fntFilePath) +void FontFNT::reloadBMFontResource(std::string_view fntFilePath) { if (s_configurations == nullptr) { - s_configurations = new Map(); + s_configurations = new StringMap(); } BMFontConfiguration* ret = s_configurations->at(fntFilePath); diff --git a/cocos/2d/CCFontFNT.h b/cocos/2d/CCFontFNT.h index 3e6cb364a62b..a255920330a9 100644 --- a/cocos/2d/CCFontFNT.h +++ b/cocos/2d/CCFontFNT.h @@ -115,27 +115,27 @@ class CC_DLL BMFontConfiguration : public Ref std::string description() const; /** allocates a BMFontConfiguration with a FNT file */ - static BMFontConfiguration* create(const std::string& FNTfile); + static BMFontConfiguration* create(std::string_view FNTfile); /** initializes a BitmapFontConfiguration with a FNT file */ - bool initWithFNTfile(const std::string& FNTfile); + bool initWithFNTfile(std::string_view FNTfile); - const std::string& getAtlasName() { return _atlasName; } - void setAtlasName(const std::string& atlasName) { _atlasName = atlasName; } + std::string_view getAtlasName() { return _atlasName; } + void setAtlasName(std::string_view atlasName) { _atlasName = atlasName; } std::set* getCharacterSet() const; protected: - virtual std::set* parseConfigFile(const std::string& controlFile); + virtual std::set* parseConfigFile(std::string_view controlFile); virtual std::set* parseBinaryConfigFile(unsigned char* pData, uint32_t size, - const std::string& controlFile); + std::string_view controlFile); private: unsigned int parseCharacterDefinition(const char* line); void parseInfoArguments(const char* line); void parseCommonArguments(const char* line); - void parseImageFileName(const char* line, const std::string& fntFile); + void parseImageFileName(const char* line, std::string_view fntFile); void parseKerningEntry(const char* line); void purgeKerningDictionary(); void purgeFontDefDictionary(); @@ -145,12 +145,11 @@ class CC_DLL FontFNT : public Font { public: - static FontFNT* create(const std::string& fntFilePath, const Rect& imageRect, bool imageRotated); - static FontFNT* create(const std::string& fntFilePath, const std::string& subTextureKey); - static FontFNT* create(const std::string& fntFilePath); + static FontFNT* create(std::string_view fntFilePath, const Rect& imageRect, bool imageRotated); + static FontFNT* create(std::string_view fntFilePath, std::string_view subTextureKey); + static FontFNT* create(std::string_view fntFilePath); - CC_DEPRECATED_ATTRIBUTE static FontFNT* create(const std::string& fntFilePath, - const Vec2& imageOffset = Vec2::ZERO); + CC_DEPRECATED_ATTRIBUTE static FontFNT* create(std::string_view fntFilePath, const Vec2& imageOffset = Vec2::ZERO); /** Purges the cached data. Removes from memory the cached configurations and the atlas name dictionary. @@ -164,7 +163,7 @@ class CC_DLL FontFNT : public Font int getOriginalFontSize() const; - static void reloadBMFontResource(const std::string& fntFilePath); + static void reloadBMFontResource(std::string_view fntFilePath); protected: FontFNT(BMFontConfiguration* theContfig, const Rect& imageRect, bool imageRotated); diff --git a/cocos/2d/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp index 4a93709cb187..c038926bc7b5 100644 --- a/cocos/2d/CCFontFreeType.cpp +++ b/cocos/2d/CCFontFreeType.cpp @@ -653,7 +653,7 @@ std::string_view FontFreeType::getGlyphCollection() const return glyphCollection; } -void FontFreeType::releaseFont(const std::string& fontName) +void FontFreeType::releaseFont(std::string_view fontName) { auto item = s_cacheFontData.begin(); while (s_cacheFontData.end() != item) diff --git a/cocos/2d/CCFontFreeType.h b/cocos/2d/CCFontFreeType.h index 177571476b04..505812e87caa 100644 --- a/cocos/2d/CCFontFreeType.h +++ b/cocos/2d/CCFontFreeType.h @@ -101,12 +101,12 @@ class CC_DLL FontFreeType : public Font int getFontAscender() const; const char* getFontFamily() const; - const std::string& getFontName() const { return _fontName; } + std::string_view getFontName() const { return _fontName; } virtual FontAtlas* newFontAtlas() override; virtual int getFontMaxHeight() const override { return _lineHeight; } - static void releaseFont(const std::string& fontName); + static void releaseFont(std::string_view fontName); static FT_Library getFTLibrary(); diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index a184fa67d3d3..e7f8a819435b 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -240,8 +240,8 @@ Label* Label::create() return ret; } -Label* Label::createWithSystemFont(const std::string& text, - const std::string& font, +Label* Label::createWithSystemFont(std::string_view text, + std::string_view font, float fontSize, const Vec2& dimensions /* = Vec2::ZERO */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */, @@ -259,8 +259,8 @@ Label* Label::createWithSystemFont(const std::string& text, return ret; } -Label* Label::createWithTTF(const std::string& text, - const std::string& fontFile, +Label* Label::createWithTTF(std::string_view text, + std::string_view fontFile, float fontSize, const Vec2& dimensions /* = Vec2::ZERO */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */, @@ -279,7 +279,7 @@ Label* Label::createWithTTF(const std::string& text, } Label* Label::createWithTTF(const TTFConfig& ttfConfig, - const std::string& text, + std::string_view text, TextHAlignment hAlignment /* = TextHAlignment::CENTER */, int maxLineWidth /* = 0 */) { @@ -295,8 +295,8 @@ Label* Label::createWithTTF(const TTFConfig& ttfConfig, return nullptr; } -Label* Label::createWithBMFont(const std::string& bmfontPath, - const std::string& text, +Label* Label::createWithBMFont(std::string_view bmfontPath, + std::string_view text, const TextHAlignment& hAlignment, int maxLineWidth) { @@ -315,8 +315,8 @@ Label* Label::createWithBMFont(const std::string& bmfontPath, return nullptr; } -Label* Label::createWithBMFont(const std::string& bmfontPath, - const std::string& text, +Label* Label::createWithBMFont(std::string_view bmfontPath, + std::string_view text, const TextHAlignment& hAlignment, int maxLineWidth, const Rect& imageRect, @@ -337,11 +337,11 @@ Label* Label::createWithBMFont(const std::string& bmfontPath, return nullptr; } -Label* Label::createWithBMFont(const std::string& bmfontPath, - const std::string& text, +Label* Label::createWithBMFont(std::string_view bmfontPath, + std::string_view text, const TextHAlignment& hAlignment, int maxLineWidth, - const std::string& subTextureKey) + std::string_view subTextureKey) { auto ret = new Label(hAlignment); @@ -358,8 +358,8 @@ Label* Label::createWithBMFont(const std::string& bmfontPath, return nullptr; } -Label* Label::createWithBMFont(const std::string& bmfontPath, - const std::string& text, +Label* Label::createWithBMFont(std::string_view bmfontPath, + std::string_view text, const TextHAlignment& hAlignment, int maxLineWidth, const Vec2& imageOffset) @@ -368,7 +368,7 @@ Label* Label::createWithBMFont(const std::string& bmfontPath, false); } -Label* Label::createWithCharMap(const std::string& plistFile) +Label* Label::createWithCharMap(std::string_view plistFile) { auto ret = new Label(); @@ -396,7 +396,7 @@ Label* Label::createWithCharMap(Texture2D* texture, int itemWidth, int itemHeigh return nullptr; } -Label* Label::createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) +Label* Label::createWithCharMap(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap) { auto ret = new Label(); @@ -410,7 +410,7 @@ Label* Label::createWithCharMap(const std::string& charMapFile, int itemWidth, i return nullptr; } -bool Label::setCharMap(const std::string& plistFile) +bool Label::setCharMap(std::string_view plistFile) { auto newAtlas = FontAtlasCache::getFontAtlasCharMap(plistFile); @@ -426,8 +426,8 @@ bool Label::setCharMap(const std::string& plistFile) return true; } -bool Label::initWithTTF(const std::string& text, - const std::string& fontFilePath, +bool Label::initWithTTF(std::string_view text, + std::string_view fontFilePath, float fontSize, const Vec2& dimensions, TextHAlignment /*hAlignment*/, @@ -447,7 +447,7 @@ bool Label::initWithTTF(const std::string& text, } bool Label::initWithTTF(const TTFConfig& ttfConfig, - const std::string& text, + std::string_view text, TextHAlignment /*hAlignment*/, int maxLineWidth) { @@ -476,7 +476,7 @@ bool Label::setCharMap(Texture2D* texture, int itemWidth, int itemHeight, int st return true; } -bool Label::setCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) +bool Label::setCharMap(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap) { auto newAtlas = FontAtlasCache::getFontAtlasCharMap(charMapFile, itemWidth, itemHeight, startCharMap); @@ -841,7 +841,7 @@ bool Label::setTTFConfig(const TTFConfig& ttfConfig) return setTTFConfigInternal(ttfConfig); } -bool Label::setBMFontFilePath(const std::string& bmfontFilePath, float fontSize) +bool Label::setBMFontFilePath(std::string_view bmfontFilePath, float fontSize) { FontAtlas* newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath); @@ -875,10 +875,7 @@ bool Label::setBMFontFilePath(const std::string& bmfontFilePath, float fontSize) return true; } -bool Label::setBMFontFilePath(const std::string& bmfontFilePath, - const Rect& imageRect, - bool imageRotated, - float fontSize) +bool Label::setBMFontFilePath(std::string_view bmfontFilePath, const Rect& imageRect, bool imageRotated, float fontSize) { FontAtlas* newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath, imageRect, imageRotated); @@ -914,7 +911,7 @@ bool Label::setBMFontFilePath(const std::string& bmfontFilePath, return true; } -bool Label::setBMFontFilePath(const std::string& bmfontFilePath, const std::string& subTextureKey, float fontSize) +bool Label::setBMFontFilePath(std::string_view bmfontFilePath, std::string_view subTextureKey, float fontSize) { FontAtlas* newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath, subTextureKey); @@ -949,7 +946,7 @@ bool Label::setBMFontFilePath(const std::string& bmfontFilePath, const std::stri return true; } -bool Label::setBMFontFilePath(const std::string& bmfontFilePath, const Vec2& imageOffset, float fontSize) +bool Label::setBMFontFilePath(std::string_view bmfontFilePath, const Vec2& imageOffset, float fontSize) { return setBMFontFilePath(bmfontFilePath, Rect(imageOffset.x, imageOffset.y, 0, 0), false); } @@ -2105,7 +2102,7 @@ void Label::drawSelf(bool visibleByCamera, Renderer* renderer, uint32_t flags) } } -void Label::setSystemFontName(const std::string& systemFont) +void Label::setSystemFontName(std::string_view systemFont) { if (systemFont != _systemFont) { diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index 66d4669cd88c..fa3e5e57e808 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -166,8 +166,8 @@ class CC_DLL Label : public Node, public LabelProtocol, public BlendProtocol * * @return An automatically released Label object. */ - static Label* createWithSystemFont(const std::string& text, - const std::string& font, + static Label* createWithSystemFont(std::string_view text, + std::string_view font, float fontSize, const Vec2& dimensions = Vec2::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT, @@ -185,8 +185,8 @@ class CC_DLL Label : public Node, public LabelProtocol, public BlendProtocol * * @return An automatically released Label object. */ - static Label* createWithTTF(const std::string& text, - const std::string& fontFilePath, + static Label* createWithTTF(std::string_view text, + std::string_view fontFilePath, float fontSize, const Vec2& dimensions = Vec2::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT, @@ -204,7 +204,7 @@ class CC_DLL Label : public Node, public LabelProtocol, public BlendProtocol * @see TTFConfig setTTFConfig setMaxLineWidth */ static Label* createWithTTF(const TTFConfig& ttfConfig, - const std::string& text, + std::string_view text, TextHAlignment hAlignment = TextHAlignment::LEFT, int maxLineWidth = 0); @@ -219,8 +219,8 @@ class CC_DLL Label : public Node, public LabelProtocol, public BlendProtocol * @return An automatically released Label object. * @see setBMFontFilePath setMaxLineWidth */ - static Label* createWithBMFont(const std::string& bmfontPath, - const std::string& text, + static Label* createWithBMFont(std::string_view bmfontPath, + std::string_view text, const TextHAlignment& hAlignment = TextHAlignment::LEFT, int maxLineWidth = 0); @@ -237,8 +237,8 @@ class CC_DLL Label : public Node, public LabelProtocol, public BlendProtocol * @return An automatically released Label object. * @see setBMFontFilePath setMaxLineWidth */ - static Label* createWithBMFont(const std::string& bmfontPath, - const std::string& text, + static Label* createWithBMFont(std::string_view bmfontPath, + std::string_view text, const TextHAlignment& hAlignment, int maxLineWidth, const Rect& imageRect, @@ -256,11 +256,11 @@ class CC_DLL Label : public Node, public LabelProtocol, public BlendProtocol * @return An automatically released Label object. * @see setBMFontFilePath setMaxLineWidth */ - static Label* createWithBMFont(const std::string& bmfontPath, - const std::string& text, + static Label* createWithBMFont(std::string_view bmfontPath, + std::string_view text, const TextHAlignment& hAlignment, int maxLineWidth, - const std::string& subTextureKey); + std::string_view subTextureKey); /** * Allocates and initializes a Label, with a bitmap font file. @@ -274,8 +274,8 @@ class CC_DLL Label : public Node, public LabelProtocol, public BlendProtocol * @return An automatically released Label object. * @see setBMFontFilePath setMaxLineWidth */ - CC_DEPRECATED_ATTRIBUTE static Label* createWithBMFont(const std::string& bmfontPath, - const std::string& text, + CC_DEPRECATED_ATTRIBUTE static Label* createWithBMFont(std::string_view bmfontPath, + std::string_view text, const TextHAlignment& hAlignment, int maxLineWidth, const Vec2& imageOffset); @@ -290,7 +290,7 @@ class CC_DLL Label : public Node, public LabelProtocol, public BlendProtocol * * @return An automatically released Label object. */ - static Label* createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); + static Label* createWithCharMap(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap); /** * Allocates and initializes a Label, with char map configuration. @@ -311,7 +311,7 @@ class CC_DLL Label : public Node, public LabelProtocol, public BlendProtocol * * @return An automatically released Label object. */ - static Label* createWithCharMap(const std::string& plistFile); + static Label* createWithCharMap(std::string_view plistFile); // end of creators group /// @} @@ -332,33 +332,31 @@ class CC_DLL Label : public Node, public LabelProtocol, public BlendProtocol virtual const TTFConfig& getTTFConfig() const { return _fontConfig; } /** Sets a new bitmap font to Label */ - virtual bool setBMFontFilePath(const std::string& bmfontFilePath, float fontSize = 0); + virtual bool setBMFontFilePath(std::string_view bmfontFilePath, float fontSize = 0); /** Sets a new bitmap font to Label */ - virtual bool setBMFontFilePath(const std::string& bmfontFilePath, + virtual bool setBMFontFilePath(std::string_view bmfontFilePath, const Rect& imageRect, bool imageRotated, float fontSize = 0); /** Sets a new bitmap font to Label */ - virtual bool setBMFontFilePath(const std::string& bmfontFilePath, - const std::string& subTextureKey, - float fontSize = 0); + virtual bool setBMFontFilePath(std::string_view bmfontFilePath, std::string_view subTextureKey, float fontSize = 0); /** Sets a new bitmap font to Label */ - CC_DEPRECATED_ATTRIBUTE virtual bool setBMFontFilePath(const std::string& bmfontFilePath, + CC_DEPRECATED_ATTRIBUTE virtual bool setBMFontFilePath(std::string_view bmfontFilePath, const Vec2& imageOffset, float fontSize = 0); /** Returns the bitmap font used by the Label.*/ - const std::string& getBMFontFilePath() const { return _bmFontPath; } + std::string_view getBMFontFilePath() const { return _bmFontPath; } /** * Sets a new char map configuration to Label. * - * @see `createWithCharMap(const std::string&,int,int,int)` + * @see `createWithCharMap(std::string_view,int,int,int)` */ - virtual bool setCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); + virtual bool setCharMap(std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap); /** * Sets a new char map configuration to Label. @@ -370,9 +368,9 @@ class CC_DLL Label : public Node, public LabelProtocol, public BlendProtocol /** * Sets a new char map configuration to Label. * - * @see `createWithCharMap(const std::string&)` + * @see `createWithCharMap(std::string_view)` */ - virtual bool setCharMap(const std::string& plistFile); + virtual bool setCharMap(std::string_view plistFile); /** * Sets a new system font to Label. @@ -380,10 +378,10 @@ class CC_DLL Label : public Node, public LabelProtocol, public BlendProtocol * @param font A font file or a font family name. * @warning */ - virtual void setSystemFontName(const std::string& font); + virtual void setSystemFontName(std::string_view font); /** Returns the system font used by the Label.*/ - virtual const std::string& getSystemFontName() const { return _systemFont; } + virtual std::string_view getSystemFontName() const { return _systemFont; } /* Sets the system font size of Label.*/ virtual void setSystemFontSize(float fontSize); @@ -403,7 +401,7 @@ class CC_DLL Label : public Node, public LabelProtocol, public BlendProtocol virtual void setString(std::string_view text) override; /** Return the text the Label is currently displaying.*/ - virtual const std::string& getString() const override { return _utf8Text; } + virtual std::string_view getString() const override { return _utf8Text; } /** * Return the number of lines of text. @@ -716,15 +714,15 @@ class CC_DLL Label : public Node, public LabelProtocol, public BlendProtocol */ virtual ~Label(); - bool initWithTTF(const std::string& text, - const std::string& fontFilePath, + bool initWithTTF(std::string_view text, + std::string_view fontFilePath, float fontSize, const Vec2& dimensions = Vec2::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT, TextVAlignment vAlignment = TextVAlignment::TOP); bool initWithTTF(const TTFConfig& ttfConfig, - const std::string& text, + std::string_view text, TextHAlignment hAlignment = TextHAlignment::LEFT, int maxLineWidth = 0); diff --git a/cocos/2d/CCLabelAtlas.cpp b/cocos/2d/CCLabelAtlas.cpp index 4b45ff28bdd3..5179b6ff0615 100644 --- a/cocos/2d/CCLabelAtlas.cpp +++ b/cocos/2d/CCLabelAtlas.cpp @@ -40,8 +40,8 @@ NS_CC_BEGIN // CCLabelAtlas - Creation & Init -LabelAtlas* LabelAtlas::create(const std::string& string, - const std::string& charMapFile, +LabelAtlas* LabelAtlas::create(std::string_view string, + std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap) @@ -56,8 +56,8 @@ LabelAtlas* LabelAtlas::create(const std::string& string, return nullptr; } -bool LabelAtlas::initWithString(const std::string& string, - const std::string& charMapFile, +bool LabelAtlas::initWithString(std::string_view string, + std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap) @@ -66,7 +66,7 @@ bool LabelAtlas::initWithString(const std::string& string, return initWithString(string, texture, itemWidth, itemHeight, startCharMap); } -bool LabelAtlas::initWithString(const std::string& string, +bool LabelAtlas::initWithString(std::string_view string, Texture2D* texture, int itemWidth, int itemHeight, @@ -81,7 +81,7 @@ bool LabelAtlas::initWithString(const std::string& string, return false; } -LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& fntFile) +LabelAtlas* LabelAtlas::create(std::string_view string, std::string_view fntFile) { LabelAtlas* ret = new LabelAtlas(); @@ -97,7 +97,7 @@ LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& fnt return ret; } -LabelAtlas* LabelAtlas::create(const std::string& string, +LabelAtlas* LabelAtlas::create(std::string_view string, Texture2D* texture, int itemWidth, int itemHeight, @@ -117,7 +117,7 @@ LabelAtlas* LabelAtlas::create(const std::string& string, return ret; } -bool LabelAtlas::initWithString(const std::string& theString, const std::string& fntFile) +bool LabelAtlas::initWithString(std::string_view theString, std::string_view fntFile) { std::string pathStr = FileUtils::getInstance()->fullPathForFilename(fntFile); std::string relPathStr = pathStr.substr(0, pathStr.find_last_of('/')) + "/"; @@ -128,8 +128,8 @@ bool LabelAtlas::initWithString(const std::string& theString, const std::string& std::string textureFilename = relPathStr + dict["textureFilename"].asString(); - unsigned int width = dict["itemWidth"].asInt() / CC_CONTENT_SCALE_FACTOR(); - unsigned int height = dict["itemHeight"].asInt() / CC_CONTENT_SCALE_FACTOR(); + unsigned int width = static_cast(dict["itemWidth"].asInt() / CC_CONTENT_SCALE_FACTOR()); + unsigned int height = static_cast(dict["itemHeight"].asInt() / CC_CONTENT_SCALE_FACTOR()); unsigned int startChar = dict["firstChar"].asInt(); this->initWithString(theString, textureFilename, width, height, startChar); @@ -156,8 +156,8 @@ void LabelAtlas::updateAtlasValues() float itemHeightInPixels = _itemHeight * CC_CONTENT_SCALE_FACTOR(); if (_ignoreContentScaleFactor) { - itemWidthInPixels = _itemWidth; - itemHeightInPixels = _itemHeight; + itemWidthInPixels = static_cast(_itemWidth); + itemHeightInPixels = static_cast(_itemHeight); } CCASSERT(n <= _textureAtlas->getCapacity(), "updateAtlasValues: Invalid String length"); @@ -239,7 +239,7 @@ void LabelAtlas::setString(std::string_view label) _quadsToDraw = len; } -const std::string& LabelAtlas::getString() const +std::string_view LabelAtlas::getString() const { return _string; } diff --git a/cocos/2d/CCLabelAtlas.h b/cocos/2d/CCLabelAtlas.h index b1f10ca9a94a..1965e75f32ce 100644 --- a/cocos/2d/CCLabelAtlas.h +++ b/cocos/2d/CCLabelAtlas.h @@ -58,8 +58,8 @@ class CC_DLL LabelAtlas : public AtlasNode, public LabelProtocol 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 std::string& string, - const std::string& charMapFile, + static LabelAtlas* create(std::string_view string, + std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap); @@ -68,13 +68,13 @@ class CC_DLL LabelAtlas : public AtlasNode, public LabelProtocol * Creates the LabelAtlas with a string and a configuration file. * @since v2.0 */ - static LabelAtlas* create(const std::string& string, const std::string& fntFile); + static LabelAtlas* create(std::string_view string, std::string_view fntFile); /** * Creates the LabelAtlas with a string, a texture, the width and height of each element and the starting char of * the atlas. */ - static LabelAtlas* create(const std::string& string, + static LabelAtlas* create(std::string_view string, Texture2D* texture, int itemWidth, int itemHeight, @@ -82,8 +82,8 @@ class CC_DLL LabelAtlas : public AtlasNode, public LabelProtocol /** 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 std::string& string, - const std::string& charMapFile, + bool initWithString(std::string_view string, + std::string_view charMapFile, int itemWidth, int itemHeight, int startCharMap); @@ -92,14 +92,14 @@ class CC_DLL LabelAtlas : public AtlasNode, public LabelProtocol * Initializes the LabelAtlas with a string and a configuration file. * @since v2.0 */ - bool initWithString(const std::string& string, const std::string& fntFile); + bool initWithString(std::string_view string, std::string_view fntFile); /** Initializes the LabelAtlas with a string, a texture, the width and height in points of each element and the * starting char of the atlas */ - bool initWithString(const std::string& string, Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); + bool initWithString(std::string_view string, Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); virtual void setString(std::string_view label) override; - virtual const std::string& getString() const override; + virtual std::string_view getString() const override; virtual void updateAtlasValues() override; /** diff --git a/cocos/2d/CCLabelTextFormatter.cpp b/cocos/2d/CCLabelTextFormatter.cpp index a357c06edefa..2a28d7686f70 100644 --- a/cocos/2d/CCLabelTextFormatter.cpp +++ b/cocos/2d/CCLabelTextFormatter.cpp @@ -109,7 +109,7 @@ int Label::getFirstWordLen(const std::u32string& utf32Text, int startIndex, int break; } - nextLetterX += letterDef.xAdvance * _bmfontScale + _additionalKerning; + nextLetterX += static_cast(letterDef.xAdvance * _bmfontScale + _additionalKerning); len++; } @@ -139,9 +139,9 @@ void Label::updateBMFontScale() auto font = _fontAtlas->getFont(); if (_currentLabelType == LabelType::BMFONT) { - FontFNT* bmFont = (FontFNT*)font; - float originalFontSize = bmFont->getOriginalFontSize(); - _bmfontScale = _bmFontSize * CC_CONTENT_SCALE_FACTOR() / originalFontSize; + FontFNT* bmFont = (FontFNT*)font; + auto originalFontSize = bmFont->getOriginalFontSize(); + _bmfontScale = _bmFontSize * CC_CONTENT_SCALE_FACTOR() / originalFontSize; } else { @@ -242,7 +242,7 @@ bool Label::multilineTextWrap(const std::function(_horizontalKernings[letterIndex + 1]); newLetterWidth += letterDef.xAdvance * _bmfontScale + _additionalKerning; nextLetterX += newLetterWidth; diff --git a/cocos/2d/CCMenu.cpp b/cocos/2d/CCMenu.cpp index bbd8808cc6ce..d24e01529155 100644 --- a/cocos/2d/CCMenu.cpp +++ b/cocos/2d/CCMenu.cpp @@ -175,7 +175,7 @@ void Menu::addChild(Node* child, int zOrder, int tag) Layer::addChild(child, zOrder, tag); } -void Menu::addChild(Node* child, int zOrder, const std::string& name) +void Menu::addChild(Node* child, int zOrder, std::string_view name) { CCASSERT(dynamic_cast(child) != nullptr, "Menu only supports MenuItem objects as children"); Layer::addChild(child, zOrder, name); diff --git a/cocos/2d/CCMenu.h b/cocos/2d/CCMenu.h index 560c75c8e506..37d86df33257 100644 --- a/cocos/2d/CCMenu.h +++ b/cocos/2d/CCMenu.h @@ -148,7 +148,7 @@ class CC_DLL Menu : public Layer virtual void addChild(Node* child) override; virtual void addChild(Node* child, int zOrder) override; virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, const std::string& name) override; + virtual void addChild(Node* child, int zOrder, std::string_view name) override; virtual void onEnter() override; virtual void onExit() override; diff --git a/cocos/2d/CCMenuItem.cpp b/cocos/2d/CCMenuItem.cpp index 83927a12d263..fb797cc8646b 100644 --- a/cocos/2d/CCMenuItem.cpp +++ b/cocos/2d/CCMenuItem.cpp @@ -180,13 +180,13 @@ bool MenuItemLabel::initWithLabel(Node* label, const ccMenuCallback& callback) MenuItemLabel::~MenuItemLabel() {} -void MenuItemLabel::setString(const std::string& label) +void MenuItemLabel::setString(std::string_view label) { dynamic_cast(_label)->setString(label); this->setContentSize(_label->getContentSize()); } -std::string MenuItemLabel::getString() const +std::string_view MenuItemLabel::getString() const { auto label = dynamic_cast(_label); return label->getString(); @@ -259,8 +259,8 @@ void MenuItemLabel::setEnabled(bool enabled) // CCMenuItemAtlasFont // -MenuItemAtlasFont* MenuItemAtlasFont::create(const std::string& value, - const std::string& charMapFile, +MenuItemAtlasFont* MenuItemAtlasFont::create(std::string_view value, + std::string_view charMapFile, int itemWidth, int itemHeight, char startCharMap) @@ -269,8 +269,8 @@ MenuItemAtlasFont* MenuItemAtlasFont::create(const std::string& value, (const ccMenuCallback&)nullptr); } -MenuItemAtlasFont* MenuItemAtlasFont::create(const std::string& value, - const std::string& charMapFile, +MenuItemAtlasFont* MenuItemAtlasFont::create(std::string_view value, + std::string_view charMapFile, int itemWidth, int itemHeight, char startCharMap, @@ -282,8 +282,8 @@ MenuItemAtlasFont* MenuItemAtlasFont::create(const std::string& value, return ret; } -bool MenuItemAtlasFont::initWithString(const std::string& value, - const std::string& charMapFile, +bool MenuItemAtlasFont::initWithString(std::string_view value, + std::string_view charMapFile, int itemWidth, int itemHeight, char startCharMap, @@ -312,7 +312,7 @@ int MenuItemFont::getFontSize() return _globalFontSize; } -void MenuItemFont::setFontName(const std::string& name) +void MenuItemFont::setFontName(std::string_view name) { if (_globalFontNameRelease) { @@ -322,12 +322,12 @@ void MenuItemFont::setFontName(const std::string& name) _globalFontNameRelease = true; } -const std::string& MenuItemFont::getFontName() +std::string_view MenuItemFont::getFontName() { return _globalFontName; } -MenuItemFont* MenuItemFont::create(const std::string& value, const ccMenuCallback& callback) +MenuItemFont* MenuItemFont::create(std::string_view value, const ccMenuCallback& callback) { MenuItemFont* ret = new MenuItemFont(); ret->initWithString(value, callback); @@ -335,7 +335,7 @@ MenuItemFont* MenuItemFont::create(const std::string& value, const ccMenuCallbac return ret; } -MenuItemFont* MenuItemFont::create(const std::string& value) +MenuItemFont* MenuItemFont::create(std::string_view value) { MenuItemFont* ret = new MenuItemFont(); ret->initWithString(value, (const ccMenuCallback&)nullptr); @@ -350,7 +350,7 @@ MenuItemFont::~MenuItemFont() CCLOGINFO("In the destructor of MenuItemFont (%p).", this); } -bool MenuItemFont::initWithString(const std::string& value, const ccMenuCallback& callback) +bool MenuItemFont::initWithString(std::string_view value, const ccMenuCallback& callback) { CCASSERT(!value.empty(), "Value length must be greater than 0"); @@ -377,14 +377,14 @@ int MenuItemFont::getFontSizeObj() const return _fontSize; } -void MenuItemFont::setFontNameObj(const std::string& name) +void MenuItemFont::setFontNameObj(std::string_view name) { _fontName = name; dynamic_cast(_label)->setSystemFontName(_fontName); this->setContentSize(dynamic_cast(_label)->getContentSize()); } -const std::string& MenuItemFont::getFontNameObj() const +std::string_view MenuItemFont::getFontNameObj() const { return _fontName; } @@ -600,21 +600,21 @@ bool MenuItemImage::init() return initWithNormalImage("", "", "", (const ccMenuCallback&)nullptr); } -MenuItemImage* MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage) +MenuItemImage* MenuItemImage::create(std::string_view normalImage, std::string_view selectedImage) { return MenuItemImage::create(normalImage, selectedImage, "", (const ccMenuCallback&)nullptr); } -MenuItemImage* MenuItemImage::create(const std::string& normalImage, - const std::string& selectedImage, +MenuItemImage* MenuItemImage::create(std::string_view normalImage, + std::string_view selectedImage, const ccMenuCallback& callback) { return MenuItemImage::create(normalImage, selectedImage, "", callback); } -MenuItemImage* MenuItemImage::create(const std::string& normalImage, - const std::string& selectedImage, - const std::string& disabledImage, +MenuItemImage* MenuItemImage::create(std::string_view normalImage, + std::string_view selectedImage, + std::string_view disabledImage, const ccMenuCallback& callback) { MenuItemImage* ret = new MenuItemImage(); @@ -627,9 +627,9 @@ MenuItemImage* MenuItemImage::create(const std::string& normalImage, return nullptr; } -MenuItemImage* MenuItemImage::create(const std::string& normalImage, - const std::string& selectedImage, - const std::string& disabledImage) +MenuItemImage* MenuItemImage::create(std::string_view normalImage, + std::string_view selectedImage, + std::string_view disabledImage) { MenuItemImage* ret = new MenuItemImage(); if (ret->initWithNormalImage(normalImage, selectedImage, disabledImage, (const ccMenuCallback&)nullptr)) @@ -641,9 +641,9 @@ MenuItemImage* MenuItemImage::create(const std::string& normalImage, return nullptr; } -bool MenuItemImage::initWithNormalImage(const std::string& normalImage, - const std::string& selectedImage, - const std::string& disabledImage, +bool MenuItemImage::initWithNormalImage(std::string_view normalImage, + std::string_view selectedImage, + std::string_view disabledImage, const ccMenuCallback& callback) { Node* normalSprite = nullptr; diff --git a/cocos/2d/CCMenuItem.h b/cocos/2d/CCMenuItem.h index a36b65aaf6ba..20639746c90b 100644 --- a/cocos/2d/CCMenuItem.h +++ b/cocos/2d/CCMenuItem.h @@ -137,10 +137,10 @@ class CC_DLL MenuItemLabel : public MenuItem static MenuItemLabel* create(Node* label); /** Sets a new string to the inner label. */ - void setString(const std::string& label); + void setString(std::string_view label); /** Get the inner string of the inner label. */ - std::string getString() const; + std::string_view getString() const; /** Gets the color that will be used when the item is disabled. */ const Color3B& getDisabledColor() const { return _disabledColor; } @@ -196,14 +196,14 @@ class CC_DLL MenuItemAtlasFont : public MenuItemLabel { public: /** Creates a menu item from a string and atlas with a target/selector. */ - static MenuItemAtlasFont* create(const std::string& value, - const std::string& charMapFile, + static MenuItemAtlasFont* create(std::string_view value, + std::string_view charMapFile, int itemWidth, int itemHeight, char startCharMap); /** Creates a menu item from a string and atlas. Use it with MenuItemToggle. */ - static MenuItemAtlasFont* create(const std::string& value, - const std::string& charMapFile, + static MenuItemAtlasFont* create(std::string_view value, + std::string_view charMapFile, int itemWidth, int itemHeight, char startCharMap, @@ -222,8 +222,8 @@ class CC_DLL MenuItemAtlasFont : public MenuItemLabel virtual ~MenuItemAtlasFont() {} /** Initializes a menu item from a string and atlas with a target/selector. */ - bool initWithString(const std::string& value, - const std::string& charMapFile, + bool initWithString(std::string_view value, + std::string_view charMapFile, int itemWidth, int itemHeight, char startCharMap, @@ -240,18 +240,18 @@ 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 std::string& value = ""); + static MenuItemFont* create(std::string_view value = ""); /** Creates a menu item from a string with a target/selector. */ - static MenuItemFont* create(const std::string& value, const ccMenuCallback& callback); + static MenuItemFont* create(std::string_view value, const ccMenuCallback& callback); /** Set default font size. */ static void setFontSize(int size); /** Get default font size. */ static int getFontSize(); /** Set the default font name. */ - static void setFontName(const std::string& name); + static void setFontName(std::string_view name); /** Get the default font name. */ - static const std::string& getFontName(); + static std::string_view getFontName(); /** Set font size. * c++ can not overload static and non-static member functions with the same parameter types. @@ -274,13 +274,13 @@ class CC_DLL MenuItemFont : public MenuItemLabel * @js setFontName * @js NA */ - void setFontNameObj(const std::string& name); + void setFontNameObj(std::string_view name); /** Returns the name of the Font. * @js getFontNameObj * @js NA */ - const std::string& getFontNameObj() const; + std::string_view getFontNameObj() const; CC_CONSTRUCTOR_ACCESS : /** @@ -294,7 +294,7 @@ class CC_DLL MenuItemFont : public MenuItemLabel virtual ~MenuItemFont(); /** Initializes a menu item from a string with a target/selector. */ - bool initWithString(const std::string& value, const ccMenuCallback& callback); + bool initWithString(std::string_view value, const ccMenuCallback& callback); protected: int _fontSize; @@ -392,19 +392,19 @@ class CC_DLL MenuItemImage : public MenuItemSprite /** Creates an MenuItemImage. */ static MenuItemImage* create(); /** Creates a menu item with a normal and selected image.*/ - static MenuItemImage* create(const std::string& normalImage, const std::string& selectedImage); + static MenuItemImage* create(std::string_view normalImage, std::string_view selectedImage); /** Creates a menu item with a normal,selected and disabled image.*/ - static MenuItemImage* create(const std::string& normalImage, - const std::string& selectedImage, - const std::string& disabledImage); + static MenuItemImage* create(std::string_view normalImage, + std::string_view selectedImage, + std::string_view disabledImage); /** Creates a menu item with a normal and selected image with a callable object. */ - static MenuItemImage* create(const std::string& normalImage, - const std::string& selectedImage, + static MenuItemImage* create(std::string_view normalImage, + std::string_view selectedImage, const ccMenuCallback& callback); /** Creates a menu item with a normal,selected and disabled image with a callable object. */ - static MenuItemImage* create(const std::string& normalImage, - const std::string& selectedImage, - const std::string& disabledImage, + static MenuItemImage* create(std::string_view normalImage, + std::string_view selectedImage, + std::string_view disabledImage, const ccMenuCallback& callback); /** Sets the sprite frame for the normal image. */ @@ -429,9 +429,9 @@ class CC_DLL MenuItemImage : public MenuItemSprite bool init(); /** Initializes a menu item with a normal, selected and disabled image with a callable object. */ - bool initWithNormalImage(const std::string& normalImage, - const std::string& selectedImage, - const std::string& disabledImage, + bool initWithNormalImage(std::string_view normalImage, + std::string_view selectedImage, + std::string_view disabledImage, const ccMenuCallback& callback); private: diff --git a/cocos/2d/CCMotionStreak.cpp b/cocos/2d/CCMotionStreak.cpp index d92839e9541e..1535875ef675 100644 --- a/cocos/2d/CCMotionStreak.cpp +++ b/cocos/2d/CCMotionStreak.cpp @@ -52,11 +52,7 @@ MotionStreak::~MotionStreak() CC_SAFE_FREE(_texCoords); } -MotionStreak* MotionStreak::create(float fade, - float minSeg, - float stroke, - const Color3B& color, - const std::string& path) +MotionStreak* MotionStreak::create(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path) { MotionStreak* ret = new MotionStreak(); if (ret->initWithFade(fade, minSeg, stroke, color, path)) @@ -82,7 +78,7 @@ MotionStreak* MotionStreak::create(float fade, float minSeg, float stroke, const return nullptr; } -bool MotionStreak::initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path) +bool MotionStreak::initWithFade(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path) { CCASSERT(!path.empty(), "Invalid filename"); diff --git a/cocos/2d/CCMotionStreak.h b/cocos/2d/CCMotionStreak.h index 07ab945dd5f5..7ce1ca2c742a 100644 --- a/cocos/2d/CCMotionStreak.h +++ b/cocos/2d/CCMotionStreak.h @@ -59,7 +59,7 @@ class CC_DLL MotionStreak : public Node, public TextureProtocol float minSeg, float strokeWidth, const Color3B& strokeColor, - const std::string& imagePath); + std::string_view imagePath); /** Creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture. * * @param timeToFade The fade time, in seconds. @@ -163,7 +163,7 @@ class CC_DLL MotionStreak : public Node, public TextureProtocol /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture filename */ - bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path); + bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path); /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture */ bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture); diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index aa068ac8fd78..49fa7a83f106 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -56,7 +56,7 @@ THE SOFTWARE. /* * 4.5x faster than std::hash in release mode */ -#define CC_HASH_NODE_NAME(name) (!name.empty() ? XXH3_64bits(name.c_str(), name.length()) : 0) +#define CC_HASH_NODE_NAME(name) (!name.empty() ? XXH3_64bits(name.data(), name.length()) : 0) NS_CC_BEGIN @@ -695,12 +695,12 @@ void Node::setTag(int tag) _tag = tag; } -const std::string& Node::getName() const +std::string_view Node::getName() const { return _name; } -void Node::setName(const std::string& name) +void Node::setName(std::string_view name) { updateParentChildrenIndexer(name); _name = name; @@ -717,7 +717,7 @@ void Node::updateParentChildrenIndexer(int tag) } } -void Node::updateParentChildrenIndexer(const std::string& name) +void Node::updateParentChildrenIndexer(std::string_view name) { uint64_t newHash = CC_HASH_NODE_NAME(name); auto parentChildrenIndexer = getParentChildrenIndexer(); @@ -817,7 +817,7 @@ Node* Node::getChildByTag(int tag) const return nullptr; } -Node* Node::getChildByName(const std::string& name) const +Node* Node::getChildByName(std::string_view name) const { // CCASSERT(!name.empty(), "Invalid name"); auto hash = CC_HASH_NODE_NAME(name); @@ -837,7 +837,7 @@ Node* Node::getChildByName(const std::string& name) const return nullptr; } -void Node::enumerateChildren(const std::string& name, std::function callback) const +void Node::enumerateChildren(std::string_view name, std::function callback) const { CCASSERT(!name.empty(), "Invalid name"); CCASSERT(callback != nullptr, "Invalid callback function"); @@ -865,7 +865,7 @@ void Node::enumerateChildren(const std::string& name, std::function } // Remove '//', '/..' if exist - std::string newName = name.substr(subStrStartPos, subStrlength); + auto newName = name.substr(subStrStartPos, subStrlength); const Node* target = this; @@ -886,15 +886,15 @@ void Node::enumerateChildren(const std::string& name, std::function else { // name is xxx - target->doEnumerate(newName, callback); + target->doEnumerate(std::string{newName}, callback); } } -bool Node::doEnumerateRecursive(const Node* node, const std::string& name, std::function callback) const +bool Node::doEnumerateRecursive(const Node* node, std::string_view name, std::function callback) const { bool ret = false; - if (node->doEnumerate(name, callback)) + if (node->doEnumerate(std::string{name}, callback)) { // search itself ret = true; @@ -966,7 +966,7 @@ void Node::addChild(Node* child, int localZOrder, int tag) addChildHelper(child, localZOrder, tag, "", true); } -void Node::addChild(Node* child, int localZOrder, const std::string& name) +void Node::addChild(Node* child, int localZOrder, std::string_view name) { CCASSERT(child != nullptr, "Argument must be non-nil"); CCASSERT(child->_parent == nullptr, "child already added. It can't be added again"); @@ -974,7 +974,7 @@ void Node::addChild(Node* child, int localZOrder, const std::string& name) addChildHelper(child, localZOrder, INVALID_TAG, name, false); } -void Node::addChildHelper(Node* child, int localZOrder, int tag, const std::string& name, bool setTag) +void Node::addChildHelper(Node* child, int localZOrder, int tag, std::string_view name, bool setTag) { auto assertNotSelfChild([this, child]() -> bool { for (Node* parent(getParent()); parent != nullptr; parent = parent->getParent()) @@ -1088,7 +1088,7 @@ void Node::removeChildByTag(int tag, bool cleanup /* = true */) } } -void Node::removeChildByName(const std::string& name, bool cleanup) +void Node::removeChildByName(std::string_view name, bool cleanup) { CCASSERT(!name.empty(), "Invalid name"); @@ -1096,7 +1096,7 @@ void Node::removeChildByName(const std::string& name, bool cleanup) if (child == nullptr) { - CCLOG("cocos2d: removeChildByName(name = %s): child not found!", name.c_str()); + CCLOG("cocos2d: removeChildByName(name = %s): child not found!", name.data()); } else { @@ -1490,7 +1490,7 @@ bool Node::isScheduled(SEL_SCHEDULE selector) const return _scheduler->isScheduled(selector, this); } -bool Node::isScheduled(const std::string& key) const +bool Node::isScheduled(std::string_view key) const { return _scheduler->isScheduled(key, this); } @@ -1547,12 +1547,12 @@ void Node::schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, _scheduler->schedule(selector, this, interval, repeat, delay, !_running); } -void Node::schedule(const std::function& callback, const std::string& key) +void Node::schedule(const std::function& callback, std::string_view key) { _scheduler->schedule(callback, this, 0, !_running, key); } -void Node::schedule(const std::function& callback, float interval, const std::string& key) +void Node::schedule(const std::function& callback, float interval, std::string_view key) { _scheduler->schedule(callback, this, interval, !_running, key); } @@ -1561,7 +1561,7 @@ void Node::schedule(const std::function& callback, float interval, unsigned int repeat, float delay, - const std::string& key) + std::string_view key) { _scheduler->schedule(callback, this, interval, repeat, delay, !_running, key); } @@ -1571,7 +1571,7 @@ void Node::scheduleOnce(SEL_SCHEDULE selector, float delay) this->schedule(selector, 0.0f, 0, delay); } -void Node::scheduleOnce(const std::function& callback, float delay, const std::string& key) +void Node::scheduleOnce(const std::function& callback, float delay, std::string_view key) { _scheduler->schedule(callback, this, 0, 0, delay, !_running, key); } @@ -1585,7 +1585,7 @@ void Node::unschedule(SEL_SCHEDULE selector) _scheduler->unschedule(selector, this); } -void Node::unschedule(const std::string& key) +void Node::unschedule(std::string_view key) { _scheduler->unschedule(key, this); } @@ -1923,7 +1923,7 @@ void Node::updateTransform() // MARK: components -Component* Node::getComponent(const std::string& name) +Component* Node::getComponent(std::string_view name) { if (_componentContainer) return _componentContainer->get(name); @@ -1943,7 +1943,7 @@ bool Node::addComponent(Component* component) return _componentContainer->add(component); } -bool Node::removeComponent(const std::string& name) +bool Node::removeComponent(std::string_view name) { if (_componentContainer) return _componentContainer->remove(name); diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index 01bd103303fc..9ebc5b5f6718 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -762,7 +762,7 @@ class CC_DLL Node : public Ref * @param name A string to identify the node easily. Please refer to `setName(int)`. * */ - virtual void addChild(Node* child, int localZOrder, const std::string& name); + virtual void addChild(Node* child, int localZOrder, std::string_view name); /** * Gets a child from the container with its tag. * @@ -796,7 +796,7 @@ class CC_DLL Node : public Ref * * @since v3.2 */ - virtual Node* getChildByName(const std::string& name) const; + virtual Node* getChildByName(std::string_view name) const; /** * Gets a child from the container with its name that can be cast to Type T. * @@ -805,7 +805,7 @@ class CC_DLL Node : public Ref * @return a Node with the given name that can be cast to Type T. */ template - T getChildByName(const std::string& name) const + T getChildByName(std::string_view name) const { return static_cast(getChildByName(name)); } @@ -835,7 +835,7 @@ class CC_DLL Node : public Ref * * @since v3.2 */ - virtual void enumerateChildren(const std::string& name, std::function callback) const; + virtual void enumerateChildren(std::string_view name, std::function callback) const; /** * Returns the array of the node's children. * @@ -909,7 +909,7 @@ class CC_DLL Node : public Ref * @param name A string that identifies a child node. * @param cleanup True if all running actions and callbacks on the child node will be cleanup, false otherwise. */ - virtual void removeChildByName(const std::string& name, bool cleanup = true); + virtual void removeChildByName(std::string_view name, bool cleanup = true); /** * Removes all children from the container with a cleanup. * @@ -989,13 +989,13 @@ class CC_DLL Node : public Ref * * @since v3.2 */ - virtual const std::string& getName() const; + virtual std::string_view getName() const; /** Changes the name that is used to identify the node easily. * @param name A string that identifies the node. * * @since v3.2 */ - virtual void setName(const std::string& name); + virtual void setName(std::string_view name); /** * Returns a custom user data pointer. @@ -1306,7 +1306,7 @@ class CC_DLL Node : public Ref * @js NA * @lua NA */ - bool isScheduled(const std::string& key) const; + bool isScheduled(std::string_view key) const; /** * Schedules the "update" method. @@ -1385,7 +1385,7 @@ class CC_DLL Node : public Ref * @param key The key of the lambda function. To be used if you want to unschedule it. * @lua NA */ - void scheduleOnce(const std::function& callback, float delay, const std::string& key); + void scheduleOnce(const std::function& callback, float delay, std::string_view key); /** * Schedules a custom selector, the scheduled selector will be ticked every frame. @@ -1403,7 +1403,7 @@ class CC_DLL Node : public Ref * @param key The key of the lambda function. To be used if you want to unschedule it. * @lua NA */ - void schedule(const std::function& callback, const std::string& key); + void schedule(const std::function& callback, std::string_view key); /** * Schedules a lambda function. The scheduled lambda function will be called every "interval" seconds @@ -1413,7 +1413,7 @@ class CC_DLL Node : public Ref * @param key The key of the lambda function. To be used if you want to unschedule it * @lua NA */ - void schedule(const std::function& callback, float interval, const std::string& key); + void schedule(const std::function& callback, float interval, std::string_view key); /** * Schedules a lambda function. @@ -1430,7 +1430,7 @@ class CC_DLL Node : public Ref float interval, unsigned int repeat, float delay, - const std::string& key); + std::string_view key); /** * Unschedules a custom selector. @@ -1447,7 +1447,7 @@ class CC_DLL Node : public Ref * @param key The key of the lambda function to be unscheduled. * @lua NA */ - void unschedule(const std::string& key); + void unschedule(std::string_view key); /** * Unschedule all scheduled selectors and lambda functions: custom selectors, and the 'update' selector and lambda @@ -1633,7 +1633,7 @@ class CC_DLL Node : public Ref * @param name A given name of component. * @return The Component by name. */ - Component* getComponent(const std::string& name); + Component* getComponent(std::string_view name); /** * Adds a component. @@ -1649,7 +1649,7 @@ class CC_DLL Node : public Ref * @param name A given name of component. * @return True if removed success. */ - virtual bool removeComponent(const std::string& name); + virtual bool removeComponent(std::string_view name); /** * Removes a component by its pointer. @@ -1854,7 +1854,7 @@ class CC_DLL Node : public Ref virtual void updateColor() {} bool doEnumerate(std::string name, std::function callback) const; - bool doEnumerateRecursive(const Node* node, const std::string& name, std::function callback) const; + bool doEnumerateRecursive(const Node* node, std::string_view name, std::function callback) const; // check whether this camera mask is visible by the current visiting camera bool isVisitableByVisitingCamera() const; @@ -1865,10 +1865,10 @@ class CC_DLL Node : public Ref void updateRotation3D(); void updateParentChildrenIndexer(int tag); - void updateParentChildrenIndexer(const std::string& name); + void updateParentChildrenIndexer(std::string_view name); private: - void addChildHelper(Node* child, int localZOrder, int tag, const std::string& name, bool setTag); + void addChildHelper(Node* child, int localZOrder, int tag, std::string_view name, bool setTag); NodeIndexerMap_t* getParentChildrenIndexer(); diff --git a/cocos/2d/CCParallaxNode.cpp b/cocos/2d/CCParallaxNode.cpp index 7282e416a453..a2c04f4ec229 100644 --- a/cocos/2d/CCParallaxNode.cpp +++ b/cocos/2d/CCParallaxNode.cpp @@ -91,7 +91,7 @@ void ParallaxNode::addChild(Node* /*child*/, int /*zOrder*/, int /*tag*/) CCASSERT(0, "ParallaxNode: use addChild:z:parallaxRatio:positionOffset instead"); } -void ParallaxNode::addChild(Node* /*child*/, int /*zOrder*/, const std::string& /*name*/) +void ParallaxNode::addChild(Node* /*child*/, int /*zOrder*/, std::string_view /*name*/) { CCASSERT(0, "ParallaxNode: use addChild:z:parallaxRatio:positionOffset instead"); } diff --git a/cocos/2d/CCParallaxNode.h b/cocos/2d/CCParallaxNode.h index 577069ec82be..409717a0e989 100644 --- a/cocos/2d/CCParallaxNode.h +++ b/cocos/2d/CCParallaxNode.h @@ -83,7 +83,7 @@ class CC_DLL ParallaxNode : public Node // Overrides // virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, const std::string& name) override; + virtual void addChild(Node* child, int zOrder, std::string_view name) override; virtual void removeChild(Node* child, bool cleanup) override; virtual void removeAllChildrenWithCleanup(bool cleanup) override; virtual void visit(Renderer* renderer, const Mat4& parentTransform, uint32_t parentFlags) override; diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index e91e27c5f6b7..e9f8edabb191 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -108,7 +108,7 @@ ParticleBatchNode* ParticleBatchNode::createWithTexture(Texture2D* tex, int capa * creation with File Image */ -ParticleBatchNode* ParticleBatchNode::create(const std::string& imageFile, int capacity /* = kParticleDefaultCapacity*/) +ParticleBatchNode* ParticleBatchNode::create(std::string_view imageFile, int capacity /* = kParticleDefaultCapacity*/) { ParticleBatchNode* p = new ParticleBatchNode(); if (p->initWithFile(imageFile, capacity)) @@ -140,7 +140,7 @@ bool ParticleBatchNode::initWithTexture(Texture2D* tex, int capacity) /* * init with FileImage */ -bool ParticleBatchNode::initWithFile(const std::string& fileImage, int capacity) +bool ParticleBatchNode::initWithFile(std::string_view fileImage, int capacity) { Texture2D* tex = _director->getTextureCache()->addImage(fileImage); return initWithTexture(tex, capacity); @@ -193,7 +193,7 @@ void ParticleBatchNode::addChild(Node* aChild, int zOrder, int tag) addChildByTagOrName(child, zOrder, tag, "", true); } -void ParticleBatchNode::addChild(Node* aChild, int zOrder, const std::string& name) +void ParticleBatchNode::addChild(Node* aChild, int zOrder, std::string_view name) { CCASSERT(aChild != nullptr, "Argument must be non-nullptr"); CCASSERT(dynamic_cast(aChild) != nullptr, @@ -208,7 +208,7 @@ void ParticleBatchNode::addChild(Node* aChild, int zOrder, const std::string& na void ParticleBatchNode::addChildByTagOrName(ParticleSystem* child, int zOrder, int tag, - const std::string& name, + std::string_view name, bool setTag) { // If this is the 1st children, then copy blending function @@ -251,7 +251,7 @@ void ParticleBatchNode::addChildByTagOrName(ParticleSystem* child, // faster // FIXME: or possibly using vertexZ for reordering, that would be fastest // this helper is almost equivalent to Node's addChild, but doesn't make use of the lazy sorting -int ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag, const std::string& name, bool setTag) +int ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag, std::string_view name, bool setTag) { CCASSERT(child != nullptr, "Argument must be non-nil"); CCASSERT(child->getParent() == nullptr, "child already added. It can't be added again"); diff --git a/cocos/2d/CCParticleBatchNode.h b/cocos/2d/CCParticleBatchNode.h index 442416209d80..6ad5991e53dd 100644 --- a/cocos/2d/CCParticleBatchNode.h +++ b/cocos/2d/CCParticleBatchNode.h @@ -87,7 +87,7 @@ class CC_DLL ParticleBatchNode : public Node, public TextureProtocol * @param capacity A capacity of particles. * @return An autoreleased ParticleBatchNode object. */ - static ParticleBatchNode* create(const std::string& fileImage, int capacity = kParticleDefaultCapacity); + static ParticleBatchNode* create(std::string_view fileImage, int capacity = kParticleDefaultCapacity); /** Inserts a child into the ParticleBatchNode. * @@ -127,7 +127,7 @@ class CC_DLL ParticleBatchNode : public Node, public TextureProtocol using Node::addChild; virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, const std::string& name) override; + virtual void addChild(Node* child, int zOrder, std::string_view name) override; virtual void removeChild(Node* child, bool cleanup) override; virtual void reorderChild(Node* child, int zOrder) override; virtual void draw(Renderer* renderer, const Mat4& transform, uint32_t flags) override; @@ -163,15 +163,15 @@ class CC_DLL ParticleBatchNode : public Node, public TextureProtocol /** initializes the particle system with the name of a file on disk (for a list of supported formats look at the * Texture2D class), a capacity of particles */ - bool initWithFile(const std::string& fileImage, int capacity); + bool initWithFile(std::string_view fileImage, int capacity); private: void updateAllAtlasIndexes(); void increaseAtlasCapacityTo(ssize_t quantity); int searchNewPositionInChildrenForZ(int z); void getCurrentIndex(int* oldIndex, int* newIndex, Node* child, int z); - int addChildHelper(ParticleSystem* child, int z, int aTag, const std::string& name, bool setTag); - void addChildByTagOrName(ParticleSystem* child, int z, int tag, const std::string& name, bool setTag); + int addChildHelper(ParticleSystem* child, int z, int aTag, std::string_view name, bool setTag); + void addChildByTagOrName(ParticleSystem* child, int z, int tag, std::string_view name, bool setTag); void updateBlendFunc(); void updateProgramStateTexture(); diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index 8a40ac94f177..b2820844ed07 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -191,11 +191,6 @@ void ParticleData::release() Vector ParticleSystem::__allInstances; float ParticleSystem::__totalParticleCountFactor = 1.0f; -inline static const cocos2d::Value& optValue(const ValueMap& dictionary, const std::string& key) -{ - return dictionary.find(key) != dictionary.cend() ? dictionary.at(key) : cocos2d::Value::Null; -} - ParticleSystem::ParticleSystem() : _isBlendAdditive(false) , _isAutoRemoveOnFinish(false) @@ -250,7 +245,7 @@ ParticleSystem::ParticleSystem() } // implementation ParticleSystem -ParticleSystem* ParticleSystem::create(const std::string& plistFile) +ParticleSystem* ParticleSystem::create(std::string_view plistFile) { ParticleSystem* ret = new ParticleSystem(); if (ret->initWithFile(plistFile)) @@ -290,7 +285,7 @@ bool ParticleSystem::init() return initWithTotalParticles(150); } -bool ParticleSystem::initWithFile(const std::string& plistFile) +bool ParticleSystem::initWithFile(std::string_view plistFile) { bool ret = false; _plistFile = FileUtils::getInstance()->fullPathForFilename(plistFile); @@ -299,7 +294,7 @@ bool ParticleSystem::initWithFile(const std::string& plistFile) CCASSERT(!dict.empty(), "Particles: file not found"); // FIXME: compute path from a path, should define a function somewhere to do it - string listFilePath = plistFile; + auto listFilePath = plistFile; if (listFilePath.find('/') != string::npos) { listFilePath = listFilePath.substr(0, listFilePath.rfind('/') + 1); @@ -318,7 +313,7 @@ bool ParticleSystem::initWithDictionary(const ValueMap& dictionary) return initWithDictionary(dictionary, ""); } -bool ParticleSystem::initWithDictionary(const ValueMap& dictionary, const std::string& dirname) +bool ParticleSystem::initWithDictionary(const ValueMap& dictionary, std::string_view dirname) { bool ret = false; unsigned char* buffer = nullptr; @@ -487,12 +482,12 @@ bool ParticleSystem::initWithDictionary(const ValueMap& dictionary, const std::s if (!dirname.empty() && textureDir != dirname) { textureName = textureName.substr(rPos + 1); - textureName = dirname + textureName; + textureName.insert(0, dirname); // textureName = dirname + textureName; } } else if (!dirname.empty() && !textureName.empty()) { - textureName = dirname + textureName; + textureName.insert(0, dirname); // textureName = dirname + textureName; } Texture2D* tex = nullptr; diff --git a/cocos/2d/CCParticleSystem.h b/cocos/2d/CCParticleSystem.h index 558cf8711192..6e9dcff08c7d 100644 --- a/cocos/2d/CCParticleSystem.h +++ b/cocos/2d/CCParticleSystem.h @@ -237,7 +237,7 @@ class CC_DLL ParticleSystem : public Node, public TextureProtocol, public Playab * @param plistFile Particle plist file name. * @return An autoreleased ParticleSystem object. */ - static ParticleSystem* create(const std::string& plistFile); + static ParticleSystem* create(std::string_view plistFile); /** Create a system with a fixed number of particles. * @@ -761,7 +761,7 @@ class CC_DLL ParticleSystem : public Node, public TextureProtocol, public Playab */ virtual const BlendFunc& getBlendFunc() const override; - const std::string& getResourceFile() const { return _plistFile; } + std::string_view getResourceFile() const { return _plistFile; } /// @{ /// @name implement Playable Protocol @@ -793,7 +793,7 @@ class CC_DLL ParticleSystem : public Node, public TextureProtocol, public Playab http://particledesigner.71squared.com/ @since v0.99.3 */ - bool initWithFile(const std::string& plistFile); + bool initWithFile(std::string_view plistFile); /** initializes a QuadParticleSystem from a Dictionary. @since v0.99.3 @@ -803,7 +803,7 @@ class CC_DLL ParticleSystem : public Node, public TextureProtocol, public Playab /** initializes a particle system from a NSDictionary and the path from where to load the png @since v2.1 */ - bool initWithDictionary(const ValueMap& dictionary, const std::string& dirname); + bool initWithDictionary(const ValueMap& dictionary, std::string_view dirname); //! Initializes a system with a fixed number of particles virtual bool initWithTotalParticles(int numberOfParticles); diff --git a/cocos/2d/CCParticleSystemQuad.cpp b/cocos/2d/CCParticleSystemQuad.cpp index 17e1b7de46ee..0c87d08083eb 100644 --- a/cocos/2d/CCParticleSystemQuad.cpp +++ b/cocos/2d/CCParticleSystemQuad.cpp @@ -91,7 +91,7 @@ ParticleSystemQuad::~ParticleSystemQuad() // implementation ParticleSystemQuad -ParticleSystemQuad* ParticleSystemQuad::create(const std::string& filename) +ParticleSystemQuad* ParticleSystemQuad::create(std::string_view filename) { ParticleSystemQuad* ret = new ParticleSystemQuad(); if (ret->initWithFile(filename)) diff --git a/cocos/2d/CCParticleSystemQuad.h b/cocos/2d/CCParticleSystemQuad.h index 5ab121035261..65229bd27f69 100644 --- a/cocos/2d/CCParticleSystemQuad.h +++ b/cocos/2d/CCParticleSystemQuad.h @@ -75,7 +75,7 @@ class CC_DLL ParticleSystemQuad : public ParticleSystem * @param filename Particle plist file name. * @return An autoreleased ParticleSystemQuad object. */ - static ParticleSystemQuad* create(const std::string& filename); + static ParticleSystemQuad* create(std::string_view filename); /** Creates a Particle Emitter with a dictionary. * * @param dictionary Particle dictionary. diff --git a/cocos/2d/CCPlistSpriteSheetLoader.cpp b/cocos/2d/CCPlistSpriteSheetLoader.cpp index 93a2a975e7ac..1406327d304a 100644 --- a/cocos/2d/CCPlistSpriteSheetLoader.cpp +++ b/cocos/2d/CCPlistSpriteSheetLoader.cpp @@ -18,7 +18,7 @@ using namespace std; NS_CC_BEGIN -void PlistSpriteSheetLoader::load(const std::string& filePath, SpriteFrameCache& cache) +void PlistSpriteSheetLoader::load(std::string_view filePath, SpriteFrameCache& cache) { CCASSERT(!filePath.empty(), "plist filename should not be nullptr"); @@ -26,7 +26,7 @@ void PlistSpriteSheetLoader::load(const std::string& filePath, SpriteFrameCache& if (fullPath.empty()) { // return if plist file doesn't exist - CCLOG("cocos2d: SpriteFrameCache: can not find %s", filePath.c_str()); + CCLOG("cocos2d: SpriteFrameCache: can not find %s", filePath.data()); return; } @@ -66,7 +66,7 @@ void PlistSpriteSheetLoader::load(const std::string& filePath, SpriteFrameCache& addSpriteFramesWithDictionary(dict, texturePath, filePath, cache); } -void PlistSpriteSheetLoader::load(const std::string& filePath, Texture2D* texture, SpriteFrameCache& cache) +void PlistSpriteSheetLoader::load(std::string_view filePath, Texture2D* texture, SpriteFrameCache& cache) { const auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); @@ -74,9 +74,7 @@ void PlistSpriteSheetLoader::load(const std::string& filePath, Texture2D* textur addSpriteFramesWithDictionary(dict, texture, filePath, cache); } -void PlistSpriteSheetLoader::load(const std::string& filePath, - const std::string& textureFileName, - SpriteFrameCache& cache) +void PlistSpriteSheetLoader::load(std::string_view filePath, std::string_view textureFileName, SpriteFrameCache& cache) { CCASSERT(!textureFileName.empty(), "texture name should not be null"); const auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); @@ -98,7 +96,7 @@ void PlistSpriteSheetLoader::load(const Data& content, Texture2D* texture, Sprit addSpriteFramesWithDictionary(dict, texture, "by#addSpriteFramesWithFileContent()", cache); } -void PlistSpriteSheetLoader::reload(const std::string& filePath, SpriteFrameCache& cache) +void PlistSpriteSheetLoader::reload(std::string_view filePath, SpriteFrameCache& cache) { const auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); @@ -151,7 +149,7 @@ void PlistSpriteSheetLoader::reload(const std::string& filePath, SpriteFrameCach void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, Texture2D* texture, - const std::string& plist, + std::string_view plist, SpriteFrameCache& cache) { /* @@ -178,15 +176,15 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, Vec2 textureSize; // get the format - auto metaItr = dictionary.find("metadata"); + auto metaItr = dictionary.find("metadata"sv); if (metaItr != dictionary.end()) { auto& metadataDict = metaItr->second.asValueMap(); - format = metadataDict["format"].asInt(); + format = optValue(metadataDict, "format"sv).asInt(); - if (metadataDict.find("size") != metadataDict.end()) + if (metadataDict.find("size"sv) != metadataDict.end()) { - textureSize = SizeFromString(metadataDict["size"].asString()); + textureSize = SizeFromString(optValue(metadataDict, "size"sv).asString()); } } @@ -210,14 +208,14 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, if (format == 0) { - auto x = frameDict["x"].asFloat(); - auto y = frameDict["y"].asFloat(); - auto w = frameDict["width"].asFloat(); - auto h = frameDict["height"].asFloat(); - auto ox = frameDict["offsetX"].asFloat(); - auto oy = frameDict["offsetY"].asFloat(); - auto ow = frameDict["originalWidth"].asInt(); - auto oh = frameDict["originalHeight"].asInt(); + auto x = optValue(frameDict, "x"sv).asFloat(); + auto y = optValue(frameDict, "y"sv).asFloat(); + auto w = optValue(frameDict, "width"sv).asFloat(); + auto h = optValue(frameDict, "height"sv).asFloat(); + auto ox = optValue(frameDict, "offsetX"sv).asFloat(); + auto oy = optValue(frameDict, "offsetY"sv).asFloat(); + auto ow = optValue(frameDict, "originalWidth"sv).asInt(); + auto oh = optValue(frameDict, "originalHeight"sv).asInt(); // check ow/oh if (!ow || !oh) { @@ -234,17 +232,17 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, } else if (format == 1 || format == 2) { - auto frame = RectFromString(frameDict["frame"].asString()); + auto frame = RectFromString(optValue(frameDict, "frame"sv).asString()); auto rotated = false; // rotation if (format == 2) { - rotated = frameDict["rotated"].asBool(); + rotated = optValue(frameDict, "rotated"sv).asBool(); } - auto offset = PointFromString(frameDict["offset"].asString()); - auto sourceSize = SizeFromString(frameDict["sourceSize"].asString()); + auto offset = PointFromString(optValue(frameDict, "offset"sv).asString()); + auto sourceSize = SizeFromString(optValue(frameDict, "sourceSize"sv).asString()); // create frame spriteFrame = SpriteFrame::createWithTexture(texture, frame, rotated, offset, sourceSize); @@ -252,14 +250,14 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, else if (format == 3) { // get values - auto spriteSize = SizeFromString(frameDict["spriteSize"].asString()); - auto spriteOffset = PointFromString(frameDict["spriteOffset"].asString()); - auto spriteSourceSize = SizeFromString(frameDict["spriteSourceSize"].asString()); - auto textureRect = RectFromString(frameDict["textureRect"].asString()); - auto textureRotated = frameDict["textureRotated"].asBool(); + auto spriteSize = SizeFromString(optValue(frameDict, "spriteSize"sv).asString()); + auto spriteOffset = PointFromString(optValue(frameDict, "spriteOffset"sv).asString()); + auto spriteSourceSize = SizeFromString(optValue(frameDict, "spriteSourceSize"sv).asString()); + auto textureRect = RectFromString(optValue(frameDict, "textureRect"sv).asString()); + auto textureRotated = optValue(frameDict, "textureRotated"sv).asBool(); // get aliases - auto& aliases = frameDict["aliases"].asValueVector(); + auto& aliases = optValue(frameDict, "aliases"sv).asValueVector(); for (const auto& value : aliases) { @@ -282,9 +280,9 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, if (frameDict.find("vertices") != frameDict.end()) { using cocos2d::utils::parseIntegerList; - auto vertices = parseIntegerList(frameDict["vertices"].asString()); - auto verticesUV = parseIntegerList(frameDict["verticesUV"].asString()); - auto indices = parseIntegerList(frameDict["triangles"].asString()); + auto vertices = parseIntegerList(optValue(frameDict, "vertices"sv).asString()); + auto verticesUV = parseIntegerList(optValue(frameDict, "verticesUV"sv).asString()); + auto indices = parseIntegerList(optValue(frameDict, "triangles"sv).asString()); PolygonInfo info; initializePolygonInfo(textureSize, spriteSourceSize, vertices, verticesUV, indices, info); @@ -292,7 +290,7 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, } if (frameDict.find("anchor") != frameDict.end()) { - spriteFrame->setAnchorPoint(PointFromString(frameDict["anchor"].asString())); + spriteFrame->setAnchorPoint(PointFromString(optValue(frameDict, "anchor"sv).asString())); } } @@ -323,8 +321,8 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dictionary, } void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dict, - const std::string& texturePath, - const std::string& plist, + std::string_view texturePath, + std::string_view plist, SpriteFrameCache& cache) { std::string pixelFormatName; @@ -378,7 +376,7 @@ void PlistSpriteSheetLoader::addSpriteFramesWithDictionary(ValueMap& dict, void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict, Texture2D* texture, - const std::string& plist, + std::string_view plist, SpriteFrameCache& cache) { auto& framesDict = dict["frames"].asValueMap(); @@ -401,8 +399,8 @@ void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict, for (auto& iter : framesDict) { - ValueMap& frameDict = iter.second.asValueMap(); - std::string spriteFrameName = iter.first; + const ValueMap& frameDict = iter.second.asValueMap(); + std::string_view spriteFrameName = iter.first; cache.eraseFrame(spriteFrameName); @@ -411,14 +409,14 @@ void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict, if (format == 0) { - const auto x = frameDict["x"].asFloat(); - const auto y = frameDict["y"].asFloat(); - const auto w = frameDict["width"].asFloat(); - const auto h = frameDict["height"].asFloat(); - const auto ox = frameDict["offsetX"].asFloat(); - const auto oy = frameDict["offsetY"].asFloat(); - auto ow = frameDict["originalWidth"].asInt(); - auto oh = frameDict["originalHeight"].asInt(); + const auto x = optValue(frameDict, "x"sv).asFloat(); + const auto y = optValue(frameDict, "y"sv).asFloat(); + const auto w = optValue(frameDict, "width"sv).asFloat(); + const auto h = optValue(frameDict, "height"sv).asFloat(); + const auto ox = optValue(frameDict, "offsetX"sv).asFloat(); + const auto oy = optValue(frameDict, "offsetY"sv).asFloat(); + auto ow = optValue(frameDict, "originalWidth"sv).asInt(); + auto oh = optValue(frameDict, "originalHeight"sv).asInt(); // check ow/oh if (!ow || !oh) { @@ -435,17 +433,17 @@ void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict, } else if (format == 1 || format == 2) { - auto frame = RectFromString(frameDict["frame"].asString()); + auto frame = RectFromString(optValue(frameDict, "frame"sv).asString()); auto rotated = false; // rotation if (format == 2) { - rotated = frameDict["rotated"].asBool(); + rotated = optValue(frameDict, "rotated"sv).asBool(); } - auto offset = PointFromString(frameDict["offset"].asString()); - auto sourceSize = SizeFromString(frameDict["sourceSize"].asString()); + auto offset = PointFromString(optValue(frameDict, "offset"sv).asString()); + auto sourceSize = SizeFromString(optValue(frameDict, "sourceSize"sv).asString()); // create frame spriteFrame = SpriteFrame::createWithTexture(texture, frame, rotated, offset, sourceSize); @@ -453,14 +451,14 @@ void PlistSpriteSheetLoader::reloadSpriteFramesWithDictionary(ValueMap& dict, else if (format == 3) { // get values - const auto spriteSize = SizeFromString(frameDict["spriteSize"].asString()); - auto spriteOffset = PointFromString(frameDict["spriteOffset"].asString()); - auto spriteSourceSize = SizeFromString(frameDict["spriteSourceSize"].asString()); - const auto textureRect = RectFromString(frameDict["textureRect"].asString()); - const auto textureRotated = frameDict["textureRotated"].asBool(); + const auto spriteSize = SizeFromString(optValue(frameDict, "spriteSize"sv).asString()); + auto spriteOffset = PointFromString(optValue(frameDict, "spriteOffset"sv).asString()); + auto spriteSourceSize = SizeFromString(optValue(frameDict, "spriteSourceSize"sv).asString()); + const auto textureRect = RectFromString(optValue(frameDict, "textureRect"sv).asString()); + const auto textureRotated = optValue(frameDict, "textureRotated"sv).asBool(); // get aliases - ValueVector& aliases = frameDict["aliases"].asValueVector(); + const ValueVector& aliases = optValue(frameDict, "aliases"sv).asValueVector(); for (const auto& value : aliases) { diff --git a/cocos/2d/CCPlistSpriteSheetLoader.h b/cocos/2d/CCPlistSpriteSheetLoader.h index 79aa405400a4..6f36caad0b32 100644 --- a/cocos/2d/CCPlistSpriteSheetLoader.h +++ b/cocos/2d/CCPlistSpriteSheetLoader.h @@ -14,30 +14,30 @@ class PlistSpriteSheetLoader : public SpriteSheetLoader static constexpr uint32_t FORMAT = SpriteSheetFormat::PLIST; uint32_t getFormat() override { return FORMAT; } - void load(const std::string& filePath, SpriteFrameCache& cache) override; - void load(const std::string& filePath, Texture2D* texture, SpriteFrameCache& cache) override; - void load(const std::string& filePath, const std::string& textureFileName, SpriteFrameCache& cache) override; + void load(std::string_view filePath, SpriteFrameCache& cache) override; + void load(std::string_view filePath, Texture2D* texture, SpriteFrameCache& cache) override; + void load(std::string_view filePath, std::string_view textureFileName, SpriteFrameCache& cache) override; void load(const Data& content, Texture2D* texture, SpriteFrameCache& cache) override; - void reload(const std::string& filePath, SpriteFrameCache& cache) override; + void reload(std::string_view filePath, SpriteFrameCache& cache) override; protected: /*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames. */ void addSpriteFramesWithDictionary(ValueMap& dictionary, Texture2D* texture, - const std::string& plist, + std::string_view plist, SpriteFrameCache& cache); /*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames. */ void addSpriteFramesWithDictionary(ValueMap& dict, - const std::string& texturePath, - const std::string& plist, + std::string_view texturePath, + std::string_view plist, SpriteFrameCache& cache); void reloadSpriteFramesWithDictionary(ValueMap& dict, Texture2D* texture, - const std::string& plist, + std::string_view plist, SpriteFrameCache& cache); }; diff --git a/cocos/2d/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp index 067237e12e46..7525359dbf84 100644 --- a/cocos/2d/CCRenderTexture.cpp +++ b/cocos/2d/CCRenderTexture.cpp @@ -357,9 +357,7 @@ void RenderTexture::visit(Renderer* renderer, const Mat4& parentTransform, uint3 // setOrderOfArrival(0); } -bool RenderTexture::saveToFileAsNonPMA(const std::string& filename, - bool isRGBA, - std::function callback) +bool RenderTexture::saveToFileAsNonPMA(std::string_view filename, bool isRGBA, SaveFileCallbackType callback) { std::string basename(filename); std::transform(basename.begin(), basename.end(), basename.begin(), ::tolower); @@ -382,9 +380,7 @@ bool RenderTexture::saveToFileAsNonPMA(const std::string& filename, return saveToFileAsNonPMA(filename, Image::Format::JPG, false, callback); } -bool RenderTexture::saveToFile(const std::string& filename, - bool isRGBA, - std::function callback) +bool RenderTexture::saveToFile(std::string_view filename, bool isRGBA, SaveFileCallbackType callback) { std::string basename(filename); std::transform(basename.begin(), basename.end(), basename.begin(), ::tolower); @@ -407,10 +403,10 @@ bool RenderTexture::saveToFile(const std::string& filename, return saveToFile(filename, Image::Format::JPG, false, callback); } -bool RenderTexture::saveToFileAsNonPMA(const std::string& fileName, +bool RenderTexture::saveToFileAsNonPMA(std::string_view fileName, Image::Format format, bool isRGBA, - std::function callback) + SaveFileCallbackType callback) { CCASSERT(format == Image::Format::JPG || format == Image::Format::PNG, "the image can only be saved as JPG or PNG format"); @@ -419,7 +415,7 @@ bool RenderTexture::saveToFileAsNonPMA(const std::string& fileName, _saveFileCallback = callback; - std::string fullpath = FileUtils::getInstance()->getWritablePath() + fileName; + std::string fullpath = FileUtils::getInstance()->getWritablePath().append(fileName); _saveToFileCommand.init(_globalZOrder); _saveToFileCommand.func = CC_CALLBACK_0(RenderTexture::onSaveToFile, this, fullpath, isRGBA, true); @@ -427,10 +423,10 @@ bool RenderTexture::saveToFileAsNonPMA(const std::string& fileName, return true; } -bool RenderTexture::saveToFile(const std::string& fileName, +bool RenderTexture::saveToFile(std::string_view fileName, Image::Format format, bool isRGBA, - std::function callback) + std::function callback) { CCASSERT(format == Image::Format::JPG || format == Image::Format::PNG, "the image can only be saved as JPG or PNG format"); @@ -439,7 +435,7 @@ bool RenderTexture::saveToFile(const std::string& fileName, _saveFileCallback = callback; - std::string fullpath = FileUtils::getInstance()->getWritablePath() + fileName; + std::string fullpath = FileUtils::getInstance()->getWritablePath().append(fileName); _saveToFileCommand.init(_globalZOrder); _saveToFileCommand.func = CC_CALLBACK_0(RenderTexture::onSaveToFile, this, fullpath, isRGBA, false); @@ -447,7 +443,7 @@ bool RenderTexture::saveToFile(const std::string& fileName, return true; } -void RenderTexture::onSaveToFile(const std::string& filename, bool isRGBA, bool forceNonPMA) +void RenderTexture::onSaveToFile(std::string_view filename, bool isRGBA, bool forceNonPMA) { auto callbackFunc = [&, filename, isRGBA, forceNonPMA](RefPtr image) { if (image) diff --git a/cocos/2d/CCRenderTexture.h b/cocos/2d/CCRenderTexture.h index 0fdfb5f5434a..b43e9c380bc9 100644 --- a/cocos/2d/CCRenderTexture.h +++ b/cocos/2d/CCRenderTexture.h @@ -61,6 +61,7 @@ class EventCustom; class CC_DLL RenderTexture : public Node { public: + using SaveFileCallbackType = std::function; /** Initializes a RenderTexture object with width and height in Points and a pixel format( only RGB and RGBA formats * are valid ) and depthStencil format. * @@ -171,9 +172,7 @@ class CC_DLL RenderTexture : public Node * @param callback When the file is save finished,it will callback this function. * @return Returns true if the operation is successful. */ - bool saveToFileAsNonPMA(const std::string& filename, - bool isRGBA = true, - std::function callback = nullptr); + bool saveToFileAsNonPMA(std::string_view filename, bool isRGBA = true, SaveFileCallbackType = nullptr); /** Saves the texture into a file using JPEG format. The file will be saved in the Documents folder. * Returns true if the operation is successful. @@ -183,9 +182,7 @@ class CC_DLL RenderTexture : public Node * @param callback When the file is save finished,it will callback this function. * @return Returns true if the operation is successful. */ - bool saveToFile(const std::string& filename, - bool isRGBA = true, - std::function callback = nullptr); + bool saveToFile(std::string_view filename, bool isRGBA = true, SaveFileCallbackType = nullptr); /** saves the texture into a file in non-PMA. The format could be JPG or PNG. The file will be saved in the Documents folder. Returns true if the operation is successful. @@ -201,10 +198,10 @@ class CC_DLL RenderTexture : public Node * @param callback When the file is save finished,it will callback this function. * @return Returns true if the operation is successful. */ - bool saveToFileAsNonPMA(const std::string& fileName, + bool saveToFileAsNonPMA(std::string_view fileName, Image::Format format, bool isRGBA, - std::function callback); + SaveFileCallbackType callback); /** saves the texture into a file. The format could be JPG or PNG. The file will be saved in the Documents folder. Returns true if the operation is successful. @@ -220,10 +217,10 @@ class CC_DLL RenderTexture : public Node * @param callback When the file is save finished,it will callback this function. * @return Returns true if the operation is successful. */ - bool saveToFile(const std::string& filename, + bool saveToFile(std::string_view filename, Image::Format format, - bool isRGBA = true, - std::function callback = nullptr); + bool isRGBA = true, + SaveFileCallbackType callback = nullptr); /** Listen "come to background" message, and save render texture. * It only has effect on Android. @@ -367,7 +364,7 @@ class CC_DLL RenderTexture : public Node void onEnd(); void clearColorAttachment(); - void onSaveToFile(const std::string& fileName, bool isRGBA = true, bool forceNonPMA = false); + void onSaveToFile(std::string_view fileName, bool isRGBA = true, bool forceNonPMA = false); bool _keepMatrix = false; Rect _rtTextureRect; @@ -411,7 +408,7 @@ class CC_DLL RenderTexture : public Node and the command and callback will be executed twice. */ CallbackCommand _saveToFileCommand; - std::function _saveFileCallback = nullptr; + std::function _saveFileCallback = nullptr; Mat4 _oldTransMatrix, _oldProjMatrix; Mat4 _transformMatrix, _projectionMatrix; diff --git a/cocos/2d/CCScene.h b/cocos/2d/CCScene.h index 96890c12dfc6..2eed035aecb3 100644 --- a/cocos/2d/CCScene.h +++ b/cocos/2d/CCScene.h @@ -142,7 +142,7 @@ class CC_DLL Scene : public Node std::vector _cameras; // weak ref to Camera Camera* _defaultCamera = nullptr; // weak ref, default camera created by scene, _cameras[0], Caution that the // default camera can not be added to _cameras before onEnter is called - bool _cameraOrderDirty = true; // order is dirty, need sort + bool _cameraOrderDirty = true; // order is dirty, need sort EventListenerCustom* _event; std::vector _lights; diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index f5e87fcd73b9..2a97c4f2474e 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -72,7 +72,7 @@ Sprite* Sprite::createWithTexture(Texture2D* texture, const Rect& rect, bool rot return nullptr; } -Sprite* Sprite::create(const std::string& filename) +Sprite* Sprite::create(std::string_view filename) { Sprite* sprite = new Sprite(); if (sprite->initWithFile(filename)) @@ -96,7 +96,7 @@ Sprite* Sprite::create(const PolygonInfo& info) return nullptr; } -Sprite* Sprite::create(const std::string& filename, const Rect& rect) +Sprite* Sprite::create(std::string_view filename, const Rect& rect) { Sprite* sprite = new Sprite(); if (sprite->initWithFile(filename, rect)) @@ -120,13 +120,13 @@ Sprite* Sprite::createWithSpriteFrame(SpriteFrame* spriteFrame) return nullptr; } -Sprite* Sprite::createWithSpriteFrameName(const std::string& spriteFrameName) +Sprite* Sprite::createWithSpriteFrameName(std::string_view spriteFrameName) { SpriteFrame* frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); #if COCOS2D_DEBUG > 0 char msg[256] = {0}; - sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName.c_str()); + sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName.data()); CCASSERT(frame != nullptr, msg); #endif @@ -167,7 +167,7 @@ bool Sprite::initWithTexture(Texture2D* texture, const Rect& rect) return initWithTexture(texture, rect, false); } -bool Sprite::initWithFile(const std::string& filename) +bool Sprite::initWithFile(std::string_view filename) { if (filename.empty()) { @@ -191,7 +191,7 @@ bool Sprite::initWithFile(const std::string& filename) return false; } -bool Sprite::initWithFile(const std::string& filename, const Rect& rect) +bool Sprite::initWithFile(std::string_view filename, const Rect& rect) { CCASSERT(!filename.empty(), "Invalid filename"); if (filename.empty()) @@ -209,7 +209,7 @@ bool Sprite::initWithFile(const std::string& filename, const Rect& rect) return false; } -bool Sprite::initWithSpriteFrameName(const std::string& spriteFrameName) +bool Sprite::initWithSpriteFrameName(std::string_view spriteFrameName) { CCASSERT(!spriteFrameName.empty(), "Invalid spriteFrameName"); if (spriteFrameName.empty()) @@ -332,7 +332,7 @@ static unsigned char cc_2x2_white_image[] = { #define CC_2x2_WHITE_IMAGE_KEY "/cc_2x2_white_image" // MARK: texture -void Sprite::setTexture(const std::string& filename) +void Sprite::setTexture(std::string_view filename) { Texture2D* texture = _director->getTextureCache()->addImage(filename); setTexture(texture); @@ -1132,7 +1132,7 @@ void Sprite::addChild(Node* child, int zOrder, int tag) Node::addChild(child, zOrder, tag); } -void Sprite::addChild(Node* child, int zOrder, const std::string& name) +void Sprite::addChild(Node* child, int zOrder, std::string_view name) { CCASSERT(child != nullptr, "Argument must be non-nullptr"); if (child == nullptr) @@ -1539,7 +1539,7 @@ bool Sprite::isOpacityModifyRGB() const // MARK: Frames -void Sprite::setSpriteFrame(const std::string& spriteFrameName) +void Sprite::setSpriteFrame(std::string_view spriteFrameName) { CCASSERT(!spriteFrameName.empty(), "spriteFrameName must not be empty"); if (spriteFrameName.empty()) @@ -1590,7 +1590,7 @@ void Sprite::setSpriteFrame(SpriteFrame* spriteFrame) setCenterRect(spriteFrame->getCenterRect()); } -void Sprite::setDisplayFrameWithAnimationName(const std::string& animationName, unsigned int frameIndex) +void Sprite::setDisplayFrameWithAnimationName(std::string_view animationName, unsigned int frameIndex) { CCASSERT(!animationName.empty(), "CCSprite#setDisplayFrameWithAnimationName. animationName must not be nullptr"); if (animationName.empty()) diff --git a/cocos/2d/CCSprite.h b/cocos/2d/CCSprite.h index e81f18064e31..d993a6fef2ed 100644 --- a/cocos/2d/CCSprite.h +++ b/cocos/2d/CCSprite.h @@ -129,7 +129,7 @@ class CC_DLL Sprite : public Node, public TextureProtocol * @param filename A path to image file, e.g., "scene1/monster.png". * @return An autoreleased sprite object. */ - static Sprite* create(const std::string& filename); + static Sprite* create(std::string_view filename); /** * Creates a polygon sprite with a polygon info. @@ -149,7 +149,7 @@ class CC_DLL Sprite : public Node, public TextureProtocol * @param rect A subrect of the image file. * @return An autoreleased sprite object. */ - static Sprite* create(const std::string& filename, const Rect& rect); + static Sprite* create(std::string_view filename, const Rect& rect); /** * Creates a sprite with a Texture2D object. @@ -191,7 +191,7 @@ class CC_DLL Sprite : public Node, public TextureProtocol * @param spriteFrameName The name of sprite frame. * @return An autoreleased sprite object. */ - static Sprite* createWithSpriteFrameName(const std::string& spriteFrameName); + static Sprite* createWithSpriteFrameName(std::string_view spriteFrameName); // end of creators group /// @} @@ -233,7 +233,7 @@ class CC_DLL Sprite : public Node, public TextureProtocol * @memberof Sprite * It will call `setTextureRect()` with the texture's content size. */ - virtual void setTexture(const std::string& filename); + virtual void setTexture(std::string_view filename); /** @overload * @@ -304,7 +304,7 @@ class CC_DLL Sprite : public Node, public TextureProtocol /** @{ * Sets a new SpriteFrame to the Sprite. */ - virtual void setSpriteFrame(const std::string& spriteFrameName); + virtual void setSpriteFrame(std::string_view spriteFrameName); virtual void setSpriteFrame(SpriteFrame* newFrame); /** @} */ @@ -326,7 +326,7 @@ class CC_DLL Sprite : public Node, public TextureProtocol * Changes the display frame with animation name and index. * The animation name will be get from the AnimationCache. */ - virtual void setDisplayFrameWithAnimationName(const std::string& animationName, unsigned int frameIndex); + virtual void setDisplayFrameWithAnimationName(std::string_view animationName, unsigned int frameIndex); /// @} /// @{ @@ -370,7 +370,7 @@ class CC_DLL Sprite : public Node, public TextureProtocol virtual void reorderChild(Node* child, int zOrder) override; using Node::addChild; virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, const std::string& name) override; + virtual void addChild(Node* child, int zOrder, std::string_view name) override; virtual void sortAllChildren() override; virtual void setScale(float scale) override; virtual void setPositionZ(float positionZ) override; @@ -513,7 +513,7 @@ class CC_DLL Sprite : public Node, public TextureProtocol /// @} int getResourceType() const { return _fileType; } - const std::string& getResourceName() const { return _fileName; } + std::string_view getResourceName() const { return _fileName; } CC_CONSTRUCTOR_ACCESS : /** @@ -588,7 +588,7 @@ class CC_DLL Sprite : public Node, public TextureProtocol * @param spriteFrameName A key string that can fetched a valid SpriteFrame from SpriteFrameCache. * @return True if the sprite is initialized properly, false otherwise. */ - virtual bool initWithSpriteFrameName(const std::string& spriteFrameName); + virtual bool initWithSpriteFrameName(std::string_view spriteFrameName); /** * Initializes a sprite with an image filename. @@ -601,7 +601,7 @@ class CC_DLL Sprite : public Node, public TextureProtocol * @return True if the sprite is initialized properly, false otherwise. * @lua init */ - virtual bool initWithFile(const std::string& filename); + virtual bool initWithFile(std::string_view filename); /** * Initializes a sprite with an image filename, and a rect. @@ -615,7 +615,7 @@ class CC_DLL Sprite : public Node, public TextureProtocol * @return True if the sprite is initialized properly, false otherwise. * @lua init */ - virtual bool initWithFile(const std::string& filename, const Rect& rect); + virtual bool initWithFile(std::string_view filename, const Rect& rect); virtual void setVertexLayout(); diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index c2c809c51826..4888ac8b5f50 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -64,7 +64,7 @@ SpriteBatchNode* SpriteBatchNode::createWithTexture(Texture2D* tex, ssize_t capa * creation with File Image */ -SpriteBatchNode* SpriteBatchNode::create(const std::string& fileImage, ssize_t capacity /* = DEFAULT_CAPACITY*/) +SpriteBatchNode* SpriteBatchNode::create(std::string_view fileImage, ssize_t capacity /* = DEFAULT_CAPACITY*/) { SpriteBatchNode* batchNode = new SpriteBatchNode(); if (batchNode->initWithFile(fileImage, capacity)) @@ -168,7 +168,7 @@ bool SpriteBatchNode::init() /* * init with FileImage */ -bool SpriteBatchNode::initWithFile(const std::string& fileImage, ssize_t capacity /* = DEFAULT_CAPACITY*/) +bool SpriteBatchNode::initWithFile(std::string_view fileImage, ssize_t capacity /* = DEFAULT_CAPACITY*/) { Texture2D* texture2D = _director->getTextureCache()->addImage(fileImage); return initWithTexture(texture2D, capacity); @@ -236,7 +236,7 @@ void SpriteBatchNode::addChild(Node* child, int zOrder, int tag) appendChild(sprite); } -void SpriteBatchNode::addChild(Node* child, int zOrder, const std::string& name) +void SpriteBatchNode::addChild(Node* child, int zOrder, std::string_view name) { CCASSERT(child != nullptr, "child should not be null"); CCASSERT(dynamic_cast(child) != nullptr, "CCSpriteBatchNode only supports Sprites as children"); diff --git a/cocos/2d/CCSpriteBatchNode.h b/cocos/2d/CCSpriteBatchNode.h index 3d99cdfa52b5..cb68aed0f4c0 100644 --- a/cocos/2d/CCSpriteBatchNode.h +++ b/cocos/2d/CCSpriteBatchNode.h @@ -84,7 +84,7 @@ class CC_DLL SpriteBatchNode : public Node, public TextureProtocol * @param capacity The capacity of children. * @return Return an autorelease object. */ - static SpriteBatchNode* create(const std::string& fileImage, ssize_t capacity = DEFAULT_CAPACITY); + static SpriteBatchNode* create(std::string_view fileImage, ssize_t capacity = DEFAULT_CAPACITY); /** Returns the TextureAtlas object. * @@ -195,7 +195,7 @@ class CC_DLL SpriteBatchNode : public Node, public TextureProtocol using Node::addChild; virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, const std::string& name) override; + virtual void addChild(Node* child, int zOrder, std::string_view name) override; virtual void reorderChild(Node* child, int zOrder) override; virtual void removeChild(Node* child, bool cleanup) override; @@ -250,7 +250,7 @@ class CC_DLL SpriteBatchNode : public Node, public TextureProtocol * @js init * @lua init */ - bool initWithFile(const std::string& fileImage, ssize_t capacity = DEFAULT_CAPACITY); + bool initWithFile(std::string_view fileImage, ssize_t capacity = DEFAULT_CAPACITY); bool init() override; protected: diff --git a/cocos/2d/CCSpriteFrame.cpp b/cocos/2d/CCSpriteFrame.cpp index 7fa67690200a..6ef46c7e67d1 100644 --- a/cocos/2d/CCSpriteFrame.cpp +++ b/cocos/2d/CCSpriteFrame.cpp @@ -35,7 +35,7 @@ NS_CC_BEGIN // implementation of SpriteFrame -SpriteFrame* SpriteFrame::create(const std::string& filename, const Rect& rect) +SpriteFrame* SpriteFrame::create(std::string_view filename, const Rect& rect) { SpriteFrame* spriteFrame = new SpriteFrame(); spriteFrame->initWithTextureFilename(filename, rect); @@ -70,7 +70,7 @@ SpriteFrame* SpriteFrame::createWithTexture(Texture2D* texture, return nullptr; } -SpriteFrame* SpriteFrame::create(const std::string& filename, +SpriteFrame* SpriteFrame::create(std::string_view filename, const Rect& rect, bool rotated, const Vec2& offset, @@ -94,7 +94,7 @@ bool SpriteFrame::initWithTexture(Texture2D* texture, const Rect& rect) return initWithTexture(texture, rectInPixels, false, Vec2::ZERO, rectInPixels.size); } -bool SpriteFrame::initWithTextureFilename(const std::string& filename, const Rect& rect) +bool SpriteFrame::initWithTextureFilename(std::string_view filename, const Rect& rect) { Rect rectInPixels = CC_RECT_POINTS_TO_PIXELS(rect); return initWithTextureFilename(filename, rectInPixels, false, Vec2::ZERO, rectInPixels.size); @@ -126,7 +126,7 @@ bool SpriteFrame::initWithTexture(Texture2D* texture, return true; } -bool SpriteFrame::initWithTextureFilename(const std::string& filename, +bool SpriteFrame::initWithTextureFilename(std::string_view filename, const Rect& rect, bool rotated, const Vec2& offset, diff --git a/cocos/2d/CCSpriteFrame.h b/cocos/2d/CCSpriteFrame.h index 32e93be8eef0..5f17fc12807a 100644 --- a/cocos/2d/CCSpriteFrame.h +++ b/cocos/2d/CCSpriteFrame.h @@ -66,7 +66,7 @@ class CC_DLL SpriteFrame : public Ref, public Clonable * @param rect A specified rect. * @return An autoreleased SpriteFrame object. */ - static SpriteFrame* create(const std::string& filename, const Rect& rect); + static SpriteFrame* create(std::string_view filename, const Rect& rect); /** Create a SpriteFrame with a texture filename, rect, rotated, offset and originalSize in pixels. The originalSize is the size in pixels of the frame before being trimmed. @@ -78,7 +78,7 @@ class CC_DLL SpriteFrame : public Ref, public Clonable * @param originalSize A specified original size. * @return An autoreleased SpriteFrame object. */ - static SpriteFrame* create(const std::string& filename, + static SpriteFrame* create(std::string_view filename, const Rect& rect, bool rotated, const Vec2& offset, @@ -279,7 +279,7 @@ class CC_DLL SpriteFrame : public Ref, public Clonable /** Initializes a SpriteFrame with a texture filename, rect in points; It is assumed that the frame was not trimmed. */ - bool initWithTextureFilename(const std::string& filename, const Rect& rect); + bool initWithTextureFilename(std::string_view filename, const Rect& rect); /** Initializes a SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels. The originalSize is the size in points of the frame before being trimmed. @@ -295,7 +295,7 @@ class CC_DLL SpriteFrame : public Ref, public Clonable @since v1.1 */ - bool initWithTextureFilename(const std::string& filename, + bool initWithTextureFilename(std::string_view filename, const Rect& rect, bool rotated, const Vec2& offset, diff --git a/cocos/2d/CCSpriteFrameCache.cpp b/cocos/2d/CCSpriteFrameCache.cpp index db7b97745828..6c4fc158a652 100644 --- a/cocos/2d/CCSpriteFrameCache.cpp +++ b/cocos/2d/CCSpriteFrameCache.cpp @@ -75,8 +75,8 @@ bool SpriteFrameCache::init() SpriteFrameCache::~SpriteFrameCache() {} -void SpriteFrameCache::addSpriteFramesWithFile(const std::string& spriteSheetFileName, - const std::string& textureFileName, +void SpriteFrameCache::addSpriteFramesWithFile(std::string_view spriteSheetFileName, + std::string_view textureFileName, uint32_t spriteSheetFormat) { auto* loader = getSpriteSheetLoader(spriteSheetFormat); @@ -86,7 +86,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(const std::string& spriteSheetFil } } -void SpriteFrameCache::addSpriteFramesWithFile(const std::string& spriteSheetFileName, +void SpriteFrameCache::addSpriteFramesWithFile(std::string_view spriteSheetFileName, Texture2D* texture, uint32_t spriteSheetFormat) { @@ -97,7 +97,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(const std::string& spriteSheetFil } } -void SpriteFrameCache::addSpriteFramesWithFile(const std::string& spriteSheetFileName, uint32_t spriteSheetFormat) +void SpriteFrameCache::addSpriteFramesWithFile(std::string_view spriteSheetFileName, uint32_t spriteSheetFormat) { auto* loader = getSpriteSheetLoader(spriteSheetFormat); if (loader) @@ -117,12 +117,12 @@ void SpriteFrameCache::addSpriteFramesWithFileContent(const Data& content, } } -bool SpriteFrameCache::isSpriteFramesWithFileLoaded(const std::string& plist) const +bool SpriteFrameCache::isSpriteFramesWithFileLoaded(std::string_view plist) const { return isSpriteSheetInUse(plist) && isPlistFull(plist); } -void SpriteFrameCache::addSpriteFrame(SpriteFrame* frame, const std::string& frameName) +void SpriteFrameCache::addSpriteFrame(SpriteFrame* frame, std::string_view frameName) { CCASSERT(frame, "frame should not be nil"); @@ -169,7 +169,7 @@ void SpriteFrameCache::removeUnusedSpriteFrames() } } -void SpriteFrameCache::removeSpriteFrameByName(const std::string& name) +void SpriteFrameCache::removeSpriteFrameByName(std::string_view name) { // explicit nil handling if (name.empty()) @@ -178,7 +178,7 @@ void SpriteFrameCache::removeSpriteFrameByName(const std::string& name) eraseFrame(name); } -void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& atlasPath) +void SpriteFrameCache::removeSpriteFramesFromFile(std::string_view atlasPath) { // const auto fullPath = FileUtils::getInstance()->fullPathForFilename(plist); // auto dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); @@ -193,7 +193,7 @@ void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& atlasPath) removeSpriteSheet(atlasPath); } -void SpriteFrameCache::removeSpriteFramesFromFileContent(const std::string& plist_content) +void SpriteFrameCache::removeSpriteFramesFromFileContent(std::string_view plist_content) { auto dict = FileUtils::getInstance()->getValueMapFromData(plist_content.data(), static_cast(plist_content.size())); @@ -241,17 +241,17 @@ void SpriteFrameCache::removeSpriteFramesFromTexture(Texture2D* texture) eraseFrames(keysToRemove); } -SpriteFrame* SpriteFrameCache::getSpriteFrameByName(const std::string& name) +SpriteFrame* SpriteFrameCache::getSpriteFrameByName(std::string_view name) { auto* frame = findFrame(name); if (!frame) { - CCLOG("cocos2d: SpriteFrameCache: Frame '%s' isn't found", name.c_str()); + CCLOG("cocos2d: SpriteFrameCache: Frame '%s' isn't found", name.data()); } return frame; } -bool SpriteFrameCache::reloadTexture(const std::string& spriteSheetFileName) +bool SpriteFrameCache::reloadTexture(std::string_view spriteSheetFileName) { CCASSERT(!spriteSheetFileName.empty(), "plist filename should not be nullptr"); @@ -283,16 +283,18 @@ bool SpriteFrameCache::reloadTexture(const std::string& spriteSheetFileName) } void SpriteFrameCache::insertFrame(const std::shared_ptr& spriteSheet, - const std::string& frameName, + std::string_view frameName, SpriteFrame* spriteFrame) { - spriteSheet->frames.insert(frameName); + spriteSheet->frames.emplace(frameName); _spriteFrames.insert(frameName, spriteFrame); // add SpriteFrame - _spriteSheets[spriteSheet->path] = spriteSheet; - _spriteFrameToSpriteSheetMap[frameName] = spriteSheet; // insert index frameName->plist + _spriteSheets[spriteSheet->path] = spriteSheet; + hlookup::set_item(_spriteFrameToSpriteSheetMap, frameName, + spriteSheet); // _spriteFrameToSpriteSheetMap[frameName] = spriteSheet; // insert + // index frameName->plist } -bool SpriteFrameCache::eraseFrame(const std::string& frameName) +bool SpriteFrameCache::eraseFrame(std::string_view frameName) { _spriteFrames.erase(frameName); // drop SpriteFrame const auto itFrame = _spriteFrameToSpriteSheetMap.find(frameName); @@ -330,7 +332,7 @@ bool SpriteFrameCache::eraseFrames(const std::vector& frames) return ret; } -bool SpriteFrameCache::removeSpriteSheet(const std::string& spriteSheetFileName) +bool SpriteFrameCache::removeSpriteSheet(std::string_view spriteSheetFileName) { auto it = _spriteSheets.find(spriteSheetFileName); if (it == _spriteSheets.end()) @@ -356,18 +358,18 @@ void SpriteFrameCache::clear() _spriteFrames.clear(); } -bool SpriteFrameCache::hasFrame(const std::string& frame) const +bool SpriteFrameCache::hasFrame(std::string_view frame) const { return _spriteFrameToSpriteSheetMap.find(frame) != _spriteFrameToSpriteSheetMap.end(); } -bool SpriteFrameCache::isSpriteSheetInUse(const std::string& spriteSheetFileName) const +bool SpriteFrameCache::isSpriteSheetInUse(std::string_view spriteSheetFileName) const { const auto spriteSheetItr = _spriteSheets.find(spriteSheetFileName); return spriteSheetItr != _spriteSheets.end() && !spriteSheetItr->second->frames.empty(); } -SpriteFrame* SpriteFrameCache::findFrame(const std::string& frame) +SpriteFrame* SpriteFrameCache::findFrame(std::string_view frame) { return _spriteFrames.at(frame); } @@ -377,7 +379,7 @@ void SpriteFrameCache::addSpriteFrameCapInset(SpriteFrame* spriteFrame, const Re texture->addSpriteFrameCapInset(spriteFrame, capInsets); } -Map& SpriteFrameCache::getSpriteFrames() +StringMap& SpriteFrameCache::getSpriteFrames() { return _spriteFrames; } diff --git a/cocos/2d/CCSpriteFrameCache.h b/cocos/2d/CCSpriteFrameCache.h index 3009a6bd85e5..78db1c5bffd4 100644 --- a/cocos/2d/CCSpriteFrameCache.h +++ b/cocos/2d/CCSpriteFrameCache.h @@ -117,7 +117,7 @@ class CC_DLL SpriteFrameCache : public Ref /** 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 std::string& plist, const + * If you want to use another texture, you should use the addSpriteFramesWithFile(std::string_view plist, const * std::string& textureFileName) method. * @js addSpriteFrames * @lua addSpriteFrames @@ -125,7 +125,7 @@ class CC_DLL SpriteFrameCache : public Ref * @param spriteSheetFileName file name. * @param spriteSheetFormat */ - void addSpriteFramesWithFile(const std::string& spriteSheetFileName, + void addSpriteFramesWithFile(std::string_view spriteSheetFileName, uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST); /** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. @@ -137,8 +137,8 @@ class CC_DLL SpriteFrameCache : public Ref * @param textureFileName Texture file name. * @param spriteSheetFormat */ - void addSpriteFramesWithFile(const std::string& spriteSheetFileName, - const std::string& textureFileName, + void addSpriteFramesWithFile(std::string_view spriteSheetFileName, + std::string_view textureFileName, uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST); /** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. @@ -149,7 +149,7 @@ class CC_DLL SpriteFrameCache : public Ref * @param texture Texture pointer. * @param spriteSheetFormat */ - void addSpriteFramesWithFile(const std::string& spriteSheetFileName, + void addSpriteFramesWithFile(std::string_view spriteSheetFileName, Texture2D* texture, uint32_t spriteSheetFormat = SpriteSheetFormat::PLIST); @@ -172,7 +172,7 @@ class CC_DLL SpriteFrameCache : public Ref * @param frame A certain sprite frame. * @param frameName The name of the sprite frame. */ - void addSpriteFrame(SpriteFrame* frame, const std::string& frameName); + void addSpriteFrame(SpriteFrame* frame, std::string_view frameName); /** Check if multiple Sprite Frames from a plist file have been loaded. * @js NA @@ -181,7 +181,7 @@ class CC_DLL SpriteFrameCache : public Ref * @param plist Plist file name. * @return True if the file is loaded. */ - bool isSpriteFramesWithFileLoaded(const std::string& plist) const; + bool isSpriteFramesWithFileLoaded(std::string_view plist) const; /** Purges the dictionary of loaded sprite frames. * Call this method if you receive the "Memory Warning". @@ -202,7 +202,7 @@ class CC_DLL SpriteFrameCache : public Ref * * @param name The name of the sprite frame that needs to removed. */ - void removeSpriteFrameByName(const std::string& name); + void removeSpriteFrameByName(std::string_view name); /** Removes multiple Sprite Frames from a plist file. * Sprite Frames stored in this file will be removed. @@ -211,7 +211,7 @@ class CC_DLL SpriteFrameCache : public Ref * * @param plist The name of the plist that needs to removed. */ - void removeSpriteFramesFromFile(const std::string& plist); + void removeSpriteFramesFromFile(std::string_view plist); /** Removes multiple Sprite Frames from a plist file content. * Sprite Frames stored in this file will be removed. @@ -220,7 +220,7 @@ class CC_DLL SpriteFrameCache : public Ref * @param plist_content The string of the plist content that needs to removed. * @js NA */ - void removeSpriteFramesFromFileContent(const std::string& plist_content); + void removeSpriteFramesFromFileContent(std::string_view plist_content); /** Removes all Sprite Frames associated with the specified textures. * It is convenient to call this method when a specific texture needs to be removed. @@ -239,22 +239,22 @@ class CC_DLL SpriteFrameCache : public Ref * @param name A certain sprite frame name. * @return The sprite frame. */ - SpriteFrame* getSpriteFrameByName(const std::string& name); + SpriteFrame* getSpriteFrameByName(std::string_view name); - bool reloadTexture(const std::string& spriteSheetFileName); + bool reloadTexture(std::string_view spriteSheetFileName); - SpriteFrame* findFrame(const std::string& frame); + SpriteFrame* findFrame(std::string_view frame); /** Record SpriteFrame with plist and frame name, add frame name * and plist to index */ void insertFrame(const std::shared_ptr& spriteSheet, - const std::string& frameName, + std::string_view frameName, SpriteFrame* frameObj); /** Delete frame from cache, rebuild index */ - bool eraseFrame(const std::string& frameName); + bool eraseFrame(std::string_view frameName); void addSpriteFrameCapInset(SpriteFrame* spriteFrame, const Rect& capInsets, Texture2D* texture); @@ -277,30 +277,35 @@ class CC_DLL SpriteFrameCache : public Ref bool eraseFrames(const std::vector& frame); /** Delete frame from index and SpriteFrame is kept. */ - bool removeSpriteSheet(const std::string& spriteSheetFileName); + bool removeSpriteSheet(std::string_view spriteSheetFileName); /** Clear index and all SpriteFrames. */ void clear(); - inline bool hasFrame(const std::string& frame) const; - inline bool isSpriteSheetInUse(const std::string& spriteSheetFileName) const; + inline bool hasFrame(std::string_view frame) const; + inline bool isSpriteSheetInUse(std::string_view spriteSheetFileName) const; - inline Map& getSpriteFrames(); + inline StringMap& getSpriteFrames(); - void markPlistFull(const std::string& spriteSheetFileName, bool full) + void markPlistFull(std::string_view spriteSheetFileName, bool full) { - _spriteSheets[spriteSheetFileName]->full = full; + // _spriteSheets[spriteSheetFileName]->full = full; + auto it = _spriteSheets.find(spriteSheetFileName); + if (it != _spriteSheets.end()) + { + it.value()->full = full; + } } - bool isPlistFull(const std::string& spriteSheetFileName) const + bool isPlistFull(std::string_view spriteSheetFileName) const { - auto&& it = _spriteSheets.find(spriteSheetFileName); + auto it = _spriteSheets.find(spriteSheetFileName); return it == _spriteSheets.end() ? false : it->second->full; } private: - Map _spriteFrames; - std::unordered_map> _spriteSheets; - std::unordered_map> _spriteFrameToSpriteSheetMap; + StringMap _spriteFrames; + hlookup::string_map> _spriteSheets; + hlookup::string_map> _spriteFrameToSpriteSheetMap; std::map> _spriteSheetLoaders; }; diff --git a/cocos/2d/CCSpriteSheetLoader.h b/cocos/2d/CCSpriteSheetLoader.h index 80d93632d576..d4a236ee9db8 100644 --- a/cocos/2d/CCSpriteSheetLoader.h +++ b/cocos/2d/CCSpriteSheetLoader.h @@ -65,20 +65,20 @@ class SpriteSheet public: std::string path; uint32_t format; - std::set frames; + hlookup::string_set frames; bool full = false; }; class ISpriteSheetLoader { public: - virtual ~ISpriteSheetLoader() = default; - virtual uint32_t getFormat() = 0; - virtual void load(const std::string& filePath, SpriteFrameCache& cache) = 0; - virtual void load(const std::string& filePath, Texture2D* texture, SpriteFrameCache& cache) = 0; - virtual void load(const std::string& filePath, const std::string& textureFileName, SpriteFrameCache& cache) = 0; - virtual void load(const Data& content, Texture2D* texture, SpriteFrameCache& cache) = 0; - virtual void reload(const std::string& filePath, SpriteFrameCache& cache) = 0; + virtual ~ISpriteSheetLoader() = default; + virtual uint32_t getFormat() = 0; + virtual void load(std::string_view filePath, SpriteFrameCache& cache) = 0; + virtual void load(std::string_view filePath, Texture2D* texture, SpriteFrameCache& cache) = 0; + virtual void load(std::string_view filePath, std::string_view textureFileName, SpriteFrameCache& cache) = 0; + virtual void load(const Data& content, Texture2D* texture, SpriteFrameCache& cache) = 0; + virtual void reload(std::string_view filePath, SpriteFrameCache& cache) = 0; }; class SpriteSheetLoader : public ISpriteSheetLoader @@ -92,12 +92,12 @@ class SpriteSheetLoader : public ISpriteSheetLoader const std::vector& triangleIndices, PolygonInfo& polygonInfo); - uint32_t getFormat() override = 0; - void load(const std::string& filePath, SpriteFrameCache& cache) override = 0; - void load(const std::string& filePath, Texture2D* texture, SpriteFrameCache& cache) override = 0; - void load(const std::string& filePath, const std::string& textureFileName, SpriteFrameCache& cache) override = 0; - void load(const Data& content, Texture2D* texture, SpriteFrameCache& cache) override = 0; - void reload(const std::string& filePath, SpriteFrameCache& cache) override = 0; + uint32_t getFormat() override = 0; + void load(std::string_view filePath, SpriteFrameCache& cache) override = 0; + void load(std::string_view filePath, Texture2D* texture, SpriteFrameCache& cache) override = 0; + void load(std::string_view filePath, std::string_view textureFileName, SpriteFrameCache& cache) override = 0; + void load(const Data& content, Texture2D* texture, SpriteFrameCache& cache) override = 0; + void reload(std::string_view filePath, SpriteFrameCache& cache) override = 0; }; // end of _2d group diff --git a/cocos/2d/CCTMXObjectGroup.cpp b/cocos/2d/CCTMXObjectGroup.cpp index 7196acad9b88..99042b01b332 100644 --- a/cocos/2d/CCTMXObjectGroup.cpp +++ b/cocos/2d/CCTMXObjectGroup.cpp @@ -40,7 +40,7 @@ TMXObjectGroup::~TMXObjectGroup() CCLOGINFO("deallocing TMXObjectGroup: %p", this); } -ValueMap TMXObjectGroup::getObject(const std::string& objectName) const +ValueMap TMXObjectGroup::getObject(std::string_view objectName) const { if (!_objects.empty()) { @@ -59,7 +59,7 @@ ValueMap TMXObjectGroup::getObject(const std::string& objectName) const return ValueMap(); } -Value TMXObjectGroup::getProperty(const std::string& propertyName) const +Value TMXObjectGroup::getProperty(std::string_view propertyName) const { if (_properties.find(propertyName) != _properties.end()) return _properties.at(propertyName); diff --git a/cocos/2d/CCTMXObjectGroup.h b/cocos/2d/CCTMXObjectGroup.h index d7df9de64bbd..5a012fc18025 100644 --- a/cocos/2d/CCTMXObjectGroup.h +++ b/cocos/2d/CCTMXObjectGroup.h @@ -60,13 +60,13 @@ class CC_DLL TMXObjectGroup : public Ref * * @return The group name. */ - const std::string& getGroupName() const { return _groupName; } + std::string_view getGroupName() const { return _groupName; } /** Set the group name. * * @param groupName A string,it is used to set the group name. */ - void setGroupName(const std::string& groupName) { _groupName = groupName; } + void setGroupName(std::string_view groupName) { _groupName = groupName; } /** Return the value for the specific property name. * @@ -74,14 +74,14 @@ class CC_DLL TMXObjectGroup : public Ref * @return Return the value for the specific property name. * @js NA */ - Value getProperty(const std::string& propertyName) const; + Value getProperty(std::string_view propertyName) const; /** Return the dictionary for the specific object name. * It will return the 1st object found on the array for the given name. * * @return Return the dictionary for the specific object name. */ - ValueMap getObject(const std::string& objectName) const; + ValueMap getObject(std::string_view objectName) const; /** Gets the offset position of child objects. * diff --git a/cocos/2d/CCTMXXMLParser.cpp b/cocos/2d/CCTMXXMLParser.cpp index 69161885483e..e8d33801d827 100644 --- a/cocos/2d/CCTMXXMLParser.cpp +++ b/cocos/2d/CCTMXXMLParser.cpp @@ -92,7 +92,7 @@ Rect TMXTilesetInfo::getRectForGID(uint32_t gid) // implementation TMXMapInfo -TMXMapInfo* TMXMapInfo::create(const std::string& tmxFile) +TMXMapInfo* TMXMapInfo::create(std::string_view tmxFile) { TMXMapInfo* ret = new TMXMapInfo(); if (ret->initWithTMXFile(tmxFile)) @@ -104,7 +104,7 @@ TMXMapInfo* TMXMapInfo::create(const std::string& tmxFile) return nullptr; } -TMXMapInfo* TMXMapInfo::createWithXML(const std::string& tmxString, const std::string& resourcePath) +TMXMapInfo* TMXMapInfo::createWithXML(std::string_view tmxString, std::string_view resourcePath) { TMXMapInfo* ret = new TMXMapInfo(); if (ret->initWithXML(tmxString, resourcePath)) @@ -116,7 +116,7 @@ TMXMapInfo* TMXMapInfo::createWithXML(const std::string& tmxString, const std::s return nullptr; } -void TMXMapInfo::internalInit(const std::string& tmxFileName, const std::string& resourcePath) +void TMXMapInfo::internalInit(std::string_view tmxFileName, std::string_view resourcePath) { if (!tmxFileName.empty()) { @@ -138,13 +138,13 @@ void TMXMapInfo::internalInit(const std::string& tmxFileName, const std::string& _currentFirstGID = -1; } -bool TMXMapInfo::initWithXML(const std::string& tmxString, const std::string& resourcePath) +bool TMXMapInfo::initWithXML(std::string_view tmxString, std::string_view resourcePath) { internalInit("", resourcePath); return parseXMLString(tmxString); } -bool TMXMapInfo::initWithTMXFile(const std::string& tmxFile) +bool TMXMapInfo::initWithTMXFile(std::string_view tmxFile) { internalInit(tmxFile, ""); return parseXMLFile(_TMXFileName); @@ -171,7 +171,7 @@ TMXMapInfo::~TMXMapInfo() CCLOGINFO("deallocing TMXMapInfo: %p", this); } -bool TMXMapInfo::parseXMLString(const std::string& xmlString) +bool TMXMapInfo::parseXMLString(std::string_view xmlString) { size_t len = xmlString.size(); if (len <= 0) @@ -186,10 +186,10 @@ bool TMXMapInfo::parseXMLString(const std::string& xmlString) parser.setDelegator(this); - return parser.parse(xmlString.c_str(), len); + return parser.parse(xmlString.data(), len); } -bool TMXMapInfo::parseXMLFile(const std::string& xmlFilename) +bool TMXMapInfo::parseXMLFile(std::string_view xmlFilename) { SAXParser parser; @@ -265,7 +265,7 @@ void TMXMapInfo::startElement(void* /*ctx*/, const char* name, const char** atts tmxMapInfo->setStaggerIndex(TMXStaggerIndex_Even); } - float hexSideLength = attributeDict["hexsidelength"].asFloat(); + auto hexSideLength = attributeDict["hexsidelength"].asInt(); tmxMapInfo->setHexSideLength(hexSideLength); Vec2 s; @@ -348,7 +348,7 @@ void TMXMapInfo::startElement(void* /*ctx*/, const char* name, const char** atts TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); Vec2 layerSize = layer->_layerSize; uint32_t gid = static_cast(attributeDict["gid"].asUnsignedInt()); - int tilesAmount = layerSize.width * layerSize.height; + int tilesAmount = static_cast(layerSize.width * layerSize.height); if (_xmlTileIndex < tilesAmount) { @@ -443,7 +443,7 @@ void TMXMapInfo::startElement(void* /*ctx*/, const char* name, const char** atts TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); Vec2 layerSize = layer->_layerSize; - int tilesAmount = layerSize.width * layerSize.height; + int tilesAmount = static_cast(layerSize.width * layerSize.height); uint32_t* tiles = (uint32_t*)malloc(tilesAmount * sizeof(uint32_t)); // set all value to 0 @@ -688,10 +688,10 @@ void TMXMapInfo::endElement(void* /*ctx*/, const char* name) TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); - std::string currentString = tmxMapInfo->getCurrentString(); + auto currentString = tmxMapInfo->getCurrentString(); unsigned char* buffer; auto len = - base64Decode((unsigned char*)currentString.c_str(), (unsigned int)currentString.length(), &buffer); + base64Decode((unsigned char*)currentString.data(), (unsigned int)currentString.length(), &buffer); if (!buffer) { CCLOG("cocos2d: TiledMap: decode data error"); @@ -733,10 +733,11 @@ void TMXMapInfo::endElement(void* /*ctx*/, const char* name) TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); tmxMapInfo->setStoringCharacters(false); - std::string currentString = tmxMapInfo->getCurrentString(); + auto currentString = tmxMapInfo->getCurrentString(); vector gidTokens; - istringstream filestr(currentString); + std::stringstream filestr; + filestr << currentString; string sRow; while (getline(filestr, sRow, '\n')) { @@ -810,7 +811,7 @@ void TMXMapInfo::textHandler(void* /*ctx*/, const char* ch, size_t len) if (tmxMapInfo->isStoringCharacters()) { - std::string currentString = tmxMapInfo->getCurrentString(); + std::string currentString{tmxMapInfo->getCurrentString()}; currentString += text; tmxMapInfo->setCurrentString(currentString); } diff --git a/cocos/2d/CCTMXXMLParser.h b/cocos/2d/CCTMXXMLParser.h index 20f780526c2d..1ec2a821f4e3 100644 --- a/cocos/2d/CCTMXXMLParser.h +++ b/cocos/2d/CCTMXXMLParser.h @@ -250,9 +250,9 @@ class CC_DLL TMXMapInfo : public Ref, public SAXDelegator { public: /** creates a TMX Format with a tmx file */ - static TMXMapInfo* create(const std::string& tmxFile); + static TMXMapInfo* create(std::string_view tmxFile); /** creates a TMX Format with an XML string and a TMX resource path */ - static TMXMapInfo* createWithXML(const std::string& tmxString, const std::string& resourcePath); + static TMXMapInfo* createWithXML(std::string_view tmxString, std::string_view resourcePath); /** * @js ctor @@ -265,13 +265,13 @@ class CC_DLL TMXMapInfo : public Ref, public SAXDelegator virtual ~TMXMapInfo(); /** initializes a TMX format with a tmx file */ - bool initWithTMXFile(const std::string& tmxFile); + bool initWithTMXFile(std::string_view tmxFile); /** initializes a TMX format with an XML string and a TMX resource path */ - bool initWithXML(const std::string& tmxString, const std::string& resourcePath); + bool initWithXML(std::string_view tmxString, std::string_view resourcePath); /** initializes parsing of an XML file, either a tmx (Map) file or tsx (Tileset) file */ - bool parseXMLFile(const std::string& xmlFilename); + bool parseXMLFile(std::string_view xmlFilename); /* initializes parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string */ - bool parseXMLString(const std::string& xmlString); + bool parseXMLString(std::string_view xmlString); ValueMapIntKey& getTileProperties() { return _tileProperties; }; void setTileProperties(const ValueMapIntKey& tileProperties) { _tileProperties = tileProperties; } @@ -353,14 +353,14 @@ class CC_DLL TMXMapInfo : public Ref, public SAXDelegator */ void textHandler(void* ctx, const char* ch, size_t len) override; - const std::string& getCurrentString() const { return _currentString; } - void setCurrentString(const std::string& currentString) { _currentString = currentString; } - const std::string& getTMXFileName() const { return _TMXFileName; } - void setTMXFileName(const std::string& fileName) { _TMXFileName = fileName; } - const std::string& getExternalTilesetFileName() const { return _externalTilesetFilename; } + std::string_view getCurrentString() const { return _currentString; } + void setCurrentString(std::string_view currentString) { _currentString = currentString; } + std::string_view getTMXFileName() const { return _TMXFileName; } + void setTMXFileName(std::string_view fileName) { _TMXFileName = fileName; } + std::string_view getExternalTilesetFileName() const { return _externalTilesetFilename; } protected: - void internalInit(const std::string& tmxFileName, const std::string& resourcePath); + void internalInit(std::string_view tmxFileName, std::string_view resourcePath); /// map orientation int _orientation; diff --git a/cocos/2d/CCTextFieldTTF.cpp b/cocos/2d/CCTextFieldTTF.cpp index 8ccdaace71e9..a134395fb9ec 100644 --- a/cocos/2d/CCTextFieldTTF.cpp +++ b/cocos/2d/CCTextFieldTTF.cpp @@ -109,10 +109,10 @@ TextFieldTTF::~TextFieldTTF() {} // static constructor ////////////////////////////////////////////////////////////////////////// -TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder, +TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(std::string_view placeholder, const Vec2& dimensions, TextHAlignment alignment, - const std::string& fontName, + std::string_view fontName, float fontSize) { TextFieldTTF* ret = new TextFieldTTF(); @@ -129,8 +129,8 @@ TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(const std::string& placehol return nullptr; } -TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder, - const std::string& fontName, +TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(std::string_view placeholder, + std::string_view fontName, float fontSize) { TextFieldTTF* ret = new TextFieldTTF(); @@ -151,10 +151,10 @@ TextFieldTTF* TextFieldTTF::textFieldWithPlaceHolder(const std::string& placehol // initialize ////////////////////////////////////////////////////////////////////////// -bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, +bool TextFieldTTF::initWithPlaceHolder(std::string_view placeholder, const Vec2& dimensions, TextHAlignment alignment, - const std::string& fontName, + std::string_view fontName, float fontSize) { setDimensions(dimensions.width, dimensions.height); @@ -162,7 +162,7 @@ bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, return initWithPlaceHolder(placeholder, fontName, fontSize); } -bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize) +bool TextFieldTTF::initWithPlaceHolder(std::string_view placeholder, std::string_view fontName, float fontSize) { _placeHolder = placeholder; @@ -366,7 +366,7 @@ void TextFieldTTF::deleteBackward() } } -const std::string& TextFieldTTF::getContentText() +std::string_view TextFieldTTF::getContentText() { return _inputText; } @@ -573,9 +573,9 @@ void TextFieldTTF::setString(std::string_view text) _charCount = charCount; } -void TextFieldTTF::appendString(const std::string& text) +void TextFieldTTF::appendString(std::string_view text) { - insertText(text.c_str(), text.length()); + insertText(text.data(), text.length()); } void TextFieldTTF::makeStringSupportCursor(std::string& displayText) @@ -677,13 +677,13 @@ void TextFieldTTF::controlKey(EventKeyboard::KeyCode keyCode) } } -const std::string& TextFieldTTF::getString() const +std::string_view TextFieldTTF::getString() const { return _inputText; } // place holder text property -void TextFieldTTF::setPlaceHolder(const std::string& text) +void TextFieldTTF::setPlaceHolder(std::string_view text) { _placeHolder = text; if (_inputText.empty() && !_isAttachWithIME) @@ -693,7 +693,7 @@ void TextFieldTTF::setPlaceHolder(const std::string& text) } } -const std::string& TextFieldTTF::getPlaceHolder() const +std::string_view TextFieldTTF::getPlaceHolder() const { return _placeHolder; } @@ -733,7 +733,7 @@ void TextFieldTTF::setSecureTextEntry(bool value) } } -void TextFieldTTF::setPasswordTextStyle(const std::string& text) +void TextFieldTTF::setPasswordTextStyle(std::string_view text) { if (text.length() < 1) { @@ -747,7 +747,7 @@ void TextFieldTTF::setPasswordTextStyle(const std::string& text) } } -const std::string& TextFieldTTF::getPasswordTextStyle() const +std::string_view TextFieldTTF::getPasswordTextStyle() const { return _passwordStyleText; } diff --git a/cocos/2d/CCTextFieldTTF.h b/cocos/2d/CCTextFieldTTF.h index 4eee6e0f8649..b9276ffb4a78 100644 --- a/cocos/2d/CCTextFieldTTF.h +++ b/cocos/2d/CCTextFieldTTF.h @@ -98,28 +98,28 @@ class CC_DLL TextFieldTTF : public Label, public IMEDelegate /** Creates a TextFieldTTF from a fontname, alignment, dimension and font size. * @js NA */ - static TextFieldTTF* textFieldWithPlaceHolder(const std::string& placeholder, + static TextFieldTTF* textFieldWithPlaceHolder(std::string_view placeholder, const Vec2& dimensions, TextHAlignment alignment, - const std::string& fontName, + std::string_view fontName, float fontSize); /** Creates a TextFieldTTF from a fontname and font size. * @js NA */ - static TextFieldTTF* textFieldWithPlaceHolder(const std::string& placeholder, - const std::string& fontName, + static TextFieldTTF* textFieldWithPlaceHolder(std::string_view placeholder, + std::string_view fontName, float fontSize); /** Initializes the TextFieldTTF with a font name, alignment, dimension and font size. */ - bool initWithPlaceHolder(const std::string& placeholder, + bool initWithPlaceHolder(std::string_view placeholder, const Vec2& dimensions, TextHAlignment alignment, - const std::string& fontName, + std::string_view fontName, float fontSize); /** Initializes the TextFieldTTF with a font name and font size. */ - bool initWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize); + bool initWithPlaceHolder(std::string_view placeholder, std::string_view fontName, float fontSize); /** *@brief Open keyboard and receive input text. @@ -183,26 +183,26 @@ class CC_DLL TextFieldTTF : public Label, public IMEDelegate * Append to input text of TextField. *@param text The append text of TextField. */ - virtual void appendString(const std::string& text); + virtual void appendString(std::string_view text); /** * Query the input text of TextField. *@return Get the input text of TextField. */ - virtual const std::string& getString() const override; + virtual std::string_view getString() const override; /** * Change placeholder text. * place holder text displayed when there is no text in the text field. *@param text The placeholder string. */ - virtual void setPlaceHolder(const std::string& text); + virtual void setPlaceHolder(std::string_view text); /** * Query the placeholder string. *@return The placeholder string. */ - virtual const std::string& getPlaceHolder() const; + virtual std::string_view getPlaceHolder() const; /** * Set enable secure text entry representation. @@ -211,8 +211,8 @@ class CC_DLL TextFieldTTF : public Label, public IMEDelegate * @js NA */ virtual void setSecureTextEntry(bool value); - virtual void setPasswordTextStyle(const std::string& text); - const std::string& getPasswordTextStyle() const; + virtual void setPasswordTextStyle(std::string_view text); + std::string_view getPasswordTextStyle() const; /** * Query whether the currently display mode is secure text entry or not. @@ -260,7 +260,7 @@ class CC_DLL TextFieldTTF : public Label, public IMEDelegate virtual void didDetachWithIME() override; virtual void insertText(const char* text, size_t len) override; virtual void deleteBackward() override; - virtual const std::string& getContentText() override; + virtual std::string_view getContentText() override; virtual void controlKey(EventKeyboard::KeyCode keyCode) override; TextFieldDelegate* _delegate; diff --git a/cocos/2d/CCTileMapAtlas.cpp b/cocos/2d/CCTileMapAtlas.cpp index 987d598f7e87..f0ca242ed4d8 100644 --- a/cocos/2d/CCTileMapAtlas.cpp +++ b/cocos/2d/CCTileMapAtlas.cpp @@ -36,7 +36,7 @@ NS_CC_BEGIN // implementation TileMapAtlas -TileMapAtlas* TileMapAtlas::create(const std::string& tile, const std::string& mapFile, int tileWidth, int tileHeight) +TileMapAtlas* TileMapAtlas::create(std::string_view tile, std::string_view mapFile, int tileWidth, int tileHeight) { TileMapAtlas* ret = new TileMapAtlas(); if (ret->initWithTileFile(tile, mapFile, tileWidth, tileHeight)) @@ -48,7 +48,7 @@ TileMapAtlas* TileMapAtlas::create(const std::string& tile, const std::string& m return nullptr; } -bool TileMapAtlas::initWithTileFile(const std::string& tile, const std::string& mapFile, int tileWidth, int tileHeight) +bool TileMapAtlas::initWithTileFile(std::string_view tile, std::string_view mapFile, int tileWidth, int tileHeight) { this->loadTGAfile(mapFile); this->calculateItemsToRender(); @@ -100,7 +100,7 @@ void TileMapAtlas::calculateItemsToRender() } } -void TileMapAtlas::loadTGAfile(const std::string& file) +void TileMapAtlas::loadTGAfile(std::string_view file) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(file); diff --git a/cocos/2d/CCTileMapAtlas.h b/cocos/2d/CCTileMapAtlas.h index 711f9e13990b..b5adc261e2d1 100644 --- a/cocos/2d/CCTileMapAtlas.h +++ b/cocos/2d/CCTileMapAtlas.h @@ -59,7 +59,7 @@ class CC_DLL TileMapAtlas : public AtlasNode /** creates a TileMap with a tile file (atlas) with a map file and the width and height of each tile in points. The tile file will be loaded using the TextureMgr. */ - static TileMapAtlas* create(const std::string& tile, const std::string& mapFile, int tileWidth, int tileHeight); + static TileMapAtlas* create(std::string_view tile, std::string_view mapFile, int tileWidth, int tileHeight); /** * @js ctor */ @@ -73,7 +73,7 @@ class CC_DLL TileMapAtlas : public AtlasNode /** initializes a TileMap with a tile file (atlas) with a map file and the width and height of each tile in points. The file will be loaded using the TextureMgr. */ - bool initWithTileFile(const std::string& tile, const std::string& mapFile, int tileWidth, int tileHeight); + bool initWithTileFile(std::string_view tile, std::string_view mapFile, int tileWidth, int tileHeight); /** * Returns a tile from position x,y. *For the moment only channel R is used @@ -100,7 +100,7 @@ class CC_DLL TileMapAtlas : public AtlasNode void setTGAInfo(struct sImageTGA* TGAInfo) { _TGAInfo = TGAInfo; } protected: - void loadTGAfile(const std::string& file); + void loadTGAfile(std::string_view file); void calculateItemsToRender(); void updateAtlasValueAt(const Vec2& pos, const Color3B& value, int index); void updateAtlasValues(); diff --git a/cocos/3d/CCAnimate3D.cpp b/cocos/3d/CCAnimate3D.cpp index 7ad77b1ce53d..a192bbd1bfc7 100644 --- a/cocos/3d/CCAnimate3D.cpp +++ b/cocos/3d/CCAnimate3D.cpp @@ -128,9 +128,9 @@ Animate3D* Animate3D::reverse() const return animate; } -Node* findChildByNameRecursively(Node* node, const std::string& childName) +Node* findChildByNameRecursively(Node* node, std::string_view childName) { - const std::string& name = node->getName(); + std::string_view name = node->getName(); if (name == childName) return node; @@ -162,11 +162,11 @@ void Animate3D::startWithTarget(Node* target) { if (_animation) { - const std::unordered_map& boneCurves = _animation->getBoneCurves(); + auto& boneCurves = _animation->getBoneCurves(); for (const auto& iter : boneCurves) { - const std::string& boneName = iter.first; - auto skin = sprite->getSkeleton(); + std::string_view boneName = iter.first; + auto skin = sprite->getSkeleton(); if (skin) { auto bone = skin->getBoneByName(boneName); @@ -200,11 +200,11 @@ void Animate3D::startWithTarget(Node* target) } else { - const std::unordered_map& boneCurves = _animation->getBoneCurves(); + auto& boneCurves = _animation->getBoneCurves(); for (const auto& iter : boneCurves) { - const std::string& boneName = iter.first; - Node* node = nullptr; + std::string_view boneName = iter.first; + Node* node = nullptr; if (target->getName() == boneName) node = target; else diff --git a/cocos/3d/CCAnimation3D.cpp b/cocos/3d/CCAnimation3D.cpp index 7657842afd36..7407b218871c 100644 --- a/cocos/3d/CCAnimation3D.cpp +++ b/cocos/3d/CCAnimation3D.cpp @@ -29,11 +29,11 @@ NS_CC_BEGIN -Animation3D* Animation3D::create(const std::string& fileName, const std::string& animationName) +Animation3D* Animation3D::create(std::string_view fileName, std::string_view animationName) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(fileName); - std::string key = fullPath + "#" + animationName; - auto animation = Animation3DCache::getInstance()->getAnimation(key); + fullPath.append("#").append(animationName); + auto animation = Animation3DCache::getInstance()->getAnimation(fullPath); if (animation != nullptr) return animation; @@ -50,7 +50,7 @@ Animation3D* Animation3D::create(const std::string& fileName, const std::string& return animation; } -bool Animation3D::initWithFile(const std::string& filename, const std::string& animationName) +bool Animation3D::initWithFile(std::string_view filename, std::string_view animationName) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename); @@ -59,8 +59,8 @@ bool Animation3D::initWithFile(const std::string& filename, const std::string& a Animation3DData animationdata; if (bundle->load(fullPath) && bundle->loadAnimationData(animationName, &animationdata) && init(animationdata)) { - std::string key = fullPath + "#" + animationName; - Animation3DCache::getInstance()->addAnimation(key, this); + fullPath.append("#").append(animationName); + Animation3DCache::getInstance()->addAnimation(fullPath, this); Bundle3D::destroyBundle(bundle); return true; } @@ -70,7 +70,7 @@ bool Animation3D::initWithFile(const std::string& filename, const std::string& a return false; } -Animation3D::Curve* Animation3D::getBoneCurveByName(const std::string& name) const +Animation3D::Curve* Animation3D::getBoneCurveByName(std::string_view name) const { auto it = _boneCurves.find(name); if (it != _boneCurves.end()) @@ -199,7 +199,7 @@ void Animation3DCache::destroyInstance() CC_SAFE_DELETE(_cacheInstance); } -Animation3D* Animation3DCache::getAnimation(const std::string& key) +Animation3D* Animation3DCache::getAnimation(std::string_view key) { auto it = _animations.find(key); if (it != _animations.end()) @@ -207,14 +207,14 @@ Animation3D* Animation3DCache::getAnimation(const std::string& key) return nullptr; } -void Animation3DCache::addAnimation(const std::string& key, Animation3D* animation) +void Animation3DCache::addAnimation(std::string_view key, Animation3D* animation) { const auto& it = _animations.find(key); if (it != _animations.end()) { return; // already have this key } - _animations[key] = animation; + _animations.emplace(key, animation); //_animations[key] = animation; animation->retain(); } diff --git a/cocos/3d/CCAnimation3D.h b/cocos/3d/CCAnimation3D.h index 80f528ae2702..64b1302d83ee 100644 --- a/cocos/3d/CCAnimation3D.h +++ b/cocos/3d/CCAnimation3D.h @@ -69,7 +69,7 @@ class CC_DLL Animation3D : public Ref }; /**read all animation or only the animation with given animationName? animationName == "" read the first.*/ - static Animation3D* create(const std::string& filename, const std::string& animationName = ""); + static Animation3D* create(std::string_view filename, std::string_view animationName = ""); /**get duration*/ float getDuration() const { return _duration; } @@ -79,10 +79,10 @@ class CC_DLL Animation3D : public Ref * * @lua NA */ - Curve* getBoneCurveByName(const std::string& name) const; + Curve* getBoneCurveByName(std::string_view name) const; /**get the bone Curves set*/ - const std::unordered_map& getBoneCurves() const { return _boneCurves; } + const hlookup::string_map& getBoneCurves() const { return _boneCurves; } CC_CONSTRUCTOR_ACCESS : Animation3D(); virtual ~Animation3D(); @@ -90,10 +90,10 @@ class CC_DLL Animation3D : public Ref bool init(const Animation3DData& data); /**init Animation3D with file name and animation name*/ - bool initWithFile(const std::string& filename, const std::string& animationName); + bool initWithFile(std::string_view filename, std::string_view animationName); protected: - std::unordered_map _boneCurves; // bone curves map, key bone name, value AnimationCurve + hlookup::string_map _boneCurves; // bone curves map, key bone name, value AnimationCurve float _duration; // animation duration }; @@ -109,10 +109,10 @@ class Animation3DCache static void destroyInstance(); /**get animation by key*/ - Animation3D* getAnimation(const std::string& key); + Animation3D* getAnimation(std::string_view key); /**add animation to cache*/ - void addAnimation(const std::string& key, Animation3D* animation); + void addAnimation(std::string_view key, Animation3D* animation); /**remove all animation*/ void removeAllAnimations(); @@ -125,7 +125,7 @@ class Animation3DCache static Animation3DCache* _cacheInstance; // cache instance - std::unordered_map _animations; // cached animations + hlookup::string_map _animations; // cached animations }; // end of 3d group diff --git a/cocos/3d/CCBillBoard.cpp b/cocos/3d/CCBillBoard.cpp index 427d262a4c72..5eaba2dbb015 100644 --- a/cocos/3d/CCBillBoard.cpp +++ b/cocos/3d/CCBillBoard.cpp @@ -53,7 +53,7 @@ BillBoard* BillBoard::createWithTexture(Texture2D* texture, Mode mode) return nullptr; } -BillBoard* BillBoard::create(const std::string& filename, Mode mode) +BillBoard* BillBoard::create(std::string_view filename, Mode mode) { BillBoard* billboard = new BillBoard(); if (billboard->initWithFile(filename)) @@ -66,7 +66,7 @@ BillBoard* BillBoard::create(const std::string& filename, Mode mode) return nullptr; } -BillBoard* BillBoard::create(const std::string& filename, const Rect& rect, Mode mode) +BillBoard* BillBoard::create(std::string_view filename, const Rect& rect, Mode mode) { BillBoard* billboard = new BillBoard(); if (billboard->initWithFile(filename, rect)) diff --git a/cocos/3d/CCBillBoard.h b/cocos/3d/CCBillBoard.h index 4eef5d257a16..2f3237023571 100644 --- a/cocos/3d/CCBillBoard.h +++ b/cocos/3d/CCBillBoard.h @@ -63,7 +63,7 @@ class CC_DLL BillBoard : public Sprite * @param filename A path to image file, e.g., "scene1/monster.png" * @return An autoreleased BillBoard object. */ - static BillBoard* create(const std::string& filename, Mode mode = Mode::VIEW_POINT_ORIENTED); + static BillBoard* create(std::string_view filename, Mode mode = Mode::VIEW_POINT_ORIENTED); /** * Creates a BillBoard with an image filename and a rect. @@ -72,7 +72,7 @@ class CC_DLL BillBoard : public Sprite * @param rect A subrect of the image file * @return An autoreleased BillBoard object */ - static BillBoard* create(const std::string& filename, const Rect& rect, Mode mode = Mode::VIEW_POINT_ORIENTED); + static BillBoard* create(std::string_view filename, const Rect& rect, Mode mode = Mode::VIEW_POINT_ORIENTED); /** * Creates a BillBoard with a Texture2D object. diff --git a/cocos/3d/CCBundle3D.cpp b/cocos/3d/CCBundle3D.cpp index d735f5f39d2d..2f18d15daa71 100644 --- a/cocos/3d/CCBundle3D.cpp +++ b/cocos/3d/CCBundle3D.cpp @@ -169,7 +169,7 @@ void Bundle3D::clear() } } -bool Bundle3D::load(const std::string& path) +bool Bundle3D::load(std::string_view path) { if (path.empty()) return false; @@ -193,7 +193,7 @@ bool Bundle3D::load(const std::string& path) } else { - CCLOG("warning: %s is invalid file formate", path.c_str()); + CCLOG("warning: %s is invalid file formate", path.data()); } ret ? (_path = path) : (_path = ""); @@ -204,7 +204,7 @@ bool Bundle3D::load(const std::string& path) bool Bundle3D::loadObj(MeshDatas& meshdatas, MaterialDatas& materialdatas, NodeDatas& nodedatas, - const std::string& fullPath, + std::string_view fullPath, const char* mtl_basepath) { meshdatas.resetData(); @@ -219,7 +219,7 @@ bool Bundle3D::loadObj(MeshDatas& meshdatas, std::vector shapes; std::vector materials; - auto ret = tinyobj::LoadObj(shapes, materials, fullPath.c_str(), mtlPath.c_str()); + auto ret = tinyobj::LoadObj(shapes, materials, fullPath.data(), mtlPath.c_str()); if (ret.empty()) { // fill data @@ -329,11 +329,11 @@ bool Bundle3D::loadObj(MeshDatas& meshdatas, return true; } - CCLOG("warning: load %s file error: %s", fullPath.c_str(), ret.c_str()); + CCLOG("warning: load %s file error: %s", fullPath.data(), ret.c_str()); return false; } -bool Bundle3D::loadSkinData(const std::string& /*id*/, SkinData* skindata) +bool Bundle3D::loadSkinData(std::string_view /*id*/, SkinData* skindata) { skindata->resetData(); @@ -347,7 +347,7 @@ bool Bundle3D::loadSkinData(const std::string& /*id*/, SkinData* skindata) } } -bool Bundle3D::loadAnimationData(const std::string& id, Animation3DData* animationdata) +bool Bundle3D::loadAnimationData(std::string_view id, Animation3DData* animationdata) { animationdata->resetData(); @@ -1062,7 +1062,7 @@ bool Bundle3D::loadMaterialsJson(MaterialDatas& materialdatas) } return true; } -bool Bundle3D::loadJson(const std::string& path) +bool Bundle3D::loadJson(std::string_view path) { clear(); @@ -1084,7 +1084,7 @@ bool Bundle3D::loadJson(const std::string& path) return true; } -bool Bundle3D::loadBinary(const std::string& path) +bool Bundle3D::loadBinary(std::string_view path) { clear(); @@ -1094,7 +1094,7 @@ bool Bundle3D::loadBinary(const std::string& path) if (_binaryBuffer.isNull()) { clear(); - CCLOG("warning: Failed to read file: %s", path.c_str()); + CCLOG("warning: Failed to read file: %s", path.data()); return false; } @@ -1107,7 +1107,7 @@ bool Bundle3D::loadBinary(const std::string& path) if (_binaryReader.read(sig, 1, 4) != 4 || memcmp(sig, identifier, 4) != 0) { clear(); - CCLOG("warning: Invalid identifier: %s", path.c_str()); + CCLOG("warning: Invalid identifier: %s", path.data()); return false; } @@ -1127,7 +1127,7 @@ bool Bundle3D::loadBinary(const std::string& path) if (_binaryReader.read(&_referenceCount, 4, 1) != 1) { clear(); - CCLOG("warning: Failed to read ref table size '%s'.", path.c_str()); + CCLOG("warning: Failed to read ref table size '%s'.", path.data()); return false; } @@ -1141,7 +1141,7 @@ bool Bundle3D::loadBinary(const std::string& path) _binaryReader.read(&_references[i].offset, 4, 1) != 1) { clear(); - CCLOG("warning: Failed to read ref number %u for bundle '%s'.", i, path.c_str()); + CCLOG("warning: Failed to read ref number %u for bundle '%s'.", i, path.data()); CC_SAFE_DELETE_ARRAY(_references); return false; } @@ -1460,7 +1460,7 @@ bool loadMaterialDataJson_0_2(MaterialData* /*materialdata*/) return true; } -bool Bundle3D::loadAnimationDataJson(const std::string& id, Animation3DData* animationdata) +bool Bundle3D::loadAnimationDataJson(std::string_view id, Animation3DData* animationdata) { std::string anim = ""; if (_version == "1.2" || _version == "0.2") @@ -1549,7 +1549,7 @@ bool Bundle3D::loadAnimationDataJson(const std::string& id, Animation3DData* ani return true; } -bool Bundle3D::loadAnimationDataBinary(const std::string& id, Animation3DData* animationdata) +bool Bundle3D::loadAnimationDataBinary(std::string_view id, Animation3DData* animationdata) { if (_version == "0.1" || _version == "0.2" || _version == "0.3" || _version == "0.4") @@ -1560,9 +1560,9 @@ bool Bundle3D::loadAnimationDataBinary(const std::string& id, Animation3DData* a else { // if id is not a null string, we need to add a suffix of "animation" for seeding. - std::string id_ = id; - if (id != "") - id_ = id + "animation"; + std::string id_{id}; + if (!id.empty()) + id_.append("animation"); if (!seekToFirstType(BUNDLE_TYPE_ANIMATIONS, id_)) return false; @@ -1998,7 +1998,7 @@ NodeData* Bundle3D::parseNodesRecursivelyBinary(bool& skeleton, bool singleSprit return nodedata; } -backend::VertexFormat Bundle3D::parseGLDataType(const std::string& str, int size) +backend::VertexFormat Bundle3D::parseGLDataType(std::string_view str, int size) { backend::VertexFormat ret = backend::VertexFormat::INT; if (str == "GL_BYTE") @@ -2097,7 +2097,7 @@ backend::VertexFormat Bundle3D::parseGLDataType(const std::string& str, int size return ret; } -backend::SamplerAddressMode Bundle3D::parseSamplerAddressMode(const std::string& str) +backend::SamplerAddressMode Bundle3D::parseSamplerAddressMode(std::string_view str) { if (str == "REPEAT") @@ -2115,7 +2115,7 @@ backend::SamplerAddressMode Bundle3D::parseSamplerAddressMode(const std::string& } } -NTextureData::Usage Bundle3D::parseGLTextureType(const std::string& str) +NTextureData::Usage Bundle3D::parseGLTextureType(std::string_view str) { if (str == "AMBIENT") { @@ -2163,7 +2163,7 @@ NTextureData::Usage Bundle3D::parseGLTextureType(const std::string& str) return NTextureData::Usage::Unknown; } } -shaderinfos::VertexKey Bundle3D::parseGLProgramAttribute(const std::string& str) +shaderinfos::VertexKey Bundle3D::parseGLProgramAttribute(std::string_view str) { if (str == "VERTEX_ATTRIB_POSITION") { @@ -2233,14 +2233,14 @@ shaderinfos::VertexKey Bundle3D::parseGLProgramAttribute(const std::string& str) } } -void Bundle3D::getModelRelativePath(const std::string& path) +void Bundle3D::getModelRelativePath(std::string_view path) { ssize_t index = path.find_last_of('/'); std::string fullModelPath; _modelPath = path.substr(0, index + 1); } -Reference* Bundle3D::seekToFirstType(unsigned int type, const std::string& id) +Reference* Bundle3D::seekToFirstType(unsigned int type, std::string_view id) { // for each Reference for (unsigned int i = 0; i < _referenceCount; ++i) @@ -2266,7 +2266,7 @@ Reference* Bundle3D::seekToFirstType(unsigned int type, const std::string& id) return nullptr; } -std::vector Bundle3D::getTrianglesList(const std::string& path) +std::vector Bundle3D::getTrianglesList(std::string_view path) { std::vector trianglesList; diff --git a/cocos/3d/CCBundle3D.h b/cocos/3d/CCBundle3D.h index 1a92eeb20d91..6fb3d760a13e 100644 --- a/cocos/3d/CCBundle3D.h +++ b/cocos/3d/CCBundle3D.h @@ -64,32 +64,32 @@ class CC_DLL Bundle3D * get define data type * @param str The type in string */ - static backend::VertexFormat parseGLDataType(const std::string& str, int size); + static backend::VertexFormat parseGLDataType(std::string_view str, int size); /** * get define data type * @param str The type in string */ - static backend::SamplerAddressMode parseSamplerAddressMode(const std::string& str); + static backend::SamplerAddressMode parseSamplerAddressMode(std::string_view str); /** * load a file. You must load a file first, then call loadMeshData, loadSkinData, and so on * @param path File to be loaded * @return result of load */ - virtual bool load(const std::string& path); + virtual bool load(std::string_view path); /** * load skin data from bundle * @param id The ID of the skin, load the first Skin in the bundle if it is empty */ - virtual bool loadSkinData(const std::string& id, SkinData* skindata); + virtual bool loadSkinData(std::string_view id, SkinData* skindata); /** * load material data from bundle * @param id The ID of the animation, load the first animation in the bundle if it is empty */ - virtual bool loadAnimationData(const std::string& id, Animation3DData* animationdata); + virtual bool loadAnimationData(std::string_view id, Animation3DData* animationdata); // since 3.3, to support reskin virtual bool loadMeshDatas(MeshDatas& meshdatas); @@ -102,21 +102,21 @@ class CC_DLL Bundle3D * load triangle list * @param path the file path to load */ - static std::vector getTrianglesList(const std::string& path); + static std::vector getTrianglesList(std::string_view path); // load .obj file static bool loadObj(MeshDatas& meshdatas, MaterialDatas& materialdatas, NodeDatas& nodedatas, - const std::string& fullPath, + std::string_view fullPath, const char* mtl_basepath = nullptr); // calculate aabb static AABB calculateAABB(const std::vector& vertex, int stride, const std::vector& index); protected: - bool loadJson(const std::string& path); - bool loadBinary(const std::string& path); + bool loadJson(std::string_view path); + bool loadBinary(std::string_view path); bool loadMeshDatasJson(MeshDatas& meshdatas); bool loadMeshDataJson_0_1(MeshDatas& meshdatas); bool loadMeshDataJson_0_2(MeshDatas& meshdatas); @@ -137,8 +137,8 @@ class CC_DLL Bundle3D bool loadMaterialDataJson(MaterialData* materialdata); bool loadMaterialDataJson_0_1(MaterialData* materialdata); bool loadMaterialDataJson_0_2(MaterialData* materialdata); - bool loadAnimationDataJson(const std::string& id, Animation3DData* animationdata); - bool loadAnimationDataBinary(const std::string& id, Animation3DData* animationdata); + bool loadAnimationDataJson(std::string_view id, Animation3DData* animationdata); + bool loadAnimationDataBinary(std::string_view id, Animation3DData* animationdata); /** * load nodes of json @@ -156,26 +156,26 @@ class CC_DLL Bundle3D * get define data type * @param str The type in string */ - NTextureData::Usage parseGLTextureType(const std::string& str); + NTextureData::Usage parseGLTextureType(std::string_view str); /** * get vertex attribute type * @param str The type in string */ - shaderinfos::VertexKey parseGLProgramAttribute(const std::string& str); + shaderinfos::VertexKey parseGLProgramAttribute(std::string_view str); /* * get model path * @param str Full path of model file */ - void getModelRelativePath(const std::string& path); + void getModelRelativePath(std::string_view path); /* * set the read position in buffer to the target type * @param The data type * @param The data id */ - Reference* seekToFirstType(unsigned int type, const std::string& id = ""); + Reference* seekToFirstType(unsigned int type, std::string_view id = ""); CC_CONSTRUCTOR_ACCESS : Bundle3D(); virtual ~Bundle3D(); diff --git a/cocos/3d/CCBundle3DData.h b/cocos/3d/CCBundle3DData.h index 2f54bdfcf2af..25382094583d 100644 --- a/cocos/3d/CCBundle3DData.h +++ b/cocos/3d/CCBundle3DData.h @@ -220,21 +220,21 @@ struct SkinData rootBoneIndex = -1; } - void addSkinBoneNames(const std::string& name) + void addSkinBoneNames(std::string_view name) { auto it = std::find(skinBoneNames.begin(), skinBoneNames.end(), name); if (it == skinBoneNames.end()) - skinBoneNames.push_back(name); + skinBoneNames.push_back(std::string{name}); } - void addNodeBoneNames(const std::string& name) + void addNodeBoneNames(std::string_view name) { auto it = std::find(nodeBoneNames.begin(), nodeBoneNames.end(), name); if (it == nodeBoneNames.end()) - nodeBoneNames.push_back(name); + nodeBoneNames.push_back(std::string{name}); } - int getSkinBoneNameIndex(const std::string& name) const + int getSkinBoneNameIndex(std::string_view name) const { int i = 0; for (const auto& iter : skinBoneNames) @@ -246,7 +246,7 @@ struct SkinData return -1; } - int getBoneNameIndex(const std::string& name) const + int getBoneNameIndex(std::string_view name) const { int i = 0; for (const auto& iter : skinBoneNames) @@ -323,7 +323,7 @@ struct MaterialDatas { std::vector materials; void resetData() { materials.clear(); } - const NMaterialData* getMaterialData(const std::string& materialid) const + const NMaterialData* getMaterialData(std::string_view materialid) const { for (const auto& it : materials) { diff --git a/cocos/3d/CCMesh.cpp b/cocos/3d/CCMesh.cpp index 92a9434da0c9..3a2478849907 100644 --- a/cocos/3d/CCMesh.cpp +++ b/cocos/3d/CCMesh.cpp @@ -228,7 +228,7 @@ Mesh* Mesh::create(const std::vector& vertices, return create("", indexData); } -Mesh* Mesh::create(const std::string& name, MeshIndexData* indexData, MeshSkin* skin) +Mesh* Mesh::create(std::string_view name, MeshIndexData* indexData, MeshSkin* skin) { auto state = new Mesh(); state->autorelease(); @@ -255,7 +255,7 @@ bool Mesh::isVisible() const return _visible; } -void Mesh::setTexture(const std::string& texPath) +void Mesh::setTexture(std::string_view texPath) { _texFile = texPath; auto tex = Director::getInstance()->getTextureCache()->addImage(texPath); @@ -307,7 +307,7 @@ void Mesh::setTexture(Texture2D* tex, NTextureData::Usage usage, bool cacheFileN } } -void Mesh::setTexture(const std::string& texPath, NTextureData::Usage usage) +void Mesh::setTexture(std::string_view texPath, NTextureData::Usage usage) { auto tex = Director::getInstance()->getTextureCache()->addImage(texPath); setTexture(tex, usage); @@ -350,7 +350,7 @@ void Mesh::setMaterial(Material* material) if (_material->getTechnique()->getName().compare(technique->getName()) == 0) { auto program = pass->getProgramState()->getProgram(); - auto& attributes = program->getActiveAttributes(); + auto attributes = program->getActiveAttributes(); auto meshVertexData = _meshIndexData->getMeshVertexData(); auto attributeCount = meshVertexData->getMeshVertexAttribCount(); CCASSERT(attributes.size() <= attributeCount, "missing attribute data"); diff --git a/cocos/3d/CCMesh.h b/cocos/3d/CCMesh.h index bbd9610b7ac7..3f8490edca82 100644 --- a/cocos/3d/CCMesh.h +++ b/cocos/3d/CCMesh.h @@ -83,7 +83,7 @@ class CC_DLL Mesh : public Ref * create mesh * @lua NA */ - static Mesh* create(const std::string& name, MeshIndexData* indexData, MeshSkin* skin = nullptr); + static Mesh* create(std::string_view name, MeshIndexData* indexData, MeshSkin* skin = nullptr); /** * get vertex buffer @@ -109,7 +109,7 @@ class CC_DLL Mesh : public Ref * call setTexture(texPath, NTextureData::Usage::Diffuse) * @param texPath texture path */ - void setTexture(const std::string& texPath); + void setTexture(std::string_view texPath); /** * set texture (diffuse), which is responsible for the main appearance. It is also means main texture, you can also * call setTexture(texPath, NTextureData::Usage::Diffuse) @@ -128,7 +128,7 @@ class CC_DLL Mesh : public Ref * @param texPath texture path * @param usage Usage of this texture */ - void setTexture(const std::string& texPath, NTextureData::Usage usage); + void setTexture(std::string_view texPath, NTextureData::Usage usage); /** * Get texture (diffuse), which is responsible for the main appearance. It is also means main texture, you can also * call getTexture(NTextureData::Usage::Diffuse) @@ -168,7 +168,7 @@ class CC_DLL Mesh : public Ref backend::ProgramState* getProgramState() const; /**name getter */ - const std::string& getName() const { return _name; } + std::string_view getName() const { return _name; } void setBlendFunc(const BlendFunc& blendFunc); const BlendFunc& getBlendFunc() const; @@ -225,7 +225,7 @@ class CC_DLL Mesh : public Ref /**Mesh index data setter*/ void setMeshIndexData(MeshIndexData* indexdata); /**name setter*/ - void setName(const std::string& name) { _name = name; } + void setName(std::string_view name) { _name = name; } /** * calculate the AABB of the mesh diff --git a/cocos/3d/CCMeshSkin.cpp b/cocos/3d/CCMeshSkin.cpp index 903ff6cc7b87..868aa50e088b 100644 --- a/cocos/3d/CCMeshSkin.cpp +++ b/cocos/3d/CCMeshSkin.cpp @@ -75,7 +75,7 @@ Bone3D* MeshSkin::getBoneByIndex(unsigned int index) const return nullptr; } -Bone3D* MeshSkin::getBoneByName(const std::string& id) const +Bone3D* MeshSkin::getBoneByName(std::string_view id) const { // search from skin bones for (const auto& it : _skinBones) diff --git a/cocos/3d/CCMeshSkin.h b/cocos/3d/CCMeshSkin.h index 13df17857297..3533f113376d 100644 --- a/cocos/3d/CCMeshSkin.h +++ b/cocos/3d/CCMeshSkin.h @@ -54,7 +54,7 @@ class CC_DLL MeshSkin : public Ref public: /**create a new meshskin if do not want to share meshskin*/ - static MeshSkin* create(Skeleton3D* skeleton, const std::string& filename, const std::string& name); + static MeshSkin* create(Skeleton3D* skeleton, std::string_view filename, std::string_view name); static MeshSkin* create(Skeleton3D* skeleton, const std::vector& boneNames, @@ -65,7 +65,7 @@ class CC_DLL MeshSkin : public Ref /**get bone*/ Bone3D* getBoneByIndex(unsigned int index) const; - Bone3D* getBoneByName(const std::string& id) const; + Bone3D* getBoneByName(std::string_view id) const; /**get bone index*/ int getBoneIndex(Bone3D* bone) const; diff --git a/cocos/3d/CCMeshVertexIndexData.cpp b/cocos/3d/CCMeshVertexIndexData.cpp index 0f4c7308594d..3e0544022d3c 100644 --- a/cocos/3d/CCMeshVertexIndexData.cpp +++ b/cocos/3d/CCMeshVertexIndexData.cpp @@ -49,7 +49,7 @@ using namespace std; NS_CC_BEGIN ///////////////////////////////////////////////////////////////////////////////////////////////////////////// -MeshIndexData* MeshIndexData::create(const std::string& id, +MeshIndexData* MeshIndexData::create(std::string_view id, MeshVertexData* vertexData, backend::Buffer* indexbuffer, const AABB& aabb) @@ -160,7 +160,7 @@ MeshVertexData* MeshVertexData::create(const MeshData& meshdata) return vertexdata; } -MeshIndexData* MeshVertexData::getMeshIndexDataById(const std::string& id) const +MeshIndexData* MeshVertexData::getMeshIndexDataById(std::string_view id) const { for (auto it : _indexs) { diff --git a/cocos/3d/CCMeshVertexIndexData.h b/cocos/3d/CCMeshVertexIndexData.h index a65a9ab64105..ef68b9455cdf 100644 --- a/cocos/3d/CCMeshVertexIndexData.h +++ b/cocos/3d/CCMeshVertexIndexData.h @@ -55,7 +55,7 @@ class CC_DLL MeshIndexData : public Ref { public: /** create */ - static MeshIndexData* create(const std::string& id, + static MeshIndexData* create(std::string_view id, MeshVertexData* vertexData, backend::Buffer* indexbuffer, const AABB& aabb); @@ -74,8 +74,8 @@ class CC_DLL MeshIndexData : public Ref const AABB& getAABB() const { return _aabb; } /** id setter and getter */ - void setId(const std::string& id) { _id = id; } - const std::string& getId() const { return _id; } + void setId(std::string_view id) { _id = id; } + std::string_view getId() const { return _id; } /**primitive type setter & getter*/ MeshCommand::PrimitiveType getPrimitiveType() const { return _primitiveType; } @@ -128,7 +128,7 @@ class CC_DLL MeshVertexData : public Ref /** get index data by index */ MeshIndexData* getMeshIndexDataByIndex(int index) const { return _indexs.at(index); } /** get index data by id */ - MeshIndexData* getMeshIndexDataById(const std::string& id) const; + MeshIndexData* getMeshIndexDataById(std::string_view id) const; ssize_t getSizePerVertex() const { return _sizePerVertex; } diff --git a/cocos/3d/CCMotionStreak3D.cpp b/cocos/3d/CCMotionStreak3D.cpp index e7ca8d32df9b..6337c9fd6668 100644 --- a/cocos/3d/CCMotionStreak3D.cpp +++ b/cocos/3d/CCMotionStreak3D.cpp @@ -61,7 +61,7 @@ MotionStreak3D* MotionStreak3D::create(float fade, float minSeg, float stroke, const Color3B& color, - const std::string& path) + std::string_view path) { MotionStreak3D* ret = new MotionStreak3D(); if (ret && ret->initWithFade(fade, minSeg, stroke, color, path)) @@ -87,7 +87,7 @@ MotionStreak3D* MotionStreak3D::create(float fade, float minSeg, float stroke, c return nullptr; } -bool MotionStreak3D::initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path) +bool MotionStreak3D::initWithFade(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path) { CCASSERT(!path.empty(), "Invalid filename"); diff --git a/cocos/3d/CCMotionStreak3D.h b/cocos/3d/CCMotionStreak3D.h index 6b020a02cd6a..dc7e072e3c45 100644 --- a/cocos/3d/CCMotionStreak3D.h +++ b/cocos/3d/CCMotionStreak3D.h @@ -57,11 +57,7 @@ class CC_DLL MotionStreak3D : public Node, public TextureProtocol * @param path The texture file name of stoke. * @return An autoreleased MotionStreak3D object. */ - static MotionStreak3D* create(float fade, - float minSeg, - float stroke, - const Color3B& color, - const std::string& path); + static MotionStreak3D* create(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path); /** Creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture. * * @param fade The fade time, in seconds. @@ -164,7 +160,7 @@ class CC_DLL MotionStreak3D : public Node, public TextureProtocol /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture filename */ - bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path); + bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, std::string_view path); /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture */ bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture); diff --git a/cocos/3d/CCObjLoader.cpp b/cocos/3d/CCObjLoader.cpp index 4d78b5d4750a..b3f0935f86ee 100644 --- a/cocos/3d/CCObjLoader.cpp +++ b/cocos/3d/CCObjLoader.cpp @@ -395,7 +395,7 @@ static bool exportFaceGroupToShape(shape_t& shape, const std::vector& in_texcoords, const std::vector>& faceGroup, const int material_id, - const std::string& name, + std::string_view name, bool clearCache) { if (faceGroup.empty()) @@ -517,7 +517,7 @@ std::string LoadMtl(std::map& material_map, char namebuf[TINYOBJ_SSCANF_BUFFER_SIZE]; token += 7; #ifdef _MSC_VER - sscanf_s(token, "%s", namebuf, _countof(namebuf)); + sscanf_s(token, "%s", namebuf, static_cast(_countof(namebuf))); #else sscanf(token, "%s", namebuf); #endif @@ -681,7 +681,7 @@ std::string LoadMtl(std::map& material_map, return err.str(); } -std::string MaterialFileReader::operator()(const std::string& matId, +std::string MaterialFileReader::operator()(std::string_view matId, std::vector& materials, std::map& matMap) { @@ -689,7 +689,7 @@ std::string MaterialFileReader::operator()(const std::string& matId, if (!m_mtlBasePath.empty()) { - filepath = std::string(m_mtlBasePath) + matId; + filepath.append(m_mtlBasePath).append(matId); } else { diff --git a/cocos/3d/CCObjLoader.h b/cocos/3d/CCObjLoader.h index ef0dde2912b0..af64222dc36d 100644 --- a/cocos/3d/CCObjLoader.h +++ b/cocos/3d/CCObjLoader.h @@ -75,7 +75,7 @@ class MaterialReader MaterialReader() {} virtual ~MaterialReader() {} - virtual std::string operator()(const std::string& matId, + virtual std::string operator()(std::string_view matId, std::vector& materials, std::map& matMap) = 0; }; @@ -83,9 +83,9 @@ class MaterialReader class MaterialFileReader : public MaterialReader { public: - MaterialFileReader(const std::string& mtl_basepath) : m_mtlBasePath(mtl_basepath) {} + MaterialFileReader(std::string_view mtl_basepath) : m_mtlBasePath(mtl_basepath) {} virtual ~MaterialFileReader() {} - virtual std::string operator()(const std::string& matId, + virtual std::string operator()(std::string_view matId, std::vector& materials, std::map& matMap); diff --git a/cocos/3d/CCSkeleton3D.cpp b/cocos/3d/CCSkeleton3D.cpp index 4bf8763fbada..7aa8d6a386f2 100644 --- a/cocos/3d/CCSkeleton3D.cpp +++ b/cocos/3d/CCSkeleton3D.cpp @@ -136,7 +136,7 @@ void Bone3D::clearBoneBlendState() /** * Creates C3DBone. */ -Bone3D* Bone3D::create(const std::string& id) +Bone3D* Bone3D::create(std::string_view id) { auto bone = new Bone3D(id); bone->autorelease(); @@ -185,7 +185,7 @@ void Bone3D::removeAllChildBone() _children.clear(); } -Bone3D::Bone3D(const std::string& id) : _name(id), _parent(nullptr), _worldDirty(true) {} +Bone3D::Bone3D(std::string_view id) : _name(id), _parent(nullptr), _worldDirty(true) {} Bone3D::~Bone3D() { @@ -279,7 +279,7 @@ Bone3D* Skeleton3D::getBoneByIndex(unsigned int index) const return nullptr; } -Bone3D* Skeleton3D::getBoneByName(const std::string& id) const +Bone3D* Skeleton3D::getBoneByName(std::string_view id) const { // search from bones for (auto it : _bones) diff --git a/cocos/3d/CCSkeleton3D.h b/cocos/3d/CCSkeleton3D.h index e63a06050cce..bd13a8a95998 100644 --- a/cocos/3d/CCSkeleton3D.h +++ b/cocos/3d/CCSkeleton3D.h @@ -61,7 +61,7 @@ class CC_DLL Bone3D : public Ref const Mat4& getWorldMat(); /**get bone name*/ - const std::string& getName() const { return _name; } + std::string_view getName() const { return _name; } /** * set animation value @@ -78,7 +78,7 @@ class CC_DLL Bone3D : public Ref /** * Creates C3DBone. */ - static Bone3D* create(const std::string& id); + static Bone3D* create(std::string_view id); /** * Sets the inverse bind pose matrix. @@ -139,7 +139,7 @@ class CC_DLL Bone3D : public Ref /** * Constructor. */ - Bone3D(const std::string& id); + Bone3D(std::string_view id); /** * Destructor. @@ -190,7 +190,7 @@ class CC_DLL Skeleton3D : public Ref /**get bone*/ Bone3D* getBoneByIndex(unsigned int index) const; - Bone3D* getBoneByName(const std::string& id) const; + Bone3D* getBoneByName(std::string_view id) const; /**get & set root bone*/ ssize_t getRootCount() const; diff --git a/cocos/3d/CCSkybox.cpp b/cocos/3d/CCSkybox.cpp index e21c9770f88a..7e9d1fc2e81a 100644 --- a/cocos/3d/CCSkybox.cpp +++ b/cocos/3d/CCSkybox.cpp @@ -41,12 +41,12 @@ Skybox::~Skybox() _texture->release(); } -Skybox* Skybox::create(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z) +Skybox* Skybox::create(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z) { auto ret = new Skybox(); ret->init(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z); @@ -90,12 +90,12 @@ bool Skybox::init() return true; } -bool Skybox::init(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z) +bool Skybox::init(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z) { auto texture = TextureCube::create(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z); if (texture == nullptr) diff --git a/cocos/3d/CCSkybox.h b/cocos/3d/CCSkybox.h index 644da6446330..40560f2978df 100644 --- a/cocos/3d/CCSkybox.h +++ b/cocos/3d/CCSkybox.h @@ -58,12 +58,12 @@ class CC_DLL Skybox : public Node @param negative_z texture for the rear side of the texture cube face. @return A new skybox inited with given parameters. */ - static Skybox* create(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z); + static Skybox* create(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z); /**texture getter and setter*/ void setTexture(TextureCube*); @@ -93,12 +93,12 @@ class CC_DLL Skybox : public Node /** * initialize with texture path */ - bool init(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z); + bool init(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z); protected: /** diff --git a/cocos/3d/CCSprite3D.cpp b/cocos/3d/CCSprite3D.cpp index 3dcdf8e65a8b..f4d2e8cb6826 100644 --- a/cocos/3d/CCSprite3D.cpp +++ b/cocos/3d/CCSprite3D.cpp @@ -63,7 +63,7 @@ Sprite3D* Sprite3D::create() return nullptr; } -Sprite3D* Sprite3D::create(const std::string& modelPath) +Sprite3D* Sprite3D::create(std::string_view modelPath) { CCASSERT(modelPath.length() >= 4, "invalid filename for Sprite3D"); @@ -77,7 +77,7 @@ Sprite3D* Sprite3D::create(const std::string& modelPath) CC_SAFE_DELETE(sprite); return nullptr; } -Sprite3D* Sprite3D::create(const std::string& modelPath, const std::string& texturePath) +Sprite3D* Sprite3D::create(std::string_view modelPath, std::string_view texturePath) { auto sprite = create(modelPath); if (sprite) @@ -88,15 +88,15 @@ Sprite3D* Sprite3D::create(const std::string& modelPath, const std::string& text return sprite; } -void Sprite3D::createAsync(const std::string& modelPath, +void Sprite3D::createAsync(std::string_view modelPath, const std::function& callback, void* callbackparam) { createAsync(modelPath, "", callback, callbackparam); } -void Sprite3D::createAsync(const std::string& modelPath, - const std::string& texturePath, +void Sprite3D::createAsync(std::string_view modelPath, + std::string_view texturePath, const std::function& callback, void* callbackparam) { @@ -197,7 +197,7 @@ AABB Sprite3D::getAABBRecursivelyImp(Node* node) return aabb; } -bool Sprite3D::loadFromCache(const std::string& path) +bool Sprite3D::loadFromCache(std::string_view path) { auto spritedata = Sprite3DCache::getInstance()->getSpriteData(path); if (spritedata) @@ -238,7 +238,7 @@ bool Sprite3D::loadFromCache(const std::string& path) return false; } -bool Sprite3D::loadFromFile(const std::string& path, +bool Sprite3D::loadFromFile(std::string_view path, NodeDatas* nodedatas, MeshDatas* meshdatas, MaterialDatas* materialdatas) @@ -296,7 +296,7 @@ bool Sprite3D::init() return false; } -bool Sprite3D::initWithFile(const std::string& path) +bool Sprite3D::initWithFile(std::string_view path) { _aabbDirty = true; _meshes.clear(); @@ -654,7 +654,7 @@ void Sprite3D::createNode(NodeData* nodedata, Node* root, const MaterialDatas& m } } -MeshIndexData* Sprite3D::getMeshIndexData(const std::string& indexId) const +MeshIndexData* Sprite3D::getMeshIndexData(std::string_view indexId) const { for (auto it : _meshVertexDatas) { @@ -672,7 +672,7 @@ void Sprite3D::addMesh(Mesh* mesh) _meshes.pushBack(mesh); } -void Sprite3D::setTexture(const std::string& texFile) +void Sprite3D::setTexture(std::string_view texFile) { auto tex = _director->getTextureCache()->addImage(texFile); setTexture(tex); @@ -685,7 +685,7 @@ void Sprite3D::setTexture(Texture2D* texture) mesh->setTexture(texture); } } -AttachNode* Sprite3D::getAttachNode(const std::string& boneName) +AttachNode* Sprite3D::getAttachNode(std::string_view boneName) { auto it = _attachments.find(boneName); if (it != _attachments.end()) @@ -698,7 +698,7 @@ AttachNode* Sprite3D::getAttachNode(const std::string& boneName) { auto attachNode = AttachNode::create(bone); addChild(attachNode); - _attachments[boneName] = attachNode; + _attachments.emplace(boneName, attachNode); // _attachments[boneName] = attachNode; return attachNode; } } @@ -706,7 +706,7 @@ AttachNode* Sprite3D::getAttachNode(const std::string& boneName) return nullptr; } -void Sprite3D::removeAttachNode(const std::string& boneName) +void Sprite3D::removeAttachNode(std::string_view boneName) { auto it = _attachments.find(boneName); if (it != _attachments.end()) @@ -918,7 +918,7 @@ Mesh* Sprite3D::getMeshByIndex(int index) const } /**get Mesh by Name */ -Mesh* Sprite3D::getMeshByName(const std::string& name) const +Mesh* Sprite3D::getMeshByName(std::string_view name) const { for (const auto& it : _meshes) { @@ -928,7 +928,7 @@ Mesh* Sprite3D::getMeshByName(const std::string& name) const return nullptr; } -std::vector Sprite3D::getMeshArrayByName(const std::string& name) const +std::vector Sprite3D::getMeshArrayByName(std::string_view name) const { std::vector meshes; for (const auto& it : _meshes) @@ -973,7 +973,7 @@ void Sprite3DCache::destroyInstance() } } -Sprite3DCache::Sprite3DData* Sprite3DCache::getSpriteData(const std::string& key) const +Sprite3DCache::Sprite3DData* Sprite3DCache::getSpriteData(std::string_view key) const { auto it = _spriteDatas.find(key); if (it != _spriteDatas.end()) @@ -981,18 +981,18 @@ Sprite3DCache::Sprite3DData* Sprite3DCache::getSpriteData(const std::string& key return nullptr; } -bool Sprite3DCache::addSprite3DData(const std::string& key, Sprite3DCache::Sprite3DData* spritedata) +bool Sprite3DCache::addSprite3DData(std::string_view key, Sprite3DCache::Sprite3DData* spritedata) { auto it = _spriteDatas.find(key); if (it == _spriteDatas.end()) { - _spriteDatas[key] = spritedata; + _spriteDatas.emplace(key, spritedata); // _spriteDatas[key] = spritedata; return true; } return false; } -void Sprite3DCache::removeSprite3DData(const std::string& key) +void Sprite3DCache::removeSprite3DData(std::string_view key) { auto it = _spriteDatas.find(key); if (it != _spriteDatas.end()) diff --git a/cocos/3d/CCSprite3D.h b/cocos/3d/CCSprite3D.h index 477b6968ce3a..d038ce60b7da 100644 --- a/cocos/3d/CCSprite3D.h +++ b/cocos/3d/CCSprite3D.h @@ -62,10 +62,10 @@ class CC_DLL Sprite3D : public Node, public BlendProtocol static Sprite3D* create(); /** creates a Sprite3D*/ - static Sprite3D* create(const std::string& modelPath); + static Sprite3D* create(std::string_view modelPath); // creates a Sprite3D. It only supports one texture, and overrides the internal texture with 'texturePath' - static Sprite3D* create(const std::string& modelPath, const std::string& texturePath); + static Sprite3D* create(std::string_view modelPath, std::string_view texturePath); /** create 3d sprite asynchronously * If the 3d model was previously loaded, it will create a new 3d sprite and the callback will be called at once. @@ -76,31 +76,31 @@ class CC_DLL Sprite3D : public Node, public BlendProtocol * @param callback callback after loading * @param callbackparam user defined parameter for the callback */ - static void createAsync(const std::string& modelPath, + static void createAsync(std::string_view modelPath, const std::function& callback, void* callbackparam); - static void createAsync(const std::string& modelPath, - const std::string& texturePath, + static void createAsync(std::string_view modelPath, + std::string_view texturePath, const std::function& callback, void* callbackparam); /**set diffuse texture, set the first if multiple textures exist*/ - void setTexture(const std::string& texFile); + void setTexture(std::string_view texFile); void setTexture(Texture2D* texture); /**get Mesh by index*/ Mesh* getMeshByIndex(int index) const; /**get Mesh by Name, it returns the first one if there are more than one mesh with the same name */ - Mesh* getMeshByName(const std::string& name) const; + Mesh* getMeshByName(std::string_view name) const; /** * get mesh array by name, returns all meshes with the given name * * @lua NA */ - std::vector getMeshArrayByName(const std::string& name) const; + std::vector getMeshArrayByName(std::string_view name) const; /**get mesh*/ Mesh* getMesh() const; @@ -111,10 +111,10 @@ class CC_DLL Sprite3D : public Node, public BlendProtocol Skeleton3D* getSkeleton() const { return _skeleton; } /**get AttachNode by bone name, return nullptr if not exist*/ - AttachNode* getAttachNode(const std::string& boneName); + AttachNode* getAttachNode(std::string_view boneName); /**remove attach node*/ - void removeAttachNode(const std::string& boneName); + void removeAttachNode(std::string_view boneName); /**remove all attach nodes*/ void removeAllAttachNode(); @@ -214,19 +214,16 @@ class CC_DLL Sprite3D : public Node, public BlendProtocol virtual bool init() override; - bool initWithFile(const std::string& path); + bool initWithFile(std::string_view path); bool initFrom(const NodeDatas& nodedatas, const MeshDatas& meshdatas, const MaterialDatas& materialdatas); /**load sprite3d from cache, return true if succeed, false otherwise*/ - bool loadFromCache(const std::string& path); + bool loadFromCache(std::string_view path); /** load file and set it to meshedatas, nodedatas and materialdatas, obj file .mtl file should be at the same * directory if exist */ - bool loadFromFile(const std::string& path, - NodeDatas* nodedatas, - MeshDatas* meshdatas, - MaterialDatas* materialdatas); + bool loadFromFile(std::string_view path, NodeDatas* nodedatas, MeshDatas* meshdatas, MaterialDatas* materialdatas); /** * Visits this Sprite3D's children and draw them recursively. @@ -242,7 +239,7 @@ class CC_DLL Sprite3D : public Node, public BlendProtocol Sprite3D* createSprite3DNode(NodeData* nodedata, ModelData* modeldata, const MaterialDatas& materialdatas); /**get MeshIndexData by Id*/ - MeshIndexData* getMeshIndexData(const std::string& indexId) const; + MeshIndexData* getMeshIndexData(std::string_view indexId) const; void addMesh(Mesh* mesh); @@ -257,7 +254,7 @@ class CC_DLL Sprite3D : public Node, public BlendProtocol Vector _meshVertexDatas; - std::unordered_map _attachments; + hlookup::string_map _attachments; BlendFunc _blend; @@ -319,17 +316,17 @@ class CC_DLL Sprite3DCache * * @lua NA */ - Sprite3DData* getSpriteData(const std::string& key) const; + Sprite3DData* getSpriteData(std::string_view key) const; /** * add the SpriteData into Sprite3D by given the specified key * * @lua NA */ - bool addSprite3DData(const std::string& key, Sprite3DData* spritedata); + bool addSprite3DData(std::string_view key, Sprite3DData* spritedata); /**remove the SpriteData from Sprite3D by given the specified key*/ - void removeSprite3DData(const std::string& key); + void removeSprite3DData(std::string_view key); /**remove all the SpriteData from Sprite3D*/ void removeAllSprite3DData(); @@ -339,7 +336,7 @@ class CC_DLL Sprite3DCache protected: static Sprite3DCache* _cacheInstance; - std::unordered_map _spriteDatas; // cached sprite data + hlookup::string_map _spriteDatas; // cached sprite data }; // end of 3d group diff --git a/cocos/3d/CCSprite3DMaterial.cpp b/cocos/3d/CCSprite3DMaterial.cpp index 5be1ec697435..1c109af5bbf0 100644 --- a/cocos/3d/CCSprite3DMaterial.cpp +++ b/cocos/3d/CCSprite3DMaterial.cpp @@ -238,7 +238,7 @@ Sprite3DMaterial* Sprite3DMaterial::createBuiltInMaterial(MaterialType type, boo return nullptr; } -Sprite3DMaterial* Sprite3DMaterial::createWithFilename(const std::string& path) +Sprite3DMaterial* Sprite3DMaterial::createWithFilename(std::string_view path) { auto validfilename = FileUtils::getInstance()->fullPathForFilename(path); if (!validfilename.empty()) @@ -311,19 +311,19 @@ void Sprite3DMaterialCache::destroyInstance() } } -bool Sprite3DMaterialCache::addSprite3DMaterial(const std::string& key, Texture2D* texture) +bool Sprite3DMaterialCache::addSprite3DMaterial(std::string_view key, Texture2D* texture) { auto itr = _materials.find(key); if (itr == _materials.end()) { CC_SAFE_RETAIN(texture); - _materials[key] = texture; + _materials.emplace(key, texture); return true; } return false; } -Texture2D* Sprite3DMaterialCache::getSprite3DMaterial(const std::string& key) +Texture2D* Sprite3DMaterialCache::getSprite3DMaterial(std::string_view key) { auto itr = _materials.find(key); if (itr != _materials.end()) diff --git a/cocos/3d/CCSprite3DMaterial.h b/cocos/3d/CCSprite3DMaterial.h index 1a128d02189c..2162627f721d 100644 --- a/cocos/3d/CCSprite3DMaterial.h +++ b/cocos/3d/CCSprite3DMaterial.h @@ -87,7 +87,7 @@ class CC_DLL Sprite3DMaterial : public Material * @param path Path of material file * @return Created material */ - static Sprite3DMaterial* createWithFilename(const std::string& path); + static Sprite3DMaterial* createWithFilename(std::string_view path); /** * Create material with GLProgramState @@ -162,10 +162,10 @@ class Sprite3DMaterialCache static void destroyInstance(); /**add to cache*/ - bool addSprite3DMaterial(const std::string& key, Texture2D* tex); + bool addSprite3DMaterial(std::string_view key, Texture2D* tex); /**get material from cache*/ - Texture2D* getSprite3DMaterial(const std::string& key); + Texture2D* getSprite3DMaterial(std::string_view key); /**remove all spritematerial*/ void removeAllSprite3DMaterial(); @@ -178,8 +178,8 @@ class Sprite3DMaterialCache ~Sprite3DMaterialCache(); protected: - static Sprite3DMaterialCache* _cacheInstance; // instance - std::unordered_map _materials; // cached material + static Sprite3DMaterialCache* _cacheInstance; // instance + hlookup::string_map _materials; // cached material }; // end of 3d group diff --git a/cocos/3d/CCTerrain.cpp b/cocos/3d/CCTerrain.cpp index cc3bea4f6cf2..19e0f005613c 100644 --- a/cocos/3d/CCTerrain.cpp +++ b/cocos/3d/CCTerrain.cpp @@ -83,7 +83,7 @@ bool Terrain::initWithTerrainData(TerrainData& parameter, CrackFixedType fixedTy return initResult; } -void cocos2d::Terrain::setLightMap(const std::string& fileName) +void cocos2d::Terrain::setLightMap(std::string_view fileName) { CC_SAFE_RELEASE(_lightMap); auto image = new Image(); @@ -197,7 +197,7 @@ void Terrain::draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, } } -bool Terrain::initHeightMap(const std::string& heightMap) +bool Terrain::initHeightMap(std::string_view heightMap) { _heightMapImage = new Image(); _heightMapImage->initWithImageFile(heightMap); @@ -343,7 +343,7 @@ float Terrain::getHeight(float x, float z, Vec3* normal) const normal->z = d - a; normal->normalize(); //(*normal) = (1-u)*(1-v)*getNormal(i,j)+ (1-u)*v*getNormal(i,j+1) + u*(1-v)*getNormal(i+1,j)+ - //u*v*getNormal(i+1,j+1); + // u*v*getNormal(i+1,j+1); } float result = (1 - u) * (1 - v) * getImageHeight(i, j) * getScaleY() + (1 - u) * v * getImageHeight(i, j + 1) * getScaleY() + @@ -611,7 +611,7 @@ cocos2d::Vec2 Terrain::convertToTerrainSpace(const Vec2& worldSpaceXZ) const return Vec2(image_x, image_y); } -void Terrain::resetHeightMap(const std::string& heightMap) +void Terrain::resetHeightMap(std::string_view heightMap) { _heightMapImage->release(); _vertices.clear(); @@ -1154,8 +1154,8 @@ void Terrain::Chunk::updateIndicesLOD() } memcpy(_neighborOldLOD, currentNeighborLOD, sizeof(currentNeighborLOD)); _oldLod = _currentLod; - int gridY = _size.height; - int gridX = _size.width; + int gridY = static_cast(_size.height); + int gridX = static_cast(_size.width); int step = 1 << _currentLod; if ((_left && _left->_currentLod > _currentLod) || (_right && _right->_currentLod > _currentLod) || @@ -1644,8 +1644,8 @@ Terrain::QuadTree::~QuadTree() delete _br; } -Terrain::TerrainData::TerrainData(const std::string& heightMapsrc, - const std::string& textureSrc, +Terrain::TerrainData::TerrainData(std::string_view heightMapsrc, + std::string_view textureSrc, const Vec2& chunksize, float height, float scale) @@ -1659,8 +1659,8 @@ Terrain::TerrainData::TerrainData(const std::string& heightMapsrc, _skirtHeightRatio = 1; } -Terrain::TerrainData::TerrainData(const std::string& heightMapsrc, - const std::string& alphamap, +Terrain::TerrainData::TerrainData(std::string_view heightMapsrc, + std::string_view alphamap, const DetailMap& detail1, const DetailMap& detail2, const DetailMap& detail3, @@ -1682,8 +1682,8 @@ Terrain::TerrainData::TerrainData(const std::string& heightMapsrc, _skirtHeightRatio = 1; } -Terrain::TerrainData::TerrainData(const std::string& heightMapsrc, - const std::string& alphamap, +Terrain::TerrainData::TerrainData(std::string_view heightMapsrc, + std::string_view alphamap, const DetailMap& detail1, const DetailMap& detail2, const DetailMap& detail3, @@ -1729,7 +1729,7 @@ Terrain::ChunkIndices::~ChunkIndices() CC_SAFE_RELEASE_NULL(_indexBuffer); } -Terrain::DetailMap::DetailMap(const std::string& detailMapPath, float size /*= 35*/) +Terrain::DetailMap::DetailMap(std::string_view detailMapPath, float size /*= 35*/) { this->_detailMapSrc = detailMapPath; this->_detailMapSize = size; diff --git a/cocos/3d/CCTerrain.h b/cocos/3d/CCTerrain.h index 25ebc401c9aa..e05a5721b2cc 100644 --- a/cocos/3d/CCTerrain.h +++ b/cocos/3d/CCTerrain.h @@ -108,7 +108,7 @@ class CC_DLL Terrain : public Node { /*Constructors*/ DetailMap(); - DetailMap(const std::string& detailMapSrc, float size = 35); + DetailMap(std::string_view detailMapSrc, float size = 35); /*detail Image source file path*/ std::string _detailMapSrc; /*detailMapSize determine how many tiles that Terrain represent*/ @@ -136,14 +136,14 @@ class CC_DLL Terrain : public Node /**empty constructor*/ TerrainData(); /**constructor, this constructor construct a simple terrain which only have 1 detailmap*/ - TerrainData(const std::string& heightMapsrc, - const std::string& textureSrc, + TerrainData(std::string_view heightMapsrc, + std::string_view textureSrc, const Vec2& chunksize = Vec2(32, 32), float mapHeight = 2, float mapScale = 0.1); /**constructor, this constructor construct a terrain which have 4 detailmaps, 1 alpha map*/ - TerrainData(const std::string& heightMapsrc, - const std::string& alphamap, + TerrainData(std::string_view heightMapsrc, + std::string_view alphamap, const DetailMap& detail1, const DetailMap& detail2, const DetailMap& detail3, @@ -152,8 +152,8 @@ class CC_DLL Terrain : public Node float mapHeight = 2, float mapScale = 0.1); /**constructor, this constructor construct a terrain which have 3 detailmaps, 1 alpha map*/ - TerrainData(const std::string& heightMapsrc, - const std::string& alphamap, + TerrainData(std::string_view heightMapsrc, + std::string_view alphamap, const DetailMap& detail1, const DetailMap& detail2, const DetailMap& detail3, @@ -337,7 +337,7 @@ class CC_DLL Terrain : public Node public: /** set light map texture */ - void setLightMap(const std::string& fileName); + void setLightMap(std::string_view fileName); /** set directional light for the terrain @@ -349,7 +349,7 @@ class CC_DLL Terrain : public Node /**initialize all Properties which terrain need */ bool initProperties(); /**initialize heightMap data */ - bool initHeightMap(const std::string& heightMap); + bool initHeightMap(std::string_view heightMap); /**initialize alphaMap ,detailMaps textures*/ bool initTextures(); /**create entry*/ @@ -429,7 +429,7 @@ class CC_DLL Terrain : public Node /** * reset the heightmap data. */ - void resetHeightMap(const std::string& heightMap); + void resetHeightMap(std::string_view heightMap); /** * get the terrain's minimal height. diff --git a/cocos/3d/CCVertexAttribBinding.cpp b/cocos/3d/CCVertexAttribBinding.cpp index 9aa5e165b7fe..f7325edb7e79 100644 --- a/cocos/3d/CCVertexAttribBinding.cpp +++ b/cocos/3d/CCVertexAttribBinding.cpp @@ -122,9 +122,8 @@ void VertexAttribBinding::parseAttributes() _attributes.clear(); _vertexAttribsFlags = 0; - auto program = _programState->getProgram(); - auto& attributes = program->getActiveAttributes(); - _attributes = attributes; + auto program = _programState->getProgram(); + _attributes = program->getActiveAttributes(); } bool VertexAttribBinding::hasAttribute(const shaderinfos::VertexKey& key) const @@ -133,7 +132,7 @@ bool VertexAttribBinding::hasAttribute(const shaderinfos::VertexKey& key) const return _attributes.find(name) != _attributes.end(); } -backend::AttributeBindInfo* VertexAttribBinding::getVertexAttribValue(const std::string& name) +backend::AttributeBindInfo* VertexAttribBinding::getVertexAttribValue(std::string_view name) { const auto itr = _attributes.find(name); if (itr != _attributes.end()) @@ -141,7 +140,7 @@ backend::AttributeBindInfo* VertexAttribBinding::getVertexAttribValue(const std: return nullptr; } -void VertexAttribBinding::setVertexAttribPointer(const std::string& name, +void VertexAttribBinding::setVertexAttribPointer(std::string_view name, backend::VertexFormat type, bool normalized, int offset, diff --git a/cocos/3d/CCVertexAttribBinding.h b/cocos/3d/CCVertexAttribBinding.h index 20879586c072..e92378262593 100644 --- a/cocos/3d/CCVertexAttribBinding.h +++ b/cocos/3d/CCVertexAttribBinding.h @@ -107,18 +107,18 @@ class CC_DLL VertexAttribBinding : public Ref VertexAttribBinding& operator=(const VertexAttribBinding&); bool init(MeshIndexData* meshIndexData, Pass* pass, MeshCommand*); - void setVertexAttribPointer(const std::string& name, + void setVertexAttribPointer(std::string_view name, backend::VertexFormat type, bool normalized, int offset, int flag); - backend::AttributeBindInfo* getVertexAttribValue(const std::string& name); + backend::AttributeBindInfo* getVertexAttribValue(std::string_view name); void parseAttributes(); MeshIndexData* _meshIndexData; backend::ProgramState* _programState; std::shared_ptr _vertexLayout = std::make_shared(); - std::unordered_map _attributes; + hlookup::string_map _attributes; uint32_t _vertexAttribsFlags; }; diff --git a/cocos/CMakeLists.txt b/cocos/CMakeLists.txt index 389e4295a86e..a25fe697daa9 100644 --- a/cocos/CMakeLists.txt +++ b/cocos/CMakeLists.txt @@ -40,6 +40,10 @@ if (NOT DEFINED CC_COMPAT_GL) set(CC_COMPAT_GL FALSE CACHE INTERNAL "Enabling CC_COMPAT_GL" ) endif() +if (NOT DEFINED ADXE_ENABLE_WEBVIEW2) + set(ADXE_ENABLE_WEBVIEW2 TRUE CACHE INTERNAL "Enabling windows webview2" ) +endif() + project(adxe_libs) if(XCODE) @@ -161,17 +165,20 @@ if(WINDOWS) # compile c as c++. needed for precompiled header set_source_files_properties(${COCOS_SPINE_SRC} base/ccFPSImages.c PROPERTIES LANGUAGE CXX) - find_program(NUGET_EXE NAMES nuget - PATHS ${ADXE_ROOT_PATH}/tools/external/nuget) - - if(NOT NUGET_EXE) - message("NUGET.EXE not found.") - message(FATAL_ERROR "Please run setup.py again to download NUGET.EXE, and run CMake again.") + if(ADXE_ENABLE_WEBVIEW2) + find_program(NUGET_EXE NAMES nuget + PATHS ${ADXE_ROOT_PATH}/tools/external/nuget) + + if(NOT NUGET_EXE) + message("NUGET.EXE not found.") + message(FATAL_ERROR "Please run setup.py again to download NUGET.EXE, and run CMake again.") + endif() + + exec_program(${NUGET_EXE} + ARGS install "Microsoft.Web.WebView2" -Version 1.0.992.28 -ExcludeVersion -OutputDirectory ${CMAKE_BINARY_DIR}/packages) + target_link_libraries(${ADXE_CORE_LIB} ${CMAKE_BINARY_DIR}/packages/Microsoft.Web.WebView2/build/native/Microsoft.Web.WebView2.targets) + target_compile_definitions(${ADXE_CORE_LIB} PUBLIC ADXE_HAVE_WEBVIEW2) endif() - - exec_program(${NUGET_EXE} - ARGS install "Microsoft.Web.WebView2" -Version 1.0.992.28 -ExcludeVersion -OutputDirectory ${CMAKE_BINARY_DIR}/packages) - target_link_libraries(${ADXE_CORE_LIB} ${CMAKE_BINARY_DIR}/packages/Microsoft.Web.WebView2/build/native/Microsoft.Web.WebView2.targets) endif() # engine extensions @@ -179,6 +186,7 @@ add_subdirectory(${ADXE_ROOT_PATH}/extensions ${ENGINE_BINARY_PATH}/extensions) if(MSVC_IDE) target_sources(${ADXE_CORE_LIB} PRIVATE ../thirdparty/yasio/yasio.natvis) + target_sources(${ADXE_CORE_LIB} PRIVATE ../thirdparty/robin-map/tsl-robin-map.natvis) endif() # copy all thirdparty libraries to ${CMAKE_BINARY_DIR}/lib/$ diff --git a/cocos/adxe.cpp b/cocos/adxe.cpp index 1dc63f4fb608..559aea4e0af2 100644 --- a/cocos/adxe.cpp +++ b/cocos/adxe.cpp @@ -33,7 +33,7 @@ NS_CC_BEGIN CC_DLL const char* adxeVersion() { - return "adxe-1.0.0b4"; + return "adxe-1.0.0b5"; } NS_CC_END diff --git a/cocos/audio/include/AudioDecoder.h b/cocos/audio/include/AudioDecoder.h index 1e1a27043d2d..780ddc2933cb 100644 --- a/cocos/audio/include/AudioDecoder.h +++ b/cocos/audio/include/AudioDecoder.h @@ -60,7 +60,7 @@ class AudioDecoder * @brief Opens an audio file specified by a file path. * @return true if succeed, otherwise false. */ - virtual bool open(const std::string& path) = 0; + virtual bool open(std::string_view path) = 0; /** * @brief Checks whether decoder has opened file successfully. diff --git a/cocos/audio/include/AudioDecoderEXT.h b/cocos/audio/include/AudioDecoderEXT.h index d8d598c8ae8c..f6eea0dbd20b 100644 --- a/cocos/audio/include/AudioDecoderEXT.h +++ b/cocos/audio/include/AudioDecoderEXT.h @@ -49,7 +49,7 @@ class AudioDecoderEXT : public AudioDecoder * @brief Opens an audio file specified by a file path. * @return true if succeed, otherwise false. */ - bool open(const std::string& path) override; + bool open(std::string_view path) override; /** * @brief Closes opened audio file. diff --git a/cocos/audio/include/AudioDecoderManager.h b/cocos/audio/include/AudioDecoderManager.h index fe5c2d1ed938..3075bf10d9be 100644 --- a/cocos/audio/include/AudioDecoderManager.h +++ b/cocos/audio/include/AudioDecoderManager.h @@ -37,7 +37,7 @@ class AudioDecoderManager public: static bool init(); static void destroy(); - static AudioDecoder* createDecoder(const std::string& path); + static AudioDecoder* createDecoder(std::string_view path); static void destroyDecoder(AudioDecoder* decoder); }; diff --git a/cocos/audio/include/AudioDecoderMp3.h b/cocos/audio/include/AudioDecoderMp3.h index a8be6fbeb3de..97311573974e 100644 --- a/cocos/audio/include/AudioDecoderMp3.h +++ b/cocos/audio/include/AudioDecoderMp3.h @@ -52,7 +52,7 @@ class AudioDecoderMp3 : public AudioDecoder * @brief Opens an audio file specified by a file path. * @return true if succeed, otherwise false. */ - bool open(const std::string& path) override; + bool open(std::string_view path) override; /** * @brief Closes opened audio file. diff --git a/cocos/audio/include/AudioDecoderOgg.h b/cocos/audio/include/AudioDecoderOgg.h index 0ca447b68019..18d86ebcedd3 100644 --- a/cocos/audio/include/AudioDecoderOgg.h +++ b/cocos/audio/include/AudioDecoderOgg.h @@ -44,7 +44,7 @@ class AudioDecoderOgg : public AudioDecoder * @brief Opens an audio file specified by a file path. * @return true if succeed, otherwise false. */ - bool open(const std::string& path) override; + bool open(std::string_view path) override; /** * @brief Closes opened audio file. diff --git a/cocos/audio/include/AudioDecoderWav.h b/cocos/audio/include/AudioDecoderWav.h index 59864494638b..8e9e101dd2fc 100644 --- a/cocos/audio/include/AudioDecoderWav.h +++ b/cocos/audio/include/AudioDecoderWav.h @@ -128,7 +128,7 @@ class AudioDecoderWav : public AudioDecoder * @brief Opens an audio file specified by a file path. * @return true if succeed, otherwise false. */ - bool open(const std::string& path) override; + bool open(std::string_view path) override; /** * @brief The helper function for convert frames to bytes diff --git a/cocos/audio/include/AudioEngine.h b/cocos/audio/include/AudioEngine.h index ee89635def62..2d864b78ee45 100644 --- a/cocos/audio/include/AudioEngine.h +++ b/cocos/audio/include/AudioEngine.h @@ -126,7 +126,7 @@ class CC_DLL AudioEngine * * @see `AudioProfile` */ - static AUDIO_ID play2d(const std::string& filePath, + static AUDIO_ID play2d(std::string_view filePath, bool loop = false, float volume = 1.0f, const AudioProfile* profile = nullptr); @@ -232,7 +232,7 @@ class CC_DLL AudioEngine * @param audioID An audioID returned by the play2d function. * @param callback */ - static void setFinishCallback(AUDIO_ID audioID, const std::function& callback); + static void setFinishCallback(AUDIO_ID audioID, const std::function& callback); /** * Gets the maximum number of simultaneous audio instance of AudioEngine. @@ -253,7 +253,7 @@ class CC_DLL AudioEngine * @warning This can lead to stop related audio first. * @param filePath Audio file path. */ - static void uncache(const std::string& filePath); + static void uncache(std::string_view filePath); /** * Uncache all audio data from internal buffer. @@ -276,20 +276,20 @@ class CC_DLL AudioEngine * @param profileName A name of audio profile. * @return The audio profile. */ - static AudioProfile* getProfile(const std::string& profileName); + static AudioProfile* getProfile(std::string_view profileName); /** * Preload audio file. * @param filePath The file path of an audio. */ - static void preload(const std::string& filePath) { preload(filePath, nullptr); } + static void preload(std::string_view filePath) { preload(filePath, nullptr); } /** * Preload audio file. * @param filePath The file path of an audio. * @param callback A callback which will be called after loading is finished. */ - static void preload(const std::string& filePath, std::function callback); + static void preload(std::string_view filePath, std::function callback); /** * Gets playing audio count. @@ -346,10 +346,10 @@ class CC_DLL AudioEngine static std::unordered_map _audioIDInfoMap; // audio file path,audio IDs - static std::unordered_map> _audioPathIDMap; + static hlookup::string_map> _audioPathIDMap; // profileName,ProfileHelper - static std::unordered_map _audioPathProfileHelperMap; + static hlookup::string_map _audioPathProfileHelperMap; static unsigned int _maxInstances; diff --git a/cocos/audio/include/AudioEngineImpl.h b/cocos/audio/include/AudioEngineImpl.h index cbb5c7284afd..eb1c4c9610c7 100644 --- a/cocos/audio/include/AudioEngineImpl.h +++ b/cocos/audio/include/AudioEngineImpl.h @@ -49,7 +49,7 @@ class CC_DLL AudioEngineImpl : public cocos2d::Ref ~AudioEngineImpl(); bool init(); - AUDIO_ID play2d(const std::string& fileFullPath, bool loop, float volume); + AUDIO_ID play2d(std::string_view fileFullPath, bool loop, float volume); void setVolume(AUDIO_ID audioID, float volume); void setLoop(AUDIO_ID audioID, bool loop); bool pause(AUDIO_ID audioID); @@ -59,11 +59,11 @@ class CC_DLL AudioEngineImpl : public cocos2d::Ref float getDuration(AUDIO_ID audioID); float getCurrentTime(AUDIO_ID audioID); bool setCurrentTime(AUDIO_ID audioID, float time); - void setFinishCallback(AUDIO_ID audioID, const std::function& callback); + void setFinishCallback(AUDIO_ID audioID, const std::function& callback); - void uncache(const std::string& filePath); + void uncache(std::string_view filePath); void uncacheAll(); - AudioCache* preload(const std::string& filePath, std::function callback); + AudioCache* preload(std::string_view filePath, std::function callback); void update(float dt); private: @@ -81,7 +81,7 @@ class CC_DLL AudioEngineImpl : public cocos2d::Ref std::queue _unusedSourcesPool; // filePath,bufferInfo - std::unordered_map _audioCaches; + hlookup::string_map> _audioCaches; // audioID,AudioInfo std::unordered_map _audioPlayers; diff --git a/cocos/audio/include/AudioPlayer.h b/cocos/audio/include/AudioPlayer.h index e114c5ea8132..81512b98d99f 100644 --- a/cocos/audio/include/AudioPlayer.h +++ b/cocos/audio/include/AudioPlayer.h @@ -72,7 +72,7 @@ class CC_DLL AudioPlayer float _volume; bool _loop; - std::function _finishCallbak; + std::function _finishCallbak; bool _isDestroyed; bool _removeByAudioEngine; diff --git a/cocos/audio/src/AudioDecoderEXT.mm b/cocos/audio/src/AudioDecoderEXT.mm index d310eb38e800..eb7f9ceaa4c0 100644 --- a/cocos/audio/src/AudioDecoderEXT.mm +++ b/cocos/audio/src/AudioDecoderEXT.mm @@ -32,183 +32,194 @@ of this software and associated documentation files (the "Software"), to deal #define LOG_TAG "AudioDecoder" -namespace cocos2d { - - AudioDecoderEXT::AudioDecoderEXT() - : _extRef(nullptr), _fileStream(nullptr), _streamSize(0), _audioFileId(nullptr) +namespace cocos2d +{ + +AudioDecoderEXT::AudioDecoderEXT() : _extRef(nullptr), _fileStream(nullptr), _streamSize(0), _audioFileId(nullptr) +{ + memset(&_outputFormat, 0, sizeof(_outputFormat)); +} + +AudioDecoderEXT::~AudioDecoderEXT() +{ + closeInternal(); +} + +bool AudioDecoderEXT::open(std::string_view fullPath) +{ + bool ret = false; + CFURLRef fileURL = nil; + do { - memset(&_outputFormat, 0, sizeof(_outputFormat)); - } + BREAK_IF_ERR_LOG(fullPath.empty(), "Invalid path!"); - AudioDecoderEXT::~AudioDecoderEXT() - { - closeInternal(); - } - - bool AudioDecoderEXT::open(const std::string& fullPath) - { - bool ret = false; - CFURLRef fileURL = nil; - do - { - BREAK_IF_ERR_LOG(fullPath.empty(), "Invalid path!"); - - _fileStream = cocos2d::FileUtils::getInstance()->openFileStream(fullPath, FileStream::Mode::READ); - BREAK_IF_ERR_LOG(_fileStream == nullptr, "FileUtils::openFileStream FAILED for file: %s", fullPath.c_str()); - if (_fileStream) - { - _streamSize = _fileStream->size(); // cache the stream size - } - - OSStatus status = AudioFileOpenWithCallbacks(this, &AudioDecoderEXT::readCallback, nullptr, &AudioDecoderEXT::getSizeCallback, nullptr, 0, &_audioFileId); - BREAK_IF_ERR_LOG(status != noErr, "AudioFileOpenWithCallbacks FAILED, Error = %d", (int)status); - - status = ExtAudioFileWrapAudioFileID(_audioFileId, false, &_extRef); - BREAK_IF_ERR_LOG(status != noErr, "ExtAudioFileWrapAudioFileID FAILED, Error = %d", (int)status); - - BREAK_IF_ERR_LOG(status != noErr, "ExtAudioFileOpenURL FAILED, Error = %d", (int)status); - - AudioStreamBasicDescription fileFormat; - UInt32 propertySize = sizeof(fileFormat); - - // Get the audio data format - status = ExtAudioFileGetProperty(_extRef, kExtAudioFileProperty_FileDataFormat, &propertySize, &fileFormat); - BREAK_IF_ERR_LOG(status != noErr, "ExtAudioFileGetProperty(kExtAudioFileProperty_FileDataFormat) FAILED, Error = %d", (int)status); - BREAK_IF_ERR_LOG(fileFormat.mChannelsPerFrame > 2, "Unsupported Format, channel count is greater than stereo!"); - - // Set the client format to 16 bit signed integer (native-endian) data - // Maintain the channel count and sample rate of the original source format - _outputFormat.mSampleRate = fileFormat.mSampleRate; - _outputFormat.mChannelsPerFrame = fileFormat.mChannelsPerFrame; - _outputFormat.mFormatID = kAudioFormatLinearPCM; - _outputFormat.mFramesPerPacket = 1; - _outputFormat.mBitsPerChannel = 16; - _outputFormat.mFormatFlags = kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked | kAudioFormatFlagIsSignedInteger; - - _sampleRate = _outputFormat.mSampleRate; - _channelCount = _outputFormat.mChannelsPerFrame; - _bytesPerBlock = 2 * _outputFormat.mChannelsPerFrame; - - _outputFormat.mBytesPerPacket = _bytesPerBlock; - _outputFormat.mBytesPerFrame = _bytesPerBlock; - - status = ExtAudioFileSetProperty(_extRef, kExtAudioFileProperty_ClientDataFormat, sizeof(_outputFormat), &_outputFormat); - BREAK_IF_ERR_LOG(status != noErr, "ExtAudioFileSetProperty FAILED, Error = %d", (int)status); - - // Get the total frame count - SInt64 totalFrames = 0; - propertySize = sizeof(totalFrames); - status = ExtAudioFileGetProperty(_extRef, kExtAudioFileProperty_FileLengthFrames, &propertySize, &totalFrames); - BREAK_IF_ERR_LOG(status != noErr, "ExtAudioFileGetProperty(kExtAudioFileProperty_FileLengthFrames) FAILED, Error = %d",(int)status); - BREAK_IF_ERR_LOG(totalFrames <= 0, "Total frames is 0, it's an invalid audio file: %s", fullPath.c_str()); - _totalFrames = static_cast(totalFrames); - _isOpened = true; - - ret = true; - } while (false); - - if (fileURL != nil) - CFRelease(fileURL); - - if (!ret) + _fileStream = cocos2d::FileUtils::getInstance()->openFileStream(fullPath, FileStream::Mode::READ); + BREAK_IF_ERR_LOG(_fileStream == nullptr, "FileUtils::openFileStream FAILED for file: %s", fullPath.data()); + if (_fileStream) { - close(); + _streamSize = _fileStream->size(); // cache the stream size } - return ret; - } - - void AudioDecoderEXT::close() + OSStatus status = AudioFileOpenWithCallbacks(this, &AudioDecoderEXT::readCallback, nullptr, + &AudioDecoderEXT::getSizeCallback, nullptr, 0, &_audioFileId); + BREAK_IF_ERR_LOG(status != noErr, "AudioFileOpenWithCallbacks FAILED, Error = %d", (int)status); + + status = ExtAudioFileWrapAudioFileID(_audioFileId, false, &_extRef); + BREAK_IF_ERR_LOG(status != noErr, "ExtAudioFileWrapAudioFileID FAILED, Error = %d", (int)status); + + BREAK_IF_ERR_LOG(status != noErr, "ExtAudioFileOpenURL FAILED, Error = %d", (int)status); + + AudioStreamBasicDescription fileFormat; + UInt32 propertySize = sizeof(fileFormat); + + // Get the audio data format + status = ExtAudioFileGetProperty(_extRef, kExtAudioFileProperty_FileDataFormat, &propertySize, &fileFormat); + BREAK_IF_ERR_LOG(status != noErr, + "ExtAudioFileGetProperty(kExtAudioFileProperty_FileDataFormat) FAILED, Error = %d", + (int)status); + BREAK_IF_ERR_LOG(fileFormat.mChannelsPerFrame > 2, "Unsupported Format, channel count is greater than stereo!"); + + // Set the client format to 16 bit signed integer (native-endian) data + // Maintain the channel count and sample rate of the original source format + _outputFormat.mSampleRate = fileFormat.mSampleRate; + _outputFormat.mChannelsPerFrame = fileFormat.mChannelsPerFrame; + _outputFormat.mFormatID = kAudioFormatLinearPCM; + _outputFormat.mFramesPerPacket = 1; + _outputFormat.mBitsPerChannel = 16; + _outputFormat.mFormatFlags = + kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked | kAudioFormatFlagIsSignedInteger; + + _sampleRate = _outputFormat.mSampleRate; + _channelCount = _outputFormat.mChannelsPerFrame; + _bytesPerBlock = 2 * _outputFormat.mChannelsPerFrame; + + _outputFormat.mBytesPerPacket = _bytesPerBlock; + _outputFormat.mBytesPerFrame = _bytesPerBlock; + + status = ExtAudioFileSetProperty(_extRef, kExtAudioFileProperty_ClientDataFormat, sizeof(_outputFormat), + &_outputFormat); + BREAK_IF_ERR_LOG(status != noErr, "ExtAudioFileSetProperty FAILED, Error = %d", (int)status); + + // Get the total frame count + SInt64 totalFrames = 0; + propertySize = sizeof(totalFrames); + status = ExtAudioFileGetProperty(_extRef, kExtAudioFileProperty_FileLengthFrames, &propertySize, &totalFrames); + BREAK_IF_ERR_LOG(status != noErr, + "ExtAudioFileGetProperty(kExtAudioFileProperty_FileLengthFrames) FAILED, Error = %d", + (int)status); + BREAK_IF_ERR_LOG(totalFrames <= 0, "Total frames is 0, it's an invalid audio file: %s", fullPath.data()); + _totalFrames = static_cast(totalFrames); + _isOpened = true; + + ret = true; + } while (false); + + if (fileURL != nil) + CFRelease(fileURL); + + if (!ret) { - closeInternal(); + close(); } - uint32_t AudioDecoderEXT::read(uint32_t framesToRead, char* pcmBuf) - { - uint32_t ret = 0; - do - { - BREAK_IF_ERR_LOG(!isOpened(), "decoder isn't openned"); - BREAK_IF_ERR_LOG(framesToRead == INVALID_FRAME_INDEX, "frameToRead is INVALID_FRAME_INDEX"); - BREAK_IF_ERR_LOG(framesToRead == 0, "frameToRead is 0"); - BREAK_IF_ERR_LOG(pcmBuf == nullptr, "pcmBuf is nullptr"); - - AudioBufferList bufferList; - bufferList.mNumberBuffers = 1; - bufferList.mBuffers[0].mDataByteSize = framesToRead * _bytesPerBlock; - bufferList.mBuffers[0].mNumberChannels = _outputFormat.mChannelsPerFrame; - bufferList.mBuffers[0].mData = pcmBuf; - - UInt32 frames = framesToRead; - OSStatus status = ExtAudioFileRead(_extRef, &frames, &bufferList); - BREAK_IF(status != noErr); - ret = frames; - } while (false); - - return ret; - } + return ret; +} + +void AudioDecoderEXT::close() +{ + closeInternal(); +} - bool AudioDecoderEXT::seek(uint32_t frameOffset) +uint32_t AudioDecoderEXT::read(uint32_t framesToRead, char* pcmBuf) +{ + uint32_t ret = 0; + do { - bool ret = false; - do - { - BREAK_IF_ERR_LOG(!isOpened(), "decoder isn't openned"); - BREAK_IF_ERR_LOG(frameOffset == INVALID_FRAME_INDEX, "frameIndex is INVALID_FRAME_INDEX"); - - OSStatus status = ExtAudioFileSeek(_extRef, frameOffset); - BREAK_IF(status != noErr); - ret = true; - } while(false); - return ret; + BREAK_IF_ERR_LOG(!isOpened(), "decoder isn't openned"); + BREAK_IF_ERR_LOG(framesToRead == INVALID_FRAME_INDEX, "frameToRead is INVALID_FRAME_INDEX"); + BREAK_IF_ERR_LOG(framesToRead == 0, "frameToRead is 0"); + BREAK_IF_ERR_LOG(pcmBuf == nullptr, "pcmBuf is nullptr"); + + AudioBufferList bufferList; + bufferList.mNumberBuffers = 1; + bufferList.mBuffers[0].mDataByteSize = framesToRead * _bytesPerBlock; + bufferList.mBuffers[0].mNumberChannels = _outputFormat.mChannelsPerFrame; + bufferList.mBuffers[0].mData = pcmBuf; + + UInt32 frames = framesToRead; + OSStatus status = ExtAudioFileRead(_extRef, &frames, &bufferList); + BREAK_IF(status != noErr); + ret = frames; + } while (false); + + return ret; +} + +bool AudioDecoderEXT::seek(uint32_t frameOffset) +{ + bool ret = false; + do + { + BREAK_IF_ERR_LOG(!isOpened(), "decoder isn't openned"); + BREAK_IF_ERR_LOG(frameOffset == INVALID_FRAME_INDEX, "frameIndex is INVALID_FRAME_INDEX"); + + OSStatus status = ExtAudioFileSeek(_extRef, frameOffset); + BREAK_IF(status != noErr); + ret = true; + } while (false); + return ret; +} + +void AudioDecoderEXT::closeInternal() +{ + if (_extRef != nullptr) + { + ExtAudioFileDispose(_extRef); + AudioFileClose(_audioFileId); + _extRef = nullptr; + _audioFileId = nullptr; + _fileStream = nullptr; } - - void AudioDecoderEXT::closeInternal() +} + +OSStatus AudioDecoderEXT::readCallback(void* inClientData, + SInt64 inPosition, + UInt32 requestCount, + void* buffer, + UInt32* actualCount) +{ + if (!inClientData) { - if (_extRef != nullptr) - { - ExtAudioFileDispose(_extRef); - AudioFileClose(_audioFileId); - _extRef = nullptr; - _audioFileId = nullptr; - _fileStream = nullptr; - } + return kAudioFileNotOpenError; } - OSStatus AudioDecoderEXT::readCallback(void *inClientData, SInt64 inPosition, UInt32 requestCount, void *buffer, UInt32 *actualCount) + auto* audioDecoder = (AudioDecoderEXT*)inClientData; + auto* fileStream = audioDecoder->_fileStream.get(); + auto currPos = (SInt64)fileStream->tell(); + auto posDiff = inPosition - currPos; + if (posDiff != 0) { - if (!inClientData) - { - return kAudioFileNotOpenError; - } - - auto* audioDecoder = (AudioDecoderEXT*)inClientData; - auto* fileStream = audioDecoder->_fileStream.get(); - auto currPos = (SInt64)fileStream->tell(); - auto posDiff = inPosition - currPos; - if (posDiff != 0) + if (fileStream->seek(posDiff, SEEK_CUR) < 0) { - if (fileStream->seek(posDiff, SEEK_CUR) < 0) - { - return kAudioFilePositionError; - } + return kAudioFilePositionError; } - - const auto count = fileStream->read(buffer, requestCount); - - if (count < 0) - { - return kAudioFileEndOfFileError; - } - - *actualCount = count; - - return noErr; } - SInt64 AudioDecoderEXT::getSizeCallback(void *inClientData) + const auto count = fileStream->read(buffer, requestCount); + + if (count < 0) { - auto* audioDecoder = (AudioDecoderEXT*)inClientData; - return audioDecoder->_streamSize; + return kAudioFileEndOfFileError; } -} // namespace cocos2d { + + *actualCount = count; + + return noErr; +} + +SInt64 AudioDecoderEXT::getSizeCallback(void* inClientData) +{ + auto* audioDecoder = (AudioDecoderEXT*)inClientData; + return audioDecoder->_streamSize; +} +} // namespace cocos2d { diff --git a/cocos/audio/src/AudioDecoderManager.cpp b/cocos/audio/src/AudioDecoderManager.cpp index fc0730e1c4ea..879d893a63c0 100644 --- a/cocos/audio/src/AudioDecoderManager.cpp +++ b/cocos/audio/src/AudioDecoderManager.cpp @@ -60,7 +60,7 @@ void AudioDecoderManager::destroy() #endif } -AudioDecoder* AudioDecoderManager::createDecoder(const std::string& path) +AudioDecoder* AudioDecoderManager::createDecoder(std::string_view path) { cxx17::string_view svPath(path); if (cxx20::ic::ends_with(svPath, ".ogg")) diff --git a/cocos/audio/src/AudioDecoderMp3.cpp b/cocos/audio/src/AudioDecoderMp3.cpp index a1c8c2cc5a56..b02cecc2a112 100644 --- a/cocos/audio/src/AudioDecoderMp3.cpp +++ b/cocos/audio/src/AudioDecoderMp3.cpp @@ -126,7 +126,7 @@ AudioDecoderMp3::~AudioDecoderMp3() close(); } -bool AudioDecoderMp3::open(const std::string& fullPath) +bool AudioDecoderMp3::open(std::string_view fullPath) { #if !CC_USE_MPG123 do diff --git a/cocos/audio/src/AudioDecoderOgg.cpp b/cocos/audio/src/AudioDecoderOgg.cpp index 15c4cc9ce866..bad5a4f6f404 100644 --- a/cocos/audio/src/AudioDecoderOgg.cpp +++ b/cocos/audio/src/AudioDecoderOgg.cpp @@ -70,7 +70,7 @@ AudioDecoderOgg::~AudioDecoderOgg() close(); } -bool AudioDecoderOgg::open(const std::string& fullPath) +bool AudioDecoderOgg::open(std::string_view fullPath) { auto fs = FileUtils::getInstance()->openFileStream(fullPath, FileStream::Mode::READ).release(); if (!fs) diff --git a/cocos/audio/src/AudioDecoderWav.cpp b/cocos/audio/src/AudioDecoderWav.cpp index 28366caed4d1..3d6be1e0feee 100644 --- a/cocos/audio/src/AudioDecoderWav.cpp +++ b/cocos/audio/src/AudioDecoderWav.cpp @@ -78,7 +78,7 @@ static bool wav_scan_chunk(WAV_FILE* wavf, uint32_t chunkID, void* header, void* } return false; } -static bool wav_open(const std::string& fullPath, WAV_FILE* wavf) +static bool wav_open(std::string_view fullPath, WAV_FILE* wavf) { wavf->Stream = FileUtils::getInstance()->openFileStream(fullPath, FileStream::Mode::READ); if (!wavf->Stream) @@ -192,7 +192,7 @@ AudioDecoderWav::~AudioDecoderWav() close(); } -bool AudioDecoderWav::open(const std::string& fullPath) +bool AudioDecoderWav::open(std::string_view fullPath) { if (wav_open(fullPath, &_wavf)) { diff --git a/cocos/audio/src/AudioEngine.cpp b/cocos/audio/src/AudioEngine.cpp index a59ac5b9a9f2..8590394e9744 100644 --- a/cocos/audio/src/AudioEngine.cpp +++ b/cocos/audio/src/AudioEngine.cpp @@ -47,9 +47,9 @@ const int AudioEngine::INVALID_AUDIO_ID = -1; const float AudioEngine::TIME_UNKNOWN = -1.0f; // audio file path,audio IDs -std::unordered_map> AudioEngine::_audioPathIDMap; +hlookup::string_map> AudioEngine::_audioPathIDMap; // profileName,ProfileHelper -std::unordered_map AudioEngine::_audioPathProfileHelperMap; +hlookup::string_map AudioEngine::_audioPathProfileHelperMap; unsigned int AudioEngine::_maxInstances = MAX_AUDIOINSTANCES; AudioEngine::ProfileHelper* AudioEngine::_defaultProfileHelper = nullptr; std::unordered_map AudioEngine::_audioIDInfoMap; @@ -172,7 +172,7 @@ bool AudioEngine::lazyInit() return true; } -AUDIO_ID AudioEngine::play2d(const std::string& filePath, bool loop, float volume, const AudioProfile* profile) +AUDIO_ID AudioEngine::play2d(std::string_view filePath, bool loop, float volume, const AudioProfile* profile) { AUDIO_ID ret = AudioEngine::INVALID_AUDIO_ID; @@ -203,7 +203,7 @@ AUDIO_ID AudioEngine::play2d(const std::string& filePath, bool loop, float volum if (_audioIDInfoMap.size() >= _maxInstances) { - log("Fail to play %s cause by limited max instance of AudioEngine", filePath.c_str()); + log("Fail to play %s cause by limited max instance of AudioEngine", filePath.data()); break; } if (profileHelper) @@ -211,7 +211,7 @@ AUDIO_ID AudioEngine::play2d(const std::string& filePath, bool loop, float volum if (profileHelper->profile.maxInstances != 0 && profileHelper->audioIDs.size() >= profileHelper->profile.maxInstances) { - log("Fail to play %s cause by limited max instance of AudioProfile", filePath.c_str()); + log("Fail to play %s cause by limited max instance of AudioProfile", filePath.data()); break; } if (profileHelper->profile.minDelay > TIME_DELAY_PRECISION) @@ -220,7 +220,7 @@ AUDIO_ID AudioEngine::play2d(const std::string& filePath, bool loop, float volum if (profileHelper->lastPlayTime > TIME_DELAY_PRECISION && currTime - profileHelper->lastPlayTime <= profileHelper->profile.minDelay) { - log("Fail to play %s cause by limited minimum delay", filePath.c_str()); + log("Fail to play %s cause by limited minimum delay", filePath.data()); break; } } @@ -238,7 +238,7 @@ AUDIO_ID AudioEngine::play2d(const std::string& filePath, bool loop, float volum ret = _audioEngineImpl->play2d(filePath, loop, volume); if (ret != INVALID_AUDIO_ID) { - _audioPathIDMap[filePath].push_back(ret); + _audioPathIDMap[filePath.data()].push_back(ret); auto it = _audioPathIDMap.find(filePath); auto& audioRef = _audioIDInfoMap[ret]; @@ -380,7 +380,7 @@ void AudioEngine::stopAll() _audioIDInfoMap.clear(); } -void AudioEngine::uncache(const std::string& filePath) +void AudioEngine::uncache(std::string_view filePath) { if (!_audioEngineImpl) { @@ -463,7 +463,7 @@ float AudioEngine::getCurrentTime(AUDIO_ID audioID) return 0.0f; } -void AudioEngine::setFinishCallback(AUDIO_ID audioID, const std::function& callback) +void AudioEngine::setFinishCallback(AUDIO_ID audioID, const std::function& callback) { auto it = _audioIDInfoMap.find(audioID); if (it != _audioIDInfoMap.end()) @@ -539,7 +539,7 @@ AudioProfile* AudioEngine::getDefaultProfile() return &_defaultProfileHelper->profile; } -AudioProfile* AudioEngine::getProfile(const std::string& name) +AudioProfile* AudioEngine::getProfile(std::string_view name) { auto it = _audioPathProfileHelperMap.find(name); if (it != _audioPathProfileHelperMap.end()) @@ -552,7 +552,7 @@ AudioProfile* AudioEngine::getProfile(const std::string& name) } } -void AudioEngine::preload(const std::string& filePath, std::function callback) +void AudioEngine::preload(std::string_view filePath, std::function callback) { if (!isEnabled()) { diff --git a/cocos/audio/src/AudioEngineImpl.mm b/cocos/audio/src/AudioEngineImpl.mm index f51ed483fc25..f4aca8818f8e 100644 --- a/cocos/audio/src/AudioEngineImpl.mm +++ b/cocos/audio/src/AudioEngineImpl.mm @@ -32,7 +32,7 @@ of this software and associated documentation files (the "Software"), to deal #include "audio/include/AudioDecoderManager.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC -#import +# import #endif #include "audio/include/AudioEngine.h" @@ -42,31 +42,33 @@ of this software and associated documentation files (the "Software"), to deal #include "base/ccUtils.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS -#import +# import #endif using namespace cocos2d; -static ALCdevice* s_ALDevice = nullptr; -static ALCcontext* s_ALContext = nullptr; +static ALCdevice* s_ALDevice = nullptr; +static ALCcontext* s_ALContext = nullptr; static AudioEngineImpl* s_instance = nullptr; -static void ccALPauseDevice() { +static void ccALPauseDevice() +{ ALOGD("%s", "===> ccALPauseDevice"); #if CC_USE_ALSOFT alcDevicePauseSOFT(s_ALDevice); #else - if(alcGetCurrentContext()) + if (alcGetCurrentContext()) alcMakeContextCurrent(nullptr); #endif } -static void ccALResumeDevice() { +static void ccALResumeDevice() +{ ALOGD("%s", "===> ccALResumeDevice"); #if CC_USE_ALSOFT alcDeviceResumeSOFT(s_ALDevice); #else - if(alcGetCurrentContext()) + if (alcGetCurrentContext()) alcMakeContextCurrent(nullptr); alcMakeContextCurrent(s_ALContext); #endif @@ -75,8 +77,14 @@ static void ccALResumeDevice() { #if defined(__APPLE__) typedef ALvoid (*alSourceNotificationProc)(ALuint sid, ALuint notificationID, ALvoid* userData); -typedef ALenum (*alSourceAddNotificationProcPtr)(ALuint sid, ALuint notificationID, alSourceNotificationProc notifyProc, ALvoid* userData); -static ALenum alSourceAddNotificationExt(ALuint sid, ALuint notificationID, alSourceNotificationProc notifyProc, ALvoid* userData) +typedef ALenum (*alSourceAddNotificationProcPtr)(ALuint sid, + ALuint notificationID, + alSourceNotificationProc notifyProc, + ALvoid* userData); +static ALenum alSourceAddNotificationExt(ALuint sid, + ALuint notificationID, + alSourceNotificationProc notifyProc, + ALvoid* userData) { static alSourceAddNotificationProcPtr proc = nullptr; @@ -92,42 +100,48 @@ static ALenum alSourceAddNotificationExt(ALuint sid, ALuint notificationID, alSo return AL_INVALID_VALUE; } -#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS -@interface AudioEngineSessionHandler : NSObject -{ +# if CC_TARGET_PLATFORM == CC_PLATFORM_IOS +@interface AudioEngineSessionHandler : NSObject { } --(id) init; --(void)handleInterruption:(NSNotification*)notification; +- (id)init; +- (void)handleInterruption:(NSNotification*)notification; @end @implementation AudioEngineSessionHandler --(id) init +- (id)init { if (self = [super init]) { int deviceVer = [[[UIDevice currentDevice] systemVersion] intValue]; ALOGD("===> The device version: %d", deviceVer); - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:UIApplicationDidBecomeActiveNotification object:nil]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:UIApplicationWillResignActiveNotification object:nil]; - - BOOL success = [[AVAudioSession sharedInstance] - setCategory: AVAudioSessionCategoryAmbient - error: nil]; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(handleInterruption:) + name:AVAudioSessionInterruptionNotification + object:[AVAudioSession sharedInstance]]; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(handleInterruption:) + name:UIApplicationDidBecomeActiveNotification + object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(handleInterruption:) + name:UIApplicationWillResignActiveNotification + object:nil]; + + BOOL success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil]; if (!success) ALOGE("Fail to set audio session."); } return self; } --(void)handleInterruption:(NSNotification*)notification +- (void)handleInterruption:(NSNotification*)notification { static bool isAudioSessionInterrupted = false; - static bool resumeOnBecomingActive = false; - static bool pauseOnResignActive = false; + static bool resumeOnBecomingActive = false; + static bool pauseOnResignActive = false; if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification]) { @@ -138,13 +152,15 @@ -(void)handleInterruption:(NSNotification*)notification if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) { - ALOGD("AVAudioSessionInterruptionTypeBegan, application != UIApplicationStateActive, alcMakeContextCurrent(nullptr)"); + ALOGD("AVAudioSessionInterruptionTypeBegan, application != UIApplicationStateActive, " + "alcMakeContextCurrent(nullptr)"); } else { - ALOGD("AVAudioSessionInterruptionTypeBegan, application == UIApplicationStateActive, pauseOnResignActive = true"); + ALOGD("AVAudioSessionInterruptionTypeBegan, application == UIApplicationStateActive, " + "pauseOnResignActive = true"); } - + // We always pause device when interruption began ccALPauseDevice(); } @@ -154,8 +170,9 @@ -(void)handleInterruption:(NSNotification*)notification if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) { - ALOGD("AVAudioSessionInterruptionTypeEnded, application == UIApplicationStateActive, alcMakeContextCurrent(s_ALContext)"); - NSError *error = nil; + ALOGD("AVAudioSessionInterruptionTypeEnded, application == UIApplicationStateActive, " + "alcMakeContextCurrent(s_ALContext)"); + NSError* error = nil; [[AVAudioSession sharedInstance] setActive:YES error:&error]; ccALResumeDevice(); if (Director::getInstance()->isPaused()) @@ -166,7 +183,8 @@ -(void)handleInterruption:(NSNotification*)notification } else { - ALOGD("AVAudioSessionInterruptionTypeEnded, application != UIApplicationStateActive, resumeOnBecomingActive = true"); + ALOGD("AVAudioSessionInterruptionTypeEnded, application != UIApplicationStateActive, " + "resumeOnBecomingActive = true"); resumeOnBecomingActive = true; } } @@ -188,14 +206,15 @@ -(void)handleInterruption:(NSNotification*)notification { resumeOnBecomingActive = false; ALOGD("UIApplicationDidBecomeActiveNotification, alcMakeContextCurrent(s_ALContext)"); - NSError *error = nil; - BOOL success = [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: &error]; - if (!success) { + NSError* error = nil; + BOOL success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&error]; + if (!success) + { ALOGE("Fail to set audio session."); return; } [[AVAudioSession sharedInstance] setActive:YES error:&error]; - + ccALResumeDevice(); } else if (isAudioSessionInterrupted) @@ -205,18 +224,20 @@ -(void)handleInterruption:(NSNotification*)notification } } --(void) dealloc +- (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionInterruptionNotification object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil]; - [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:self + name:UIApplicationWillResignActiveNotification + object:nil]; [super dealloc]; } @end static id s_AudioEngineSessionHandler = nullptr; -#endif +# endif ALvoid AudioEngineImpl::myAlSourceNotificationCallback(ALuint sid, ALuint notificationID, ALvoid* userData) { @@ -239,10 +260,7 @@ -(void) dealloc #endif -AudioEngineImpl::AudioEngineImpl() -: _scheduled(false) -, _currentAudioID(0) -, _scheduler(nullptr) +AudioEngineImpl::AudioEngineImpl() : _scheduled(false), _currentAudioID(0), _scheduler(nullptr) { s_instance = this; } @@ -254,7 +272,8 @@ -(void) dealloc _scheduler->unschedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this); } - if (s_ALContext) { + if (s_ALContext) + { alDeleteSources(MAX_AUDIOINSTANCES, _alSources); _audioCaches.clear(); @@ -264,7 +283,8 @@ -(void) dealloc s_ALContext = nullptr; } - if (s_ALDevice) { + if (s_ALDevice) + { alcCloseDevice(s_ALDevice); s_ALDevice = nullptr; } @@ -280,30 +300,34 @@ -(void) dealloc bool AudioEngineImpl::init() { bool ret = false; - do{ + do + { #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS s_AudioEngineSessionHandler = [[AudioEngineSessionHandler alloc] init]; #endif s_ALDevice = alcOpenDevice(nullptr); - if (s_ALDevice) { + if (s_ALDevice) + { alGetError(); s_ALContext = alcCreateContext(s_ALDevice, nullptr); alcMakeContextCurrent(s_ALContext); alGenSources(MAX_AUDIOINSTANCES, _alSources); auto alError = alGetError(); - if(alError != AL_NO_ERROR) + if (alError != AL_NO_ERROR) { ALOGE("%s:generating sources failed! error = %x\n", __FUNCTION__, alError); break; } - for (int i = 0; i < MAX_AUDIOINSTANCES; ++i) { + for (int i = 0; i < MAX_AUDIOINSTANCES; ++i) + { _unusedSourcesPool.push(_alSources[i]); #if defined(__APPLE__) - alSourceAddNotificationExt(_alSources[i], AL_BUFFERS_PROCESSED, myAlSourceNotificationCallback, nullptr); + alSourceAddNotificationExt(_alSources[i], AL_BUFFERS_PROCESSED, myAlSourceNotificationCallback, + nullptr); #endif } @@ -368,28 +392,30 @@ AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids) #endif // ================ Workaround end ================ // - _scheduler = Director::getInstance()->getScheduler(); - ret = AudioDecoderManager::init(); - const char* vender = alGetString(AL_VENDOR); + _scheduler = Director::getInstance()->getScheduler(); + ret = AudioDecoderManager::init(); + const char* vender = alGetString(AL_VENDOR); const char* version = alGetString(AL_VERSION); ALOGI("OpenAL was initialized successfully, vender:%s, version:%s", vender, version); } - }while (false); + } while (false); return ret; } -AudioCache* AudioEngineImpl::preload(const std::string& filePath, std::function callback) +AudioCache* AudioEngineImpl::preload(std::string_view filePath, std::function callback) { AudioCache* audioCache = nullptr; auto it = _audioCaches.find(filePath); - if (it == _audioCaches.end()) { - audioCache = &_audioCaches[filePath]; + if (it == _audioCaches.end()) + { + audioCache = new AudioCache(); // hlookup_second(it); + _audioCaches.emplace(filePath, std::unique_ptr(audioCache)); audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath); - unsigned int cacheId = audioCache->_id; - auto isCacheDestroyed = audioCache->_isDestroyed; - AudioEngine::addTask([audioCache, cacheId, isCacheDestroyed](){ + unsigned int cacheId = audioCache->_id; + auto isCacheDestroyed = audioCache->_isDestroyed; + AudioEngine::addTask([audioCache, cacheId, isCacheDestroyed]() { if (*isCacheDestroyed) { ALOGV("AudioCache (id=%u) was destroyed, no need to launch readDataTask.", cacheId); @@ -399,8 +425,9 @@ AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids) audioCache->readDataTask(cacheId); }); } - else { - audioCache = &it->second; + else + { + audioCache = it->second.get(); } if (audioCache && callback) @@ -410,9 +437,10 @@ AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids) return audioCache; } -AUDIO_ID AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume) +AUDIO_ID AudioEngineImpl::play2d(std::string_view filePath, bool loop, float volume) { - if (s_ALDevice == nullptr) { + if (s_ALDevice == nullptr) + { return AudioEngine::INVALID_AUDIO_ID; } @@ -423,16 +451,18 @@ AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids) } auto player = new AudioPlayer; - if (player == nullptr) { + if (player == nullptr) + { return AudioEngine::INVALID_AUDIO_ID; } player->_alSource = alSource; - player->_loop = loop; - player->_volume = volume; + player->_loop = loop; + player->_volume = volume; auto audioCache = preload(filePath, nullptr); - if (audioCache == nullptr) { + if (audioCache == nullptr) + { delete player; return AudioEngine::INVALID_AUDIO_ID; } @@ -442,7 +472,7 @@ AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids) _audioPlayers.emplace(++_currentAudioID, player); _threadMutex.unlock(); - audioCache->addPlayCallback(std::bind(&AudioEngineImpl::_play2d,this,audioCache,_currentAudioID)); + audioCache->addPlayCallback(std::bind(&AudioEngineImpl::_play2d, this, audioCache, _currentAudioID)); if (!_scheduled) { @@ -453,7 +483,7 @@ AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids) return _currentAudioID; } -void AudioEngineImpl::_play2d(AudioCache *cache, AUDIO_ID audioID) +void AudioEngineImpl::_play2d(AudioCache* cache, AUDIO_ID audioID) { std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); @@ -461,13 +491,14 @@ AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids) return; auto player = iter->second; - //Note: It maybe in sub thread or main thread :( + // Note: It maybe in sub thread or main thread :( if (!*cache->_isDestroyed && cache->_state == AudioCache::State::READY) { - if (player->play2d()) { - _scheduler->performFunctionInCocosThread([audioID](){ - - if (AudioEngine::_audioIDInfoMap.find(audioID) != AudioEngine::_audioIDInfoMap.end()) { + if (player->play2d()) + { + _scheduler->performFunctionInCocosThread([audioID]() { + if (AudioEngine::_audioIDInfoMap.find(audioID) != AudioEngine::_audioIDInfoMap.end()) + { AudioEngine::_audioIDInfoMap[audioID].state = AudioEngine::AudioState::PLAYING; } }); @@ -492,23 +523,25 @@ AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids) return sourceId; } -void AudioEngineImpl::setVolume(AUDIO_ID audioID,float volume) +void AudioEngineImpl::setVolume(AUDIO_ID audioID, float volume) { std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if(iter == _audioPlayers.end()) + if (iter == _audioPlayers.end()) return; - + auto player = iter->second; lck.unlock(); - + player->_volume = volume; - if (player->_ready) { + if (player->_ready) + { alSourcef(player->_alSource, AL_GAIN, volume); auto error = alGetError(); - if (error != AL_NO_ERROR) { + if (error != AL_NO_ERROR) + { ALOGE("%s: audio id = " AUDIO_ID_PRID ", error = %x", __FUNCTION__, audioID, error); } } @@ -518,30 +551,39 @@ AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids) { std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if(iter == _audioPlayers.end()) + if (iter == _audioPlayers.end()) return; - + auto player = iter->second; lck.unlock(); - - if (player->_ready) { - if (player->_streamingSource) { + + if (player->_ready) + { + if (player->_streamingSource) + { player->setLoop(loop); - } else { - if (loop) { + } + else + { + if (loop) + { alSourcei(player->_alSource, AL_LOOPING, AL_TRUE); - } else { + } + else + { alSourcei(player->_alSource, AL_LOOPING, AL_FALSE); } auto error = alGetError(); - if (error != AL_NO_ERROR) { + if (error != AL_NO_ERROR) + { ALOGE("%s: audio id = " AUDIO_ID_PRID ", error = %x", __FUNCTION__, audioID, error); } } } - else { + else + { player->_loop = loop; } } @@ -550,18 +592,19 @@ AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids) { std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if(iter == _audioPlayers.end()) + if (iter == _audioPlayers.end()) return false; - + auto player = iter->second; - + lck.unlock(); - + bool ret = true; alSourcePause(player->_alSource); auto error = alGetError(); - if (error != AL_NO_ERROR) { + if (error != AL_NO_ERROR) + { ret = false; ALOGE("%s: audio id = " AUDIO_ID_PRID ", error = %x\n", __FUNCTION__, audioID, error); } @@ -574,16 +617,17 @@ AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids) bool ret = true; std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if(iter == _audioPlayers.end()) + if (iter == _audioPlayers.end()) return false; - + auto player = iter->second; lck.unlock(); - + alSourcePlay(player->_alSource); auto error = alGetError(); - if (error != AL_NO_ERROR) { + if (error != AL_NO_ERROR) + { ret = false; ALOGE("%s: audio id = " AUDIO_ID_PRID ", error = %x\n", __FUNCTION__, audioID, error); } @@ -595,29 +639,30 @@ AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids) { std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if(iter == _audioPlayers.end()) + if (iter == _audioPlayers.end()) return; - + auto player = iter->second; player->destroy(); - // Call '_updatePlayersState' method to cleanup immediately since the schedule may be cancelled without any notification. + // Call '_updatePlayersState' method to cleanup immediately since the schedule may be cancelled without any + // notification. _updatePlayers(true); } void AudioEngineImpl::stopAll() { std::lock_guard lck(_threadMutex); - for(auto&& player : _audioPlayers) + for (auto&& player : _audioPlayers) { player.second->destroy(); } - //Note: Don't set the flag to false here, it should be set in 'update' function. + // Note: Don't set the flag to false here, it should be set in 'update' function. // Otherwise, the state got from alSourceState may be wrong -// for(int index = 0; index < MAX_AUDIOINSTANCES; ++index) -// { -// _alSourceUsed[_alSources[index]] = false; -// } + // for(int index = 0; index < MAX_AUDIOINSTANCES; ++index) + // { + // _alSourceUsed[_alSources[index]] = false; + // } // Call '_updatePlayers' method to cleanup immediately since the schedule may be cancelled without any notification. _updatePlayers(true); @@ -627,9 +672,11 @@ AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids) { std::lock_guard lck(_threadMutex); auto it = _audioPlayers.find(audioID); - if (it != _audioPlayers.end()) { + if (it != _audioPlayers.end()) + { auto player = it->second; - if (player->_ready) { + if (player->_ready) + { return player->_audioCache->_duration; } } @@ -639,21 +686,25 @@ AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids) float AudioEngineImpl::getCurrentTime(AUDIO_ID audioID) { std::unique_lock lck(_threadMutex); - auto it = _audioPlayers.find(audioID); + auto it = _audioPlayers.find(audioID); if (it == _audioPlayers.end()) return 0.0f; - float ret = 0.0f; + float ret = 0.0f; auto player = it->second; - if (player->_ready) { - if (player->_streamingSource) { + if (player->_ready) + { + if (player->_streamingSource) + { ret = player->getTime(); } - else { + else + { alGetSourcef(player->_alSource, AL_SEC_OFFSET, &ret); auto error = alGetError(); - if (error != AL_NO_ERROR) { + if (error != AL_NO_ERROR) + { ALOGE("%s, audio id:" AUDIO_ID_PRID ",error code:%x", __FUNCTION__, audioID, error); } } @@ -667,23 +718,28 @@ AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids) bool ret = false; std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if(iter == _audioPlayers.end()) + if (iter == _audioPlayers.end()) return false; - + auto player = iter->second; - do { - if (!player->_ready) { + do + { + if (!player->_ready) + { break; } - if (player->_streamingSource) { + if (player->_streamingSource) + { ret = player->setTime(time); break; } - else { + else + { if (player->_audioCache->_framesRead != player->_audioCache->_totalFrames && - (time * player->_audioCache->_sampleRate) > player->_audioCache->_framesRead) { + (time * player->_audioCache->_sampleRate) > player->_audioCache->_framesRead) + { ALOGE("%s: audio id = " AUDIO_ID_PRID, __FUNCTION__, audioID); break; } @@ -691,7 +747,8 @@ AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids) alSourcef(player->_alSource, AL_SEC_OFFSET, time); auto error = alGetError(); - if (error != AL_NO_ERROR) { + if (error != AL_NO_ERROR) + { ALOGE("%s: audio id = " AUDIO_ID_PRID ", error = %x", __FUNCTION__, audioID, error); } ret = true; @@ -701,16 +758,17 @@ AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids) return ret; } -void AudioEngineImpl::setFinishCallback(AUDIO_ID audioID, const std::function &callback) +void AudioEngineImpl::setFinishCallback(AUDIO_ID audioID, + const std::function& callback) { std::unique_lock lck(_threadMutex); auto iter = _audioPlayers.find(audioID); - if(iter == _audioPlayers.end()) + if (iter == _audioPlayers.end()) return; - + auto player = iter->second; lck.unlock(); - + player->_finishCallbak = callback; } @@ -726,45 +784,49 @@ AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids) AudioPlayer* player; ALuint alSource; -// ALOGV("AudioPlayer count: %d", (int)_audioPlayers.size()); - for (auto it = _audioPlayers.begin(); it != _audioPlayers.end(); ) { - audioID = it->first; - player = it->second; + // ALOGV("AudioPlayer count: %d", (int)_audioPlayers.size()); + for (auto it = _audioPlayers.begin(); it != _audioPlayers.end();) + { + audioID = it->first; + player = it->second; alSource = player->_alSource; if (player->_removeByAudioEngine) { AudioEngine::remove(audioID); - + it = _audioPlayers.erase(it); delete player; _unusedSourcesPool.push(alSource); } - else if (player->_ready && player->isFinished()) { + else if (player->_ready && player->isFinished()) + { std::string filePath; - if (player->_finishCallbak) { + if (player->_finishCallbak) + { auto& audioInfo = AudioEngine::_audioIDInfoMap[audioID]; - filePath = audioInfo.filePath; + filePath = audioInfo.filePath; } AudioEngine::remove(audioID); - + it = _audioPlayers.erase(it); - if (player->_finishCallbak) { + if (player->_finishCallbak) + { /// ###IMPORTANT: don't call immidiately, because at callback, user-end may play a new audio /// cause _audioPlayers' iterator goan to invalid. - _finishCallbacks.push_back([finishCallback = std::move(player->_finishCallbak), audioID, filePath = std::move(filePath)](){ - finishCallback(audioID, filePath); - }); + _finishCallbacks.push_back([finishCallback = std::move(player->_finishCallbak), audioID, + filePath = std::move(filePath)]() { finishCallback(audioID, filePath); }); } // clear cache when audio player finsihed properly player->setCache(nullptr); delete player; _unusedSourcesPool.push(alSource); } - else{ + else + { ++it; } } @@ -786,7 +848,8 @@ AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids) _unscheduleUpdate(); } -void AudioEngineImpl::_unscheduleUpdate() { +void AudioEngineImpl::_unscheduleUpdate() +{ if (_scheduled) { _scheduled = false; @@ -794,7 +857,7 @@ AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids) } } -void AudioEngineImpl::uncache(const std::string &filePath) +void AudioEngineImpl::uncache(std::string_view filePath) { _audioCaches.erase(filePath); } diff --git a/cocos/base/CCAutoreleasePool.cpp b/cocos/base/CCAutoreleasePool.cpp index 9be2e9cdf0f6..3027fee8a0f8 100644 --- a/cocos/base/CCAutoreleasePool.cpp +++ b/cocos/base/CCAutoreleasePool.cpp @@ -38,7 +38,7 @@ AutoreleasePool::AutoreleasePool() PoolManager::getInstance()->push(this); } -AutoreleasePool::AutoreleasePool(const std::string& name) +AutoreleasePool::AutoreleasePool(std::string_view name) : _name(name) #if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) , _isClearing(false) diff --git a/cocos/base/CCAutoreleasePool.h b/cocos/base/CCAutoreleasePool.h index fde07e39ded7..d2a8341adef2 100644 --- a/cocos/base/CCAutoreleasePool.h +++ b/cocos/base/CCAutoreleasePool.h @@ -58,7 +58,7 @@ class CC_DLL AutoreleasePool * * @param name The name of created autorelease pool. */ - AutoreleasePool(const std::string& name); + AutoreleasePool(std::string_view name); /** * @js NA diff --git a/cocos/base/CCConfiguration.cpp b/cocos/base/CCConfiguration.cpp index 0d623209a947..1979f0225c22 100644 --- a/cocos/base/CCConfiguration.cpp +++ b/cocos/base/CCConfiguration.cpp @@ -186,7 +186,7 @@ void Configuration::destroyInstance() CC_SAFE_RELEASE_NULL(s_sharedConfiguration); } -bool Configuration::checkForGLExtension(const std::string& searchName) const +bool Configuration::checkForGLExtension(std::string_view searchName) const { return _glExtensions.find(searchName) != std::string::npos; } @@ -315,7 +315,7 @@ Animate3DQuality Configuration::getAnimate3DQuality() const // // generic getters for properties // -const Value& Configuration::getValue(const std::string& key, const Value& defaultValue) const +const Value& Configuration::getValue(std::string_view key, const Value& defaultValue) const { auto iter = _valueDict.find(key); if (iter != _valueDict.cend()) @@ -324,15 +324,15 @@ const Value& Configuration::getValue(const std::string& key, const Value& defaul return defaultValue; } -void Configuration::setValue(const std::string& key, const Value& value) +void Configuration::setValue(std::string_view key, const Value& value) { - _valueDict[key] = value; + hlookup::set_item(_valueDict, key, value); // _valueDict[key] = value; } // // load file // -void Configuration::loadConfigFile(const std::string& filename) +void Configuration::loadConfigFile(std::string_view filename) { ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(filename); CCASSERT(!dict.empty(), "cannot create dictionary"); @@ -360,14 +360,14 @@ void Configuration::loadConfigFile(const std::string& filename) if (!validMetadata) { - CCLOG("Invalid config format for file: %s", filename.c_str()); + CCLOG("Invalid config format for file: %s", filename.data()); return; } auto dataIter = dict.find("data"); if (dataIter == dict.cend() || dataIter->second.getType() != Value::Type::MAP) { - CCLOG("Expected 'data' dict, but not found. Config file: %s", filename.c_str()); + CCLOG("Expected 'data' dict, but not found. Config file: %s", filename.data()); return; } diff --git a/cocos/base/CCConfiguration.h b/cocos/base/CCConfiguration.h index 976113588474..aefcefbede10 100644 --- a/cocos/base/CCConfiguration.h +++ b/cocos/base/CCConfiguration.h @@ -205,7 +205,7 @@ class CC_DLL Configuration : public Ref * @param searchName A given search name. * @return Is true if an OpenGL is supported. */ - bool checkForGLExtension(const std::string& searchName) const; + bool checkForGLExtension(std::string_view searchName) const; /** Initialize method. * @@ -219,14 +219,14 @@ class CC_DLL Configuration : public Ref * @param defaultValue if not find the value, return the defaultValue. * @return */ - const Value& getValue(const std::string& key, const Value& defaultValue = Value::Null) const; + const Value& getValue(std::string_view key, const Value& defaultValue = Value::Null) const; /** Sets a new key/value pair in the configuration dictionary. * * @param key A given key. * @param value A given value. */ - void setValue(const std::string& key, const Value& value); + void setValue(std::string_view key, const Value& value); /** Returns the Configuration info. * @@ -243,7 +243,7 @@ class CC_DLL Configuration : public Ref * * @param filename Config file name. */ - void loadConfigFile(const std::string& filename); + void loadConfigFile(std::string_view filename); static const char* CONFIG_FILE_LOADED; diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index c0953cb9e517..60c03d7aa6da 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -204,9 +204,10 @@ std::string& Console::Utility::trim(std::string& s) return Console::Utility::ltrim(Console::Utility::rtrim(s)); } -std::vector& Console::Utility::split(const std::string& s, char delim, std::vector& elems) +std::vector& Console::Utility::split(std::string_view s, char delim, std::vector& elems) { - std::stringstream ss(s); + std::stringstream ss; + ss << s; std::string item; while (std::getline(ss, item, delim)) { @@ -215,7 +216,7 @@ std::vector& Console::Utility::split(const std::string& s, char del return elems; } -std::vector Console::Utility::split(const std::string& s, char delim) +std::vector Console::Utility::split(std::string_view s, char delim) { std::vector elems; Console::Utility::split(s, delim, elems); @@ -223,13 +224,14 @@ std::vector Console::Utility::split(const std::string& s, char deli } // isFloat taken from http://stackoverflow.com/questions/447206/c-isfloat-function -bool Console::Utility::isFloat(const std::string& myString) +bool Console::Utility::isFloat(std::string_view myString) { - std::istringstream iss(myString); + std::stringstream ss; + ss << myString; float f; - iss >> std::noskipws >> f; // noskipws considers leading whitespace invalid + ss >> std::noskipws >> f; // noskipws considers leading whitespace invalid // Check the entire string was consumed and if either failbit or badbit is set - return iss.eof() && !iss.fail(); + return ss.eof() && !ss.fail(); } ssize_t Console::Utility::sendToConsole(int fd, const void* buffer, size_t length, int flags) @@ -275,12 +277,12 @@ void Console::Utility::sendPrompt(int fd) send(fd, prompt, strlen(prompt), 0); } -void Console::Utility::setPrompt(const std::string& prompt) +void Console::Utility::setPrompt(std::string_view prompt) { _prompt = prompt; } -const std::string& Console::Utility::getPrompt() +std::string_view Console::Utility::getPrompt() { return _prompt; } @@ -291,11 +293,10 @@ const std::string& Console::Utility::getPrompt() Console::Command::Command() : _callback(nullptr) {} -Console::Command::Command(const std::string& name, const std::string& help) - : _name(name), _help(help), _callback(nullptr) +Console::Command::Command(std::string_view name, std::string_view help) : _name(name), _help(help), _callback(nullptr) {} -Console::Command::Command(const std::string& name, const std::string& help, const Callback& callback) +Console::Command::Command(std::string_view name, std::string_view help, const Callback& callback) : _name(name), _help(help), _callback(callback) {} @@ -378,7 +379,7 @@ void Console::Command::addSubCommand(const Command& subCmd) _subCommands[subCmd._name] = cmd; } -const Console::Command* Console::Command::getSubCommand(const std::string& subCmdName) const +const Console::Command* Console::Command::getSubCommand(std::string_view subCmdName) const { auto it = _subCommands.find(subCmdName); if (it != _subCommands.end()) @@ -389,7 +390,7 @@ const Console::Command* Console::Command::getSubCommand(const std::string& subCm return nullptr; } -void Console::Command::delSubCommand(const std::string& subCmdName) +void Console::Command::delSubCommand(std::string_view subCmdName) { auto iter = _subCommands.find(subCmdName); if (iter != _subCommands.end()) @@ -399,7 +400,7 @@ void Console::Command::delSubCommand(const std::string& subCmdName) } } -void Console::Command::commandHelp(int fd, const std::string& /*args*/) +void Console::Command::commandHelp(int fd, std::string_view /*args*/) { if (!_help.empty()) { @@ -412,7 +413,7 @@ void Console::Command::commandHelp(int fd, const std::string& /*args*/) } } -void Console::Command::commandGeneric(int fd, const std::string& args) +void Console::Command::commandGeneric(int fd, std::string_view args) { // The first argument (including the empty) std::string key(args); @@ -621,10 +622,10 @@ void Console::addCommand(const Command& cmd) delete iter->second; _commands.erase(iter); } - _commands[cmd.getName()] = newCommand; + _commands.emplace(cmd.getName(), newCommand); // _commands[cmd.getName()] = newCommand; } -void Console::addSubCommand(const std::string& cmdName, const Command& subCmd) +void Console::addSubCommand(std::string_view cmdName, const Command& subCmd) { auto it = _commands.find(cmdName); if (it != _commands.end()) @@ -639,7 +640,7 @@ void Console::addSubCommand(Command& cmd, const Command& subCmd) cmd.addSubCommand(subCmd); } -const Console::Command* Console::getCommand(const std::string& cmdName) +const Console::Command* Console::getCommand(std::string_view cmdName) { auto it = _commands.find(cmdName); if (it != _commands.end()) @@ -650,7 +651,7 @@ const Console::Command* Console::getCommand(const std::string& cmdName) return nullptr; } -const Console::Command* Console::getSubCommand(const std::string& cmdName, const std::string& subCmdName) +const Console::Command* Console::getSubCommand(std::string_view cmdName, std::string_view subCmdName) { auto it = _commands.find(cmdName); if (it != _commands.end()) @@ -661,12 +662,12 @@ const Console::Command* Console::getSubCommand(const std::string& cmdName, const return nullptr; } -const Console::Command* Console::getSubCommand(const Command& cmd, const std::string& subCmdName) +const Console::Command* Console::getSubCommand(const Command& cmd, std::string_view subCmdName) { return cmd.getSubCommand(subCmdName); } -void Console::delCommand(const std::string& cmdName) +void Console::delCommand(std::string_view cmdName) { auto it = _commands.find(cmdName); if (it != _commands.end()) @@ -676,7 +677,7 @@ void Console::delCommand(const std::string& cmdName) } } -void Console::delSubCommand(const std::string& cmdName, const std::string& subCmdName) +void Console::delSubCommand(std::string_view cmdName, std::string_view subCmdName) { auto it = _commands.find(cmdName); if (it != _commands.end()) @@ -686,7 +687,7 @@ void Console::delSubCommand(const std::string& cmdName, const std::string& subCm } } -void Console::delSubCommand(Command& cmd, const std::string& subCmdName) +void Console::delSubCommand(Command& cmd, std::string_view subCmdName) { cmd.delSubCommand(subCmdName); } @@ -701,7 +702,7 @@ void Console::log(const char* buf) } } -void Console::setBindAddress(const std::string& address) +void Console::setBindAddress(std::string_view address) { _bindAddress = address; } @@ -973,7 +974,7 @@ bool Console::parseCommand(socket_native_type fd) return true; } -void Console::performCommand(socket_native_type fd, const std::string& command) +void Console::performCommand(socket_native_type fd, std::string_view command) { std::vector args = Console::Utility::split(command, ' '); if (args.empty()) @@ -998,7 +999,7 @@ void Console::performCommand(socket_native_type fd, const std::string& command) } else { - throw std::runtime_error("Unknown command " + command + ". Type 'help' for options\n"); + throw std::runtime_error(std::string{"Unknown command "}.append(command).append(". Type 'help' for options\n")); } } @@ -1162,7 +1163,7 @@ void Console::createCommandVersion() // commands // -void Console::commandAllocator(socket_native_type fd, const std::string& /*args*/) +void Console::commandAllocator(socket_native_type fd, std::string_view /*args*/) { #if CC_ENABLE_ALLOCATOR_DIAGNOSTICS auto info = allocator::AllocatorDiagnostics::instance()->diagnostics(); @@ -1173,7 +1174,7 @@ void Console::commandAllocator(socket_native_type fd, const std::string& /*args* #endif } -void Console::commandConfig(socket_native_type fd, const std::string& /*args*/) +void Console::commandConfig(socket_native_type fd, std::string_view /*args*/) { Scheduler* sched = Director::getInstance()->getScheduler(); sched->performFunctionInCocosThread([=]() { @@ -1182,49 +1183,49 @@ void Console::commandConfig(socket_native_type fd, const std::string& /*args*/) }); } -void Console::commandDebugMsg(socket_native_type fd, const std::string& /*args*/) +void Console::commandDebugMsg(socket_native_type fd, std::string_view /*args*/) { Console::Utility::mydprintf(fd, "Debug message is: %s\n", _sendDebugStrings ? "on" : "off"); } -void Console::commandDebugMsgSubCommandOnOff(socket_native_type /*fd*/, const std::string& args) +void Console::commandDebugMsgSubCommandOnOff(socket_native_type /*fd*/, std::string_view args) { _sendDebugStrings = (args.compare("on") == 0); } -void Console::commandDirectorSubCommandPause(socket_native_type /*fd*/, const std::string& /*args*/) +void Console::commandDirectorSubCommandPause(socket_native_type /*fd*/, std::string_view /*args*/) { auto director = Director::getInstance(); Scheduler* sched = director->getScheduler(); sched->performFunctionInCocosThread([]() { Director::getInstance()->pause(); }); } -void Console::commandDirectorSubCommandResume(socket_native_type /*fd*/, const std::string& /*args*/) +void Console::commandDirectorSubCommandResume(socket_native_type /*fd*/, std::string_view /*args*/) { auto director = Director::getInstance(); director->resume(); } -void Console::commandDirectorSubCommandStop(socket_native_type /*fd*/, const std::string& /*args*/) +void Console::commandDirectorSubCommandStop(socket_native_type /*fd*/, std::string_view /*args*/) { auto director = Director::getInstance(); Scheduler* sched = director->getScheduler(); sched->performFunctionInCocosThread([]() { Director::getInstance()->stopAnimation(); }); } -void Console::commandDirectorSubCommandStart(socket_native_type /*fd*/, const std::string& /*args*/) +void Console::commandDirectorSubCommandStart(socket_native_type /*fd*/, std::string_view /*args*/) { auto director = Director::getInstance(); director->startAnimation(); } -void Console::commandDirectorSubCommandEnd(socket_native_type /*fd*/, const std::string& /*args*/) +void Console::commandDirectorSubCommandEnd(socket_native_type /*fd*/, std::string_view /*args*/) { auto director = Director::getInstance(); director->end(); } -void Console::commandExit(socket_native_type fd, const std::string& /*args*/) +void Console::commandExit(socket_native_type fd, std::string_view /*args*/) { FD_CLR(fd, &_read_set); _fds.erase(std::remove(_fds.begin(), _fds.end(), fd), _fds.end()); @@ -1235,23 +1236,23 @@ void Console::commandExit(socket_native_type fd, const std::string& /*args*/) #endif } -void Console::commandFileUtils(socket_native_type fd, const std::string& /*args*/) +void Console::commandFileUtils(socket_native_type fd, std::string_view /*args*/) { Scheduler* sched = Director::getInstance()->getScheduler(); sched->performFunctionInCocosThread(std::bind(&Console::printFileUtils, this, fd)); } -void Console::commandFileUtilsSubCommandFlush(socket_native_type /*fd*/, const std::string& /*args*/) +void Console::commandFileUtilsSubCommandFlush(socket_native_type /*fd*/, std::string_view /*args*/) { FileUtils::getInstance()->purgeCachedEntries(); } -void Console::commandFps(socket_native_type fd, const std::string& /*args*/) +void Console::commandFps(socket_native_type fd, std::string_view /*args*/) { Console::Utility::mydprintf(fd, "FPS is: %s\n", Director::getInstance()->isDisplayStats() ? "on" : "off"); } -void Console::commandFpsSubCommandOnOff(socket_native_type /*fd*/, const std::string& args) +void Console::commandFpsSubCommandOnOff(socket_native_type /*fd*/, std::string_view args) { bool state = (args.compare("on") == 0); Director* dir = Director::getInstance(); @@ -1259,12 +1260,12 @@ void Console::commandFpsSubCommandOnOff(socket_native_type /*fd*/, const std::st sched->performFunctionInCocosThread(std::bind(&Director::setDisplayStats, dir, state)); } -void Console::commandHelp(socket_native_type fd, const std::string& /*args*/) +void Console::commandHelp(socket_native_type fd, std::string_view /*args*/) { sendHelp(fd, _commands, "\nAvailable commands:\n"); } -void Console::commandProjection(socket_native_type fd, const std::string& /*args*/) +void Console::commandProjection(socket_native_type fd, std::string_view /*args*/) { auto director = Director::getInstance(); char buf[20]; @@ -1288,25 +1289,26 @@ void Console::commandProjection(socket_native_type fd, const std::string& /*args Console::Utility::mydprintf(fd, "Current projection: %s\n", buf); } -void Console::commandProjectionSubCommand2d(socket_native_type /*fd*/, const std::string& /*args*/) +void Console::commandProjectionSubCommand2d(socket_native_type /*fd*/, std::string_view /*args*/) { auto director = Director::getInstance(); Scheduler* sched = director->getScheduler(); sched->performFunctionInCocosThread([=]() { director->setProjection(Director::Projection::_2D); }); } -void Console::commandProjectionSubCommand3d(socket_native_type /*fd*/, const std::string& /*args*/) +void Console::commandProjectionSubCommand3d(socket_native_type /*fd*/, std::string_view /*args*/) { auto director = Director::getInstance(); Scheduler* sched = director->getScheduler(); sched->performFunctionInCocosThread([=]() { director->setProjection(Director::Projection::_3D); }); } -void Console::commandResolution(socket_native_type /*fd*/, const std::string& args) +void Console::commandResolution(socket_native_type /*fd*/, std::string_view args) { int policy; float width, height; - std::istringstream stream(args); + std::stringstream stream; + stream << args; stream >> width >> height >> policy; Scheduler* sched = Director::getInstance()->getScheduler(); @@ -1316,7 +1318,7 @@ void Console::commandResolution(socket_native_type /*fd*/, const std::string& ar }); } -void Console::commandResolutionSubCommandEmpty(socket_native_type fd, const std::string& /*args*/) +void Console::commandResolutionSubCommandEmpty(socket_native_type fd, std::string_view /*args*/) { auto director = Director::getInstance(); Vec2 points = director->getWinSize(); @@ -1340,13 +1342,13 @@ void Console::commandResolutionSubCommandEmpty(socket_native_type fd, const std: (int)visibleRect.origin.y, (int)visibleRect.size.width, (int)visibleRect.size.height); } -void Console::commandSceneGraph(socket_native_type fd, const std::string& /*args*/) +void Console::commandSceneGraph(socket_native_type fd, std::string_view /*args*/) { Scheduler* sched = Director::getInstance()->getScheduler(); sched->performFunctionInCocosThread(std::bind(&Console::printSceneGraphBoot, this, fd)); } -void Console::commandTextures(socket_native_type fd, const std::string& /*args*/) +void Console::commandTextures(socket_native_type fd, std::string_view /*args*/) { Scheduler* sched = Director::getInstance()->getScheduler(); sched->performFunctionInCocosThread([=]() { @@ -1356,13 +1358,13 @@ void Console::commandTextures(socket_native_type fd, const std::string& /*args*/ }); } -void Console::commandTexturesSubCommandFlush(socket_native_type /*fd*/, const std::string& /*args*/) +void Console::commandTexturesSubCommandFlush(socket_native_type /*fd*/, std::string_view /*args*/) { Scheduler* sched = Director::getInstance()->getScheduler(); sched->performFunctionInCocosThread([]() { Director::getInstance()->getTextureCache()->removeAllTextures(); }); } -void Console::commandTouchSubCommandTap(socket_native_type fd, const std::string& args) +void Console::commandTouchSubCommandTap(socket_native_type fd, std::string_view args) { auto argv = Console::Utility::split(args, ' '); @@ -1387,7 +1389,7 @@ void Console::commandTouchSubCommandTap(socket_native_type fd, const std::string } } -void Console::commandTouchSubCommandSwipe(socket_native_type fd, const std::string& args) +void Console::commandTouchSubCommandSwipe(socket_native_type fd, std::string_view args) { auto argv = Console::Utility::split(args, ' '); @@ -1558,7 +1560,7 @@ void Console::commandUpload(socket_native_type fd) } } -void Console::commandVersion(socket_native_type fd, const std::string& /*args*/) +void Console::commandVersion(socket_native_type fd, std::string_view /*args*/) { Console::Utility::mydprintf(fd, "%s\n", adxeVersion()); } @@ -1618,9 +1620,7 @@ void Console::printFileUtils(socket_native_type fd) Console::Utility::sendPrompt(fd); } -void Console::sendHelp(socket_native_type fd, - const std::unordered_map& commands, - const char* msg) +void Console::sendHelp(socket_native_type fd, const hlookup::string_map& commands, const char* msg) { Console::Utility::sendToConsole(fd, msg, strlen(msg)); for (auto& it : commands) @@ -1629,14 +1629,14 @@ void Console::sendHelp(socket_native_type fd, if (command->getHelp().empty()) continue; - Console::Utility::mydprintf(fd, "\t%s", command->getName().c_str()); - ssize_t tabs = strlen(command->getName().c_str()) / 8; + Console::Utility::mydprintf(fd, "\t%s", command->getName().data()); + ssize_t tabs = command->getName().length() / 8; tabs = 3 - tabs; for (int j = 0; j < tabs; j++) { Console::Utility::mydprintf(fd, "\t"); } - Console::Utility::mydprintf(fd, "%s\n", command->getHelp().c_str()); + Console::Utility::mydprintf(fd, "%s\n", command->getHelp().data()); } } diff --git a/cocos/base/CCConsole.h b/cocos/base/CCConsole.h index 20f5aa54f446..07882085c6b7 100644 --- a/cocos/base/CCConsole.h +++ b/cocos/base/CCConsole.h @@ -82,11 +82,11 @@ class CC_DLL Console : public Ref static std::string& trim(std::string& s); // split - static std::vector& split(const std::string& s, char delim, std::vector& elems); - static std::vector split(const std::string& s, char delim); + static std::vector& split(std::string_view s, char delim, std::vector& elems); + static std::vector split(std::string_view s, char delim); /** Checks myString is a floating-point type. */ - static bool isFloat(const std::string& myString); + static bool isFloat(std::string_view myString); /** send a message to console */ static ssize_t sendToConsole(int fd, const void* buffer, size_t length, int flags = 0); @@ -98,10 +98,10 @@ class CC_DLL Console : public Ref static void sendPrompt(int fd); /** set a new string for the prompt. */ - static void setPrompt(const std::string& prompt); + static void setPrompt(std::string_view prompt); /** get the prompt string. */ - static const std::string& getPrompt(); + static std::string_view getPrompt(); private: static std::string _prompt; /*!< prompt */ @@ -111,11 +111,11 @@ class CC_DLL Console : public Ref class CC_DLL Command { public: - using Callback = std::function; + using Callback = std::function; /** Constructor */ Command(); - Command(const std::string& name, const std::string& help); - Command(const std::string& name, const std::string& help, const Callback& callback); + Command(std::string_view name, std::string_view help); + Command(std::string_view name, std::string_view help, const Callback& callback); /** Copy constructor */ Command(const Command& o); @@ -139,29 +139,29 @@ class CC_DLL Console : public Ref void addSubCommand(const Command& subCmd); /** get sub command */ - const Command* getSubCommand(const std::string& subCmdName) const; + const Command* getSubCommand(std::string_view subCmdName) const; /** delete sub command */ - void delSubCommand(const std::string& subCmdName); + void delSubCommand(std::string_view subCmdName); /** help command handler */ - void commandHelp(int fd, const std::string& args); + void commandHelp(int fd, std::string_view args); /** generic command handler */ - void commandGeneric(int fd, const std::string& args); + void commandGeneric(int fd, std::string_view args); /** Gets the name of the current command */ - const std::string& getName() const { return _name; } + std::string_view getName() const { return _name; } /** Gets the help information of the current command */ - const std::string& getHelp() const { return _help; } + std::string_view getHelp() const { return _help; } private: std::string _name; std::string _help; Callback _callback; - std::unordered_map _subCommands; + hlookup::string_map _subCommands; }; /** Constructor */ @@ -181,18 +181,18 @@ class CC_DLL Console : public Ref /** add custom command */ void addCommand(const Command& cmd); - void addSubCommand(const std::string& cmdName, const Command& subCmd); + void addSubCommand(std::string_view cmdName, const Command& subCmd); void addSubCommand(Command& cmd, const Command& subCmd); /** get custom command */ - const Command* getCommand(const std::string& cmdName); - const Command* getSubCommand(const std::string& cmdName, const std::string& subCmdName); - const Command* getSubCommand(const Command& cmd, const std::string& subCmdName); + const Command* getCommand(std::string_view cmdName); + const Command* getSubCommand(std::string_view cmdName, std::string_view subCmdName); + const Command* getSubCommand(const Command& cmd, std::string_view subCmdName); /** delete custom command */ - void delCommand(const std::string& cmdName); - void delSubCommand(const std::string& cmdName, const std::string& subCmdName); - void delSubCommand(Command& cmd, const std::string& subCmdName); + void delCommand(std::string_view cmdName); + void delSubCommand(std::string_view cmdName, std::string_view subCmdName); + void delSubCommand(Command& cmd, std::string_view subCmdName); /** log something in the console */ void log(const char* buf); @@ -202,7 +202,7 @@ class CC_DLL Console : public Ref * * @address : 127.0.0.1 */ - void setBindAddress(const std::string& address); + void setBindAddress(std::string_view address); /** Checks whether the server for console is bound with ipv6 address */ bool isIpv6Server() const; @@ -218,7 +218,7 @@ class CC_DLL Console : public Ref ssize_t readline(socket_native_type fd, char* buf, size_t maxlen); ssize_t readBytes(socket_native_type fd, char* buffer, size_t maxlen, bool* more); bool parseCommand(socket_native_type fd); - void performCommand(socket_native_type fd, const std::string& command); + void performCommand(socket_native_type fd, std::string_view command); void addClient(); @@ -240,33 +240,33 @@ class CC_DLL Console : public Ref void createCommandVersion(); // Add commands here - void commandAllocator(socket_native_type fd, const std::string& args); - void commandConfig(socket_native_type fd, const std::string& args); - void commandDebugMsg(socket_native_type fd, const std::string& args); - void commandDebugMsgSubCommandOnOff(socket_native_type fd, const std::string& args); - void commandDirectorSubCommandPause(socket_native_type fd, const std::string& args); - void commandDirectorSubCommandResume(socket_native_type fd, const std::string& args); - void commandDirectorSubCommandStop(socket_native_type fd, const std::string& args); - void commandDirectorSubCommandStart(socket_native_type fd, const std::string& args); - void commandDirectorSubCommandEnd(socket_native_type fd, const std::string& args); - void commandExit(socket_native_type fd, const std::string& args); - void commandFileUtils(socket_native_type fd, const std::string& args); - void commandFileUtilsSubCommandFlush(socket_native_type fd, const std::string& args); - void commandFps(socket_native_type fd, const std::string& args); - void commandFpsSubCommandOnOff(socket_native_type fd, const std::string& args); - void commandHelp(socket_native_type fd, const std::string& args); - void commandProjection(socket_native_type fd, const std::string& args); - void commandProjectionSubCommand2d(socket_native_type fd, const std::string& args); - void commandProjectionSubCommand3d(socket_native_type fd, const std::string& args); - void commandResolution(socket_native_type fd, const std::string& args); - void commandResolutionSubCommandEmpty(socket_native_type fd, const std::string& args); - void commandSceneGraph(socket_native_type fd, const std::string& args); - void commandTextures(socket_native_type fd, const std::string& args); - void commandTexturesSubCommandFlush(socket_native_type fd, const std::string& args); - void commandTouchSubCommandTap(socket_native_type fd, const std::string& args); - void commandTouchSubCommandSwipe(socket_native_type fd, const std::string& args); + void commandAllocator(socket_native_type fd, std::string_view args); + void commandConfig(socket_native_type fd, std::string_view args); + void commandDebugMsg(socket_native_type fd, std::string_view args); + void commandDebugMsgSubCommandOnOff(socket_native_type fd, std::string_view args); + void commandDirectorSubCommandPause(socket_native_type fd, std::string_view args); + void commandDirectorSubCommandResume(socket_native_type fd, std::string_view args); + void commandDirectorSubCommandStop(socket_native_type fd, std::string_view args); + void commandDirectorSubCommandStart(socket_native_type fd, std::string_view args); + void commandDirectorSubCommandEnd(socket_native_type fd, std::string_view args); + void commandExit(socket_native_type fd, std::string_view args); + void commandFileUtils(socket_native_type fd, std::string_view args); + void commandFileUtilsSubCommandFlush(socket_native_type fd, std::string_view args); + void commandFps(socket_native_type fd, std::string_view args); + void commandFpsSubCommandOnOff(socket_native_type fd, std::string_view args); + void commandHelp(socket_native_type fd, std::string_view args); + void commandProjection(socket_native_type fd, std::string_view args); + void commandProjectionSubCommand2d(socket_native_type fd, std::string_view args); + void commandProjectionSubCommand3d(socket_native_type fd, std::string_view args); + void commandResolution(socket_native_type fd, std::string_view args); + void commandResolutionSubCommandEmpty(socket_native_type fd, std::string_view args); + void commandSceneGraph(socket_native_type fd, std::string_view args); + void commandTextures(socket_native_type fd, std::string_view args); + void commandTexturesSubCommandFlush(socket_native_type fd, std::string_view args); + void commandTouchSubCommandTap(socket_native_type fd, std::string_view args); + void commandTouchSubCommandSwipe(socket_native_type fd, std::string_view args); void commandUpload(socket_native_type fd); - void commandVersion(socket_native_type fd, const std::string& args); + void commandVersion(socket_native_type fd, std::string_view args); // file descriptor: socket, console, etc. socket_native_type _listenfd; socket_native_type _maxfd; @@ -279,7 +279,7 @@ class CC_DLL Console : public Ref bool _endThread; bool _isIpv6Server; - std::unordered_map _commands; + hlookup::string_map _commands; // strings generated by cocos2d sent to the remote console bool _sendDebugStrings; @@ -299,9 +299,7 @@ class CC_DLL Console : public Ref void printFileUtils(socket_native_type fd); /** send help message to console */ - static void sendHelp(socket_native_type fd, - const std::unordered_map& commands, - const char* msg); + static void sendHelp(socket_native_type fd, const hlookup::string_map& commands, const char* msg); }; NS_CC_END diff --git a/cocos/base/CCController-android.cpp b/cocos/base/CCController-android.cpp index 564735b5c987..d7084d06cc63 100644 --- a/cocos/base/CCController-android.cpp +++ b/cocos/base/CCController-android.cpp @@ -40,7 +40,7 @@ class ControllerImpl public: ControllerImpl(Controller* controller) : _controller(controller) {} - static std::vector::iterator findController(const std::string& deviceName, int deviceId) + static std::vector::iterator findController(std::string_view deviceName, int deviceId) { auto iter = std::find_if( Controller::s_allController.begin(), Controller::s_allController.end(), [&](Controller* controller) { @@ -50,10 +50,10 @@ class ControllerImpl return iter; } - static void onConnected(const std::string& deviceName, int deviceId) + static void onConnected(std::string_view deviceName, int deviceId) { // Check whether the controller is already connected. - CCLOG("onConnected %s,%d", deviceName.c_str(), deviceId); + CCLOG("onConnected %s,%d", deviceName.data(), deviceId); auto iter = findController(deviceName, deviceId); if (iter != Controller::s_allController.end()) @@ -68,9 +68,9 @@ class ControllerImpl controller->onConnected(); } - static void onDisconnected(const std::string& deviceName, int deviceId) + static void onDisconnected(std::string_view deviceName, int deviceId) { - CCLOG("onDisconnected %s,%d", deviceName.c_str(), deviceId); + CCLOG("onDisconnected %s,%d", deviceName.data(), deviceId); auto iter = findController(deviceName, deviceId); if (iter == Controller::s_allController.end()) @@ -83,7 +83,7 @@ class ControllerImpl Controller::s_allController.erase(iter); } - static void onButtonEvent(const std::string& deviceName, + static void onButtonEvent(std::string_view deviceName, int deviceId, int keyCode, bool isPressed, @@ -101,7 +101,7 @@ class ControllerImpl (*iter)->onButtonEvent(keyCode, isPressed, value, isAnalog); } - static void onAxisEvent(const std::string& deviceName, int deviceId, int axisCode, float value, bool isAnalog) + static void onAxisEvent(std::string_view deviceName, int deviceId, int axisCode, float value, bool isAnalog) { auto iter = findController(deviceName, deviceId); if (iter == Controller::s_allController.end()) diff --git a/cocos/base/CCController-apple.mm b/cocos/base/CCController-apple.mm index 349ab4188c9a..0140a148ff4f 100644 --- a/cocos/base/CCController-apple.mm +++ b/cocos/base/CCController-apple.mm @@ -2,19 +2,19 @@ Copyright (c) 2014 cocos2d-x.org Copyright (c) 2014-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -28,36 +28,35 @@ of this software and associated documentation files (the "Software"), to deal #include "platform/CCPlatformConfig.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -#include "base/ccMacros.h" -#include "base/CCEventDispatcher.h" -#include "base/CCEventController.h" -#include "base/CCEventListenerController.h" -#include "base/CCDirector.h" -#include "2d/CCLabel.h" +# include "base/ccMacros.h" +# include "base/CCEventDispatcher.h" +# include "base/CCEventController.h" +# include "base/CCEventListenerController.h" +# include "base/CCDirector.h" +# include "2d/CCLabel.h" -#import +# import typedef void (^GCControllerConnectionBlock)(GCController* controller); typedef void (^GCControllerDisconnectionBlock)(GCController* controller); -@interface GCControllerConnectionEventHandler : NSObject -{ +@interface GCControllerConnectionEventHandler : NSObject { } -@property (copy) GCControllerConnectionBlock _connectionBlock; -@property (copy) GCControllerDisconnectionBlock _disconnectionBlock; +@property(copy) GCControllerConnectionBlock _connectionBlock; +@property(copy) GCControllerDisconnectionBlock _disconnectionBlock; -+(GCControllerConnectionEventHandler*) getInstance; -+(void) destroyInstance; ++ (GCControllerConnectionEventHandler*)getInstance; ++ (void)destroyInstance; @end @implementation GCControllerConnectionEventHandler - static GCControllerConnectionEventHandler* __instance = nil; -+(GCControllerConnectionEventHandler*) getInstance { - ++ (GCControllerConnectionEventHandler*)getInstance +{ + if (__instance == nil) { __instance = [[GCControllerConnectionEventHandler alloc] init]; @@ -65,7 +64,8 @@ +(GCControllerConnectionEventHandler*) getInstance { return __instance; } -+(void) destroyInstance { ++ (void)destroyInstance +{ if (__instance) { [__instance release]; @@ -73,33 +73,44 @@ +(void) destroyInstance { } } --(void) observerConnection: (GCControllerConnectionBlock) connectBlock disconnection: (GCControllerDisconnectionBlock) disconnectBlock { - self._connectionBlock = connectBlock; +- (void)observerConnection:(GCControllerConnectionBlock)connectBlock + disconnection:(GCControllerDisconnectionBlock)disconnectBlock +{ + self._connectionBlock = connectBlock; self._disconnectionBlock = disconnectBlock; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onControllerConnected:) name:GCControllerDidConnectNotification object:nil]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onControllerDisconnected:) name:GCControllerDidDisconnectNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(onControllerConnected:) + name:GCControllerDidConnectNotification + object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(onControllerDisconnected:) + name:GCControllerDidDisconnectNotification + object:nil]; } --(void)dealloc { +- (void)dealloc +{ [[NSNotificationCenter defaultCenter] removeObserver:self]; // Have to reset 'copy' property to nil value to avoid memory leak. - self._connectionBlock = nil; + self._connectionBlock = nil; self._disconnectionBlock = nil; [super dealloc]; } --(void) onControllerConnected :(NSNotification *)connectedNotification { - GCController *controller =(GCController *)[connectedNotification object]; - +- (void)onControllerConnected:(NSNotification*)connectedNotification +{ + GCController* controller = (GCController*)[connectedNotification object]; + self._connectionBlock(controller); } --(void) onControllerDisconnected :(NSNotification *)connectedNotification { - - GCController *controller =(GCController *)[connectedNotification object]; +- (void)onControllerDisconnected:(NSNotification*)connectedNotification +{ + + GCController* controller = (GCController*)[connectedNotification object]; self._disconnectionBlock(controller); } @@ -110,67 +121,64 @@ -(void) onControllerDisconnected :(NSNotification *)connectedNotification { class ControllerImpl { public: - ControllerImpl(Controller* controller) - : _controller(controller) - , _gcController(nil) - { - - } - + ControllerImpl(Controller* controller) : _controller(controller), _gcController(nil) {} + Controller* _controller; GCController* _gcController; }; void Controller::startDiscoveryController() { - if (NSClassFromString(@"GCController") == nil) { + if (NSClassFromString(@"GCController") == nil) + { return; } - [GCController startWirelessControllerDiscoveryWithCompletionHandler: nil]; - - [[GCControllerConnectionEventHandler getInstance] observerConnection: ^(GCController* gcController) { - - auto controller = new Controller(); - controller->_impl->_gcController = gcController; - controller->_deviceName = [gcController.vendorName UTF8String]; - - s_allController.push_back(controller); - - controller->registerListeners(); - controller->getDeviceName(); - - controller->onConnected(); - - } disconnection: ^(GCController* gcController) { - auto iter = std::find_if(s_allController.begin(), s_allController.end(), [gcController](Controller* c){ return c->_impl->_gcController == gcController; }); - - if(iter == s_allController.end()) - { - log("disconnect:Could not find the controller"); - return; + [GCController startWirelessControllerDiscoveryWithCompletionHandler:nil]; + + [[GCControllerConnectionEventHandler getInstance] + observerConnection:^(GCController* gcController) { + auto controller = new Controller(); + controller->_impl->_gcController = gcController; + controller->_deviceName = [gcController.vendorName UTF8String]; + + s_allController.push_back(controller); + + controller->registerListeners(); + controller->getDeviceName(); + + controller->onConnected(); } - - (*iter)->onDisconnected(); - s_allController.erase(iter); - - }]; + disconnection:^(GCController* gcController) { + auto iter = std::find_if(s_allController.begin(), s_allController.end(), + [gcController](Controller* c) { return c->_impl->_gcController == gcController; }); + + if (iter == s_allController.end()) + { + log("disconnect:Could not find the controller"); + return; + } + + (*iter)->onDisconnected(); + s_allController.erase(iter); + }]; } void Controller::stopDiscoveryController() { - if (NSClassFromString(@"GCController") == nil) { + if (NSClassFromString(@"GCController") == nil) + { return; } [GCController stopWirelessControllerDiscovery]; } Controller::Controller() -: _deviceId(0) -, _controllerTag(TAG_UNSET) -, _impl(new ControllerImpl(this)) -, _connectEvent(nullptr) -, _keyEvent(nullptr) -, _axisEvent(nullptr) + : _deviceId(0) + , _controllerTag(TAG_UNSET) + , _impl(new ControllerImpl(this)) + , _connectEvent(nullptr) + , _keyEvent(nullptr) + , _axisEvent(nullptr) { init(); } @@ -178,7 +186,7 @@ -(void) onControllerDisconnected :(NSNotification *)connectedNotification { Controller::~Controller() { delete _impl; - + delete _connectEvent; delete _keyEvent; delete _axisEvent; @@ -188,164 +196,184 @@ -(void) onControllerDisconnected :(NSNotification *)connectedNotification { { if (_impl->_gcController.extendedGamepad != nil) { - _impl->_gcController.extendedGamepad.dpad.up.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ - onButtonEvent(Key::BUTTON_DPAD_UP, pressed, value, button.isAnalog); - }; - - _impl->_gcController.extendedGamepad.dpad.down.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ - onButtonEvent(Key::BUTTON_DPAD_DOWN, pressed, value, button.isAnalog); - }; - - _impl->_gcController.extendedGamepad.dpad.left.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ - onButtonEvent(Key::BUTTON_DPAD_LEFT, pressed, value, button.isAnalog); - }; - - _impl->_gcController.extendedGamepad.dpad.right.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ - onButtonEvent(Key::BUTTON_DPAD_RIGHT, pressed, value, button.isAnalog); - }; - - _impl->_gcController.extendedGamepad.leftThumbstick.xAxis.valueChangedHandler = ^(GCControllerAxisInput *axis, float value){ - onAxisEvent(Key::JOYSTICK_LEFT_X, value, axis.isAnalog); - }; - - _impl->_gcController.extendedGamepad.leftThumbstick.yAxis.valueChangedHandler = ^(GCControllerAxisInput *axis, float value){ - onAxisEvent(Key::JOYSTICK_LEFT_Y, -value, axis.isAnalog); - }; - - _impl->_gcController.extendedGamepad.rightThumbstick.xAxis.valueChangedHandler = ^(GCControllerAxisInput *axis, float value){ - onAxisEvent(Key::JOYSTICK_RIGHT_X, value, axis.isAnalog); - }; - - _impl->_gcController.extendedGamepad.rightThumbstick.yAxis.valueChangedHandler = ^(GCControllerAxisInput *axis, float value){ - onAxisEvent(Key::JOYSTICK_RIGHT_Y, -value, axis.isAnalog); - }; - - _impl->_gcController.extendedGamepad.valueChangedHandler = ^(GCExtendedGamepad *gamepad, GCControllerElement *element){ - if (element == gamepad.buttonA) - { - onButtonEvent(Key::BUTTON_A, gamepad.buttonA.isPressed, gamepad.buttonA.value, gamepad.buttonA.isAnalog); - } - else if (element == gamepad.buttonB) - { - onButtonEvent(Key::BUTTON_B, gamepad.buttonB.isPressed, gamepad.buttonB.value, gamepad.buttonB.isAnalog); - } - else if (element == gamepad.buttonX) - { - onButtonEvent(Key::BUTTON_X, gamepad.buttonX.isPressed, gamepad.buttonX.value, gamepad.buttonX.isAnalog); - } - else if (element == gamepad.buttonY) - { - onButtonEvent(Key::BUTTON_Y, gamepad.buttonY.isPressed, gamepad.buttonY.value, gamepad.buttonY.isAnalog); - } - else if (element == gamepad.leftShoulder) - { - onButtonEvent(Key::BUTTON_LEFT_SHOULDER, gamepad.leftShoulder.isPressed, gamepad.leftShoulder.value, gamepad.leftShoulder.isAnalog); - } - else if (element == gamepad.rightShoulder) - { - onButtonEvent(Key::BUTTON_RIGHT_SHOULDER, gamepad.rightShoulder.isPressed, gamepad.rightShoulder.value, gamepad.rightShoulder.isAnalog); - } - else if (element == gamepad.leftTrigger) - { - onAxisEvent(Key::AXIS_LEFT_TRIGGER, gamepad.leftTrigger.value, gamepad.leftTrigger.isAnalog); - } - else if (element == gamepad.rightTrigger) - { - onAxisEvent(Key::AXIS_RIGHT_TRIGGER, gamepad.rightTrigger.value, gamepad.rightTrigger.isAnalog); - } + _impl->_gcController.extendedGamepad.dpad.up.valueChangedHandler = + ^(GCControllerButtonInput* button, float value, BOOL pressed) { + onButtonEvent(Key::BUTTON_DPAD_UP, pressed, value, button.isAnalog); + }; + + _impl->_gcController.extendedGamepad.dpad.down.valueChangedHandler = + ^(GCControllerButtonInput* button, float value, BOOL pressed) { + onButtonEvent(Key::BUTTON_DPAD_DOWN, pressed, value, button.isAnalog); + }; + + _impl->_gcController.extendedGamepad.dpad.left.valueChangedHandler = + ^(GCControllerButtonInput* button, float value, BOOL pressed) { + onButtonEvent(Key::BUTTON_DPAD_LEFT, pressed, value, button.isAnalog); + }; + + _impl->_gcController.extendedGamepad.dpad.right.valueChangedHandler = + ^(GCControllerButtonInput* button, float value, BOOL pressed) { + onButtonEvent(Key::BUTTON_DPAD_RIGHT, pressed, value, button.isAnalog); + }; + + _impl->_gcController.extendedGamepad.leftThumbstick.xAxis.valueChangedHandler = + ^(GCControllerAxisInput* axis, float value) { + onAxisEvent(Key::JOYSTICK_LEFT_X, value, axis.isAnalog); + }; + + _impl->_gcController.extendedGamepad.leftThumbstick.yAxis.valueChangedHandler = + ^(GCControllerAxisInput* axis, float value) { + onAxisEvent(Key::JOYSTICK_LEFT_Y, -value, axis.isAnalog); + }; + + _impl->_gcController.extendedGamepad.rightThumbstick.xAxis.valueChangedHandler = + ^(GCControllerAxisInput* axis, float value) { + onAxisEvent(Key::JOYSTICK_RIGHT_X, value, axis.isAnalog); + }; + + _impl->_gcController.extendedGamepad.rightThumbstick.yAxis.valueChangedHandler = + ^(GCControllerAxisInput* axis, float value) { + onAxisEvent(Key::JOYSTICK_RIGHT_Y, -value, axis.isAnalog); + }; + + _impl->_gcController.extendedGamepad.valueChangedHandler = ^(GCExtendedGamepad* gamepad, + GCControllerElement* element) { + if (element == gamepad.buttonA) + { + onButtonEvent(Key::BUTTON_A, gamepad.buttonA.isPressed, gamepad.buttonA.value, gamepad.buttonA.isAnalog); + } + else if (element == gamepad.buttonB) + { + onButtonEvent(Key::BUTTON_B, gamepad.buttonB.isPressed, gamepad.buttonB.value, gamepad.buttonB.isAnalog); + } + else if (element == gamepad.buttonX) + { + onButtonEvent(Key::BUTTON_X, gamepad.buttonX.isPressed, gamepad.buttonX.value, gamepad.buttonX.isAnalog); + } + else if (element == gamepad.buttonY) + { + onButtonEvent(Key::BUTTON_Y, gamepad.buttonY.isPressed, gamepad.buttonY.value, gamepad.buttonY.isAnalog); + } + else if (element == gamepad.leftShoulder) + { + onButtonEvent(Key::BUTTON_LEFT_SHOULDER, gamepad.leftShoulder.isPressed, gamepad.leftShoulder.value, + gamepad.leftShoulder.isAnalog); + } + else if (element == gamepad.rightShoulder) + { + onButtonEvent(Key::BUTTON_RIGHT_SHOULDER, gamepad.rightShoulder.isPressed, gamepad.rightShoulder.value, + gamepad.rightShoulder.isAnalog); + } + else if (element == gamepad.leftTrigger) + { + onAxisEvent(Key::AXIS_LEFT_TRIGGER, gamepad.leftTrigger.value, gamepad.leftTrigger.isAnalog); + } + else if (element == gamepad.rightTrigger) + { + onAxisEvent(Key::AXIS_RIGHT_TRIGGER, gamepad.rightTrigger.value, gamepad.rightTrigger.isAnalog); + } }; } else if (_impl->_gcController.gamepad != nil) { - _impl->_gcController.gamepad.dpad.up.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ - onButtonEvent(Key::BUTTON_DPAD_UP, pressed, value, button.isAnalog); - }; - - _impl->_gcController.gamepad.dpad.down.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ - onButtonEvent(Key::BUTTON_DPAD_DOWN, pressed, value, button.isAnalog); - }; - - _impl->_gcController.gamepad.dpad.left.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ - onButtonEvent(Key::BUTTON_DPAD_LEFT, pressed, value, button.isAnalog); - }; - - _impl->_gcController.gamepad.dpad.right.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ - onButtonEvent(Key::BUTTON_DPAD_RIGHT, pressed, value, button.isAnalog); - }; - - _impl->_gcController.gamepad.valueChangedHandler = ^(GCGamepad *gamepad, GCControllerElement *element){ - - if (element == gamepad.buttonA) - { - onButtonEvent(Key::BUTTON_A, gamepad.buttonA.isPressed, gamepad.buttonA.value, gamepad.buttonA.isAnalog); - } - else if (element == gamepad.buttonB) - { - onButtonEvent(Key::BUTTON_B, gamepad.buttonB.isPressed, gamepad.buttonB.value, gamepad.buttonB.isAnalog); - } - else if (element == gamepad.buttonX) - { - onButtonEvent(Key::BUTTON_X, gamepad.buttonX.isPressed, gamepad.buttonX.value, gamepad.buttonX.isAnalog); - } - else if (element == gamepad.buttonY) - { - onButtonEvent(Key::BUTTON_Y, gamepad.buttonY.isPressed, gamepad.buttonY.value, gamepad.buttonY.isAnalog); - } - else if (element == gamepad.leftShoulder) - { - onButtonEvent(Key::BUTTON_LEFT_SHOULDER, gamepad.leftShoulder.isPressed, gamepad.leftShoulder.value, gamepad.leftShoulder.isAnalog); - } - else if (element == gamepad.rightShoulder) - { - onButtonEvent(Key::BUTTON_RIGHT_SHOULDER, gamepad.rightShoulder.isPressed, gamepad.rightShoulder.value, gamepad.rightShoulder.isAnalog); - } + _impl->_gcController.gamepad.dpad.up.valueChangedHandler = + ^(GCControllerButtonInput* button, float value, BOOL pressed) { + onButtonEvent(Key::BUTTON_DPAD_UP, pressed, value, button.isAnalog); + }; + + _impl->_gcController.gamepad.dpad.down.valueChangedHandler = + ^(GCControllerButtonInput* button, float value, BOOL pressed) { + onButtonEvent(Key::BUTTON_DPAD_DOWN, pressed, value, button.isAnalog); + }; + + _impl->_gcController.gamepad.dpad.left.valueChangedHandler = + ^(GCControllerButtonInput* button, float value, BOOL pressed) { + onButtonEvent(Key::BUTTON_DPAD_LEFT, pressed, value, button.isAnalog); + }; + + _impl->_gcController.gamepad.dpad.right.valueChangedHandler = + ^(GCControllerButtonInput* button, float value, BOOL pressed) { + onButtonEvent(Key::BUTTON_DPAD_RIGHT, pressed, value, button.isAnalog); + }; + + _impl->_gcController.gamepad.valueChangedHandler = ^(GCGamepad* gamepad, GCControllerElement* element) { + if (element == gamepad.buttonA) + { + onButtonEvent(Key::BUTTON_A, gamepad.buttonA.isPressed, gamepad.buttonA.value, gamepad.buttonA.isAnalog); + } + else if (element == gamepad.buttonB) + { + onButtonEvent(Key::BUTTON_B, gamepad.buttonB.isPressed, gamepad.buttonB.value, gamepad.buttonB.isAnalog); + } + else if (element == gamepad.buttonX) + { + onButtonEvent(Key::BUTTON_X, gamepad.buttonX.isPressed, gamepad.buttonX.value, gamepad.buttonX.isAnalog); + } + else if (element == gamepad.buttonY) + { + onButtonEvent(Key::BUTTON_Y, gamepad.buttonY.isPressed, gamepad.buttonY.value, gamepad.buttonY.isAnalog); + } + else if (element == gamepad.leftShoulder) + { + onButtonEvent(Key::BUTTON_LEFT_SHOULDER, gamepad.leftShoulder.isPressed, gamepad.leftShoulder.value, + gamepad.leftShoulder.isAnalog); + } + else if (element == gamepad.rightShoulder) + { + onButtonEvent(Key::BUTTON_RIGHT_SHOULDER, gamepad.rightShoulder.isPressed, gamepad.rightShoulder.value, + gamepad.rightShoulder.isAnalog); + } }; } -#if defined(CC_TARGET_OS_TVOS) +# if defined(CC_TARGET_OS_TVOS) else if (_impl->_gcController.microGamepad != nil) { - _impl->_gcController.microGamepad.dpad.up.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ - onButtonEvent(Key::BUTTON_DPAD_UP, pressed, value, button.isAnalog); - }; - - _impl->_gcController.microGamepad.dpad.down.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ - onButtonEvent(Key::BUTTON_DPAD_DOWN, pressed, value, button.isAnalog); - }; - - _impl->_gcController.microGamepad.dpad.left.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ - onButtonEvent(Key::BUTTON_DPAD_LEFT, pressed, value, button.isAnalog); - }; - - _impl->_gcController.microGamepad.dpad.right.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){ - onButtonEvent(Key::BUTTON_DPAD_RIGHT, pressed, value, button.isAnalog); - }; - - _impl->_gcController.microGamepad.valueChangedHandler = ^(GCMicroGamepad *gamepad, GCControllerElement *element){ - - if (element == gamepad.buttonA) - { - onButtonEvent(Key::BUTTON_A, gamepad.buttonA.isPressed, gamepad.buttonA.value, gamepad.buttonA.isAnalog); - } - else if (element == gamepad.buttonX) - { - onButtonEvent(Key::BUTTON_X, gamepad.buttonX.isPressed, gamepad.buttonX.value, gamepad.buttonX.isAnalog); - } + _impl->_gcController.microGamepad.dpad.up.valueChangedHandler = + ^(GCControllerButtonInput* button, float value, BOOL pressed) { + onButtonEvent(Key::BUTTON_DPAD_UP, pressed, value, button.isAnalog); + }; + + _impl->_gcController.microGamepad.dpad.down.valueChangedHandler = + ^(GCControllerButtonInput* button, float value, BOOL pressed) { + onButtonEvent(Key::BUTTON_DPAD_DOWN, pressed, value, button.isAnalog); + }; + + _impl->_gcController.microGamepad.dpad.left.valueChangedHandler = + ^(GCControllerButtonInput* button, float value, BOOL pressed) { + onButtonEvent(Key::BUTTON_DPAD_LEFT, pressed, value, button.isAnalog); + }; + + _impl->_gcController.microGamepad.dpad.right.valueChangedHandler = + ^(GCControllerButtonInput* button, float value, BOOL pressed) { + onButtonEvent(Key::BUTTON_DPAD_RIGHT, pressed, value, button.isAnalog); + }; + + _impl->_gcController.microGamepad.valueChangedHandler = ^(GCMicroGamepad* gamepad, + GCControllerElement* element) { + if (element == gamepad.buttonA) + { + onButtonEvent(Key::BUTTON_A, gamepad.buttonA.isPressed, gamepad.buttonA.value, gamepad.buttonA.isAnalog); + } + else if (element == gamepad.buttonX) + { + onButtonEvent(Key::BUTTON_X, gamepad.buttonX.isPressed, gamepad.buttonX.value, gamepad.buttonX.isAnalog); + } }; } -#endif - - _impl->_gcController.controllerPausedHandler = ^(GCController* gcCon){ - - auto iter = std::find_if(s_allController.begin(), s_allController.end(), [gcCon](Controller* c){ return c->_impl->_gcController == gcCon; }); - - if(iter == s_allController.end()) - { - log("Could not find the controller"); - return; - } - - onButtonEvent(Key::BUTTON_PAUSE, true, 1.0f, false); - onButtonEvent(Key::BUTTON_PAUSE, false, 0.0f, false); +# endif + + _impl->_gcController.controllerPausedHandler = ^(GCController* gcCon) { + auto iter = std::find_if(s_allController.begin(), s_allController.end(), + [gcCon](Controller* c) { return c->_impl->_gcController == gcCon; }); + + if (iter == s_allController.end()) + { + log("Could not find the controller"); + return; + } + + onButtonEvent(Key::BUTTON_PAUSE, true, 1.0f, false); + onButtonEvent(Key::BUTTON_PAUSE, false, 0.0f, false); }; } @@ -354,10 +382,8 @@ -(void) onControllerDisconnected :(NSNotification *)connectedNotification { return _impl->_gcController.isAttachedToDevice == YES; } -void Controller::receiveExternalKeyEvent(int externalKeyCode,bool receive) -{ -} +void Controller::receiveExternalKeyEvent(int externalKeyCode, bool receive) {} NS_CC_END -#endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) +#endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) diff --git a/cocos/base/CCController-linux-win32.cpp b/cocos/base/CCController-linux-win32.cpp index cca3d2ee2cf0..f99e23b64188 100644 --- a/cocos/base/CCController-linux-win32.cpp +++ b/cocos/base/CCController-linux-win32.cpp @@ -4203,7 +4203,7 @@ class CC_DLL ControllerImpl return iter; } - static void onConnected(const std::string& deviceName, int deviceId) + static void onConnected(std::string_view deviceName, int deviceId) { // Check whether the controller is already registered auto iter = findController(deviceId); @@ -4222,7 +4222,7 @@ class CC_DLL ControllerImpl if (deviceName.compare(it.first) == 0) { // Found controller profile. Attach it to the controller: - CCLOG("ControllerImpl: Found input profile for controller: %s", deviceName.c_str()); + CCLOG("ControllerImpl: Found input profile for controller: %s", deviceName.data()); controller->_buttonInputMap = it.second.first; controller->_axisInputMap = it.second.second; @@ -4241,7 +4241,7 @@ class CC_DLL ControllerImpl CCLOG( "ControllerImpl: Could not find a button input mapping for controller \"%s\", and keyCode " "\"%d\". This keyCode will not match any from Controller::Key", - controller->getDeviceName().c_str(), i); + controller->getDeviceName().data(), i); } } @@ -4255,7 +4255,7 @@ class CC_DLL ControllerImpl CCLOG( "ControllerImpl: Could not find an axis input mapping for controller \"%s\", and keyCode " "\"%d\". This keyCode will not match any from Controller::Key", - controller->getDeviceName().c_str(), i); + controller->getDeviceName().data(), i); } } # endif @@ -4268,12 +4268,12 @@ class CC_DLL ControllerImpl # ifdef COCOS2D_DEBUG if (controller->_buttonInputMap.empty()) { - CCLOG("ControllerImpl: Could not find a button input map for controller: %s", deviceName.c_str()); + CCLOG("ControllerImpl: Could not find a button input map for controller: %s", deviceName.data()); } if (controller->_axisInputMap.empty()) { - CCLOG("ControllerImpl: Could not find an axis input map for controller: %s", deviceName.c_str()); + CCLOG("ControllerImpl: Could not find an axis input map for controller: %s", deviceName.data()); } # endif diff --git a/cocos/base/CCController.h b/cocos/base/CCController.h index 646195def434..f6c3bc70f4f3 100644 --- a/cocos/base/CCController.h +++ b/cocos/base/CCController.h @@ -153,7 +153,7 @@ class CC_DLL Controller /** * Gets the name of this Controller object. */ - const std::string& getDeviceName() const { return _deviceName; } + std::string_view getDeviceName() const { return _deviceName; } /** * Gets the Controller id. diff --git a/cocos/base/CCEventCustom.cpp b/cocos/base/CCEventCustom.cpp index 025252f7a79a..2d3cb05fd2b7 100644 --- a/cocos/base/CCEventCustom.cpp +++ b/cocos/base/CCEventCustom.cpp @@ -28,7 +28,6 @@ NS_CC_BEGIN -EventCustom::EventCustom(const std::string& eventName) : Event(Type::CUSTOM), _userData(nullptr), _eventName(eventName) -{} +EventCustom::EventCustom(std::string_view eventName) : Event(Type::CUSTOM), _userData(nullptr), _eventName(eventName) {} NS_CC_END diff --git a/cocos/base/CCEventCustom.h b/cocos/base/CCEventCustom.h index ae14031001df..e7a03091c752 100644 --- a/cocos/base/CCEventCustom.h +++ b/cocos/base/CCEventCustom.h @@ -47,7 +47,7 @@ class CC_DLL EventCustom : public Event * @param eventName A given name of the custom event. * @js ctor */ - EventCustom(const std::string& eventName); + EventCustom(std::string_view eventName); /** Sets user data. * @@ -65,7 +65,7 @@ class CC_DLL EventCustom : public Event * * @return The name of the event. */ - const std::string& getEventName() const { return _eventName; } + std::string_view getEventName() const { return _eventName; } protected: void* _userData; ///< User data diff --git a/cocos/base/CCEventDispatcher.cpp b/cocos/base/CCEventDispatcher.cpp index 7a18512e6612..41eae69d1e37 100644 --- a/cocos/base/CCEventDispatcher.cpp +++ b/cocos/base/CCEventDispatcher.cpp @@ -451,9 +451,9 @@ void EventDispatcher::addEventListener(EventListener* listener) void EventDispatcher::forceAddEventListener(EventListener* listener) { - EventListenerVector* listeners = nullptr; - EventListener::ListenerID listenerID = listener->getListenerID(); - auto itr = _listenerMap.find(listenerID); + EventListenerVector* listeners = nullptr; + auto listenerID = listener->getListenerID(); + auto itr = _listenerMap.find(listenerID); if (itr == _listenerMap.end()) { @@ -579,7 +579,7 @@ void EventDispatcher::addEventListenerWithFixedPriority(EventListener* listener, addEventListener(listener); } -EventListenerCustom* EventDispatcher::addCustomEventListener(const std::string& eventName, +EventListenerCustom* EventDispatcher::addCustomEventListener(std::string_view eventName, const std::function& callback) { EventListenerCustom* listener = EventListenerCustom::create(eventName, callback); @@ -931,14 +931,14 @@ void EventDispatcher::dispatchEvent(Event* event) updateListeners(event); } -void EventDispatcher::dispatchCustomEvent(const std::string& eventName, void* optionalUserData) +void EventDispatcher::dispatchCustomEvent(std::string_view eventName, void* optionalUserData) { EventCustom ev(eventName); ev.setUserData(optionalUserData); dispatchEvent(&ev); } -bool EventDispatcher::hasEventListener(const EventListener::ListenerID& listenerID) const +bool EventDispatcher::hasEventListener(std::string_view listenerID) const { return getListeners(listenerID) != nullptr; } @@ -1268,7 +1268,7 @@ void EventDispatcher::updateDirtyFlagForSceneGraph() } } -void EventDispatcher::sortEventListeners(const EventListener::ListenerID& listenerID) +void EventDispatcher::sortEventListeners(std::string_view listenerID) { DirtyFlag dirtyFlag = DirtyFlag::NONE; @@ -1303,8 +1303,7 @@ void EventDispatcher::sortEventListeners(const EventListener::ListenerID& listen } } -void EventDispatcher::sortEventListenersOfSceneGraphPriority(const EventListener::ListenerID& listenerID, - Node* rootNode) +void EventDispatcher::sortEventListenersOfSceneGraphPriority(std::string_view listenerID, Node* rootNode) { auto listeners = getListeners(listenerID); @@ -1337,7 +1336,7 @@ void EventDispatcher::sortEventListenersOfSceneGraphPriority(const EventListener #endif } -void EventDispatcher::sortEventListenersOfFixedPriority(const EventListener::ListenerID& listenerID) +void EventDispatcher::sortEventListenersOfFixedPriority(std::string_view listenerID) { auto listeners = getListeners(listenerID); @@ -1374,7 +1373,7 @@ void EventDispatcher::sortEventListenersOfFixedPriority(const EventListener::Lis #endif } -EventDispatcher::EventListenerVector* EventDispatcher::getListeners(const EventListener::ListenerID& listenerID) const +EventDispatcher::EventListenerVector* EventDispatcher::getListeners(std::string_view listenerID) const { auto iter = _listenerMap.find(listenerID); if (iter != _listenerMap.end()) @@ -1385,7 +1384,7 @@ EventDispatcher::EventListenerVector* EventDispatcher::getListeners(const EventL return nullptr; } -void EventDispatcher::removeEventListenersForListenerID(const EventListener::ListenerID& listenerID) +void EventDispatcher::removeEventListenersForListenerID(std::string_view listenerID) { auto listenerItemIter = _listenerMap.find(listenerID); if (listenerItemIter != _listenerMap.end()) @@ -1479,7 +1478,7 @@ void EventDispatcher::removeEventListenersForType(EventListener::Type listenerTy } } -void EventDispatcher::removeCustomEventListeners(const std::string& customEventName) +void EventDispatcher::removeCustomEventListeners(std::string_view customEventName) { removeEventListenersForListenerID(customEventName); } @@ -1539,7 +1538,7 @@ void EventDispatcher::setDirtyForNode(Node* node) } } -void EventDispatcher::setDirty(const EventListener::ListenerID& listenerID, DirtyFlag flag) +void EventDispatcher::setDirty(std::string_view listenerID, DirtyFlag flag) { auto iter = _priorityDirtyFlagMap.find(listenerID); if (iter == _priorityDirtyFlagMap.end()) diff --git a/cocos/base/CCEventDispatcher.h b/cocos/base/CCEventDispatcher.h index 2523f7ff2b96..9c01a79663a1 100644 --- a/cocos/base/CCEventDispatcher.h +++ b/cocos/base/CCEventDispatcher.h @@ -87,7 +87,7 @@ class CC_DLL EventDispatcher : public Ref * @param callback A given callback method that associated the event name. * @return the generated event. Needed in order to remove the event from the dispatcher */ - EventListenerCustom* addCustomEventListener(const std::string& eventName, + EventListenerCustom* addCustomEventListener(std::string_view eventName, const std::function& callback); ///////////////////////////////////////////// @@ -117,7 +117,7 @@ class CC_DLL EventDispatcher : public Ref * * @param customEventName A given event listener name which needs to be removed. */ - void removeCustomEventListeners(const std::string& customEventName); + void removeCustomEventListeners(std::string_view customEventName); /** Removes all listeners. */ @@ -177,7 +177,7 @@ class CC_DLL EventDispatcher : public Ref * @param eventName The name of the event which needs to be dispatched. * @param optionalUserData The optional user data, it's a void*, the default value is nullptr. */ - void dispatchCustomEvent(const std::string& eventName, void* optionalUserData = nullptr); + void dispatchCustomEvent(std::string_view eventName, void* optionalUserData = nullptr); /** Query whether the specified event listener id has been added. * @@ -185,7 +185,7 @@ class CC_DLL EventDispatcher : public Ref * * @return True if dispatching events is exist */ - bool hasEventListener(const EventListener::ListenerID& listenerID) const; + bool hasEventListener(std::string_view listenerID) const; ///////////////////////////////////////////// @@ -252,22 +252,22 @@ class CC_DLL EventDispatcher : public Ref void forceAddEventListener(EventListener* listener); /** Gets event the listener list for the event listener type. */ - EventListenerVector* getListeners(const EventListener::ListenerID& listenerID) const; + EventListenerVector* getListeners(std::string_view listenerID) const; /** Update dirty flag */ void updateDirtyFlagForSceneGraph(); /** Removes all listeners with the same event listener ID */ - void removeEventListenersForListenerID(const EventListener::ListenerID& listenerID); + void removeEventListenersForListenerID(std::string_view listenerID); /** Sort event listener */ - void sortEventListeners(const EventListener::ListenerID& listenerID); + void sortEventListeners(std::string_view listenerID); /** Sorts the listeners of specified type by scene graph priority */ - void sortEventListenersOfSceneGraphPriority(const EventListener::ListenerID& listenerID, Node* rootNode); + void sortEventListenersOfSceneGraphPriority(std::string_view listenerID, Node* rootNode); /** Sorts the listeners of specified type by fixed priority */ - void sortEventListenersOfFixedPriority(const EventListener::ListenerID& listenerID); + void sortEventListenersOfFixedPriority(std::string_view listenerID); /** Updates all listeners * 1) Removes all listener items that have been marked as 'removed' when dispatching event. @@ -311,7 +311,7 @@ class CC_DLL EventDispatcher : public Ref }; /** Sets the dirty flag for a specified listener ID */ - void setDirty(const EventListener::ListenerID& listenerID, DirtyFlag flag); + void setDirty(std::string_view listenerID, DirtyFlag flag); /** Walks though scene graph to get the draw order for each node, it's called before sorting event listener with * scene graph priority */ @@ -321,10 +321,10 @@ class CC_DLL EventDispatcher : public Ref void cleanToRemovedListeners(); /** Listeners map */ - std::unordered_map _listenerMap; + hlookup::string_map _listenerMap; /** The map of dirty flag */ - std::unordered_map _priorityDirtyFlagMap; + hlookup::string_map _priorityDirtyFlagMap; /** The map of node and event listeners */ std::unordered_map*> _nodeListenersMap; diff --git a/cocos/base/CCEventListener.cpp b/cocos/base/CCEventListener.cpp index 5da92081a718..d2e9e29c88ff 100644 --- a/cocos/base/CCEventListener.cpp +++ b/cocos/base/CCEventListener.cpp @@ -35,7 +35,7 @@ EventListener::~EventListener() CCLOGINFO("In the destructor of EventListener. %p", this); } -bool EventListener::init(Type t, const ListenerID& listenerID, const std::function& callback) +bool EventListener::init(Type t, std::string_view listenerID, const std::function& callback) { _onEvent = callback; _type = t; diff --git a/cocos/base/CCEventListener.h b/cocos/base/CCEventListener.h index 3f8a64631d57..6eb1f728edcf 100644 --- a/cocos/base/CCEventListener.h +++ b/cocos/base/CCEventListener.h @@ -79,7 +79,7 @@ class CC_DLL EventListener : public Ref * Initializes event with type and callback function * @js NA */ - bool init(Type t, const ListenerID& listenerID, const std::function& callback); + bool init(Type t, std::string_view listenerID, const std::function& callback); public: /** Destructor. @@ -143,7 +143,7 @@ class CC_DLL EventListener : public Ref /** Gets the listener ID of this listener * When event is being dispatched, listener ID is used as key for searching listeners according to event type. */ - const ListenerID& getListenerID() const { return _listenerID; } + std::string_view getListenerID() const { return _listenerID; } /** Sets the fixed priority for this listener * @note This method is only used for `fixed priority listeners`, it needs to access a non-zero value. diff --git a/cocos/base/CCEventListenerCustom.cpp b/cocos/base/CCEventListenerCustom.cpp index 6ccfe8071268..299d6724fcbf 100644 --- a/cocos/base/CCEventListenerCustom.cpp +++ b/cocos/base/CCEventListenerCustom.cpp @@ -30,7 +30,7 @@ NS_CC_BEGIN EventListenerCustom::EventListenerCustom() : _onCustomEvent(nullptr) {} -EventListenerCustom* EventListenerCustom::create(const std::string& eventName, +EventListenerCustom* EventListenerCustom::create(std::string_view eventName, const std::function& callback) { EventListenerCustom* ret = new EventListenerCustom(); @@ -45,7 +45,7 @@ EventListenerCustom* EventListenerCustom::create(const std::string& eventName, return ret; } -bool EventListenerCustom::init(const ListenerID& listenerId, const std::function& callback) +bool EventListenerCustom::init(std::string_view listenerId, const std::function& callback) { bool ret = false; diff --git a/cocos/base/CCEventListenerCustom.h b/cocos/base/CCEventListenerCustom.h index b9821624919a..ea68f2302e3c 100644 --- a/cocos/base/CCEventListenerCustom.h +++ b/cocos/base/CCEventListenerCustom.h @@ -66,7 +66,7 @@ class CC_DLL EventListenerCustom : public EventListener * @param callback The callback function when the specified event was emitted. * @return An autoreleased EventListenerCustom object. */ - static EventListenerCustom* create(const std::string& eventName, const std::function& callback); + static EventListenerCustom* create(std::string_view eventName, const std::function& callback); /// Overrides virtual bool checkAvailable() override; @@ -77,7 +77,7 @@ class CC_DLL EventListenerCustom : public EventListener EventListenerCustom(); /** Initializes event with type and callback function */ - bool init(const ListenerID& listenerId, const std::function& callback); + bool init(std::string_view listenerId, const std::function& callback); protected: std::function _onCustomEvent; diff --git a/cocos/base/CCIMEDelegate.h b/cocos/base/CCIMEDelegate.h index 9c9c63574c98..276c0d5d24f1 100644 --- a/cocos/base/CCIMEDelegate.h +++ b/cocos/base/CCIMEDelegate.h @@ -137,7 +137,7 @@ class CC_DLL IMEDelegate * @js NA * @lua NA */ - virtual const std::string& getContentText() { return STD_STRING_EMPTY; } + virtual std::string_view getContentText() { return STD_STRING_EMPTY; } ////////////////////////////////////////////////////////////////////////// // keyboard show/hide notification diff --git a/cocos/base/CCIMEDispatcher.cpp b/cocos/base/CCIMEDispatcher.cpp index ccd59f96dcf5..744446667823 100644 --- a/cocos/base/CCIMEDispatcher.cpp +++ b/cocos/base/CCIMEDispatcher.cpp @@ -247,7 +247,7 @@ void IMEDispatcher::dispatchControlKey(EventKeyboard::KeyCode keyCode) } while (0); } -const std::string& IMEDispatcher::getContentText() +std::string_view IMEDispatcher::getContentText() { if (_impl && _impl->_delegateWithIme) { diff --git a/cocos/base/CCIMEDispatcher.h b/cocos/base/CCIMEDispatcher.h index 5040b9d32431..4ab9b6f5b493 100644 --- a/cocos/base/CCIMEDispatcher.h +++ b/cocos/base/CCIMEDispatcher.h @@ -76,7 +76,7 @@ class CC_DLL IMEDispatcher * @brief Get the content text from IMEDelegate, retrieved previously from IME. * @lua NA */ - const std::string& getContentText(); + std::string_view getContentText(); ////////////////////////////////////////////////////////////////////////// // dispatch keyboard notification diff --git a/cocos/base/CCMap.h b/cocos/base/CCMap.h index 8bfd817dfab0..af45abeacf17 100644 --- a/cocos/base/CCMap.h +++ b/cocos/base/CCMap.h @@ -27,6 +27,7 @@ #define __CCMAP_H__ #define USE_STD_UNORDERED_MAP 1 +#define USE_ROBIN_MAP 1 #include "base/ccMacros.h" #include "base/CCRef.h" @@ -51,12 +52,12 @@ NS_CC_BEGIN * @js NA * @lua NA */ -template +template , typename E = std::equal_to> class Map { public: #if USE_STD_UNORDERED_MAP - typedef std::unordered_map RefMap; + typedef tsl::robin_map RefMap; #else typedef std::map RefMap; #endif @@ -86,14 +87,14 @@ class Map const_iterator cend() const { return _data.cend(); } /** Default constructor */ - Map() : _data() + Map() : _data() { static_assert(std::is_convertible::value, "Invalid Type for cocos2d::Map!"); CCLOGINFO("In the default constructor of Map!"); } /** Constructor with capacity. */ - explicit Map(ssize_t capacity) : _data() + explicit Map(ssize_t capacity) : _data() { static_assert(std::is_convertible::value, "Invalid Type for cocos2d::Map!"); CCLOGINFO("In the constructor with capacity of Map!"); @@ -101,7 +102,7 @@ class Map } /** Copy constructor. */ - Map(const Map& other) + Map(const Map& other) { static_assert(std::is_convertible::value, "Invalid Type for cocos2d::Map!"); CCLOGINFO("In the copy constructor of Map!"); @@ -110,7 +111,7 @@ class Map } /** Move constructor. */ - Map(Map&& other) + Map(Map&& other) { static_assert(std::is_convertible::value, "Invalid Type for cocos2d::Map!"); CCLOGINFO("In the move constructor of Map!"); @@ -121,7 +122,7 @@ class Map * Destructor. * It will release all objects in map. */ - ~Map() + ~Map() { CCLOGINFO("In the destructor of Map!"); clear(); @@ -148,7 +149,7 @@ class Map /** Returns the number of elements in bucket n. */ ssize_t bucketSize(ssize_t n) const { -#if USE_STD_UNORDERED_MAP +#if USE_STD_UNORDERED_MAP && !defined(USE_ROBIN_MAP) return _data.bucket_size(n); #else return 0; @@ -158,7 +159,7 @@ class Map /** Returns the bucket number where the element with key k is located. */ ssize_t bucket(const K& k) const { -#if USE_STD_UNORDERED_MAP +#if USE_STD_UNORDERED_MAP && !defined(USE_ROBIN_MAP) return _data.bucket(k); #else return 0; @@ -223,7 +224,8 @@ class Map * Member type K is the keys for the elements in the container. defined in Map as an alias of its first * template parameter (Key). */ - const V at(const K& key) const + template + const V at(const K2& key) const { auto iter = _data.find(key); if (iter != _data.end()) @@ -231,7 +233,8 @@ class Map return nullptr; } - V at(const K& key) + template + V at(const K2& key) { auto iter = _data.find(key); if (iter != _data.end()) @@ -247,9 +250,17 @@ class Map * Member type 'K' is the type of the keys for the elements in the container, * defined in Map as an alias of its first template parameter (Key). */ - const_iterator find(const K& key) const { return _data.find(key); } + template + const_iterator find(const K2& key) const + { + return _data.find(key); + } - iterator find(const K& key) { return _data.find(key); } + template + iterator find(const K2& key) + { + return _data.find(key); + } /** * Inserts new elements in the map. @@ -259,7 +270,8 @@ class Map * @param key The key to be inserted. * @param object The object to be inserted. */ - void insert(const K& key, V object) + template + void insert(const K2& key, V object) { CCASSERT(object != nullptr, "Object is nullptr!"); object->retain(); @@ -280,6 +292,13 @@ class Map return _data.erase(position); } + iterator erase(iterator position) + { + CCASSERT(position != _data.cend(), "Invalid iterator!"); + position->second->release(); + return _data.erase(position); + } + /** * Removes an element with an iterator from the Map container. * @@ -287,7 +306,20 @@ class Map * Member type 'K' is the type of the keys for the elements in the container, * defined in Map as an alias of its first template parameter (Key). */ - size_t erase(const K& k) + // size_t erase(const K& k) + //{ + // auto iter = _data.find(k); + // if (iter != _data.end()) + // { + // iter->second->release(); + // _data.erase(iter); + // return 1; + // } + // return 0; + // } + + template + size_t erase(const _K2& k) { auto iter = _data.find(k); if (iter != _data.end()) @@ -304,7 +336,8 @@ class Map * * @param keys Keys of elements to be erased. */ - void erase(const std::vector& keys) + template + void erase(const std::vector<_K2>& keys) { for (const auto& key : keys) { @@ -369,7 +402,7 @@ class Map // } /** Copy assignment operator. */ - Map& operator=(const Map& other) + Map& operator=(const Map& other) { if (this != &other) { @@ -382,7 +415,7 @@ class Map } /** Move assignment operator. */ - Map& operator=(Map&& other) + Map& operator=(Map&& other) { if (this != &other) { @@ -406,6 +439,9 @@ class Map RefMap _data; }; +template +using StringMap = Map; + NS_CC_END // end group /// @} diff --git a/cocos/base/CCNS.cpp b/cocos/base/CCNS.cpp index 2ebd2ff5a699..17d4165860d3 100644 --- a/cocos/base/CCNS.cpp +++ b/cocos/base/CCNS.cpp @@ -38,7 +38,7 @@ NS_CC_BEGIN typedef std::vector strArray; // string toolkit -static inline void split(const std::string& src, const std::string& token, strArray& vect) +static inline void split(std::string_view src, std::string_view token, strArray& vect) { size_t nend = 0; size_t nbegin = 0; @@ -47,9 +47,9 @@ static inline void split(const std::string& src, const std::string& token, strAr { nend = src.find(token, nbegin); if (nend == std::string::npos) - vect.push_back(src.substr(nbegin, src.length() - nbegin)); + vect.push_back(std::string{src.substr(nbegin, src.length() - nbegin)}); else - vect.push_back(src.substr(nbegin, nend - nbegin)); + vect.push_back(std::string{src.substr(nbegin, nend - nbegin)}); nbegin = nend + tokenSize; } } @@ -58,7 +58,7 @@ static inline void split(const std::string& src, const std::string& token, strAr // if the form is right,the string will be split into the parameter strs; // or the parameter strs will be empty. // if the form is right return true,else return false. -static bool splitWithForm(const std::string& content, strArray& strs) +static bool splitWithForm(std::string_view content, strArray& strs) { bool bRet = false; @@ -74,7 +74,7 @@ static bool splitWithForm(const std::string& content, strArray& strs) // '}' is before '{' CC_BREAK_IF(nPosLeft > nPosRight); - const std::string pointStr = content.substr(nPosLeft + 1, nPosRight - nPosLeft - 1); + auto pointStr = content.substr(nPosLeft + 1, nPosRight - nPosLeft - 1); // nothing between '{' and '}' CC_BREAK_IF(pointStr.empty()); @@ -98,14 +98,14 @@ static bool splitWithForm(const std::string& content, strArray& strs) // implement the functions -Rect RectFromString(const std::string& str) +Rect RectFromString(std::string_view str) { Rect result = Rect::ZERO; do { CC_BREAK_IF(str.empty()); - std::string content = str; + auto content = str; // find the first '{' and the third '}' size_t nPosLeft = content.find('{'); @@ -127,8 +127,8 @@ Rect RectFromString(const std::string& str) CC_BREAK_IF(nPointEnd == std::string::npos); // get the point string and size string - const std::string pointStr = content.substr(0, nPointEnd); - const std::string sizeStr = content.substr(nPointEnd + 1, content.length() - nPointEnd); + auto pointStr = content.substr(0, nPointEnd); + auto sizeStr = content.substr(nPointEnd + 1, content.length() - nPointEnd); // split the string with ',' strArray pointInfo; @@ -147,7 +147,7 @@ Rect RectFromString(const std::string& str) return result; } -Vec2 PointFromString(const std::string& str) +Vec2 PointFromString(std::string_view str) { Vec2 ret; @@ -165,7 +165,7 @@ Vec2 PointFromString(const std::string& str) return ret; } -Vec2 SizeFromString(const std::string& pszContent) +Vec2 SizeFromString(std::string_view pszContent) { Vec2 ret = Vec2::ZERO; diff --git a/cocos/base/CCNS.h b/cocos/base/CCNS.h index 730fd94faa0f..c08b79999237 100644 --- a/cocos/base/CCNS.h +++ b/cocos/base/CCNS.h @@ -46,7 +46,7 @@ NS_CC_BEGIN * @return A Core Graphics structure that represents a rectangle. * If the string is not well-formed, the function returns Rect::ZERO. */ -Rect CC_DLL RectFromString(const std::string& str); +Rect CC_DLL RectFromString(std::string_view str); /** * @brief Returns a Core Graphics point structure corresponding to the data in a given string. @@ -58,7 +58,7 @@ Rect CC_DLL RectFromString(const std::string& str); * @return A Core Graphics structure that represents a point. * If the string is not well-formed, the function returns Vec2::ZERO. */ -Vec2 CC_DLL PointFromString(const std::string& str); +Vec2 CC_DLL PointFromString(std::string_view str); /** * @brief Returns a Core Graphics size structure corresponding to the data in a given string. @@ -70,7 +70,7 @@ Vec2 CC_DLL PointFromString(const std::string& str); * @return A Core Graphics structure that represents a size. * If the string is not well-formed, the function returns Vec2::ZERO. */ -Vec2 CC_DLL SizeFromString(const std::string& str); +Vec2 CC_DLL SizeFromString(std::string_view str); // end of data_structure group /** @} */ diff --git a/cocos/base/CCNinePatchImageParser.cpp b/cocos/base/CCNinePatchImageParser.cpp index ab71f14fdd43..5d23b2041f54 100644 --- a/cocos/base/CCNinePatchImageParser.cpp +++ b/cocos/base/CCNinePatchImageParser.cpp @@ -179,7 +179,7 @@ void NinePatchImageParser::setSpriteFrameInfo(Image* image, const cocos2d::Rect& this->_isRotated = rotated; } -bool NinePatchImageParser::isNinePatchImage(const std::string& filepath) +bool NinePatchImageParser::isNinePatchImage(std::string_view filepath) { size_t length = filepath.length(); if (length < 7) diff --git a/cocos/base/CCNinePatchImageParser.h b/cocos/base/CCNinePatchImageParser.h index c695e10b8544..b16c6be5937b 100644 --- a/cocos/base/CCNinePatchImageParser.h +++ b/cocos/base/CCNinePatchImageParser.h @@ -51,7 +51,7 @@ class CC_DLL NinePatchImageParser * * @return If the filename contains ".9.png", then return true, otherwise false. */ - static bool isNinePatchImage(const std::string& filename); + static bool isNinePatchImage(std::string_view filename); /** * Default constructor. diff --git a/cocos/base/CCProperties.cpp b/cocos/base/CCProperties.cpp index a518a91d7f7a..4709844f7a23 100644 --- a/cocos/base/CCProperties.cpp +++ b/cocos/base/CCProperties.cpp @@ -38,7 +38,7 @@ USING_NS_CC; // Utility functions (shared with SceneLoader). /** @script{ignore} */ -void calculateNamespacePath(const std::string& urlString, +void calculateNamespacePath(std::string_view urlString, std::string& fileString, std::vector& namespacePath); /** @script{ignore} */ @@ -79,7 +79,7 @@ Properties::Properties(Data* data, ssize_t* dataIdx) Properties::Properties(Data* data, ssize_t* dataIdx, - const std::string& name, + std::string_view name, const char* id, const char* parentID, Properties* parent) @@ -97,7 +97,7 @@ Properties::Properties(Data* data, rewind(); } -Properties* Properties::createNonRefCounted(const std::string& url) +Properties* Properties::createNonRefCounted(std::string_view url) { if (url.empty()) { @@ -106,7 +106,7 @@ Properties* Properties::createNonRefCounted(const std::string& url) } // Calculate the file and full namespace path from the specified url. - std::string urlString = url; + auto& urlString = url; std::string fileString; std::vector namespacePath; calculateNamespacePath(urlString, fileString, namespacePath); @@ -122,7 +122,7 @@ Properties* Properties::createNonRefCounted(const std::string& url) Properties* p = getPropertiesFromNamespacePath(properties, namespacePath); if (!p) { - CCLOGWARN("Failed to load properties from url '%s'.", url.c_str()); + CCLOGWARN("Failed to load properties from url '%s'.", url.data()); CC_SAFE_DELETE(properties); return nullptr; } @@ -1093,7 +1093,7 @@ void Properties::setDirectoryPath(const std::string* path) } } -void Properties::setDirectoryPath(const std::string& path) +void Properties::setDirectoryPath(std::string_view path) { if (_dirPath == NULL) { @@ -1105,7 +1105,7 @@ void Properties::setDirectoryPath(const std::string& path) } } -void calculateNamespacePath(const std::string& urlString, +void calculateNamespacePath(std::string_view urlString, std::string& fileString, std::vector& namespacePath) { @@ -1114,14 +1114,14 @@ void calculateNamespacePath(const std::string& urlString, size_t loc = urlString.rfind('#'); if (loc != std::string::npos) { - fileString = urlString.substr(0, loc); - std::string namespacePathString = urlString.substr(loc + 1); + fileString = urlString.substr(0, loc); + auto namespacePathString = urlString.substr(loc + 1); while ((loc = namespacePathString.find('/')) != std::string::npos) { - namespacePath.push_back(namespacePathString.substr(0, loc)); + namespacePath.push_back(std::string{namespacePathString.substr(0, loc)}); namespacePathString = namespacePathString.substr(loc + 1); } - namespacePath.push_back(namespacePathString); + namespacePath.push_back(std::string{namespacePathString}); } else { diff --git a/cocos/base/CCProperties.h b/cocos/base/CCProperties.h index 97c123802c1d..14ddc7eeb33f 100644 --- a/cocos/base/CCProperties.h +++ b/cocos/base/CCProperties.h @@ -183,7 +183,7 @@ class CC_DLL Properties * @return The created Properties or NULL if there was an error. * @script{create} */ - static Properties* createNonRefCounted(const std::string& url); + static Properties* createNonRefCounted(std::string_view url); /** * Destructor. @@ -533,7 +533,7 @@ class CC_DLL Properties { std::string name; std::string value; - Property(const std::string& aname, const std::string& avalue) : name(aname), value(avalue) {} + Property(std::string_view aname, std::string_view avalue) : name(aname), value(avalue) {} }; /** @@ -554,7 +554,7 @@ class CC_DLL Properties */ Properties(Data* data, ssize_t* dataIdx, - const std::string& name, + std::string_view name, const char* id, const char* parentID, Properties* parent); @@ -578,7 +578,7 @@ class CC_DLL Properties Properties* clone(); void setDirectoryPath(const std::string* path); - void setDirectoryPath(const std::string& path); + void setDirectoryPath(std::string_view path); /** * Reads the next character from the Data. Returns EOF if the end of the Data is reached. diff --git a/cocos/base/CCProtocols.h b/cocos/base/CCProtocols.h index 99708d8fc1a9..a5e3a138ef4c 100644 --- a/cocos/base/CCProtocols.h +++ b/cocos/base/CCProtocols.h @@ -250,7 +250,7 @@ class CC_DLL LabelProtocol * @js NA * @lua NA */ - virtual const std::string& getString() const = 0; + virtual std::string_view getString() const = 0; }; /** diff --git a/cocos/base/CCScheduler.cpp b/cocos/base/CCScheduler.cpp index 029a12f1b6bd..7709d9468741 100644 --- a/cocos/base/CCScheduler.cpp +++ b/cocos/base/CCScheduler.cpp @@ -188,7 +188,7 @@ TimerTargetCallback::TimerTargetCallback() : _target(nullptr), _callback(nullptr bool TimerTargetCallback::initWithCallback(Scheduler* scheduler, const ccSchedulerFunc& callback, void* target, - const std::string& key, + std::string_view key, float seconds, unsigned int repeat, float delay) @@ -283,7 +283,7 @@ void Scheduler::schedule(const ccSchedulerFunc& callback, void* target, float interval, bool paused, - const std::string& key) + std::string_view key) { this->schedule(callback, target, interval, CC_REPEAT_FOREVER, 0.0f, paused, key); } @@ -294,7 +294,7 @@ void Scheduler::schedule(const ccSchedulerFunc& callback, unsigned int repeat, float delay, bool paused, - const std::string& key) + std::string_view key) { CCASSERT(target, "Argument target must be non-nullptr"); CCASSERT(!key.empty(), "key should not be empty!"); @@ -344,7 +344,7 @@ void Scheduler::schedule(const ccSchedulerFunc& callback, timer->release(); } -void Scheduler::unschedule(const std::string& key, void* target) +void Scheduler::unschedule(std::string_view key, void* target) { // explicit handle nil arguments when removing an object if (target == nullptr || key.empty()) @@ -513,7 +513,7 @@ void Scheduler::schedulePerFrame(const ccSchedulerFunc& callback, void* target, } } -bool Scheduler::isScheduled(const std::string& key, const void* target) const +bool Scheduler::isScheduled(std::string_view key, const void* target) const { CCASSERT(!key.empty(), "Argument key must not be empty"); CCASSERT(target, "Argument target must be non-nullptr"); diff --git a/cocos/base/CCScheduler.h b/cocos/base/CCScheduler.h index 5cf609f375f3..2dfe4283c444 100644 --- a/cocos/base/CCScheduler.h +++ b/cocos/base/CCScheduler.h @@ -109,13 +109,13 @@ class CC_DLL TimerTargetCallback : public Timer bool initWithCallback(Scheduler* scheduler, const ccSchedulerFunc& callback, void* target, - const std::string& key, + std::string_view key, float seconds, unsigned int repeat, float delay); const ccSchedulerFunc& getCallback() const { return _callback; } - const std::string& getKey() const { return _key; } + std::string_view getKey() const { return _key; } virtual void trigger(float dt) override; virtual void cancel() override; @@ -252,7 +252,7 @@ class CC_DLL Scheduler : public Ref unsigned int repeat, float delay, bool paused, - const std::string& key); + std::string_view key); /** The scheduled method will be called every 'interval' seconds for ever. @param callback The callback function. @@ -263,7 +263,7 @@ class CC_DLL Scheduler : public Ref @param key The key to identify the callback function, because there is not way to identify a std::function<>. @since v3.0 */ - void schedule(const ccSchedulerFunc& callback, void* target, float interval, bool paused, const std::string& key); + void schedule(const ccSchedulerFunc& callback, void* target, float interval, bool paused, std::string_view key); /** The scheduled method will be called every `interval` seconds. If paused is true, then it won't be called until it is resumed. @@ -329,7 +329,7 @@ class CC_DLL Scheduler : public Ref @param target The target to be unscheduled. @since v3.0 */ - void unschedule(const std::string& key, void* target); + void unschedule(std::string_view key, void* target); /** Unschedules a selector for a given target. If you want to unschedule the "update", use `unscheduleUpdate()`. @@ -386,7 +386,7 @@ class CC_DLL Scheduler : public Ref @return True if the specified callback is invoked, false if not. @since v3.0.0 */ - bool isScheduled(const std::string& key, const void* target) const; + bool isScheduled(std::string_view key, const void* target) const; /** Checks whether a selector for a given target is scheduled. @param selector The selector to be checked. diff --git a/cocos/base/CCScriptSupport.h b/cocos/base/CCScriptSupport.h index 318eec1da08d..6613b152da6b 100644 --- a/cocos/base/CCScriptSupport.h +++ b/cocos/base/CCScriptSupport.h @@ -756,7 +756,7 @@ class CC_DLL ScriptEngineProtocol * @lua NA * @js NA */ - virtual bool parseConfig(ConfigType type, const std::string& str) = 0; + virtual bool parseConfig(ConfigType type, std::string_view str) = 0; /** Root a Reference. It tells the Garbage Collector that the associated Scripting object should not be collected diff --git a/cocos/base/CCUserDefault.cpp b/cocos/base/CCUserDefault.cpp index e3b243fe9c69..d241ca88a43f 100644 --- a/cocos/base/CCUserDefault.cpp +++ b/cocos/base/CCUserDefault.cpp @@ -211,12 +211,12 @@ double UserDefault::getDoubleForKey(const char* pKey, double defaultValue) return defaultValue; } -std::string UserDefault::getStringForKey(const char* pKey) +std::string_view UserDefault::getStringForKey(const char* pKey) { return getStringForKey(pKey, ""); } -std::string UserDefault::getStringForKey(const char* pKey, const std::string& defaultValue) +std::string_view UserDefault::getStringForKey(const char* pKey, std::string_view defaultValue) { auto pValue = getValueForKey(pKey); if (pValue) @@ -225,7 +225,7 @@ std::string UserDefault::getStringForKey(const char* pKey, const std::string& de return defaultValue; } -const std::string* UserDefault::getValueForKey(const std::string& key) +const std::string* UserDefault::getValueForKey(std::string_view key) { // do lazyInit at here to make sure _encryptEnabled works well, lazyInit(); @@ -294,7 +294,7 @@ void UserDefault::setDoubleForKey(const char* pKey, double value) setStringForKey(pKey, tmp); } -void UserDefault::setStringForKey(const char* pKey, const std::string& value) +void UserDefault::setStringForKey(const char* pKey, std::string_view value) { // ignore empty key if (!pKey || !*pKey) @@ -338,7 +338,7 @@ void UserDefault::setStringForKey(const char* pKey, const std::string& value) #endif } -void UserDefault::setValueForKey(const std::string& key, const std::string& value) +void UserDefault::setValueForKey(std::string_view key, std::string_view value) { // do lazyInit at here to make sure _encryptEnabled works well lazyInit(); @@ -346,7 +346,7 @@ void UserDefault::setValueForKey(const std::string& key, const std::string& valu updateValueForKey(key, value); } -void UserDefault::updateValueForKey(const std::string& key, const std::string& value) +void UserDefault::updateValueForKey(std::string_view key, std::string_view value) { auto it = _values.find(key); if (it != _values.end()) diff --git a/cocos/base/CCUserDefault.h b/cocos/base/CCUserDefault.h index 6f100450459f..cf5de7f394e9 100644 --- a/cocos/base/CCUserDefault.h +++ b/cocos/base/CCUserDefault.h @@ -149,7 +149,7 @@ class CC_DLL UserDefault * @return String value of the key. * @js NA */ - std::string getStringForKey(const char* key); + std::string_view getStringForKey(const char* key); /** * Get string value by key, if the key doesn't exist, will return passed default value. @@ -158,7 +158,7 @@ class CC_DLL UserDefault * @return String value of the key. * @js NA */ - virtual std::string getStringForKey(const char* key, const std::string& defaultValue); + virtual std::string_view getStringForKey(const char* key, std::string_view defaultValue); // set value methods @@ -203,7 +203,7 @@ class CC_DLL UserDefault * @param value A string value to set to the key. * @js NA */ - virtual void setStringForKey(const char* key, const std::string& value); + virtual void setStringForKey(const char* key, std::string_view value); /** * Since we reimplement UserDefault with file mapping io, @@ -265,16 +265,16 @@ class CC_DLL UserDefault void closeFileMapping(); // The low level API of all getXXXForKey - const std::string* getValueForKey(const std::string& key); + const std::string* getValueForKey(std::string_view key); // The low level API of all setXXXForKey - void setValueForKey(const std::string& key, const std::string& value); + void setValueForKey(std::string_view key, std::string_view value); // Update value without lazyInit - void updateValueForKey(const std::string& key, const std::string& value); + void updateValueForKey(std::string_view key, std::string_view value); protected: - std::unordered_map _values; + hlookup::string_map _values; static UserDefault* _userDefault; std::string _filePath; diff --git a/cocos/base/CCValue.cpp b/cocos/base/CCValue.cpp index 8045669764a7..225d8976ba46 100644 --- a/cocos/base/CCValue.cpp +++ b/cocos/base/CCValue.cpp @@ -92,7 +92,7 @@ Value::Value(const char* v) : _type(Type::STRING) _field.strVal = new std::string(v ? v : ""); } -Value::Value(const std::string& v) : _type(Type::STRING) +Value::Value(std::string_view v) : _type(Type::STRING) { _field.strVal = new std::string(v); } @@ -308,7 +308,7 @@ Value& Value::operator=(const char* v) return *this; } -Value& Value::operator=(const std::string& v) +Value& Value::operator=(std::string_view v) { reset(Type::STRING); *_field.strVal = v; @@ -769,7 +769,7 @@ std::string Value::asString() const return ret; } -const std::string& Value::asStringRef() const +std::string_view Value::asStringRef() const { if (_type == Type::STRING) return *_field.strVal; diff --git a/cocos/base/CCValue.h b/cocos/base/CCValue.h index 47e511cf43fa..27c8c94fc15d 100644 --- a/cocos/base/CCValue.h +++ b/cocos/base/CCValue.h @@ -43,7 +43,7 @@ NS_CC_BEGIN class Value; typedef std::vector ValueVector; -typedef std::unordered_map ValueMap; +typedef hlookup::string_map ValueMap; typedef std::unordered_map ValueMapIntKey; CC_DLL extern const ValueVector ValueVectorNull; @@ -91,7 +91,7 @@ class CC_DLL Value explicit Value(const char* v); /** Create a Value by a string. */ - explicit Value(const std::string& v); + explicit Value(std::string_view v); explicit Value(std::string&& v); @@ -142,7 +142,7 @@ class CC_DLL Value /** Assignment operator, assign from char* to Value. */ Value& operator=(const char* v); /** Assignment operator, assign from string to Value. */ - Value& operator=(const std::string& v); + Value& operator=(std::string_view v); Value& operator=(std::string&& v); /** Assignment operator, assign from ValueVector to Value. */ @@ -193,7 +193,7 @@ class CC_DLL Value std::string asString() const; /** Gets as a string value reference without conversion, if value type is not string will return "" */ - const std::string& asStringRef() const; + std::string_view asStringRef() const; /** Gets as a ValueVector reference. Will convert to ValueVector if possible, or will trigger assert error. */ ValueVector& asValueVector(); @@ -279,6 +279,11 @@ class CC_DLL Value Type _type; }; +inline const cocos2d::Value& optValue(const ValueMap& dictionary, std::string_view key) +{ + return dictionary.find(key) != dictionary.cend() ? dictionary.at(key) : cocos2d::Value::Null; +} + /** @} */ NS_CC_END diff --git a/cocos/base/ObjectFactory.cpp b/cocos/base/ObjectFactory.cpp index 065d70f04966..d0920f7dff71 100644 --- a/cocos/base/ObjectFactory.cpp +++ b/cocos/base/ObjectFactory.cpp @@ -30,12 +30,12 @@ NS_CC_BEGIN ObjectFactory::TInfo::TInfo() : _class(""), _fun(nullptr), _func(nullptr) {} -ObjectFactory::TInfo::TInfo(const std::string& type, Instance ins) : _class(type), _fun(ins), _func(nullptr) +ObjectFactory::TInfo::TInfo(std::string_view type, Instance ins) : _class(type), _fun(ins), _func(nullptr) { ObjectFactory::getInstance()->registerType(*this); } -ObjectFactory::TInfo::TInfo(const std::string& type, InstanceFunc ins) : _class(type), _fun(nullptr), _func(ins) +ObjectFactory::TInfo::TInfo(std::string_view type, InstanceFunc ins) : _class(type), _fun(nullptr), _func(ins) { ObjectFactory::getInstance()->registerType(*this); } @@ -85,12 +85,16 @@ void ObjectFactory::destroyInstance() CC_SAFE_DELETE(_sharedFactory); } -Ref* ObjectFactory::createObject(const std::string& name) +Ref* ObjectFactory::createObject(std::string_view name) { Ref* o = nullptr; do { - const TInfo t = _typeMap[name]; + // const TInfo t = _typeMap[name.data]; + auto it = _typeMap.find(name); + if (it == _typeMap.end()) + break; + auto& t = it->second; if (t._fun != nullptr) { o = t._fun(); diff --git a/cocos/base/ObjectFactory.h b/cocos/base/ObjectFactory.h index e7499b08e0e1..0ee3ad46f75a 100644 --- a/cocos/base/ObjectFactory.h +++ b/cocos/base/ObjectFactory.h @@ -42,8 +42,8 @@ class CC_DLL ObjectFactory struct CC_DLL TInfo { TInfo(); - TInfo(const std::string& type, Instance ins = nullptr); - TInfo(const std::string& type, InstanceFunc ins = nullptr); + TInfo(std::string_view type, Instance ins = nullptr); + TInfo(std::string_view type, InstanceFunc ins = nullptr); TInfo(const TInfo& t); ~TInfo(); TInfo& operator=(const TInfo& t); @@ -51,11 +51,11 @@ class CC_DLL ObjectFactory Instance _fun; InstanceFunc _func; }; - typedef std::unordered_map FactoryMap; + typedef hlookup::string_map FactoryMap; static ObjectFactory* getInstance(); static void destroyInstance(); - cocos2d::Ref* createObject(const std::string& name); + cocos2d::Ref* createObject(std::string_view name); void registerType(const TInfo& t); void removeAll(); diff --git a/cocos/base/ZipUtils.cpp b/cocos/base/ZipUtils.cpp index f5fa6beb313f..3aea081acede 100644 --- a/cocos/base/ZipUtils.cpp +++ b/cocos/base/ZipUtils.cpp @@ -658,7 +658,7 @@ struct ZipFilePrivate std::unique_ptr memfs; // std::unordered_map is faster if available on the platform - typedef std::unordered_map FileListContainer; + typedef hlookup::string_map FileListContainer; FileListContainer fileList; zlib_filefunc_def functionOverrides{}; @@ -683,10 +683,10 @@ ZipFile::ZipFile() : _data(new ZipFilePrivate()) _data->zipFile = nullptr; } -ZipFile::ZipFile(const std::string& zipFile, const std::string& filter) : _data(new ZipFilePrivate()) +ZipFile::ZipFile(std::string_view zipFile, std::string_view filter) : _data(new ZipFilePrivate()) { _data->zipFileName = zipFile; - _data->zipFile = unzOpen2(zipFile.c_str(), &_data->functionOverrides); + _data->zipFile = unzOpen2(zipFile.data(), &_data->functionOverrides); setFilter(filter); } @@ -700,7 +700,7 @@ ZipFile::~ZipFile() CC_SAFE_DELETE(_data); } -bool ZipFile::setFilter(const std::string& filter) +bool ZipFile::setFilter(std::string_view filter) { bool ret = false; do @@ -743,7 +743,7 @@ bool ZipFile::setFilter(const std::string& filter) return ret; } -bool ZipFile::fileExists(const std::string& fileName) const +bool ZipFile::fileExists(std::string_view fileName) const { bool ret = false; do @@ -756,7 +756,7 @@ bool ZipFile::fileExists(const std::string& fileName) const return ret; } -std::vector ZipFile::listFiles(const std::string& pathname) const +std::vector ZipFile::listFiles(std::string_view pathname) const { // filter files which `filename.startsWith(pathname)` @@ -766,22 +766,23 @@ std::vector ZipFile::listFiles(const std::string& pathname) const ZipFilePrivate::FileListContainer::const_iterator it = _data->fileList.begin(); ZipFilePrivate::FileListContainer::const_iterator end = _data->fileList.end(); // ensure pathname ends with `/` as a directory - std::string dirname = pathname[pathname.length() - 1] == '/' ? pathname : pathname + "/"; + std::string ensureDir; + std::string_view dirname = pathname[pathname.length() - 1] == '/' ? pathname : (ensureDir.append(pathname) += '/'); for (auto& item : _data->fileList) { - const std::string& filename = item.first; - if (cxx20::starts_with(cxx17::string_view{filename}, cxx17::string_view{dirname})) + std::string_view filename = item.first; + if (cxx20::starts_with(filename, cxx17::string_view{dirname})) { - std::string suffix = filename.substr(dirname.length()); - auto pos = suffix.find('/'); + std::string_view suffix{filename.substr(dirname.length())}; + auto pos = suffix.find('/'); if (pos == std::string::npos) { - fileSet.insert(suffix); + fileSet.insert(std::string{suffix}); } else { // fileSet.insert(parts[0] + "/"); - fileSet.insert(suffix.substr(0, pos + 1)); + fileSet.insert(std::string{suffix.substr(0, pos + 1)}); } } } @@ -789,7 +790,7 @@ std::vector ZipFile::listFiles(const std::string& pathname) const return std::vector{fileSet.begin(), fileSet.end()}; } -unsigned char* ZipFile::getFileData(const std::string& fileName, ssize_t* size) +unsigned char* ZipFile::getFileData(std::string_view fileName, ssize_t* size) { unsigned char* buffer = nullptr; if (size) @@ -800,7 +801,7 @@ unsigned char* ZipFile::getFileData(const std::string& fileName, ssize_t* size) CC_BREAK_IF(!_data->zipFile); CC_BREAK_IF(fileName.empty()); - ZipFilePrivate::FileListContainer::iterator it = _data->fileList.find(fileName); + auto it = _data->fileList.find(fileName); CC_BREAK_IF(it == _data->fileList.end()); ZipEntryInfo& fileInfo = it->second; @@ -828,7 +829,7 @@ unsigned char* ZipFile::getFileData(const std::string& fileName, ssize_t* size) return buffer; } -bool ZipFile::getFileData(const std::string& fileName, ResizableBuffer* buffer) +bool ZipFile::getFileData(std::string_view fileName, ResizableBuffer* buffer) { bool res = false; do @@ -915,7 +916,7 @@ bool ZipFile::initWithBuffer(const void* buffer, unsigned int size) return true; } -bool ZipFile::zfopen(const std::string& fileName, ZipFileStream* zfs) +bool ZipFile::zfopen(std::string_view fileName, ZipFileStream* zfs) { if (!zfs) return false; @@ -1005,7 +1006,7 @@ long long ZipFile::zfsize(ZipFileStream* zfs) return -1; } -unsigned char* ZipFile::getFileDataFromZip(const std::string& zipFilePath, const std::string& filename, ssize_t* size) +unsigned char* ZipFile::getFileDataFromZip(std::string_view zipFilePath, std::string_view filename, ssize_t* size) { unsigned char* buffer = nullptr; unzFile file = nullptr; @@ -1015,11 +1016,11 @@ unsigned char* ZipFile::getFileDataFromZip(const std::string& zipFilePath, const { CC_BREAK_IF(zipFilePath.empty()); - file = unzOpen(zipFilePath.c_str()); + file = unzOpen(zipFilePath.data()); CC_BREAK_IF(!file); // minizip 1.2.0 is same with other platforms - int ret = unzLocateFile(file, filename.c_str(), nullptr); + int ret = unzLocateFile(file, filename.data(), nullptr); CC_BREAK_IF(UNZ_OK != ret); diff --git a/cocos/base/ZipUtils.h b/cocos/base/ZipUtils.h index 4a74a38fb214..8fb4e5b5295f 100644 --- a/cocos/base/ZipUtils.h +++ b/cocos/base/ZipUtils.h @@ -250,7 +250,7 @@ class CC_DLL ZipFile * * @since v2.0.5 */ - ZipFile(const std::string& zipFile, const std::string& filter = std::string()); + ZipFile(std::string_view zipFile, std::string_view filter = std::string()); virtual ~ZipFile(); /** @@ -262,7 +262,7 @@ class CC_DLL ZipFile * * @since v2.0.5 */ - bool setFilter(const std::string& filter); + bool setFilter(std::string_view filter); /** * Check does a file exists or not in zip file @@ -272,7 +272,7 @@ class CC_DLL ZipFile * * @since v2.0.5 */ - bool fileExists(const std::string& fileName) const; + bool fileExists(std::string_view fileName) const; /** * Get files and folders in pathname @@ -280,7 +280,7 @@ class CC_DLL ZipFile * @param dirname * @return */ - std::vector listFiles(const std::string& pathname) const; + std::vector listFiles(std::string_view pathname) const; /** * Get resource file data from a zip file. @@ -291,7 +291,7 @@ class CC_DLL ZipFile * * @since v2.0.5 */ - unsigned char* getFileData(const std::string& fileName, ssize_t* size); + unsigned char* getFileData(std::string_view fileName, ssize_t* size); /** * Get resource file data from a zip file. @@ -299,7 +299,7 @@ class CC_DLL ZipFile * @param[out] buffer If the file read operation succeeds, if will contain the file data. * @return True if successful. */ - bool getFileData(const std::string& fileName, ResizableBuffer* buffer); + bool getFileData(std::string_view fileName, ResizableBuffer* buffer); std::string getFirstFilename(); std::string getNextFilename(); @@ -310,7 +310,7 @@ class CC_DLL ZipFile * zipFile Streaming support, !!!important, the file in zip must no compress level, otherwise * stream seek doesn't work. */ - bool zfopen(const std::string& fileName, ZipFileStream* zfs); + bool zfopen(std::string_view fileName, ZipFileStream* zfs); int zfread(ZipFileStream* zfs, void* buf, unsigned int size); int32_t zfseek(ZipFileStream* zfs, int32_t offset, int origin); void zfclose(ZipFileStream* zfs); @@ -325,9 +325,7 @@ class CC_DLL ZipFile * @warning Recall: you are responsible for calling free() on any Non-nullptr pointer returned. */ CC_DEPRECATED() - static unsigned char* getFileDataFromZip(const std::string& zipFilePath, - const std::string& filename, - ssize_t* size); + static unsigned char* getFileDataFromZip(std::string_view zipFilePath, std::string_view filename, ssize_t* size); private: /* Only used internal for createWithBuffer() */ diff --git a/cocos/base/ccUTF8.cpp b/cocos/base/ccUTF8.cpp index 1c993a629967..2db5969e2b25 100644 --- a/cocos/base/ccUTF8.cpp +++ b/cocos/base/ccUTF8.cpp @@ -375,7 +375,7 @@ std::string getStringUTFCharsJNI(JNIEnv* env, jstring srcjStr, bool* ret) return utf8Str; } -jstring newStringUTFJNI(JNIEnv* env, const std::string& utf8Str, bool* ret) +jstring newStringUTFJNI(JNIEnv* env, std::string_view utf8Str, bool* ret) { std::u16string utf16Str; bool flag = cocos2d::StringUtils::UTF8ToUTF16(utf8Str, utf16Str); @@ -399,9 +399,9 @@ std::vector getChar16VectorFromUTF16String(const std::u16string& utf16 return std::vector(utf16.begin(), utf16.end()); } -int32_t getCharacterCountInUTF8String(const std::string& utf8) +int32_t getCharacterCountInUTF8String(std::string_view utf8) { - return getUTF8StringLength((const UTF8*)utf8.c_str()); + return getUTF8StringLength((const UTF8*)utf8.data()); } bool hasNonAsciiUTF8(const char* str, size_t len) @@ -455,7 +455,7 @@ bool isLegalUTF8String(const char* str, size_t len) StringUTF8::StringUTF8() {} -StringUTF8::StringUTF8(const std::string& newStr) +StringUTF8::StringUTF8(std::string_view newStr) { replace(newStr); } @@ -467,18 +467,18 @@ std::size_t StringUTF8::length() const return _str.size(); } -void StringUTF8::replace(const std::string& newStr) +void StringUTF8::replace(std::string_view newStr) { _str.clear(); if (!newStr.empty()) { - UTF8* sequenceUtf8 = (UTF8*)newStr.c_str(); + UTF8* sequenceUtf8 = (UTF8*)newStr.data(); int lengthString = getUTF8StringLength(sequenceUtf8); if (lengthString == 0) { - CCLOG("Bad utf-8 set string: %s", newStr.c_str()); + CCLOG("Bad utf-8 set string: %s", newStr.data()); return; } @@ -536,7 +536,7 @@ bool StringUTF8::deleteChar(std::size_t pos) } } -bool StringUTF8::insert(std::size_t pos, const std::string& insertStr) +bool StringUTF8::insert(std::size_t pos, std::string_view insertStr) { StringUTF8 utf8(insertStr); diff --git a/cocos/base/ccUTF8.h b/cocos/base/ccUTF8.h index 80626a4bc81c..a64837201807 100644 --- a/cocos/base/ccUTF8.h +++ b/cocos/base/ccUTF8.h @@ -147,7 +147,7 @@ CC_DLL std::string getStringUTFCharsJNI(JNIEnv* env, jstring srcjStr, bool* ret * @param ret True if the conversion succeeds and the ret pointer isn't null * @returns the result of jstring,the jstring need to DeleteLocalRef(jstring); */ -CC_DLL jstring newStringUTFJNI(JNIEnv* env, const std::string& utf8Str, bool* ret = nullptr); +CC_DLL jstring newStringUTFJNI(JNIEnv* env, std::string_view utf8Str, bool* ret = nullptr); #endif /** @@ -199,7 +199,7 @@ CC_DLL bool isUnicodeNonBreaking(char32_t ch); * @param utf8 An UTF-8 encoded string. * @returns The length of the string in characters. */ -CC_DLL int32_t getCharacterCountInUTF8String(const std::string& utf8); +CC_DLL int32_t getCharacterCountInUTF8String(std::string_view utf8); /** * @brief Gets the index of the last character that is not equal to the character given. @@ -245,18 +245,18 @@ class CC_DLL StringUTF8 typedef std::vector CharUTF8Store; StringUTF8(); - StringUTF8(const std::string& newStr); + StringUTF8(std::string_view newStr); ~StringUTF8(); std::size_t length() const; - void replace(const std::string& newStr); + void replace(std::string_view newStr); std::string getAsCharSequence() const; std::string getAsCharSequence(std::size_t pos) const; std::string getAsCharSequence(std::size_t pos, std::size_t len) const; bool deleteChar(std::size_t pos); - bool insert(std::size_t pos, const std::string& insertStr); + bool insert(std::size_t pos, std::string_view insertStr); bool insert(std::size_t pos, const StringUTF8& insertStr); CharUTF8Store& getString() { return _str; } diff --git a/cocos/base/ccUtils.cpp b/cocos/base/ccUtils.cpp index a661939ab0b9..c10a345f0b66 100644 --- a/cocos/base/ccUtils.cpp +++ b/cocos/base/ccUtils.cpp @@ -178,13 +178,13 @@ void captureNode(Node* startNode, std::function)> imageCallba } // [DEPRECATED] -void captureScreen(std::function afterCap, const std::string& filename) +void captureScreen(std::function afterCap, std::string_view filename) { std::string outfile; if (FileUtils::getInstance()->isAbsolutePath(filename)) outfile = filename; else - outfile = FileUtils::getInstance()->getWritablePath() + filename; + outfile = FileUtils::getInstance()->getWritablePath().append(filename); captureScreen([_afterCap = std::move(afterCap), _outfile = std::move(outfile)](RefPtr image) mutable { AsyncTaskPool::getInstance()->enqueue( @@ -199,7 +199,7 @@ void captureScreen(std::function afterCap, const }); } -std::vector findChildren(const Node& node, const std::string& name) +std::vector findChildren(const Node& node, std::string_view name) { std::vector vec; @@ -348,7 +348,7 @@ Sprite* createSpriteFromBase64(const char* base64String) return sprite; } -Node* findChild(Node* levelRoot, const std::string& name) +Node* findChild(Node* levelRoot, std::string_view name) { if (levelRoot == nullptr || name.empty()) return nullptr; @@ -389,7 +389,7 @@ Node* findChild(Node* levelRoot, int tag) return nullptr; } -std::string getFileMD5Hash(const std::string& filename) +std::string getFileMD5Hash(std::string_view filename) { Data data; FileUtils::getInstance()->getContents(filename, &data); diff --git a/cocos/base/ccUtils.h b/cocos/base/ccUtils.h index 9ea8fad56d15..8276c42355cf 100644 --- a/cocos/base/ccUtils.h +++ b/cocos/base/ccUtils.h @@ -92,7 +92,7 @@ CC_DLL void captureNode(Node* startNode, std::function)> imag * etc.). * @since v4.0 */ -CC_DLL void captureScreen(std::function afterCap, const std::string& filename); +CC_DLL void captureScreen(std::function afterCap, std::string_view filename); /** Find children by name, it will return all child that has the same name. * It supports c++ 11 regular expression. It is a helper function of `Node::enumerateChildren()`. @@ -103,7 +103,7 @@ CC_DLL void captureScreen(std::function afterCap * @return Array of Nodes that matches the name * @since v3.2 */ -CC_DLL std::vector findChildren(const Node& node, const std::string& name); +CC_DLL std::vector findChildren(const Node& node, std::string_view name); /** Same to ::atof, but strip the string, remain 7 numbers after '.' before call atof. * Why we need this? Because in android c++_static, atof ( and std::atof ) is unsupported for numbers have long decimal @@ -151,7 +151,7 @@ CC_DLL Sprite* createSpriteFromBase64(const char* base64String); * @return Returns found node or nullptr */ -CC_DLL Node* findChild(Node* levelRoot, const std::string& name); +CC_DLL Node* findChild(Node* levelRoot, std::string_view name); /** * Find a child by tag recursively @@ -166,7 +166,7 @@ CC_DLL Node* findChild(Node* levelRoot, int tag); * @return Returns found node or nullptr with specified type 'T' */ template -inline T findChild(Node* levelRoot, const std::string& name) +inline T findChild(Node* levelRoot, std::string_view name) { return dynamic_cast(findChild(levelRoot, name)); } @@ -187,7 +187,7 @@ inline T findChild(Node* levelRoot, int tag) * @param filename The file to calculate md5 hash. * @return The md5 hash for the file */ -CC_DLL std::string getFileMD5Hash(const std::string& filename); +CC_DLL std::string getFileMD5Hash(std::string_view filename); /** * Gets the md5 hash for the given buffer. diff --git a/cocos/base/hlookup.h b/cocos/base/hlookup.h new file mode 100644 index 000000000000..6a6694933316 --- /dev/null +++ b/cocos/base/hlookup.h @@ -0,0 +1,64 @@ +// Heterogeneous lookup support on c++17 with robin_hash +// C++20 demo: Heterogeneous lookup for unordered containers (transparent hashing) +// https://en.cppreference.com/w/cpp/container/unordered_map/find +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include "tsl/robin_map.h" +#include "tsl/robin_set.h" + +using namespace std::string_literals; +using namespace std::string_view_literals; + +namespace hlookup +{ +struct string_hash +{ + using hash_type = std::hash; + using is_transparent = void; + + size_t operator()(const char* str) const { return hash_type{}(str); } + size_t operator()(std::string_view str) const { return hash_type{}(str); } + size_t operator()(const std::string& str) const { return hash_type{}(str); } +}; + +struct equal_to +{ + template + constexpr auto operator()(_Ty1&& _Left, _Ty2&& _Right) const + noexcept(noexcept(static_cast<_Ty1&&>(_Left) == static_cast<_Ty2&&>(_Right))) // strengthened + -> decltype(static_cast<_Ty1&&>(_Left) == static_cast<_Ty2&&>(_Right)) + { + return static_cast<_Ty1&&>(_Left) == static_cast<_Ty2&&>(_Right); + } + + using is_transparent = void; +}; + +template +using stl_string_map = std::map>; +using stl_string_set = std::set>; + +template +using string_map = tsl::robin_map; +using string_set = tsl::robin_set; + +template +inline auto set_item(_Cont& cont, std::string_view k, _Valty&& v) +{ + typename _Cont::iterator it = cont.find(k); + if (it != cont.end()) + it->second = std::forward<_Valty>(v); + else + it = cont.emplace(k, std::forward<_Valty>(v)).first; + return it; +} + +constexpr auto empty_sv = ""sv; + +} // namespace hlookup diff --git a/cocos/math/CCMathBase.h b/cocos/math/CCMathBase.h index 36b6ff1a3afc..527be2f10e17 100644 --- a/cocos/math/CCMathBase.h +++ b/cocos/math/CCMathBase.h @@ -53,9 +53,9 @@ //#define MATH_LOG2E 1.442695040888963387f //#define MATH_PI 3.14159265358979323846f //#define MATH_RANDOM_MINUS1_1() ((2.0f*((float)rand()/RAND_MAX))-1.0f) // Returns a random float between -1 -//and 1. #define MATH_RANDOM_0_1() ((float)rand()/RAND_MAX) // Returns a random float -//between 0 and 1. #define MATH_CLAMP(x, lo, hi) ((x < lo) ? lo : ((x > hi) ? hi : x)) #ifndef M_1_PI #define -//M_1_PI 0.31830988618379067154 +// and 1. #define MATH_RANDOM_0_1() ((float)rand()/RAND_MAX) // Returns a random float +// between 0 and 1. #define MATH_CLAMP(x, lo, hi) ((x < lo) ? lo : ((x > hi) ? hi : x)) #ifndef M_1_PI #define +// M_1_PI 0.31830988618379067154 #ifdef __cplusplus # define NS_CC_MATH_BEGIN \ diff --git a/cocos/navmesh/CCNavMesh.cpp b/cocos/navmesh/CCNavMesh.cpp index cd990f580f07..dacb3948fb29 100644 --- a/cocos/navmesh/CCNavMesh.cpp +++ b/cocos/navmesh/CCNavMesh.cpp @@ -90,7 +90,7 @@ static const int TILECACHESET_MAGIC = 'T' << 24 | 'S' << 16 | 'E' << 8 | 'T'; static const int TILECACHESET_VERSION = 2; // 1: fastlz, 2: lz4 static const int MAX_AGENTS = 128; -NavMesh* NavMesh::create(const std::string& navFilePath, const std::string& geomFilePath) +NavMesh* NavMesh::create(std::string_view navFilePath, std::string_view geomFilePath) { auto ref = new NavMesh(); if (ref->initWithFilePath(navFilePath, geomFilePath)) @@ -138,7 +138,7 @@ NavMesh::~NavMesh() _obstacleList.clear(); } -bool NavMesh::initWithFilePath(const std::string& navFilePath, const std::string& geomFilePath) +bool NavMesh::initWithFilePath(std::string_view navFilePath, std::string_view geomFilePath) { _navFilePath = navFilePath; _geomFilePath = geomFilePath; diff --git a/cocos/navmesh/CCNavMesh.h b/cocos/navmesh/CCNavMesh.h index 44aaaa1d0321..41ad2f8d6b58 100644 --- a/cocos/navmesh/CCNavMesh.h +++ b/cocos/navmesh/CCNavMesh.h @@ -60,7 +60,7 @@ class CC_DLL NavMesh : public Ref @param navFilePath The NavMesh File path. @param geomFilePath The geometry File Path,include offmesh information,etc. */ - static NavMesh* create(const std::string& navFilePath, const std::string& geomFilePath); + static NavMesh* create(std::string_view navFilePath, std::string_view geomFilePath); /** update navmesh. */ void update(float dt); @@ -99,7 +99,7 @@ class CC_DLL NavMesh : public Ref virtual ~NavMesh(); protected: - bool initWithFilePath(const std::string& navFilePath, const std::string& geomFilePath); + bool initWithFilePath(std::string_view navFilePath, std::string_view geomFilePath); bool read(); bool loadNavMeshFile(); bool loadGeomFile(); diff --git a/cocos/navmesh/CCNavMeshAgent.cpp b/cocos/navmesh/CCNavMeshAgent.cpp index 920bd386d1b8..f72ee758a250 100644 --- a/cocos/navmesh/CCNavMeshAgent.cpp +++ b/cocos/navmesh/CCNavMeshAgent.cpp @@ -60,7 +60,7 @@ NavMeshAgent* NavMeshAgent::create(const NavMeshAgentParam& param) return nullptr; } -const std::string& NavMeshAgent::getNavMeshAgentComponentName() +std::string_view NavMeshAgent::getNavMeshAgentComponentName() { static std::string comName = "___NavMeshAgentComponent___"; return comName; diff --git a/cocos/navmesh/CCNavMeshAgent.h b/cocos/navmesh/CCNavMeshAgent.h index d92e541d619f..9b532cfd4a6f 100644 --- a/cocos/navmesh/CCNavMeshAgent.h +++ b/cocos/navmesh/CCNavMeshAgent.h @@ -97,7 +97,7 @@ class CC_DLL NavMeshAgent : public Component @param param The parameters of agent. */ static NavMeshAgent* create(const NavMeshAgentParam& param); - static const std::string& getNavMeshAgentComponentName(); + static std::string_view getNavMeshAgentComponentName(); virtual void onEnter() override; virtual void onExit() override; diff --git a/cocos/navmesh/CCNavMeshObstacle.cpp b/cocos/navmesh/CCNavMeshObstacle.cpp index 61ad5d183a8c..81e9ec900fbe 100644 --- a/cocos/navmesh/CCNavMeshObstacle.cpp +++ b/cocos/navmesh/CCNavMeshObstacle.cpp @@ -45,7 +45,7 @@ NavMeshObstacle* NavMeshObstacle::create(float radius, float height) return nullptr; } -const std::string& NavMeshObstacle::getNavMeshObstacleComponentName() +std::string_view NavMeshObstacle::getNavMeshObstacleComponentName() { static std::string comName = "___NavMeshObstacleComponent___"; return comName; diff --git a/cocos/navmesh/CCNavMeshObstacle.h b/cocos/navmesh/CCNavMeshObstacle.h index 0dc5677284d0..b0a0ad32f3ec 100644 --- a/cocos/navmesh/CCNavMeshObstacle.h +++ b/cocos/navmesh/CCNavMeshObstacle.h @@ -64,7 +64,7 @@ class CC_DLL NavMeshObstacle : public Component @param height The height of obstacle. */ static NavMeshObstacle* create(float radius, float height); - static const std::string& getNavMeshObstacleComponentName(); + static std::string_view getNavMeshObstacleComponentName(); virtual void onEnter() override; virtual void onExit() override; diff --git a/cocos/network/CCDownloader-curl.cpp b/cocos/network/CCDownloader-curl.cpp index 41e97da10b23..7a98042eb60c 100644 --- a/cocos/network/CCDownloader-curl.cpp +++ b/cocos/network/CCDownloader-curl.cpp @@ -106,7 +106,7 @@ class DownloadTaskCURL : public IDownloadTask DLLOG("Destruct DownloadTaskCURL %p", this); } - bool init(const std::string& filename, const std::string& tempSuffix) + bool init(std::string_view filename, std::string_view tempSuffix) { if (0 == filename.length()) { @@ -170,7 +170,7 @@ class DownloadTaskCURL : public IDownloadTask } // init md5 state - _checksumFileName = filename + ".chksum"; + _checksumFileName = _tempFileName + ".chksum"; _fsMd5 = FileUtils::getInstance()->openFileStream(_checksumFileName, FileStream::Mode::OVERLAPPED); _fsMd5->seek(0, SEEK_END); @@ -219,7 +219,7 @@ class DownloadTaskCURL : public IDownloadTask /* retval: 0. don't check, 1. check succeed, 2. check failed */ - int checkFileMd5(const std::string& requiredsum, std::string* outsum = nullptr) + int checkFileMd5(std::string_view requiredsum, std::string* outsum = nullptr) { int status = 0; if (!requiredsum.empty()) @@ -573,7 +573,7 @@ class DownloaderCURL::Impl : public std::enable_shared_from_thisrequestURL = srcUrl; this->identifier = identifier; this->background = false; } -DownloadTask::DownloadTask(const std::string& srcUrl, - const std::string& storagePath, - const std::string& checksum, - const std::string& identifier, +DownloadTask::DownloadTask(std::string_view srcUrl, + std::string_view storagePath, + std::string_view checksum, + std::string_view identifier, bool background) { this->requestURL = srcUrl; @@ -87,7 +87,7 @@ Downloader::Downloader(const DownloaderHints& hints) }; _impl->onTaskFinish = [this](const DownloadTask& task, int errorCode, int errorCodeInternal, - const std::string& errorStr, std::vector& data) { + std::string_view errorStr, std::vector& data) { if (DownloadTask::ERROR_NO_ERROR != errorCode) { if (onTaskError) @@ -121,8 +121,8 @@ Downloader::~Downloader() DLLOG("Destruct Downloader %p", this); } -std::shared_ptr Downloader::createDownloadDataTask(const std::string& srcUrl, - const std::string& identifier /* = ""*/) +std::shared_ptr Downloader::createDownloadDataTask(std::string_view srcUrl, + std::string_view identifier /* = ""*/) { auto task = std::make_shared(srcUrl, identifier); @@ -143,10 +143,10 @@ std::shared_ptr Downloader::createDownloadDataTask(const std::stri return task; } -std::shared_ptr Downloader::createDownloadFileTask(const std::string& srcUrl, - const std::string& storagePath, - const std::string& identifier, - const std::string& md5checksum, +std::shared_ptr Downloader::createDownloadFileTask(std::string_view srcUrl, + std::string_view storagePath, + std::string_view identifier, + std::string_view md5checksum, bool background) { auto task = std::make_shared(srcUrl, storagePath, md5checksum, identifier, background); @@ -167,7 +167,7 @@ std::shared_ptr Downloader::createDownloadFileTask(const std::stri return task; } -// std::string Downloader::getFileNameFromUrl(const std::string& srcUrl) +// std::string Downloader::getFileNameFromUrl(std::string_view srcUrl) //{ // // Find file name and file extension // std::string filename; diff --git a/cocos/network/CCDownloader.h b/cocos/network/CCDownloader.h index 164859bb73ec..c6e3379a40f2 100644 --- a/cocos/network/CCDownloader.h +++ b/cocos/network/CCDownloader.h @@ -72,11 +72,11 @@ class CC_DLL DownloadTask final } mutable progressInfo; DownloadTask(); - DownloadTask(const std::string& srcUrl, const std::string& identifier); - DownloadTask(const std::string& srcUrl, - const std::string& storagePath, - const std::string& checksum, // currently is MD5 - const std::string& identifier, + DownloadTask(std::string_view srcUrl, std::string_view identifier); + DownloadTask(std::string_view srcUrl, + std::string_view storagePath, + std::string_view checksum, // currently is MD5 + std::string_view identifier, bool background); virtual ~DownloadTask(); @@ -114,7 +114,7 @@ class CC_DLL Downloader final std::function onTaskProgress; - std::function + std::function onTaskError; void setOnFileTaskSuccess(const std::function& callback) @@ -129,19 +129,18 @@ class CC_DLL Downloader final void setOnTaskError( const std::function< - void(const DownloadTask& task, int errorCode, int errorCodeInternal, const std::string& errorStr)>& - callback) + void(const DownloadTask& task, int errorCode, int errorCodeInternal, std::string_view errorStr)>& callback) { onTaskError = callback; }; - std::shared_ptr createDownloadDataTask(const std::string& srcUrl, const std::string& identifier = ""); + std::shared_ptr createDownloadDataTask(std::string_view srcUrl, std::string_view identifier = ""); - std::shared_ptr createDownloadFileTask(const std::string& srcUrl, - const std::string& storagePath, - const std::string& identifier = "", - const std::string& checksum = "", - bool background = false); + std::shared_ptr createDownloadFileTask(std::string_view srcUrl, + std::string_view storagePath, + std::string_view identifier = "", + std::string_view checksum = "", + bool background = false); private: std::unique_ptr _impl; diff --git a/cocos/network/CCIDownloaderImpl.h b/cocos/network/CCIDownloaderImpl.h index 71ffa7925345..ceefec26fe78 100644 --- a/cocos/network/CCIDownloaderImpl.h +++ b/cocos/network/CCIDownloaderImpl.h @@ -67,7 +67,7 @@ class IDownloaderImpl std::function& data)> onTaskFinish; diff --git a/cocos/network/HttpClient.cpp b/cocos/network/HttpClient.cpp index 0f2f78290ef7..6c54503bd76c 100644 --- a/cocos/network/HttpClient.cpp +++ b/cocos/network/HttpClient.cpp @@ -104,7 +104,7 @@ void HttpClient::enableCookies(const char* cookieFile) _cookie->readFile(); } -void HttpClient::setSSLVerification(const std::string& caFile) +void HttpClient::setSSLVerification(std::string_view caFile) { std::lock_guard lock(_sslCaFileMutex); _sslCaFilename = caFile; @@ -167,9 +167,9 @@ void HttpClient::handleNetworkStatusChanged() _service->set_option(YOPT_S_DNS_DIRTY, 1); } -void HttpClient::setNameServers(const std::string& servers) +void HttpClient::setNameServers(std::string_view servers) { - _service->set_option(YOPT_S_DNS_LIST, servers.c_str()); + _service->set_option(YOPT_S_DNS_LIST, servers.data()); } yasio::io_service* HttpClient::getInternalService() @@ -208,7 +208,7 @@ int HttpClient::tryTakeAvailChannel() return -1; } -void HttpClient::processResponse(HttpResponse* response, const std::string& url) +void HttpClient::processResponse(HttpResponse* response, std::string_view url) { auto channelIndex = tryTakeAvailChannel(); response->retain(); @@ -221,7 +221,7 @@ void HttpClient::processResponse(HttpResponse* response, const std::string& url) auto& requestUri = response->getRequestUri(); auto channelHandle = _service->channel_at(channelIndex); channelHandle->ud_.ptr = response; - _service->set_option(YOPT_C_REMOTE_ENDPOINT, channelIndex, requestUri.getHost().c_str(), + _service->set_option(YOPT_C_REMOTE_ENDPOINT, channelIndex, requestUri.getHost().data(), (int)requestUri.getPort()); if (requestUri.isSecure()) _service->open(channelIndex, YCK_SSL_CLIENT); @@ -292,7 +292,7 @@ void HttpClient::handleNetworkEvent(yasio::io_event* event) obs.write_bytes(uri.getPath()); if (!usePostData) { - auto& query = uri.getQuery(); + auto query = uri.getQuery(); if (!query.empty()) { obs.write_byte('?'); @@ -530,13 +530,13 @@ int HttpClient::getTimeoutForRead() return _timeoutForRead; } -const std::string& HttpClient::getCookieFilename() +std::string_view HttpClient::getCookieFilename() { std::lock_guard lock(_cookieFileMutex); return _cookieFilename; } -const std::string& HttpClient::getSSLVerification() +std::string_view HttpClient::getSSLVerification() { std::lock_guard lock(_sslCaFileMutex); return _sslCaFilename; diff --git a/cocos/network/HttpClient.h b/cocos/network/HttpClient.h index 7d6fd1a7a649..36a191fbf654 100644 --- a/cocos/network/HttpClient.h +++ b/cocos/network/HttpClient.h @@ -89,21 +89,21 @@ class CC_DLL HttpClient * * @return the cookie filename */ - const std::string& getCookieFilename(); + std::string_view getCookieFilename(); /** * Set root certificate path for SSL verification. * * @param caFile a full path of root certificate.if it is empty, SSL verification is disabled. */ - void setSSLVerification(const std::string& caFile); + void setSSLVerification(std::string_view caFile); /** * Get the ssl CA filename * * @return the ssl CA filename */ - const std::string& getSSLVerification(); + std::string_view getSSLVerification(); /** * Send http request concurrently, non-blocking @@ -197,7 +197,7 @@ class CC_DLL HttpClient * Sets custom dns server list: * format: "xxx.xxx.xxx.xxx[:port],xxx.xxx.xxx.xxx[:port] */ - void setNameServers(const std::string& servers); + void setNameServers(std::string_view servers); yasio::io_service* getInternalService(); @@ -205,7 +205,7 @@ class CC_DLL HttpClient HttpClient(); virtual ~HttpClient(); - void processResponse(HttpResponse* response, const std::string& url); + void processResponse(HttpResponse* response, std::string_view url); int tryTakeAvailChannel(); diff --git a/cocos/network/HttpCookie.cpp b/cocos/network/HttpCookie.cpp index be22e571b11e..bfe76554e184 100644 --- a/cocos/network/HttpCookie.cpp +++ b/cocos/network/HttpCookie.cpp @@ -151,11 +151,11 @@ std::string HttpCookie::checkAndGetFormatedMatchCookies(const Uri& uri) return ret; } -bool HttpCookie::updateOrAddCookie(const std::string& cookie, const Uri& uri) +bool HttpCookie::updateOrAddCookie(std::string_view cookie, const Uri& uri) { unsigned int count = 0; CookieInfo info; - xsbase::nzls::fast_split(cookie.c_str(), cookie.length(), ';', [&](const char* start, const char* end) { + xsbase::nzls::fast_split(cookie.data(), cookie.length(), ';', [&](const char* start, const char* end) { unsigned int count_ = 0; while (*start == ' ') ++start; // skip ws @@ -289,7 +289,7 @@ void HttpCookie::writeFile() fclose(out); } -void HttpCookie::setCookieFileName(const std::string& filename) +void HttpCookie::setCookieFileName(std::string_view filename) { _cookieFileName = filename; } diff --git a/cocos/network/HttpCookie.h b/cocos/network/HttpCookie.h index 8e7d116cac0c..4ba517d2d25f 100644 --- a/cocos/network/HttpCookie.h +++ b/cocos/network/HttpCookie.h @@ -90,7 +90,7 @@ class HttpCookie void readFile(); void writeFile(); - void setCookieFileName(const std::string& fileName); + void setCookieFileName(std::string_view fileName); const std::vector* getCookies() const; const CookieInfo* getMatchCookie(const Uri& uri) const; @@ -98,7 +98,7 @@ class HttpCookie // Check match cookies for http request std::string checkAndGetFormatedMatchCookies(const Uri& uri); - bool updateOrAddCookie(const std::string& cookie, const Uri& uri); + bool updateOrAddCookie(std::string_view cookie, const Uri& uri); private: std::string _cookieFileName; diff --git a/cocos/network/HttpRequest.h b/cocos/network/HttpRequest.h index 2dee876f3200..10a5ad007211 100644 --- a/cocos/network/HttpRequest.h +++ b/cocos/network/HttpRequest.h @@ -125,14 +125,14 @@ class CC_DLL HttpRequest : public Ref * * @param url the string object. */ - void setUrl(const std::string& url) { _url = url; } + void setUrl(std::string_view url) { _url = url; } /** * Get the url address of HttpRequest object. * * @return const char* the pointer of _url. */ - const std::string& getUrl() const { return _url; } + std::string_view getUrl() const { return _url; } /** * Set the request data of HttpRequest object. @@ -168,7 +168,7 @@ class CC_DLL HttpRequest : public Ref * * @param tag the string object. */ - void setTag(const std::string& tag) { _tag = tag; } + void setTag(std::string_view tag) { _tag = tag; } /** * Get the string tag to identify the request. diff --git a/cocos/network/HttpResponse.h b/cocos/network/HttpResponse.h index 8909c36440ea..68b3694df6e4 100644 --- a/cocos/network/HttpResponse.h +++ b/cocos/network/HttpResponse.h @@ -155,7 +155,7 @@ class CC_DLL HttpResponse : public cocos2d::Ref * @param value a string pointer that point to response data buffer. * @param n the defined size that the response data buffer would be copied. */ - bool prepareForProcess(const std::string& url) + bool prepareForProcess(std::string_view url) { /* Resets response status */ _finished = false; diff --git a/cocos/network/Uri.cpp b/cocos/network/Uri.cpp index 665837fccc88..835738740bff 100644 --- a/cocos/network/Uri.cpp +++ b/cocos/network/Uri.cpp @@ -143,7 +143,7 @@ bool Uri::operator==(const Uri& o) const _queryParams == o._queryParams); } -Uri Uri::parse(const std::string& str) +Uri Uri::parse(std::string_view str) { Uri uri; @@ -155,7 +155,7 @@ Uri Uri::parse(const std::string& str) return uri; } -bool Uri::doParse(const std::string& str) +bool Uri::doParse(std::string_view str) { static const std::regex uriRegex( "([a-zA-Z][a-zA-Z0-9+.-]*):" // scheme: @@ -182,7 +182,7 @@ bool Uri::doParse(const std::string& str) std::smatch match; if (UNLIKELY(!std::regex_match(copied.cbegin(), copied.cend(), match, uriRegex))) { - CCLOGERROR("Invalid URI: %s", str.c_str()); + CCLOGERROR("Invalid URI: %s", str.data()); return false; } diff --git a/cocos/network/Uri.h b/cocos/network/Uri.h index aa24b1d9249d..de32b9892158 100644 --- a/cocos/network/Uri.h +++ b/cocos/network/Uri.h @@ -58,7 +58,7 @@ class CC_DLL Uri /** * Parse a Uri from a string. Throws std::invalid_argument on parse error. */ - static Uri parse(const std::string& str); + static Uri parse(std::string_view str); /** Default constructor */ Uri(); @@ -85,18 +85,18 @@ class CC_DLL Uri bool isSecure() const { return _isSecure; } /** Gets the scheme name for this URI. */ - const std::string& getScheme() const { return _scheme; } + std::string_view getScheme() const { return _scheme; } /** Gets the user name with the specified URI. */ - const std::string& getUserName() const { return _username; } + std::string_view getUserName() const { return _username; } /** Gets the password with the specified URI. */ - const std::string& getPassword() const { return _password; } + std::string_view getPassword() const { return _password; } /** * Get host part of URI. If host is an IPv6 address, square brackets will be * returned, for example: "[::1]". */ - const std::string& getHost() const { return _host; } + std::string_view getHost() const { return _host; } /** * Get host part of URI. If host is an IPv6 address, square brackets will not * be returned, for exmaple "::1"; otherwise it returns the same thing as @@ -106,29 +106,29 @@ class CC_DLL Uri * or API that connects to that host/port; e.g. getaddrinfo() only understands * IPv6 host without square brackets */ - const std::string& getHostName() const { return _hostName; } + std::string_view getHostName() const { return _hostName; } /** Gets the port number of the URI. */ uint16_t getPort() const { return _port; } /** Gets the path part of the URI. */ - const std::string& getPath() const { return _path; } + std::string_view getPath() const { return _path; } /// Gets the path, query and fragment parts of the URI. - const std::string& getPathEtc() const { return _pathEtc; } + std::string_view getPathEtc() const { return _pathEtc; } /** Gets the query part of the URI. */ - const std::string& getQuery() const { return _query; } + std::string_view getQuery() const { return _query; } /** Gets the fragment part of the URI */ - const std::string& getFragment() const { return _fragment; } + std::string_view getFragment() const { return _fragment; } /** Gets the authority part (userName, password, host and port) of the URI. * @note If the port number is a well-known port * number for the given scheme (e.g., 80 for http), it * is not included in the authority. */ - const std::string& getAuthority() const { return _authority; } + std::string_view getAuthority() const { return _authority; } /** Gets a string representation of the URI. */ std::string toString() const; @@ -159,7 +159,7 @@ class CC_DLL Uri void clear(); private: - bool doParse(const std::string& str); + bool doParse(std::string_view str); bool _isValid; bool _isSecure; diff --git a/cocos/physics3d/CCPhysicsSprite3D.cpp b/cocos/physics3d/CCPhysicsSprite3D.cpp index be3b00805401..26a0da9a7f52 100644 --- a/cocos/physics3d/CCPhysicsSprite3D.cpp +++ b/cocos/physics3d/CCPhysicsSprite3D.cpp @@ -31,7 +31,7 @@ NS_CC_BEGIN -PhysicsSprite3D* PhysicsSprite3D::create(const std::string& modelPath, +PhysicsSprite3D* PhysicsSprite3D::create(std::string_view modelPath, Physics3DRigidBodyDes* rigidDes, const cocos2d::Vec3& translateInPhysics, const cocos2d::Quaternion& rotInPhsyics) @@ -50,7 +50,7 @@ PhysicsSprite3D* PhysicsSprite3D::create(const std::string& modelPath, return ret; } -PhysicsSprite3D* PhysicsSprite3D::createWithCollider(const std::string& modelPath, +PhysicsSprite3D* PhysicsSprite3D::createWithCollider(std::string_view modelPath, Physics3DColliderDes* colliderDes, const cocos2d::Vec3& translateInPhysics, const cocos2d::Quaternion& rotInPhsyics) diff --git a/cocos/physics3d/CCPhysicsSprite3D.h b/cocos/physics3d/CCPhysicsSprite3D.h index 3a61876de442..7e94346f5504 100644 --- a/cocos/physics3d/CCPhysicsSprite3D.h +++ b/cocos/physics3d/CCPhysicsSprite3D.h @@ -48,13 +48,13 @@ class CC_DLL PhysicsSprite3D : public cocos2d::Sprite3D { public: /** creates a PhysicsSprite3D*/ - static PhysicsSprite3D* create(const std::string& modelPath, + static PhysicsSprite3D* create(std::string_view modelPath, Physics3DRigidBodyDes* rigidDes, const cocos2d::Vec3& translateInPhysics = cocos2d::Vec3::ZERO, const cocos2d::Quaternion& rotInPhsyics = cocos2d::Quaternion::ZERO); /** creates a PhysicsSprite3D as a collider*/ - static PhysicsSprite3D* createWithCollider(const std::string& modelPath, + static PhysicsSprite3D* createWithCollider(std::string_view modelPath, Physics3DColliderDes* colliderDes, const cocos2d::Vec3& translateInPhysics = cocos2d::Vec3::ZERO, const cocos2d::Quaternion& rotInPhsyics = cocos2d::Quaternion::ZERO); diff --git a/cocos/platform/CCApplicationProtocol.h b/cocos/platform/CCApplicationProtocol.h index 7bb1e930fdaa..cfb3b0ba0443 100644 --- a/cocos/platform/CCApplicationProtocol.h +++ b/cocos/platform/CCApplicationProtocol.h @@ -152,7 +152,7 @@ class CC_DLL ApplicationProtocol * @js NA * @lua NA */ - virtual bool openURL(const std::string& url) = 0; + virtual bool openURL(std::string_view url) = 0; }; // end of platform group diff --git a/cocos/platform/CCFileStream.h b/cocos/platform/CCFileStream.h index e44e74a512fb..74caba22bc73 100644 --- a/cocos/platform/CCFileStream.h +++ b/cocos/platform/CCFileStream.h @@ -28,7 +28,7 @@ class CC_DLL FileStream * @param mode File open mode, being READ | WRITE | APPEND * @return true if successful, false if not */ - virtual bool open(const std::string& path, FileStream::Mode mode) = 0; + virtual bool open(std::string_view path, FileStream::Mode mode) = 0; /** * Close a file stream diff --git a/cocos/platform/CCFileUtils.cpp b/cocos/platform/CCFileUtils.cpp index 06fd8061c896..517cb2fc2e20 100644 --- a/cocos/platform/CCFileUtils.cpp +++ b/cocos/platform/CCFileUtils.cpp @@ -29,6 +29,7 @@ THE SOFTWARE. #include #include +#include #include "base/CCData.h" #include "base/ccMacros.h" @@ -44,9 +45,38 @@ THE SOFTWARE. #endif #include +#if defined(_WIN32) +# include "ntcvt/ntcvt.hpp" +#endif + +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS +# include "tinydir/tinydir.h" +#endif + #include "pugixml/pugixml.hpp" + #define DECLARE_GUARD (void)0 +#if CC_TARGET_PLATFORM != CC_PLATFORM_IOS && (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID || (defined(__NDK_MAJOR__) && __NDK_MAJOR__ >= 22) ) +# define ADXE_HAVE_STDFS 1 +# include +namespace stdfs = std::filesystem; +# if defined(_WIN32) +inline stdfs::path toFspath(const std::string_view& pathSV) +{ + return stdfs::path{ntcvt::from_chars(pathSV)}; +} +# else +inline stdfs::path toFspath(const std::string_view& pathSV) +{ + return stdfs::path{pathSV}; +} +# endif +#else +# include "tinydir/tinydir.h" +# define ADXE_HAVE_STDFS 0 +#endif + NS_CC_BEGIN // Implement DictMaker @@ -92,7 +122,7 @@ class DictMaker : public SAXDelegator ~DictMaker() {} - ValueMap dictionaryWithContentsOfFile(const std::string& fileName) + ValueMap dictionaryWithContentsOfFile(std::string_view fileName) { _resultType = SAX_RESULT_DICT; SAXParser parser; @@ -116,7 +146,7 @@ class DictMaker : public SAXDelegator return _rootDict; } - ValueVector arrayWithContentsOfFile(const std::string& fileName) + ValueVector arrayWithContentsOfFile(std::string_view fileName) { _resultType = SAX_RESULT_ARRAY; SAXParser parser; @@ -156,9 +186,9 @@ class DictMaker : public SAXDelegator { // add a new dictionary into the pre dictionary CCASSERT(!_dictStack.empty(), "The state is wrong!"); - ValueMap* preDict = _dictStack.top(); - (*preDict)[_curKey] = Value(ValueMap()); - _curDict = &(*preDict)[_curKey].asValueMap(); + ValueMap* preDict = _dictStack.top(); + auto& curVal = hlookup::set_item(*preDict, _curKey, Value(ValueMap()))->second; + _curDict = &curVal.asValueMap(); } // record the dict state @@ -321,7 +351,7 @@ class DictMaker : public SAXDelegator } }; -ValueMap FileUtils::getValueMapFromFile(const std::string& filename) const +ValueMap FileUtils::getValueMapFromFile(std::string_view filename) const { const std::string fullPath = fullPathForFilename(filename); DictMaker tMaker; @@ -334,7 +364,7 @@ ValueMap FileUtils::getValueMapFromData(const char* filedata, int filesize) cons return tMaker.dictionaryWithDataOfFile(filedata, filesize); } -ValueVector FileUtils::getValueVectorFromFile(const std::string& filename) const +ValueVector FileUtils::getValueVectorFromFile(std::string_view filename) const { const std::string fullPath = fullPathForFilename(filename); DictMaker tMaker; @@ -350,12 +380,12 @@ static void generateElementForDict(const ValueMap& dict, pugi::xml_node& innerDi /* * Use pugixml to write plist files */ -bool FileUtils::writeToFile(const ValueMap& dict, const std::string& fullPath) const +bool FileUtils::writeToFile(const ValueMap& dict, std::string_view fullPath) const { return writeValueMapToFile(dict, fullPath); } -bool FileUtils::writeValueMapToFile(const ValueMap& dict, const std::string& fullPath) const +bool FileUtils::writeValueMapToFile(const ValueMap& dict, std::string_view fullPath) const { pugi::xml_document doc; doc.load_string(R"( @@ -371,7 +401,7 @@ bool FileUtils::writeValueMapToFile(const ValueMap& dict, const std::string& ful return writeStringToFile(ss.str(), fullPath); } -bool FileUtils::writeValueVectorToFile(const ValueVector& vecData, const std::string& fullPath) const +bool FileUtils::writeValueVectorToFile(const ValueVector& vecData, std::string_view fullPath) const { pugi::xml_document doc; doc.load_string(R"( @@ -460,35 +490,37 @@ FileUtils::FileUtils() : _writablePath("") {} FileUtils::~FileUtils() {} -bool FileUtils::writeStringToFile(const std::string& dataStr, const std::string& fullPath) const +bool FileUtils::writeStringToFile(std::string_view dataStr, std::string_view fullPath) const { - return FileUtils::writeBinaryToFile(dataStr.c_str(), dataStr.size(), fullPath); + return FileUtils::writeBinaryToFile(dataStr.data(), dataStr.size(), fullPath); } void FileUtils::writeStringToFile(std::string dataStr, - const std::string& fullPath, + std::string_view fullPath, std::function callback) const { performOperationOffthread( - [fullPath](const std::string& dataStrIn) -> bool { - return FileUtils::getInstance()->writeStringToFile(dataStrIn, fullPath); + [path = std::string{fullPath}](std::string_view dataStrIn) -> bool { + return FileUtils::getInstance()->writeStringToFile(dataStrIn, path); }, std::move(callback), std::move(dataStr)); } -bool FileUtils::writeDataToFile(const Data& data, const std::string& fullPath) const +bool FileUtils::writeDataToFile(const Data& data, std::string_view fullPath) const { return FileUtils::writeBinaryToFile(data.getBytes(), data.getSize(), fullPath); } -void FileUtils::writeDataToFile(Data data, const std::string& fullPath, std::function callback) const +void FileUtils::writeDataToFile(Data data, std::string_view fullPath, std::function callback) const { performOperationOffthread( - [fullPath](const Data& dataIn) -> bool { return FileUtils::getInstance()->writeDataToFile(dataIn, fullPath); }, + [path = std::string{fullPath}](const Data& dataIn) -> bool { + return FileUtils::getInstance()->writeDataToFile(dataIn, path); + }, std::move(callback), std::move(data)); } -bool FileUtils::writeBinaryToFile(const void* data, size_t dataSize, const std::string& fullPath) +bool FileUtils::writeBinaryToFile(const void* data, size_t dataSize, std::string_view fullPath) { CCASSERT(!fullPath.empty() && dataSize > 0, "Invalid parameters."); @@ -521,38 +553,39 @@ void FileUtils::purgeCachedEntries() _fullPathCacheDir.clear(); } -std::string FileUtils::getStringFromFile(const std::string& filename) const +std::string FileUtils::getStringFromFile(std::string_view filename) const { std::string s; getContents(filename, &s); return s; } -void FileUtils::getStringFromFile(const std::string& path, std::function callback) const +void FileUtils::getStringFromFile(std::string_view path, std::function callback) const { // Get the full path on the main thread, to avoid the issue that FileUtil's is not // thread safe, and accessing the fullPath cache and searching the search paths is not thread safe auto fullPath = fullPathForFilename(path); performOperationOffthread( - [fullPath]() -> std::string { return FileUtils::getInstance()->getStringFromFile(fullPath); }, + [path = std::string{fullPath}]() -> std::string { return FileUtils::getInstance()->getStringFromFile(path); }, std::move(callback)); } -Data FileUtils::getDataFromFile(const std::string& filename) const +Data FileUtils::getDataFromFile(std::string_view filename) const { Data d; getContents(filename, &d); return d; } -void FileUtils::getDataFromFile(const std::string& filename, std::function callback) const +void FileUtils::getDataFromFile(std::string_view filename, std::function callback) const { auto fullPath = fullPathForFilename(filename); - performOperationOffthread([fullPath]() -> Data { return FileUtils::getInstance()->getDataFromFile(fullPath); }, - std::move(callback)); + performOperationOffthread( + [path = std::string{fullPath}]() -> Data { return FileUtils::getInstance()->getDataFromFile(path); }, + std::move(callback)); } -FileUtils::Status FileUtils::getContents(const std::string& filename, ResizableBuffer* buffer) const +FileUtils::Status FileUtils::getContents(std::string_view filename, ResizableBuffer* buffer) const { if (filename.empty()) return Status::NotExists; @@ -590,30 +623,28 @@ FileUtils::Status FileUtils::getContents(const std::string& filename, ResizableB return Status::OK; } -void FileUtils::writeValueMapToFile(ValueMap dict, - const std::string& fullPath, - std::function callback) const +void FileUtils::writeValueMapToFile(ValueMap dict, std::string_view fullPath, std::function callback) const { performOperationOffthread( - [fullPath](const ValueMap& dictIn) -> bool { - return FileUtils::getInstance()->writeValueMapToFile(dictIn, fullPath); + [path = std::string{fullPath}](const ValueMap& dictIn) -> bool { + return FileUtils::getInstance()->writeValueMapToFile(dictIn, path); }, std::move(callback), std::move(dict)); } void FileUtils::writeValueVectorToFile(ValueVector vecData, - const std::string& fullPath, + std::string_view fullPath, std::function callback) const { performOperationOffthread( - [fullPath](const ValueVector& vecDataIn) -> bool { - return FileUtils::getInstance()->writeValueVectorToFile(vecDataIn, fullPath); + [path = std::string{fullPath}](const ValueVector& vecDataIn) -> bool { + return FileUtils::getInstance()->writeValueVectorToFile(vecDataIn, path); }, std::move(callback), std::move(vecData)); } -std::string FileUtils::getNewFilename(const std::string& filename) const +std::string FileUtils::getNewFilename(std::string_view filename) const { std::string newFileName; @@ -633,13 +664,13 @@ std::string FileUtils::getNewFilename(const std::string& filename) const return newFileName; } -std::string FileUtils::getPathForFilename(const std::string& filename, - const std::string& resolutionDirectory, - const std::string& searchPath) const +std::string FileUtils::getPathForFilename(std::string_view filename, + std::string_view resolutionDirectory, + std::string_view searchPath) const { - std::string file = filename; - std::string file_path = ""; - size_t pos = filename.find_last_of('/'); + auto file = filename; + std::string_view file_path = hlookup::empty_sv; + size_t pos = filename.find_last_of('/'); if (pos != std::string::npos) { file_path = filename.substr(0, pos + 1); @@ -647,7 +678,7 @@ std::string FileUtils::getPathForFilename(const std::string& filename, } // searchPath + file_path + resourceDirectory - std::string path = searchPath; + std::string path{searchPath}; path += file_path; path += resolutionDirectory; @@ -656,14 +687,14 @@ std::string FileUtils::getPathForFilename(const std::string& filename, return path; } -std::string FileUtils::getPathForDirectory(const std::string& dir, - const std::string& resolutionDiretory, - const std::string& searchPath) const +std::string FileUtils::getPathForDirectory(std::string_view dir, + std::string_view resolutionDiretory, + std::string_view searchPath) const { - return searchPath + resolutionDiretory + dir; + return std::string{searchPath}.append(resolutionDiretory).append(dir); } -std::string FileUtils::fullPathForFilename(const std::string& filename) const +std::string FileUtils::fullPathForFilename(std::string_view filename) const { DECLARE_GUARD; @@ -681,7 +712,7 @@ std::string FileUtils::fullPathForFilename(const std::string& filename) const */ if (isAbsolutePath(filename)) { - return filename; + return std::string{filename}; } // Already Cached ? @@ -713,14 +744,14 @@ std::string FileUtils::fullPathForFilename(const std::string& filename) const if (isPopupNotify()) { - CCLOG("cocos2d: fullPathForFilename: No file found at %s. Possible missing file.", filename.c_str()); + CCLOG("cocos2d: fullPathForFilename: No file found at %s. Possible missing file.", filename.data()); } // The file wasn't found, return empty string. - return ""; + return std::string{}; } -std::string FileUtils::fullPathForDirectory(const std::string& dir) const +std::string FileUtils::fullPathForDirectory(std::string_view dir) const { DECLARE_GUARD; @@ -731,7 +762,7 @@ std::string FileUtils::fullPathForDirectory(const std::string& dir) const if (isAbsolutePath(dir)) { - return dir; + return std::string{dir}; } // Already Cached ? @@ -740,7 +771,7 @@ std::string FileUtils::fullPathForDirectory(const std::string& dir) const { return cacheIter->second; } - std::string longdir = dir; + std::string longdir{dir}; std::string fullpath; if (longdir[longdir.length() - 1] != '/') @@ -766,16 +797,16 @@ std::string FileUtils::fullPathForDirectory(const std::string& dir) const if (isPopupNotify()) { - CCLOG("cocos2d: fullPathForDirectory: No directory found at %s. Possible missing directory.", dir.c_str()); + CCLOG("cocos2d: fullPathForDirectory: No directory found at %s. Possible missing directory.", dir.data()); } // The file wasn't found, return empty string. return ""; } -std::string FileUtils::fullPathFromRelativeFile(const std::string& filename, const std::string& relativeFile) const +std::string FileUtils::fullPathFromRelativeFile(std::string_view filename, std::string_view relativeFile) const { - return relativeFile.substr(0, relativeFile.rfind('/') + 1) + getNewFilename(filename); + return std::string{relativeFile.substr(0, relativeFile.rfind('/') + 1)}.append(getNewFilename(filename)); } void FileUtils::setSearchResolutionsOrder(const std::vector& searchResolutionsOrder) @@ -795,7 +826,7 @@ void FileUtils::setSearchResolutionsOrder(const std::vector& search for (const auto& iter : searchResolutionsOrder) { std::string resolutionDirectory = iter; - if (!existDefault && resolutionDirectory == "") + if (!existDefault && resolutionDirectory.empty()) { existDefault = true; } @@ -814,12 +845,12 @@ void FileUtils::setSearchResolutionsOrder(const std::vector& search } } -void FileUtils::addSearchResolutionsOrder(const std::string& order, const bool front) +void FileUtils::addSearchResolutionsOrder(std::string_view order, const bool front) { DECLARE_GUARD; - std::string resOrder = order; + std::string resOrder{order}; if (!resOrder.empty() && resOrder[resOrder.length() - 1] != '/') resOrder.push_back('/'); @@ -851,7 +882,7 @@ const std::vector FileUtils::getOriginalSearchPaths() const return _originalSearchPaths; } -void FileUtils::setWritablePath(const std::string& writablePath) +void FileUtils::setWritablePath(std::string_view writablePath) { DECLARE_GUARD; _writablePath = writablePath; @@ -863,7 +894,7 @@ const std::string FileUtils::getDefaultResourceRootPath() const return _defaultResRootPath; } -void FileUtils::setDefaultResourceRootPath(const std::string& path) +void FileUtils::setDefaultResourceRootPath(std::string_view path) { DECLARE_GUARD; if (_defaultResRootPath != path) @@ -919,14 +950,14 @@ void FileUtils::setSearchPaths(const std::vector& searchPaths) } } -void FileUtils::addSearchPath(const std::string& searchpath, const bool front) +void FileUtils::addSearchPath(std::string_view searchpath, const bool front) { DECLARE_GUARD; - std::string prefix; + std::string path; if (!isAbsolutePath(searchpath)) - prefix = _defaultResRootPath; + path = _defaultResRootPath; - std::string path = prefix + searchpath; + path.append(searchpath); if (!path.empty() && path[path.length() - 1] != '/') { path += "/"; @@ -934,13 +965,13 @@ void FileUtils::addSearchPath(const std::string& searchpath, const bool front) if (front) { - _originalSearchPaths.insert(_originalSearchPaths.begin(), searchpath); - _searchPathArray.insert(_searchPathArray.begin(), path); + _originalSearchPaths.insert(_originalSearchPaths.begin(), std::string{searchpath}); + _searchPathArray.insert(_searchPathArray.begin(), std::move(path)); } else { - _originalSearchPaths.push_back(searchpath); - _searchPathArray.push_back(path); + _originalSearchPaths.push_back(std::string{searchpath}); + _searchPathArray.push_back(std::move(path)); } } @@ -952,7 +983,7 @@ void FileUtils::setFilenameLookupDictionary(const ValueMap& filenameLookupDict) _filenameLookupDict = filenameLookupDict; } -void FileUtils::loadFilenameLookupDictionaryFromFile(const std::string& filename) +void FileUtils::loadFilenameLookupDictionaryFromFile(std::string_view filename) { const std::string fullPath = fullPathForFilename(filename); if (!fullPath.empty()) @@ -965,7 +996,7 @@ void FileUtils::loadFilenameLookupDictionaryFromFile(const std::string& filename if (version != 1) { CCLOG("cocos2d: ERROR: Invalid filenameLookup dictionary version: %d. Filename: %s", version, - filename.c_str()); + filename.data()); return; } setFilenameLookupDictionary(dict["filenames"].asValueMap()); @@ -973,12 +1004,12 @@ void FileUtils::loadFilenameLookupDictionaryFromFile(const std::string& filename } } -std::string FileUtils::getFullPathForFilenameWithinDirectory(const std::string& directory, - const std::string& filename) const +std::string FileUtils::getFullPathForFilenameWithinDirectory(std::string_view directory, + std::string_view filename) const { // get directory+filename, safely adding '/' as necessary - std::string ret = directory; - if (directory.size() && directory[directory.size() - 1] != '/') + std::string ret{directory}; + if (!directory.empty() && directory[directory.size() - 1] != '/') { ret += '/'; } @@ -986,12 +1017,12 @@ std::string FileUtils::getFullPathForFilenameWithinDirectory(const std::string& // if the file doesn't exist, return an empty string if (!isFileExistInternal(ret)) { - ret = ""; + ret.clear(); } return ret; } -bool FileUtils::isFileExist(const std::string& filename) const +bool FileUtils::isFileExist(std::string_view filename) const { if (isAbsolutePath(filename)) { @@ -1007,19 +1038,20 @@ bool FileUtils::isFileExist(const std::string& filename) const } } -void FileUtils::isFileExist(const std::string& filename, std::function callback) const +void FileUtils::isFileExist(std::string_view filename, std::function callback) const { auto fullPath = fullPathForFilename(filename); - performOperationOffthread([fullPath]() -> bool { return FileUtils::getInstance()->isFileExist(fullPath); }, - std::move(callback)); + performOperationOffthread( + [path = std::string{fullPath}]() -> bool { return FileUtils::getInstance()->isFileExist(path); }, + std::move(callback)); } -bool FileUtils::isAbsolutePath(const std::string& path) const +bool FileUtils::isAbsolutePath(std::string_view path) const { return isAbsolutePathInternal(path); } -bool FileUtils::isAbsolutePathInternal(const std::string& path) +bool FileUtils::isAbsolutePathInternal(std::string_view path) { #if defined(_WIN32) // see also: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file?redirectedfrom=MSDN @@ -1034,7 +1066,7 @@ bool FileUtils::isAbsolutePathInternal(const std::string& path) #endif } -bool FileUtils::isDirectoryExist(const std::string& dirPath) const +bool FileUtils::isDirectoryExist(std::string_view dirPath) const { CCASSERT(!dirPath.empty(), "Invalid path"); @@ -1051,79 +1083,87 @@ bool FileUtils::isDirectoryExist(const std::string& dirPath) const } } -void FileUtils::isDirectoryExist(const std::string& fullPath, std::function callback) const +void FileUtils::isDirectoryExist(std::string_view fullPath, std::function callback) const { CCASSERT(isAbsolutePath(fullPath), "Async isDirectoryExist only accepts absolute file paths"); - performOperationOffthread([fullPath]() -> bool { return FileUtils::getInstance()->isDirectoryExist(fullPath); }, - std::move(callback)); + performOperationOffthread( + [path = std::string{fullPath}]() -> bool { return FileUtils::getInstance()->isDirectoryExist(path); }, + std::move(callback)); } -void FileUtils::createDirectory(const std::string& dirPath, std::function callback) const +void FileUtils::createDirectory(std::string_view dirPath, std::function callback) const { - performOperationOffthread([dirPath]() -> bool { return FileUtils::getInstance()->createDirectory(dirPath); }, - std::move(callback)); + performOperationOffthread( + [path = std::string{dirPath}]() -> bool { return FileUtils::getInstance()->createDirectory(path); }, + std::move(callback)); } -void FileUtils::removeDirectory(const std::string& dirPath, std::function callback) const +void FileUtils::removeDirectory(std::string_view dirPath, std::function callback) const { - performOperationOffthread([dirPath]() -> bool { return FileUtils::getInstance()->removeDirectory(dirPath); }, - std::move(callback)); + performOperationOffthread( + [path = std::string{dirPath}]() -> bool { return FileUtils::getInstance()->removeDirectory(path); }, + std::move(callback)); } -void FileUtils::removeFile(const std::string& filepath, std::function callback) const +void FileUtils::removeFile(std::string_view filepath, std::function callback) const { auto fullPath = fullPathForFilename(filepath); - performOperationOffthread([fullPath]() -> bool { return FileUtils::getInstance()->removeFile(fullPath); }, - std::move(callback)); + performOperationOffthread( + [path = std::string{fullPath}]() -> bool { return FileUtils::getInstance()->removeFile(path); }, + std::move(callback)); } -void FileUtils::renameFile(const std::string& path, - const std::string& oldname, - const std::string& name, +void FileUtils::renameFile(std::string_view path, + std::string_view oldname, + std::string_view name, std::function callback) const { performOperationOffthread( - [path, oldname, name]() -> bool { return FileUtils::getInstance()->renameFile(path, oldname, name); }, + [path = std::string{path}, oldname = std::string{oldname}, name = std::string{name}]() -> bool { + return FileUtils::getInstance()->renameFile(path, oldname, name); + }, std::move(callback)); } -void FileUtils::renameFile(const std::string& oldfullpath, - const std::string& newfullpath, +void FileUtils::renameFile(std::string_view oldfullpath, + std::string_view newfullpath, std::function callback) const { performOperationOffthread( - [oldfullpath, newfullpath]() { return FileUtils::getInstance()->renameFile(oldfullpath, newfullpath); }, + [oldpath = std::string{oldfullpath}, newpath = std::string{newfullpath}]() { + return FileUtils::getInstance()->renameFile(oldpath, newpath); + }, std::move(callback)); } -void FileUtils::getFileSize(const std::string& filepath, std::function callback) const +void FileUtils::getFileSize(std::string_view filepath, std::function callback) const { auto fullPath = fullPathForFilename(filepath); - performOperationOffthread([fullPath]() { return FileUtils::getInstance()->getFileSize(fullPath); }, + performOperationOffthread([path = std::string{fullPath}]() { return FileUtils::getInstance()->getFileSize(path); }, std::move(callback)); } -void FileUtils::listFilesAsync(const std::string& dirPath, std::function)> callback) const +void FileUtils::listFilesAsync(std::string_view dirPath, std::function)> callback) const { auto fullPath = fullPathForDirectory(dirPath); - performOperationOffthread([fullPath]() { return FileUtils::getInstance()->listFiles(fullPath); }, + performOperationOffthread([path = std::string{fullPath}]() { return FileUtils::getInstance()->listFiles(path); }, std::move(callback)); } -void FileUtils::listFilesRecursivelyAsync(const std::string& dirPath, +void FileUtils::listFilesRecursivelyAsync(std::string_view dirPath, std::function)> callback) const { auto fullPath = fullPathForDirectory(dirPath); performOperationOffthread( - [fullPath]() { + [path = std::string{fullPath}]() { std::vector retval; - FileUtils::getInstance()->listFilesRecursively(fullPath, &retval); + FileUtils::getInstance()->listFilesRecursively(path, &retval); return retval; }, std::move(callback)); } -std::unique_ptr FileUtils::openFileStream(const std::string& filePath, FileStream::Mode mode) +std::unique_ptr FileUtils::openFileStream(std::string_view filePath, FileStream::Mode mode) { PosixFileStream fs; @@ -1135,64 +1175,211 @@ std::unique_ptr FileUtils::openFileStream(const std::string& filePat return nullptr; } +/* !!!Notes for c++fs + a. ios: require ios 13.0+ + b. android: require ndk-r22+ +*/ +#if ADXE_HAVE_STDFS +std::vector FileUtils::listFiles(std::string_view dirPath) const +{ + const auto fullPath = fullPathForDirectory(dirPath); + auto fsPath = toFspath(fullPath); + if (!stdfs::is_directory(fsPath)) + { + return {}; + } + std::vector files = {}; + for (const auto& entry : stdfs::directory_iterator(fsPath)) + { + const auto isDir = entry.is_directory(); + if (isDir || entry.is_regular_file()) + { +# if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) +# if defined(__cpp_lib_char8_t) + std::u8string u8path = entry.path().u8string(); + std::string pathStr = {u8path.begin(), u8path.end()}; +# else + std::string pathStr = entry.path().u8string(); +# endif + std::replace(pathStr.begin(), pathStr.end(), '\\', '/'); +# else + std::string pathStr = entry.path().string(); +# endif + if (isDir) + { + pathStr += '/'; + } + files.emplace_back(std::move(pathStr)); + } + } + return files; +} + +void FileUtils::listFilesRecursively(std::string_view dirPath, std::vector* files) const +{ + const auto fullPath = fullPathForDirectory(dirPath); + auto fsPath = toFspath(fullPath); + if (!stdfs::is_directory(fsPath)) + { + return; + } + for (const auto& entry : stdfs::recursive_directory_iterator(fsPath)) + { + const auto isDir = entry.is_directory(); + if (isDir || entry.is_regular_file()) + { +# if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) +# if defined(__cpp_lib_char8_t) + std::u8string u8path = entry.path().u8string(); + std::string pathStr = {u8path.begin(), u8path.end()}; +# else + std::string pathStr = entry.path().u8string(); +# endif + std::replace(pathStr.begin(), pathStr.end(), '\\', '/'); +# else + std::string pathStr = entry.path().string(); +# endif + if (isDir) + { + pathStr += '/'; + } + files->emplace_back(std::move(pathStr)); + } + } +} +#else +std::vector FileUtils::listFiles(std::string_view dirPath) const +{ + std::vector files; + std::string fullpath = fullPathForDirectory(dirPath); + if (!fullpath.empty() && isDirectoryExist(fullpath)) + { + tinydir_dir dir; + std::string fullpathstr = fullpath; + + if (tinydir_open(&dir, &fullpathstr[0]) != -1) + { + while (dir.has_next) + { + tinydir_file file; + if (tinydir_readfile(&dir, &file) == -1) + { + // Error getting file + break; + } + std::string filepath = file.path; + + if (strcmp(file.name, ".") != 0 && strcmp(file.name, "..") != 0) + { + if (file.is_dir) + filepath.push_back('/'); + + files.push_back(std::move(filepath)); + } + + if (tinydir_next(&dir) == -1) + { + // Error getting next file + break; + } + } + } + tinydir_close(&dir); + } + return files; +} + +void FileUtils::listFilesRecursively(std::string_view dirPath, std::vector* files) const +{ + std::string fullpath = fullPathForDirectory(dirPath); + if (isDirectoryExist(fullpath)) + { + tinydir_dir dir; + std::string fullpathstr = fullpath; + + if (tinydir_open(&dir, &fullpathstr[0]) != -1) + { + while (dir.has_next) + { + tinydir_file file; + if (tinydir_readfile(&dir, &file) == -1) + { + // Error getting file + break; + } + + if (strcmp(file.name, ".") != 0 && strcmp(file.name, "..") != 0) + { + std::string filepath = file.path; + if (file.is_dir) + { + filepath.push_back('/'); + files->push_back(filepath); + listFilesRecursively(filepath, files); + } + else + { + files->push_back(std::move(filepath)); + } + } + + if (tinydir_next(&dir) == -1) + { + // Error getting next file + break; + } + } + } + tinydir_close(&dir); + } +} +#endif + #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) // windows os implement should override in platform specific FileUtiles class -bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const +bool FileUtils::isDirectoryExistInternal(std::string_view dirPath) const { CCASSERT(false, "FileUtils not support isDirectoryExistInternal"); return false; } -bool FileUtils::createDirectory(const std::string& path) const +bool FileUtils::createDirectory(std::string_view path) const { CCASSERT(false, "FileUtils not support createDirectory"); return false; } -bool FileUtils::removeDirectory(const std::string& path) const +bool FileUtils::removeDirectory(std::string_view path) const { CCASSERT(false, "FileUtils not support removeDirectory"); return false; } -bool FileUtils::removeFile(const std::string& path) const +bool FileUtils::removeFile(std::string_view path) const { CCASSERT(false, "FileUtils not support removeFile"); return false; } -bool FileUtils::renameFile(const std::string& oldfullpath, const std::string& newfullpath) const +bool FileUtils::renameFile(std::string_view oldfullpath, std::string_view newfullpath) const { CCASSERT(false, "FileUtils not support renameFile"); return false; } -bool FileUtils::renameFile(const std::string& path, const std::string& oldname, const std::string& name) const +bool FileUtils::renameFile(std::string_view path, std::string_view oldname, std::string_view name) const { CCASSERT(false, "FileUtils not support renameFile"); return false; } -int64_t FileUtils::getFileSize(const std::string& filepath) const +int64_t FileUtils::getFileSize(std::string_view filepath) const { CCASSERT(false, "getFileSize should be override by platform FileUtils"); return 0; } -std::vector FileUtils::listFiles(const std::string& dirPath) const -{ - CCASSERT(false, "FileUtils not support listFiles"); - return std::vector(); -} - -void FileUtils::listFilesRecursively(const std::string& dirPath, std::vector* files) const -{ - CCASSERT(false, "FileUtils not support listFilesRecursively"); - return; -} - #else -# include "tinydir/tinydir.h" // default implements for unix like os # include # include @@ -1203,17 +1390,17 @@ void FileUtils::listFilesRecursively(const std::string& dirPath, std::vector # endif -bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const +bool FileUtils::isDirectoryExistInternal(std::string_view dirPath) const { struct stat st; - if (stat(dirPath.c_str(), &st) == 0) + if (stat(dirPath.data(), &st) == 0) { return S_ISDIR(st.st_mode); } return false; } -bool FileUtils::createDirectory(const std::string& path) const +bool FileUtils::createDirectory(std::string_view path) const { CCASSERT(!path.empty(), "Invalid path"); @@ -1223,7 +1410,7 @@ bool FileUtils::createDirectory(const std::string& path) const // Split the path size_t start = 0; size_t found = path.find_first_of("/\\", start); - std::string subpath; + std::string_view subpath; std::vector dirs; if (found != std::string::npos) @@ -1232,14 +1419,14 @@ bool FileUtils::createDirectory(const std::string& path) const { subpath = path.substr(start, found - start + 1); if (!subpath.empty()) - dirs.push_back(subpath); + dirs.push_back(std::string{subpath}); start = found + 1; found = path.find_first_of("/\\", start); if (found == std::string::npos) { if (start < path.length()) { - dirs.push_back(path.substr(start)); + dirs.push_back(std::string{path.substr(start)}); } break; } @@ -1249,17 +1436,17 @@ bool FileUtils::createDirectory(const std::string& path) const DIR* dir = NULL; // Create path recursively - subpath = ""; + std::string strSubpath; for (const auto& iter : dirs) { - subpath += iter; - dir = opendir(subpath.c_str()); + strSubpath += iter; + dir = opendir(strSubpath.c_str()); if (!dir) { // directory doesn't exist, should create a new one - int ret = mkdir(subpath.c_str(), S_IRWXU | S_IRWXG | S_IRWXO); + int ret = mkdir(strSubpath.c_str(), S_IRWXU | S_IRWXG | S_IRWXO); if (ret != 0 && (errno != EEXIST)) { // current directory can not be created, sub directories can not be created too @@ -1291,19 +1478,19 @@ int unlink_cb(const char* fpath, const struct stat* sb, int typeflag, struct FTW # endif } // namespace -bool FileUtils::removeDirectory(const std::string& path) const +bool FileUtils::removeDirectory(std::string_view path) const { # if !defined(CC_TARGET_OS_TVOS) # if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) - if (nftw(path.c_str(), unlink_cb, 64, FTW_DEPTH | FTW_PHYS) == -1) + if (nftw(path.data(), unlink_cb, 64, FTW_DEPTH | FTW_PHYS) == -1) return false; else return true; # else - std::string command = "rm -r "; + std::string command = "rm -r \""s; // Path may include space. - command += "\"" + path + "\""; + command.append(path).append("\"", 1); if (system(command.c_str()) >= 0) return true; else @@ -1315,9 +1502,9 @@ bool FileUtils::removeDirectory(const std::string& path) const # endif // !defined(CC_TARGET_OS_TVOS) } -bool FileUtils::removeFile(const std::string& path) const +bool FileUtils::removeFile(std::string_view path) const { - if (remove(path.c_str())) + if (remove(path.data())) { return false; } @@ -1327,46 +1514,51 @@ bool FileUtils::removeFile(const std::string& path) const } } -bool FileUtils::renameFile(const std::string& oldfullpath, const std::string& newfullpath) const +bool FileUtils::renameFile(std::string_view oldfullpath, std::string_view newfullpath) const { CCASSERT(!oldfullpath.empty(), "Invalid path"); CCASSERT(!newfullpath.empty(), "Invalid path"); - int errorCode = rename(oldfullpath.c_str(), newfullpath.c_str()); + int errorCode = rename(oldfullpath.data(), newfullpath.data()); if (0 != errorCode) { - CCLOGERROR("Fail to rename file %s to %s !Error code is %d", oldfullpath.c_str(), newfullpath.c_str(), - errorCode); + CCLOGERROR("Fail to rename file %s to %s !Error code is %d", oldfullpath.data(), newfullpath.data(), errorCode); return false; } return true; } -bool FileUtils::renameFile(const std::string& path, const std::string& oldname, const std::string& name) const +bool FileUtils::renameFile(std::string_view path, std::string_view oldname, std::string_view name) const { CCASSERT(!path.empty(), "Invalid path"); - std::string oldPath = path + oldname; - std::string newPath = path + name; + std::string oldPath{path}; + oldPath += oldname; + std::string newPath{path}; + newPath += name; return this->renameFile(oldPath, newPath); } -int64_t FileUtils::getFileSize(const std::string& filepath) const +int64_t FileUtils::getFileSize(std::string_view filepath) const { CCASSERT(!filepath.empty(), "Invalid path"); - std::string fullpath = filepath; + std::string_view path; + std::string fullpath; if (!isAbsolutePath(filepath)) { fullpath = fullPathForFilename(filepath); if (fullpath.empty()) return 0; + path = fullpath; } + else + path = filepath; struct stat info; // Get data associated with "crt_stat.c": - int result = ::stat(fullpath.c_str(), &info); + int result = ::stat(path.data(), &info); // Check if statistics are valid: if (result != 0) @@ -1380,92 +1572,6 @@ int64_t FileUtils::getFileSize(const std::string& filepath) const } } -std::vector FileUtils::listFiles(const std::string& dirPath) const -{ - std::vector files; - std::string fullpath = fullPathForDirectory(dirPath); - if (!fullpath.empty() && isDirectoryExist(fullpath)) - { - tinydir_dir dir; - std::string fullpathstr = fullpath; - - if (tinydir_open(&dir, &fullpathstr[0]) != -1) - { - while (dir.has_next) - { - tinydir_file file; - if (tinydir_readfile(&dir, &file) == -1) - { - // Error getting file - break; - } - std::string filepath = file.path; - - if (strcmp(file.name, ".") != 0 && strcmp(file.name, "..") != 0) - { - if (file.is_dir) - filepath.push_back('/'); - - files.push_back(std::move(filepath)); - } - - if (tinydir_next(&dir) == -1) - { - // Error getting next file - break; - } - } - } - tinydir_close(&dir); - } - return files; -} - -void FileUtils::listFilesRecursively(const std::string& dirPath, std::vector* files) const -{ - std::string fullpath = fullPathForDirectory(dirPath); - if (isDirectoryExist(fullpath)) - { - tinydir_dir dir; - std::string fullpathstr = fullpath; - - if (tinydir_open(&dir, &fullpathstr[0]) != -1) - { - while (dir.has_next) - { - tinydir_file file; - if (tinydir_readfile(&dir, &file) == -1) - { - // Error getting file - break; - } - - if (strcmp(file.name, ".") != 0 && strcmp(file.name, "..") != 0) - { - std::string filepath = file.path; - if (file.is_dir) - { - filepath.push_back('/'); - files->push_back(filepath); - listFilesRecursively(filepath, files); - } - else - { - files->push_back(std::move(filepath)); - } - } - - if (tinydir_next(&dir) == -1) - { - // Error getting next file - break; - } - } - } - tinydir_close(&dir); - } -} - #endif ////////////////////////////////////////////////////////////////////////// @@ -1483,7 +1589,7 @@ bool FileUtils::isPopupNotify() const return s_popupNotify; } -std::string FileUtils::getFileExtension(const std::string& filePath) const +std::string FileUtils::getFileExtension(std::string_view filePath) const { std::string fileExtension; size_t pos = filePath.find_last_of('.'); @@ -1497,16 +1603,16 @@ std::string FileUtils::getFileExtension(const std::string& filePath) const return fileExtension; } -std::string FileUtils::getFileShortName(const std::string& filePath) +std::string FileUtils::getFileShortName(std::string_view filePath) { - std::string fileExtension; + // std::string fileExtension; size_t pos = filePath.find_last_of("/\\"); if (pos != std::string::npos) { - return filePath.substr(pos + 1); + return std::string{filePath.substr(pos + 1)}; } - return filePath; + return std::string{filePath}; } void FileUtils::valueMapCompact(ValueMap& /*valueMap*/) const {} diff --git a/cocos/platform/CCFileUtils.h b/cocos/platform/CCFileUtils.h index 3376b9035d7f..0e82201e78f2 100644 --- a/cocos/platform/CCFileUtils.h +++ b/cocos/platform/CCFileUtils.h @@ -157,7 +157,7 @@ class CC_DLL FileUtils /** * Gets string from a file. */ - virtual std::string getStringFromFile(const std::string& filename) const; + virtual std::string getStringFromFile(std::string_view filename) const; /** * Gets string from a file, async off the main cocos thread @@ -166,13 +166,13 @@ class CC_DLL FileUtils * @param callback Function that will be called when file is read. Will be called * on the main cocos thread. */ - virtual void getStringFromFile(const std::string& path, std::function callback) const; + virtual void getStringFromFile(std::string_view path, std::function callback) const; /** * Creates binary data from a file. * @return A data object. */ - virtual Data getDataFromFile(const std::string& filename) const; + virtual Data getDataFromFile(std::string_view filename) const; /** * Gets a binary data object from a file, async off the main cocos thread. @@ -181,7 +181,7 @@ class CC_DLL FileUtils * @param callback Function that will be called when file is read. Will be called * on the main cocos thread. */ - virtual void getDataFromFile(const std::string& filename, std::function callback) const; + virtual void getDataFromFile(std::string_view filename, std::function callback) const; enum class Status { @@ -255,12 +255,12 @@ class CC_DLL FileUtils template >::value>::type> - Status getContents(const std::string& filename, T* buffer) const + Status getContents(std::string_view filename, T* buffer) const { ResizableBufferAdapter buf(buffer); return getContents(filename, &buf); } - virtual Status getContents(const std::string& filename, ResizableBuffer* buffer) const; + virtual Status getContents(std::string_view filename, ResizableBuffer* buffer) const; /** Returns the fullpath for a given filename. @@ -310,7 +310,7 @@ class CC_DLL FileUtils @since v2.1 */ - virtual std::string fullPathForFilename(const std::string& filename) const; + virtual std::string fullPathForFilename(std::string_view filename) const; /** * Loads the filenameLookup dictionary from the contents of a filename. @@ -345,7 +345,7 @@ class CC_DLL FileUtils * @js loadFilenameLookup * @lua loadFilenameLookup */ - virtual void loadFilenameLookupDictionaryFromFile(const std::string& filename); + virtual void loadFilenameLookupDictionaryFromFile(std::string_view filename); /** * Sets the filenameLookup dictionary. @@ -365,7 +365,7 @@ class CC_DLL FileUtils * dictionary. ) * */ - virtual std::string fullPathFromRelativeFile(const std::string& filename, const std::string& relativeFile) const; + virtual std::string fullPathFromRelativeFile(std::string_view filename, std::string_view relativeFile) const; /** * Sets the array that contains the search order of the resources. @@ -384,7 +384,7 @@ class CC_DLL FileUtils * @see setSearchResolutionsOrder(), fullPathForFilename(). * @since v2.1 */ - virtual void addSearchResolutionsOrder(const std::string& order, const bool front = false); + virtual void addSearchResolutionsOrder(std::string_view order, const bool front = false); /** * Gets the array that contains the search order of the resources. @@ -424,14 +424,14 @@ class CC_DLL FileUtils /** * Set default resource root path. */ - void setDefaultResourceRootPath(const std::string& path); + void setDefaultResourceRootPath(std::string_view path); /** * Add search path. * * @since v2.1 */ - void addSearchPath(const std::string& path, const bool front = false); + void addSearchPath(std::string_view path, const bool front = false); /** * Gets the array of search paths. @@ -468,7 +468,7 @@ class CC_DLL FileUtils /** * Sets writable path. */ - virtual void setWritablePath(const std::string& writablePath); + virtual void setWritablePath(std::string_view writablePath); /** * Sets whether to pop-up a message box when failed to load an image. @@ -486,7 +486,7 @@ class CC_DLL FileUtils * @return ValueMap of the file contents. * @note This method is used internally. */ - virtual ValueMap getValueMapFromFile(const std::string& filename) const; + virtual ValueMap getValueMapFromFile(std::string_view filename) const; /** Converts the contents of a file to a ValueMap. * This method is used internally. @@ -500,7 +500,7 @@ class CC_DLL FileUtils *@param fullPath The full path to the file you want to save a string *@return bool */ - virtual bool writeToFile(const ValueMap& dict, const std::string& fullPath) const; + virtual bool writeToFile(const ValueMap& dict, std::string_view fullPath) const; /** * write a string into a file @@ -509,7 +509,7 @@ class CC_DLL FileUtils * @param fullPath The full path to the file you want to save a string * @return bool True if write success */ - virtual bool writeStringToFile(const std::string& dataStr, const std::string& fullPath) const; + virtual bool writeStringToFile(std::string_view dataStr, std::string_view fullPath) const; /** * Write a string to a file, done async off the main cocos thread @@ -525,7 +525,7 @@ class CC_DLL FileUtils * signifying if the write was successful. */ virtual void writeStringToFile(std::string dataStr, - const std::string& fullPath, + std::string_view fullPath, std::function callback) const; /** @@ -535,12 +535,12 @@ class CC_DLL FileUtils *@param fullPath The full path to the file you want to save a string *@return bool */ - virtual bool writeDataToFile(const Data& data, const std::string& fullPath) const; + virtual bool writeDataToFile(const Data& data, std::string_view fullPath) const; /** * save data to file */ - static bool writeBinaryToFile(const void* data, size_t dataSize, const std::string& fullPath); + static bool writeBinaryToFile(const void* data, size_t dataSize, std::string_view fullPath); /** * Write Data into a file, done async off the main cocos thread. @@ -556,7 +556,7 @@ class CC_DLL FileUtils * function will be executed on the main cocos thread. It will have on boolean argument * signifying if the write was successful. */ - virtual void writeDataToFile(Data data, const std::string& fullPath, std::function callback) const; + virtual void writeDataToFile(Data data, std::string_view fullPath, std::function callback) const; /** * write ValueMap into a plist file @@ -565,7 +565,7 @@ class CC_DLL FileUtils *@param fullPath The full path to the file you want to save a string *@return bool */ - virtual bool writeValueMapToFile(const ValueMap& dict, const std::string& fullPath) const; + virtual bool writeValueMapToFile(const ValueMap& dict, std::string_view fullPath) const; /** * Write a ValueMap into a file, done async off the main cocos thread. @@ -582,7 +582,7 @@ class CC_DLL FileUtils * signifying if the write was successful. */ virtual void writeValueMapToFile(ValueMap dict, - const std::string& fullPath, + std::string_view fullPath, std::function callback) const; /** @@ -592,7 +592,7 @@ class CC_DLL FileUtils *@param fullPath The full path to the file you want to save a string *@return bool */ - virtual bool writeValueVectorToFile(const ValueVector& vecData, const std::string& fullPath) const; + virtual bool writeValueVectorToFile(const ValueVector& vecData, std::string_view fullPath) const; /** * Write a ValueVector into a file, done async off the main cocos thread. @@ -609,12 +609,12 @@ class CC_DLL FileUtils * signifying if the write was successful. */ virtual void writeValueVectorToFile(ValueVector vecData, - const std::string& fullPath, + std::string_view fullPath, std::function callback) const; // Converts the contents of a file to a ValueVector. // This method is used internally. - virtual ValueVector getValueVectorFromFile(const std::string& filename) const; + virtual ValueVector getValueVectorFromFile(std::string_view filename) const; /** * Checks whether a file exists. @@ -623,7 +623,7 @@ class CC_DLL FileUtils * @param filename The path of the file, it could be a relative or absolute path. * @return True if the file exists, false if not. */ - virtual bool isFileExist(const std::string& filename) const; + virtual bool isFileExist(std::string_view filename) const; /** * Checks if a file exists, done async off the main cocos thread. @@ -635,7 +635,7 @@ class CC_DLL FileUtils * @param callback The function that will be called when the operation is complete. Will have one boolean * argument, true if the file exists, false otherwise. */ - virtual void isFileExist(const std::string& filename, std::function callback) const; + virtual void isFileExist(std::string_view filename, std::function callback) const; /** * Gets filename extension is a suffix (separated from the base filename by a dot) in lower case. @@ -643,14 +643,14 @@ class CC_DLL FileUtils * @param filePath The path of the file, it could be a relative or absolute path. * @return suffix for filename in lower case or empty if a dot not found. */ - virtual std::string getFileExtension(const std::string& filePath) const; + virtual std::string getFileExtension(std::string_view filePath) const; /** * Gets filename shotName * @param filePath The path of the file, it could be a relative or absolute path. * @return fileName.Extension without path */ - static std::string getFileShortName(const std::string& filePath); + static std::string getFileShortName(std::string_view filePath); /** * Checks whether the path is an absolute path. @@ -661,9 +661,9 @@ class CC_DLL FileUtils * @param path The path that needs to be checked. * @return True if it's an absolute path, false if not. */ - virtual bool isAbsolutePath(const std::string& path) const; + virtual bool isAbsolutePath(std::string_view path) const; - static bool isAbsolutePathInternal(const std::string& path); + static bool isAbsolutePathInternal(std::string_view path); /** * Checks whether the path is a directory. @@ -671,7 +671,7 @@ class CC_DLL FileUtils * @param dirPath The path of the directory, it could be a relative or an absolute path. * @return True if the directory exists, false if not. */ - virtual bool isDirectoryExist(const std::string& dirPath) const; + virtual bool isDirectoryExist(std::string_view dirPath) const; /** * Checks whether the absoulate path is a directory, async off of the main cocos thread. @@ -680,7 +680,7 @@ class CC_DLL FileUtils * @param callback that will accept a boolean, true if the file exists, false otherwise. * Callback will happen on the main cocos thread. */ - virtual void isDirectoryExist(const std::string& fullPath, std::function callback) const; + virtual void isDirectoryExist(std::string_view fullPath, std::function callback) const; /** * Creates a directory. @@ -688,7 +688,7 @@ class CC_DLL FileUtils * @param dirPath The path of the directory, it must be an absolute path. * @return True if the directory have been created successfully, false if not. */ - virtual bool createDirectory(const std::string& dirPath) const; + virtual bool createDirectory(std::string_view dirPath) const; /** * Create a directory, async off the main cocos thread. @@ -697,7 +697,7 @@ class CC_DLL FileUtils * @param callback The function that will be called when the operation is complete. Will have one boolean * argument, true if the directory was successfully, false otherwise. */ - virtual void createDirectory(const std::string& dirPath, std::function callback) const; + virtual void createDirectory(std::string_view dirPath, std::function callback) const; /** * Removes a directory. @@ -705,7 +705,7 @@ class CC_DLL FileUtils * @param dirPath The full path of the directory, it must be an absolute path. * @return True if the directory have been removed successfully, false if not. */ - virtual bool removeDirectory(const std::string& dirPath) const; + virtual bool removeDirectory(std::string_view dirPath) const; /** * Removes a directory, async off the main cocos thread. @@ -714,7 +714,7 @@ class CC_DLL FileUtils * @param callback The function that will be called when the operation is complete. Will have one boolean * argument, true if the directory was successfully removed, false otherwise. */ - virtual void removeDirectory(const std::string& dirPath, std::function callback) const; + virtual void removeDirectory(std::string_view dirPath, std::function callback) const; /** * Removes a file. @@ -722,7 +722,7 @@ class CC_DLL FileUtils * @param filepath The full path of the file, it must be an absolute path. * @return True if the file have been removed successfully, false if not. */ - virtual bool removeFile(const std::string& filepath) const; + virtual bool removeFile(std::string_view filepath) const; /** * Removes a file, async off the main cocos thread. @@ -731,7 +731,7 @@ class CC_DLL FileUtils * @param callback The function that will be called when the operation is complete. Will have one boolean * argument, true if the file was successfully removed, false otherwise. */ - virtual void removeFile(const std::string& filepath, std::function callback) const; + virtual void removeFile(std::string_view filepath, std::function callback) const; /** * Renames a file under the given directory. @@ -741,7 +741,7 @@ class CC_DLL FileUtils * @param name The new name of the file. * @return True if the file have been renamed successfully, false if not. */ - virtual bool renameFile(const std::string& path, const std::string& oldname, const std::string& name) const; + virtual bool renameFile(std::string_view path, std::string_view oldname, std::string_view name) const; /** * Renames a file under the given directory, async off the main cocos thread. @@ -752,9 +752,9 @@ class CC_DLL FileUtils * @param callback The function that will be called when the operation is complete. Will have one boolean * argument, true if the file was successfully renamed, false otherwise. */ - virtual void renameFile(const std::string& path, - const std::string& oldname, - const std::string& name, + virtual void renameFile(std::string_view path, + std::string_view oldname, + std::string_view name, std::function callback) const; /** @@ -764,7 +764,7 @@ class CC_DLL FileUtils * @param newfullpath The new fullpath of the file. Includes path and name. * @return True if the file have been renamed successfully, false if not. */ - virtual bool renameFile(const std::string& oldfullpath, const std::string& newfullpath) const; + virtual bool renameFile(std::string_view oldfullpath, std::string_view newfullpath) const; /** * Renames a file under the given directory, async off the main cocos thread. @@ -774,8 +774,8 @@ class CC_DLL FileUtils * @param callback The function that will be called when the operation is complete. Will have one boolean * argument, true if the file was successfully renamed, false otherwise. */ - virtual void renameFile(const std::string& oldfullpath, - const std::string& newfullpath, + virtual void renameFile(std::string_view oldfullpath, + std::string_view newfullpath, std::function callback) const; /** @@ -785,7 +785,7 @@ class CC_DLL FileUtils * @param filepath The path of the file, it could be a relative or absolute path. * @return The file size. */ - virtual int64_t getFileSize(const std::string& filepath) const; + virtual int64_t getFileSize(std::string_view filepath) const; /** * Retrieve the file size, async off the main cocos thread. @@ -795,7 +795,7 @@ class CC_DLL FileUtils * @param callback The function that will be called when the operation is complete. Will have one long * argument, the file size. */ - virtual void getFileSize(const std::string& filepath, std::function callback) const; + virtual void getFileSize(std::string_view filepath, std::function callback) const; /** * List all files in a directory. @@ -803,7 +803,7 @@ class CC_DLL FileUtils * @param dirPath The path of the directory, it could be a relative or an absolute path. * @return File paths in a string vector */ - virtual std::vector listFiles(const std::string& dirPath) const; + virtual std::vector listFiles(std::string_view dirPath) const; /** * List all files in a directory async, off of the main cocos thread. @@ -814,8 +814,7 @@ class CC_DLL FileUtils * @js NA * @lua NA */ - virtual void listFilesAsync(const std::string& dirPath, - std::function)> callback) const; + virtual void listFilesAsync(std::string_view dirPath, std::function)> callback) const; /** * List all files recursively in a directory. @@ -823,7 +822,7 @@ class CC_DLL FileUtils * @param dirPath The path of the directory, it could be a relative or an absolute path. * @return File paths in a string vector */ - virtual void listFilesRecursively(const std::string& dirPath, std::vector* files) const; + virtual void listFilesRecursively(std::string_view dirPath, std::vector* files) const; /** * List all files recursively in a directory, async off the main cocos thread. @@ -834,11 +833,11 @@ class CC_DLL FileUtils * @js NA * @lua NA */ - virtual void listFilesRecursivelyAsync(const std::string& dirPath, + virtual void listFilesRecursivelyAsync(std::string_view dirPath, std::function)> callback) const; /** Returns the full path cache. */ - const std::unordered_map getFullPathCache() const { return _fullPathCache; } + const hlookup::string_map getFullPathCache() const { return _fullPathCache; } /** * Gets the new filename from the filename lookup dictionary. @@ -847,21 +846,21 @@ class CC_DLL FileUtils * @return The new filename after searching in the filename lookup dictionary. * If the original filename wasn't in the dictionary, it will return the original filename. */ - virtual std::string getNewFilename(const std::string& filename) const; + virtual std::string getNewFilename(std::string_view filename) const; /** * Checks whether a file exists without considering search paths and resolution orders. * @param filename The file (with absolute path) to look up for * @return Returns true if the file found at the given absolute path, otherwise returns false */ - virtual bool isFileExistInternal(const std::string& filename) const = 0; + virtual bool isFileExistInternal(std::string_view filename) const = 0; /** * Checks whether a directory exists without considering search paths and resolution orders. * @param dirPath The directory (with absolute path) to look up for * @return Returns true if the directory found at the given absolute path, otherwise returns false */ - virtual bool isDirectoryExistInternal(const std::string& dirPath) const; + virtual bool isDirectoryExistInternal(std::string_view dirPath) const; /** * Open a FileStream based on the implementation provided in openFileStream or its overrides @@ -869,7 +868,7 @@ class CC_DLL FileUtils * @param mode The mode to open the file in, being READ | WRITE | APPEND * @return Returns a pointer to the file stream */ - virtual std::unique_ptr openFileStream(const std::string& filePath, FileStream::Mode mode); + virtual std::unique_ptr openFileStream(std::string_view filePath, FileStream::Mode mode); protected: /** @@ -897,13 +896,13 @@ class CC_DLL FileUtils * @param searchPath The search path. * @return The full path of the file. It will return an empty string if the full path of the file doesn't exist. */ - virtual std::string getPathForFilename(const std::string& filename, - const std::string& resolutionDirectory, - const std::string& searchPath) const; + virtual std::string getPathForFilename(std::string_view filename, + std::string_view resolutionDirectory, + std::string_view searchPath) const; - virtual std::string getPathForDirectory(const std::string& dir, - const std::string& resolutionDiretory, - const std::string& searchPath) const; + virtual std::string getPathForDirectory(std::string_view dir, + std::string_view resolutionDiretory, + std::string_view searchPath) const; /** * Gets full path for the directory and the filename. @@ -915,14 +914,14 @@ class CC_DLL FileUtils * @param filename The name of the file. * @return The full path of the file, if the file can't be found, it will return an empty string. */ - virtual std::string getFullPathForFilenameWithinDirectory(const std::string& directory, - const std::string& filename) const; + virtual std::string getFullPathForFilenameWithinDirectory(std::string_view directory, + std::string_view filename) const; /** * Returns the fullpath for a given dirname. * @since 3.17.1 */ - virtual std::string fullPathForDirectory(const std::string& dirname) const; + virtual std::string fullPathForDirectory(std::string_view dirname) const; /** * mutex used to protect fields. @@ -968,13 +967,13 @@ class CC_DLL FileUtils * The full path cache for normal files. When a file is found, it will be added into this cache. * This variable is used for improving the performance of file search. */ - mutable std::unordered_map _fullPathCache; + mutable hlookup::string_map _fullPathCache; /** * The full path cache for directories. When a diretory is found, it will be added into this cache. * This variable is used for improving the performance of file search. */ - mutable std::unordered_map _fullPathCacheDir; + mutable hlookup::string_map _fullPathCacheDir; /** * Writable path. diff --git a/cocos/platform/CCGLView.cpp b/cocos/platform/CCGLView.cpp index 5c8494362ae9..7ee97868afbf 100644 --- a/cocos/platform/CCGLView.cpp +++ b/cocos/platform/CCGLView.cpp @@ -279,12 +279,12 @@ Rect GLView::getScissorRect() const return Rect(x, y, w, h); } -void GLView::setViewName(const std::string& viewname) +void GLView::setViewName(std::string_view viewname) { _viewName = viewname; } -const std::string& GLView::getViewName() const +std::string_view GLView::getViewName() const { return _viewName; } diff --git a/cocos/platform/CCGLView.h b/cocos/platform/CCGLView.h index 6cd6c1568b77..f5bbc43547f6 100644 --- a/cocos/platform/CCGLView.h +++ b/cocos/platform/CCGLView.h @@ -308,13 +308,13 @@ class CC_DLL GLView : public Ref * * @param viewname A string will be set to the view as name. */ - virtual void setViewName(const std::string& viewname); + virtual void setViewName(std::string_view viewname); /** Get the view name. * * @return The view name. */ - const std::string& getViewName() const; + std::string_view getViewName() const; /** Touch events are handled by default; if you want to customize your handlers, please override this function. * @@ -367,14 +367,14 @@ class CC_DLL GLView : public Ref * * @param filename A path to image file, e.g., "icons/cusom.png". */ - virtual void setIcon(const std::string& filename) const {}; + virtual void setIcon(std::string_view filename) const {}; /** Set window icon (implemented for windows and linux). * Best icon (based on size) will be auto selected. * * @param filelist The array contains icons. */ - virtual void setIcon(const std::vector& filelist) const {}; + virtual void setIcon(const std::vector& filelist) const {}; /** Set default window icon (implemented for windows and linux). * On windows it will use icon from .exe file (if included). diff --git a/cocos/platform/CCImage.cpp b/cocos/platform/CCImage.cpp index 6f2340a153da..7296355cae2b 100644 --- a/cocos/platform/CCImage.cpp +++ b/cocos/platform/CCImage.cpp @@ -601,7 +601,7 @@ Image::~Image() } } -bool Image::initWithImageFile(const std::string& path) +bool Image::initWithImageFile(std::string_view path) { bool ret = false; _filePath = FileUtils::getInstance()->fullPathForFilename(path); @@ -618,7 +618,7 @@ bool Image::initWithImageFile(const std::string& path) return ret; } -bool Image::initWithImageFileThreadSafe(const std::string& fullpath) +bool Image::initWithImageFileThreadSafe(std::string_view fullpath) { bool ret = false; _filePath = fullpath; @@ -2193,7 +2193,7 @@ void Image::forwardPixels(uint8_t* data, ssize_t dataLen, int offset, bool ownDa } #if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) -bool Image::saveToFile(const std::string& filename, bool isToRGB) +bool Image::saveToFile(std::string_view filename, bool isToRGB) { // only support for backend::PixelFormat::RGB8 or backend::PixelFormat::RGBA8 uncompressed data if (isCompressed() || (_pixelFormat != backend::PixelFormat::RGB8 && _pixelFormat != backend::PixelFormat::RGBA8)) @@ -2216,13 +2216,13 @@ bool Image::saveToFile(const std::string& filename, bool isToRGB) } else { - CCLOG("cocos2d: Image: saveToFile no support file extension(only .png or .jpg) for file: %s", filename.c_str()); + CCLOG("cocos2d: Image: saveToFile no support file extension(only .png or .jpg) for file: %s", filename.data()); return false; } } #endif -bool Image::saveImageToPNG(const std::string& filePath, bool isToRGB) +bool Image::saveImageToPNG(std::string_view filePath, bool isToRGB) { #if CC_USE_PNG bool ret = false; @@ -2365,7 +2365,7 @@ bool Image::saveImageToPNG(const std::string& filePath, bool isToRGB) #endif // CC_USE_PNG } -bool Image::saveImageToJPG(const std::string& filePath) +bool Image::saveImageToJPG(std::string_view filePath) { #if CC_USE_JPEG bool ret = false; diff --git a/cocos/platform/CCImage.h b/cocos/platform/CCImage.h index 3466dbe61744..ae1adc4ff3b9 100644 --- a/cocos/platform/CCImage.h +++ b/cocos/platform/CCImage.h @@ -148,7 +148,7 @@ class CC_DLL Image : public Ref @param path the absolute file path. @return true if loaded correctly. */ - bool initWithImageFile(const std::string& path); + bool initWithImageFile(std::string_view path); /** @brief Load image from stream buffer. @@ -191,7 +191,7 @@ class CC_DLL Image : public Ref @param filePath the file's absolute path, including file suffix. @param isToRGB whether the image is saved as RGB format. */ - bool saveToFile(const std::string& filename, bool isToRGB = true); + bool saveToFile(std::string_view filename, bool isToRGB = true); void premultiplyAlpha(); void reversePremultipliedAlpha(); @@ -218,8 +218,8 @@ class CC_DLL Image : public Ref // fast forward pixels to GPU if ownData void forwardPixels(uint8_t* data, ssize_t dataLen, int offset, bool ownData); - bool saveImageToPNG(const std::string& filePath, bool isToRGB = true); - bool saveImageToJPG(const std::string& filePath); + bool saveImageToPNG(std::string_view filePath, bool isToRGB = true); + bool saveImageToJPG(std::string_view filePath); protected: /** @@ -259,7 +259,7 @@ class CC_DLL Image : public Ref @param imageType the type of image, currently only supporting two types. @return true if loaded correctly. */ - bool initWithImageFileThreadSafe(const std::string& fullpath); + bool initWithImageFileThreadSafe(std::string_view fullpath); Format detectFormat(const uint8_t* data, ssize_t dataLen); bool isPng(const uint8_t* data, ssize_t dataLen); diff --git a/cocos/platform/CCPlatformMacros.h b/cocos/platform/CCPlatformMacros.h index 4f2a33e3e028..b8a6516c14d6 100644 --- a/cocos/platform/CCPlatformMacros.h +++ b/cocos/platform/CCPlatformMacros.h @@ -32,6 +32,7 @@ Copyright (c) 2021 Bytedance Inc. * Define some platform specific macros. */ #include "base/ccConfig.h" +#include "base/hlookup.h" #include "platform/CCPlatformConfig.h" #include "platform/CCPlatformDefine.h" diff --git a/cocos/platform/CCPosixFileStream.cpp b/cocos/platform/CCPosixFileStream.cpp index 6606cc594ceb..cdf1f76bee94 100644 --- a/cocos/platform/CCPosixFileStream.cpp +++ b/cocos/platform/CCPosixFileStream.cpp @@ -19,7 +19,7 @@ struct PXIoF long long (*size)(PXFileHandle& handle); }; -static int pfs_posix_open(const std::string& path, FileStream::Mode mode, PXFileHandle& handle) +static int pfs_posix_open(std::string_view path, FileStream::Mode mode, PXFileHandle& handle) { switch (mode) { @@ -127,7 +127,7 @@ PosixFileStream::~PosixFileStream() internalClose(); } -bool PosixFileStream::open(const std::string& path, FileStream::Mode mode) +bool PosixFileStream::open(std::string_view path, FileStream::Mode mode) { bool ok = false; #if CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID diff --git a/cocos/platform/CCPosixFileStream.h b/cocos/platform/CCPosixFileStream.h index 183f6d5dea43..02b668a616ce 100644 --- a/cocos/platform/CCPosixFileStream.h +++ b/cocos/platform/CCPosixFileStream.h @@ -54,7 +54,7 @@ # define O_APPEND_FLAGS O_APPEND | O_CREAT | O_RDWR, S_IRWXU # define O_OVERLAP_FLAGS O_CREAT | O_RDWR, S_IRWXU -# define posix_open_cxx(path, ...) ::open(path.c_str(), ##__VA_ARGS__) +# define posix_open_cxx(path, ...) ::open(path.data(), ##__VA_ARGS__) # define posix_open ::open # define posix_close ::close # define posix_lseek ::lseek @@ -114,7 +114,7 @@ class CC_DLL PosixFileStream : public FileStream APPEND, }; - bool open(const std::string& path, FileStream::Mode mode) override; + bool open(std::string_view path, FileStream::Mode mode) override; int close() override; int seek(int64_t offset, int origin) override; diff --git a/cocos/platform/CCSAXParser.cpp b/cocos/platform/CCSAXParser.cpp index 2629c6a856df..7af489f71f43 100644 --- a/cocos/platform/CCSAXParser.cpp +++ b/cocos/platform/CCSAXParser.cpp @@ -108,7 +108,7 @@ bool SAXParser::parse(const char* xmlData, size_t dataLength) return false; } -bool SAXParser::parse(const std::string& filename) +bool SAXParser::parse(std::string_view filename) { bool ret = false; Data data = FileUtils::getInstance()->getDataFromFile(filename); diff --git a/cocos/platform/CCSAXParser.h b/cocos/platform/CCSAXParser.h index 7b948fc0711b..ecb4c7bbe5f5 100644 --- a/cocos/platform/CCSAXParser.h +++ b/cocos/platform/CCSAXParser.h @@ -90,7 +90,7 @@ class CC_DLL SAXParser * @js NA * @lua NA */ - bool parse(const std::string& filename); + bool parse(std::string_view filename); /** * New API for performance. diff --git a/cocos/platform/CMakeLists.txt b/cocos/platform/CMakeLists.txt index c91d63fdd5cf..1b60199c7b56 100644 --- a/cocos/platform/CMakeLists.txt +++ b/cocos/platform/CMakeLists.txt @@ -30,6 +30,14 @@ if(ANDROID) platform/android/CCGLViewImpl-android.cpp platform/android/CCFileUtils-android.cpp platform/android/CCEnhanceAPI-android.cpp + platform/android/CCDevice-android.cpp + platform/android/javaactivity-android.cpp + platform/android/jni/JniHelper.cpp + platform/android/jni/TouchesJni.cpp + platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxAccelerometer.cpp + platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp + platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp + platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp ) elseif(WINDOWS) set(COCOS_PLATFORM_SPECIFIC_HEADER diff --git a/cocos/platform/android/CCApplication-android.cpp b/cocos/platform/android/CCApplication-android.cpp index 08809fb6d7ad..16927d40d5c7 100644 --- a/cocos/platform/android/CCApplication-android.cpp +++ b/cocos/platform/android/CCApplication-android.cpp @@ -43,7 +43,7 @@ extern "C" size_t __ctype_get_mb_cur_max(void) } #endif -static const std::string helperClassName = "org.cocos2dx.lib.Cocos2dxHelper"; +static const char* helperClassName = "org.cocos2dx.lib.Cocos2dxHelper"; NS_CC_BEGIN @@ -119,7 +119,7 @@ std::string Application::getVersion() return JniHelper::callStaticStringMethod(helperClassName, "getVersion"); } -bool Application::openURL(const std::string& url) +bool Application::openURL(std::string_view url) { return JniHelper::callStaticBooleanMethod(helperClassName, "openURL", url); } diff --git a/cocos/platform/android/CCApplication-android.h b/cocos/platform/android/CCApplication-android.h index 42cf2dc28721..71f0e2146eee 100644 --- a/cocos/platform/android/CCApplication-android.h +++ b/cocos/platform/android/CCApplication-android.h @@ -90,7 +90,7 @@ class CC_DLL Application : public ApplicationProtocol @param String with url to open. @return true if the resource located by the URL was successfully opened; otherwise false. */ - virtual bool openURL(const std::string& url) override; + virtual bool openURL(std::string_view url) override; /** @brief This function will be called when the application screen size is changed. diff --git a/cocos/platform/android/CCDevice-android.cpp b/cocos/platform/android/CCDevice-android.cpp index ebfda66eb062..e5e994fc3a3d 100644 --- a/cocos/platform/android/CCDevice-android.cpp +++ b/cocos/platform/android/CCDevice-android.cpp @@ -33,7 +33,7 @@ THE SOFTWARE. #include "platform/CCFileUtils.h" #include "yasio/cxx17/string_view.hpp" -static const std::string helperClassName = "org.cocos2dx.lib.Cocos2dxHelper"; +static const char* helperClassName = "org.cocos2dx.lib.Cocos2dxHelper"; NS_CC_BEGIN diff --git a/cocos/platform/android/CCFileUtils-android.cpp b/cocos/platform/android/CCFileUtils-android.cpp index dabb0a4148c1..e9ca5b5639a5 100644 --- a/cocos/platform/android/CCFileUtils-android.cpp +++ b/cocos/platform/android/CCFileUtils-android.cpp @@ -36,6 +36,8 @@ THE SOFTWARE. #include #include +#include "yasio/cxx17/string_view.hpp" + #define LOG_TAG "CCFileUtils-android.cpp" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) @@ -103,7 +105,7 @@ bool FileUtilsAndroid::init() return FileUtils::init(); } -std::string FileUtilsAndroid::getNewFilename(const std::string& filename) const +std::string FileUtilsAndroid::getNewFilename(std::string_view filename) const { std::string newFileName = FileUtils::getNewFilename(filename); // ../xxx do not fix this path @@ -156,7 +158,7 @@ std::string FileUtilsAndroid::getNewFilename(const std::string& filename) const return newFileName; } -bool FileUtilsAndroid::isFileExistInternal(const std::string& strFilePath) const +bool FileUtilsAndroid::isFileExistInternal(std::string_view strFilePath) const { DECLARE_GUARD; @@ -171,7 +173,7 @@ bool FileUtilsAndroid::isFileExistInternal(const std::string& strFilePath) const // Check whether file exists in apk. if (strFilePath[0] != '/') { - const char* s = strFilePath.c_str(); + const char* s = strFilePath.data(); // Found "assets/" at the beginning of the path and we don't want it if (strFilePath.find(_defaultResRootPath) == 0) @@ -198,26 +200,30 @@ bool FileUtilsAndroid::isFileExistInternal(const std::string& strFilePath) const else { struct stat st; - if (::stat(strFilePath.c_str(), &st) == 0) + if (::stat(strFilePath.data(), &st) == 0) bFound = S_ISREG(st.st_mode); } return bFound; } -bool FileUtilsAndroid::isDirectoryExistInternal(const std::string& dirPath) const +bool FileUtilsAndroid::isDirectoryExistInternal(std::string_view dirPath) const { if (dirPath.empty()) { return false; } - std::string dirPathCopy = dirPath; - if (dirPathCopy[dirPathCopy.length() - 1] == '/') + std::string_view path; + std::string dirPathCopy; + if (dirPath[dirPath.length() - 1] == '/') { - dirPathCopy.erase(dirPathCopy.length() - 1); + dirPathCopy.assign(dirPath.data(), dirPath.length() - 1); + path = dirPathCopy; } + else + path = dirPath; - const char* s = dirPathCopy.c_str(); + const char* s = path.data(); // find absolute path in flash memory if (s[0] == '/') @@ -254,7 +260,7 @@ bool FileUtilsAndroid::isDirectoryExistInternal(const std::string& dirPath) cons return false; } -bool FileUtilsAndroid::isAbsolutePath(const std::string& strPath) const +bool FileUtilsAndroid::isAbsolutePath(std::string_view strPath) const { DECLARE_GUARD; // On Android, there are two situations for full path. @@ -264,7 +270,7 @@ bool FileUtilsAndroid::isAbsolutePath(const std::string& strPath) const return (strPath[0] == '/' || strPath.find(_defaultResRootPath) == 0); } -int64_t FileUtilsAndroid::getFileSize(const std::string& filepath) const +int64_t FileUtilsAndroid::getFileSize(std::string_view filepath) const { DECLARE_GUARD; int64_t size = FileUtils::getFileSize(filepath); @@ -275,13 +281,16 @@ int64_t FileUtilsAndroid::getFileSize(const std::string& filepath) const if (FileUtilsAndroid::assetmanager) { - string relativePath = filepath; - if (filepath.find(_defaultResRootPath) == 0) + std::string_view path; + std::string relativePath; + if (cxx20::starts_with(filepath, _defaultResRootPath)) { - relativePath = filepath.substr(_defaultResRootPath.size()); + path = relativePath = filepath.substr(_defaultResRootPath.size()); } + else + path = filepath; - AAsset* asset = AAssetManager_open(FileUtilsAndroid::assetmanager, relativePath.data(), AASSET_MODE_UNKNOWN); + AAsset* asset = AAssetManager_open(FileUtilsAndroid::assetmanager, path.data(), AASSET_MODE_UNKNOWN); if (asset) { size = AAsset_getLength(asset); @@ -292,7 +301,7 @@ int64_t FileUtilsAndroid::getFileSize(const std::string& filepath) const return size; } -std::vector FileUtilsAndroid::listFiles(const std::string& dirPath) const +std::vector FileUtilsAndroid::listFiles(std::string_view dirPath) const { if (!dirPath.empty() && dirPath[0] == '/') @@ -347,7 +356,7 @@ std::vector FileUtilsAndroid::listFiles(const std::string& dirPath) return fileList; } -FileUtils::Status FileUtilsAndroid::getContents(const std::string& filename, ResizableBuffer* buffer) const +FileUtils::Status FileUtilsAndroid::getContents(std::string_view filename, ResizableBuffer* buffer) const { static const std::string apkprefix("assets/"); if (filename.empty()) diff --git a/cocos/platform/android/CCFileUtils-android.h b/cocos/platform/android/CCFileUtils-android.h index 44ef3864fb32..fc3c6c8577f6 100644 --- a/cocos/platform/android/CCFileUtils-android.h +++ b/cocos/platform/android/CCFileUtils-android.h @@ -64,20 +64,20 @@ class CC_DLL FileUtilsAndroid : public FileUtils /* override functions */ bool init() override; - virtual std::string getNewFilename(const std::string& filename) const override; + virtual std::string getNewFilename(std::string_view filename) const override; - virtual FileUtils::Status getContents(const std::string& filename, ResizableBuffer* buffer) const override; + virtual FileUtils::Status getContents(std::string_view filename, ResizableBuffer* buffer) const override; virtual std::string getWritablePath() const override; std::string getNativeWritableAbsolutePath() const override; - virtual bool isAbsolutePath(const std::string& strPath) const override; + virtual bool isAbsolutePath(std::string_view strPath) const override; - virtual int64_t getFileSize(const std::string& filepath) const override; - virtual std::vector listFiles(const std::string& dirPath) const override; + virtual int64_t getFileSize(std::string_view filepath) const override; + virtual std::vector listFiles(std::string_view dirPath) const override; private: - virtual bool isFileExistInternal(const std::string& strFilePath) const override; - virtual bool isDirectoryExistInternal(const std::string& dirPath) const override; + virtual bool isFileExistInternal(std::string_view strFilePath) const override; + virtual bool isDirectoryExistInternal(std::string_view dirPath) const override; static AAssetManager* assetmanager; static ZipFile* obbfile; diff --git a/cocos/platform/android/CCGLViewImpl-android.cpp b/cocos/platform/android/CCGLViewImpl-android.cpp index b09471431223..8a0ff6eb3c6b 100644 --- a/cocos/platform/android/CCGLViewImpl-android.cpp +++ b/cocos/platform/android/CCGLViewImpl-android.cpp @@ -50,7 +50,7 @@ void initExtensions() NS_CC_BEGIN -GLViewImpl* GLViewImpl::createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor) +GLViewImpl* GLViewImpl::createWithRect(std::string_view viewName, Rect rect, float frameZoomFactor) { auto ret = new GLViewImpl; if (ret && ret->initWithRect(viewName, rect, frameZoomFactor)) @@ -62,7 +62,7 @@ GLViewImpl* GLViewImpl::createWithRect(const std::string& viewName, Rect rect, f return nullptr; } -GLViewImpl* GLViewImpl::create(const std::string& viewName) +GLViewImpl* GLViewImpl::create(std::string_view viewName) { auto ret = new GLViewImpl; if (ret && ret->initWithFullScreen(viewName)) @@ -74,7 +74,7 @@ GLViewImpl* GLViewImpl::create(const std::string& viewName) return nullptr; } -GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName) +GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName) { auto ret = new GLViewImpl(); if (ret && ret->initWithFullScreen(viewName)) @@ -93,12 +93,12 @@ GLViewImpl::GLViewImpl() GLViewImpl::~GLViewImpl() {} -bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor) +bool GLViewImpl::initWithRect(std::string_view viewName, Rect rect, float frameZoomFactor) { return true; } -bool GLViewImpl::initWithFullScreen(const std::string& viewName) +bool GLViewImpl::initWithFullScreen(std::string_view viewName) { return true; } diff --git a/cocos/platform/android/CCGLViewImpl-android.h b/cocos/platform/android/CCGLViewImpl-android.h index 0f7e2d539bab..fc421309649c 100644 --- a/cocos/platform/android/CCGLViewImpl-android.h +++ b/cocos/platform/android/CCGLViewImpl-android.h @@ -35,9 +35,9 @@ class CC_DLL GLViewImpl : public GLView { public: // static function - static GLViewImpl* create(const std::string& viewname); - static GLViewImpl* createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor = 1.0f); - static GLViewImpl* createWithFullScreen(const std::string& viewName); + static GLViewImpl* create(std::string_view viewname); + static GLViewImpl* createWithRect(std::string_view viewName, Rect rect, float frameZoomFactor = 1.0f); + static GLViewImpl* createWithFullScreen(std::string_view viewName); bool isOpenGLReady() override; void end() override; @@ -49,8 +49,8 @@ class CC_DLL GLViewImpl : public GLView GLViewImpl(); virtual ~GLViewImpl(); - bool initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor); - bool initWithFullScreen(const std::string& viewName); + bool initWithRect(std::string_view viewName, Rect rect, float frameZoomFactor); + bool initWithFullScreen(std::string_view viewName); }; NS_CC_END diff --git a/cocos/platform/android/CMakeLists.txt b/cocos/platform/android/CMakeLists.txt deleted file mode 100644 index fb10db45a146..000000000000 --- a/cocos/platform/android/CMakeLists.txt +++ /dev/null @@ -1,26 +0,0 @@ -# need to whole-archive this lib -set(target_name cpp_android_spec) - -project(${target_name}) - -set(${target_name}_src - CCDevice-android.cpp - javaactivity-android.cpp - jni/JniHelper.cpp - jni/TouchesJni.cpp - jni/Java_org_cocos2dx_lib_Cocos2dxAccelerometer.cpp - jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp - jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp - jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp -) - -add_library(${target_name} STATIC - ${${target_name}_src} -) - -target_include_directories(${target_name} - PRIVATE .. - PRIVATE ../.. - PRIVATE ../../../thirdparty -) - diff --git a/cocos/platform/android/javaactivity-android.cpp b/cocos/platform/android/javaactivity-android.cpp index 2865ba594206..cceffd07fc13 100644 --- a/cocos/platform/android/javaactivity-android.cpp +++ b/cocos/platform/android/javaactivity-android.cpp @@ -1,8 +1,9 @@ /**************************************************************************** Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. +Copyright (c) Bytedance Inc. -http://www.cocos2d-x.org +https://adxeproject.github.io/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -35,6 +36,8 @@ THE SOFTWARE. #include #include +#include "jni/jni.hpp" + #define LOG_TAG "main" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) diff --git a/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp b/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp index f89188ceb427..daad8b2d6dad 100644 --- a/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp +++ b/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp @@ -31,7 +31,7 @@ THE SOFTWARE. #include "platform/CCFileUtils.h" #include "base/ccUTF8.h" -static const std::string className = "org.cocos2dx.lib.Cocos2dxBitmap"; +static const char* className = "org.cocos2dx.lib.Cocos2dxBitmap"; using namespace cocos2d; diff --git a/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp b/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp index 0592dc404412..85bba0fe9097 100644 --- a/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp +++ b/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp @@ -37,7 +37,7 @@ THE SOFTWARE. #define LOG_TAG "Java_org_cocos2dx_lib_Cocos2dxHelper.cpp" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) -static const std::string className = "org.cocos2dx.lib.Cocos2dxHelper"; +static const char* className = "org.cocos2dx.lib.Cocos2dxHelper"; static EditTextCallback s_editTextCallback = nullptr; static void* s_ctx = nullptr; @@ -142,8 +142,7 @@ int getObbAssetFileDescriptorJNI(const char* path, int64_t* startOffset, int64_t JniMethodInfo methodInfo; int fd = 0; - if (JniHelper::getStaticMethodInfo(methodInfo, className.c_str(), "getObbAssetFileDescriptor", - "(Ljava/lang/String;)[J")) + if (JniHelper::getStaticMethodInfo(methodInfo, className, "getObbAssetFileDescriptor", "(Ljava/lang/String;)[J")) { jstring stringArg = methodInfo.env->NewStringUTF(path); jlongArray newArray = @@ -181,7 +180,7 @@ void conversionEncodingJNI(const char* src, int byteSize, const char* fromCharse { JniMethodInfo methodInfo; - if (JniHelper::getStaticMethodInfo(methodInfo, className.c_str(), "conversionEncoding", + if (JniHelper::getStaticMethodInfo(methodInfo, className, "conversionEncoding", "([BLjava/lang/String;Ljava/lang/String;)[B")) { jbyteArray strArray = methodInfo.env->NewByteArray(byteSize); diff --git a/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp b/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp index bf9de1f55e3c..ec5960b5694e 100644 --- a/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp +++ b/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp @@ -84,7 +84,7 @@ JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeDeleteBackwa JNIEXPORT jstring JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeGetContentText(JNIEnv* env, jclass) { - std::string pszText = cocos2d::IMEDispatcher::sharedDispatcher()->getContentText(); + auto pszText = cocos2d::IMEDispatcher::sharedDispatcher()->getContentText(); return cocos2d::StringUtils::newStringUTFJNI(env, pszText); } } diff --git a/cocos/platform/android/jni/JniHelper.cpp b/cocos/platform/android/jni/JniHelper.cpp index bddad033dfc8..66dbf8e90a74 100644 --- a/cocos/platform/android/jni/JniHelper.cpp +++ b/cocos/platform/android/jni/JniHelper.cpp @@ -319,6 +319,11 @@ jstring JniHelper::convert(LocalRefMapType& localRefs, cocos2d::JniMethodInfo& t return ret; } +jstring JniHelper::convert(LocalRefMapType& localRefs, cocos2d::JniMethodInfo& t, std::string_view x) +{ + return convert(localRefs, t, x.data()); +} + jstring JniHelper::convert(LocalRefMapType& localRefs, cocos2d::JniMethodInfo& t, const std::string& x) { return convert(localRefs, t, x.c_str()); @@ -338,10 +343,10 @@ void JniHelper::deleteLocalRefs(JNIEnv* env, LocalRefMapType& localRefs) localRefs[env].clear(); } -void JniHelper::reportError(const std::string& className, const std::string& methodName, const std::string& signature) +void JniHelper::reportError(const char* className, const char* methodName, const char* signature) { - LOGE("Failed to find static java method. Class name: %s, method name: %s, signature: %s ", className.c_str(), - methodName.c_str(), signature.c_str()); + LOGE("Failed to find static java method. Class name: %s, method name: %s, signature: %s ", className, methodName, + signature); } } // namespace cocos2d diff --git a/cocos/platform/android/jni/JniHelper.h b/cocos/platform/android/jni/JniHelper.h index 1367b95c5adc..60fa77e86d6d 100644 --- a/cocos/platform/android/jni/JniHelper.h +++ b/cocos/platform/android/jni/JniHelper.h @@ -2,8 +2,9 @@ Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. +Copyright (c) 2021 Bytedance Inc. -http://www.cocos2d-x.org +https://adxeproject.github.io Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -31,8 +32,34 @@ THE SOFTWARE. #include #include #include +#include #include "platform/CCPlatformMacros.h" #include "math/Vec3.h" +#include "jni/jni.hpp" + +namespace jni +{ +template <> +struct TypeSignature +{ + constexpr auto operator()() const { return TypeSignature{}(); } +}; +template <> +struct TypeSignature +{ + constexpr auto operator()() const { return TypeSignature{}(); } +}; +template <> +struct TypeSignature +{ + constexpr auto operator()() const { return TypeSignature{}(); } +}; +template <> +struct TypeSignature +{ + constexpr auto operator()() const { return TypeSignature{}(); } +}; +} // namespace jni NS_CC_BEGIN @@ -74,11 +101,11 @@ class CC_DLL JniHelper @if no such method will log error */ template - static void callStaticVoidMethod(const std::string& className, const std::string& methodName, Ts... xs) + static void callStaticVoidMethod(const char* className, const char* methodName, Ts&&... xs) { cocos2d::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")V"; - if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) + const char* signature = jni::TypeSignature...)>{}(); + if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, signature)) { LocalRefMapType localRefs; t.env->CallStaticVoidMethod(t.classID, t.methodID, convert(localRefs, t, xs)...); @@ -96,12 +123,12 @@ class CC_DLL JniHelper @return value from Java static boolean method if there are proper JniMethodInfo; otherwise false. */ template - static bool callStaticBooleanMethod(const std::string& className, const std::string& methodName, Ts... xs) + static bool callStaticBooleanMethod(const char* className, const char* methodName, Ts&&... xs) { jboolean jret = JNI_FALSE; cocos2d::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")Z"; - if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) + const char* signature = jni::TypeSignature...)>{}(); + if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, signature)) { LocalRefMapType localRefs; jret = t.env->CallStaticBooleanMethod(t.classID, t.methodID, convert(localRefs, t, xs)...); @@ -120,12 +147,12 @@ class CC_DLL JniHelper @return value from Java static int method if there are proper JniMethodInfo; otherwise 0. */ template - static int callStaticIntMethod(const std::string& className, const std::string& methodName, Ts... xs) + static int callStaticIntMethod(const char* className, const char* methodName, Ts&&... xs) { jint ret = 0; cocos2d::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")I"; - if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) + const char* signature = jni::TypeSignature...)>{}(); + if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, signature)) { LocalRefMapType localRefs; ret = t.env->CallStaticIntMethod(t.classID, t.methodID, convert(localRefs, t, xs)...); @@ -144,12 +171,12 @@ class CC_DLL JniHelper @return value from Java static float method if there are proper JniMethodInfo; otherwise 0. */ template - static float callStaticFloatMethod(const std::string& className, const std::string& methodName, Ts... xs) + static float callStaticFloatMethod(const char* className, const char* methodName, Ts&&... xs) { jfloat ret = 0.0; cocos2d::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")F"; - if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) + const char* signature = jni::TypeSignature...)>{}(); + if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, signature)) { LocalRefMapType localRefs; ret = t.env->CallStaticFloatMethod(t.classID, t.methodID, convert(localRefs, t, xs)...); @@ -168,12 +195,12 @@ class CC_DLL JniHelper @return address of JniMethodInfo if there are proper JniMethodInfo; otherwise nullptr. */ template - static float* callStaticFloatArrayMethod(const std::string& className, const std::string& methodName, Ts... xs) + static float* callStaticFloatArrayMethod(const char* className, const char* methodName, Ts&&... xs) { static float ret[32]; cocos2d::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")[F"; - if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) + const char* signature = jni::TypeSignature(std::decay_t...)>{}(); + if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, signature)) { LocalRefMapType localRefs; jfloatArray array = @@ -204,12 +231,12 @@ class CC_DLL JniHelper @return address of JniMethodInfo if there are proper JniMethodInfo; otherwise nullptr. */ template - static int* callStaticIntArrayMethod(const std::string& className, const std::string& methodName, Ts... xs) + static int* callStaticIntArrayMethod(const char* className, const char* methodName, Ts&&... xs) { static int ret[32]; cocos2d::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")[I"; - if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) + const char* signature = jni::TypeSignature(std::decay_t...)>{}(); + if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, signature)) { LocalRefMapType localRefs; jintArray array = @@ -240,12 +267,12 @@ class CC_DLL JniHelper @return JniMethodInfo of Vec3 type if there are proper JniMethodInfo; otherwise Vec3(0, 0, 0). */ template - static Vec3 callStaticVec3Method(const std::string& className, const std::string& methodName, Ts... xs) + static Vec3 callStaticVec3Method(const char* className, const char* methodName, Ts&&... xs) { Vec3 ret; cocos2d::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")[F"; - if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) + const char* signature = jni::TypeSignature(std::decay_t...)>{}(); + if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, signature)) { LocalRefMapType localRefs; jfloatArray array = @@ -274,12 +301,12 @@ class CC_DLL JniHelper @return value from Java static double method if there are proper JniMethodInfo; otherwise 0. */ template - static double callStaticDoubleMethod(const std::string& className, const std::string& methodName, Ts... xs) + static double callStaticDoubleMethod(const char* className, const char* methodName, Ts&&... xs) { jdouble ret = 0.0; cocos2d::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")D"; - if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) + const char* signature = jni::TypeSignature...)>{}(); + if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, signature)) { LocalRefMapType localRefs; ret = t.env->CallStaticDoubleMethod(t.classID, t.methodID, convert(localRefs, t, xs)...); @@ -298,13 +325,13 @@ class CC_DLL JniHelper @return JniMethodInfo of string type if there are proper JniMethodInfo; otherwise empty string. */ template - static std::string callStaticStringMethod(const std::string& className, const std::string& methodName, Ts... xs) + static std::string callStaticStringMethod(const char* className, const char* methodName, Ts&&... xs) { std::string ret; cocos2d::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")Ljava/lang/String;"; - if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) + const char* signature = jni::TypeSignature...)>{}(); + if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, signature)) { LocalRefMapType localRefs; jstring jret = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(localRefs, t, xs)...); @@ -334,6 +361,8 @@ class CC_DLL JniHelper static jstring convert(LocalRefMapType& localRefs, cocos2d::JniMethodInfo& t, const char* x); + static jstring convert(LocalRefMapType& localRefs, cocos2d::JniMethodInfo& t, std::string_view x); + static jstring convert(LocalRefMapType& localRefs, cocos2d::JniMethodInfo& t, const std::string& x); inline static jint convert(LocalRefMapType&, cocos2d::JniMethodInfo&, int32_t value) @@ -377,41 +406,7 @@ class CC_DLL JniHelper static void deleteLocalRefs(JNIEnv* env, LocalRefMapType& localRefs); - static std::string getJNISignature() { return ""; } - - static std::string getJNISignature(bool) { return "Z"; } - - static std::string getJNISignature(char) { return "C"; } - - static std::string getJNISignature(short) { return "S"; } - - static std::string getJNISignature(int) { return "I"; } - - static std::string getJNISignature(long) { return "J"; } - - static std::string getJNISignature(float) { return "F"; } - - static std::string getJNISignature(double) { return "D"; } - - static std::string getJNISignature(const char*) { return "Ljava/lang/String;"; } - - static std::string getJNISignature(const std::string&) { return "Ljava/lang/String;"; } - - template - static std::string getJNISignature(T x) - { - // This template should never be instantiated - static_assert(sizeof(x) == 0, "Unsupported argument type"); - return ""; - } - - template - static std::string getJNISignature(T x, Ts... xs) - { - return getJNISignature(x) + getJNISignature(xs...); - } - - static void reportError(const std::string& className, const std::string& methodName, const std::string& signature); + static void reportError(const char* className, const char* methodName, const char* signature); }; NS_CC_END diff --git a/cocos/platform/apple/CCDevice-apple.mm b/cocos/platform/apple/CCDevice-apple.mm index e4a72afd2f0b..fff35eb1bbb4 100644 --- a/cocos/platform/apple/CCDevice-apple.mm +++ b/cocos/platform/apple/CCDevice-apple.mm @@ -2,19 +2,19 @@ Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -29,51 +29,56 @@ of this software and associated documentation files (the "Software"), to deal #if CC_TARGET_PLATFORM == CC_PLATFORM_MAC -#include -#include -#include +# include +# include +# include #elif CC_TARGET_PLATFORM == CC_PLATFORM_IOS -#import +# import #endif #include "base/ccTypes.h" #include "platform/apple/CCDevice-apple.h" -namespace FontUtils { - NSMutableParagraphStyle* _calculateParagraphStyle(bool enableWrap, int overflow) - { - NSMutableParagraphStyle* paragraphStyle = [[[NSMutableParagraphStyle alloc] init] autorelease]; - paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping; - return paragraphStyle; - } - - NSTextAlignment _calculateTextAlignment(cocos2d::Device::TextAlign align) - { - unsigned uHoriFlag = (int)align & 0x0f; - NSTextAlignment nsAlign = (2 == uHoriFlag) ? NSTextAlignmentRight - : (3 == uHoriFlag) ? NSTextAlignmentCenter - : NSTextAlignmentLeft; - - return nsAlign; - } - +namespace FontUtils +{ +NSMutableParagraphStyle* _calculateParagraphStyle(bool enableWrap, int overflow) +{ + NSMutableParagraphStyle* paragraphStyle = [[[NSMutableParagraphStyle alloc] init] autorelease]; + paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping; + return paragraphStyle; +} + +NSTextAlignment _calculateTextAlignment(cocos2d::Device::TextAlign align) +{ + unsigned uHoriFlag = (int)align & 0x0f; + NSTextAlignment nsAlign = (2 == uHoriFlag) ? NSTextAlignmentRight + : (3 == uHoriFlag) ? NSTextAlignmentCenter + : NSTextAlignmentLeft; - - CGFloat _calculateTextDrawStartWidth(cocos2d::Device::TextAlign align, CGSize realDimensions, CGSize dimensions) + return nsAlign; +} + +CGFloat _calculateTextDrawStartWidth(cocos2d::Device::TextAlign align, CGSize realDimensions, CGSize dimensions) +{ + CGFloat xPadding = 0; + unsigned uHoriFlag = (int)align & 0x0f; + switch (uHoriFlag) { - CGFloat xPadding = 0; - unsigned uHoriFlag = (int)align & 0x0f; - switch (uHoriFlag) { - //center - case 3: xPadding = (dimensions.width - realDimensions.width) / 2.0f; break; - //right - case 2: xPadding = dimensions.width - realDimensions.width; break; - default: break; - } - return xPadding; + // center + case 3: + xPadding = (dimensions.width - realDimensions.width) / 2.0f; + break; + // right + case 2: + xPadding = dimensions.width - realDimensions.width; + break; + default: + break; } + return xPadding; +} } diff --git a/cocos/platform/apple/CCFileUtils-apple.h b/cocos/platform/apple/CCFileUtils-apple.h index 8eff83505aea..14a3fb62e41f 100644 --- a/cocos/platform/apple/CCFileUtils-apple.h +++ b/cocos/platform/apple/CCFileUtils-apple.h @@ -51,21 +51,21 @@ class CC_DLL FileUtilsApple : public FileUtils /* override functions */ virtual std::string getWritablePath() const override; virtual std::string getNativeWritableAbsolutePath() const override; - virtual std::string getFullPathForFilenameWithinDirectory(const std::string& directory, - const std::string& filename) const override; + virtual std::string getFullPathForFilenameWithinDirectory(std::string_view directory, + std::string_view filename) const override; #if CC_FILEUTILS_APPLE_ENABLE_OBJC void setBundle(NSBundle* bundle); #endif - virtual bool createDirectory(const std::string& path) const override; - virtual std::string getPathForDirectory(const std::string& dir, - const std::string& resolutionDiretory, - const std::string& searchPath) const override; + virtual bool createDirectory(std::string_view path) const override; + virtual std::string getPathForDirectory(std::string_view dir, + std::string_view resolutionDiretory, + std::string_view searchPath) const override; private: - virtual bool isFileExistInternal(const std::string& filePath) const override; - virtual bool removeDirectory(const std::string& dirPath) const override; + virtual bool isFileExistInternal(std::string_view filePath) const override; + virtual bool removeDirectory(std::string_view dirPath) const override; struct IMPL; std::unique_ptr pimpl_; diff --git a/cocos/platform/apple/CCFileUtils-apple.mm b/cocos/platform/apple/CCFileUtils-apple.mm index 75dabafb2131..3c4717884ccd 100644 --- a/cocos/platform/apple/CCFileUtils-apple.mm +++ b/cocos/platform/apple/CCFileUtils-apple.mm @@ -36,29 +36,27 @@ of this software and associated documentation files (the "Software"), to deal #include "base/CCDirector.h" #include "platform/CCFileUtils.h" -#define DECLARE_GUARD (void)0 // std::lock_guard mutexGuard(_mutex) +#define DECLARE_GUARD (void)0 // std::lock_guard mutexGuard(_mutex) NS_CC_BEGIN -struct FileUtilsApple::IMPL { - IMPL(NSBundle* bundle):bundle_([NSBundle mainBundle]) {} - void setBundle(NSBundle* bundle) { - bundle_ = bundle; - } - NSBundle* getBundle() const { - return bundle_; - } +struct FileUtilsApple::IMPL +{ + IMPL(NSBundle* bundle) : bundle_([NSBundle mainBundle]) {} + void setBundle(NSBundle* bundle) { bundle_ = bundle; } + NSBundle* getBundle() const { return bundle_; } + private: NSBundle* bundle_; }; -FileUtilsApple::FileUtilsApple() : pimpl_(new IMPL([NSBundle mainBundle])) { -} +FileUtilsApple::FileUtilsApple() : pimpl_(new IMPL([NSBundle mainBundle])) {} FileUtilsApple::~FileUtilsApple() = default; #if CC_FILEUTILS_APPLE_ENABLE_OBJC -void FileUtilsApple::setBundle(NSBundle* bundle) { +void FileUtilsApple::setBundle(NSBundle* bundle) +{ pimpl_->setBundle(bundle); } #endif @@ -72,17 +70,16 @@ void setBundle(NSBundle* bundle) { if (s_sharedFileUtils == nullptr) { s_sharedFileUtils = new FileUtilsApple(); - if(!s_sharedFileUtils->init()) + if (!s_sharedFileUtils->init()) { - delete s_sharedFileUtils; - s_sharedFileUtils = nullptr; - CCLOG("ERROR: Could not init CCFileUtilsApple"); + delete s_sharedFileUtils; + s_sharedFileUtils = nullptr; + CCLOG("ERROR: Could not init CCFileUtilsApple"); } } return s_sharedFileUtils; } - std::string FileUtilsApple::getWritablePath() const { DECLARE_GUARD; @@ -98,14 +95,14 @@ void setBundle(NSBundle* bundle) { } // save to document folder - NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); - NSString *documentsDirectory = [paths objectAtIndex:0]; - std::string strRet = [documentsDirectory UTF8String]; + NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString* documentsDirectory = [paths objectAtIndex:0]; + std::string strRet = [documentsDirectory UTF8String]; strRet.append("/"); return strRet; } -bool FileUtilsApple::isFileExistInternal(const std::string& filePath) const +bool FileUtilsApple::isFileExistInternal(std::string_view filePath) const { if (filePath.empty()) { @@ -121,8 +118,8 @@ void setBundle(NSBundle* bundle) { size_t pos = filePath.find_last_of("/"); if (pos != std::string::npos) { - file = filePath.substr(pos+1); - path = filePath.substr(0, pos+1); + file = filePath.substr(pos + 1); + path = filePath.substr(0, pos + 1); } else { @@ -130,16 +127,18 @@ void setBundle(NSBundle* bundle) { } NSString* fullpath = [pimpl_->getBundle() pathForResource:[NSString stringWithUTF8String:file.c_str()] - ofType:nil - inDirectory:[NSString stringWithUTF8String:path.c_str()]]; - if (fullpath != nil) { + ofType:nil + inDirectory:[NSString stringWithUTF8String:path.c_str()]]; + if (fullpath != nil) + { ret = true; } } else { // Search path is an absolute path. - if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:filePath.c_str()]]) { + if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:filePath.data()]]) + { ret = true; } } @@ -147,18 +146,18 @@ void setBundle(NSBundle* bundle) { return ret; } -static int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) +static int unlink_cb(const char* fpath, const struct stat* sb, int typeflag, struct FTW* ftwbuf) { auto ret = remove(fpath); if (ret) { - log("Fail to remove: %s ",fpath); + log("Fail to remove: %s ", fpath); } return ret; } -bool FileUtilsApple::removeDirectory(const std::string& path) const +bool FileUtilsApple::removeDirectory(std::string_view path) const { if (path.empty()) { @@ -166,78 +165,89 @@ static int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, str return false; } - if (nftw(path.c_str(),unlink_cb, 64, FTW_DEPTH | FTW_PHYS)) + if (nftw(path.data(), unlink_cb, 64, FTW_DEPTH | FTW_PHYS)) return false; else return true; } -std::string FileUtilsApple::getPathForDirectory(const std::string &dir, const std::string &resolutionDiretory, const std::string &searchPath) const +std::string FileUtilsApple::getPathForDirectory(std::string_view dir, + std::string_view resolutionDiretory, + std::string_view searchPath) const { - auto path = searchPath + resolutionDiretory + dir; - - if(!path.empty() && path[path.length() -1] == '/') { + std::string path{searchPath}; + path.append(resolutionDiretory).append(dir); + + if (!path.empty() && path[path.length() - 1] == '/') + { path.erase(path.end() - 1); } - - if(path[0] == '/') + + if (path[0] == '/') { BOOL isDir = false; - if([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:dir.c_str()] - isDirectory:&isDir]) { + if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:dir.data()] isDirectory:&isDir]) + { return isDir ? path : ""; } } else { - NSString *fullpath = [pimpl_->getBundle() pathForResource:[NSString stringWithUTF8String:path.c_str()] + NSString* fullpath = [pimpl_->getBundle() pathForResource:[NSString stringWithUTF8String:path.c_str()] ofType:nil]; - if(fullpath != nil) { + if (fullpath != nil) + { return [fullpath UTF8String]; } } return ""; } - -std::string FileUtilsApple::getFullPathForFilenameWithinDirectory(const std::string& directory, const std::string& filename) const +std::string FileUtilsApple::getFullPathForFilenameWithinDirectory(std::string_view directory, + std::string_view filename) const { if (directory[0] != '/') { - NSString* fullpath = [pimpl_->getBundle() pathForResource:[NSString stringWithUTF8String:filename.c_str()] - ofType:nil - inDirectory:[NSString stringWithUTF8String:directory.c_str()]]; - if (fullpath != nil) { + NSString* fullpath = [pimpl_->getBundle() pathForResource:[NSString stringWithUTF8String:filename.data()] + ofType:nil + inDirectory:[NSString stringWithUTF8String:directory.data()]]; + if (fullpath != nil) + { return [fullpath UTF8String]; } } else { - std::string fullPath = directory+filename; + std::string fullPath{directory}; + fullPath += filename; // Search path is an absolute path. - if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:fullPath.c_str()]]) { + if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:fullPath.c_str()]]) + { return fullPath; } } return ""; } -bool FileUtilsApple::createDirectory(const std::string& path) const +bool FileUtilsApple::createDirectory(std::string_view path) const { CCASSERT(!path.empty(), "Invalid path"); - + if (isDirectoryExist(path)) return true; - + NSError* error; - - bool result = [s_fileManager createDirectoryAtPath:[NSString stringWithUTF8String:path.c_str()] withIntermediateDirectories:YES attributes:nil error:&error]; - - if(!result && error != nil) + + bool result = [s_fileManager createDirectoryAtPath:[NSString stringWithUTF8String:path.data()] + withIntermediateDirectories:YES + attributes:nil + error:&error]; + + if (!result && error != nil) { - CCLOGERROR("Fail to create directory \"%s\": %s", path.c_str(), [error.localizedDescription UTF8String]); + CCLOGERROR("Fail to create directory \"%s\": %s", path.data(), [error.localizedDescription UTF8String]); } - + return result; } diff --git a/cocos/platform/desktop/CCGLViewImpl-desktop.cpp b/cocos/platform/desktop/CCGLViewImpl-desktop.cpp index 7f18509643d9..d3183da959a7 100644 --- a/cocos/platform/desktop/CCGLViewImpl-desktop.cpp +++ b/cocos/platform/desktop/CCGLViewImpl-desktop.cpp @@ -326,12 +326,12 @@ GLViewImpl::~GLViewImpl() #endif } -GLViewImpl* GLViewImpl::create(const std::string& viewName) +GLViewImpl* GLViewImpl::create(std::string_view viewName) { return GLViewImpl::create(viewName, false); } -GLViewImpl* GLViewImpl::create(const std::string& viewName, bool resizable) +GLViewImpl* GLViewImpl::create(std::string_view viewName, bool resizable) { auto ret = new GLViewImpl; if (ret->initWithRect(viewName, Rect(0, 0, 960, 640), 1.0f, resizable)) @@ -343,7 +343,7 @@ GLViewImpl* GLViewImpl::create(const std::string& viewName, bool resizable) return nullptr; } -GLViewImpl* GLViewImpl::createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable) +GLViewImpl* GLViewImpl::createWithRect(std::string_view viewName, Rect rect, float frameZoomFactor, bool resizable) { auto ret = new GLViewImpl; if (ret->initWithRect(viewName, rect, frameZoomFactor, resizable)) @@ -355,7 +355,7 @@ GLViewImpl* GLViewImpl::createWithRect(const std::string& viewName, Rect rect, f return nullptr; } -GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName) +GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName) { auto ret = new GLViewImpl(); if (ret->initWithFullScreen(viewName)) @@ -367,7 +367,7 @@ GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName) return nullptr; } -GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName, +GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName, const GLFWvidmode& videoMode, GLFWmonitor* monitor) { @@ -381,7 +381,7 @@ GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName, return nullptr; } -bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable) +bool GLViewImpl::initWithRect(std::string_view viewName, Rect rect, float frameZoomFactor, bool resizable) { setViewName(viewName); @@ -509,7 +509,7 @@ bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float fram return true; } -bool GLViewImpl::initWithFullScreen(const std::string& viewName) +bool GLViewImpl::initWithFullScreen(std::string_view viewName) { // Create fullscreen window on primary monitor at its current video mode. _monitor = glfwGetPrimaryMonitor(); @@ -520,7 +520,7 @@ bool GLViewImpl::initWithFullScreen(const std::string& viewName) return initWithRect(viewName, Rect(0, 0, (float)videoMode->width, (float)videoMode->height), 1.0f, false); } -bool GLViewImpl::initWithFullscreen(const std::string& viewname, const GLFWvidmode& videoMode, GLFWmonitor* monitor) +bool GLViewImpl::initWithFullscreen(std::string_view viewname, const GLFWvidmode& videoMode, GLFWmonitor* monitor) { // Create fullscreen on specified monitor at the specified video mode. _monitor = monitor; @@ -575,30 +575,29 @@ void GLViewImpl::pollEvents() void GLViewImpl::enableRetina(bool enabled) { // official v4 comment follow sources - // #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) - // _isRetinaEnabled = enabled; - // if (_isRetinaEnabled) - // { - // _retinaFactor = 1; - // } - // else - // { - // _retinaFactor = 2; - // } - // updateFrameSize(); - // #endif + // #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) + // _isRetinaEnabled = enabled; + // if (_isRetinaEnabled) + // { + // _retinaFactor = 1; + // } + // else + // { + // _retinaFactor = 2; + // } + // updateFrameSize(); + // #endif } void GLViewImpl::setIMEKeyboardState(bool /*bOpen*/) {} #if CC_ICON_SET_SUPPORT -void GLViewImpl::setIcon(const std::string& filename) const +void GLViewImpl::setIcon(std::string_view filename) const { - std::vector vec = {filename}; - this->setIcon(vec); + this->setIcon(std::vector{filename}); } -void GLViewImpl::setIcon(const std::vector& filelist) const +void GLViewImpl::setIcon(const std::vector& filelist) const { if (filelist.empty()) return; diff --git a/cocos/platform/desktop/CCGLViewImpl-desktop.h b/cocos/platform/desktop/CCGLViewImpl-desktop.h index f46a0f0ec2a4..74c7d895fec9 100644 --- a/cocos/platform/desktop/CCGLViewImpl-desktop.h +++ b/cocos/platform/desktop/CCGLViewImpl-desktop.h @@ -60,14 +60,14 @@ class CC_DLL GLViewImpl : public GLView friend class GLFWEventHandler; public: - static GLViewImpl* create(const std::string& viewName); - static GLViewImpl* create(const std::string& viewName, bool resizable); - static GLViewImpl* createWithRect(const std::string& viewName, + static GLViewImpl* create(std::string_view viewName); + static GLViewImpl* create(std::string_view viewName, bool resizable); + static GLViewImpl* createWithRect(std::string_view viewName, Rect size, float frameZoomFactor = 1.0f, bool resizable = false); - static GLViewImpl* createWithFullScreen(const std::string& viewName); - static GLViewImpl* createWithFullScreen(const std::string& viewName, + static GLViewImpl* createWithFullScreen(std::string_view viewName); + static GLViewImpl* createWithFullScreen(std::string_view viewName, const GLFWvidmode& videoMode, GLFWmonitor* monitor); @@ -121,8 +121,8 @@ class CC_DLL GLViewImpl : public GLView virtual void setIMEKeyboardState(bool bOpen) override; #if CC_ICON_SET_SUPPORT - virtual void setIcon(const std::string& filename) const override; - virtual void setIcon(const std::vector& filelist) const override; + virtual void setIcon(std::string_view filename) const override; + virtual void setIcon(const std::vector& filelist) const override; virtual void setDefaultIcon() const override; #endif /* CC_ICON_SET_SUPPORT */ @@ -157,9 +157,9 @@ class CC_DLL GLViewImpl : public GLView GLViewImpl(bool initglfw = true); virtual ~GLViewImpl(); - bool initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable); - bool initWithFullScreen(const std::string& viewName); - bool initWithFullscreen(const std::string& viewname, const GLFWvidmode& videoMode, GLFWmonitor* monitor); + bool initWithRect(std::string_view viewName, Rect rect, float frameZoomFactor, bool resizable); + bool initWithFullScreen(std::string_view viewName); + bool initWithFullscreen(std::string_view viewname, const GLFWvidmode& videoMode, GLFWmonitor* monitor); bool loadGL(); diff --git a/cocos/platform/ios/CCApplication-ios.h b/cocos/platform/ios/CCApplication-ios.h index bcced55ac190..d87e7a79bcf2 100644 --- a/cocos/platform/ios/CCApplication-ios.h +++ b/cocos/platform/ios/CCApplication-ios.h @@ -87,7 +87,7 @@ class CC_DLL Application : public ApplicationProtocol @param String with url to open. @return true if the resource located by the URL was successfully opened; otherwise false. */ - virtual bool openURL(const std::string& url) override; + virtual bool openURL(std::string_view url) override; /** @brief This function will be called when the application screen size is changed. diff --git a/cocos/platform/ios/CCApplication-ios.mm b/cocos/platform/ios/CCApplication-ios.mm index fbf2827c29e1..79d3576b03e3 100644 --- a/cocos/platform/ios/CCApplication-ios.mm +++ b/cocos/platform/ios/CCApplication-ios.mm @@ -37,7 +37,7 @@ of this software and associated documentation files (the "Software"), to deal Application::Application() { - CC_ASSERT(! sm_pSharedApplication); + CC_ASSERT(!sm_pSharedApplication); sm_pSharedApplication = this; } @@ -58,7 +58,7 @@ of this software and associated documentation files (the "Software"), to deal void Application::setAnimationInterval(float interval) { - [[CCDirectorCaller sharedDirectorCaller] setAnimationInterval: interval ]; + [[CCDirectorCaller sharedDirectorCaller] setAnimationInterval:interval]; } ///////////////////////////////////////////////////////////////////////////////////////////////// @@ -71,39 +71,39 @@ of this software and associated documentation files (the "Software"), to deal return sm_pSharedApplication; } -const char * Application::getCurrentLanguageCode() +const char* Application::getCurrentLanguageCode() { - static char code[3]={0}; - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - NSArray *languages = [defaults objectForKey:@"AppleLanguages"]; - NSString *currentLanguage = [languages objectAtIndex:0]; + static char code[3] = {0}; + NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; + NSArray* languages = [defaults objectForKey:@"AppleLanguages"]; + NSString* currentLanguage = [languages objectAtIndex:0]; // get the current language code.(such as English is "en", Chinese is "zh" and so on) - NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; - NSString * languageCode = [temp objectForKey:NSLocaleLanguageCode]; + NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; + NSString* languageCode = [temp objectForKey:NSLocaleLanguageCode]; [languageCode getCString:code maxLength:3 encoding:NSASCIIStringEncoding]; - code[2]='\0'; + code[2] = '\0'; return code; } LanguageType Application::getCurrentLanguage() { // get the current language and country config - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - NSArray *languages = [defaults objectForKey:@"AppleLanguages"]; - NSString *currentLanguage = [languages objectAtIndex:0]; + NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; + NSArray* languages = [defaults objectForKey:@"AppleLanguages"]; + NSString* currentLanguage = [languages objectAtIndex:0]; // get the current language code.(such as English is "en", Chinese is "zh" and so on) - NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; - NSString * languageCode = [temp objectForKey:NSLocaleLanguageCode]; + NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; + NSString* languageCode = [temp objectForKey:NSLocaleLanguageCode]; return utils::getLanguageTypeByISO2([languageCode UTF8String]); - } Application::Platform Application::getTargetPlatform() { - if ([UIDevice.currentDevice userInterfaceIdiom] == UIUserInterfaceIdiomPad) // idiom for iOS <= 3.2, otherwise: [UIDevice userInterfaceIdiom] is faster. + if ([UIDevice.currentDevice userInterfaceIdiom] == + UIUserInterfaceIdiomPad) // idiom for iOS <= 3.2, otherwise: [UIDevice userInterfaceIdiom] is faster. { return Platform::OS_IPAD; } @@ -113,21 +113,23 @@ of this software and associated documentation files (the "Software"), to deal } } -std::string Application::getVersion() { +std::string Application::getVersion() +{ NSString* version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]; - if (version) { + if (version) + { return [version UTF8String]; } return ""; } -bool Application::openURL(const std::string &url) +bool Application::openURL(std::string_view url) { - NSString* msg = [NSString stringWithCString:url.c_str() encoding:NSUTF8StringEncoding]; - NSURL* nsUrl = [NSURL URLWithString:msg]; - + NSString* msg = [NSString stringWithCString:url.data() encoding:NSUTF8StringEncoding]; + NSURL* nsUrl = [NSURL URLWithString:msg]; + id application = [UIApplication sharedApplication]; - if ([application respondsToSelector:@selector(openURL:options:completionHandler:)] ) + if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) { [application openURL:nsUrl options:@{} completionHandler:nil]; } @@ -137,8 +139,6 @@ of this software and associated documentation files (the "Software"), to deal } } -void Application::applicationScreenSizeChanged(int newWidth, int newHeight) { - -} +void Application::applicationScreenSizeChanged(int newWidth, int newHeight) {} NS_CC_END diff --git a/cocos/platform/ios/CCCommon-ios.mm b/cocos/platform/ios/CCCommon-ios.mm index 254978be54fb..fb2a462e6364 100644 --- a/cocos/platform/ios/CCCommon-ios.mm +++ b/cocos/platform/ios/CCCommon-ios.mm @@ -36,29 +36,30 @@ of this software and associated documentation files (the "Software"), to deal NS_CC_BEGIN // ios no MessageBox, use log instead -void ccMessageBox(const char * msg, const char * title) +void ccMessageBox(const char* msg, const char* title) { // only enable it on iOS. // FIXME: Implement it for tvOS #if !defined(CC_TARGET_OS_TVOS) - NSString * tmpTitle = (title) ? [NSString stringWithUTF8String : title] : nil; - NSString * tmpMsg = (msg) ? [NSString stringWithUTF8String : msg] : nil; + NSString* tmpTitle = (title) ? [NSString stringWithUTF8String:title] : nil; + NSString* tmpMsg = (msg) ? [NSString stringWithUTF8String:msg] : nil; UIAlertController* alertController = [UIAlertController alertControllerWithTitle:tmpTitle - message:tmpMsg - preferredStyle:UIAlertControllerStyleAlert]; + message:tmpMsg + preferredStyle:UIAlertControllerStyleAlert]; - UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault - handler:^(UIAlertAction * action) {}]; + UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" + style:UIAlertActionStyleDefault + handler:^(UIAlertAction* action){ + }]; [alertController addAction:defaultAction]; auto rootViewController = [UIApplication sharedApplication].windows[0].rootViewController; [rootViewController presentViewController:alertController animated:YES completion:nil]; #endif - } -void LuaLog(const char * format) +void LuaLog(const char* format) { puts(format); } diff --git a/cocos/platform/ios/CCDevice-ios.mm b/cocos/platform/ios/CCDevice-ios.mm index 9b3036fbc858..ae01148a19f8 100644 --- a/cocos/platform/ios/CCDevice-ios.mm +++ b/cocos/platform/ios/CCDevice-ios.mm @@ -34,29 +34,30 @@ of this software and associated documentation files (the "Software"), to deal // Accelerometer #if !defined(CC_TARGET_OS_TVOS) -#import +# import #endif -#import +#import #import // Vibrate #import const float MAX_MEASURE_HEIGHT = 10000; - static NSAttributedString* __attributedStringWithFontSize(NSMutableAttributedString* attributedString, CGFloat fontSize) { { [attributedString beginEditing]; - [attributedString enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, attributedString.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) { - - UIFont* font = value; - font = [font fontWithSize:fontSize]; + [attributedString enumerateAttribute:NSFontAttributeName + inRange:NSMakeRange(0, attributedString.length) + options:0 + usingBlock:^(id value, NSRange range, BOOL* stop) { + UIFont* font = value; + font = [font fontWithSize:fontSize]; - [attributedString removeAttribute:NSFontAttributeName range:range]; - [attributedString addAttribute:NSFontAttributeName value:font range:range]; - }]; + [attributedString removeAttribute:NSFontAttributeName range:range]; + [attributedString addAttribute:NSFontAttributeName value:font range:range]; + }]; [attributedString endEditing]; } @@ -69,97 +70,116 @@ static CGFloat _calculateTextDrawStartHeight(cocos2d::Device::TextAlign align, C float startH = 0; // vertical alignment unsigned int vAlignment = ((int)align >> 4) & 0x0F; - switch (vAlignment) { - //bottom - case 2:startH = dimensions.height - realDimensions.height;break; - //top - case 1:startH = 0;break; - //center - case 3: startH = (dimensions.height - realDimensions.height) / 2;break; - default: - break; + switch (vAlignment) + { + // bottom + case 2: + startH = dimensions.height - realDimensions.height; + break; + // top + case 1: + startH = 0; + break; + // center + case 3: + startH = (dimensions.height - realDimensions.height) / 2; + break; + default: + break; } return startH; } -static CGSize _calculateShrinkedSizeForString(NSAttributedString **str, +static CGSize _calculateShrinkedSizeForString(NSAttributedString** str, id font, CGSize constrainSize, bool enableWrap, int& newFontSize) { CGRect actualSize = CGRectMake(0, 0, constrainSize.width + 1, constrainSize.height + 1); - int fontSize = [font pointSize]; - fontSize = fontSize + 1; + int fontSize = [font pointSize]; + fontSize = fontSize + 1; - if (!enableWrap) { - while (actualSize.size.width > constrainSize.width || - actualSize.size.height > constrainSize.height) { + if (!enableWrap) + { + while (actualSize.size.width > constrainSize.width || actualSize.size.height > constrainSize.height) + { fontSize = fontSize - 1; - if(fontSize < 0) { + if (fontSize < 0) + { actualSize = CGRectMake(0, 0, 0, 0); break; } - NSMutableAttributedString *mutableString = [[*str mutableCopy] autorelease]; - *str = __attributedStringWithFontSize(mutableString, fontSize); + NSMutableAttributedString* mutableString = [[*str mutableCopy] autorelease]; + *str = __attributedStringWithFontSize(mutableString, fontSize); - CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)*str); + CTFramesetterRef framesetter = + CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef) * str); CGSize targetSize = CGSizeMake(MAX_MEASURE_HEIGHT, MAX_MEASURE_HEIGHT); - CGSize fitSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, [(*str) length]), NULL, targetSize, NULL); + CGSize fitSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, [(*str) length]), + NULL, targetSize, NULL); CFRelease(framesetter); - if (fitSize.width == 0 || fitSize.height == 0) { + if (fitSize.width == 0 || fitSize.height == 0) + { continue; } - + actualSize.size = fitSize; - - if (constrainSize.width <= 0) { + + if (constrainSize.width <= 0) + { constrainSize.width = fitSize.width; } - if (constrainSize.height <= 0) { + if (constrainSize.height <= 0) + { constrainSize.height = fitSize.height; } - if (fontSize <= 0) { + if (fontSize <= 0) + { break; } } - } - else { - while (actualSize.size.height > constrainSize.height || - actualSize.size.width > constrainSize.width) { + else + { + while (actualSize.size.height > constrainSize.height || actualSize.size.width > constrainSize.width) + { fontSize = fontSize - 1; - if(fontSize < 0) { + if (fontSize < 0) + { actualSize = CGRectMake(0, 0, 0, 0); break; } - - NSMutableAttributedString *mutableString = [[*str mutableCopy] autorelease]; - *str = __attributedStringWithFontSize(mutableString, fontSize); - + + NSMutableAttributedString* mutableString = [[*str mutableCopy] autorelease]; + *str = __attributedStringWithFontSize(mutableString, fontSize); + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake(constrainSize.width, MAX_MEASURE_HEIGHT) - options:(NSStringDrawingUsesLineFragmentOrigin) - context:nil].size; + options:(NSStringDrawingUsesLineFragmentOrigin)context:nil] + .size; - if (fitSize.width == 0 || fitSize.height == 0) { + if (fitSize.width == 0 || fitSize.height == 0) + { continue; } - + actualSize.size = fitSize; - - if (constrainSize.height <= 0) { + + if (constrainSize.height <= 0) + { constrainSize.height = fitSize.height; } - if (constrainSize.width <= 0) { + if (constrainSize.width <= 0) + { constrainSize.width = fitSize.width; } - if (fontSize <= 0) { + if (fontSize <= 0) + { break; } } - } newFontSize = fontSize; @@ -170,16 +190,15 @@ static CGSize _calculateShrinkedSizeForString(NSAttributedString **str, #define SENSOR_DELAY_GAME 0.02 #if !defined(CC_TARGET_OS_TVOS) -@interface CCAccelerometerDispatcher : NSObject -{ - cocos2d::Acceleration *_acceleration; - CMMotionManager *_motionManager; +@interface CCAccelerometerDispatcher : NSObject { + cocos2d::Acceleration* _acceleration; + CMMotionManager* _motionManager; } -+ (id) sharedAccelerometerDispatcher; -- (id) init; -- (void) setAccelerometerEnabled: (bool) isEnabled; -- (void) setAccelerometerInterval:(float) interval; ++ (id)sharedAccelerometerDispatcher; +- (id)init; +- (void)setAccelerometerEnabled:(bool)isEnabled; +- (void)setAccelerometerInterval:(float)interval; @end @@ -187,26 +206,28 @@ @implementation CCAccelerometerDispatcher static CCAccelerometerDispatcher* s_pAccelerometerDispatcher; -+ (id) sharedAccelerometerDispatcher ++ (id)sharedAccelerometerDispatcher { - if (s_pAccelerometerDispatcher == nil) { + if (s_pAccelerometerDispatcher == nil) + { s_pAccelerometerDispatcher = [[self alloc] init]; } return s_pAccelerometerDispatcher; } -- (id) init +- (id)init { - if( (self = [super init]) ) { - _acceleration = new cocos2d::Acceleration(); - _motionManager = [[CMMotionManager alloc] init]; + if ((self = [super init])) + { + _acceleration = new cocos2d::Acceleration(); + _motionManager = [[CMMotionManager alloc] init]; _motionManager.accelerometerUpdateInterval = SENSOR_DELAY_GAME; } return self; } -- (void) dealloc +- (void)dealloc { s_pAccelerometerDispatcher = nullptr; delete _acceleration; @@ -214,13 +235,14 @@ - (void) dealloc [super dealloc]; } -- (void) setAccelerometerEnabled: (bool) isEnabled +- (void)setAccelerometerEnabled:(bool)isEnabled { if (isEnabled) { - [_motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) { - [self accelerometer:accelerometerData]; - }]; + [_motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] + withHandler:^(CMAccelerometerData* accelerometerData, NSError* error) { + [self accelerometer:accelerometerData]; + }]; } else { @@ -228,16 +250,16 @@ - (void) setAccelerometerEnabled: (bool) isEnabled } } --(void) setAccelerometerInterval:(float)interval +- (void)setAccelerometerInterval:(float)interval { _motionManager.accelerometerUpdateInterval = interval; } -- (void)accelerometer:(CMAccelerometerData *)accelerometerData +- (void)accelerometer:(CMAccelerometerData*)accelerometerData { - _acceleration->x = accelerometerData.acceleration.x; - _acceleration->y = accelerometerData.acceleration.y; - _acceleration->z = accelerometerData.acceleration.z; + _acceleration->x = accelerometerData.acceleration.x; + _acceleration->y = accelerometerData.acceleration.y; + _acceleration->z = accelerometerData.acceleration.z; _acceleration->timestamp = accelerometerData.timestamp; double tmp = _acceleration->x; @@ -251,28 +273,28 @@ - (void)accelerometer:(CMAccelerometerData *)accelerometerData // Fallback on earlier versions orientation = [[UIApplication sharedApplication] statusBarOrientation]; } - + switch (orientation) { - case UIInterfaceOrientationLandscapeRight: - _acceleration->x = -_acceleration->y; - _acceleration->y = tmp; - break; - - case UIInterfaceOrientationLandscapeLeft: - _acceleration->x = _acceleration->y; - _acceleration->y = -tmp; - break; - - case UIInterfaceOrientationPortraitUpsideDown: - _acceleration->x = -_acceleration->y; - _acceleration->y = -tmp; - break; - - case UIInterfaceOrientationPortrait: - break; - default: - NSAssert(false, @"unknown orientation"); + case UIInterfaceOrientationLandscapeRight: + _acceleration->x = -_acceleration->y; + _acceleration->y = tmp; + break; + + case UIInterfaceOrientationLandscapeLeft: + _acceleration->x = _acceleration->y; + _acceleration->y = -tmp; + break; + + case UIInterfaceOrientationPortraitUpsideDown: + _acceleration->x = -_acceleration->y; + _acceleration->y = -tmp; + break; + + case UIInterfaceOrientationPortrait: + break; + default: + NSAssert(false, @"unknown orientation"); } cocos2d::EventAcceleration event(*_acceleration); @@ -280,8 +302,7 @@ - (void)accelerometer:(CMAccelerometerData *)accelerometerData dispatcher->dispatchEvent(&event); } @end -#endif // !defined(CC_TARGET_OS_TVOS) - +#endif // !defined(CC_TARGET_OS_TVOS) // @@ -295,23 +316,28 @@ - (void)accelerometer:(CMAccelerometerData *)accelerometerData { float scale = 1.0f; - if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) { + if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) + { scale = [[UIScreen mainScreen] scale]; } UIUserInterfaceIdiom userInterfaceIdiom = [UIDevice.currentDevice userInterfaceIdiom]; - if (userInterfaceIdiom == UIUserInterfaceIdiomPad) { + if (userInterfaceIdiom == UIUserInterfaceIdiomPad) + { dpi = 132 * scale; - } else if (userInterfaceIdiom == UIUserInterfaceIdiomPhone) { + } + else if (userInterfaceIdiom == UIUserInterfaceIdiomPhone) + { dpi = 163 * scale; - } else { + } + else + { dpi = 160 * scale; } } return dpi; } - void Device::setAccelerometerEnabled(bool isEnabled) { #if !defined(CC_TARGET_OS_TVOS) @@ -330,67 +356,74 @@ - (void)accelerometer:(CMAccelerometerData *)accelerometerData { unsigned int height; unsigned int width; - bool isPremultipliedAlpha; - bool hasShadow; - CGSize shadowOffset; - float shadowBlur; - float shadowOpacity; - bool hasStroke; - float strokeColorR; - float strokeColorG; - float strokeColorB; - float strokeColorA; - float strokeSize; - float tintColorR; - float tintColorG; - float tintColorB; - float tintColorA; - - unsigned char* data; + bool isPremultipliedAlpha; + bool hasShadow; + CGSize shadowOffset; + float shadowBlur; + float shadowOpacity; + bool hasStroke; + float strokeColorR; + float strokeColorG; + float strokeColorB; + float strokeColorA; + float strokeSize; + float tintColorR; + float tintColorG; + float tintColorB; + float tintColorA; + + unsigned char* data; } tImageInfo; -static CGSize _calculateStringSize(NSAttributedString *str, id font, CGSize *constrainSize, bool enableWrap, int overflow) +static CGSize _calculateStringSize(NSAttributedString* str, + id font, + CGSize* constrainSize, + bool enableWrap, + int overflow) { CGSize textRect = CGSizeZero; - textRect.width = constrainSize->width > 0 ? constrainSize->width - : MAX_MEASURE_HEIGHT; - textRect.height = constrainSize->height > 0 ? constrainSize->height - : MAX_MEASURE_HEIGHT; - - if (overflow == 1) { - if(!enableWrap) { - textRect.width = MAX_MEASURE_HEIGHT; + textRect.width = constrainSize->width > 0 ? constrainSize->width : MAX_MEASURE_HEIGHT; + textRect.height = constrainSize->height > 0 ? constrainSize->height : MAX_MEASURE_HEIGHT; + + if (overflow == 1) + { + if (!enableWrap) + { + textRect.width = MAX_MEASURE_HEIGHT; textRect.height = MAX_MEASURE_HEIGHT; - } else { + } + else + { textRect.height = MAX_MEASURE_HEIGHT; } } CGSize dim; dim = [str boundingRectWithSize:CGSizeMake(textRect.width, textRect.height) - options:(NSStringDrawingUsesLineFragmentOrigin) - context:nil].size; + options:(NSStringDrawingUsesLineFragmentOrigin)context:nil] + .size; - dim.width = ceilf(dim.width); + dim.width = ceilf(dim.width); dim.height = ceilf(dim.height); return dim; } -static id _createSystemFont( const char * fontName, int size) +static id _createSystemFont(const char* fontName, int size) { - NSString * fntName = [NSString stringWithUTF8String:fontName]; - // On iOS custom fonts must be listed beforehand in the App info.plist (in order to be usable) and referenced only the by the font family name itself when - // calling [UIFont fontWithName]. Therefore even if the developer adds 'SomeFont.ttf' or 'fonts/SomeFont.ttf' to the App .plist, the font must - // be referenced as 'SomeFont' when calling [UIFont fontWithName]. Hence we strip out the folder path components and the extension here in order to get just - // the font family name itself. This stripping step is required especially for references to user fonts stored in CCB files; CCB files appear to store - // the '.ttf' extensions when referring to custom fonts. + NSString* fntName = [NSString stringWithUTF8String:fontName]; + // On iOS custom fonts must be listed beforehand in the App info.plist (in order to be usable) and referenced only + // the by the font family name itself when calling [UIFont fontWithName]. Therefore even if the developer adds + // 'SomeFont.ttf' or 'fonts/SomeFont.ttf' to the App .plist, the font must be referenced as 'SomeFont' when calling + // [UIFont fontWithName]. Hence we strip out the folder path components and the extension here in order to get just + // the font family name itself. This stripping step is required especially for references to user fonts stored in + // CCB files; CCB files appear to store the '.ttf' extensions when referring to custom fonts. fntName = [[fntName lastPathComponent] stringByDeletingPathExtension]; - + // create the font id font = [UIFont fontWithName:fntName size:size]; - + if (!font) { font = [UIFont systemFontOfSize:size]; @@ -398,86 +431,89 @@ static id _createSystemFont( const char * fontName, int size) return font; } -static bool _initWithString(const char * text, cocos2d::Device::TextAlign align, const char * fontName, int size, tImageInfo* info, bool enableWrap, int overflow) +static bool _initWithString(const char* text, + cocos2d::Device::TextAlign align, + const char* fontName, + int size, + tImageInfo* info, + bool enableWrap, + int overflow) { bool bRet = false; do { - CC_BREAK_IF(! text || ! info); + CC_BREAK_IF(!text || !info); id font = _createSystemFont(fontName, size); - - CC_BREAK_IF(! font); - - NSString * str = [NSString stringWithUTF8String:text]; + + CC_BREAK_IF(!font); + + NSString* str = [NSString stringWithUTF8String:text]; CC_BREAK_IF(!str); CGSize dimensions; - dimensions.width = info->width; - dimensions.height = info->height; + dimensions.width = info->width; + dimensions.height = info->height; - NSTextAlignment nsAlign = FontUtils::_calculateTextAlignment(align); + NSTextAlignment nsAlign = FontUtils::_calculateTextAlignment(align); NSMutableParagraphStyle* paragraphStyle = FontUtils::_calculateParagraphStyle(enableWrap, overflow); - paragraphStyle.alignment = nsAlign; + paragraphStyle.alignment = nsAlign; // measure text size with specified font and determine the rectangle to draw text in - UIColor *foregroundColor = [UIColor colorWithRed:info->tintColorR - green:info->tintColorG - blue:info->tintColorB - alpha:info->tintColorA]; + UIColor* foregroundColor = [UIColor colorWithRed:info->tintColorR + green:info->tintColorG + blue:info->tintColorB + alpha:info->tintColorA]; // adjust text rect according to overflow - NSMutableDictionary* tokenAttributesDict = [NSMutableDictionary dictionaryWithObjectsAndKeys: - foregroundColor,NSForegroundColorAttributeName, - font, NSFontAttributeName, - paragraphStyle, NSParagraphStyleAttributeName, nil]; + NSMutableDictionary* tokenAttributesDict = [NSMutableDictionary + dictionaryWithObjectsAndKeys:foregroundColor, NSForegroundColorAttributeName, font, NSFontAttributeName, + paragraphStyle, NSParagraphStyleAttributeName, nil]; - NSAttributedString *stringWithAttributes =[[[NSAttributedString alloc] initWithString:str - attributes:tokenAttributesDict] autorelease]; + NSAttributedString* stringWithAttributes = + [[[NSAttributedString alloc] initWithString:str attributes:tokenAttributesDict] autorelease]; int shrinkFontSize = size; CGSize realDimensions; - if (overflow == 2) { - realDimensions = _calculateShrinkedSizeForString(&stringWithAttributes, font, dimensions, enableWrap, shrinkFontSize); - } else { + if (overflow == 2) + { + realDimensions = + _calculateShrinkedSizeForString(&stringWithAttributes, font, dimensions, enableWrap, shrinkFontSize); + } + else + { realDimensions = _calculateStringSize(stringWithAttributes, font, &dimensions, enableWrap, overflow); } - CC_BREAK_IF(realDimensions.width <= 0 || realDimensions.height <= 0); - if (dimensions.width <= 0) { + if (dimensions.width <= 0) + { dimensions.width = realDimensions.width; } - if (dimensions.height <= 0) { + if (dimensions.height <= 0) + { dimensions.height = realDimensions.height; } // compute start point CGFloat yPadding = _calculateTextDrawStartHeight(align, realDimensions, dimensions); CGFloat xPadding = FontUtils::_calculateTextDrawStartWidth(align, realDimensions, dimensions); - + NSInteger POTWide = dimensions.width; NSInteger POTHigh = dimensions.height; - - CGRect textRect = CGRectMake(xPadding, yPadding, - realDimensions.width, realDimensions.height); + CGRect textRect = CGRectMake(xPadding, yPadding, realDimensions.width, realDimensions.height); NSUInteger textureSize = POTWide * POTHigh * 4; - unsigned char* data = (unsigned char*)malloc(sizeof(unsigned char) * textureSize); + unsigned char* data = (unsigned char*)malloc(sizeof(unsigned char) * textureSize); memset(data, 0, textureSize); // draw text - CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); - CGContextRef context = CGBitmapContextCreate(data, - POTWide, - POTHigh, - 8, - POTWide * 4, - colorSpace, - kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGContextRef context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, POTWide * 4, colorSpace, + kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); if (!context) { CGColorSpaceRelease(colorSpace); @@ -486,16 +522,12 @@ static bool _initWithString(const char * text, cocos2d::Device::TextAlign align, } // text color - CGContextSetRGBFillColor(context, - info->tintColorR, - info->tintColorG, - info->tintColorB, - info->tintColorA); + CGContextSetRGBFillColor(context, info->tintColorR, info->tintColorG, info->tintColorB, info->tintColorA); // move Y rendering to the top of the image CGContextTranslateCTM(context, 0.0f, POTHigh); - - //NOTE: NSString draws in UIKit referential i.e. renders upside-down compared to CGBitmapContext referential + + // NOTE: NSString draws in UIKit referential i.e. renders upside-down compared to CGBitmapContext referential CGContextScaleCTM(context, 1.0f, -1.0f); // store the current context UIGraphicsPushContext(context); @@ -506,34 +538,30 @@ static bool _initWithString(const char * text, cocos2d::Device::TextAlign align, CGContextBeginTransparencyLayerWithRect(context, textRect, NULL); - - if ( info->hasStroke ) + if (info->hasStroke) { CGContextSetTextDrawingMode(context, kCGTextStroke); - UIColor *strokeColor = [UIColor colorWithRed:info->strokeColorR - green:info->strokeColorG - blue:info->strokeColorB - alpha:info->strokeColorA]; - - - NSMutableDictionary* tokenAttributesDict2 = [NSMutableDictionary dictionaryWithObjectsAndKeys: - foregroundColor,NSForegroundColorAttributeName, - font, NSFontAttributeName, - paragraphStyle, NSParagraphStyleAttributeName, nil]; - [tokenAttributesDict2 setObject:[NSNumber numberWithFloat: info->strokeSize / shrinkFontSize * 100] + UIColor* strokeColor = [UIColor colorWithRed:info->strokeColorR + green:info->strokeColorG + blue:info->strokeColorB + alpha:info->strokeColorA]; + + NSMutableDictionary* tokenAttributesDict2 = [NSMutableDictionary + dictionaryWithObjectsAndKeys:foregroundColor, NSForegroundColorAttributeName, font, NSFontAttributeName, + paragraphStyle, NSParagraphStyleAttributeName, nil]; + [tokenAttributesDict2 setObject:[NSNumber numberWithFloat:info->strokeSize / shrinkFontSize * 100] forKey:NSStrokeWidthAttributeName]; - [tokenAttributesDict2 setObject:strokeColor forKey:NSStrokeColorAttributeName]; - - NSAttributedString *strokeString =[[[NSAttributedString alloc] initWithString:str - attributes:tokenAttributesDict2] autorelease]; - - if(overflow == 2){ + [tokenAttributesDict2 setObject:strokeColor forKey:NSStrokeColorAttributeName]; + + NSAttributedString* strokeString = + [[[NSAttributedString alloc] initWithString:str attributes:tokenAttributesDict2] autorelease]; + + if (overflow == 2) + { _calculateShrinkedSizeForString(&strokeString, font, dimensions, enableWrap, shrinkFontSize); } - [strokeString drawInRect:textRect]; - } CGContextSetTextDrawingMode(context, kCGTextFill); @@ -548,51 +576,57 @@ static bool _initWithString(const char * text, cocos2d::Device::TextAlign align, // release the context CGContextRelease(context); - + // output params info->data = data; info->isPremultipliedAlpha = true; info->width = static_cast(POTWide); info->height = static_cast(POTHigh); - bRet = true; + bRet = true; } while (0); return bRet; } - -Data Device::getTextureDataForText(const char * text, const FontDefinition& textDefinition, TextAlign align, int &width, int &height, bool& hasPremultipliedAlpha) +Data Device::getTextureDataForText(const char* text, + const FontDefinition& textDefinition, + TextAlign align, + int& width, + int& height, + bool& hasPremultipliedAlpha) { Data ret; - do { - tImageInfo info = {0}; - info.width = textDefinition._dimensions.width; - info.height = textDefinition._dimensions.height; - info.hasShadow = textDefinition._shadow._shadowEnabled; - info.shadowOffset.width = textDefinition._shadow._shadowOffset.width; - info.shadowOffset.height = textDefinition._shadow._shadowOffset.height; - info.shadowBlur = textDefinition._shadow._shadowBlur; - info.shadowOpacity = textDefinition._shadow._shadowOpacity; - info.hasStroke = textDefinition._stroke._strokeEnabled; - info.strokeColorR = textDefinition._stroke._strokeColor.r / 255.0f; - info.strokeColorG = textDefinition._stroke._strokeColor.g / 255.0f; - info.strokeColorB = textDefinition._stroke._strokeColor.b / 255.0f; - info.strokeColorA = textDefinition._stroke._strokeAlpha / 255.0f; - info.strokeSize = textDefinition._stroke._strokeSize; - info.tintColorR = textDefinition._fontFillColor.r / 255.0f; - info.tintColorG = textDefinition._fontFillColor.g / 255.0f; - info.tintColorB = textDefinition._fontFillColor.b / 255.0f; - info.tintColorA = textDefinition._fontAlpha / 255.0f; - - if (! _initWithString(text, align, textDefinition._fontName.c_str(), textDefinition._fontSize, &info, textDefinition._enableWrap, textDefinition._overflow)) + do + { + tImageInfo info = {0}; + info.width = textDefinition._dimensions.width; + info.height = textDefinition._dimensions.height; + info.hasShadow = textDefinition._shadow._shadowEnabled; + info.shadowOffset.width = textDefinition._shadow._shadowOffset.width; + info.shadowOffset.height = textDefinition._shadow._shadowOffset.height; + info.shadowBlur = textDefinition._shadow._shadowBlur; + info.shadowOpacity = textDefinition._shadow._shadowOpacity; + info.hasStroke = textDefinition._stroke._strokeEnabled; + info.strokeColorR = textDefinition._stroke._strokeColor.r / 255.0f; + info.strokeColorG = textDefinition._stroke._strokeColor.g / 255.0f; + info.strokeColorB = textDefinition._stroke._strokeColor.b / 255.0f; + info.strokeColorA = textDefinition._stroke._strokeAlpha / 255.0f; + info.strokeSize = textDefinition._stroke._strokeSize; + info.tintColorR = textDefinition._fontFillColor.r / 255.0f; + info.tintColorG = textDefinition._fontFillColor.g / 255.0f; + info.tintColorB = textDefinition._fontFillColor.b / 255.0f; + info.tintColorA = textDefinition._fontAlpha / 255.0f; + + if (!_initWithString(text, align, textDefinition._fontName.c_str(), textDefinition._fontSize, &info, + textDefinition._enableWrap, textDefinition._overflow)) { break; } height = info.height; - width = info.width; - ret.fastSet(info.data,width * height * 4); + width = info.width; + ret.fastSet(info.data, width * height * 4); hasPremultipliedAlpha = true; } while (0); @@ -605,22 +639,23 @@ static bool _initWithString(const char * text, cocos2d::Device::TextAlign align, } /*! - @brief Only works on iOS devices that support vibration (such as iPhone). Should only be used for important alerts. Use risks rejection in iTunes Store. + @brief Only works on iOS devices that support vibration (such as iPhone). Should only be used for important alerts. Use + risks rejection in iTunes Store. @param duration ignored for iOS */ void Device::vibrate(float duration) { // See http://stackoverflow.com/questions/4724980/making-the-iphone-vibrate // should vibrate no matter it is silient or not - if([[UIDevice currentDevice].model isEqualToString:@"iPhone"]) + if ([[UIDevice currentDevice].model isEqualToString:@"iPhone"]) { - AudioServicesPlaySystemSound (1352); //works ALWAYS as of this post + AudioServicesPlaySystemSound(1352); // works ALWAYS as of this post } else { // Not an iPhone, so doesn't have vibrate // play the less annoying tick noise or one of your own - AudioServicesPlayAlertSound (kSystemSoundID_Vibrate); + AudioServicesPlayAlertSound(kSystemSoundID_Vibrate); } } diff --git a/cocos/platform/ios/CCDirectorCaller-ios.mm b/cocos/platform/ios/CCDirectorCaller-ios.mm index 6b34dd90f105..53c4e249737b 100644 --- a/cocos/platform/ios/CCDirectorCaller-ios.mm +++ b/cocos/platform/ios/CCDirectorCaller-ios.mm @@ -35,50 +35,55 @@ of this software and associated documentation files (the "Software"), to deal static id s_sharedDirectorCaller; -@interface NSObject(CADisplayLink) -+(id) displayLinkWithTarget: (id)arg1 selector:(SEL)arg2; --(void) addToRunLoop: (id)arg1 forMode: (id)arg2; --(void) setFrameInterval: (NSInteger)interval; --(void) invalidate; +@interface NSObject (CADisplayLink) ++ (id)displayLinkWithTarget:(id)arg1 selector:(SEL)arg2; +- (void)addToRunLoop:(id)arg1 forMode:(id)arg2; +- (void)setFrameInterval:(NSInteger)interval; +- (void)invalidate; @end @implementation CCDirectorCaller @synthesize interval; -+(id) sharedDirectorCaller ++ (id)sharedDirectorCaller { if (s_sharedDirectorCaller == nil) { s_sharedDirectorCaller = [[CCDirectorCaller alloc] init]; } - + return s_sharedDirectorCaller; } -+(void) destroy ++ (void)destroy { [s_sharedDirectorCaller stopMainLoop]; [s_sharedDirectorCaller release]; s_sharedDirectorCaller = nil; } - - (instancetype)init { if (self = [super init]) { - isAppActive = [UIApplication sharedApplication].applicationState == UIApplicationStateActive; - NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; - [nc addObserver:self selector:@selector(appDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil]; - [nc addObserver:self selector:@selector(appDidBecomeInactive) name:UIApplicationWillResignActiveNotification object:nil]; - + isAppActive = [UIApplication sharedApplication].applicationState == UIApplicationStateActive; + NSNotificationCenter* nc = [NSNotificationCenter defaultCenter]; + [nc addObserver:self + selector:@selector(appDidBecomeActive) + name:UIApplicationDidBecomeActiveNotification + object:nil]; + [nc addObserver:self + selector:@selector(appDidBecomeInactive) + name:UIApplicationWillResignActiveNotification + object:nil]; + self.interval = 1; } return self; } --(void) dealloc +- (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; [displayLink release]; @@ -100,52 +105,53 @@ - (void)appDidBecomeInactive isAppActive = NO; } --(void) startMainLoop +- (void)startMainLoop { // Director::setAnimationInterval() is called, we should invalidate it first [self stopMainLoop]; - + displayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(doCaller:)]; - [displayLink setFrameInterval: self.interval]; + [displayLink setFrameInterval:self.interval]; [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; } --(void) stopMainLoop +- (void)stopMainLoop { [displayLink invalidate]; displayLink = nil; } --(void) setAnimationInterval:(double)intervalNew +- (void)setAnimationInterval:(double)intervalNew { // Director::setAnimationInterval() is called, we should invalidate it first [self stopMainLoop]; - + self.interval = 60.0 * intervalNew; - + displayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(doCaller:)]; - [displayLink setFrameInterval: self.interval]; + [displayLink setFrameInterval:self.interval]; [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; } - --(void) doCaller: (id) sender + +- (void)doCaller:(id)sender { - if (isAppActive) { + if (isAppActive) + { cocos2d::Director* director = cocos2d::Director::getInstance(); #if defined(CC_USE_GLES) EAGLContext* cocos2dxContext = [(CCEAGLView*)director->getOpenGLView()->getEAGLView() context]; if (cocos2dxContext != [EAGLContext currentContext]) glFlush(); - - [EAGLContext setCurrentContext: cocos2dxContext]; + + [EAGLContext setCurrentContext:cocos2dxContext]; #endif CFTimeInterval dt = ((CADisplayLink*)displayLink).timestamp - lastDisplayTime; - lastDisplayTime = ((CADisplayLink*)displayLink).timestamp; + lastDisplayTime = ((CADisplayLink*)displayLink).timestamp; director->mainLoop(dt); } } --(void)initLastDisplayTime +- (void)initLastDisplayTime { struct mach_timebase_info timeBaseInfo; mach_timebase_info(&timeBaseInfo); diff --git a/cocos/platform/ios/CCEAGLView-ios.mm b/cocos/platform/ios/CCEAGLView-ios.mm index 6cd9b6c270ec..ca1bccdadd3f 100644 --- a/cocos/platform/ios/CCEAGLView-ios.mm +++ b/cocos/platform/ios/CCEAGLView-ios.mm @@ -70,21 +70,21 @@ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE #import "platform/ios/CCInputView-ios.h" #if defined(CC_USE_METAL) -#import -#import "renderer/backend/metal/DeviceMTL.h" -#import "renderer/backend/metal/UtilsMTL.h" +# import +# import "renderer/backend/metal/DeviceMTL.h" +# import "renderer/backend/metal/UtilsMTL.h" #else -#import "platform/ios/CCGLViewImpl-ios.h" -#import "platform/ios/CCES2Renderer-ios.h" -#import "platform/ios/OpenGL_Internal-ios.h" +# import "platform/ios/CCGLViewImpl-ios.h" +# import "platform/ios/CCES2Renderer-ios.h" +# import "platform/ios/OpenGL_Internal-ios.h" #endif -//CLASS IMPLEMENTATIONS: +// CLASS IMPLEMENTATIONS: -#define IOS_MAX_TOUCHES_COUNT 10 +#define IOS_MAX_TOUCHES_COUNT 10 @interface CCEAGLView () -@property (nonatomic) CCInputView* textInputView; +@property(nonatomic) CCInputView* textInputView; @property(nonatomic, readwrite, assign) BOOL isKeyboardShown; @property(nonatomic, copy) NSNotification* keyboardShowNotification; @property(nonatomic, assign) CGRect originalRect; @@ -92,17 +92,17 @@ @interface CCEAGLView () @implementation CCEAGLView -@synthesize surfaceSize=size_; -@synthesize pixelFormat=pixelformat_, depthFormat=depthFormat_; +@synthesize surfaceSize = size_; +@synthesize pixelFormat = pixelformat_, depthFormat = depthFormat_; #if !defined(CC_USE_METAL) -@synthesize context=context_; +@synthesize context = context_; #endif -@synthesize multiSampling=multiSampling_; +@synthesize multiSampling = multiSampling_; @synthesize keyboardShowNotification = keyboardShowNotification_; @synthesize isKeyboardShown; @synthesize originalRect = originalRect_; -+ (Class) layerClass ++ (Class)layerClass { #if defined(CC_USE_METAL) return [CAMetalLayer class]; @@ -111,153 +111,191 @@ + (Class) layerClass #endif } -+ (id) viewWithFrame:(CGRect)frame ++ (id)viewWithFrame:(CGRect)frame { return [[[self alloc] initWithFrame:frame] autorelease]; } -+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format ++ (id)viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format { - return [[[self alloc]initWithFrame:frame pixelFormat:format] autorelease]; + return [[[self alloc] initWithFrame:frame pixelFormat:format] autorelease]; } -+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth ++ (id)viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth { - return [[[self alloc] initWithFrame:frame pixelFormat:format depthFormat:depth preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0] autorelease]; + return [[[self alloc] initWithFrame:frame + pixelFormat:format + depthFormat:depth + preserveBackbuffer:NO + sharegroup:nil + multiSampling:NO + numberOfSamples:0] autorelease]; } -+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)multisampling numberOfSamples:(unsigned int)samples ++ (id)viewWithFrame:(CGRect)frame + pixelFormat:(NSString*)format + depthFormat:(GLuint)depth + preserveBackbuffer:(BOOL)retained + sharegroup:(EAGLSharegroup*)sharegroup + multiSampling:(BOOL)multisampling + numberOfSamples:(unsigned int)samples { - return [[[self alloc]initWithFrame:frame pixelFormat:format depthFormat:depth preserveBackbuffer:retained sharegroup:sharegroup multiSampling:multisampling numberOfSamples:samples] autorelease]; + return [[[self alloc] initWithFrame:frame + pixelFormat:format + depthFormat:depth + preserveBackbuffer:retained + sharegroup:sharegroup + multiSampling:multisampling + numberOfSamples:samples] autorelease]; } -- (id) initWithFrame:(CGRect)frame +- (id)initWithFrame:(CGRect)frame { - return [self initWithFrame:frame pixelFormat:kEAGLColorFormatRGB565 depthFormat:0 preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0]; + return [self initWithFrame:frame + pixelFormat:kEAGLColorFormatRGB565 + depthFormat:0 + preserveBackbuffer:NO + sharegroup:nil + multiSampling:NO + numberOfSamples:0]; } -- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format +- (id)initWithFrame:(CGRect)frame pixelFormat:(NSString*)format { - return [self initWithFrame:frame pixelFormat:format depthFormat:0 preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0]; + return [self initWithFrame:frame + pixelFormat:format + depthFormat:0 + preserveBackbuffer:NO + sharegroup:nil + multiSampling:NO + numberOfSamples:0]; } -- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)sampling numberOfSamples:(unsigned int)nSamples +- (id)initWithFrame:(CGRect)frame + pixelFormat:(NSString*)format + depthFormat:(GLuint)depth + preserveBackbuffer:(BOOL)retained + sharegroup:(EAGLSharegroup*)sharegroup + multiSampling:(BOOL)sampling + numberOfSamples:(unsigned int)nSamples { - if((self = [super initWithFrame:frame])) + if ((self = [super initWithFrame:frame])) { self.textInputView = [[CCInputView alloc] initWithFrame:frame]; - originalRect_ = self.frame; + originalRect_ = self.frame; self.keyboardShowNotification = nil; if ([self respondsToSelector:@selector(setContentScaleFactor:)]) { self.contentScaleFactor = [[UIScreen mainScreen] scale]; } - + #if defined(CC_USE_METAL) id device = MTLCreateSystemDefaultDevice(); if (!device) { - CCLOG("Doesn't support metal."); - return nil; + CCLOG("Doesn't support metal."); + return nil; } - CAMetalLayer* metalLayer = (CAMetalLayer*)[self layer]; - metalLayer.device = device; - metalLayer.pixelFormat = MTLPixelFormatBGRA8Unorm; + CAMetalLayer* metalLayer = (CAMetalLayer*)[self layer]; + metalLayer.device = device; + metalLayer.pixelFormat = MTLPixelFormatBGRA8Unorm; metalLayer.framebufferOnly = YES; cocos2d::backend::DeviceMTL::setCAMetalLayer(metalLayer); #else - pixelformat_ = format; - depthFormat_ = depth; - multiSampling_ = sampling; - requestedSamples_ = nSamples; + pixelformat_ = format; + depthFormat_ = depth; + multiSampling_ = sampling; + requestedSamples_ = nSamples; preserveBackbuffer_ = retained; - if( ! [self setupSurfaceWithSharegroup:sharegroup] ) { + if (![self setupSurfaceWithSharegroup:sharegroup]) + { [self release]; return nil; } #endif } - + return self; } --(id) initWithCoder:(NSCoder *)aDecoder +- (id)initWithCoder:(NSCoder*)aDecoder { - if ( (self = [super initWithCoder:aDecoder]) ) + if ((self = [super initWithCoder:aDecoder])) { self.textInputView = [[CCInputView alloc] initWithCoder:aDecoder]; #if defined(CC_USE_METAL) size_ = [self bounds].size; #else CAEAGLLayer* eaglLayer = (CAEAGLLayer*)[self layer]; - - pixelformat_ = kEAGLColorFormatRGB565; - depthFormat_ = 0; // GL_DEPTH_COMPONENT24_OES; - multiSampling_= NO; + + pixelformat_ = kEAGLColorFormatRGB565; + depthFormat_ = 0; // GL_DEPTH_COMPONENT24_OES; + multiSampling_ = NO; requestedSamples_ = 0; - size_ = [eaglLayer bounds].size; - - if( ! [self setupSurfaceWithSharegroup:nil] ) { + size_ = [eaglLayer bounds].size; + + if (![self setupSurfaceWithSharegroup:nil]) + { [self release]; return nil; } #endif } - + return self; } --(int) getWidth +- (int)getWidth { CGSize bound = [self bounds].size; return (int)bound.width * self.contentScaleFactor; } --(int) getHeight +- (int)getHeight { CGSize bound = [self bounds].size; return (int)bound.height * self.contentScaleFactor; } #if !defined(CC_USE_METAL) --(BOOL) setupSurfaceWithSharegroup:(EAGLSharegroup*)sharegroup +- (BOOL)setupSurfaceWithSharegroup:(EAGLSharegroup*)sharegroup { - CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer; - + CAEAGLLayer* eaglLayer = (CAEAGLLayer*)self.layer; + eaglLayer.opaque = YES; - eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys: - [NSNumber numberWithBool:preserveBackbuffer_], kEAGLDrawablePropertyRetainedBacking, - pixelformat_, kEAGLDrawablePropertyColorFormat, nil]; - - + eaglLayer.drawableProperties = + [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:preserveBackbuffer_], + kEAGLDrawablePropertyRetainedBacking, pixelformat_, + kEAGLDrawablePropertyColorFormat, nil]; + renderer_ = [[CCES2Renderer alloc] initWithDepthFormat:depthFormat_ - withPixelFormat:[self convertPixelFormat:pixelformat_] - withSharegroup:sharegroup - withMultiSampling:multiSampling_ - withNumberOfSamples:requestedSamples_]; - + withPixelFormat:[self convertPixelFormat:pixelformat_] + withSharegroup:sharegroup + withMultiSampling:multiSampling_ + withNumberOfSamples:requestedSamples_]; + NSAssert(renderer_, @"OpenGL ES 2.O is required."); if (!renderer_) return NO; - + context_ = [renderer_ context]; - - #if GL_EXT_discard_framebuffer == 1 - discardFramebufferSupported_ = YES; - #else - discardFramebufferSupported_ = NO; - #endif - + +# if GL_EXT_discard_framebuffer == 1 + discardFramebufferSupported_ = YES; +# else + discardFramebufferSupported_ = NO; +# endif + CHECK_GL_ERROR(); - + return YES; } #endif -- (void) dealloc +- (void)dealloc { - [[NSNotificationCenter defaultCenter] removeObserver:self]; // remove keyboard notification + [[NSNotificationCenter defaultCenter] removeObserver:self]; // remove keyboard notification #if !defined(CC_USE_METAL) [renderer_ release]; #endif @@ -265,29 +303,29 @@ - (void) dealloc [super dealloc]; } -- (void) layoutSubviews +- (void)layoutSubviews { if (!cocos2d::Director::getInstance()->isValid()) return; - + #if defined(CC_USE_METAL) size_ = [self bounds].size; size_.width *= self.contentScaleFactor; size_.height *= self.contentScaleFactor; - cocos2d::backend::UtilsMTL::resizeDefaultAttachmentTexture(size_.width, size_.height); + cocos2d::backend::UtilsMTL::resizeDefaultAttachmentTexture(size_.width, size_.height); #else [renderer_ resizeFromLayer:(CAEAGLLayer*)self.layer]; size_ = [renderer_ backingSize]; // Issue #914 #924 -// Director *director = [Director sharedDirector]; -// [director reshapeProjection:size_]; + // Director *director = [Director sharedDirector]; + // [director reshapeProjection:size_]; cocos2d::Size size; - size.width = size_.width; + size.width = size_.width; size.height = size_.height; - //cocos2d::Director::getInstance()->reshapeProjection(size); + // cocos2d::Director::getInstance()->reshapeProjection(size); #endif - + // Avoid flicker. Issue #350 if ([NSThread isMainThread]) { @@ -296,29 +334,28 @@ - (void) layoutSubviews } #if defined(CC_USE_METAL) -- (void) swapBuffers -{ -} +- (void)swapBuffers +{} #else -- (void) swapBuffers +- (void)swapBuffers { // IMPORTANT: - // - preconditions - // -> context_ MUST be the OpenGL context - // -> renderbuffer_ must be the RENDER BUFFER + // - preconditions + // -> context_ MUST be the OpenGL context + // -> renderbuffer_ must be the RENDER BUFFER + +# ifdef __IPHONE_4_0 -#ifdef __IPHONE_4_0 - if (multiSampling_) { /* Resolve from msaaFramebuffer to resolveFramebuffer */ - //glDisable(GL_SCISSOR_TEST); + // glDisable(GL_SCISSOR_TEST); glBindFramebuffer(GL_READ_FRAMEBUFFER_APPLE, [renderer_ msaaFrameBuffer]); glBindFramebuffer(GL_DRAW_FRAMEBUFFER_APPLE, [renderer_ defaultFrameBuffer]); glResolveMultisampleFramebufferAPPLE(); } - - if(discardFramebufferSupported_) + + if (discardFramebufferSupported_) { if (multiSampling_) { @@ -332,97 +369,98 @@ - (void) swapBuffers GLenum attachments[] = {GL_COLOR_ATTACHMENT0}; glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 1, attachments); } - + glBindRenderbuffer(GL_RENDERBUFFER, [renderer_ colorRenderBuffer]); - } - + // not MSAA - else if (depthFormat_ ) { - GLenum attachments[] = { GL_DEPTH_ATTACHMENT}; + else if (depthFormat_) + { + GLenum attachments[] = {GL_DEPTH_ATTACHMENT}; glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments); } } - -#endif // __IPHONE_4_0 - - if(![context_ presentRenderbuffer:GL_RENDERBUFFER]) - { -// CCLOG(@"cocos2d: Failed to swap renderbuffer in %s\n", __FUNCTION__); - } -#if COCOS2D_DEBUG +# endif // __IPHONE_4_0 + + if (![context_ presentRenderbuffer:GL_RENDERBUFFER]) + { + // CCLOG(@"cocos2d: Failed to swap renderbuffer in %s\n", __FUNCTION__); + } + +# if COCOS2D_DEBUG CHECK_GL_ERROR(); -#endif - +# endif + // We can safely re-bind the framebuffer here, since this will be the // 1st instruction of the new main loop - if( multiSampling_ ) + if (multiSampling_) glBindFramebuffer(GL_FRAMEBUFFER, [renderer_ msaaFrameBuffer]); } -- (unsigned int) convertPixelFormat:(NSString*) pixelFormat +- (unsigned int)convertPixelFormat:(NSString*)pixelFormat { // define the pixel format GLenum pFormat; - - - if([pixelFormat isEqualToString:@"EAGLColorFormat565"]) + + if ([pixelFormat isEqualToString:@"EAGLColorFormat565"]) pFormat = GL_RGB565; else pFormat = GL_RGBA8_OES; - + return pFormat; } #endif #pragma mark CCEAGLView - Point conversion -- (CGPoint) convertPointFromViewToSurface:(CGPoint)point +- (CGPoint)convertPointFromViewToSurface:(CGPoint)point { CGRect bounds = [self bounds]; - + CGPoint ret; ret.x = (point.x - bounds.origin.x) / bounds.size.width * size_.width; - ret.y = (point.y - bounds.origin.y) / bounds.size.height * size_.height; - + ret.y = (point.y - bounds.origin.y) / bounds.size.height * size_.height; + return ret; } -- (CGRect) convertRectFromViewToSurface:(CGRect)rect +- (CGRect)convertRectFromViewToSurface:(CGRect)rect { CGRect bounds = [self bounds]; - + CGRect ret; - ret.origin.x = (rect.origin.x - bounds.origin.x) / bounds.size.width * size_.width; - ret.origin.y = (rect.origin.y - bounds.origin.y) / bounds.size.height * size_.height; - ret.size.width = rect.size.width / bounds.size.width * size_.width; + ret.origin.x = (rect.origin.x - bounds.origin.x) / bounds.size.width * size_.width; + ret.origin.y = (rect.origin.y - bounds.origin.y) / bounds.size.height * size_.height; + ret.size.width = rect.size.width / bounds.size.width * size_.width; ret.size.height = rect.size.height / bounds.size.height * size_.height; - + return ret; } // Pass the touches to the superview #pragma mark CCEAGLView - Touch Delegate -- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event +- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { if (self.isKeyboardShown) [self closeKeyboardOpenedByEditBox]; - + UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0}; - float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; - float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; - + float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; + float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; + int i = 0; - for (UITouch *touch in touches) { - if (i >= IOS_MAX_TOUCHES_COUNT) { + for (UITouch* touch in touches) + { + if (i >= IOS_MAX_TOUCHES_COUNT) + { CCLOG("warning: touches more than 10, should adjust IOS_MAX_TOUCHES_COUNT"); break; } ids[i] = touch; - xs[i] = [touch locationInView: [touch view]].x * self.contentScaleFactor; - ys[i] = [touch locationInView: [touch view]].y * self.contentScaleFactor; + xs[i] = [touch locationInView:[touch view]].x * self.contentScaleFactor; + ys[i] = [touch locationInView:[touch view]].y * self.contentScaleFactor; ++i; } @@ -430,27 +468,30 @@ - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event glview->handleTouchesBegin(i, (intptr_t*)ids, xs, ys); } -- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event +- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event { UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0}; - float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; - float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; - float fs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; - float ms[IOS_MAX_TOUCHES_COUNT] = {0.0f}; - + float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; + float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; + float fs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; + float ms[IOS_MAX_TOUCHES_COUNT] = {0.0f}; + int i = 0; - for (UITouch *touch in touches) { - if (i >= IOS_MAX_TOUCHES_COUNT) { + for (UITouch* touch in touches) + { + if (i >= IOS_MAX_TOUCHES_COUNT) + { CCLOG("warning: touches more than 10, should adjust IOS_MAX_TOUCHES_COUNT"); break; } ids[i] = touch; - xs[i] = [touch locationInView: [touch view]].x * self.contentScaleFactor; - ys[i] = [touch locationInView: [touch view]].y * self.contentScaleFactor; + xs[i] = [touch locationInView:[touch view]].x * self.contentScaleFactor; + ys[i] = [touch locationInView:[touch view]].y * self.contentScaleFactor; #if defined(__IPHONE_9_0) && (__IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0) // running on iOS 9.0 or higher version - if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0f) { + if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0f) + { fs[i] = touch.force; ms[i] = touch.maximumPossibleForce; } @@ -462,45 +503,49 @@ - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event glview->handleTouchesMove(i, (intptr_t*)ids, xs, ys, fs, ms); } -- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event +- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event { UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0}; - float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; - float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; - + float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; + float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; + int i = 0; - for (UITouch *touch in touches) { - if (i >= IOS_MAX_TOUCHES_COUNT) { + for (UITouch* touch in touches) + { + if (i >= IOS_MAX_TOUCHES_COUNT) + { CCLOG("warning: touches more than 10, should adjust IOS_MAX_TOUCHES_COUNT"); break; } ids[i] = touch; - xs[i] = [touch locationInView: [touch view]].x * self.contentScaleFactor; - ys[i] = [touch locationInView: [touch view]].y * self.contentScaleFactor; + xs[i] = [touch locationInView:[touch view]].x * self.contentScaleFactor; + ys[i] = [touch locationInView:[touch view]].y * self.contentScaleFactor; ++i; } auto glview = cocos2d::Director::getInstance()->getOpenGLView(); glview->handleTouchesEnd(i, (intptr_t*)ids, xs, ys); } - -- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event + +- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event { UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0}; - float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; - float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; - + float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; + float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; + int i = 0; - for (UITouch *touch in touches) { - if (i >= IOS_MAX_TOUCHES_COUNT) { + for (UITouch* touch in touches) + { + if (i >= IOS_MAX_TOUCHES_COUNT) + { CCLOG("warning: touches more than 10, should adjust IOS_MAX_TOUCHES_COUNT"); break; } - + ids[i] = touch; - xs[i] = [touch locationInView: [touch view]].x * self.contentScaleFactor; - ys[i] = [touch locationInView: [touch view]].y * self.contentScaleFactor; + xs[i] = [touch locationInView:[touch view]].x * self.contentScaleFactor; + ys[i] = [touch locationInView:[touch view]].y * self.contentScaleFactor; ++i; } @@ -508,83 +553,90 @@ - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event glview->handleTouchesCancel(i, (intptr_t*)ids, xs, ys); } -- (void) showKeyboard +- (void)showKeyboard { [self addSubview:self.textInputView]; [self.textInputView becomeFirstResponder]; } -- (void) hideKeyboard +- (void)hideKeyboard { [self.textInputView resignFirstResponder]; [self.textInputView removeFromSuperview]; } --(void) doAnimationWhenKeyboardMoveWithDuration:(float) duration distance:(float) dis +- (void)doAnimationWhenKeyboardMoveWithDuration:(float)duration distance:(float)dis { [UIView beginAnimations:nil context:nullptr]; - [UIView setAnimationDelegate:self]; - [UIView setAnimationDuration:duration]; - [UIView setAnimationBeginsFromCurrentState:YES]; - - //NSLog(@"[animation] dis = %f, scale = %f \n", dis, cocos2d::GLView::getInstance()->getScaleY()); - - if (dis < 0.0f) dis = 0.0f; - - auto glview = cocos2d::Director::getInstance()->getOpenGLView(); - dis *= glview->getScaleY(); - - dis /= self.contentScaleFactor; - - #if defined(CC_TARGET_OS_TVOS) - self.frame = CGRectMake(originalRect_.origin.x, originalRect_.origin.y - dis, originalRect_.size.width, originalRect_.size.height); - #else - switch (getFixedOrientation([[UIApplication sharedApplication] statusBarOrientation])) - { - case UIInterfaceOrientationPortrait: - self.frame = CGRectMake(originalRect_.origin.x, originalRect_.origin.y - dis, originalRect_.size.width, originalRect_.size.height); - break; - - case UIInterfaceOrientationPortraitUpsideDown: - self.frame = CGRectMake(originalRect_.origin.x, originalRect_.origin.y + dis, originalRect_.size.width, originalRect_.size.height); - break; - - case UIInterfaceOrientationLandscapeLeft: - self.frame = CGRectMake(originalRect_.origin.x - dis, originalRect_.origin.y , originalRect_.size.width, originalRect_.size.height); - break; - - case UIInterfaceOrientationLandscapeRight: - self.frame = CGRectMake(originalRect_.origin.x + dis, originalRect_.origin.y , originalRect_.size.width, originalRect_.size.height); - break; - - default: - break; - } - #endif - - [UIView commitAnimations]; + [UIView setAnimationDelegate:self]; + [UIView setAnimationDuration:duration]; + [UIView setAnimationBeginsFromCurrentState:YES]; + + // NSLog(@"[animation] dis = %f, scale = %f \n", dis, cocos2d::GLView::getInstance()->getScaleY()); + + if (dis < 0.0f) + dis = 0.0f; + + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + dis *= glview->getScaleY(); + + dis /= self.contentScaleFactor; + +#if defined(CC_TARGET_OS_TVOS) + self.frame = CGRectMake(originalRect_.origin.x, originalRect_.origin.y - dis, originalRect_.size.width, + originalRect_.size.height); +#else + switch (getFixedOrientation([[UIApplication sharedApplication] statusBarOrientation])) + { + case UIInterfaceOrientationPortrait: + self.frame = CGRectMake(originalRect_.origin.x, originalRect_.origin.y - dis, originalRect_.size.width, + originalRect_.size.height); + break; + + case UIInterfaceOrientationPortraitUpsideDown: + self.frame = CGRectMake(originalRect_.origin.x, originalRect_.origin.y + dis, originalRect_.size.width, + originalRect_.size.height); + break; + + case UIInterfaceOrientationLandscapeLeft: + self.frame = CGRectMake(originalRect_.origin.x - dis, originalRect_.origin.y, originalRect_.size.width, + originalRect_.size.height); + break; + + case UIInterfaceOrientationLandscapeRight: + self.frame = CGRectMake(originalRect_.origin.x + dis, originalRect_.origin.y, originalRect_.size.width, + originalRect_.size.height); + break; + + default: + break; + } +#endif + + [UIView commitAnimations]; } --(void) doAnimationWhenAnotherEditBeClicked +- (void)doAnimationWhenAnotherEditBeClicked { if (self.keyboardShowNotification != nil) { - [[NSNotificationCenter defaultCenter]postNotification:self.keyboardShowNotification]; + [[NSNotificationCenter defaultCenter] postNotification:self.keyboardShowNotification]; } } #pragma UIKeyboard notification #if !defined(CC_TARGET_OS_TVOS) -namespace { - UIInterfaceOrientation getFixedOrientation(UIInterfaceOrientation statusBarOrientation) +namespace +{ +UIInterfaceOrientation getFixedOrientation(UIInterfaceOrientation statusBarOrientation) +{ + if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) { - if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) - { - statusBarOrientation = UIInterfaceOrientationPortrait; - } - return statusBarOrientation; + statusBarOrientation = UIInterfaceOrientationPortrait; } + return statusBarOrientation; +} } #endif @@ -593,87 +645,89 @@ - (void)didMoveToWindow #if !defined(CC_TARGET_OS_TVOS) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUIKeyboardNotification:) - name:UIKeyboardWillShowNotification object:nil]; + name:UIKeyboardWillShowNotification + object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUIKeyboardNotification:) - name:UIKeyboardDidShowNotification object:nil]; + name:UIKeyboardDidShowNotification + object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUIKeyboardNotification:) - name:UIKeyboardWillHideNotification object:nil]; + name:UIKeyboardWillHideNotification + object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUIKeyboardNotification:) - name:UIKeyboardDidHideNotification object:nil]; + name:UIKeyboardDidHideNotification + object:nil]; #endif } -- (void)onUIKeyboardNotification:(NSNotification *)notif +- (void)onUIKeyboardNotification:(NSNotification*)notif { - NSString * type = notif.name; - + NSString* type = notif.name; + NSDictionary* info = [notif userInfo]; - CGRect begin = [self convertRect: - [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue] - fromView:self]; - CGRect end = [self convertRect: - [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue] - fromView:self]; + CGRect begin = [self convertRect:[[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue] fromView:self]; + CGRect end = [self convertRect:[[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue] fromView:self]; double aniDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; - + CGSize viewSize = self.frame.size; CGFloat tmp; switch (getFixedOrientation([[UIApplication sharedApplication] statusBarOrientation])) { - case UIInterfaceOrientationPortrait: - begin.origin.y = viewSize.height - begin.origin.y - begin.size.height; - end.origin.y = viewSize.height - end.origin.y - end.size.height; - break; - - case UIInterfaceOrientationPortraitUpsideDown: - begin.origin.x = viewSize.width - (begin.origin.x + begin.size.width); - end.origin.x = viewSize.width - (end.origin.x + end.size.width); - break; - - case UIInterfaceOrientationLandscapeLeft: - std::swap(begin.size.width, begin.size.height); - std::swap(end.size.width, end.size.height); - std::swap(viewSize.width, viewSize.height); - - tmp = begin.origin.x; - begin.origin.x = begin.origin.y; - begin.origin.y = viewSize.height - tmp - begin.size.height; - tmp = end.origin.x; - end.origin.x = end.origin.y; - end.origin.y = viewSize.height - tmp - end.size.height; - break; - - case UIInterfaceOrientationLandscapeRight: - std::swap(begin.size.width, begin.size.height); - std::swap(end.size.width, end.size.height); - std::swap(viewSize.width, viewSize.height); - - tmp = begin.origin.x; - begin.origin.x = begin.origin.y; - begin.origin.y = tmp; - tmp = end.origin.x; - end.origin.x = end.origin.y; - end.origin.y = tmp; - break; - - default: - break; + case UIInterfaceOrientationPortrait: + begin.origin.y = viewSize.height - begin.origin.y - begin.size.height; + end.origin.y = viewSize.height - end.origin.y - end.size.height; + break; + + case UIInterfaceOrientationPortraitUpsideDown: + begin.origin.x = viewSize.width - (begin.origin.x + begin.size.width); + end.origin.x = viewSize.width - (end.origin.x + end.size.width); + break; + + case UIInterfaceOrientationLandscapeLeft: + std::swap(begin.size.width, begin.size.height); + std::swap(end.size.width, end.size.height); + std::swap(viewSize.width, viewSize.height); + + tmp = begin.origin.x; + begin.origin.x = begin.origin.y; + begin.origin.y = viewSize.height - tmp - begin.size.height; + tmp = end.origin.x; + end.origin.x = end.origin.y; + end.origin.y = viewSize.height - tmp - end.size.height; + break; + + case UIInterfaceOrientationLandscapeRight: + std::swap(begin.size.width, begin.size.height); + std::swap(end.size.width, end.size.height); + std::swap(viewSize.width, viewSize.height); + + tmp = begin.origin.x; + begin.origin.x = begin.origin.y; + begin.origin.y = tmp; + tmp = end.origin.x; + end.origin.x = end.origin.y; + end.origin.y = tmp; + break; + + default: + break; } - auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); float scaleX = glview->getScaleX(); float scaleY = glview->getScaleY(); - + // Convert to pixel coordinate - begin = CGRectApplyAffineTransform(begin, CGAffineTransformScale(CGAffineTransformIdentity, self.contentScaleFactor, self.contentScaleFactor)); - end = CGRectApplyAffineTransform(end, CGAffineTransformScale(CGAffineTransformIdentity, self.contentScaleFactor, self.contentScaleFactor)); - + begin = CGRectApplyAffineTransform( + begin, CGAffineTransformScale(CGAffineTransformIdentity, self.contentScaleFactor, self.contentScaleFactor)); + end = CGRectApplyAffineTransform( + end, CGAffineTransformScale(CGAffineTransformIdentity, self.contentScaleFactor, self.contentScaleFactor)); + float offestY = glview->getViewPortRect().origin.y; if (offestY < 0.0f) { @@ -681,23 +735,18 @@ - (void)onUIKeyboardNotification:(NSNotification *)notif begin.size.height -= offestY; end.size.height -= offestY; } - + // Convert to design coordinate - begin = CGRectApplyAffineTransform(begin, CGAffineTransformScale(CGAffineTransformIdentity, 1.0f/scaleX, 1.0f/scaleY)); - end = CGRectApplyAffineTransform(end, CGAffineTransformScale(CGAffineTransformIdentity, 1.0f/scaleX, 1.0f/scaleY)); + begin = CGRectApplyAffineTransform(begin, + CGAffineTransformScale(CGAffineTransformIdentity, 1.0f / scaleX, 1.0f / scaleY)); + end = CGRectApplyAffineTransform(end, + CGAffineTransformScale(CGAffineTransformIdentity, 1.0f / scaleX, 1.0f / scaleY)); - cocos2d::IMEKeyboardNotificationInfo notiInfo; - notiInfo.begin = cocos2d::Rect(begin.origin.x, - begin.origin.y, - begin.size.width, - begin.size.height); - notiInfo.end = cocos2d::Rect(end.origin.x, - end.origin.y, - end.size.width, - end.size.height); + notiInfo.begin = cocos2d::Rect(begin.origin.x, begin.origin.y, begin.size.width, begin.size.height); + notiInfo.end = cocos2d::Rect(end.origin.x, end.origin.y, end.size.width, end.size.height); notiInfo.duration = (float)aniDuration; - + cocos2d::IMEDispatcher* dispatcher = cocos2d::IMEDispatcher::sharedDispatcher(); if (UIKeyboardWillShowNotification == type) { @@ -720,14 +769,14 @@ - (void)onUIKeyboardNotification:(NSNotification *)notif } // Close the keyboard opened by EditBox --(void) closeKeyboardOpenedByEditBox +- (void)closeKeyboardOpenedByEditBox { - NSArray *subviews = self.subviews; - - for(UIView* view in subviews) + NSArray* subviews = self.subviews; + + for (UIView* view in subviews) { - if([view isKindOfClass:NSClassFromString(@"UITextView")] || - [view isKindOfClass:NSClassFromString(@"UITextField")]) + if ([view isKindOfClass:NSClassFromString(@"UITextView")] || + [view isKindOfClass:NSClassFromString(@"UITextField")]) { if ([view isFirstResponder]) { diff --git a/cocos/platform/ios/CCES2Renderer-ios.h b/cocos/platform/ios/CCES2Renderer-ios.h index d0ac908bb3cf..7aec434db774 100644 --- a/cocos/platform/ios/CCES2Renderer-ios.h +++ b/cocos/platform/ios/CCES2Renderer-ios.h @@ -37,7 +37,7 @@ # import # import -# import "platform/CCPlatformMacros.h" +//# import "platform/CCPlatformMacros.h" @interface CCES2Renderer : NSObject { // The pixel dimensions of the CAEAGLLayer diff --git a/cocos/platform/ios/CCES2Renderer-ios.m b/cocos/platform/ios/CCES2Renderer-ios.m index c1f04ab98e83..fd49e8f1f459 100644 --- a/cocos/platform/ios/CCES2Renderer-ios.m +++ b/cocos/platform/ios/CCES2Renderer-ios.m @@ -33,7 +33,7 @@ of this software and associated documentation files (the "Software"), to deal #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS #import "platform/ios/CCES2Renderer-ios.h" -#import "platform/CCPlatformMacros.h" +// #import "platform/CCPlatformMacros.h" #import "platform/ios/OpenGL_Internal-ios.h" #if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0 diff --git a/cocos/platform/ios/CCESRenderer-ios.h b/cocos/platform/ios/CCESRenderer-ios.h index 7498b3099170..c21fb928c578 100644 --- a/cocos/platform/ios/CCESRenderer-ios.h +++ b/cocos/platform/ios/CCESRenderer-ios.h @@ -32,7 +32,7 @@ #include "platform/CCPlatformConfig.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS -# include "platform/CCPlatformMacros.h" +// # include "platform/CCPlatformMacros.h" # import # import diff --git a/cocos/platform/ios/CCGLViewImpl-ios.h b/cocos/platform/ios/CCGLViewImpl-ios.h index 0aa8892865cd..f8ab60f75b2b 100644 --- a/cocos/platform/ios/CCGLViewImpl-ios.h +++ b/cocos/platform/ios/CCGLViewImpl-ios.h @@ -40,13 +40,13 @@ class CC_DLL GLViewImpl : public GLView static GLViewImpl* createWithEAGLView(void* eaGLView); /** creates a GLViewImpl with a title name in fullscreen mode */ - static GLViewImpl* create(const std::string& viewName); + static GLViewImpl* create(std::string_view viewName); /** creates a GLViewImpl with a title name, a rect and the zoom factor */ - static GLViewImpl* createWithRect(const std::string& viewName, const Rect& rect, float frameZoomFactor = 1.0f); + static GLViewImpl* createWithRect(std::string_view viewName, const Rect& rect, float frameZoomFactor = 1.0f); /** creates a GLViewImpl with a name in fullscreen mode */ - static GLViewImpl* createWithFullScreen(const std::string& viewName); + static GLViewImpl* createWithFullScreen(std::string_view viewName); static void convertAttrs(); static void* _pixelFormat; @@ -78,8 +78,8 @@ class CC_DLL GLViewImpl : public GLView virtual ~GLViewImpl(); bool initWithEAGLView(void* eaGLView); - bool initWithRect(const std::string& viewName, const Rect& rect, float frameZoomFactor); - bool initWithFullScreen(const std::string& viewName); + bool initWithRect(std::string_view viewName, const Rect& rect, float frameZoomFactor); + bool initWithFullScreen(std::string_view viewName); // the objective-c CCEAGLView instance void* _eaglview; diff --git a/cocos/platform/ios/CCGLViewImpl-ios.mm b/cocos/platform/ios/CCGLViewImpl-ios.mm index 53a1e78194d3..594680a9154b 100644 --- a/cocos/platform/ios/CCGLViewImpl-ios.mm +++ b/cocos/platform/ios/CCGLViewImpl-ios.mm @@ -33,14 +33,15 @@ of this software and associated documentation files (the "Software"), to deal NS_CC_BEGIN -void* GLViewImpl::_pixelFormat = kEAGLColorFormatRGB565; -int GLViewImpl::_depthFormat = GL_DEPTH_COMPONENT16; +void* GLViewImpl::_pixelFormat = kEAGLColorFormatRGB565; +int GLViewImpl::_depthFormat = GL_DEPTH_COMPONENT16; int GLViewImpl::_multisamplingCount = 0; -GLViewImpl* GLViewImpl::createWithEAGLView(void *eaglview) +GLViewImpl* GLViewImpl::createWithEAGLView(void* eaglview) { auto ret = new GLViewImpl; - if(ret->initWithEAGLView(eaglview)) { + if (ret->initWithEAGLView(eaglview)) + { ret->autorelease(); return ret; } @@ -48,10 +49,11 @@ of this software and associated documentation files (the "Software"), to deal return nullptr; } -GLViewImpl* GLViewImpl::create(const std::string& viewName) +GLViewImpl* GLViewImpl::create(std::string_view viewName) { auto ret = new GLViewImpl; - if(ret->initWithFullScreen(viewName)) { + if (ret->initWithFullScreen(viewName)) + { ret->autorelease(); return ret; } @@ -59,10 +61,11 @@ of this software and associated documentation files (the "Software"), to deal return nullptr; } -GLViewImpl* GLViewImpl::createWithRect(const std::string& viewName, const Rect& rect, float frameZoomFactor) +GLViewImpl* GLViewImpl::createWithRect(std::string_view viewName, const Rect& rect, float frameZoomFactor) { auto ret = new GLViewImpl; - if(ret->initWithRect(viewName, rect, frameZoomFactor)) { + if (ret->initWithRect(viewName, rect, frameZoomFactor)) + { ret->autorelease(); return ret; } @@ -70,10 +73,11 @@ of this software and associated documentation files (the "Software"), to deal return nullptr; } -GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName) +GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName) { auto ret = new GLViewImpl(); - if(ret->initWithFullScreen(viewName)) { + if (ret->initWithFullScreen(viewName)) + { ret->autorelease(); return ret; } @@ -83,64 +87,68 @@ of this software and associated documentation files (the "Software"), to deal void GLViewImpl::convertAttrs() { - if(_glContextAttrs.redBits==8 && _glContextAttrs.greenBits==8 && _glContextAttrs.blueBits==8 && _glContextAttrs.alphaBits==8) + if (_glContextAttrs.redBits == 8 && _glContextAttrs.greenBits == 8 && _glContextAttrs.blueBits == 8 && + _glContextAttrs.alphaBits == 8) { _pixelFormat = kEAGLColorFormatRGBA8; - } else if (_glContextAttrs.redBits==5 && _glContextAttrs.greenBits==6 && _glContextAttrs.blueBits==5 && _glContextAttrs.alphaBits==0) + } + else if (_glContextAttrs.redBits == 5 && _glContextAttrs.greenBits == 6 && _glContextAttrs.blueBits == 5 && + _glContextAttrs.alphaBits == 0) { _pixelFormat = kEAGLColorFormatRGB565; - } else + } + else { CCASSERT(0, "Unsupported render buffer pixel format. Using default"); } - if(_glContextAttrs.depthBits==24 && _glContextAttrs.stencilBits==8) + if (_glContextAttrs.depthBits == 24 && _glContextAttrs.stencilBits == 8) { _depthFormat = GL_DEPTH24_STENCIL8_OES; - } else if (_glContextAttrs.depthBits==0 && _glContextAttrs.stencilBits==0) + } + else if (_glContextAttrs.depthBits == 0 && _glContextAttrs.stencilBits == 0) { _depthFormat = 0; - } else + } + else { CCASSERT(0, "Unsupported format for depth and stencil buffers. Using default"); } - + _multisamplingCount = _glContextAttrs.multisamplingCount; } -GLViewImpl::GLViewImpl() -{ -} +GLViewImpl::GLViewImpl() {} GLViewImpl::~GLViewImpl() { - //CCEAGLView *glview = (CCEAGLView*) _eaglview; + // CCEAGLView *glview = (CCEAGLView*) _eaglview; //[glview release]; } -bool GLViewImpl::initWithEAGLView(void *eaglview) +bool GLViewImpl::initWithEAGLView(void* eaglview) { - _eaglview = eaglview; - CCEAGLView *glview = (CCEAGLView*) _eaglview; + _eaglview = eaglview; + CCEAGLView* glview = (CCEAGLView*)_eaglview; _screenSize.width = _designResolutionSize.width = [glview getWidth]; _screenSize.height = _designResolutionSize.height = [glview getHeight]; -// _scaleX = _scaleY = [glview contentScaleFactor]; + // _scaleX = _scaleY = [glview contentScaleFactor]; return true; } -bool GLViewImpl::initWithRect(const std::string& viewName, const Rect& rect, float frameZoomFactor) +bool GLViewImpl::initWithRect(std::string_view viewName, const Rect& rect, float frameZoomFactor) { CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height); convertAttrs(); - CCEAGLView *eaglview = [CCEAGLView viewWithFrame: r - pixelFormat: (NSString*)_pixelFormat - depthFormat: _depthFormat - preserveBackbuffer: NO - sharegroup: nil - multiSampling: NO - numberOfSamples: 0]; + CCEAGLView* eaglview = [CCEAGLView viewWithFrame:r + pixelFormat:(NSString*)_pixelFormat + depthFormat:_depthFormat + preserveBackbuffer:NO + sharegroup:nil + multiSampling:NO + numberOfSamples:0]; // Not available on tvOS #if !defined(CC_TARGET_OS_TVOS) @@ -149,20 +157,20 @@ of this software and associated documentation files (the "Software"), to deal _screenSize.width = _designResolutionSize.width = [eaglview getWidth]; _screenSize.height = _designResolutionSize.height = [eaglview getHeight]; -// _scaleX = _scaleY = [eaglview contentScaleFactor]; + // _scaleX = _scaleY = [eaglview contentScaleFactor]; _eaglview = eaglview; return true; } -bool GLViewImpl::initWithFullScreen(const std::string& viewName) +bool GLViewImpl::initWithFullScreen(std::string_view viewName) { CGRect rect = [[UIScreen mainScreen] bounds]; Rect r; - r.origin.x = rect.origin.x; - r.origin.y = rect.origin.y; - r.size.width = rect.size.width; + r.origin.x = rect.origin.x; + r.origin.y = rect.origin.y; + r.size.width = rect.size.width; r.size.height = rect.size.height; return initWithRect(viewName, r, 1); @@ -175,10 +183,10 @@ of this software and associated documentation files (the "Software"), to deal bool GLViewImpl::setContentScaleFactor(float contentScaleFactor) { - CC_ASSERT(_resolutionPolicy == ResolutionPolicy::UNKNOWN); // cannot enable retina mode + CC_ASSERT(_resolutionPolicy == ResolutionPolicy::UNKNOWN); // cannot enable retina mode _scaleX = _scaleY = contentScaleFactor; - CCEAGLView *eaglview = (CCEAGLView*) _eaglview; + CCEAGLView* eaglview = (CCEAGLView*)_eaglview; [eaglview setNeedsLayout]; return true; @@ -186,11 +194,11 @@ of this software and associated documentation files (the "Software"), to deal float GLViewImpl::getContentScaleFactor() const { - CCEAGLView *eaglview = (CCEAGLView*) _eaglview; + CCEAGLView* eaglview = (CCEAGLView*)_eaglview; float scaleFactor = [eaglview contentScaleFactor]; -// CCASSERT(scaleFactor == _scaleX == _scaleY, "Logic error in GLView::getContentScaleFactor"); + // CCASSERT(scaleFactor == _scaleX == _scaleY, "Logic error in GLView::getContentScaleFactor"); return scaleFactor; } @@ -200,23 +208,22 @@ of this software and associated documentation files (the "Software"), to deal [CCDirectorCaller destroy]; // destroy EAGLView - CCEAGLView *eaglview = (CCEAGLView*) _eaglview; + CCEAGLView* eaglview = (CCEAGLView*)_eaglview; [eaglview removeFromSuperview]; //[eaglview release]; release(); } - void GLViewImpl::swapBuffers() { - CCEAGLView *eaglview = (CCEAGLView*) _eaglview; + CCEAGLView* eaglview = (CCEAGLView*)_eaglview; [eaglview swapBuffers]; } void GLViewImpl::setIMEKeyboardState(bool open) { - CCEAGLView *eaglview = (CCEAGLView*) _eaglview; + CCEAGLView* eaglview = (CCEAGLView*)_eaglview; if (open) { @@ -230,16 +237,16 @@ of this software and associated documentation files (the "Software"), to deal Rect GLViewImpl::getSafeAreaRect() const { - CCEAGLView *eaglview = (CCEAGLView*) _eaglview; + CCEAGLView* eaglview = (CCEAGLView*)_eaglview; #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 float version = [[UIDevice currentDevice].systemVersion floatValue]; if (version >= 11.0f) { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wpartial-availability" +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wpartial-availability" UIEdgeInsets safeAreaInsets = eaglview.safeAreaInsets; -#pragma clang diagnostic pop +# pragma clang diagnostic pop // Multiply contentScaleFactor since safeAreaInsets return points. safeAreaInsets.left *= eaglview.contentScaleFactor; @@ -249,23 +256,23 @@ of this software and associated documentation files (the "Software"), to deal // Get leftBottom and rightTop point in UI coordinates Vec2 leftBottom = Vec2(safeAreaInsets.left, _screenSize.height - safeAreaInsets.bottom); - Vec2 rightTop = Vec2(_screenSize.width - safeAreaInsets.right, safeAreaInsets.top); + Vec2 rightTop = Vec2(_screenSize.width - safeAreaInsets.right, safeAreaInsets.top); // Convert a point from UI coordinates to which in design resolution coordinate. leftBottom.x = (leftBottom.x - _viewPortRect.origin.x) / _scaleX, leftBottom.y = (leftBottom.y - _viewPortRect.origin.y) / _scaleY; - rightTop.x = (rightTop.x - _viewPortRect.origin.x) / _scaleX, - rightTop.y = (rightTop.y - _viewPortRect.origin.y) / _scaleY; + rightTop.x = (rightTop.x - _viewPortRect.origin.x) / _scaleX, + rightTop.y = (rightTop.y - _viewPortRect.origin.y) / _scaleY; // Adjust points to make them inside design resolution leftBottom.x = MAX(leftBottom.x, 0); leftBottom.y = MIN(leftBottom.y, _designResolutionSize.height); - rightTop.x = MIN(rightTop.x, _designResolutionSize.width); - rightTop.y = MAX(rightTop.y, 0); + rightTop.x = MIN(rightTop.x, _designResolutionSize.width); + rightTop.y = MAX(rightTop.y, 0); // Convert to GL coordinates leftBottom = Director::getInstance()->convertToGL(leftBottom); - rightTop = Director::getInstance()->convertToGL(rightTop); + rightTop = Director::getInstance()->convertToGL(rightTop); return Rect(leftBottom.x, leftBottom.y, rightTop.x - leftBottom.x, rightTop.y - leftBottom.y); } diff --git a/cocos/platform/ios/CCImage-ios.mm b/cocos/platform/ios/CCImage-ios.mm index b5b93879989d..372ed56fa131 100644 --- a/cocos/platform/ios/CCImage-ios.mm +++ b/cocos/platform/ios/CCImage-ios.mm @@ -35,15 +35,16 @@ of this software and associated documentation files (the "Software"), to deal NS_CC_BEGIN -bool cocos2d::Image::saveToFile(const std::string& filename, bool isToRGB) +bool cocos2d::Image::saveToFile(std::string_view filename, bool isToRGB) { - //only support for backend::PixelFormat::RGB8 or backend::PixelFormat::RGBA8 uncompressed data + // only support for backend::PixelFormat::RGB8 or backend::PixelFormat::RGBA8 uncompressed data if (isCompressed() || (_pixelFormat != backend::PixelFormat::RGB8 && _pixelFormat != backend::PixelFormat::RGBA8)) { - CCLOG("cocos2d: Image: saveToFile is only support for backend::PixelFormat::RGB8 or backend::PixelFormat::RGBA8 uncompressed data for now"); + CCLOG("cocos2d: Image: saveToFile is only support for backend::PixelFormat::RGB8 or " + "backend::PixelFormat::RGBA8 uncompressed data for now"); return false; } - bool saveToPNG = false; + bool saveToPNG = false; bool needToCopyPixels = false; std::string basename(filename); @@ -52,64 +53,65 @@ of this software and associated documentation files (the "Software"), to deal { saveToPNG = true; } - - int bitsPerComponent = 8; - int bitsPerPixel = hasAlpha() ? 32 : 24; - if ((! saveToPNG) || isToRGB) + + int bitsPerComponent = 8; + int bitsPerPixel = hasAlpha() ? 32 : 24; + if ((!saveToPNG) || isToRGB) { bitsPerPixel = 24; - } - - int bytesPerRow = (bitsPerPixel/8) * _width; + } + + int bytesPerRow = (bitsPerPixel / 8) * _width; int myDataLength = bytesPerRow * _height; - - unsigned char *pixels = _data; - + + unsigned char* pixels = _data; + // The data has alpha channel, and want to save it with an RGB png file, // or want to save as jpg, remove the alpha channel. if (hasAlpha() && bitsPerPixel == 24) { pixels = new unsigned char[myDataLength]; - + for (int i = 0; i < _height; ++i) { for (int j = 0; j < _width; ++j) { - pixels[(i * _width + j) * 3] = _data[(i * _width + j) * 4]; + pixels[(i * _width + j) * 3] = _data[(i * _width + j) * 4]; pixels[(i * _width + j) * 3 + 1] = _data[(i * _width + j) * 4 + 1]; pixels[(i * _width + j) * 3 + 2] = _data[(i * _width + j) * 4 + 2]; } } - + needToCopyPixels = true; } - + // make data provider with data. CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault; - if (saveToPNG && hasAlpha() && (! isToRGB)) + if (saveToPNG && hasAlpha() && (!isToRGB)) { bitmapInfo |= kCGImageAlphaLast; } - CGDataProviderRef provider = CGDataProviderCreateWithData(nullptr, pixels, myDataLength, nullptr); - CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); - CGImageRef iref = CGImageCreate(_width, _height, - bitsPerComponent, bitsPerPixel, bytesPerRow, - colorSpaceRef, bitmapInfo, provider, - nullptr, false, - kCGRenderingIntentDefault); - - UIImage* image = [[UIImage alloc] initWithCGImage:iref]; - - CGImageRelease(iref); + CGDataProviderRef provider = CGDataProviderCreateWithData(nullptr, pixels, myDataLength, nullptr); + CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); + CGImageRef iref = CGImageCreate(_width, _height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, + bitmapInfo, provider, nullptr, false, kCGRenderingIntentDefault); + + UIImage* image = [[UIImage alloc] initWithCGImage:iref]; + + CGImageRelease(iref); CGColorSpaceRelease(colorSpaceRef); CGDataProviderRelease(provider); // NOTE: Prevent memory leak. Requires ARC enabled. - @autoreleasepool { - NSData *data; - if (saveToPNG) { + @autoreleasepool + { + NSData* data; + if (saveToPNG) + { data = UIImagePNGRepresentation(image); - } else { + } + else + { data = UIImageJPEGRepresentation(image, 1.0f); } @@ -121,9 +123,9 @@ of this software and associated documentation files (the "Software"), to deal if (needToCopyPixels) { - delete [] pixels; + delete[] pixels; } - + return true; } diff --git a/cocos/platform/ios/CCInputView-ios.mm b/cocos/platform/ios/CCInputView-ios.mm index 8b131d54f5f9..aea326830e42 100644 --- a/cocos/platform/ios/CCInputView-ios.mm +++ b/cocos/platform/ios/CCInputView-ios.mm @@ -41,27 +41,31 @@ @implementation CCInputView @synthesize tokenizer; @synthesize autocorrectionType; -- (instancetype) initWithFrame:(CGRect)frame { - if (self = [super initWithFrame:frame] ) { - self.myMarkedText = nil; +- (instancetype)initWithFrame:(CGRect)frame +{ + if (self = [super initWithFrame:frame]) + { + self.myMarkedText = nil; self.autocorrectionType = UITextAutocorrectionTypeNo; } - + return self; } -- (void) dealloc { - [[NSNotificationCenter defaultCenter] removeObserver:self]; // remove keyboard notification +- (void)dealloc +{ + [[NSNotificationCenter defaultCenter] removeObserver:self]; // remove keyboard notification [self.myMarkedText release]; [self removeFromSuperview]; [super dealloc]; } -- (BOOL) canBecomeFirstResponder { +- (BOOL)canBecomeFirstResponder +{ return YES; } -- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event +- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { [self resignFirstResponder]; [self removeFromSuperview]; @@ -69,159 +73,190 @@ - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event #pragma TextInput protocol -- (id)inputDelegate { +- (id)inputDelegate +{ return nil; } -- (void)setInputDelegate:(id)inputDelegate { - -} +- (void)setInputDelegate:(id)inputDelegate +{} -- (void)setSelectedTextRange:(UITextRange *)aSelectedTextRange { +- (void)setSelectedTextRange:(UITextRange*)aSelectedTextRange +{ CCLOG("UITextRange:setSelectedTextRange"); } -- (UITextRange *)selectedTextRange { +- (UITextRange*)selectedTextRange +{ return [[[UITextRange alloc] init] autorelease]; } -- (void)deleteBackward { - if (nil != self.myMarkedText) { +- (void)deleteBackward +{ + if (nil != self.myMarkedText) + { [self.myMarkedText release]; self.myMarkedText = nil; } cocos2d::IMEDispatcher::sharedDispatcher()->dispatchDeleteBackward(); } -- (void)insertText:(nonnull NSString *)text { - if (nil != self.myMarkedText) { +- (void)insertText:(nonnull NSString*)text +{ + if (nil != self.myMarkedText) + { [self.myMarkedText release]; self.myMarkedText = nil; } - const char * pszText = [text cStringUsingEncoding:NSUTF8StringEncoding]; + const char* pszText = [text cStringUsingEncoding:NSUTF8StringEncoding]; cocos2d::IMEDispatcher::sharedDispatcher()->dispatchInsertText(pszText, strlen(pszText)); } -- (NSWritingDirection)baseWritingDirectionForPosition:(nonnull UITextPosition *)position inDirection:(UITextStorageDirection)direction { +- (NSWritingDirection)baseWritingDirectionForPosition:(nonnull UITextPosition*)position + inDirection:(UITextStorageDirection)direction +{ CCLOG("baseWritingDirectionForPosition"); return NSWritingDirectionLeftToRight; } -- (CGRect)caretRectForPosition:(nonnull UITextPosition *)position { +- (CGRect)caretRectForPosition:(nonnull UITextPosition*)position +{ CCLOG("caretRectForPosition"); return CGRectZero; } -- (nullable UITextRange *)characterRangeAtPoint:(CGPoint)point { +- (nullable UITextRange*)characterRangeAtPoint:(CGPoint)point +{ CCLOG("characterRangeAtPoint"); return nil; } -- (nullable UITextRange *)characterRangeByExtendingPosition:(nonnull UITextPosition *)position inDirection:(UITextLayoutDirection)direction { +- (nullable UITextRange*)characterRangeByExtendingPosition:(nonnull UITextPosition*)position + inDirection:(UITextLayoutDirection)direction +{ CCLOG("characterRangeByExtendingPosition"); return nil; } -- (nullable UITextPosition *)closestPositionToPoint:(CGPoint)point { +- (nullable UITextPosition*)closestPositionToPoint:(CGPoint)point +{ CCLOG("closestPositionToPoint"); return nil; } -- (nullable UITextPosition *)closestPositionToPoint:(CGPoint)point withinRange:(nonnull UITextRange *)range { +- (nullable UITextPosition*)closestPositionToPoint:(CGPoint)point withinRange:(nonnull UITextRange*)range +{ CCLOG("closestPositionToPoint"); return nil; } -- (NSComparisonResult)comparePosition:(nonnull UITextPosition *)position toPosition:(nonnull UITextPosition *)other { +- (NSComparisonResult)comparePosition:(nonnull UITextPosition*)position toPosition:(nonnull UITextPosition*)other +{ CCLOG("comparePosition"); return (NSComparisonResult)0; } -- (CGRect)firstRectForRange:(nonnull UITextRange *)range { +- (CGRect)firstRectForRange:(nonnull UITextRange*)range +{ CCLOG("firstRectForRange"); return CGRectNull; } -- (NSInteger)offsetFromPosition:(nonnull UITextPosition *)from toPosition:(nonnull UITextPosition *)toPosition { +- (NSInteger)offsetFromPosition:(nonnull UITextPosition*)from toPosition:(nonnull UITextPosition*)toPosition +{ CCLOG("offsetFromPosition"); return 0; } -- (nullable UITextPosition *)positionFromPosition:(nonnull UITextPosition *)position inDirection:(UITextLayoutDirection)direction offset:(NSInteger)offset { +- (nullable UITextPosition*)positionFromPosition:(nonnull UITextPosition*)position + inDirection:(UITextLayoutDirection)direction + offset:(NSInteger)offset +{ CCLOG("positionFromPosition"); return nil; } -- (nullable UITextPosition *)positionFromPosition:(nonnull UITextPosition *)position offset:(NSInteger)offset { +- (nullable UITextPosition*)positionFromPosition:(nonnull UITextPosition*)position offset:(NSInteger)offset +{ CCLOG("positionFromPosition"); return nil; } -- (nullable UITextPosition *)positionWithinRange:(nonnull UITextRange *)range farthestInDirection:(UITextLayoutDirection)direction { +- (nullable UITextPosition*)positionWithinRange:(nonnull UITextRange*)range + farthestInDirection:(UITextLayoutDirection)direction +{ CCLOG("positionWithinRange"); return nil; } -- (void)replaceRange:(nonnull UITextRange *)range withText:(nonnull NSString *)text { - -} +- (void)replaceRange:(nonnull UITextRange*)range withText:(nonnull NSString*)text +{} -- (nonnull NSArray *)selectionRectsForRange:(nonnull UITextRange *)range { +- (nonnull NSArray*)selectionRectsForRange:(nonnull UITextRange*)range +{ CCLOG("selectionRectsForRange"); return nil; } -- (void)setBaseWritingDirection:(NSWritingDirection)writingDirection forRange:(nonnull UITextRange *)range { - -} +- (void)setBaseWritingDirection:(NSWritingDirection)writingDirection forRange:(nonnull UITextRange*)range +{} -- (void)setMarkedText:(nullable NSString *)markedText selectedRange:(NSRange)selectedRange { +- (void)setMarkedText:(nullable NSString*)markedText selectedRange:(NSRange)selectedRange +{ CCLOG("setMarkedText"); - if (markedText == self.myMarkedText) { + if (markedText == self.myMarkedText) + { return; } - if (nil != self.myMarkedText) { + if (nil != self.myMarkedText) + { [self.myMarkedText release]; } self.myMarkedText = markedText; [self.myMarkedText retain]; } -- (UITextRange *)markedTextRange +- (UITextRange*)markedTextRange { CCLOG("markedTextRange"); - if (nil != self.myMarkedText) { + if (nil != self.myMarkedText) + { return [[[UITextRange alloc] init] autorelease]; } - return nil; // Nil if no marked text. + return nil; // Nil if no marked text. } -- (nullable NSString *)textInRange:(nonnull UITextRange *)range { +- (nullable NSString*)textInRange:(nonnull UITextRange*)range +{ CCLOG("textInRange"); - if (nil != self.myMarkedText) { + if (nil != self.myMarkedText) + { return self.myMarkedText; } return nil; } -- (nullable UITextRange *)textRangeFromPosition:(nonnull UITextPosition *)fromPosition toPosition:(nonnull UITextPosition *)toPosition { +- (nullable UITextRange*)textRangeFromPosition:(nonnull UITextPosition*)fromPosition + toPosition:(nonnull UITextPosition*)toPosition +{ CCLOG("textRangeFromPosition"); return nil; } -- (void)unmarkText { +- (void)unmarkText +{ CCLOG("unmarkText"); if (nil == self.myMarkedText) { return; } - const char * pszText = [self.myMarkedText cStringUsingEncoding:NSUTF8StringEncoding]; + const char* pszText = [self.myMarkedText cStringUsingEncoding:NSUTF8StringEncoding]; cocos2d::IMEDispatcher::sharedDispatcher()->dispatchInsertText(pszText, strlen(pszText)); [self.myMarkedText release]; self.myMarkedText = nil; } -- (void)encodeWithCoder:(nonnull NSCoder *)coder { -} +- (void)encodeWithCoder:(nonnull NSCoder*)coder +{} @end diff --git a/cocos/platform/linux/CCApplication-linux.cpp b/cocos/platform/linux/CCApplication-linux.cpp index be903a2dabcf..fa98b686a6d6 100644 --- a/cocos/platform/linux/CCApplication-linux.cpp +++ b/cocos/platform/linux/CCApplication-linux.cpp @@ -110,7 +110,7 @@ void Application::setAnimationInterval(float interval) _animationInterval = interval * 1000.0f; } -void Application::setResourceRootPath(const std::string& rootResDir) +void Application::setResourceRootPath(std::string_view rootResDir) { _resourceRootPath = rootResDir; if (_resourceRootPath[_resourceRootPath.length() - 1] != '/') @@ -123,7 +123,7 @@ void Application::setResourceRootPath(const std::string& rootResDir) pFileUtils->setSearchPaths(searchPaths); } -const std::string& Application::getResourceRootPath() +std::string_view Application::getResourceRootPath() { return _resourceRootPath; } @@ -138,7 +138,7 @@ std::string Application::getVersion() return ""; } -bool Application::openURL(const std::string& url) +bool Application::openURL(std::string_view url) { std::string op = std::string("xdg-open '").append(url).append("'"); return system(op.c_str()) == 0; diff --git a/cocos/platform/linux/CCApplication-linux.h b/cocos/platform/linux/CCApplication-linux.h index 8f40f7ea0044..3d5c05e60217 100644 --- a/cocos/platform/linux/CCApplication-linux.h +++ b/cocos/platform/linux/CCApplication-linux.h @@ -84,19 +84,19 @@ class Application : public ApplicationProtocol @param String with url to open. @return true if the resource located by the URL was successfully opened; otherwise false. */ - virtual bool openURL(const std::string& url) override; + virtual bool openURL(std::string_view url) override; /** * Sets the Resource root path. * @deprecated Please use FileUtils::getInstance()->setSearchPaths() instead. */ - CC_DEPRECATED_ATTRIBUTE void setResourceRootPath(const std::string& rootResDir); + CC_DEPRECATED_ATTRIBUTE void setResourceRootPath(std::string_view rootResDir); /** * Gets the Resource root path. * @deprecated Please use FileUtils::getInstance()->getSearchPaths() instead. */ - CC_DEPRECATED_ATTRIBUTE const std::string& getResourceRootPath(); + CC_DEPRECATED_ATTRIBUTE std::string_view getResourceRootPath(); /** @brief Get target platform diff --git a/cocos/platform/linux/CCFileUtils-linux.cpp b/cocos/platform/linux/CCFileUtils-linux.cpp index 0ec3a38d079f..31ab5ada2e1a 100644 --- a/cocos/platform/linux/CCFileUtils-linux.cpp +++ b/cocos/platform/linux/CCFileUtils-linux.cpp @@ -2,8 +2,9 @@ Copyright (c) 2011 Laschweinski Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. +Copyright (c) 2021 Bytedance Inc. -http://www.cocos2d-x.org +https://adxeproject.github.io Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -115,22 +116,23 @@ std::string FileUtilsLinux::getNativeWritableAbsolutePath() const return _writablePath; } -bool FileUtilsLinux::isFileExistInternal(const std::string& strFilePath) const +bool FileUtilsLinux::isFileExistInternal(std::string_view path) const { DECLARE_GUARD; - if (strFilePath.empty()) + if (path.empty()) { return false; } - std::string strPath = strFilePath; - if (!isAbsolutePath(strPath)) + std::string strPath; + if (!isAbsolutePath(path)) { // Not absolute path, add the default root path at the beginning. - strPath.insert(0, _defaultResRootPath); + strPath.assign(_defaultResRootPath).append(path); + path = strPath; } struct stat sts; - return (stat(strPath.c_str(), &sts) == 0) && S_ISREG(sts.st_mode); + return (stat(path.data(), &sts) == 0) && S_ISREG(sts.st_mode); } NS_CC_END diff --git a/cocos/platform/linux/CCFileUtils-linux.h b/cocos/platform/linux/CCFileUtils-linux.h index 258ac96d99ac..1dc54ec21311 100644 --- a/cocos/platform/linux/CCFileUtils-linux.h +++ b/cocos/platform/linux/CCFileUtils-linux.h @@ -56,7 +56,7 @@ class CC_DLL FileUtilsLinux : public FileUtils std::string getNativeWritableAbsolutePath() const override; private: - virtual bool isFileExistInternal(const std::string& strFilePath) const override; + virtual bool isFileExistInternal(std::string_view strFilePath) const override; }; // end of platform group diff --git a/cocos/platform/mac/CCApplication-mac.h b/cocos/platform/mac/CCApplication-mac.h index 9636b4af889a..fe6bbbff1a04 100644 --- a/cocos/platform/mac/CCApplication-mac.h +++ b/cocos/platform/mac/CCApplication-mac.h @@ -90,11 +90,11 @@ class CC_DLL Application : public ApplicationProtocol @param String with url to open. @return true if the resource located by the URL was successfully opened; otherwise false. */ - virtual bool openURL(const std::string& url) override; + virtual bool openURL(std::string_view url) override; - void setStartupScriptFilename(const std::string& startupScriptFile); + void setStartupScriptFilename(std::string_view startupScriptFile); - const std::string& getStartupScriptFilename(); + std::string_view getStartupScriptFilename(); protected: static Application* sm_pSharedApplication; diff --git a/cocos/platform/mac/CCApplication-mac.mm b/cocos/platform/mac/CCApplication-mac.mm index 8d8a92b31329..b4fd1dc68414 100644 --- a/cocos/platform/mac/CCApplication-mac.mm +++ b/cocos/platform/mac/CCApplication-mac.mm @@ -40,18 +40,17 @@ static int32_t getCurrentMillSecond() { int32_t lLastTime = 0; struct timeval stCurrentTime; - - gettimeofday(&stCurrentTime,NULL); - lLastTime = stCurrentTime.tv_sec*1000+stCurrentTime.tv_usec*0.001; // milliseconds + + gettimeofday(&stCurrentTime, NULL); + lLastTime = stCurrentTime.tv_sec * 1000 + stCurrentTime.tv_usec * 0.001; // milliseconds return lLastTime; } Application* Application::sm_pSharedApplication = nullptr; -Application::Application() -: _animationInterval(1.0f/60.0f*1000.0f) +Application::Application() : _animationInterval(1.0f / 60.0f * 1000.0f) { - CCASSERT(! sm_pSharedApplication, "sm_pSharedApplication already exist"); + CCASSERT(!sm_pSharedApplication, "sm_pSharedApplication already exist"); sm_pSharedApplication = this; } @@ -64,53 +63,53 @@ static int32_t getCurrentMillSecond() int Application::run() { initGLContextAttrs(); - if(!applicationDidFinishLaunching()) + if (!applicationDidFinishLaunching()) { return 1; } - + int32_t lastTime = 0L; - int32_t curTime = 0L; - + int32_t curTime = 0L; + auto director = Director::getInstance(); - auto glview = director->getOpenGLView(); - + auto glview = director->getOpenGLView(); + // Retain glview to avoid glview being released in the while loop glview->retain(); while (!glview->windowShouldClose()) { lastTime = getCurrentMillSecond(); - + director->mainLoop(); glview->pollEvents(); curTime = getCurrentMillSecond(); if (curTime - lastTime < _animationInterval) { - usleep(static_cast((_animationInterval - curTime + lastTime)*1000)); + usleep(static_cast((_animationInterval - curTime + lastTime) * 1000)); } } /* Only work on Desktop - * Director::mainLoop is really one frame logic - * when we want to close the window, we should call Director::end(); - * then call Director::mainLoop to do release of internal resources - */ + * Director::mainLoop is really one frame logic + * when we want to close the window, we should call Director::end(); + * then call Director::mainLoop to do release of internal resources + */ if (glview->isOpenGLReady()) { director->end(); director->mainLoop(); } - + glview->release(); - + return 0; } void Application::setAnimationInterval(float interval) { - _animationInterval = interval*1000.0f; + _animationInterval = interval * 1000.0f; } Application::Platform Application::getTargetPlatform() @@ -118,9 +117,11 @@ static int32_t getCurrentMillSecond() return Platform::OS_MAC; } -std::string Application::getVersion() { +std::string Application::getVersion() +{ NSString* version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]; - if (version) { + if (version) + { return [version UTF8String]; } return ""; @@ -136,49 +137,49 @@ static int32_t getCurrentMillSecond() return sm_pSharedApplication; } -const char * Application::getCurrentLanguageCode() +const char* Application::getCurrentLanguageCode() { - static char code[3]={0}; - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - NSArray *languages = [defaults objectForKey:@"AppleLanguages"]; - NSString *currentLanguage = [languages objectAtIndex:0]; - + static char code[3] = {0}; + NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; + NSArray* languages = [defaults objectForKey:@"AppleLanguages"]; + NSString* currentLanguage = [languages objectAtIndex:0]; + // get the current language code.(such as English is "en", Chinese is "zh" and so on) - NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; - NSString * languageCode = [temp objectForKey:NSLocaleLanguageCode]; + NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; + NSString* languageCode = [temp objectForKey:NSLocaleLanguageCode]; [languageCode getCString:code maxLength:3 encoding:NSASCIIStringEncoding]; - code[2]='\0'; + code[2] = '\0'; return code; } LanguageType Application::getCurrentLanguage() { // get the current language and country config - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - NSArray *languages = [defaults objectForKey:@"AppleLanguages"]; - NSString *currentLanguage = [languages objectAtIndex:0]; - + NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; + NSArray* languages = [defaults objectForKey:@"AppleLanguages"]; + NSString* currentLanguage = [languages objectAtIndex:0]; + // get the current language code.(such as English is "en", Chinese is "zh" and so on) - NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; - NSString * languageCode = [temp objectForKey:NSLocaleLanguageCode]; - + NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; + NSString* languageCode = [temp objectForKey:NSLocaleLanguageCode]; + return utils::getLanguageTypeByISO2([languageCode UTF8String]); } -bool Application::openURL(const std::string &url) +bool Application::openURL(std::string_view url) { - NSString* msg = [NSString stringWithCString:url.c_str() encoding:NSUTF8StringEncoding]; - NSURL* nsUrl = [NSURL URLWithString:msg]; + NSString* msg = [NSString stringWithCString:url.data() encoding:NSUTF8StringEncoding]; + NSURL* nsUrl = [NSURL URLWithString:msg]; return [[NSWorkspace sharedWorkspace] openURL:nsUrl]; } -void Application::setStartupScriptFilename(const std::string& startupScriptFile) +void Application::setStartupScriptFilename(std::string_view startupScriptFile) { _startupScriptFilename = startupScriptFile; std::replace(_startupScriptFilename.begin(), _startupScriptFilename.end(), '\\', '/'); } -const std::string& Application::getStartupScriptFilename() +std::string_view Application::getStartupScriptFilename() { return _startupScriptFilename; } diff --git a/cocos/platform/mac/CCCommon-mac.mm b/cocos/platform/mac/CCCommon-mac.mm index 3ce527eb5231..5e3be91e60d3 100644 --- a/cocos/platform/mac/CCCommon-mac.mm +++ b/cocos/platform/mac/CCCommon-mac.mm @@ -33,25 +33,25 @@ of this software and associated documentation files (the "Software"), to deal NS_CC_BEGIN -void LuaLog(const char * format) +void LuaLog(const char* format) { puts(format); } // ios no MessageBox, use log instead -void ccMessageBox(const char * msg, const char * title) +void ccMessageBox(const char* msg, const char* title) { - NSString * tmpTitle = (title) ? [NSString stringWithUTF8String : title] : nil; - NSString * tmpMsg = (msg) ? [NSString stringWithUTF8String : msg] : nil; + NSString* tmpTitle = (title) ? [NSString stringWithUTF8String:title] : nil; + NSString* tmpMsg = (msg) ? [NSString stringWithUTF8String:msg] : nil; - NSAlert *alert = [[[NSAlert alloc] init] autorelease]; + NSAlert* alert = [[[NSAlert alloc] init] autorelease]; [alert addButtonWithTitle:@"OK"]; [alert setMessageText:tmpMsg]; [alert setInformativeText:tmpTitle]; [alert setAlertStyle:NSAlertStyleWarning]; auto glview = Director::getInstance()->getOpenGLView(); - id window = glview->getCocoaWindow(); + id window = glview->getCocoaWindow(); [alert beginSheetModalForWindow:window completionHandler:nil]; } diff --git a/cocos/platform/mac/CCDevice-mac.mm b/cocos/platform/mac/CCDevice-mac.mm index 5a8b4e09c916..cf1b1ae014dd 100644 --- a/cocos/platform/mac/CCDevice-mac.mm +++ b/cocos/platform/mac/CCDevice-mac.mm @@ -36,41 +36,37 @@ of this software and associated documentation files (the "Software"), to deal { { [attributedString beginEditing]; - - [attributedString enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, attributedString.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) { - - NSFont* font = value; - font = [[NSFontManager sharedFontManager] convertFont:font toSize:fontSize]; - - [attributedString removeAttribute:NSFontAttributeName range:range]; - [attributedString addAttribute:NSFontAttributeName value:font range:range]; - }]; - + + [attributedString enumerateAttribute:NSFontAttributeName + inRange:NSMakeRange(0, attributedString.length) + options:0 + usingBlock:^(id value, NSRange range, BOOL* stop) { + NSFont* font = value; + font = [[NSFontManager sharedFontManager] convertFont:font toSize:fontSize]; + + [attributedString removeAttribute:NSFontAttributeName range:range]; + [attributedString addAttribute:NSFontAttributeName value:font range:range]; + }]; + [attributedString endEditing]; } - + return [[attributedString copy] autorelease]; } int Device::getDPI() { - NSScreen *screen = [NSScreen mainScreen]; - NSDictionary *description = [screen deviceDescription]; - NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue]; + NSScreen* screen = [NSScreen mainScreen]; + NSDictionary* description = [screen deviceDescription]; + NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue]; CGSize displayPhysicalSize = CGDisplayScreenSize([[description objectForKey:@"NSScreenNumber"] unsignedIntValue]); - - return ((displayPixelSize.width / displayPhysicalSize.width) * 25.4f); -} - -void Device::setAccelerometerEnabled(bool isEnabled) -{ + return ((displayPixelSize.width / displayPhysicalSize.width) * 25.4f); } -void Device::setAccelerometerInterval(float interval) -{ +void Device::setAccelerometerEnabled(bool isEnabled) {} -} +void Device::setAccelerometerInterval(float interval) {} typedef struct { @@ -81,305 +77,359 @@ of this software and associated documentation files (the "Software"), to deal unsigned char* data; } tImageInfo; -static NSSize _calculateStringSize(NSAttributedString *str, id font, CGSize *constrainSize, bool enableWrap, int overflow) +static NSSize _calculateStringSize(NSAttributedString* str, + id font, + CGSize* constrainSize, + bool enableWrap, + int overflow) { NSSize textRect = NSZeroSize; - textRect.width = constrainSize->width > 0 ? constrainSize->width - : CGFLOAT_MAX; - textRect.height = constrainSize->height > 0 ? constrainSize->height - : CGFLOAT_MAX; - - if (overflow == 1) { - if (!enableWrap) { - textRect.width = CGFLOAT_MAX; + textRect.width = constrainSize->width > 0 ? constrainSize->width : CGFLOAT_MAX; + textRect.height = constrainSize->height > 0 ? constrainSize->height : CGFLOAT_MAX; + + if (overflow == 1) + { + if (!enableWrap) + { + textRect.width = CGFLOAT_MAX; textRect.height = CGFLOAT_MAX; - } else { + } + else + { textRect.height = CGFLOAT_MAX; } } - + NSSize dim; #ifdef __MAC_10_11 - #if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_11 - dim = [str boundingRectWithSize:textRect options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin) context:nil].size; - #else - dim = [str boundingRectWithSize:textRect options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin)].size; - #endif +# if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_11 + dim = [str boundingRectWithSize:textRect + options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin)context:nil] + .size; +# else + dim = [str boundingRectWithSize:textRect options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin)] + .size; +# endif #else - dim = [str boundingRectWithSize:textRect options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin)].size; + dim = [str boundingRectWithSize:textRect options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin)] + .size; #endif - - - dim.width = ceilf(dim.width); + + dim.width = ceilf(dim.width); dim.height = ceilf(dim.height); return dim; } -static NSSize _calculateRealSizeForString(NSAttributedString **str, id font, NSSize constrainSize, bool enableWrap) +static NSSize _calculateRealSizeForString(NSAttributedString** str, id font, NSSize constrainSize, bool enableWrap) { CGRect actualSize = CGRectMake(0, 0, constrainSize.width + 1, constrainSize.height + 1); - int fontSize = [font pointSize]; - fontSize = fontSize + 1; + int fontSize = [font pointSize]; + fontSize = fontSize + 1; - if (!enableWrap) { - while (actualSize.size.width > constrainSize.width || - actualSize.size.height > constrainSize.height) { + if (!enableWrap) + { + while (actualSize.size.width > constrainSize.width || actualSize.size.height > constrainSize.height) + { fontSize = fontSize - 1; - if (fontSize < 0) { + if (fontSize < 0) + { actualSize = CGRectMake(0, 0, 0, 0); break; } - - NSMutableAttributedString *mutableString = [[*str mutableCopy] autorelease]; - *str = __attributedStringWithFontSize(mutableString, fontSize); + + NSMutableAttributedString* mutableString = [[*str mutableCopy] autorelease]; + *str = __attributedStringWithFontSize(mutableString, fontSize); #ifdef __MAC_10_11 - #if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_11 - CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size; - #else - CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin].size; - #endif +# if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_11 + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) + options:NSStringDrawingUsesLineFragmentOrigin + context:nil] + .size; +# else + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) + options:NSStringDrawingUsesLineFragmentOrigin] + .size; +# endif #else - CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin].size; + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) + options:NSStringDrawingUsesLineFragmentOrigin] + .size; #endif - if(fitSize.width == 0 || fitSize.height == 0) continue; + if (fitSize.width == 0 || fitSize.height == 0) + continue; actualSize.size = fitSize; - if (constrainSize.width <= 0) { + if (constrainSize.width <= 0) + { constrainSize.width = fitSize.width; } - if (constrainSize.height <= 0){ + if (constrainSize.height <= 0) + { constrainSize.height = fitSize.height; } - if(fontSize <= 0){ + if (fontSize <= 0) + { break; } } - } - else { - while (actualSize.size.height > constrainSize.height - ||actualSize.size.width > constrainSize.width) { + else + { + while (actualSize.size.height > constrainSize.height || actualSize.size.width > constrainSize.width) + { fontSize = fontSize - 1; - if (fontSize < 0) { + if (fontSize < 0) + { actualSize = CGRectMake(0, 0, 0, 0); break; } - - NSMutableAttributedString *mutableString = [[*str mutableCopy] autorelease]; - *str = __attributedStringWithFontSize(mutableString, fontSize); + + NSMutableAttributedString* mutableString = [[*str mutableCopy] autorelease]; + *str = __attributedStringWithFontSize(mutableString, fontSize); #ifdef __MAC_10_11 - #if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_11 - CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( constrainSize.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size; - #else - CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( constrainSize.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin].size; - #endif +# if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_11 + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake(constrainSize.width, CGFLOAT_MAX) + options:NSStringDrawingUsesLineFragmentOrigin + context:nil] + .size; +# else + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake(constrainSize.width, CGFLOAT_MAX) + options:NSStringDrawingUsesLineFragmentOrigin] + .size; +# endif #else - CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( constrainSize.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin].size; + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake(constrainSize.width, CGFLOAT_MAX) + options:NSStringDrawingUsesLineFragmentOrigin] + .size; #endif - - if(fitSize.width == 0 || fitSize.height == 0) continue; + + if (fitSize.width == 0 || fitSize.height == 0) + continue; actualSize.size = fitSize; - - if (constrainSize.width <= 0) { + + if (constrainSize.width <= 0) + { constrainSize.width = fitSize.width; } - if (constrainSize.height <= 0){ + if (constrainSize.height <= 0) + { constrainSize.height = fitSize.height; } - if(fontSize <= 0){ + if (fontSize <= 0) + { break; } } - } return CGSizeMake(actualSize.size.width, actualSize.size.height); } static NSFont* _createSystemFont(const char* fontName, int size) { - NSString * fntName = [NSString stringWithUTF8String:fontName]; - fntName = [[fntName lastPathComponent] stringByDeletingPathExtension]; - + NSString* fntName = [NSString stringWithUTF8String:fontName]; + fntName = [[fntName lastPathComponent] stringByDeletingPathExtension]; + // font - NSFont *font = [NSFont fontWithName:fntName size:size]; - - if (font == nil) { + NSFont* font = [NSFont fontWithName:fntName size:size]; + + if (font == nil) + { font = [NSFont systemFontOfSize:size]; } return font; } - static CGFloat _calculateTextDrawStartHeight(cocos2d::Device::TextAlign align, CGSize realDimensions, CGSize dimensions) { float startH = 0; // vertical alignment unsigned int vAlignment = ((int)align >> 4) & 0x0F; - switch (vAlignment) { - //bottom - case 1:startH = dimensions.height - realDimensions.height;break; - //top - case 2:startH = 0;break; - //center - case 3: startH = (dimensions.height - realDimensions.height) / 2;break; - default: - break; + switch (vAlignment) + { + // bottom + case 1: + startH = dimensions.height - realDimensions.height; + break; + // top + case 2: + startH = 0; + break; + // center + case 3: + startH = (dimensions.height - realDimensions.height) / 2; + break; + default: + break; } return startH; } -static bool _initWithString(const char * text, Device::TextAlign align, const char * fontName, int size, tImageInfo* info, const Color3B* fontColor, int fontAlpha, bool enableWrap, int overflow, const FontStroke &stroke) +static bool _initWithString(const char* text, + Device::TextAlign align, + const char* fontName, + int size, + tImageInfo* info, + const Color3B* fontColor, + int fontAlpha, + bool enableWrap, + int overflow, + const FontStroke& stroke) { bool ret = false; - + CCASSERT(text, "Invalid text"); CCASSERT(info, "Invalid info"); - - do { - NSString * string = [NSString stringWithUTF8String:text]; + + do + { + NSString* string = [NSString stringWithUTF8String:text]; CC_BREAK_IF(!string); - + id font = _createSystemFont(fontName, size); CC_BREAK_IF(!font); - + // color NSColor* foregroundColor; - if (fontColor) { - foregroundColor = [NSColor colorWithDeviceRed:fontColor->r/255.0 - green:fontColor->g/255.0 - blue:fontColor->b/255.0 - alpha:fontAlpha/255.0]; - } else { + if (fontColor) + { + foregroundColor = [NSColor colorWithDeviceRed:fontColor->r / 255.0 + green:fontColor->g / 255.0 + blue:fontColor->b / 255.0 + alpha:fontAlpha / 255.0]; + } + else + { foregroundColor = [NSColor whiteColor]; } - + // alignment - NSTextAlignment textAlign = FontUtils::_calculateTextAlignment(align); - NSMutableParagraphStyle *paragraphStyle = FontUtils::_calculateParagraphStyle(enableWrap, overflow); + NSTextAlignment textAlign = FontUtils::_calculateTextAlignment(align); + NSMutableParagraphStyle* paragraphStyle = FontUtils::_calculateParagraphStyle(enableWrap, overflow); [paragraphStyle setAlignment:textAlign]; - + // attribute - NSDictionary* tokenAttributesDict = [NSDictionary dictionaryWithObjectsAndKeys: - foregroundColor,NSForegroundColorAttributeName, - font, NSFontAttributeName, - paragraphStyle, NSParagraphStyleAttributeName, nil]; - NSAttributedString *stringWithAttributes =[[[NSAttributedString alloc] initWithString:string - attributes:tokenAttributesDict] autorelease]; - + NSDictionary* tokenAttributesDict = [NSDictionary + dictionaryWithObjectsAndKeys:foregroundColor, NSForegroundColorAttributeName, font, NSFontAttributeName, + paragraphStyle, NSParagraphStyleAttributeName, nil]; + NSAttributedString* stringWithAttributes = + [[[NSAttributedString alloc] initWithString:string attributes:tokenAttributesDict] autorelease]; + CGSize dimensions = CGSizeMake(info->width, info->height); NSSize realDimensions; - + if (overflow == 2) realDimensions = _calculateRealSizeForString(&stringWithAttributes, font, dimensions, enableWrap); else - realDimensions = _calculateStringSize(stringWithAttributes, font, &dimensions, enableWrap, overflow); + realDimensions = _calculateStringSize(stringWithAttributes, font, &dimensions, enableWrap, overflow); // Mac crashes if the width or height is 0 CC_BREAK_IF(realDimensions.width <= 0 || realDimensions.height <= 0); - - if(dimensions.width <= 0.f) + + if (dimensions.width <= 0.f) dimensions.width = realDimensions.width; if (dimensions.height <= 0.f) - dimensions.height = realDimensions.height; - - //Alignment + dimensions.height = realDimensions.height; + + // Alignment CGFloat xPadding = FontUtils::_calculateTextDrawStartWidth(align, realDimensions, dimensions); CGFloat yPadding = _calculateTextDrawStartHeight(align, realDimensions, dimensions); NSInteger POTWide = dimensions.width; NSInteger POTHigh = dimensions.height; - NSRect textRect = NSMakeRect(xPadding, POTHigh - dimensions.height + yPadding, - realDimensions.width, realDimensions.height); - - NSBitmapImageRep* offscreenRep = [[[NSBitmapImageRep alloc] - initWithBitmapDataPlanes:NULL - pixelsWide:POTWide - pixelsHigh:POTHigh - bitsPerSample:8 - samplesPerPixel:4 - hasAlpha:YES - isPlanar:NO - colorSpaceName:NSDeviceRGBColorSpace - bitmapFormat: 0 - bytesPerRow:4 * POTWide - bitsPerPixel:32] autorelease]; + NSRect textRect = + NSMakeRect(xPadding, POTHigh - dimensions.height + yPadding, realDimensions.width, realDimensions.height); + + NSBitmapImageRep* offscreenRep = [[[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL + pixelsWide:POTWide + pixelsHigh:POTHigh + bitsPerSample:8 + samplesPerPixel:4 + hasAlpha:YES + isPlanar:NO + colorSpaceName:NSDeviceRGBColorSpace + bitmapFormat:0 + bytesPerRow:4 * POTWide + bitsPerPixel:32] autorelease]; NSGraphicsContext* g = [NSGraphicsContext graphicsContextWithBitmapImageRep:offscreenRep]; [NSGraphicsContext saveGraphicsState]; [NSGraphicsContext setCurrentContext:g]; - - if (stroke._strokeSize > 0) { - NSColor *strokeColor = [NSColor colorWithDeviceRed:stroke._strokeColor.r/255.0 - green:stroke._strokeColor.g/255.0 - blue:stroke._strokeColor.b/255.0 - alpha:stroke._strokeAlpha/255.0]; - NSNumber *strokeSize = [NSNumber numberWithFloat:stroke._strokeSize / size * 100.0]; - NSDictionary *tokenAttributesDict2 = [NSDictionary dictionaryWithObjectsAndKeys: - foregroundColor,NSForegroundColorAttributeName, - font, NSFontAttributeName, - paragraphStyle, NSParagraphStyleAttributeName, - strokeSize, NSStrokeWidthAttributeName, - strokeColor, NSStrokeColorAttributeName, - nil]; - NSAttributedString *strokeString = [[[NSAttributedString alloc] initWithString:string - attributes:tokenAttributesDict2] autorelease]; + + if (stroke._strokeSize > 0) + { + NSColor* strokeColor = [NSColor colorWithDeviceRed:stroke._strokeColor.r / 255.0 + green:stroke._strokeColor.g / 255.0 + blue:stroke._strokeColor.b / 255.0 + alpha:stroke._strokeAlpha / 255.0]; + NSNumber* strokeSize = [NSNumber numberWithFloat:stroke._strokeSize / size * 100.0]; + NSDictionary* tokenAttributesDict2 = [NSDictionary + dictionaryWithObjectsAndKeys:foregroundColor, NSForegroundColorAttributeName, font, NSFontAttributeName, + paragraphStyle, NSParagraphStyleAttributeName, strokeSize, + NSStrokeWidthAttributeName, strokeColor, NSStrokeColorAttributeName, nil]; + NSAttributedString* strokeString = + [[[NSAttributedString alloc] initWithString:string attributes:tokenAttributesDict2] autorelease]; [strokeString drawInRect:textRect]; } - + [stringWithAttributes drawInRect:textRect]; [NSGraphicsContext restoreGraphicsState]; - auto data = (unsigned char*) [offscreenRep bitmapData]; //Use the same buffer to improve the performance. + auto data = (unsigned char*)[offscreenRep bitmapData]; // Use the same buffer to improve the performance. NSUInteger textureSize = POTWide * POTHigh * 4; - auto dataNew = (unsigned char*)malloc(sizeof(unsigned char) * textureSize); - if (dataNew) { + auto dataNew = (unsigned char*)malloc(sizeof(unsigned char) * textureSize); + if (dataNew) + { memcpy(dataNew, data, textureSize); // output params - info->width = static_cast(POTWide); - info->height = static_cast(POTHigh); - info->data = dataNew; - info->hasAlpha = true; + info->width = static_cast(POTWide); + info->height = static_cast(POTHigh); + info->data = dataNew; + info->hasAlpha = true; info->isPremultipliedAlpha = true; - ret = true; + ret = true; } } while (0); return ret; } -Data Device::getTextureDataForText(const char * text, const FontDefinition& textDefinition, TextAlign align, int &width, int &height, bool& hasPremultipliedAlpha) +Data Device::getTextureDataForText(const char* text, + const FontDefinition& textDefinition, + TextAlign align, + int& width, + int& height, + bool& hasPremultipliedAlpha) { Data ret; - do { + do + { tImageInfo info = {0}; - info.width = textDefinition._dimensions.width; - info.height = textDefinition._dimensions.height; + info.width = textDefinition._dimensions.width; + info.height = textDefinition._dimensions.height; - if (! _initWithString(text, align, textDefinition._fontName.c_str(), textDefinition._fontSize, &info, &textDefinition._fontFillColor, textDefinition._fontAlpha, textDefinition._enableWrap, textDefinition._overflow, textDefinition._stroke)) + if (!_initWithString(text, align, textDefinition._fontName.c_str(), textDefinition._fontSize, &info, + &textDefinition._fontFillColor, textDefinition._fontAlpha, textDefinition._enableWrap, + textDefinition._overflow, textDefinition._stroke)) { break; } height = (short)info.height; - width = (short)info.width; - ret.fastSet(info.data,width * height * 4); + width = (short)info.width; + ret.fastSet(info.data, width * height * 4); hasPremultipliedAlpha = true; } while (0); - + return ret; } -void Device::setKeepScreenOn(bool value) -{ -} +void Device::setKeepScreenOn(bool value) {} -void Device::vibrate(float duration) -{ -} +void Device::vibrate(float duration) {} NS_CC_END diff --git a/cocos/platform/mac/CCGLViewImpl-mac.h b/cocos/platform/mac/CCGLViewImpl-mac.h index 7c2d480dfa3c..01317ae283ce 100644 --- a/cocos/platform/mac/CCGLViewImpl-mac.h +++ b/cocos/platform/mac/CCGLViewImpl-mac.h @@ -58,14 +58,14 @@ class CC_DLL GLViewImpl : public GLView friend class GLFWEventHandler; public: - static GLViewImpl* create(const std::string& viewName); - static GLViewImpl* create(const std::string& viewName, bool resizable); - static GLViewImpl* createWithRect(const std::string& viewName, + static GLViewImpl* create(std::string_view viewName); + static GLViewImpl* create(std::string_view viewName, bool resizable); + static GLViewImpl* createWithRect(std::string_view viewName, Rect size, float frameZoomFactor = 1.0f, bool resizable = false); - static GLViewImpl* createWithFullScreen(const std::string& viewName); - static GLViewImpl* createWithFullScreen(const std::string& viewName, + static GLViewImpl* createWithFullScreen(std::string_view viewName); + static GLViewImpl* createWithFullScreen(std::string_view viewName, const GLFWvidmode& videoMode, GLFWmonitor* monitor); @@ -119,7 +119,7 @@ class CC_DLL GLViewImpl : public GLView virtual void setIMEKeyboardState(bool bOpen) override; #if CC_ICON_SET_SUPPORT - virtual void setIcon(const std::string& filename) const override; + virtual void setIcon(std::string_view filename) const override; virtual void setIcon(const std::vector& filelist) const override; virtual void setDefaultIcon() const override; #endif /* CC_ICON_SET_SUPPORT */ @@ -149,9 +149,9 @@ class CC_DLL GLViewImpl : public GLView GLViewImpl(bool initglfw = true); virtual ~GLViewImpl(); - bool initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable); - bool initWithFullScreen(const std::string& viewName); - bool initWithFullscreen(const std::string& viewname, const GLFWvidmode& videoMode, GLFWmonitor* monitor); + bool initWithRect(std::string_view viewName, Rect rect, float frameZoomFactor, bool resizable); + bool initWithFullScreen(std::string_view viewName); + bool initWithFullscreen(std::string_view viewname, const GLFWvidmode& videoMode, GLFWmonitor* monitor); /* update frame layout when enter/exit full screen mode */ void updateWindowSize(); diff --git a/cocos/platform/mac/CCGLViewImpl-mac.mm b/cocos/platform/mac/CCGLViewImpl-mac.mm index 8d47ababc9ca..dfd66ec28d3b 100644 --- a/cocos/platform/mac/CCGLViewImpl-mac.mm +++ b/cocos/platform/mac/CCGLViewImpl-mac.mm @@ -40,7 +40,7 @@ of this software and associated documentation files (the "Software"), to deal #include "base/ccUTF8.h" #include "2d/CCCamera.h" #if CC_ICON_SET_SUPPORT -#include "platform/CCImage.h" +# include "platform/CCImage.h" #endif /* CC_ICON_SET_SUPPORT */ #include "renderer/backend/metal/DeviceMTL.h" #include "renderer/CCRenderer.h" @@ -100,16 +100,13 @@ static void onGLFWWindowPosCallback(GLFWwindow* windows, int x, int y) // _view->onGLFWframebufferSize(window, w, h); // } - static void onGLFWWindowSizeCallback(GLFWwindow *window, int width, int height) + static void onGLFWWindowSizeCallback(GLFWwindow* window, int width, int height) { if (_view) _view->onGLFWWindowSizeCallback(window, width, height); } - static void setGLViewImpl(GLViewImpl* view) - { - _view = view; - } + static void setGLViewImpl(GLViewImpl* view) { _view = view; } static void onGLFWWindowIconifyCallback(GLFWwindow* window, int iconified) { @@ -132,8 +129,8 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) }; GLViewImpl* GLFWEventHandler::_view = nullptr; -const std::string GLViewImpl::EVENT_WINDOW_RESIZED = "glview_window_resized"; -const std::string GLViewImpl::EVENT_WINDOW_FOCUSED = "glview_window_focused"; +const std::string GLViewImpl::EVENT_WINDOW_RESIZED = "glview_window_resized"; +const std::string GLViewImpl::EVENT_WINDOW_FOCUSED = "glview_window_focused"; const std::string GLViewImpl::EVENT_WINDOW_UNFOCUSED = "glview_window_unfocused"; //////////////////////////////////////////////////// @@ -148,149 +145,147 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) static keyCodeItem g_keyCodeStructArray[] = { /* The unknown key */ - { GLFW_KEY_UNKNOWN , EventKeyboard::KeyCode::KEY_NONE }, + {GLFW_KEY_UNKNOWN, EventKeyboard::KeyCode::KEY_NONE}, /* Printable keys */ - { GLFW_KEY_SPACE , EventKeyboard::KeyCode::KEY_SPACE }, - { GLFW_KEY_APOSTROPHE , EventKeyboard::KeyCode::KEY_APOSTROPHE }, - { GLFW_KEY_COMMA , EventKeyboard::KeyCode::KEY_COMMA }, - { GLFW_KEY_MINUS , EventKeyboard::KeyCode::KEY_MINUS }, - { GLFW_KEY_PERIOD , EventKeyboard::KeyCode::KEY_PERIOD }, - { GLFW_KEY_SLASH , EventKeyboard::KeyCode::KEY_SLASH }, - { GLFW_KEY_0 , EventKeyboard::KeyCode::KEY_0 }, - { GLFW_KEY_1 , EventKeyboard::KeyCode::KEY_1 }, - { GLFW_KEY_2 , EventKeyboard::KeyCode::KEY_2 }, - { GLFW_KEY_3 , EventKeyboard::KeyCode::KEY_3 }, - { GLFW_KEY_4 , EventKeyboard::KeyCode::KEY_4 }, - { GLFW_KEY_5 , EventKeyboard::KeyCode::KEY_5 }, - { GLFW_KEY_6 , EventKeyboard::KeyCode::KEY_6 }, - { GLFW_KEY_7 , EventKeyboard::KeyCode::KEY_7 }, - { GLFW_KEY_8 , EventKeyboard::KeyCode::KEY_8 }, - { GLFW_KEY_9 , EventKeyboard::KeyCode::KEY_9 }, - { GLFW_KEY_SEMICOLON , EventKeyboard::KeyCode::KEY_SEMICOLON }, - { GLFW_KEY_EQUAL , EventKeyboard::KeyCode::KEY_EQUAL }, - { GLFW_KEY_A , EventKeyboard::KeyCode::KEY_A }, - { GLFW_KEY_B , EventKeyboard::KeyCode::KEY_B }, - { GLFW_KEY_C , EventKeyboard::KeyCode::KEY_C }, - { GLFW_KEY_D , EventKeyboard::KeyCode::KEY_D }, - { GLFW_KEY_E , EventKeyboard::KeyCode::KEY_E }, - { GLFW_KEY_F , EventKeyboard::KeyCode::KEY_F }, - { GLFW_KEY_G , EventKeyboard::KeyCode::KEY_G }, - { GLFW_KEY_H , EventKeyboard::KeyCode::KEY_H }, - { GLFW_KEY_I , EventKeyboard::KeyCode::KEY_I }, - { GLFW_KEY_J , EventKeyboard::KeyCode::KEY_J }, - { GLFW_KEY_K , EventKeyboard::KeyCode::KEY_K }, - { GLFW_KEY_L , EventKeyboard::KeyCode::KEY_L }, - { GLFW_KEY_M , EventKeyboard::KeyCode::KEY_M }, - { GLFW_KEY_N , EventKeyboard::KeyCode::KEY_N }, - { GLFW_KEY_O , EventKeyboard::KeyCode::KEY_O }, - { GLFW_KEY_P , EventKeyboard::KeyCode::KEY_P }, - { GLFW_KEY_Q , EventKeyboard::KeyCode::KEY_Q }, - { GLFW_KEY_R , EventKeyboard::KeyCode::KEY_R }, - { GLFW_KEY_S , EventKeyboard::KeyCode::KEY_S }, - { GLFW_KEY_T , EventKeyboard::KeyCode::KEY_T }, - { GLFW_KEY_U , EventKeyboard::KeyCode::KEY_U }, - { GLFW_KEY_V , EventKeyboard::KeyCode::KEY_V }, - { GLFW_KEY_W , EventKeyboard::KeyCode::KEY_W }, - { GLFW_KEY_X , EventKeyboard::KeyCode::KEY_X }, - { GLFW_KEY_Y , EventKeyboard::KeyCode::KEY_Y }, - { GLFW_KEY_Z , EventKeyboard::KeyCode::KEY_Z }, - { GLFW_KEY_LEFT_BRACKET , EventKeyboard::KeyCode::KEY_LEFT_BRACKET }, - { GLFW_KEY_BACKSLASH , EventKeyboard::KeyCode::KEY_BACK_SLASH }, - { GLFW_KEY_RIGHT_BRACKET , EventKeyboard::KeyCode::KEY_RIGHT_BRACKET }, - { GLFW_KEY_GRAVE_ACCENT , EventKeyboard::KeyCode::KEY_GRAVE }, - { GLFW_KEY_WORLD_1 , EventKeyboard::KeyCode::KEY_GRAVE }, - { GLFW_KEY_WORLD_2 , EventKeyboard::KeyCode::KEY_NONE }, + {GLFW_KEY_SPACE, EventKeyboard::KeyCode::KEY_SPACE}, + {GLFW_KEY_APOSTROPHE, EventKeyboard::KeyCode::KEY_APOSTROPHE}, + {GLFW_KEY_COMMA, EventKeyboard::KeyCode::KEY_COMMA}, + {GLFW_KEY_MINUS, EventKeyboard::KeyCode::KEY_MINUS}, + {GLFW_KEY_PERIOD, EventKeyboard::KeyCode::KEY_PERIOD}, + {GLFW_KEY_SLASH, EventKeyboard::KeyCode::KEY_SLASH}, + {GLFW_KEY_0, EventKeyboard::KeyCode::KEY_0}, + {GLFW_KEY_1, EventKeyboard::KeyCode::KEY_1}, + {GLFW_KEY_2, EventKeyboard::KeyCode::KEY_2}, + {GLFW_KEY_3, EventKeyboard::KeyCode::KEY_3}, + {GLFW_KEY_4, EventKeyboard::KeyCode::KEY_4}, + {GLFW_KEY_5, EventKeyboard::KeyCode::KEY_5}, + {GLFW_KEY_6, EventKeyboard::KeyCode::KEY_6}, + {GLFW_KEY_7, EventKeyboard::KeyCode::KEY_7}, + {GLFW_KEY_8, EventKeyboard::KeyCode::KEY_8}, + {GLFW_KEY_9, EventKeyboard::KeyCode::KEY_9}, + {GLFW_KEY_SEMICOLON, EventKeyboard::KeyCode::KEY_SEMICOLON}, + {GLFW_KEY_EQUAL, EventKeyboard::KeyCode::KEY_EQUAL}, + {GLFW_KEY_A, EventKeyboard::KeyCode::KEY_A}, + {GLFW_KEY_B, EventKeyboard::KeyCode::KEY_B}, + {GLFW_KEY_C, EventKeyboard::KeyCode::KEY_C}, + {GLFW_KEY_D, EventKeyboard::KeyCode::KEY_D}, + {GLFW_KEY_E, EventKeyboard::KeyCode::KEY_E}, + {GLFW_KEY_F, EventKeyboard::KeyCode::KEY_F}, + {GLFW_KEY_G, EventKeyboard::KeyCode::KEY_G}, + {GLFW_KEY_H, EventKeyboard::KeyCode::KEY_H}, + {GLFW_KEY_I, EventKeyboard::KeyCode::KEY_I}, + {GLFW_KEY_J, EventKeyboard::KeyCode::KEY_J}, + {GLFW_KEY_K, EventKeyboard::KeyCode::KEY_K}, + {GLFW_KEY_L, EventKeyboard::KeyCode::KEY_L}, + {GLFW_KEY_M, EventKeyboard::KeyCode::KEY_M}, + {GLFW_KEY_N, EventKeyboard::KeyCode::KEY_N}, + {GLFW_KEY_O, EventKeyboard::KeyCode::KEY_O}, + {GLFW_KEY_P, EventKeyboard::KeyCode::KEY_P}, + {GLFW_KEY_Q, EventKeyboard::KeyCode::KEY_Q}, + {GLFW_KEY_R, EventKeyboard::KeyCode::KEY_R}, + {GLFW_KEY_S, EventKeyboard::KeyCode::KEY_S}, + {GLFW_KEY_T, EventKeyboard::KeyCode::KEY_T}, + {GLFW_KEY_U, EventKeyboard::KeyCode::KEY_U}, + {GLFW_KEY_V, EventKeyboard::KeyCode::KEY_V}, + {GLFW_KEY_W, EventKeyboard::KeyCode::KEY_W}, + {GLFW_KEY_X, EventKeyboard::KeyCode::KEY_X}, + {GLFW_KEY_Y, EventKeyboard::KeyCode::KEY_Y}, + {GLFW_KEY_Z, EventKeyboard::KeyCode::KEY_Z}, + {GLFW_KEY_LEFT_BRACKET, EventKeyboard::KeyCode::KEY_LEFT_BRACKET}, + {GLFW_KEY_BACKSLASH, EventKeyboard::KeyCode::KEY_BACK_SLASH}, + {GLFW_KEY_RIGHT_BRACKET, EventKeyboard::KeyCode::KEY_RIGHT_BRACKET}, + {GLFW_KEY_GRAVE_ACCENT, EventKeyboard::KeyCode::KEY_GRAVE}, + {GLFW_KEY_WORLD_1, EventKeyboard::KeyCode::KEY_GRAVE}, + {GLFW_KEY_WORLD_2, EventKeyboard::KeyCode::KEY_NONE}, /* Function keys */ - { GLFW_KEY_ESCAPE , EventKeyboard::KeyCode::KEY_ESCAPE }, - { GLFW_KEY_ENTER , EventKeyboard::KeyCode::KEY_ENTER }, - { GLFW_KEY_TAB , EventKeyboard::KeyCode::KEY_TAB }, - { GLFW_KEY_BACKSPACE , EventKeyboard::KeyCode::KEY_BACKSPACE }, - { GLFW_KEY_INSERT , EventKeyboard::KeyCode::KEY_INSERT }, - { GLFW_KEY_DELETE , EventKeyboard::KeyCode::KEY_DELETE }, - { GLFW_KEY_RIGHT , EventKeyboard::KeyCode::KEY_RIGHT_ARROW }, - { GLFW_KEY_LEFT , EventKeyboard::KeyCode::KEY_LEFT_ARROW }, - { GLFW_KEY_DOWN , EventKeyboard::KeyCode::KEY_DOWN_ARROW }, - { GLFW_KEY_UP , EventKeyboard::KeyCode::KEY_UP_ARROW }, - { GLFW_KEY_PAGE_UP , EventKeyboard::KeyCode::KEY_PG_UP }, - { GLFW_KEY_PAGE_DOWN , EventKeyboard::KeyCode::KEY_PG_DOWN }, - { GLFW_KEY_HOME , EventKeyboard::KeyCode::KEY_HOME }, - { GLFW_KEY_END , EventKeyboard::KeyCode::KEY_END }, - { GLFW_KEY_CAPS_LOCK , EventKeyboard::KeyCode::KEY_CAPS_LOCK }, - { GLFW_KEY_SCROLL_LOCK , EventKeyboard::KeyCode::KEY_SCROLL_LOCK }, - { GLFW_KEY_NUM_LOCK , EventKeyboard::KeyCode::KEY_NUM_LOCK }, - { GLFW_KEY_PRINT_SCREEN , EventKeyboard::KeyCode::KEY_PRINT }, - { GLFW_KEY_PAUSE , EventKeyboard::KeyCode::KEY_PAUSE }, - { GLFW_KEY_F1 , EventKeyboard::KeyCode::KEY_F1 }, - { GLFW_KEY_F2 , EventKeyboard::KeyCode::KEY_F2 }, - { GLFW_KEY_F3 , EventKeyboard::KeyCode::KEY_F3 }, - { GLFW_KEY_F4 , EventKeyboard::KeyCode::KEY_F4 }, - { GLFW_KEY_F5 , EventKeyboard::KeyCode::KEY_F5 }, - { GLFW_KEY_F6 , EventKeyboard::KeyCode::KEY_F6 }, - { GLFW_KEY_F7 , EventKeyboard::KeyCode::KEY_F7 }, - { GLFW_KEY_F8 , EventKeyboard::KeyCode::KEY_F8 }, - { GLFW_KEY_F9 , EventKeyboard::KeyCode::KEY_F9 }, - { GLFW_KEY_F10 , EventKeyboard::KeyCode::KEY_F10 }, - { GLFW_KEY_F11 , EventKeyboard::KeyCode::KEY_F11 }, - { GLFW_KEY_F12 , EventKeyboard::KeyCode::KEY_F12 }, - { GLFW_KEY_F13 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F14 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F15 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F16 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F17 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F18 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F19 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F20 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F21 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F22 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F23 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F24 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F25 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_KP_0 , EventKeyboard::KeyCode::KEY_0 }, - { GLFW_KEY_KP_1 , EventKeyboard::KeyCode::KEY_1 }, - { GLFW_KEY_KP_2 , EventKeyboard::KeyCode::KEY_2 }, - { GLFW_KEY_KP_3 , EventKeyboard::KeyCode::KEY_3 }, - { GLFW_KEY_KP_4 , EventKeyboard::KeyCode::KEY_4 }, - { GLFW_KEY_KP_5 , EventKeyboard::KeyCode::KEY_5 }, - { GLFW_KEY_KP_6 , EventKeyboard::KeyCode::KEY_6 }, - { GLFW_KEY_KP_7 , EventKeyboard::KeyCode::KEY_7 }, - { GLFW_KEY_KP_8 , EventKeyboard::KeyCode::KEY_8 }, - { GLFW_KEY_KP_9 , EventKeyboard::KeyCode::KEY_9 }, - { GLFW_KEY_KP_DECIMAL , EventKeyboard::KeyCode::KEY_PERIOD }, - { GLFW_KEY_KP_DIVIDE , EventKeyboard::KeyCode::KEY_KP_DIVIDE }, - { GLFW_KEY_KP_MULTIPLY , EventKeyboard::KeyCode::KEY_KP_MULTIPLY }, - { GLFW_KEY_KP_SUBTRACT , EventKeyboard::KeyCode::KEY_KP_MINUS }, - { GLFW_KEY_KP_ADD , EventKeyboard::KeyCode::KEY_KP_PLUS }, - { GLFW_KEY_KP_ENTER , EventKeyboard::KeyCode::KEY_KP_ENTER }, - { GLFW_KEY_KP_EQUAL , EventKeyboard::KeyCode::KEY_EQUAL }, - { GLFW_KEY_LEFT_SHIFT , EventKeyboard::KeyCode::KEY_LEFT_SHIFT }, - { GLFW_KEY_LEFT_CONTROL , EventKeyboard::KeyCode::KEY_LEFT_CTRL }, - { GLFW_KEY_LEFT_ALT , EventKeyboard::KeyCode::KEY_LEFT_ALT }, - { GLFW_KEY_LEFT_SUPER , EventKeyboard::KeyCode::KEY_HYPER }, - { GLFW_KEY_RIGHT_SHIFT , EventKeyboard::KeyCode::KEY_RIGHT_SHIFT }, - { GLFW_KEY_RIGHT_CONTROL , EventKeyboard::KeyCode::KEY_RIGHT_CTRL }, - { GLFW_KEY_RIGHT_ALT , EventKeyboard::KeyCode::KEY_RIGHT_ALT }, - { GLFW_KEY_RIGHT_SUPER , EventKeyboard::KeyCode::KEY_HYPER }, - { GLFW_KEY_MENU , EventKeyboard::KeyCode::KEY_MENU }, - { GLFW_KEY_LAST , EventKeyboard::KeyCode::KEY_NONE } -}; + {GLFW_KEY_ESCAPE, EventKeyboard::KeyCode::KEY_ESCAPE}, + {GLFW_KEY_ENTER, EventKeyboard::KeyCode::KEY_ENTER}, + {GLFW_KEY_TAB, EventKeyboard::KeyCode::KEY_TAB}, + {GLFW_KEY_BACKSPACE, EventKeyboard::KeyCode::KEY_BACKSPACE}, + {GLFW_KEY_INSERT, EventKeyboard::KeyCode::KEY_INSERT}, + {GLFW_KEY_DELETE, EventKeyboard::KeyCode::KEY_DELETE}, + {GLFW_KEY_RIGHT, EventKeyboard::KeyCode::KEY_RIGHT_ARROW}, + {GLFW_KEY_LEFT, EventKeyboard::KeyCode::KEY_LEFT_ARROW}, + {GLFW_KEY_DOWN, EventKeyboard::KeyCode::KEY_DOWN_ARROW}, + {GLFW_KEY_UP, EventKeyboard::KeyCode::KEY_UP_ARROW}, + {GLFW_KEY_PAGE_UP, EventKeyboard::KeyCode::KEY_PG_UP}, + {GLFW_KEY_PAGE_DOWN, EventKeyboard::KeyCode::KEY_PG_DOWN}, + {GLFW_KEY_HOME, EventKeyboard::KeyCode::KEY_HOME}, + {GLFW_KEY_END, EventKeyboard::KeyCode::KEY_END}, + {GLFW_KEY_CAPS_LOCK, EventKeyboard::KeyCode::KEY_CAPS_LOCK}, + {GLFW_KEY_SCROLL_LOCK, EventKeyboard::KeyCode::KEY_SCROLL_LOCK}, + {GLFW_KEY_NUM_LOCK, EventKeyboard::KeyCode::KEY_NUM_LOCK}, + {GLFW_KEY_PRINT_SCREEN, EventKeyboard::KeyCode::KEY_PRINT}, + {GLFW_KEY_PAUSE, EventKeyboard::KeyCode::KEY_PAUSE}, + {GLFW_KEY_F1, EventKeyboard::KeyCode::KEY_F1}, + {GLFW_KEY_F2, EventKeyboard::KeyCode::KEY_F2}, + {GLFW_KEY_F3, EventKeyboard::KeyCode::KEY_F3}, + {GLFW_KEY_F4, EventKeyboard::KeyCode::KEY_F4}, + {GLFW_KEY_F5, EventKeyboard::KeyCode::KEY_F5}, + {GLFW_KEY_F6, EventKeyboard::KeyCode::KEY_F6}, + {GLFW_KEY_F7, EventKeyboard::KeyCode::KEY_F7}, + {GLFW_KEY_F8, EventKeyboard::KeyCode::KEY_F8}, + {GLFW_KEY_F9, EventKeyboard::KeyCode::KEY_F9}, + {GLFW_KEY_F10, EventKeyboard::KeyCode::KEY_F10}, + {GLFW_KEY_F11, EventKeyboard::KeyCode::KEY_F11}, + {GLFW_KEY_F12, EventKeyboard::KeyCode::KEY_F12}, + {GLFW_KEY_F13, EventKeyboard::KeyCode::KEY_NONE}, + {GLFW_KEY_F14, EventKeyboard::KeyCode::KEY_NONE}, + {GLFW_KEY_F15, EventKeyboard::KeyCode::KEY_NONE}, + {GLFW_KEY_F16, EventKeyboard::KeyCode::KEY_NONE}, + {GLFW_KEY_F17, EventKeyboard::KeyCode::KEY_NONE}, + {GLFW_KEY_F18, EventKeyboard::KeyCode::KEY_NONE}, + {GLFW_KEY_F19, EventKeyboard::KeyCode::KEY_NONE}, + {GLFW_KEY_F20, EventKeyboard::KeyCode::KEY_NONE}, + {GLFW_KEY_F21, EventKeyboard::KeyCode::KEY_NONE}, + {GLFW_KEY_F22, EventKeyboard::KeyCode::KEY_NONE}, + {GLFW_KEY_F23, EventKeyboard::KeyCode::KEY_NONE}, + {GLFW_KEY_F24, EventKeyboard::KeyCode::KEY_NONE}, + {GLFW_KEY_F25, EventKeyboard::KeyCode::KEY_NONE}, + {GLFW_KEY_KP_0, EventKeyboard::KeyCode::KEY_0}, + {GLFW_KEY_KP_1, EventKeyboard::KeyCode::KEY_1}, + {GLFW_KEY_KP_2, EventKeyboard::KeyCode::KEY_2}, + {GLFW_KEY_KP_3, EventKeyboard::KeyCode::KEY_3}, + {GLFW_KEY_KP_4, EventKeyboard::KeyCode::KEY_4}, + {GLFW_KEY_KP_5, EventKeyboard::KeyCode::KEY_5}, + {GLFW_KEY_KP_6, EventKeyboard::KeyCode::KEY_6}, + {GLFW_KEY_KP_7, EventKeyboard::KeyCode::KEY_7}, + {GLFW_KEY_KP_8, EventKeyboard::KeyCode::KEY_8}, + {GLFW_KEY_KP_9, EventKeyboard::KeyCode::KEY_9}, + {GLFW_KEY_KP_DECIMAL, EventKeyboard::KeyCode::KEY_PERIOD}, + {GLFW_KEY_KP_DIVIDE, EventKeyboard::KeyCode::KEY_KP_DIVIDE}, + {GLFW_KEY_KP_MULTIPLY, EventKeyboard::KeyCode::KEY_KP_MULTIPLY}, + {GLFW_KEY_KP_SUBTRACT, EventKeyboard::KeyCode::KEY_KP_MINUS}, + {GLFW_KEY_KP_ADD, EventKeyboard::KeyCode::KEY_KP_PLUS}, + {GLFW_KEY_KP_ENTER, EventKeyboard::KeyCode::KEY_KP_ENTER}, + {GLFW_KEY_KP_EQUAL, EventKeyboard::KeyCode::KEY_EQUAL}, + {GLFW_KEY_LEFT_SHIFT, EventKeyboard::KeyCode::KEY_LEFT_SHIFT}, + {GLFW_KEY_LEFT_CONTROL, EventKeyboard::KeyCode::KEY_LEFT_CTRL}, + {GLFW_KEY_LEFT_ALT, EventKeyboard::KeyCode::KEY_LEFT_ALT}, + {GLFW_KEY_LEFT_SUPER, EventKeyboard::KeyCode::KEY_HYPER}, + {GLFW_KEY_RIGHT_SHIFT, EventKeyboard::KeyCode::KEY_RIGHT_SHIFT}, + {GLFW_KEY_RIGHT_CONTROL, EventKeyboard::KeyCode::KEY_RIGHT_CTRL}, + {GLFW_KEY_RIGHT_ALT, EventKeyboard::KeyCode::KEY_RIGHT_ALT}, + {GLFW_KEY_RIGHT_SUPER, EventKeyboard::KeyCode::KEY_HYPER}, + {GLFW_KEY_MENU, EventKeyboard::KeyCode::KEY_MENU}, + {GLFW_KEY_LAST, EventKeyboard::KeyCode::KEY_NONE}}; ////////////////////////////////////////////////////////////////////////// // implement GLViewImpl ////////////////////////////////////////////////////////////////////////// - GLViewImpl::GLViewImpl(bool initglfw) -: _captured(false) -, _isInRetinaMonitor(false) -, _isRetinaEnabled(false) -, _retinaFactor(1) -, _frameZoomFactor(1.0f) -, _mainWindow(nullptr) -, _monitor(nullptr) -, _mouseX(0.0f) -, _mouseY(0.0f) + : _captured(false) + , _isInRetinaMonitor(false) + , _isRetinaEnabled(false) + , _retinaFactor(1) + , _frameZoomFactor(1.0f) + , _mainWindow(nullptr) + , _monitor(nullptr) + , _mouseX(0.0f) + , _mouseY(0.0f) { _viewName = "cocos2dx"; g_keyCodeMap.clear(); @@ -314,15 +309,16 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) glfwTerminate(); } -GLViewImpl* GLViewImpl::create(const std::string& viewName) +GLViewImpl* GLViewImpl::create(std::string_view viewName) { return GLViewImpl::create(viewName, false); } -GLViewImpl* GLViewImpl::create(const std::string& viewName, bool resizable) +GLViewImpl* GLViewImpl::create(std::string_view viewName, bool resizable) { auto ret = new GLViewImpl; - if(ret->initWithRect(viewName, Rect(0, 0, 960, 640), 1.0f, resizable)) { + if (ret->initWithRect(viewName, Rect(0, 0, 960, 640), 1.0f, resizable)) + { ret->autorelease(); return ret; } @@ -330,10 +326,11 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) return nullptr; } -GLViewImpl* GLViewImpl::createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable) +GLViewImpl* GLViewImpl::createWithRect(std::string_view viewName, Rect rect, float frameZoomFactor, bool resizable) { auto ret = new GLViewImpl; - if(ret->initWithRect(viewName, rect, frameZoomFactor, resizable)) { + if (ret->initWithRect(viewName, rect, frameZoomFactor, resizable)) + { ret->autorelease(); return ret; } @@ -341,10 +338,11 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) return nullptr; } -GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName) +GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName) { auto ret = new GLViewImpl(); - if(ret->initWithFullScreen(viewName)) { + if (ret->initWithFullScreen(viewName)) + { ret->autorelease(); return ret; } @@ -352,10 +350,13 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) return nullptr; } -GLViewImpl* GLViewImpl::createWithFullScreen(const std::string& viewName, const GLFWvidmode &videoMode, GLFWmonitor *monitor) +GLViewImpl* GLViewImpl::createWithFullScreen(std::string_view viewName, + const GLFWvidmode& videoMode, + GLFWmonitor* monitor) { auto ret = new GLViewImpl(); - if(ret->initWithFullscreen(viewName, videoMode, monitor)) { + if (ret->initWithFullscreen(viewName, videoMode, monitor)) + { ret->autorelease(); return ret; } @@ -363,28 +364,28 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) return nullptr; } -bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable) +bool GLViewImpl::initWithRect(std::string_view viewName, Rect rect, float frameZoomFactor, bool resizable) { setViewName(viewName); _frameZoomFactor = frameZoomFactor; - glfwWindowHint(GLFW_RESIZABLE,resizable?GL_TRUE:GL_FALSE); - glfwWindowHint(GLFW_RED_BITS,_glContextAttrs.redBits); - glfwWindowHint(GLFW_GREEN_BITS,_glContextAttrs.greenBits); - glfwWindowHint(GLFW_BLUE_BITS,_glContextAttrs.blueBits); - glfwWindowHint(GLFW_ALPHA_BITS,_glContextAttrs.alphaBits); - glfwWindowHint(GLFW_DEPTH_BITS,_glContextAttrs.depthBits); - glfwWindowHint(GLFW_STENCIL_BITS,_glContextAttrs.stencilBits); - + glfwWindowHint(GLFW_RESIZABLE, resizable ? GL_TRUE : GL_FALSE); + glfwWindowHint(GLFW_RED_BITS, _glContextAttrs.redBits); + glfwWindowHint(GLFW_GREEN_BITS, _glContextAttrs.greenBits); + glfwWindowHint(GLFW_BLUE_BITS, _glContextAttrs.blueBits); + glfwWindowHint(GLFW_ALPHA_BITS, _glContextAttrs.alphaBits); + glfwWindowHint(GLFW_DEPTH_BITS, _glContextAttrs.depthBits); + glfwWindowHint(GLFW_STENCIL_BITS, _glContextAttrs.stencilBits); + glfwWindowHint(GLFW_SAMPLES, _glContextAttrs.multisamplingCount); - + #if defined(CC_USE_METAL) // Don't create gl context. glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); #endif - int neededWidth = rect.size.width * _frameZoomFactor; + int neededWidth = rect.size.width * _frameZoomFactor; int neededHeight = rect.size.height * _frameZoomFactor; _mainWindow = glfwCreateWindow(neededWidth, neededHeight, _viewName.c_str(), _monitor, nullptr); @@ -401,13 +402,12 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) ccMessageBox(message.c_str(), "Error launch application"); return false; } - + int fbWidth, fbHeight; glfwGetFramebufferSize(_mainWindow, &fbWidth, &fbHeight); - - + CGSize size; - size.width = static_cast(fbWidth); + size.width = static_cast(fbWidth); size.height = static_cast(fbHeight); #if defined(CC_USE_METAL) @@ -420,7 +420,7 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) } NSView* contentView = [getCocoaWindow() contentView]; - [contentView setWantsLayer: YES]; + [contentView setWantsLayer:YES]; CAMetalLayer* layer = [CAMetalLayer layer]; [layer setDevice:device]; [layer setPixelFormat:MTLPixelFormatBGRA8Unorm]; @@ -431,15 +431,15 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) #endif /* - * Note that the created window and context may differ from what you requested, - * as not all parameters and hints are - * [hard constraints](@ref window_hints_hard). This includes the size of the - * window, especially for full screen windows. To retrieve the actual - * attributes of the created window and context, use queries like @ref - * glfwGetWindowAttrib and @ref glfwGetWindowSize. - * - * see declaration glfwCreateWindow - */ + * Note that the created window and context may differ from what you requested, + * as not all parameters and hints are + * [hard constraints](@ref window_hints_hard). This includes the size of the + * window, especially for full screen windows. To retrieve the actual + * attributes of the created window and context, use queries like @ref + * glfwGetWindowAttrib and @ref glfwGetWindowSize. + * + * see declaration glfwCreateWindow + */ int realW = 0, realH = 0; glfwGetWindowSize(_mainWindow, &realW, &realH); if (realW != neededWidth) @@ -470,9 +470,9 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) return true; } -bool GLViewImpl::initWithFullScreen(const std::string& viewName) +bool GLViewImpl::initWithFullScreen(std::string_view viewName) { - //Create fullscreen window on primary monitor at its current video mode. + // Create fullscreen window on primary monitor at its current video mode. _monitor = glfwGetPrimaryMonitor(); if (nullptr == _monitor) return false; @@ -481,19 +481,21 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) return initWithRect(viewName, Rect(0, 0, (float)videoMode->width, (float)videoMode->height), 1.0f, false); } -bool GLViewImpl::initWithFullscreen(const std::string &viewname, const GLFWvidmode &videoMode, GLFWmonitor *monitor) +bool GLViewImpl::initWithFullscreen(std::string_view viewname, const GLFWvidmode& videoMode, GLFWmonitor* monitor) { - //Create fullscreen on specified monitor at the specified video mode. + // Create fullscreen on specified monitor at the specified video mode. _monitor = monitor; if (nullptr == _monitor) return false; - - //These are soft constraints. If the video mode is retrieved at runtime, the resulting window and context should match these exactly. If invalid attribs are passed (eg. from an outdated cache), window creation will NOT fail but the actual window/context may differ. + + // These are soft constraints. If the video mode is retrieved at runtime, the resulting window and context should + // match these exactly. If invalid attribs are passed (eg. from an outdated cache), window creation will NOT fail + // but the actual window/context may differ. glfwWindowHint(GLFW_REFRESH_RATE, videoMode.refreshRate); glfwWindowHint(GLFW_RED_BITS, videoMode.redBits); glfwWindowHint(GLFW_BLUE_BITS, videoMode.blueBits); glfwWindowHint(GLFW_GREEN_BITS, videoMode.greenBits); - + return initWithRect(viewname, Rect(0, 0, (float)videoMode.width, (float)videoMode.height), 1.0f, false); } @@ -504,9 +506,9 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) void GLViewImpl::end() { - if(_mainWindow) + if (_mainWindow) { - glfwSetWindowShouldClose(_mainWindow,1); + glfwSetWindowShouldClose(_mainWindow, 1); _mainWindow = nullptr; } // Release self. Otherwise, GLViewImpl could not be freed. @@ -516,14 +518,14 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) void GLViewImpl::swapBuffers() { #if defined(CC_USE_GL) - if(_mainWindow) + if (_mainWindow) glfwSwapBuffers(_mainWindow); #endif } bool GLViewImpl::windowShouldClose() { - if(_mainWindow) + if (_mainWindow) return glfwWindowShouldClose(_mainWindow) ? true : false; else return true; @@ -536,49 +538,54 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) void GLViewImpl::enableRetina(bool enabled) { - _isRetinaEnabled = enabled; - if (_isRetinaEnabled) - { - _retinaFactor = 1; - } - else - { - _retinaFactor = 2; - } - updateFrameSize(); + _isRetinaEnabled = enabled; + if (_isRetinaEnabled) + { + _retinaFactor = 1; + } + else + { + _retinaFactor = 2; + } + updateFrameSize(); } - -void GLViewImpl::setIMEKeyboardState(bool /*bOpen*/) -{ - -} +void GLViewImpl::setIMEKeyboardState(bool /*bOpen*/) {} #if CC_ICON_SET_SUPPORT -void GLViewImpl::setIcon(const std::string& filename) const { +void GLViewImpl::setIcon(std::string_view filename) const +{ std::vector vec = {filename}; this->setIcon(vec); } -void GLViewImpl::setIcon(const std::vector& filelist) const { - if (filelist.empty()) return; +void GLViewImpl::setIcon(const std::vector& filelist) const +{ + if (filelist.empty()) + return; std::vector icons; - for (auto const& filename: filelist) { + for (auto const& filename : filelist) + { Image* icon = new Image(); - if (icon->initWithImageFile(filename)) { + if (icon->initWithImageFile(filename)) + { icons.push_back(icon); - } else { + } + else + { CC_SAFE_DELETE(icon); } } - if (icons.empty()) return; // No valid images + if (icons.empty()) + return; // No valid images size_t iconsCount = icons.size(); - auto images = new GLFWimage[iconsCount]; - for (size_t i = 0; i < iconsCount; i++) { - auto& image = images[i]; - auto& icon = icons[i]; - image.width = icon->getWidth(); + auto images = new GLFWimage[iconsCount]; + for (size_t i = 0; i < iconsCount; i++) + { + auto& image = images[i]; + auto& icon = icons[i]; + image.width = icon->getWidth(); image.height = icon->getHeight(); image.pixels = icon->getData(); }; @@ -587,23 +594,25 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) glfwSetWindowIcon(window, iconsCount, images); CC_SAFE_DELETE_ARRAY(images); - for (auto& icon: icons) { + for (auto& icon : icons) + { CC_SAFE_DELETE(icon); } } -void GLViewImpl::setDefaultIcon() const { +void GLViewImpl::setDefaultIcon() const +{ GLFWwindow* window = this->getWindow(); glfwSetWindowIcon(window, 0, nullptr); } #endif /* CC_ICON_SET_SUPPORT */ -void GLViewImpl::setCursorVisible( bool isVisible ) +void GLViewImpl::setCursorVisible(bool isVisible) { - if( _mainWindow == NULL ) + if (_mainWindow == NULL) return; - - if( isVisible ) + + if (isVisible) glfwSetInputMode(_mainWindow, GLFW_CURSOR, GLFW_CURSOR_NORMAL); else glfwSetInputMode(_mainWindow, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); @@ -627,7 +636,8 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) return _frameZoomFactor; } -bool GLViewImpl::isFullscreen() const { +bool GLViewImpl::isFullscreen() const +{ return (_monitor != nullptr); } @@ -636,9 +646,11 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) setFullscreen(-1, -1, -1); } -void GLViewImpl::setFullscreen(int w, int h, int refreshRate) { +void GLViewImpl::setFullscreen(int w, int h, int refreshRate) +{ auto monitor = glfwGetPrimaryMonitor(); - if (nullptr == monitor || monitor == _monitor) { + if (nullptr == monitor || monitor == _monitor) + { return; } this->setFullscreen(monitor, w, h, refreshRate); @@ -649,20 +661,24 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) setFullscreen(monitorIndex, -1, -1, -1); } -void GLViewImpl::setFullscreen(int monitorIndex, int w, int h, int refreshRate) { - int count = 0; +void GLViewImpl::setFullscreen(int monitorIndex, int w, int h, int refreshRate) +{ + int count = 0; GLFWmonitor** monitors = glfwGetMonitors(&count); - if (monitorIndex < 0 || monitorIndex >= count) { + if (monitorIndex < 0 || monitorIndex >= count) + { return; } GLFWmonitor* monitor = monitors[monitorIndex]; - if (nullptr == monitor || _monitor == monitor) { + if (nullptr == monitor || _monitor == monitor) + { return; } this->setFullscreen(monitor, w, h, refreshRate); } -void GLViewImpl::setFullscreen(GLFWmonitor *monitor, int w, int h, int refreshRate) { +void GLViewImpl::setFullscreen(GLFWmonitor* monitor, int w, int h, int refreshRate) +{ _monitor = monitor; const GLFWvidmode* videoMode = glfwGetVideoMode(_monitor); @@ -678,10 +694,14 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) updateWindowSize(); } -void GLViewImpl::setWindowed(int width, int height) { - if (!this->isFullscreen()) { +void GLViewImpl::setWindowed(int width, int height) +{ + if (!this->isFullscreen()) + { this->setFrameSize((float)width, (float)height); - } else { + } + else + { const GLFWvidmode* videoMode = glfwGetVideoMode(_monitor); int xpos = 0, ypos = 0; glfwGetMonitorPos(_monitor, &xpos, &ypos); @@ -702,31 +722,36 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) { int w = 0, h = 0; glfwGetFramebufferSize(_mainWindow, &w, &h); - int frameWidth = w / _frameZoomFactor; + int frameWidth = w / _frameZoomFactor; int frameHeight = h / _frameZoomFactor; setFrameSize(frameWidth, frameHeight); updateDesignResolutionSize(); Director::getInstance()->getEventDispatcher()->dispatchCustomEvent(GLViewImpl::EVENT_WINDOW_RESIZED, nullptr); } -int GLViewImpl::getMonitorCount() const { +int GLViewImpl::getMonitorCount() const +{ int count = 0; glfwGetMonitors(&count); return count; } -Size GLViewImpl::getMonitorSize() const { +Size GLViewImpl::getMonitorSize() const +{ GLFWmonitor* monitor = _monitor; - if (nullptr == monitor) { + if (nullptr == monitor) + { GLFWwindow* window = this->getWindow(); - monitor = glfwGetWindowMonitor(window); + monitor = glfwGetWindowMonitor(window); } - if (nullptr == monitor) { + if (nullptr == monitor) + { monitor = glfwGetPrimaryMonitor(); } - if (nullptr != monitor) { + if (nullptr != monitor) + { const GLFWvidmode* videoMode = glfwGetVideoMode(monitor); - Size size = Size((float)videoMode->width, (float)videoMode->height); + Size size = Size((float)videoMode->width, (float)videoMode->height); return size; } return Size::ZERO; @@ -752,7 +777,8 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) { _retinaFactor = 2; } - glfwSetWindowSize(_mainWindow, _screenSize.width/2 * _retinaFactor * _frameZoomFactor, _screenSize.height/2 * _retinaFactor * _frameZoomFactor); + glfwSetWindowSize(_mainWindow, _screenSize.width / 2 * _retinaFactor * _frameZoomFactor, + _screenSize.height / 2 * _retinaFactor * _frameZoomFactor); _isInRetinaMonitor = true; } @@ -762,7 +788,8 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) { _retinaFactor = 1; } - glfwSetWindowSize(_mainWindow, (int)(_screenSize.width * _retinaFactor * _frameZoomFactor), (int)(_screenSize.height *_retinaFactor * _frameZoomFactor)); + glfwSetWindowSize(_mainWindow, (int)(_screenSize.width * _retinaFactor * _frameZoomFactor), + (int)(_screenSize.height * _retinaFactor * _frameZoomFactor)); _isInRetinaMonitor = false; } @@ -775,22 +802,26 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) updateFrameSize(); } -void GLViewImpl::setViewPortInPoints(float x , float y , float w , float h) +void GLViewImpl::setViewPortInPoints(float x, float y, float w, float h) { Viewport vp; - vp.x = (int)(x * _scaleX * _retinaFactor * _frameZoomFactor + _viewPortRect.origin.x * _retinaFactor * _frameZoomFactor); - vp.y = (int)(y * _scaleY * _retinaFactor * _frameZoomFactor + _viewPortRect.origin.y * _retinaFactor * _frameZoomFactor); + vp.x = (int)(x * _scaleX * _retinaFactor * _frameZoomFactor + + _viewPortRect.origin.x * _retinaFactor * _frameZoomFactor); + vp.y = (int)(y * _scaleY * _retinaFactor * _frameZoomFactor + + _viewPortRect.origin.y * _retinaFactor * _frameZoomFactor); vp.w = (unsigned int)(w * _scaleX * _retinaFactor * _frameZoomFactor); vp.h = (unsigned int)(h * _scaleY * _retinaFactor * _frameZoomFactor); Camera::setDefaultViewport(vp); } -void GLViewImpl::setScissorInPoints(float x , float y , float w , float h) +void GLViewImpl::setScissorInPoints(float x, float y, float w, float h) { - auto x1 = (int)(x * _scaleX * _retinaFactor * _frameZoomFactor + _viewPortRect.origin.x * _retinaFactor * _frameZoomFactor); - auto y1 = (int)(y * _scaleY * _retinaFactor * _frameZoomFactor + _viewPortRect.origin.y * _retinaFactor * _frameZoomFactor); - auto width1 = (unsigned int)(w * _scaleX * _retinaFactor * _frameZoomFactor); - auto height1 = (unsigned int)(h * _scaleY * _retinaFactor * _frameZoomFactor); + auto x1 = (int)(x * _scaleX * _retinaFactor * _frameZoomFactor + + _viewPortRect.origin.x * _retinaFactor * _frameZoomFactor); + auto y1 = (int)(y * _scaleY * _retinaFactor * _frameZoomFactor + + _viewPortRect.origin.y * _retinaFactor * _frameZoomFactor); + auto width1 = (unsigned int)(w * _scaleX * _retinaFactor * _frameZoomFactor); + auto height1 = (unsigned int)(h * _scaleY * _retinaFactor * _frameZoomFactor); auto renderer = Director::getInstance()->getRenderer(); renderer->setScissorRect(x1, y1, width1, height1); } @@ -798,12 +829,14 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) Rect GLViewImpl::getScissorRect() const { auto renderer = Director::getInstance()->getRenderer(); - auto& rect = renderer->getScissorRect(); + auto& rect = renderer->getScissorRect(); - float x = (rect.x - _viewPortRect.origin.x * _retinaFactor * _frameZoomFactor) / (_scaleX * _retinaFactor * _frameZoomFactor); - float y = (rect.y - _viewPortRect.origin.y * _retinaFactor * _frameZoomFactor) / (_scaleY * _retinaFactor * _frameZoomFactor); + float x = (rect.x - _viewPortRect.origin.x * _retinaFactor * _frameZoomFactor) / + (_scaleX * _retinaFactor * _frameZoomFactor); + float y = (rect.y - _viewPortRect.origin.y * _retinaFactor * _frameZoomFactor) / + (_scaleY * _retinaFactor * _frameZoomFactor); float w = rect.width / (_scaleX * _retinaFactor * _frameZoomFactor); - float h = rect.height / (_scaleY * _retinaFactor * _frameZoomFactor); + float h = rect.height / (_scaleY * _retinaFactor * _frameZoomFactor); return Rect(x, y, w, h); } @@ -822,40 +855,41 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) void GLViewImpl::onGLFWMouseCallBack(GLFWwindow* /*window*/, int button, int action, int /*modify*/) { - if(GLFW_MOUSE_BUTTON_LEFT == button) + if (GLFW_MOUSE_BUTTON_LEFT == button) { - if(GLFW_PRESS == action) + if (GLFW_PRESS == action) { _captured = true; - if (this->getViewPortRect().equals(Rect::ZERO) || this->getViewPortRect().containsPoint(Vec2(_mouseX,_mouseY))) + if (this->getViewPortRect().equals(Rect::ZERO) || + this->getViewPortRect().containsPoint(Vec2(_mouseX, _mouseY))) { intptr_t id = 0; this->handleTouchesBegin(1, &id, &_mouseX, &_mouseY); } } - else if(GLFW_RELEASE == action) + else if (GLFW_RELEASE == action) { if (_captured) { - _captured = false; + _captured = false; intptr_t id = 0; this->handleTouchesEnd(1, &id, &_mouseX, &_mouseY); } } } - - //Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here + + // Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here float cursorX = (_mouseX - _viewPortRect.origin.x) / _scaleX; float cursorY = (_viewPortRect.origin.y + _viewPortRect.size.height - _mouseY) / _scaleY; - if(GLFW_PRESS == action) + if (GLFW_PRESS == action) { EventMouse event(EventMouse::MouseEventType::MOUSE_DOWN); event.setCursorPosition(cursorX, cursorY); event.setMouseButton(static_cast(button)); Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); } - else if(GLFW_RELEASE == action) + else if (GLFW_RELEASE == action) { EventMouse event(EventMouse::MouseEventType::MOUSE_UP); event.setCursorPosition(cursorX, cursorY); @@ -886,8 +920,8 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) intptr_t id = 0; this->handleTouchesMove(1, &id, &_mouseX, &_mouseY); } - - //Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here + + // Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here float cursorX = (_mouseX - _viewPortRect.origin.x) / _scaleX; float cursorY = (_viewPortRect.origin.y + _viewPortRect.size.height - _mouseY) / _scaleY; @@ -912,7 +946,7 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) void GLViewImpl::onGLFWMouseScrollCallback(GLFWwindow* /*window*/, double x, double y) { EventMouse event(EventMouse::MouseEventType::MOUSE_SCROLL); - //Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here + // Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here float cursorX = (_mouseX - _viewPortRect.origin.x) / _scaleX; float cursorY = (_viewPortRect.origin.y + _viewPortRect.size.height - _mouseY) / _scaleY; event.setScrollData((float)x, -(float)y); @@ -952,26 +986,26 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) void GLViewImpl::onGLFWCharCallback(GLFWwindow* /*window*/, unsigned int character) { - char16_t wcharString[2] = { (char16_t) character, 0 }; + char16_t wcharString[2] = {(char16_t)character, 0}; std::string utf8String; - StringUtils::UTF16ToUTF8( wcharString, utf8String ); + StringUtils::UTF16ToUTF8(wcharString, utf8String); static std::set controlUnicode = { - "\xEF\x9C\x80", // up - "\xEF\x9C\x81", // down - "\xEF\x9C\x82", // left - "\xEF\x9C\x83", // right - "\xEF\x9C\xA8", // delete - "\xEF\x9C\xA9", // home - "\xEF\x9C\xAB", // end - "\xEF\x9C\xAC", // pageup - "\xEF\x9C\xAD", // pagedown - "\xEF\x9C\xB9" // clear + "\xEF\x9C\x80", // up + "\xEF\x9C\x81", // down + "\xEF\x9C\x82", // left + "\xEF\x9C\x83", // right + "\xEF\x9C\xA8", // delete + "\xEF\x9C\xA9", // home + "\xEF\x9C\xAB", // end + "\xEF\x9C\xAC", // pageup + "\xEF\x9C\xAD", // pagedown + "\xEF\x9C\xB9" // clear }; // Check for send control key if (controlUnicode.find(utf8String) == controlUnicode.end()) { - IMEDispatcher::sharedDispatcher()->dispatchInsertText( utf8String.c_str(), utf8String.size() ); + IMEDispatcher::sharedDispatcher()->dispatchInsertText(utf8String.c_str(), utf8String.size()); } } @@ -984,18 +1018,18 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) { if (width && height && _resolutionPolicy != ResolutionPolicy::UNKNOWN) { - Size baseDesignSize = _designResolutionSize; + Size baseDesignSize = _designResolutionSize; ResolutionPolicy baseResolutionPolicy = _resolutionPolicy; - int frameWidth = width / _frameZoomFactor; + int frameWidth = width / _frameZoomFactor; int frameHeight = height / _frameZoomFactor; setFrameSize(frameWidth, frameHeight); setDesignResolutionSize(baseDesignSize.width, baseDesignSize.height, baseResolutionPolicy); Director::getInstance()->setViewport(); Director::getInstance()->getEventDispatcher()->dispatchCustomEvent(GLViewImpl::EVENT_WINDOW_RESIZED, nullptr); - + #if defined(CC_USE_METAL) - //update metal attachment texture size. + // update metal attachment texture size. int fbWidth, fbHeight; glfwGetFramebufferSize(_mainWindow, &fbWidth, &fbHeight); backend::UtilsMTL::resizeDefaultAttachmentTexture(fbWidth, fbHeight); @@ -1027,4 +1061,4 @@ static void onGLFWWindowFocusCallback(GLFWwindow* window, int focused) } } -NS_CC_END // end of namespace cocos2d; +NS_CC_END // end of namespace cocos2d; diff --git a/cocos/platform/win32/CCApplication-win32.cpp b/cocos/platform/win32/CCApplication-win32.cpp index 3f51532ce9c0..ea159d973b98 100644 --- a/cocos/platform/win32/CCApplication-win32.cpp +++ b/cocos/platform/win32/CCApplication-win32.cpp @@ -287,14 +287,14 @@ std::string Application::getVersion() return verString; } -bool Application::openURL(const std::string& url) +bool Application::openURL(std::string_view url) { std::wstring wURL = ntcvt::from_chars(url, CP_UTF8); HINSTANCE r = ShellExecuteW(NULL, L"open", wURL.c_str(), NULL, NULL, SW_SHOWNORMAL); return (size_t)r > 32; } -void Application::setResourceRootPath(const std::string& rootResDir) +void Application::setResourceRootPath(std::string_view rootResDir) { _resourceRootPath = rootResDir; std::replace(_resourceRootPath.begin(), _resourceRootPath.end(), '\\', '/'); @@ -308,12 +308,12 @@ void Application::setResourceRootPath(const std::string& rootResDir) pFileUtils->setSearchPaths(searchPaths); } -const std::string& Application::getResourceRootPath(void) +std::string_view Application::getResourceRootPath(void) { return _resourceRootPath; } -void Application::setStartupScriptFilename(const std::string& startupScriptFile) +void Application::setStartupScriptFilename(std::string_view startupScriptFile) { _startupScriptFilename = startupScriptFile; std::replace(_startupScriptFilename.begin(), _startupScriptFilename.end(), '\\', '/'); diff --git a/cocos/platform/win32/CCApplication-win32.h b/cocos/platform/win32/CCApplication-win32.h index 011100a3f229..56fcc81e849c 100644 --- a/cocos/platform/win32/CCApplication-win32.h +++ b/cocos/platform/win32/CCApplication-win32.h @@ -78,23 +78,23 @@ class CC_DLL Application : public ApplicationProtocol @param String with url to open. @return true if the resource located by the URL was successfully opened; otherwise false. */ - virtual bool openURL(const std::string& url); + virtual bool openURL(std::string_view url); /** * Sets the Resource root path. * @deprecated Please use FileUtils::getInstance()->setSearchPaths() instead. */ - CC_DEPRECATED_ATTRIBUTE void setResourceRootPath(const std::string& rootResDir); + CC_DEPRECATED_ATTRIBUTE void setResourceRootPath(std::string_view rootResDir); /** * Gets the Resource root path. * @deprecated Please use FileUtils::getInstance()->getSearchPaths() instead. */ - CC_DEPRECATED_ATTRIBUTE const std::string& getResourceRootPath(); + CC_DEPRECATED_ATTRIBUTE std::string_view getResourceRootPath(); - void setStartupScriptFilename(const std::string& startupScriptFile); + void setStartupScriptFilename(std::string_view startupScriptFile); - const std::string& getStartupScriptFilename() { return _startupScriptFilename; } + std::string_view getStartupScriptFilename() { return _startupScriptFilename; } protected: HINSTANCE _instance; diff --git a/cocos/platform/win32/CCFileUtils-win32.cpp b/cocos/platform/win32/CCFileUtils-win32.cpp index 1dd25374afe9..3b70dd413b66 100644 --- a/cocos/platform/win32/CCFileUtils-win32.cpp +++ b/cocos/platform/win32/CCFileUtils-win32.cpp @@ -26,7 +26,6 @@ THE SOFTWARE. ****************************************************************************/ #include "platform/win32/CCFileUtils-win32.h" #include "platform/CCCommon.h" -#include "tinydir/tinydir.h" #include #include #include @@ -45,14 +44,14 @@ NS_CC_BEGIN // The root path of resources, the character encoding is UTF-8. // UTF-8 is the only encoding supported by adxe API by default. -static std::string s_workingPath = ""; -static std::string s_exePath = ""; +static std::wstring s_workingPath; +static std::string s_exePath; // D:\aaa\bbb\ccc\ddd\abc.txt --> D:/aaa/bbb/ccc/ddd/abc.txt -static std::string convertPathFormatToUnixStyle(const std::string& path) +static std::string convertPathFormatToUnixStyle(std::string_view path) { - std::string ret = path; - int len = ret.length(); + std::string ret{path}; + int len = ret.length(); for (int i = 0; i < len; ++i) { if (ret[i] == '\\') @@ -63,6 +62,20 @@ static std::string convertPathFormatToUnixStyle(const std::string& path) return ret; } +static std::string convertPathFormatToWinStyle(std::string_view path) +{ + std::string ret{path}; + int len = ret.length(); + for (int i = 0; i < len; ++i) + { + if (ret[i] == '/') + { + ret[i] = '\\'; + } + } + return ret; +} + static void _checkWorkingPath() { if (s_workingPath.empty()) @@ -70,15 +83,9 @@ static void _checkWorkingPath() WCHAR utf16Path[CC_MAX_PATH] = {0}; int nNum = GetCurrentDirectoryW(CC_MAX_PATH - 2, utf16Path); - char utf8WorkingDir[CC_MAX_PATH] = {0}; - nNum = - WideCharToMultiByte(CP_UTF8, 0, utf16Path, nNum, utf8WorkingDir, sizeof(utf8WorkingDir), nullptr, nullptr); - if (nNum < (CC_MAX_PATH - 2)) - { - utf8WorkingDir[nNum] = '\\'; - utf8WorkingDir[nNum + 1] = '\0'; - s_workingPath = convertPathFormatToUnixStyle(utf8WorkingDir); - } + s_workingPath.reserve(nNum + 1); + s_workingPath.assign(utf16Path, nNum); + s_workingPath.push_back('\\'); } } @@ -121,25 +128,26 @@ bool FileUtilsWin32::init() DECLARE_GUARD; _checkWorkingPath(); - _defaultResRootPath = s_workingPath; + _defaultResRootPath = ntcvt::from_chars(s_workingPath); + _defaultResRootPathUtf16 = s_workingPath; bool bRet = FileUtils::init(); _checkExePath(); - if (s_workingPath != s_exePath) + if (_defaultResRootPath != s_exePath) addSearchPath(s_exePath); return bRet; } -bool FileUtilsWin32::isDirectoryExistInternal(const std::string& dirPath) const +bool FileUtilsWin32::isDirectoryExistInternal(std::string_view dirPath) const { uint32_t fAttrib = GetFileAttributesW(ntcvt::from_chars(dirPath).c_str()); return (fAttrib != INVALID_FILE_ATTRIBUTES && (fAttrib & FILE_ATTRIBUTE_DIRECTORY)); } -bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const +bool FileUtilsWin32::isFileExistInternal(std::string_view strFilePath) const { DECLARE_GUARD; if (strFilePath.empty()) @@ -147,17 +155,19 @@ bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const return false; } - std::string strPath = strFilePath; - if (!isAbsolutePath(strPath)) + std::wstring strPathUtf16; + if (!isAbsolutePath(strFilePath)) { // Not absolute path, add the default root path at the beginning. - strPath.insert(0, _defaultResRootPath); + strPathUtf16.insert(0, _defaultResRootPathUtf16); } + else + strPathUtf16 = ntcvt::from_chars(strFilePath); - DWORD attr = GetFileAttributesW(ntcvt::from_chars(strPath).c_str()); + DWORD attr = GetFileAttributesW(strPathUtf16.c_str()); return (attr != INVALID_FILE_ATTRIBUTES && !(attr & FILE_ATTRIBUTE_DIRECTORY)); } -FileUtils::Status FileUtilsWin32::getContents(const std::string& filename, ResizableBuffer* buffer) const +FileUtils::Status FileUtilsWin32::getContents(std::string_view filename, ResizableBuffer* buffer) const { if (filename.empty()) return FileUtils::Status::NotExists; @@ -199,9 +209,9 @@ FileUtils::Status FileUtilsWin32::getContents(const std::string& filename, Resiz return FileUtils::Status::OK; } -std::string FileUtilsWin32::getPathForFilename(const std::string& filename, - const std::string& resolutionDirectory, - const std::string& searchPath) const +std::string FileUtilsWin32::getPathForFilename(std::string_view filename, + std::string_view resolutionDirectory, + std::string_view searchPath) const { std::string unixFileName = convertPathFormatToUnixStyle(filename); std::string unixResolutionDirectory = convertPathFormatToUnixStyle(resolutionDirectory); @@ -210,8 +220,8 @@ std::string FileUtilsWin32::getPathForFilename(const std::string& filename, return FileUtils::getPathForFilename(unixFileName, unixResolutionDirectory, unixSearchPath); } -std::string FileUtilsWin32::getFullPathForFilenameWithinDirectory(const std::string& strDirectory, - const std::string& strFilename) const +std::string FileUtilsWin32::getFullPathForFilenameWithinDirectory(std::string_view strDirectory, + std::string_view strFilename) const { std::string unixDirectory = convertPathFormatToUnixStyle(strDirectory); std::string unixFilename = convertPathFormatToUnixStyle(strFilename); @@ -219,53 +229,7 @@ std::string FileUtilsWin32::getFullPathForFilenameWithinDirectory(const std::str return FileUtils::getFullPathForFilenameWithinDirectory(unixDirectory, unixFilename); } -void FileUtilsWin32::listFilesRecursively(const std::string& dirPath, std::vector* files) const -{ - std::string fullpath = fullPathForDirectory(dirPath); - if (isDirectoryExist(fullpath)) - { - tinydir_dir dir; - std::wstring fullpathstr = ntcvt::from_chars(fullpath); - - if (tinydir_open(&dir, &fullpathstr[0]) != -1) - { - while (dir.has_next) - { - tinydir_file file; - if (tinydir_readfile(&dir, &file) == -1) - { - // Error getting file - break; - } - std::string fileName = ntcvt::from_chars(file.name); - - if (fileName != "." && fileName != "..") - { - std::string filepath = ntcvt::from_chars(file.path); - if (file.is_dir) - { - filepath.push_back('/'); - files->push_back(filepath); - listFilesRecursively(filepath, files); - } - else - { - files->push_back(std::move(filepath)); - } - } - - if (tinydir_next(&dir) == -1) - { - // Error getting next file - break; - } - } - } - tinydir_close(&dir); - } -} - -int64_t FileUtilsWin32::getFileSize(const std::string& filepath) const +int64_t FileUtilsWin32::getFileSize(std::string_view filepath) const { if (filepath.empty()) return -1; @@ -276,49 +240,6 @@ int64_t FileUtilsWin32::getFileSize(const std::string& filepath) const return -1; } -std::vector FileUtilsWin32::listFiles(const std::string& dirPath) const -{ - std::string fullpath = fullPathForDirectory(dirPath); - std::vector files; - if (isDirectoryExist(fullpath)) - { - tinydir_dir dir; - std::wstring fullpathstr = ntcvt::from_chars(fullpath); - - if (tinydir_open(&dir, &fullpathstr[0]) != -1) - { - while (dir.has_next) - { - tinydir_file file; - if (tinydir_readfile(&dir, &file) == -1) - { - // Error getting file - break; - } - - std::string fileName = ntcvt::from_chars(file.name); - if (fileName != "." && fileName != "..") - { - std::string filepath = ntcvt::from_chars(file.path); - if (file.is_dir) - { - filepath.push_back('/'); - } - files.push_back(std::move(filepath)); - } - - if (tinydir_next(&dir) == -1) - { - // Error getting next file - break; - } - } - } - tinydir_close(&dir); - } - return files; -} - std::string FileUtilsWin32::getWritablePath() const { DECLARE_GUARD; @@ -380,7 +301,7 @@ std::string FileUtilsWin32::getNativeWritableAbsolutePath() const return convertPathFormatToUnixStyle(ntcvt::from_chars(retPath)); } -bool FileUtilsWin32::renameFile(const std::string& oldfullpath, const std::string& newfullpath) const +bool FileUtilsWin32::renameFile(std::string_view oldfullpath, std::string_view newfullpath) const { CCASSERT(!oldfullpath.empty(), "Invalid path"); CCASSERT(!newfullpath.empty(), "Invalid path"); @@ -392,7 +313,7 @@ bool FileUtilsWin32::renameFile(const std::string& oldfullpath, const std::strin { if (!DeleteFile(_wNew.c_str())) { - CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newfullpath.c_str(), GetLastError()); + CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newfullpath.data(), GetLastError()); } } @@ -402,17 +323,19 @@ bool FileUtilsWin32::renameFile(const std::string& oldfullpath, const std::strin } else { - CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldfullpath.c_str(), newfullpath.c_str(), + CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldfullpath.data(), newfullpath.data(), GetLastError()); return false; } } -bool FileUtilsWin32::renameFile(const std::string& path, const std::string& oldname, const std::string& name) const +bool FileUtilsWin32::renameFile(std::string_view path, std::string_view oldname, std::string_view name) const { CCASSERT(!path.empty(), "Invalid path"); - std::string oldPath = path + oldname; - std::string newPath = path + name; + std::string oldPath{path}; + oldPath += oldname; + std::string newPath{path}; + newPath += name; std::regex pat("\\/"); std::string _old = std::regex_replace(oldPath, pat, "\\"); @@ -421,7 +344,7 @@ bool FileUtilsWin32::renameFile(const std::string& path, const std::string& oldn return renameFile(_old, _new); } -bool FileUtilsWin32::createDirectory(const std::string& dirPath) const +bool FileUtilsWin32::createDirectory(std::string_view dirPath) const { CCASSERT(!dirPath.empty(), "Invalid path"); @@ -478,10 +401,9 @@ bool FileUtilsWin32::createDirectory(const std::string& dirPath) const return true; } -bool FileUtilsWin32::removeFile(const std::string& filepath) const +bool FileUtilsWin32::removeFile(std::string_view filepath) const { - std::regex pat("\\/"); - std::string win32path = std::regex_replace(filepath, pat, "\\"); + std::string win32path = convertPathFormatToWinStyle(filepath); if (DeleteFileW(ntcvt::from_chars(win32path).c_str())) { @@ -489,14 +411,14 @@ bool FileUtilsWin32::removeFile(const std::string& filepath) const } else { - CCLOGERROR("Fail remove file %s !Error code is 0x%x", filepath.c_str(), GetLastError()); + CCLOGERROR("Fail remove file %s !Error code is 0x%x", filepath.data(), GetLastError()); return false; } } -bool FileUtilsWin32::removeDirectory(const std::string& dirPath) const +bool FileUtilsWin32::removeDirectory(std::string_view dirPath) const { - std::string dirPathCopy = dirPath; + std::string dirPathCopy{dirPath}; if (!dirPath.empty() && dirPath[dirPath.length() - 1] != '/' && dirPath[dirPath.length() - 1] != '\\') { dirPathCopy.push_back('/'); diff --git a/cocos/platform/win32/CCFileUtils-win32.h b/cocos/platform/win32/CCFileUtils-win32.h index 5188e7f83aea..d68f8c54aa93 100644 --- a/cocos/platform/win32/CCFileUtils-win32.h +++ b/cocos/platform/win32/CCFileUtils-win32.h @@ -53,7 +53,7 @@ class CC_DLL FileUtilsWin32 : public FileUtils virtual std::string getNativeWritableAbsolutePath() const override; protected: - virtual bool isFileExistInternal(const std::string& strFilePath) const override; + virtual bool isFileExistInternal(std::string_view strFilePath) const override; /** * Renames a file under the given directory. @@ -63,9 +63,7 @@ class CC_DLL FileUtilsWin32 : public FileUtils * @param name The new name of the file. * @return True if the file have been renamed successfully, false if not. */ - virtual bool renameFile(const std::string& path, - const std::string& oldname, - const std::string& name) const override; + virtual bool renameFile(std::string_view path, std::string_view oldname, std::string_view name) const override; /** * Renames a file under the given directory. @@ -74,14 +72,14 @@ class CC_DLL FileUtilsWin32 : public FileUtils * @param newfullpath The new path + name of the file. * @return True if the file have been renamed successfully, false if not. */ - virtual bool renameFile(const std::string& oldfullpath, const std::string& newfullpath) const override; + virtual bool renameFile(std::string_view oldfullpath, std::string_view newfullpath) const override; /** * Checks whether a directory exists without considering search paths and resolution orders. * @param dirPath The directory (with absolute path) to look up for * @return Returns true if the directory found at the given absolute path, otherwise returns false */ - virtual bool isDirectoryExistInternal(const std::string& dirPath) const override; + virtual bool isDirectoryExistInternal(std::string_view dirPath) const override; /** * Removes a file. @@ -89,7 +87,7 @@ class CC_DLL FileUtilsWin32 : public FileUtils * @param filepath The full path of the file, it must be an absolute path. * @return True if the file have been removed successfully, false if not. */ - virtual bool removeFile(const std::string& filepath) const override; + virtual bool removeFile(std::string_view filepath) const override; /** * Creates a directory. @@ -97,7 +95,7 @@ class CC_DLL FileUtilsWin32 : public FileUtils * @param dirPath The path of the directory, it must be an absolute path. * @return True if the directory have been created successfully, false if not. */ - virtual bool createDirectory(const std::string& dirPath) const override; + virtual bool createDirectory(std::string_view dirPath) const override; /** * Removes a directory. @@ -105,11 +103,11 @@ class CC_DLL FileUtilsWin32 : public FileUtils * @param dirPath The full path of the directory, it must be an absolute path. * @return True if the directory have been removed successfully, false if not. */ - virtual bool removeDirectory(const std::string& dirPath) const override; + virtual bool removeDirectory(std::string_view dirPath) const override; - virtual FileUtils::Status getContents(const std::string& filename, ResizableBuffer* buffer) const override; + virtual FileUtils::Status getContents(std::string_view filename, ResizableBuffer* buffer) const override; - virtual int64_t getFileSize(const std::string& filepath) const override; + virtual int64_t getFileSize(std::string_view filepath) const override; /** * Gets full path for filename, resolution directory and search path. @@ -119,9 +117,9 @@ class CC_DLL FileUtilsWin32 : public FileUtils * @param searchPath The search path. * @return The full path of the file. It will return an empty string if the full path of the file doesn't exist. */ - virtual std::string getPathForFilename(const std::string& filename, - const std::string& resolutionDirectory, - const std::string& searchPath) const override; + virtual std::string getPathForFilename(std::string_view filename, + std::string_view resolutionDirectory, + std::string_view searchPath) const override; /** * Gets full path for the directory and the filename. @@ -133,24 +131,11 @@ class CC_DLL FileUtilsWin32 : public FileUtils * @param filename The name of the file. * @return The full path of the file, if the file can't be found, it will return an empty string. */ - virtual std::string getFullPathForFilenameWithinDirectory(const std::string& directory, - const std::string& filename) const override; + virtual std::string getFullPathForFilenameWithinDirectory(std::string_view directory, + std::string_view filename) const override; - /** - * List all files in a directory. - * - * @param dirPath The path of the directory, it could be a relative or an absolute path. - * @return File paths in a string vector - */ - virtual std::vector listFiles(const std::string& dirPath) const override; - - /** - * List all files recursively in a directory. - * - * @param dirPath The path of the directory, it could be a relative or an absolute path. - * @return File paths in a string vector - */ - virtual void listFilesRecursively(const std::string& dirPath, std::vector* files) const override; +private: + std::wstring_view _defaultResRootPathUtf16; }; // end of platform group diff --git a/cocos/renderer/CCMaterial.cpp b/cocos/renderer/CCMaterial.cpp index 17a43f39b939..da4aeb7cf106 100644 --- a/cocos/renderer/CCMaterial.cpp +++ b/cocos/renderer/CCMaterial.cpp @@ -48,7 +48,7 @@ NS_CC_BEGIN namespace { -std::string replaceDefines(const std::string& compileTimeDefines) +std::string replaceDefines(std::string_view compileTimeDefines) { auto defineParts = Console::Utility::split(compileTimeDefines, ';'); @@ -72,7 +72,7 @@ std::string replaceDefines(const std::string& compileTimeDefines) static const char* getOptionalString(Properties* properties, const char* key, const char* defaultValue); static bool isValidUniform(const char* name); -Material* Material::createWithFilename(const std::string& filepath) +Material* Material::createWithFilename(std::string_view filepath) { auto validfilename = FileUtils::getInstance()->fullPathForFilename(filepath); if (!validfilename.empty()) @@ -130,7 +130,7 @@ bool Material::initWithProgramState(backend::ProgramState* state) return false; } -bool Material::initWithFile(const std::string& validfilename) +bool Material::initWithFile(std::string_view validfilename) { // Warning: properties is not a "Ref" object, must be manually deleted Properties* properties = Properties::createNonRefCounted(validfilename); @@ -496,7 +496,7 @@ bool Material::parseRenderState(RenderState::StateBlock* state, Properties* prop return true; } -void Material::setName(const std::string& name) +void Material::setName(std::string_view name) { _name = name; } @@ -542,7 +542,7 @@ const Vector& Material::getTechniques() const return _techniques; } -Technique* Material::getTechniqueByName(const std::string& name) +Technique* Material::getTechniqueByName(std::string_view name) { for (const auto& technique : _techniques) { @@ -564,7 +564,7 @@ void Material::addTechnique(Technique* technique) _techniques.pushBack(technique); } -void Material::setTechnique(const std::string& techniqueName) +void Material::setTechnique(std::string_view techniqueName) { auto technique = getTechniqueByName(techniqueName); if (technique) diff --git a/cocos/renderer/CCMaterial.h b/cocos/renderer/CCMaterial.h index acc8ccdda2e8..bc94addc47cb 100644 --- a/cocos/renderer/CCMaterial.h +++ b/cocos/renderer/CCMaterial.h @@ -78,7 +78,7 @@ class CC_DLL Material : public Ref * * @return A new Material or NULL if there was an error. */ - static Material* createWithFilename(const std::string& path); + static Material* createWithFilename(std::string_view path); /** Creates a Material with a GLProgramState. It will only contain one Technique and one Pass. @@ -107,12 +107,12 @@ class CC_DLL Material : public Ref /// returns the material name std::string getName() const; /// sets the material name - void setName(const std::string& name); + void setName(std::string_view name); /** Returns a Technique by its name. returns `nullptr` if the Technique can't be found. */ - Technique* getTechniqueByName(const std::string& name); + Technique* getTechniqueByName(std::string_view name); /** Returns a Technique by index. returns `nullptr` if the index is invalid. @@ -132,7 +132,7 @@ class CC_DLL Material : public Ref void addTechnique(Technique* technique); /** Sets the current technique */ - void setTechnique(const std::string& techniqueName); + void setTechnique(std::string_view techniqueName); /** returns a clone (deep-copy) of the material */ virtual Material* clone() const; @@ -147,7 +147,7 @@ class CC_DLL Material : public Ref Material(); ~Material(); bool initWithProgramState(backend::ProgramState* state); - bool initWithFile(const std::string& file); + bool initWithFile(std::string_view file); bool initWithProperties(Properties* materialProperties); void setTarget(Node* target); diff --git a/cocos/renderer/CCPass.h b/cocos/renderer/CCPass.h index ee095d854fae..483112611e64 100644 --- a/cocos/renderer/CCPass.h +++ b/cocos/renderer/CCPass.h @@ -94,8 +94,8 @@ class CC_DLL Pass : public Ref */ VertexAttribBinding* getVertexAttributeBinding() const; - void setName(const std::string& name) { _name = name; } - const std::string& getName() const { return _name; } + void setName(std::string_view name) { _name = name; } + std::string_view getName() const { return _name; } inline RenderState::StateBlock& getStateBlock() { return _renderState._state; } diff --git a/cocos/renderer/CCRenderState.cpp b/cocos/renderer/CCRenderState.cpp index 4a1b8821d7a6..690af0e4595e 100644 --- a/cocos/renderer/CCRenderState.cpp +++ b/cocos/renderer/CCRenderState.cpp @@ -183,12 +183,12 @@ void RenderState::StateBlock::restoreUnmodifiedStates(int32_t overrideBits, Pipe } } -static bool parseBoolean(const std::string& value) +static bool parseBoolean(std::string_view value) { return (value.compare("true") == 0); } -static backend::BlendFactor parseBlend(const std::string& value) +static backend::BlendFactor parseBlend(std::string_view value) { // Convert the string to uppercase for comparison. std::string upper(value); @@ -222,12 +222,12 @@ static backend::BlendFactor parseBlend(const std::string& value) else { CCLOG("Unsupported blend value (%s). (Will default to BLEND_ONE if errors are treated as warnings)", - value.c_str()); + value.data()); return backend::BlendFactor::ONE; } } -static DepthFunction parseDepthFunc(const std::string& value) +static DepthFunction parseDepthFunc(std::string_view value) { // Convert string to uppercase for comparison std::string upper(value); @@ -251,12 +251,12 @@ static DepthFunction parseDepthFunc(const std::string& value) else { CCLOG("Unsupported depth function value (%s). Will default to DEPTH_LESS if errors are treated as warnings)", - value.c_str()); + value.data()); return DepthFunction::LESS; } } -static CullFaceSide parseCullFaceSide(const std::string& value) +static CullFaceSide parseCullFaceSide(std::string_view value) { // Convert string to uppercase for comparison std::string upper(value); @@ -271,12 +271,12 @@ static CullFaceSide parseCullFaceSide(const std::string& value) else { CCLOG("Unsupported cull face side value (%s). Will default to BACK if errors are treated as warnings.", - value.c_str()); + value.data()); return CullFaceSide::BACK; } } -static FrontFace parseFrontFace(const std::string& value) +static FrontFace parseFrontFace(std::string_view value) { // Convert string to uppercase for comparison std::string upper(value); @@ -288,12 +288,12 @@ static FrontFace parseFrontFace(const std::string& value) else { CCLOG("Unsupported front face side value (%s). Will default to CCW if errors are treated as warnings.", - value.c_str()); + value.data()); return FrontFace::COUNTER_CLOCK_WISE; } } -void RenderState::StateBlock::setState(const std::string& name, const std::string& value) +void RenderState::StateBlock::setState(std::string_view name, std::string_view value) { if (name.compare("blend") == 0) { @@ -333,7 +333,7 @@ void RenderState::StateBlock::setState(const std::string& name, const std::strin } else { - CCLOG("Unsupported render state string '%s'.", name.c_str()); + CCLOG("Unsupported render state string '%s'.", name.data()); } } diff --git a/cocos/renderer/CCRenderState.h b/cocos/renderer/CCRenderState.h index 3e94b36afbee..27fd7c497394 100644 --- a/cocos/renderer/CCRenderState.h +++ b/cocos/renderer/CCRenderState.h @@ -194,7 +194,7 @@ class CC_DLL RenderState : public Ref * @param name Name of the render state to set. * @param value Value of the specified render state. */ - void setState(const std::string& name, const std::string& value); + void setState(std::string_view name, std::string_view value); uint32_t getHash() const; bool isDirty() const; diff --git a/cocos/renderer/CCTechnique.cpp b/cocos/renderer/CCTechnique.cpp index 88e5ee9e8beb..bc7e20896aa6 100644 --- a/cocos/renderer/CCTechnique.cpp +++ b/cocos/renderer/CCTechnique.cpp @@ -98,7 +98,7 @@ std::string Technique::getName() const return _name; } -void Technique::setName(const std::string& name) +void Technique::setName(std::string_view name) { _name = name; } diff --git a/cocos/renderer/CCTechnique.h b/cocos/renderer/CCTechnique.h index aaf4c937d861..6c7641b557bb 100644 --- a/cocos/renderer/CCTechnique.h +++ b/cocos/renderer/CCTechnique.h @@ -91,7 +91,7 @@ class CC_DLL Technique : public Ref ~Technique(); bool init(Material* parent); - void setName(const std::string& name); + void setName(std::string_view name); RenderState _renderState; std::string _name; Vector _passes; diff --git a/cocos/renderer/CCTexture2D.cpp b/cocos/renderer/CCTexture2D.cpp index 55995f8d5a9b..a81f654cd320 100644 --- a/cocos/renderer/CCTexture2D.cpp +++ b/cocos/renderer/CCTexture2D.cpp @@ -460,7 +460,7 @@ bool Texture2D::initWithImage(Image* image, backend::PixelFormat format) // implementation Texture2D (Text) bool Texture2D::initWithString(const char* text, - const std::string& fontName, + std::string_view fontName, float fontSize, const Vec2& dimensions /* = Vec2(0, 0)*/, TextHAlignment hAlignment /* = TextHAlignment::CENTER */, @@ -741,7 +741,7 @@ void Texture2D::initProgram() // setup vertex layout auto vertexLayout = _programState->getVertexLayout(); - auto& attributes = _programState->getProgram()->getActiveAttributes(); + auto attributes = _programState->getProgram()->getActiveAttributes(); auto iter = attributes.find("a_position"); if (iter != attributes.end()) vertexLayout->setAttribute("a_position", iter->second.location, backend::VertexFormat::FLOAT2, 0, false); diff --git a/cocos/renderer/CCTexture2D.h b/cocos/renderer/CCTexture2D.h index 19afa6192876..9d4fb89c8493 100644 --- a/cocos/renderer/CCTexture2D.h +++ b/cocos/renderer/CCTexture2D.h @@ -273,7 +273,7 @@ class CC_DLL Texture2D : public Ref @param overflow Whether shrink font size when content larger than the dimensions. */ bool initWithString(const char* text, - const std::string& fontName, + std::string_view fontName, float fontSize, const Vec2& dimensions = Vec2(0, 0), TextHAlignment hAlignment = TextHAlignment::CENTER, diff --git a/cocos/renderer/CCTextureAtlas.cpp b/cocos/renderer/CCTextureAtlas.cpp index 5617481f5553..0810493c9f20 100644 --- a/cocos/renderer/CCTextureAtlas.cpp +++ b/cocos/renderer/CCTextureAtlas.cpp @@ -99,7 +99,7 @@ void TextureAtlas::setQuads(V3F_C4B_T2F_Quad* quads) // TextureAtlas - alloc & init -TextureAtlas* TextureAtlas::create(const std::string& file, ssize_t capacity) +TextureAtlas* TextureAtlas::create(std::string_view file, ssize_t capacity) { TextureAtlas* textureAtlas = new TextureAtlas(); if (textureAtlas->initWithFile(file, capacity)) @@ -123,7 +123,7 @@ TextureAtlas* TextureAtlas::createWithTexture(Texture2D* texture, ssize_t capaci return nullptr; } -bool TextureAtlas::initWithFile(const std::string& file, ssize_t capacity) +bool TextureAtlas::initWithFile(std::string_view file, ssize_t capacity) { // retained in property Texture2D* texture = Director::getInstance()->getTextureCache()->addImage(file); @@ -134,7 +134,7 @@ bool TextureAtlas::initWithFile(const std::string& file, ssize_t capacity) } else { - CCLOG("cocos2d: Could not open file: %s", file.c_str()); + CCLOG("cocos2d: Could not open file: %s", file.data()); return false; } } diff --git a/cocos/renderer/CCTextureAtlas.h b/cocos/renderer/CCTextureAtlas.h index 0f8abffd2621..e088f3e95ffd 100644 --- a/cocos/renderer/CCTextureAtlas.h +++ b/cocos/renderer/CCTextureAtlas.h @@ -68,7 +68,7 @@ class CC_DLL TextureAtlas : public Ref @param file The file path. @param capacity Capacity for Quads. */ - static TextureAtlas* create(const std::string& file, ssize_t capacity); + static TextureAtlas* create(std::string_view file, ssize_t capacity); /** Creates a TextureAtlas with a previously initialized Texture2D object, and * with an initial capacity for n Quads. @@ -95,7 +95,7 @@ class CC_DLL TextureAtlas : public Ref @param file The file path. @param capacity Capacity for Quads. */ - bool initWithFile(const std::string& file, ssize_t capacity); + bool initWithFile(std::string_view file, ssize_t capacity); /** Initializes a TextureAtlas with a previously initialized Texture2D object, and * with an initial capacity for Quads. diff --git a/cocos/renderer/CCTextureCache.cpp b/cocos/renderer/CCTextureCache.cpp index 3315479d7b1d..f99bcfc4de20 100644 --- a/cocos/renderer/CCTextureCache.cpp +++ b/cocos/renderer/CCTextureCache.cpp @@ -52,7 +52,7 @@ std::string TextureCache::s_etc1AlphaFileSuffix = "@alpha"; // implementation TextureCache -void TextureCache::setETC1AlphaFileSuffix(const std::string& suffix) +void TextureCache::setETC1AlphaFileSuffix(std::string_view suffix) { s_etc1AlphaFileSuffix = suffix; } @@ -82,7 +82,7 @@ std::string TextureCache::getDescription() const struct TextureCache::AsyncStruct { public: - AsyncStruct(const std::string& fn, const std::function& f, const std::string& key) + AsyncStruct(std::string_view fn, const std::function& f, std::string_view key) : filename(fn) , callback(f) , callbackKey(key) @@ -131,7 +131,7 @@ struct TextureCache::AsyncStruct Call unbindImageAsync(path) to prevent the call to the callback when the texture is loaded. */ -void TextureCache::addImageAsync(const std::string& path, const std::function& callback) +void TextureCache::addImageAsync(std::string_view path, const std::function& callback) { addImageAsync(path, callback, path); } @@ -170,9 +170,9 @@ void TextureCache::addImageAsync(const std::string& path, const std::function& callback, - const std::string& callbackKey) + std::string_view callbackKey) { Texture2D* texture = nullptr; @@ -223,7 +223,7 @@ void TextureCache::addImageAsync(const std::string& path, _sleepCondition.notify_one(); } -void TextureCache::unbindImageAsync(const std::string& callbackKey) +void TextureCache::unbindImageAsync(std::string_view callbackKey) { if (_asyncStructQueue.empty()) { @@ -383,7 +383,7 @@ void TextureCache::addImageAsyncCallBack(float /*dt*/) } } -Texture2D* TextureCache::addImage(const std::string& path) +Texture2D* TextureCache::addImage(std::string_view path) { Texture2D* texture = nullptr; Image* image = nullptr; @@ -422,7 +422,8 @@ Texture2D* TextureCache::addImage(const std::string& path) _textures.emplace(fullpath, texture); //-- ANDROID ETC1 ALPHA SUPPORTS. - std::string alphaFullPath = path + s_etc1AlphaFileSuffix; + std::string alphaFullPath{path}; + alphaFullPath += s_etc1AlphaFileSuffix; if (image->getFileType() == Image::Format::ETC1 && !s_etc1AlphaFileSuffix.empty() && FileUtils::getInstance()->isFileExist(alphaFullPath)) { @@ -438,7 +439,7 @@ Texture2D* TextureCache::addImage(const std::string& path) } else { - CCLOG("cocos2d: Couldn't create texture for file:%s in TextureCache", path.c_str()); + CCLOG("cocos2d: Couldn't create texture for file:%s in TextureCache", path.data()); CC_SAFE_RELEASE(texture); texture = nullptr; } @@ -450,7 +451,7 @@ Texture2D* TextureCache::addImage(const std::string& path) return texture; } -void TextureCache::parseNinePatchImage(cocos2d::Image* image, cocos2d::Texture2D* texture, const std::string& path) +void TextureCache::parseNinePatchImage(cocos2d::Image* image, cocos2d::Texture2D* texture, std::string_view path) { if (NinePatchImageParser::isNinePatchImage(path)) { @@ -460,7 +461,7 @@ void TextureCache::parseNinePatchImage(cocos2d::Image* image, cocos2d::Texture2D } } -Texture2D* TextureCache::addImage(Image* image, const std::string& key) +Texture2D* TextureCache::addImage(Image* image, std::string_view key) { CCASSERT(image != nullptr, "TextureCache: image MUST not be nil"); CCASSERT(image->getData() != nullptr, "TextureCache: image MUST not be nil"); @@ -497,7 +498,7 @@ Texture2D* TextureCache::addImage(Image* image, const std::string& key) return texture; } -bool TextureCache::reloadTexture(const std::string& fileName) +bool TextureCache::reloadTexture(std::string_view fileName) { Texture2D* texture = nullptr; @@ -585,15 +586,14 @@ void TextureCache::removeTexture(Texture2D* texture) } } -void TextureCache::removeTextureForKey(const std::string& textureKeyName) +void TextureCache::removeTextureForKey(std::string_view textureKeyName) { - std::string key = textureKeyName; - auto it = _textures.find(key); + auto it = _textures.find(textureKeyName); if (it == _textures.end()) { - key = FileUtils::getInstance()->fullPathForFilename(textureKeyName); - it = _textures.find(key); + auto key = FileUtils::getInstance()->fullPathForFilename(textureKeyName); + it = _textures.find(key); } if (it != _textures.end()) @@ -603,15 +603,14 @@ void TextureCache::removeTextureForKey(const std::string& textureKeyName) } } -Texture2D* TextureCache::getTextureForKey(const std::string& textureKeyName) const +Texture2D* TextureCache::getTextureForKey(std::string_view textureKeyName) const { - std::string key = textureKeyName; - auto it = _textures.find(key); + auto it = _textures.find(textureKeyName); if (it == _textures.end()) { - key = FileUtils::getInstance()->fullPathForFilename(textureKeyName); - it = _textures.find(key); + auto key = FileUtils::getInstance()->fullPathForFilename(textureKeyName); + it = _textures.find(key); } if (it != _textures.end()) @@ -676,15 +675,14 @@ std::string TextureCache::getCachedTextureInfo() const return buffer; } -void TextureCache::renameTextureWithKey(const std::string& srcName, const std::string& dstName) +void TextureCache::renameTextureWithKey(std::string_view srcName, std::string_view dstName) { - std::string key = srcName; - auto it = _textures.find(key); + auto it = _textures.find(srcName); if (it == _textures.end()) { - key = FileUtils::getInstance()->fullPathForFilename(srcName); - it = _textures.find(key); + auto key = FileUtils::getInstance()->fullPathForFilename(srcName); + it = _textures.find(key); } if (it != _textures.end()) @@ -723,7 +721,7 @@ VolatileTexture::~VolatileTexture() CC_SAFE_RELEASE(_uiImage); } -void VolatileTextureMgr::addImageTexture(Texture2D* tt, const std::string& imageFileName) +void VolatileTextureMgr::addImageTexture(Texture2D* tt, std::string_view imageFileName) { if (_isReloading) { @@ -866,9 +864,7 @@ void VolatileTextureMgr::reloadAllTextures() _isReloading = false; } -void VolatileTextureMgr::reloadTexture(Texture2D* texture, - const std::string& filename, - backend::PixelFormat pixelFormat) +void VolatileTextureMgr::reloadTexture(Texture2D* texture, std::string_view filename, backend::PixelFormat pixelFormat) { if (!texture) return; diff --git a/cocos/renderer/CCTextureCache.h b/cocos/renderer/CCTextureCache.h index 2aca398febfd..f06643675861 100644 --- a/cocos/renderer/CCTextureCache.h +++ b/cocos/renderer/CCTextureCache.h @@ -64,7 +64,7 @@ class CC_DLL TextureCache : public Ref { public: // ETC1 ALPHA supports. - static void setETC1AlphaFileSuffix(const std::string& suffix); + static void setETC1AlphaFileSuffix(std::string_view suffix); static std::string getETC1AlphaFileSuffix(); public: @@ -92,7 +92,7 @@ class CC_DLL TextureCache : public Ref * Supported image extensions: .png, .bmp, .jpeg, .pvr. @param filepath The file path. */ - Texture2D* addImage(const std::string& filepath); + Texture2D* addImage(std::string_view filepath); /** Returns a Texture2D object given a file image. * If the file image was not previously loaded, it will create a new Texture2D object and it will return it. @@ -104,11 +104,11 @@ class CC_DLL TextureCache : public Ref @param callback A callback function would be invoked after the image is loaded. @since v0.8 */ - virtual void addImageAsync(const std::string& filepath, const std::function& callback); + virtual void addImageAsync(std::string_view filepath, const std::function& callback); - void addImageAsync(const std::string& path, + void addImageAsync(std::string_view path, const std::function& callback, - const std::string& callbackKey); + std::string_view callbackKey); /** Unbind a specified bound image asynchronous callback. * In the case an object who was bound to an image asynchronous callback was destroyed before the callback is @@ -116,7 +116,7 @@ class CC_DLL TextureCache : public Ref * @param filename It's the related/absolute path of the file image. * @since v3.1 */ - virtual void unbindImageAsync(const std::string& filename); + virtual void unbindImageAsync(std::string_view filename); /** Unbind all bound image asynchronous load callbacks. * @since v3.1 @@ -129,13 +129,13 @@ class CC_DLL TextureCache : public Ref * @param key The "key" parameter will be used as the "key" for the cache. * If "key" is nil, then a new texture will be created each time. */ - Texture2D* addImage(Image* image, const std::string& key); + Texture2D* addImage(Image* image, std::string_view key); /** Returns an already created texture. Returns nil if the texture doesn't exist. @param key It's the related/absolute path of the file image. @since v0.99.5 */ - Texture2D* getTextureForKey(const std::string& key) const; + Texture2D* getTextureForKey(std::string_view key) const; /** Reload texture from the image file. * If the file image hasn't loaded before, load it. @@ -143,7 +143,7 @@ class CC_DLL TextureCache : public Ref * @param fileName It's the related/absolute path of the file image. * @return True if the reloading is succeed, otherwise return false. */ - bool reloadTexture(const std::string& fileName); + bool reloadTexture(std::string_view fileName); /** Purges the dictionary of loaded textures. * Call this method if you receive the "Memory Warning". @@ -168,7 +168,7 @@ class CC_DLL TextureCache : public Ref @param key It's the related/absolute path of the file image. @since v0.99.4 */ - void removeTextureForKey(const std::string& key); + void removeTextureForKey(std::string_view key); /** Output to CCLOG the current contents of this TextureCache. * This will attempt to calculate the size of each texture, and the total texture memory in use. @@ -198,12 +198,12 @@ class CC_DLL TextureCache : public Ref * * @since v3.10 */ - void renameTextureWithKey(const std::string& srcName, const std::string& dstName); + void renameTextureWithKey(std::string_view srcName, std::string_view dstName); private: void addImageAsyncCallBack(float dt); void loadImage(); - void parseNinePatchImage(Image* image, Texture2D* texture, const std::string& path); + void parseNinePatchImage(Image* image, Texture2D* texture, std::string_view path); public: protected: @@ -224,7 +224,7 @@ class CC_DLL TextureCache : public Ref int _asyncRefCount; - std::unordered_map _textures; + hlookup::string_map _textures; static std::string s_etc1AlphaFileSuffix; }; @@ -272,7 +272,7 @@ class VolatileTexture class CC_DLL VolatileTextureMgr { public: - static void addImageTexture(Texture2D* tt, const std::string& imageFileName); + static void addImageTexture(Texture2D* tt, std::string_view imageFileName); static void addStringTexture(Texture2D* tt, const char* text, const FontDefinition& fontDefinition); static void addDataTexture(Texture2D* tt, void* data, @@ -292,7 +292,7 @@ class CC_DLL VolatileTextureMgr static VolatileTexture* findVolotileTexture(Texture2D* tt); private: - static void reloadTexture(Texture2D* texture, const std::string& filename, backend::PixelFormat pixelFormat); + static void reloadTexture(Texture2D* texture, std::string_view filename, backend::PixelFormat pixelFormat); }; #endif diff --git a/cocos/renderer/CCTextureCube.cpp b/cocos/renderer/CCTextureCube.cpp index d7a7929cb434..9a757b226423 100644 --- a/cocos/renderer/CCTextureCube.cpp +++ b/cocos/renderer/CCTextureCube.cpp @@ -119,7 +119,7 @@ unsigned char* getImageData(Image* img, backend::PixelFormat& ePixFmt) return pTmpData; } -Image* createImage(const std::string& path) +Image* createImage(std::string_view path) { // Split up directory and filename // MUTEX: @@ -150,12 +150,12 @@ TextureCube::~TextureCube() CC_SAFE_RELEASE_NULL(_texture); } -TextureCube* TextureCube::create(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z) +TextureCube* TextureCube::create(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z) { auto ret = new TextureCube(); if (ret->init(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z)) @@ -167,12 +167,12 @@ TextureCube* TextureCube::create(const std::string& positive_x, return nullptr; } -bool TextureCube::init(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z) +bool TextureCube::init(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z) { _imgPath[0] = positive_x; _imgPath[1] = negative_x; diff --git a/cocos/renderer/CCTextureCube.h b/cocos/renderer/CCTextureCube.h index 99ee3f1c3eb4..578c32eccac7 100644 --- a/cocos/renderer/CCTextureCube.h +++ b/cocos/renderer/CCTextureCube.h @@ -56,12 +56,12 @@ class CC_DLL TextureCube : public Ref @param negative_z texture for the rear side of the texture cube face. @return A new texture cube inited with given parameters. */ - static TextureCube* create(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z); + static TextureCube* create(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z); /** Sets the min filter, mag filter, wrap s and wrap t texture parameters. If the texture size is NPOT (non power of 2), then in can only use GL_CLAMP_TO_EDGE in GL_TEXTURE_WRAP_{S,T}. @@ -86,12 +86,12 @@ class CC_DLL TextureCube : public Ref virtual ~TextureCube(); protected: - bool init(const std::string& positive_x, - const std::string& negative_x, - const std::string& positive_y, - const std::string& negative_y, - const std::string& positive_z, - const std::string& negative_z); + bool init(std::string_view positive_x, + std::string_view negative_x, + std::string_view positive_y, + std::string_view negative_y, + std::string_view positive_z, + std::string_view negative_z); private: std::vector _imgPath; diff --git a/cocos/renderer/backend/Device.h b/cocos/renderer/backend/Device.h index fbf8934bc597..27a498e334a7 100644 --- a/cocos/renderer/backend/Device.h +++ b/cocos/renderer/backend/Device.h @@ -125,7 +125,7 @@ class CC_DLL Device : public cocos2d::Ref * @param fragmentShader Specifes this is a fragment shader source. * @return A Program instance. */ - virtual Program* newProgram(const std::string& vertexShader, const std::string& fragmentShader) = 0; + virtual Program* newProgram(std::string_view vertexShader, std::string_view fragmentShader) = 0; /** * Get a DeviceInfo object. @@ -140,7 +140,7 @@ class CC_DLL Device : public cocos2d::Ref * @param source Specifies shader source. * @return A ShaderModule object. */ - virtual ShaderModule* newShaderModule(ShaderStage stage, const std::string& source) = 0; + virtual ShaderModule* newShaderModule(ShaderStage stage, std::string_view source) = 0; DeviceInfo* _deviceInfo = nullptr; ///< Device information. diff --git a/cocos/renderer/backend/Program.cpp b/cocos/renderer/backend/Program.cpp index 4c3da6cfaab0..b92ab3d0b24b 100644 --- a/cocos/renderer/backend/Program.cpp +++ b/cocos/renderer/backend/Program.cpp @@ -27,7 +27,7 @@ CC_BACKEND_BEGIN -Program::Program(const std::string& vs, const std::string& fs) : _vertexShader(vs), _fragmentShader(fs) {} +Program::Program(std::string_view vs, std::string_view fs) : _vertexShader(vs), _fragmentShader(fs) {} void Program::setProgramType(uint32_t type) { diff --git a/cocos/renderer/backend/Program.h b/cocos/renderer/backend/Program.h index 3cc20bdf216c..fceb28f8f456 100644 --- a/cocos/renderer/backend/Program.h +++ b/cocos/renderer/backend/Program.h @@ -60,7 +60,7 @@ class CC_DLL Program : public Ref * @param uniform Specifies the uniform name. * @return The uniform location. */ - virtual UniformLocation getUniformLocation(const std::string& uniform) const = 0; + virtual UniformLocation getUniformLocation(std::string_view uniform) const = 0; /** * Get uniform location by engine built-in uniform enum name. @@ -74,7 +74,7 @@ class CC_DLL Program : public Ref * @param name Specifies the attribute name. * @return The attribute location. */ - virtual int getAttributeLocation(const std::string& name) const = 0; + virtual int getAttributeLocation(std::string_view name) const = 0; /** * Get attribute location by engine built-in attribute enum name. @@ -99,19 +99,19 @@ class CC_DLL Program : public Ref * Get active vertex attributes. * @return Active vertex attributes. key is active attribute name, Value is corresponding attribute info. */ - virtual const std::unordered_map getActiveAttributes() const = 0; + virtual const hlookup::string_map getActiveAttributes() const = 0; /** * Get vertex shader. * @return Vertex shader. */ - const std::string& getVertexShader() const { return _vertexShader; } + std::string_view getVertexShader() const { return _vertexShader; } /** * Get fragment shader. * @ Fragment shader. */ - const std::string& getFragmentShader() const { return _fragmentShader; } + std::string_view getFragmentShader() const { return _fragmentShader; } /** * Get engine built-in program type. @@ -138,7 +138,7 @@ class CC_DLL Program : public Ref * Get all uniformInfos. * @return The uniformInfos. */ - virtual const std::unordered_map& getAllActiveUniformInfo(ShaderStage stage) const = 0; + virtual const hlookup::string_map& getAllActiveUniformInfo(ShaderStage stage) const = 0; /** * Set engin built-in program type. @@ -151,7 +151,7 @@ class CC_DLL Program : public Ref * @param vs Specifes the vertex shader source. * @param fs Specifes the fragment shader source. */ - Program(const std::string& vs, const std::string& fs); + Program(std::string_view vs, std::string_view fs); #if CC_ENABLE_CACHE_TEXTURE_DATA /** diff --git a/cocos/renderer/backend/ProgramState.cpp b/cocos/renderer/backend/ProgramState.cpp index 8eacbc2bb658..79e036e3e08b 100644 --- a/cocos/renderer/backend/ProgramState.cpp +++ b/cocos/renderer/backend/ProgramState.cpp @@ -263,7 +263,7 @@ backend::UniformLocation ProgramState::getUniformLocation(backend::Uniform name) return _program->getUniformLocation(name); } -backend::UniformLocation ProgramState::getUniformLocation(const std::string& uniform) const +backend::UniformLocation ProgramState::getUniformLocation(std::string_view uniform) const { return _program->getUniformLocation(uniform); } @@ -514,13 +514,13 @@ void ProgramState::setTextureArray(int location, #endif } -void ProgramState::setParameterAutoBinding(const std::string& uniform, const std::string& autoBinding) +void ProgramState::setParameterAutoBinding(std::string_view uniform, std::string_view autoBinding) { _autoBindings.emplace(uniform, autoBinding); applyAutoBinding(uniform, autoBinding); } -void ProgramState::applyAutoBinding(const std::string& uniformName, const std::string& autoBinding) +void ProgramState::applyAutoBinding(std::string_view uniformName, std::string_view autoBinding) { for (const auto resolver : _customAutoBindingResolvers) { diff --git a/cocos/renderer/backend/ProgramState.h b/cocos/renderer/backend/ProgramState.h index 7a5f756e616b..8c31ca96858a 100644 --- a/cocos/renderer/backend/ProgramState.h +++ b/cocos/renderer/backend/ProgramState.h @@ -124,7 +124,7 @@ class CC_DLL ProgramState : public Ref * @return Uniform location. * @see `backend::UniformLocation getUniformLocation(backend::Uniform name) const` */ - backend::UniformLocation getUniformLocation(const std::string& uniform) const; + backend::UniformLocation getUniformLocation(std::string_view uniform) const; /** * Get uniform location in a more efficient way by the given built-in uniform name. @@ -138,15 +138,15 @@ class CC_DLL ProgramState : public Ref * Get an attribute location by the actual attribute name. * @param name Specifies the attribute name. * @return Attribute location. - * @see `int getAttributeLocation(const std::string& name) const` + * @see `int getAttributeLocation(std::string_view name) const` */ - inline int getAttributeLocation(const std::string& name) const { return _program->getAttributeLocation(name); } + inline int getAttributeLocation(std::string_view name) const { return _program->getAttributeLocation(name); } /** * Get an attribute location by the engine built-in attribute name. * @param name Specifies the built-in attribute name. * @return Attribute location. - * @see `int getAttributeLocation(const std::string& name) const` + * @see `int getAttributeLocation(std::string_view name) const` */ inline int getAttributeLocation(Attribute name) const { return _program->getAttributeLocation(name); } @@ -278,9 +278,7 @@ class CC_DLL ProgramState : public Ref * @return True if the auto binding is handled and the associated parameter is * bound, false otherwise. */ - virtual bool resolveAutoBinding(ProgramState*, - const std::string& uniformName, - const std::string& autoBinding) = 0; + virtual bool resolveAutoBinding(ProgramState*, std::string_view uniformName, std::string_view autoBinding) = 0; }; /** * Sets a uniform auto-binding. @@ -292,7 +290,7 @@ class CC_DLL ProgramState : public Ref * @param uniformName The name of the material parameter to store an auto-binding for. * @param autoBinding A string matching one of the built-in AutoBinding enum constants. */ - void setParameterAutoBinding(const std::string& uniformName, const std::string& autoBinding); + void setParameterAutoBinding(std::string_view uniformName, std::string_view autoBinding); inline std::shared_ptr getVertexLayout() const { return _vertexLayout; } @@ -379,7 +377,7 @@ class CC_DLL ProgramState : public Ref * @param uniformName Name of the shader uniform. * @param autoBinding Name of the auto binding. */ - void applyAutoBinding(const std::string&, const std::string&); + void applyAutoBinding(std::string_view, std::string_view); backend::Program* _program = nullptr; std::unordered_map _callbackUniforms; diff --git a/cocos/renderer/backend/ShaderCache.cpp b/cocos/renderer/backend/ShaderCache.cpp index 7d92c21ba71d..149fc2fcb7e0 100644 --- a/cocos/renderer/backend/ShaderCache.cpp +++ b/cocos/renderer/backend/ShaderCache.cpp @@ -62,21 +62,21 @@ bool ShaderCache::init() return true; } -backend::ShaderModule* ShaderCache::newVertexShaderModule(const std::string& shaderSource) +backend::ShaderModule* ShaderCache::newVertexShaderModule(std::string_view shaderSource) { auto vertexShaderModule = newShaderModule(backend::ShaderStage::VERTEX, shaderSource); return vertexShaderModule; } -backend::ShaderModule* ShaderCache::newFragmentShaderModule(const std::string& shaderSource) +backend::ShaderModule* ShaderCache::newFragmentShaderModule(std::string_view shaderSource) { auto fragmenShaderModule = newShaderModule(backend::ShaderStage::FRAGMENT, shaderSource); return fragmenShaderModule; } -backend::ShaderModule* ShaderCache::newShaderModule(backend::ShaderStage stage, const std::string& shaderSource) +backend::ShaderModule* ShaderCache::newShaderModule(backend::ShaderStage stage, std::string_view shaderSource) { - std::size_t key = std::hash{}(shaderSource); + std::size_t key = std::hash{}(shaderSource); auto iter = _cachedShaders.find(key); if (_cachedShaders.end() != iter) return iter->second; diff --git a/cocos/renderer/backend/ShaderCache.h b/cocos/renderer/backend/ShaderCache.h index d5daf870aeb7..87709042f598 100644 --- a/cocos/renderer/backend/ShaderCache.h +++ b/cocos/renderer/backend/ShaderCache.h @@ -54,14 +54,14 @@ class CC_DLL ShaderCache : public Ref * If it is created before, then just return the cached shader module. * @param shaderSource The source code of the shader. */ - static backend::ShaderModule* newVertexShaderModule(const std::string& shaderSource); + static backend::ShaderModule* newVertexShaderModule(std::string_view shaderSource); /** * Create a fragment shader module. * If it is created before, then just return the cached shader module. * @param shaderSource The source code of the shader. */ - static backend::ShaderModule* newFragmentShaderModule(const std::string& shaderSource); + static backend::ShaderModule* newFragmentShaderModule(std::string_view shaderSource); /** * Remove all unused shaders. @@ -85,7 +85,7 @@ class CC_DLL ShaderCache : public Ref * @param source Specifies shader source. * @return A ShaderModule object. */ - static backend::ShaderModule* newShaderModule(backend::ShaderStage stage, const std::string& shaderSource); + static backend::ShaderModule* newShaderModule(backend::ShaderStage stage, std::string_view shaderSource); static std::unordered_map _cachedShaders; static ShaderCache* _sharedShaderCache; diff --git a/cocos/renderer/backend/VertexLayout.cpp b/cocos/renderer/backend/VertexLayout.cpp index 044a2661c032..fbd4be4d3e8d 100644 --- a/cocos/renderer/backend/VertexLayout.cpp +++ b/cocos/renderer/backend/VertexLayout.cpp @@ -28,7 +28,7 @@ CC_BACKEND_BEGIN -void VertexLayout::setAttribute(const std::string& name, +void VertexLayout::setAttribute(std::string_view name, std::size_t index, VertexFormat format, std::size_t offset, @@ -37,7 +37,11 @@ void VertexLayout::setAttribute(const std::string& name, if (index == -1) return; - _attributes[name] = {name, index, format, offset, needToBeNormallized}; + // FIXME 2021/12/25 TODO: store name key is enough + hlookup::set_item( + _attributes, name, + Attribute{name, index, format, offset, + needToBeNormallized}); // _attributes[name] = {name, index, format, offset, needToBeNormallized}; } void VertexLayout::setLayout(std::size_t stride) diff --git a/cocos/renderer/backend/VertexLayout.h b/cocos/renderer/backend/VertexLayout.h index e3b33746e45a..3c11bf49f38d 100644 --- a/cocos/renderer/backend/VertexLayout.h +++ b/cocos/renderer/backend/VertexLayout.h @@ -48,7 +48,7 @@ class CC_DLL VertexLayout struct Attribute { Attribute() = default; - Attribute(const std::string& _name, + Attribute(std::string_view _name, std::size_t _index, VertexFormat _format, std::size_t _offset, @@ -74,7 +74,7 @@ class CC_DLL VertexLayout * @param needToBeNormallized Specifies whether fixed-point data values should be normalized (true) or converted * directly as fixed-point values (false) when they are accessed. */ - void setAttribute(const std::string& name, + void setAttribute(std::string_view name, std::size_t index, VertexFormat format, std::size_t offset, @@ -103,7 +103,7 @@ class CC_DLL VertexLayout * Get attribute informations * @return Atrribute informations. */ - inline const std::unordered_map& getAttributes() const { return _attributes; } + inline const hlookup::string_map& getAttributes() const { return _attributes; } /** * Check if vertex layout has been set. @@ -111,7 +111,7 @@ class CC_DLL VertexLayout inline bool isValid() const { return _stride != 0; } private: - std::unordered_map _attributes; + hlookup::string_map _attributes; std::size_t _stride = 0; VertexStepMode _stepMode = VertexStepMode::VERTEX; }; diff --git a/cocos/renderer/backend/metal/BufferMTL.mm b/cocos/renderer/backend/metal/BufferMTL.mm index 9abe3d62a4a4..fb336acfd5fc 100644 --- a/cocos/renderer/backend/metal/BufferMTL.mm +++ b/cocos/renderer/backend/metal/BufferMTL.mm @@ -21,7 +21,7 @@ of this software and associated documentation files (the "Software"), to deal OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + #include "BufferMTL.h" #include "../Macros.h" #include "BufferManager.h" @@ -29,15 +29,15 @@ of this software and associated documentation files (the "Software"), to deal CC_BACKEND_BEGIN BufferMTL::BufferMTL(id mtlDevice, std::size_t size, BufferType type, BufferUsage usage) -: Buffer(size, type, usage) + : Buffer(size, type, usage) { if (BufferUsage::DYNAMIC == usage) { - NSMutableArray *mutableDynamicDataBuffers = [NSMutableArray arrayWithCapacity:MAX_INFLIGHT_BUFFER]; + NSMutableArray* mutableDynamicDataBuffers = [NSMutableArray arrayWithCapacity:MAX_INFLIGHT_BUFFER]; for (int i = 0; i < MAX_INFLIGHT_BUFFER; ++i) { // Create a new buffer with enough capacity to store one instance of the dynamic buffer data - id dynamicDataBuffer = [mtlDevice newBufferWithLength:size options:MTLResourceStorageModeShared]; + id dynamicDataBuffer = [mtlDevice newBufferWithLength:size options:MTLResourceStorageModeShared]; [mutableDynamicDataBuffers addObject:dynamicDataBuffer]; } _dynamicDataBuffers = [mutableDynamicDataBuffers copy]; @@ -97,8 +97,8 @@ of this software and associated documentation files (the "Software"), to deal if (BufferUsage::DYNAMIC == _usage && !_indexUpdated) { _currentFrameIndex = (_currentFrameIndex + 1) % MAX_INFLIGHT_BUFFER; - _mtlBuffer = _dynamicDataBuffers[_currentFrameIndex]; - _indexUpdated = true; + _mtlBuffer = _dynamicDataBuffers[_currentFrameIndex]; + _indexUpdated = true; } } diff --git a/cocos/renderer/backend/metal/BufferManager.mm b/cocos/renderer/backend/metal/BufferManager.mm index 22776b4799de..0fae9871b2a2 100644 --- a/cocos/renderer/backend/metal/BufferManager.mm +++ b/cocos/renderer/backend/metal/BufferManager.mm @@ -21,7 +21,7 @@ of this software and associated documentation files (the "Software"), to deal OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + #include "BufferManager.h" #include "BufferMTL.h" diff --git a/cocos/renderer/backend/metal/CommandBufferMTL.mm b/cocos/renderer/backend/metal/CommandBufferMTL.mm index 0490fa56248d..3d881af178b7 100644 --- a/cocos/renderer/backend/metal/CommandBufferMTL.mm +++ b/cocos/renderer/backend/metal/CommandBufferMTL.mm @@ -22,7 +22,7 @@ of this software and associated documentation files (the "Software"), to deal OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + #include "CommandBufferMTL.h" #include "BufferMTL.h" #include "DeviceMTL.h" @@ -39,130 +39,131 @@ of this software and associated documentation files (the "Software"), to deal namespace { -#define byte(n) ((n) * 8) +#define byte(n) ((n)*8) #define bit(n) (n) - static uint8_t getBitsPerElementMTL(MTLPixelFormat pixleFormat) +static uint8_t getBitsPerElementMTL(MTLPixelFormat pixleFormat) +{ + switch (pixleFormat) { - switch (pixleFormat) - { - case MTLPixelFormatDepth32Float_Stencil8: - return byte(8); - case MTLPixelFormatBGRA8Unorm: - case MTLPixelFormatRGBA8Unorm: - case MTLPixelFormatDepth32Float: - return byte(4); - #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) - case MTLPixelFormatDepth24Unorm_Stencil8: - return byte(4); - #else - case MTLPixelFormatABGR4Unorm: - case MTLPixelFormatBGR5A1Unorm: - case MTLPixelFormatB5G6R5Unorm: - case MTLPixelFormatA1BGR5Unorm: - return byte(2); - #endif - case MTLPixelFormatA8Unorm: - case MTLPixelFormatR8Unorm: - return byte(1); - default: - assert(false); - break; - } - return 0; + case MTLPixelFormatDepth32Float_Stencil8: + return byte(8); + case MTLPixelFormatBGRA8Unorm: + case MTLPixelFormatRGBA8Unorm: + case MTLPixelFormatDepth32Float: + return byte(4); +#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) + case MTLPixelFormatDepth24Unorm_Stencil8: + return byte(4); +#else + case MTLPixelFormatABGR4Unorm: + case MTLPixelFormatBGR5A1Unorm: + case MTLPixelFormatB5G6R5Unorm: + case MTLPixelFormatA1BGR5Unorm: + return byte(2); +#endif + case MTLPixelFormatA8Unorm: + case MTLPixelFormatR8Unorm: + return byte(1); + default: + assert(false); + break; } + return 0; +} - static MTLWinding toMTLWinding(Winding winding) - { - if (Winding::CLOCK_WISE == winding) - return MTLWindingClockwise; - else - return MTLWindingCounterClockwise; - } +static MTLWinding toMTLWinding(Winding winding) +{ + if (Winding::CLOCK_WISE == winding) + return MTLWindingClockwise; + else + return MTLWindingCounterClockwise; +} - static MTLPrimitiveType toMTLPrimitive(PrimitiveType primitiveType) - { - MTLPrimitiveType ret = MTLPrimitiveTypeTriangle; - switch (primitiveType) - { - case PrimitiveType::POINT: - ret = MTLPrimitiveTypePoint; - break; - case PrimitiveType::LINE: - ret = MTLPrimitiveTypeLine; - break; - case PrimitiveType::LINE_STRIP: - ret = MTLPrimitiveTypeLineStrip; - break; - case PrimitiveType::TRIANGLE: - ret = MTLPrimitiveTypeTriangle; - break; - case PrimitiveType::TRIANGLE_STRIP: - ret = MTLPrimitiveTypeTriangleStrip; - break; - default: - break; - } - return ret; - } - - static MTLIndexType toMTLIndexType(IndexFormat indexFormat) - { - if (IndexFormat::U_SHORT == indexFormat) - return MTLIndexTypeUInt16; - else - return MTLIndexTypeUInt32; - } - - static MTLCullMode toMTLCullMode(CullMode mode) - { - switch (mode) { - case CullMode::NONE: - return MTLCullModeNone; - case CullMode::FRONT: - return MTLCullModeFront; - case CullMode::BACK: - return MTLCullModeBack; - } - } - - static MTLRenderPassDescriptor* toMTLRenderPassDescriptor(const RenderTarget* rt, const RenderPassDescriptor& desc) - { - MTLRenderPassDescriptor* mtlDescritpor = [MTLRenderPassDescriptor renderPassDescriptor]; - - auto rtMTL = static_cast(rt); - rtMTL->applyRenderPassAttachments(desc, mtlDescritpor); - return mtlDescritpor; - } - - static id getMTLTexture(TextureBackend* texture, int index) +static MTLPrimitiveType toMTLPrimitive(PrimitiveType primitiveType) +{ + MTLPrimitiveType ret = MTLPrimitiveTypeTriangle; + switch (primitiveType) { - return reinterpret_cast>(texture->getHandler(index)); + case PrimitiveType::POINT: + ret = MTLPrimitiveTypePoint; + break; + case PrimitiveType::LINE: + ret = MTLPrimitiveTypeLine; + break; + case PrimitiveType::LINE_STRIP: + ret = MTLPrimitiveTypeLineStrip; + break; + case PrimitiveType::TRIANGLE: + ret = MTLPrimitiveTypeTriangle; + break; + case PrimitiveType::TRIANGLE_STRIP: + ret = MTLPrimitiveTypeTriangleStrip; + break; + default: + break; } - - static id getMTLSamplerState(TextureBackend* texture) + return ret; +} + +static MTLIndexType toMTLIndexType(IndexFormat indexFormat) +{ + if (IndexFormat::U_SHORT == indexFormat) + return MTLIndexTypeUInt16; + else + return MTLIndexTypeUInt32; +} + +static MTLCullMode toMTLCullMode(CullMode mode) +{ + switch (mode) { - switch (texture->getTextureType()) - { - case TextureType::TEXTURE_2D: - return static_cast(texture)->getMTLSamplerState(); - case TextureType::TEXTURE_CUBE: - return static_cast(texture)->getMTLSamplerState(); - default: - assert(false); - return nil; - } + case CullMode::NONE: + return MTLCullModeNone; + case CullMode::FRONT: + return MTLCullModeFront; + case CullMode::BACK: + return MTLCullModeBack; } +} - inline int clamp(int value, int min, int max) { - return std::min(max, std::max(min, value)); +static MTLRenderPassDescriptor* toMTLRenderPassDescriptor(const RenderTarget* rt, const RenderPassDescriptor& desc) +{ + MTLRenderPassDescriptor* mtlDescritpor = [MTLRenderPassDescriptor renderPassDescriptor]; + + auto rtMTL = static_cast(rt); + rtMTL->applyRenderPassAttachments(desc, mtlDescritpor); + return mtlDescritpor; +} + +static id getMTLTexture(TextureBackend* texture, int index) +{ + return reinterpret_cast>(texture->getHandler(index)); +} + +static id getMTLSamplerState(TextureBackend* texture) +{ + switch (texture->getTextureType()) + { + case TextureType::TEXTURE_2D: + return static_cast(texture)->getMTLSamplerState(); + case TextureType::TEXTURE_CUBE: + return static_cast(texture)->getMTLSamplerState(); + default: + assert(false); + return nil; } } -CommandBufferMTL::CommandBufferMTL(DeviceMTL* deviceMTL) -: _mtlCommandQueue(deviceMTL->getMTLCommandQueue()) -, _frameBoundarySemaphore(dispatch_semaphore_create(MAX_INFLIGHT_BUFFER)) +inline int clamp(int value, int min, int max) { + return std::min(max, std::max(min, value)); } +} + +CommandBufferMTL::CommandBufferMTL(DeviceMTL* deviceMTL) + : _mtlCommandQueue(deviceMTL->getMTLCommandQueue()) + , _frameBoundarySemaphore(dispatch_semaphore_create(MAX_INFLIGHT_BUFFER)) +{} CommandBufferMTL::~CommandBufferMTL() { @@ -171,7 +172,7 @@ inline int clamp(int value, int min, int max) { id oneOffBuffer = [_mtlCommandQueue commandBuffer]; [oneOffBuffer commit]; [oneOffBuffer waitUntilCompleted]; - + dispatch_semaphore_signal(_frameBoundarySemaphore); } @@ -199,38 +200,37 @@ inline int clamp(int value, int min, int max) { return true; } -void CommandBufferMTL::updateRenderCommandEncoder(const RenderTarget* renderTarget, const RenderPassDescriptor& renderPassDesc) +void CommandBufferMTL::updateRenderCommandEncoder(const RenderTarget* renderTarget, + const RenderPassDescriptor& renderPassDesc) { - if(_mtlRenderEncoder != nil && - _currentRenderPassDesc == renderPassDesc && - _currentRenderTarget == renderTarget && - _currentRenderTargetFlags == renderTarget->getTargetFlags()) + if (_mtlRenderEncoder != nil && _currentRenderPassDesc == renderPassDesc && _currentRenderTarget == renderTarget && + _currentRenderTargetFlags == renderTarget->getTargetFlags()) { return _mtlRenderEncoder; } - - _currentRenderTarget = renderTarget; - _currentRenderPassDesc = renderPassDesc; + + _currentRenderTarget = renderTarget; + _currentRenderPassDesc = renderPassDesc; _currentRenderTargetFlags = renderTarget->getTargetFlags(); - - if(_mtlRenderEncoder != nil) + + if (_mtlRenderEncoder != nil) { [_mtlRenderEncoder endEncoding]; [_mtlRenderEncoder release]; _mtlRenderEncoder = nil; } - auto mtlDescriptor = toMTLRenderPassDescriptor(renderTarget, renderPassDesc); - _renderTargetWidth = (unsigned int)mtlDescriptor.colorAttachments[0].texture.width; + auto mtlDescriptor = toMTLRenderPassDescriptor(renderTarget, renderPassDesc); + _renderTargetWidth = (unsigned int)mtlDescriptor.colorAttachments[0].texture.width; _renderTargetHeight = (unsigned int)mtlDescriptor.colorAttachments[0].texture.height; - _mtlRenderEncoder = [_mtlCommandBuffer renderCommandEncoderWithDescriptor:mtlDescriptor]; + _mtlRenderEncoder = [_mtlCommandBuffer renderCommandEncoderWithDescriptor:mtlDescriptor]; [_mtlRenderEncoder retain]; } void CommandBufferMTL::beginRenderPass(const RenderTarget* renderTarget, const RenderPassDescriptor& renderPassDesc) { updateRenderCommandEncoder(renderTarget, renderPassDesc); -// [_mtlRenderEncoder setFrontFacingWinding:MTLWindingCounterClockwise]; + // [_mtlRenderEncoder setFrontFacingWinding:MTLWindingCounterClockwise]; } void CommandBufferMTL::updateDepthStencilState(const DepthStencilDescriptor& descriptor) @@ -249,10 +249,10 @@ inline int clamp(int value, int min, int max) { MTLViewport viewport; viewport.originX = x; viewport.originY = (int)(_renderTargetHeight - y - h); - viewport.width = w; - viewport.height = h; - viewport.znear = 0; - viewport.zfar = 1; + viewport.width = w; + viewport.height = h; + viewport.znear = 0; + viewport.zfar = 1; [_mtlRenderEncoder setViewport:viewport]; } @@ -269,9 +269,7 @@ inline int clamp(int value, int min, int max) { void CommandBufferMTL::setVertexBuffer(Buffer* buffer) { // Vertex buffer is bound in index 0. - [_mtlRenderEncoder setVertexBuffer:static_cast(buffer)->getMTLBuffer() - offset:0 - atIndex:0]; + [_mtlRenderEncoder setVertexBuffer:static_cast(buffer)->getMTLBuffer() offset:0 atIndex:0]; } void CommandBufferMTL::setProgramState(ProgramState* programState) @@ -286,20 +284,21 @@ inline int clamp(int value, int min, int max) { assert(buffer != nullptr); if (!buffer) return; - + _mtlIndexBuffer = static_cast(buffer)->getMTLBuffer(); [_mtlIndexBuffer retain]; } -void CommandBufferMTL::drawArrays(PrimitiveType primitiveType, std::size_t start, std::size_t count) +void CommandBufferMTL::drawArrays(PrimitiveType primitiveType, std::size_t start, std::size_t count) { prepareDrawing(); - [_mtlRenderEncoder drawPrimitives:toMTLPrimitive(primitiveType) - vertexStart:start - vertexCount:count]; + [_mtlRenderEncoder drawPrimitives:toMTLPrimitive(primitiveType) vertexStart:start vertexCount:count]; } -void CommandBufferMTL::drawElements(PrimitiveType primitiveType, IndexFormat indexType, std::size_t count, std::size_t offset) +void CommandBufferMTL::drawElements(PrimitiveType primitiveType, + IndexFormat indexType, + std::size_t count, + std::size_t offset) { prepareDrawing(); [_mtlRenderEncoder drawIndexedPrimitives:toMTLPrimitive(primitiveType) @@ -307,7 +306,6 @@ inline int clamp(int value, int min, int max) { indexType:toMTLIndexType(indexType) indexBuffer:_mtlIndexBuffer indexBufferOffset:offset]; - } void CommandBufferMTL::endRenderPass() @@ -318,7 +316,7 @@ inline int clamp(int value, int min, int max) { void CommandBufferMTL::readPixels(RenderTarget* rt, std::function callback) { auto rtMTL = static_cast(rt); - + // we only read form color attachment 0 // if it's nullptr, will regard as screen to perform capture auto texture = rtMTL->_color[0].texture; @@ -331,14 +329,14 @@ inline int clamp(int value, int min, int max) { [_mtlRenderEncoder endEncoding]; [_mtlRenderEncoder release]; _mtlRenderEncoder = nil; - + auto currentDrawable = DeviceMTL::getCurrentDrawable(); [_mtlCommandBuffer presentDrawable:currentDrawable]; _drawableTexture = currentDrawable.texture; [_mtlCommandBuffer addCompletedHandler:^(id commandBuffer) { - // GPU work is complete - // Signal the semaphore to start the CPU work - dispatch_semaphore_signal(_frameBoundarySemaphore); + // GPU work is complete + // Signal the semaphore to start the CPU work + dispatch_semaphore_signal(_frameBoundarySemaphore); }]; flush(); @@ -349,12 +347,13 @@ inline int clamp(int value, int min, int max) { void CommandBufferMTL::flush() { - if(_mtlCommandBuffer) { + if (_mtlCommandBuffer) + { assert(_mtlCommandBuffer.status != MTLCommandBufferStatusCommitted); [_mtlCommandBuffer commit]; - + flushCaptureCommands(); - + [_mtlCommandBuffer release]; _mtlCommandBuffer = nil; } @@ -362,24 +361,30 @@ inline int clamp(int value, int min, int max) { void CommandBufferMTL::flushCaptureCommands() { - if(!_captureCallbacks.empty()) { + if (!_captureCallbacks.empty()) + { // !!!important, if have capture request, must wait pending commandBuffer finish at this frame, // because readPixels require sync operation to get screen pixels properly without data race issue, // otherwise, will lead dead-lock // !!!Notes, MTL is mutli-threading, all GPU handler is dispatch at GPU threads [_mtlCommandBuffer waitUntilCompleted]; - + PixelBufferDescriptor screenPixelData; - for(auto& cb : _captureCallbacks) { - if(cb.first == nil) { // screen capture - if(!screenPixelData) { - CommandBufferMTL::readPixels(_drawableTexture, 0, 0, [_drawableTexture width], [_drawableTexture height], screenPixelData); + for (auto& cb : _captureCallbacks) + { + if (cb.first == nil) + { // screen capture + if (!screenPixelData) + { + CommandBufferMTL::readPixels(_drawableTexture, 0, 0, [_drawableTexture width], + [_drawableTexture height], screenPixelData); // screen framebuffer copied, restore screen framebuffer only to true backend::Device::getInstance()->setFrameBufferOnly(true); } cb.second(screenPixelData); } - else { + else + { PixelBufferDescriptor pixelData; auto texture = cb.first; assert(texture != nullptr); @@ -399,7 +404,7 @@ inline int clamp(int value, int min, int max) { [_mtlIndexBuffer release]; _mtlIndexBuffer = nullptr; } - + CC_SAFE_RELEASE_NULL(_programState); } @@ -407,7 +412,7 @@ inline int clamp(int value, int min, int max) { { setUniformBuffer(); setTextures(); - + auto mtlDepthStencilState = _depthStencilStateMTL->getMTLDepthStencilState(); if (mtlDepthStencilState) { @@ -428,36 +433,33 @@ inline int clamp(int value, int min, int max) { void CommandBufferMTL::doSetTextures(bool isVertex) const { - const auto& bindTextureInfos = (isVertex) ? _programState->getVertexTextureInfos() : _programState->getFragmentTextureInfos(); + const auto& bindTextureInfos = + (isVertex) ? _programState->getVertexTextureInfos() : _programState->getFragmentTextureInfos(); - for(const auto& iter : bindTextureInfos) + for (const auto& iter : bindTextureInfos) { /* About mutli textures support - * a. TODO: sampler2DArray, not implemented in Metal Renderer currently - * b. texture slot, one BackendTexture, multi GPU texture handlers, used by etc1, restrict: textures must have same size - * c. Bind multi BackendTexture to 1 Shader Program, see the ShaderTest - * d. iter.second.slots not used for Metal Renderer - */ - auto location = iter.first; + * a. TODO: sampler2DArray, not implemented in Metal Renderer currently + * b. texture slot, one BackendTexture, multi GPU texture handlers, used by etc1, restrict: textures must have + * same size c. Bind multi BackendTexture to 1 Shader Program, see the ShaderTest d. iter.second.slots not used + * for Metal Renderer + */ + auto location = iter.first; auto& textures = iter.second.textures; - auto& indexs = iter.second.indexs; - + auto& indexs = iter.second.indexs; + auto texture = textures[0]; - auto index = indexs[0]; + auto index = indexs[0]; if (isVertex) { - [_mtlRenderEncoder setVertexTexture:getMTLTexture(texture, index) - atIndex:location]; - [_mtlRenderEncoder setVertexSamplerState:getMTLSamplerState(texture) - atIndex:location]; + [_mtlRenderEncoder setVertexTexture:getMTLTexture(texture, index) atIndex:location]; + [_mtlRenderEncoder setVertexSamplerState:getMTLSamplerState(texture) atIndex:location]; } else { - [_mtlRenderEncoder setFragmentTexture:getMTLTexture(texture, index) - atIndex:location]; - [_mtlRenderEncoder setFragmentSamplerState:getMTLSamplerState(texture) - atIndex:location]; + [_mtlRenderEncoder setFragmentTexture:getMTLTexture(texture, index) atIndex:location]; + [_mtlRenderEncoder setFragmentSamplerState:getMTLSamplerState(texture) atIndex:location]; } } } @@ -466,108 +468,122 @@ inline int clamp(int value, int min, int max) { { if (_programState) { - auto& callbackUniforms = _programState->getCallbackUniforms(); - for(auto& cb : callbackUniforms) - cb.second(_programState, cb.first); + auto& callbackUniforms = _programState->getCallbackUniforms(); + for (auto& cb : callbackUniforms) + cb.second(_programState, cb.first); // Uniform buffer is bound to index 1. std::size_t bufferSize = 0; - char* vertexBuffer = nullptr; + char* vertexBuffer = nullptr; _programState->getVertexUniformBuffer(&vertexBuffer, bufferSize); - if(vertexBuffer) + if (vertexBuffer) { - [_mtlRenderEncoder setVertexBytes:vertexBuffer - length:bufferSize - atIndex:1]; + [_mtlRenderEncoder setVertexBytes:vertexBuffer length:bufferSize atIndex:1]; } - + char* fragmentBuffer = nullptr; _programState->getFragmentUniformBuffer(&fragmentBuffer, bufferSize); - if(fragmentBuffer) + if (fragmentBuffer) { - [_mtlRenderEncoder setFragmentBytes:fragmentBuffer - length:bufferSize - atIndex:1]; + [_mtlRenderEncoder setFragmentBytes:fragmentBuffer length:bufferSize atIndex:1]; } } } -void CommandBufferMTL::setLineWidth(float lineWidth) -{ -} +void CommandBufferMTL::setLineWidth(float lineWidth) {} void CommandBufferMTL::setScissorRect(bool isEnabled, float x, float y, float width, float height) { MTLScissorRect scissorRect; - if(isEnabled) + if (isEnabled) { - y = _renderTargetHeight - height - y; - int minX = clamp((int)x, 0, (int)_renderTargetWidth); - int minY = clamp((int)y, 0, (int)_renderTargetHeight); - int maxX = clamp((int)(x + width), 0, (int)_renderTargetWidth); - int maxY = clamp((int)(y + height), 0, (int)_renderTargetHeight); - scissorRect.x = minX; - scissorRect.y = minY; - scissorRect.width = maxX - minX; + y = _renderTargetHeight - height - y; + int minX = clamp((int)x, 0, (int)_renderTargetWidth); + int minY = clamp((int)y, 0, (int)_renderTargetHeight); + int maxX = clamp((int)(x + width), 0, (int)_renderTargetWidth); + int maxY = clamp((int)(y + height), 0, (int)_renderTargetHeight); + scissorRect.x = minX; + scissorRect.y = minY; + scissorRect.width = maxX - minX; scissorRect.height = maxY - minY; - if (scissorRect.width == 0 || scissorRect.height == 0) { - scissorRect.width = 0; + if (scissorRect.width == 0 || scissorRect.height == 0) + { + scissorRect.width = 0; scissorRect.height = 0; } } else { - scissorRect.x = 0; - scissorRect.y = 0; - scissorRect.width = _renderTargetWidth; + scissorRect.x = 0; + scissorRect.y = 0; + scissorRect.width = _renderTargetWidth; scissorRect.height = _renderTargetHeight; } [_mtlRenderEncoder setScissorRect:scissorRect]; } -void CommandBufferMTL::readPixels(TextureBackend* texture, std::size_t origX, std::size_t origY, std::size_t rectWidth, std::size_t rectHeight, PixelBufferDescriptor& pbd) +void CommandBufferMTL::readPixels(TextureBackend* texture, + std::size_t origX, + std::size_t origY, + std::size_t rectWidth, + std::size_t rectHeight, + PixelBufferDescriptor& pbd) { - CommandBufferMTL::readPixels(reinterpret_cast>(texture->getHandler()), origX, origY, rectWidth, rectHeight, pbd); + CommandBufferMTL::readPixels(reinterpret_cast>(texture->getHandler()), origX, origY, rectWidth, + rectHeight, pbd); } -void CommandBufferMTL::readPixels(id texture, std::size_t origX, std::size_t origY, std::size_t rectWidth, std::size_t rectHeight, PixelBufferDescriptor& pbd) +void CommandBufferMTL::readPixels(id texture, + std::size_t origX, + std::size_t origY, + std::size_t rectWidth, + std::size_t rectHeight, + PixelBufferDescriptor& pbd) { - NSUInteger texWidth = texture.width; - NSUInteger texHeight = texture.height; - MTLRegion region = MTLRegionMake2D(0, 0, texWidth, texHeight); + NSUInteger texWidth = texture.width; + NSUInteger texHeight = texture.height; + MTLRegion region = MTLRegionMake2D(0, 0, texWidth, texHeight); MTLRegion imageRegion = MTLRegionMake2D(origX, origY, rectWidth, rectHeight); - + MTLTextureDescriptor* textureDescriptor = - [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:[texture pixelFormat] - width:texWidth - height:texHeight - mipmapped:NO]; - id device = static_cast(DeviceMTL::getInstance())->getMTLDevice(); + [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:[texture pixelFormat] + width:texWidth + height:texHeight + mipmapped:NO]; + id device = static_cast(DeviceMTL::getInstance())->getMTLDevice(); id readPixelsTexture = [device newTextureWithDescriptor:textureDescriptor]; - + id commandQueue = static_cast(DeviceMTL::getInstance())->getMTLCommandQueue(); - auto commandBuffer = [commandQueue commandBuffer]; + auto commandBuffer = [commandQueue commandBuffer]; // [commandBuffer enqueue]; - + id blitCommandEncoder = [commandBuffer blitCommandEncoder]; - [blitCommandEncoder copyFromTexture:texture sourceSlice:0 sourceLevel:0 sourceOrigin:region.origin sourceSize:region.size toTexture:readPixelsTexture destinationSlice:0 destinationLevel:0 destinationOrigin:region.origin]; - + [blitCommandEncoder copyFromTexture:texture + sourceSlice:0 + sourceLevel:0 + sourceOrigin:region.origin + sourceSize:region.size + toTexture:readPixelsTexture + destinationSlice:0 + destinationLevel:0 + destinationOrigin:region.origin]; + #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) [blitCommandEncoder synchronizeResource:readPixelsTexture]; #endif [blitCommandEncoder endEncoding]; - + [commandBuffer addCompletedHandler:^(id commandBufferMTL) { - auto bytePerRow = rectWidth * getBitsPerElementMTL(texture.pixelFormat) / 8; - auto texelData = pbd._data.resize(bytePerRow * rectHeight); - if(texelData != nullptr) - { + auto bytePerRow = rectWidth * getBitsPerElementMTL(texture.pixelFormat) / 8; + auto texelData = pbd._data.resize(bytePerRow * rectHeight); + if (texelData != nullptr) + { [readPixelsTexture getBytes:texelData bytesPerRow:bytePerRow fromRegion:imageRegion mipmapLevel:0]; UtilsMTL::swizzleImage(texelData, rectWidth, rectHeight, readPixelsTexture.pixelFormat); - pbd._width = rectWidth; + pbd._width = rectWidth; pbd._height = rectHeight; - } - [readPixelsTexture release]; + } + [readPixelsTexture release]; }]; [commandBuffer commit]; [commandBuffer waitUntilCompleted]; diff --git a/cocos/renderer/backend/metal/DepthStencilStateMTL.mm b/cocos/renderer/backend/metal/DepthStencilStateMTL.mm index 9c84efcb7968..4b1e0955a969 100644 --- a/cocos/renderer/backend/metal/DepthStencilStateMTL.mm +++ b/cocos/renderer/backend/metal/DepthStencilStateMTL.mm @@ -21,7 +21,7 @@ of this software and associated documentation files (the "Software"), to deal OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + #include "DepthStencilStateMTL.h" #include "../RenderTarget.h" #include "xxhash.h" @@ -30,108 +30,110 @@ of this software and associated documentation files (the "Software"), to deal namespace { - MTLCompareFunction toMTLCompareFunction(CompareFunction compareFunction) - { - MTLCompareFunction ret = MTLCompareFunctionNever; - switch (compareFunction) { - case CompareFunction::NEVER: - ret = MTLCompareFunctionNever; - break; - case CompareFunction::LESS: - ret = MTLCompareFunctionLess; - break; - case CompareFunction::LESS_EQUAL: - ret = MTLCompareFunctionLessEqual; - break; - case CompareFunction::GREATER: - ret = MTLCompareFunctionGreater; - break; - case CompareFunction::GREATER_EQUAL: - ret = MTLCompareFunctionGreaterEqual; - break; - case CompareFunction::EQUAL: - ret = MTLCompareFunctionEqual; - break; - case CompareFunction::NOT_EQUAL: - ret = MTLCompareFunctionNotEqual; - break; - case CompareFunction::ALWAYS: - ret = MTLCompareFunctionAlways; - break; - default: - assert(false); - break; - } - return ret; - } - - MTLStencilOperation toMTLStencilOperation(StencilOperation operation) +MTLCompareFunction toMTLCompareFunction(CompareFunction compareFunction) +{ + MTLCompareFunction ret = MTLCompareFunctionNever; + switch (compareFunction) { - MTLStencilOperation ret = MTLStencilOperationKeep; - switch (operation) { - case StencilOperation::KEEP: - ret = MTLStencilOperationKeep; - break; - case StencilOperation::ZERO: - ret = MTLStencilOperationZero; - break; - case StencilOperation::REPLACE: - ret = MTLStencilOperationReplace; - break; - case StencilOperation::INVERT: - ret = MTLStencilOperationInvert; - break; - case StencilOperation::INCREMENT_WRAP: - ret = MTLStencilOperationIncrementWrap; - break; - case StencilOperation::DECREMENT_WRAP: - ret = MTLStencilOperationDecrementWrap; - break; - default: - assert(false); - break; - } - return ret; + case CompareFunction::NEVER: + ret = MTLCompareFunctionNever; + break; + case CompareFunction::LESS: + ret = MTLCompareFunctionLess; + break; + case CompareFunction::LESS_EQUAL: + ret = MTLCompareFunctionLessEqual; + break; + case CompareFunction::GREATER: + ret = MTLCompareFunctionGreater; + break; + case CompareFunction::GREATER_EQUAL: + ret = MTLCompareFunctionGreaterEqual; + break; + case CompareFunction::EQUAL: + ret = MTLCompareFunctionEqual; + break; + case CompareFunction::NOT_EQUAL: + ret = MTLCompareFunctionNotEqual; + break; + case CompareFunction::ALWAYS: + ret = MTLCompareFunctionAlways; + break; + default: + assert(false); + break; } - - void setMTLStencilDescriptor(MTLStencilDescriptor* stencilDescriptor, const StencilDescriptor& descriptor) + return ret; +} + +MTLStencilOperation toMTLStencilOperation(StencilOperation operation) +{ + MTLStencilOperation ret = MTLStencilOperationKeep; + switch (operation) { - stencilDescriptor.stencilFailureOperation = toMTLStencilOperation(descriptor.stencilFailureOperation); - stencilDescriptor.depthFailureOperation = toMTLStencilOperation(descriptor.depthFailureOperation); - stencilDescriptor.depthStencilPassOperation = toMTLStencilOperation(descriptor.depthStencilPassOperation); - stencilDescriptor.stencilCompareFunction = toMTLCompareFunction(descriptor.stencilCompareFunction); - stencilDescriptor.readMask = descriptor.readMask; - stencilDescriptor.writeMask = descriptor.writeMask; + case StencilOperation::KEEP: + ret = MTLStencilOperationKeep; + break; + case StencilOperation::ZERO: + ret = MTLStencilOperationZero; + break; + case StencilOperation::REPLACE: + ret = MTLStencilOperationReplace; + break; + case StencilOperation::INVERT: + ret = MTLStencilOperationInvert; + break; + case StencilOperation::INCREMENT_WRAP: + ret = MTLStencilOperationIncrementWrap; + break; + case StencilOperation::DECREMENT_WRAP: + ret = MTLStencilOperationDecrementWrap; + break; + default: + assert(false); + break; } + return ret; } -DepthStencilStateMTL::DepthStencilStateMTL(id mtlDevice) : _mtlDevice(mtlDevice) +void setMTLStencilDescriptor(MTLStencilDescriptor* stencilDescriptor, const StencilDescriptor& descriptor) { + stencilDescriptor.stencilFailureOperation = toMTLStencilOperation(descriptor.stencilFailureOperation); + stencilDescriptor.depthFailureOperation = toMTLStencilOperation(descriptor.depthFailureOperation); + stencilDescriptor.depthStencilPassOperation = toMTLStencilOperation(descriptor.depthStencilPassOperation); + stencilDescriptor.stencilCompareFunction = toMTLCompareFunction(descriptor.stencilCompareFunction); + stencilDescriptor.readMask = descriptor.readMask; + stencilDescriptor.writeMask = descriptor.writeMask; +} } +DepthStencilStateMTL::DepthStencilStateMTL(id mtlDevice) : _mtlDevice(mtlDevice) {} + void DepthStencilStateMTL::update(const DepthStencilDescriptor& dsDesc) { DepthStencilState::update(dsDesc); - - if(!isEnabled()) { + + if (!isEnabled()) + { _mtlDepthStencilState = nil; return; } - + DepthStencilDescriptor hashMe; memset(&hashMe, 0, sizeof(hashMe)); hashMe.depthCompareFunction = dsDesc.depthCompareFunction; - hashMe.backFaceStencil = dsDesc.backFaceStencil; - hashMe.frontFaceStencil = dsDesc.frontFaceStencil; - hashMe.flags = dsDesc.flags; - + hashMe.backFaceStencil = dsDesc.backFaceStencil; + hashMe.frontFaceStencil = dsDesc.frontFaceStencil; + hashMe.flags = dsDesc.flags; + auto key = XXH32((const void*)&hashMe, sizeof(hashMe), 0); - auto it = _mtlStateCache.find(key); - if(it != _mtlStateCache.end()) { + auto it = _mtlStateCache.find(key); + if (it != _mtlStateCache.end()) + { _mtlDepthStencilState = it->second; return; } - + MTLDepthStencilDescriptor* mtlDescriptor = [[MTLDepthStencilDescriptor alloc] init]; if (bitmask::any(dsDesc.flags, DepthStencilFlags::DEPTH_TEST)) @@ -149,7 +151,7 @@ void setMTLStencilDescriptor(MTLStencilDescriptor* stencilDescriptor, const Sten _mtlDepthStencilState = [_mtlDevice newDepthStencilStateWithDescriptor:mtlDescriptor]; [mtlDescriptor release]; - + // emplace to state cache _mtlStateCache.emplace(key, _mtlDepthStencilState); } @@ -157,7 +159,7 @@ void setMTLStencilDescriptor(MTLStencilDescriptor* stencilDescriptor, const Sten DepthStencilStateMTL::~DepthStencilStateMTL() { _mtlDepthStencilState = nullptr; - for(auto& stateItem : _mtlStateCache) + for (auto& stateItem : _mtlStateCache) [stateItem.second release]; _mtlStateCache.clear(); } diff --git a/cocos/renderer/backend/metal/DeviceInfoMTL.mm b/cocos/renderer/backend/metal/DeviceInfoMTL.mm index 87d0e6a65e33..18208a5e8ab7 100644 --- a/cocos/renderer/backend/metal/DeviceInfoMTL.mm +++ b/cocos/renderer/backend/metal/DeviceInfoMTL.mm @@ -22,367 +22,367 @@ of this software and associated documentation files (the "Software"), to deal OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - #include "DeviceInfoMTL.h" #include "base/ccMacros.h" #include "UtilsMTL.h" CC_BACKEND_BEGIN -namespace { - int getMaxVertexAttributes(FeatureSet featureSet) +namespace +{ +int getMaxVertexAttributes(FeatureSet featureSet) +{ + int maxAttributes = 0; + switch (featureSet) { - int maxAttributes = 0; - switch (featureSet) - { - case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: - maxAttributes = 31; - break; - default: - break; - } - return maxAttributes; + case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: + maxAttributes = 31; + break; + default: + break; } - - int getMaxTextureEntries(FeatureSet featureSet) + return maxAttributes; +} + +int getMaxTextureEntries(FeatureSet featureSet) +{ + int maxTextureEntries = 0; + switch (featureSet) { - int maxTextureEntries = 0; - switch (featureSet) - { - case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: - maxTextureEntries = 31; - break; - case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: - maxTextureEntries = 128; - break; - default: - break; - } - return maxTextureEntries; + case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: + maxTextureEntries = 31; + break; + case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: + maxTextureEntries = 128; + break; + default: + break; } - - int getMaxSamplerEntries(FeatureSet featureSet) + return maxTextureEntries; +} + +int getMaxSamplerEntries(FeatureSet featureSet) +{ + int maxSamplerEntries = 0; + switch (featureSet) { - int maxSamplerEntries = 0; - switch (featureSet) - { - case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: - maxSamplerEntries = 16; - break; - default: - break; - } - return maxSamplerEntries; + case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: + maxSamplerEntries = 16; + break; + default: + break; } - - int getMaxTextureWidthHeight(FeatureSet featureSet) + return maxSamplerEntries; +} + +int getMaxTextureWidthHeight(FeatureSet featureSet) +{ + int maxTextureSize = 0; + switch (featureSet) { - int maxTextureSize = 0; - switch (featureSet) - { - case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: - maxTextureSize = 4096; - break; - case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: - maxTextureSize = 8192; - break; - case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: - maxTextureSize = 16384; - break; - default: - break; - } - return maxTextureSize; + case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: + maxTextureSize = 4096; + break; + case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: + maxTextureSize = 8192; + break; + case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: + maxTextureSize = 16384; + break; + default: + break; } - - const char* featureSetToString(FeatureSet featureSet) + return maxTextureSize; +} + +const char* featureSetToString(FeatureSet featureSet) +{ + switch (featureSet) { - switch (featureSet) - { - case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: - return "iOS_GPUFamily1_v1"; - case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: - return "iOS_GPUFamily2_v1"; - case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: - return "iOS_GPUFamily1_v2"; - case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: - return "iOS_GPUFamily2_v2"; - case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: - return "iOS_GPUFamily1_v3"; - case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: - return "iOS_GPUFamily2_v3"; - case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: - return "iOS_GPUFamily1_v4"; - case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: - return "iOS_GPUFamily2_v4"; - case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: - return "iOS_GPUFamily1_v5"; - case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: - return "iOS_GPUFamily2_v5"; - case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: - return "iOS_GPUFamily3_v1"; - case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: - return "iOS_GPUFamily3_v2"; - case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: - return "iOS_GPUFamily3_v3"; - case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: - return "iOS_GPUFamily4_v1"; - case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: - return "iOS_GPUFamily3_v4"; - case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: - return "iOS_GPUFamily4_v2"; - case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: - return "macOS_GPUFamily1_v1"; - case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: - return "macOS_GPUFamily1_v2"; - case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: - return "macOS_ReadWriteTextureTier2"; - case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: - return "macOS_GPUFamily1_v3"; - case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: - return "macOS_GPUFamily1_v4"; - case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: - return "macOS_GPUFamily2_v1"; - default: - break; - } - return ""; + case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: + return "iOS_GPUFamily1_v1"; + case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: + return "iOS_GPUFamily2_v1"; + case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: + return "iOS_GPUFamily1_v2"; + case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: + return "iOS_GPUFamily2_v2"; + case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: + return "iOS_GPUFamily1_v3"; + case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: + return "iOS_GPUFamily2_v3"; + case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: + return "iOS_GPUFamily1_v4"; + case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: + return "iOS_GPUFamily2_v4"; + case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: + return "iOS_GPUFamily1_v5"; + case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: + return "iOS_GPUFamily2_v5"; + case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: + return "iOS_GPUFamily3_v1"; + case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: + return "iOS_GPUFamily3_v2"; + case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: + return "iOS_GPUFamily3_v3"; + case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: + return "iOS_GPUFamily4_v1"; + case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: + return "iOS_GPUFamily3_v4"; + case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: + return "iOS_GPUFamily4_v2"; + case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: + return "macOS_GPUFamily1_v1"; + case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: + return "macOS_GPUFamily1_v2"; + case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: + return "macOS_ReadWriteTextureTier2"; + case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: + return "macOS_GPUFamily1_v3"; + case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: + return "macOS_GPUFamily1_v4"; + case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: + return "macOS_GPUFamily2_v1"; + default: + break; } - - bool supportPVRTC(FeatureSet featureSet) + return ""; +} + +bool supportPVRTC(FeatureSet featureSet) +{ + switch (featureSet) { - switch (featureSet) - { - case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: - return true; - case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: - return false; - default: - break; - } + case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: + return true; + case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: return false; + default: + break; } - - bool supportEACETC(FeatureSet featureSet) + return false; +} + +bool supportEACETC(FeatureSet featureSet) +{ + switch (featureSet) { - switch (featureSet) - { - case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: - return true; - case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: - return false; - default: - break; - } + case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: + return true; + case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: return false; + default: + break; } - - bool supportASTC(FeatureSet featureSet) + return false; +} + +bool supportASTC(FeatureSet featureSet) +{ + switch (featureSet) { - switch (featureSet) - { - case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: - return false; - case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: - return true; - case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: - return false; - default: - break; - } + case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: + return false; + case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: + return true; + case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: return false; + default: + break; } - - bool supportS3TC(FeatureSet featureSet) + return false; +} + +bool supportS3TC(FeatureSet featureSet) +{ + switch (featureSet) { - switch (featureSet) - { - case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: - case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: - case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: - return false; - case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: - case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: - case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: - case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: - return true; - default: - break; - } + case FeatureSet::FeatureSet_iOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily1_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily2_v5: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v2: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v3: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v1: + case FeatureSet::FeatureSet_iOS_GPUFamily3_v4: + case FeatureSet::FeatureSet_iOS_GPUFamily4_v2: return false; + case FeatureSet::FeatureSet_macOS_GPUFamily1_v1: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v2: + case FeatureSet::FeatureSet_macOS_ReadWriteTextureTier2: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v3: + case FeatureSet::FeatureSet_macOS_GPUFamily1_v4: + case FeatureSet::FeatureSet_macOS_GPUFamily2_v1: + return true; + default: + break; } + return false; +} } bool DeviceInfoMTL::_isDepth24Stencil8PixelFormatSupported = false; DeviceInfoMTL::DeviceInfoMTL(id device) { - _deviceName = [device.name UTF8String]; - + _deviceName = [device.name UTF8String]; + #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) const FeatureSet minRequiredFeatureSet = FeatureSet::FeatureSet_iOS_GPUFamily1_v1; - const FeatureSet maxKnownFeatureSet = FeatureSet::FeatureSet_iOS_GPUFamily4_v2; + const FeatureSet maxKnownFeatureSet = FeatureSet::FeatureSet_iOS_GPUFamily4_v2; #else const FeatureSet minRequiredFeatureSet = FeatureSet::FeatureSet_macOS_GPUFamily1_v1; - const FeatureSet maxKnownFeatureSet = FeatureSet::FeatureSet_macOS_GPUFamily2_v1; + const FeatureSet maxKnownFeatureSet = FeatureSet::FeatureSet_macOS_GPUFamily2_v1; _isDepth24Stencil8PixelFormatSupported = [device isDepth24Stencil8PixelFormatSupported]; #endif - + for (auto featureSet = maxKnownFeatureSet; featureSet >= minRequiredFeatureSet; --featureSet) { if ([device supportsFeatureSet:MTLFeatureSet(featureSet)]) @@ -391,17 +391,17 @@ bool supportS3TC(FeatureSet featureSet) break; } } - + UtilsMTL::initGPUTextureFormats(); } bool DeviceInfoMTL::init() { - _maxAttributes = getMaxVertexAttributes(_featureSet); + _maxAttributes = getMaxVertexAttributes(_featureSet); _maxSamplesAllowed = getMaxSamplerEntries(_featureSet); - _maxTextureUnits = getMaxTextureEntries(_featureSet); - _maxTextureSize = getMaxTextureWidthHeight(_featureSet); - + _maxTextureUnits = getMaxTextureEntries(_featureSet); + _maxTextureSize = getMaxTextureWidthHeight(_featureSet); + return true; } diff --git a/cocos/renderer/backend/metal/DeviceMTL.h b/cocos/renderer/backend/metal/DeviceMTL.h index fac8be126d0c..10cfdd30f23a 100644 --- a/cocos/renderer/backend/metal/DeviceMTL.h +++ b/cocos/renderer/backend/metal/DeviceMTL.h @@ -133,7 +133,7 @@ class DeviceMTL : public Device * @param fragmentShader Specifes this is a fragment shader source. * @return A Program instance. */ - virtual Program* newProgram(const std::string& vertexShader, const std::string& fragmentShader) override; + virtual Program* newProgram(std::string_view vertexShader, std::string_view fragmentShader) override; /** * Get a MTLDevice object. @@ -154,7 +154,7 @@ class DeviceMTL : public Device * @param source Specifies shader source. * @return A ShaderModule object. */ - virtual ShaderModule* newShaderModule(ShaderStage stage, const std::string& source) override; + virtual ShaderModule* newShaderModule(ShaderStage stage, std::string_view source) override; private: static CAMetalLayer* _metalLayer; diff --git a/cocos/renderer/backend/metal/DeviceMTL.mm b/cocos/renderer/backend/metal/DeviceMTL.mm index 174e2807a921..fddde3997e10 100644 --- a/cocos/renderer/backend/metal/DeviceMTL.mm +++ b/cocos/renderer/backend/metal/DeviceMTL.mm @@ -21,7 +21,7 @@ of this software and associated documentation files (the "Software"), to deal OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + #include "DeviceMTL.h" #include "CommandBufferMTL.h" #include "BufferMTL.h" @@ -37,12 +37,12 @@ of this software and associated documentation files (the "Software"), to deal CC_BACKEND_BEGIN -CAMetalLayer* DeviceMTL::_metalLayer = nil; +CAMetalLayer* DeviceMTL::_metalLayer = nil; id DeviceMTL::_currentDrawable = nil; Device* Device::getInstance() { - if (! Device::_instance) + if (!Device::_instance) Device::_instance = new DeviceMTL(); return Device::_instance; @@ -55,9 +55,9 @@ of this software and associated documentation files (the "Software"), to deal id DeviceMTL::getCurrentDrawable() { - if (! DeviceMTL::_currentDrawable) + if (!DeviceMTL::_currentDrawable) DeviceMTL::_currentDrawable = [DeviceMTL::_metalLayer nextDrawable]; - + return DeviceMTL::_currentDrawable; } @@ -68,10 +68,10 @@ of this software and associated documentation files (the "Software"), to deal DeviceMTL::DeviceMTL() { - _mtlDevice = DeviceMTL::_metalLayer.device; + _mtlDevice = DeviceMTL::_metalLayer.device; _mtlCommandQueue = [_mtlDevice newCommandQueue]; - _deviceInfo = new DeviceInfoMTL(_mtlDevice); - if(!_deviceInfo->init()) + _deviceInfo = new DeviceInfoMTL(_mtlDevice); + if (!_deviceInfo->init()) { delete _deviceInfo; _deviceInfo = nullptr; @@ -97,15 +97,15 @@ of this software and associated documentation files (the "Software"), to deal TextureBackend* DeviceMTL::newTexture(const TextureDescriptor& descriptor) { - switch(descriptor.textureType) + switch (descriptor.textureType) { - case TextureType::TEXTURE_2D: - return new TextureMTL(_mtlDevice, descriptor); - case TextureType::TEXTURE_CUBE: - return new TextureCubeMTL(_mtlDevice, descriptor); - default: - CCASSERT(false, "invalidate texture type"); - return nullptr; + case TextureType::TEXTURE_2D: + return new TextureMTL(_mtlDevice, descriptor); + case TextureType::TEXTURE_CUBE: + return new TextureCubeMTL(_mtlDevice, descriptor); + default: + CCASSERT(false, "invalidate texture type"); + return nullptr; } } @@ -117,21 +117,21 @@ of this software and associated documentation files (the "Software"), to deal } RenderTarget* DeviceMTL::newRenderTarget(TargetBufferFlags rtf, - TextureBackend* colorAttachment, - TextureBackend* depthAttachment, - TextureBackend* stencilAttachhment) + TextureBackend* colorAttachment, + TextureBackend* depthAttachment, + TextureBackend* stencilAttachhment) { auto rtGL = new RenderTargetMTL(false); rtGL->setTargetFlags(rtf); rtGL->bindFrameBuffer(); - RenderTarget::ColorAttachment colors{ {colorAttachment, 0} }; + RenderTarget::ColorAttachment colors{{colorAttachment, 0}}; rtGL->setColorAttachment(colors); rtGL->setDepthAttachment(depthAttachment); rtGL->setStencilAttachment(stencilAttachhment); return rtGL; } -ShaderModule* DeviceMTL::newShaderModule(ShaderStage stage, const std::string& source) +ShaderModule* DeviceMTL::newShaderModule(ShaderStage stage, std::string_view source) { return new ShaderModuleMTL(_mtlDevice, stage, source); } @@ -146,7 +146,7 @@ of this software and associated documentation files (the "Software"), to deal return new RenderPipelineMTL(_mtlDevice); } -Program* DeviceMTL::newProgram(const std::string& vertexShader, const std::string& fragmentShader) +Program* DeviceMTL::newProgram(std::string_view vertexShader, std::string_view fragmentShader) { return new ProgramMTL(vertexShader, fragmentShader); } diff --git a/cocos/renderer/backend/metal/ProgramMTL.h b/cocos/renderer/backend/metal/ProgramMTL.h index 0b014941bd18..c6c0be6b9595 100644 --- a/cocos/renderer/backend/metal/ProgramMTL.h +++ b/cocos/renderer/backend/metal/ProgramMTL.h @@ -47,7 +47,7 @@ class ProgramMTL : public Program * @param vertexShader Specifes the vertex shader source. * @param fragmentShader Specifes the fragment shader source. */ - ProgramMTL(const std::string& vertexShader, const std::string& fragmentShader); + ProgramMTL(std::string_view vertexShader, std::string_view fragmentShader); virtual ~ProgramMTL(); /** @@ -55,7 +55,7 @@ class ProgramMTL : public Program * @param uniform Specifies the uniform name. * @return The uniform location. */ - virtual UniformLocation getUniformLocation(const std::string& uniform) const override; + virtual UniformLocation getUniformLocation(std::string_view uniform) const override; /** * Get uniform location by engine built-in uniform enum name. @@ -69,7 +69,7 @@ class ProgramMTL : public Program * @param name Specifies the attribute name. * @return The attribute location. */ - virtual int getAttributeLocation(const std::string& name) const override; + virtual int getAttributeLocation(std::string_view name) const override; /** * Get attribute location by engine built-in attribute enum name. @@ -94,7 +94,7 @@ class ProgramMTL : public Program * Get active vertex attributes. * @return Active vertex attributes. key is active attribute name, Value is corresponding attribute info. */ - const std::unordered_map getActiveAttributes() const override; + const hlookup::string_map getActiveAttributes() const override; /** * Get maximum vertex location. @@ -127,8 +127,7 @@ class ProgramMTL : public Program * Get all uniformInfos. * @return The uniformInfos. */ - virtual const std::unordered_map& getAllActiveUniformInfo( - ShaderStage stage) const override; + virtual const hlookup::string_map& getAllActiveUniformInfo(ShaderStage stage) const override; private: ShaderModuleMTL* _vertexShader = nullptr; diff --git a/cocos/renderer/backend/metal/ProgramMTL.mm b/cocos/renderer/backend/metal/ProgramMTL.mm index d1f2cb7a86bc..3bbe43cae42e 100644 --- a/cocos/renderer/backend/metal/ProgramMTL.mm +++ b/cocos/renderer/backend/metal/ProgramMTL.mm @@ -21,21 +21,24 @@ of this software and associated documentation files (the "Software"), to deal OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + #include "ProgramMTL.h" #include "ShaderModuleMTL.h" #include "base/ccMacros.h" CC_BACKEND_BEGIN -namespace { - const std::string metalSpecificDefine = "#define METAL\n"; +namespace +{ +constexpr std::string_view metalSpecificDefine = "#define METAL\n"sv; } -ProgramMTL::ProgramMTL(const std::string& vertexShader, const std::string& fragmentShader) -: Program(vertexShader, fragmentShader) +ProgramMTL::ProgramMTL(std::string_view vertexShader, std::string_view fragmentShader) + : Program(vertexShader, fragmentShader) { _vertexShader = static_cast(ShaderCache::newVertexShaderModule(vertexShader)); - _fragmentShader = static_cast(ShaderCache::newFragmentShaderModule(std::move(metalSpecificDefine + fragmentShader))); + std::string combinedSource{metalSpecificDefine}; + combinedSource += fragmentShader; + _fragmentShader = static_cast(ShaderCache::newFragmentShaderModule(std::move(combinedSource))); CC_SAFE_RETAIN(_vertexShader); CC_SAFE_RETAIN(_fragmentShader); @@ -52,7 +55,7 @@ of this software and associated documentation files (the "Software"), to deal return _vertexShader->getAttributeLocation(name); } -int ProgramMTL::getAttributeLocation(const std::string &name) const +int ProgramMTL::getAttributeLocation(std::string_view name) const { return _vertexShader->getAttributeLocation(name); } @@ -62,13 +65,13 @@ of this software and associated documentation files (the "Software"), to deal UniformLocation uniformLocation; auto vsLocation = _vertexShader->getUniformLocation(name); auto fsLocation = _fragmentShader->getUniformLocation(name); - if(vsLocation != -1 && fsLocation != -1) + if (vsLocation != -1 && fsLocation != -1) { uniformLocation.shaderStage = ShaderStage::VERTEX_AND_FRAGMENT; uniformLocation.location[0] = vsLocation; uniformLocation.location[1] = fsLocation; } - else if( vsLocation != -1) + else if (vsLocation != -1) { uniformLocation.shaderStage = ShaderStage::VERTEX; uniformLocation.location[0] = vsLocation; @@ -81,18 +84,18 @@ of this software and associated documentation files (the "Software"), to deal return uniformLocation; } -UniformLocation ProgramMTL::getUniformLocation(const std::string& uniform) const +UniformLocation ProgramMTL::getUniformLocation(std::string_view uniform) const { UniformLocation uniformLocation; auto vsLocation = _vertexShader->getUniformLocation(uniform); auto fsLocation = _fragmentShader->getUniformLocation(uniform); - if(vsLocation != -1 && fsLocation != -1) + if (vsLocation != -1 && fsLocation != -1) { uniformLocation.shaderStage = ShaderStage::VERTEX_AND_FRAGMENT; uniformLocation.location[0] = vsLocation; uniformLocation.location[1] = fsLocation; } - else if( vsLocation != -1) + else if (vsLocation != -1) { uniformLocation.shaderStage = ShaderStage::VERTEX; uniformLocation.location[0] = vsLocation; @@ -115,63 +118,64 @@ of this software and associated documentation files (the "Software"), to deal return _fragmentShader->getMaxLocation(); } -const std::unordered_map ProgramMTL::getActiveAttributes() const +const hlookup::string_map ProgramMTL::getActiveAttributes() const { return _vertexShader->getAttributeInfo(); } -//const std::vector& ProgramMTL::cloneUniformBuffer(ShaderStage stage) const +// const std::vector& ProgramMTL::cloneUniformBuffer(ShaderStage stage) const //{ -// switch (stage) { -// case ShaderStage::VERTEX: -// return _vertexShader->cloneUniformBuffer(); -// break; -// case ShaderStage::FRAGMENT: -// return _fragmentShader->cloneUniformBuffer(); -// default: -// CCASSERT(false, "Invalid shader stage."); -// break; -// } -//} +// switch (stage) { +// case ShaderStage::VERTEX: +// return _vertexShader->cloneUniformBuffer(); +// break; +// case ShaderStage::FRAGMENT: +// return _fragmentShader->cloneUniformBuffer(); +// default: +// CCASSERT(false, "Invalid shader stage."); +// break; +// } +// } const UniformInfo& ProgramMTL::getActiveUniformInfo(ShaderStage stage, int location) const { - switch (stage) { - case ShaderStage::VERTEX: - return _vertexShader->getActiveUniform(location); - case ShaderStage::FRAGMENT: - return _fragmentShader->getActiveUniform(location); - default: - CCASSERT(false, "Invalid shader stage."); + switch (stage) + { + case ShaderStage::VERTEX: + return _vertexShader->getActiveUniform(location); + case ShaderStage::FRAGMENT: + return _fragmentShader->getActiveUniform(location); + default: + CCASSERT(false, "Invalid shader stage."); break; } } - std::size_t ProgramMTL::getUniformBufferSize(ShaderStage stage) const { - switch (stage) { - case ShaderStage::VERTEX: - return _vertexShader->getUniformBufferSize(); - case ShaderStage::FRAGMENT: - return _fragmentShader->getUniformBufferSize(); - default: - CCASSERT(false, "Invalid shader stage."); - break; + switch (stage) + { + case ShaderStage::VERTEX: + return _vertexShader->getUniformBufferSize(); + case ShaderStage::FRAGMENT: + return _fragmentShader->getUniformBufferSize(); + default: + CCASSERT(false, "Invalid shader stage."); + break; } return 0; } -const std::unordered_map& ProgramMTL::getAllActiveUniformInfo(ShaderStage stage) const +const hlookup::string_map& ProgramMTL::getAllActiveUniformInfo(ShaderStage stage) const { - switch (stage) { - case ShaderStage::VERTEX: - return _vertexShader->getAllActiveUniformInfo(); - case ShaderStage::FRAGMENT: - return _fragmentShader->getAllActiveUniformInfo(); - default: - CCASSERT(false, "Invalid shader stage."); - break; + switch (stage) + { + case ShaderStage::VERTEX: + return _vertexShader->getAllActiveUniformInfo(); + case ShaderStage::FRAGMENT: + return _fragmentShader->getAllActiveUniformInfo(); + default: + CCASSERT(false, "Invalid shader stage."); } } diff --git a/cocos/renderer/backend/metal/RenderPipelineMTL.mm b/cocos/renderer/backend/metal/RenderPipelineMTL.mm index 14f3e65bf320..30ed67d0087c 100644 --- a/cocos/renderer/backend/metal/RenderPipelineMTL.mm +++ b/cocos/renderer/backend/metal/RenderPipelineMTL.mm @@ -21,7 +21,7 @@ of this software and associated documentation files (the "Software"), to deal OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + #include "RenderPipelineMTL.h" #include "DeviceMTL.h" #include "RenderTargetMTL.h" @@ -35,133 +35,133 @@ of this software and associated documentation files (the "Software"), to deal namespace { - MTLVertexStepFunction toMTLVertexStepFunction(VertexStepMode vertexStepMode) +MTLVertexStepFunction toMTLVertexStepFunction(VertexStepMode vertexStepMode) +{ + if (VertexStepMode::VERTEX == vertexStepMode) + return MTLVertexStepFunctionPerVertex; + else + return MTLVertexStepFunctionPerInstance; +} + +MTLVertexFormat toMTLVertexFormat(VertexFormat vertexFormat, bool needNormalize) +{ + MTLVertexFormat ret = MTLVertexFormatFloat4; + switch (vertexFormat) { - if (VertexStepMode::VERTEX == vertexStepMode) - return MTLVertexStepFunctionPerVertex; + case VertexFormat::FLOAT4: + ret = MTLVertexFormatFloat4; + break; + case VertexFormat::FLOAT3: + ret = MTLVertexFormatFloat3; + break; + case VertexFormat::FLOAT2: + ret = MTLVertexFormatFloat2; + break; + case VertexFormat::FLOAT: + ret = MTLVertexFormatFloat; + break; + case VertexFormat::INT4: + ret = MTLVertexFormatInt4; + break; + case VertexFormat::INT3: + ret = MTLVertexFormatInt3; + break; + case VertexFormat::INT2: + ret = MTLVertexFormatInt2; + break; + case VertexFormat::INT: + ret = MTLVertexFormatInt; + break; + case VertexFormat::USHORT4: + ret = MTLVertexFormatUShort4; + break; + case VertexFormat::USHORT2: + ret = MTLVertexFormatUShort2; + break; + case VertexFormat::UBYTE4: + if (needNormalize) + ret = MTLVertexFormatUChar4Normalized; else - return MTLVertexStepFunctionPerInstance; - } - - MTLVertexFormat toMTLVertexFormat(VertexFormat vertexFormat, bool needNormalize) - { - MTLVertexFormat ret = MTLVertexFormatFloat4; - switch (vertexFormat) - { - case VertexFormat::FLOAT4: - ret = MTLVertexFormatFloat4; - break; - case VertexFormat::FLOAT3: - ret = MTLVertexFormatFloat3; - break; - case VertexFormat::FLOAT2: - ret = MTLVertexFormatFloat2; - break; - case VertexFormat::FLOAT: - ret = MTLVertexFormatFloat; - break; - case VertexFormat::INT4: - ret = MTLVertexFormatInt4; - break; - case VertexFormat::INT3: - ret = MTLVertexFormatInt3; - break; - case VertexFormat::INT2: - ret = MTLVertexFormatInt2; - break; - case VertexFormat::INT: - ret = MTLVertexFormatInt; - break; - case VertexFormat::USHORT4: - ret = MTLVertexFormatUShort4; - break; - case VertexFormat::USHORT2: - ret = MTLVertexFormatUShort2; - break; - case VertexFormat::UBYTE4: - if (needNormalize) - ret = MTLVertexFormatUChar4Normalized; - else - ret = MTLVertexFormatUChar4; - break; - default: - assert(false); - break; - } - return ret; - } - - MTLColorWriteMask toMTLColorWriteMask(ColorWriteMask mask) - { - switch (mask) { - case ColorWriteMask::NONE: - return MTLColorWriteMaskNone; - case ColorWriteMask::RED: - return MTLColorWriteMaskRed; - case ColorWriteMask::GREEN: - return MTLColorWriteMaskGreen; - case ColorWriteMask::BLUE: - return MTLColorWriteMaskBlue; - case ColorWriteMask::ALPHA: - return MTLColorWriteMaskAlpha; - case ColorWriteMask::ALL: - return MTLColorWriteMaskAll; - } + ret = MTLVertexFormatUChar4; + break; + default: + assert(false); + break; } - - MTLBlendFactor toMTLBlendFactor(BlendFactor factor) + return ret; +} + +MTLColorWriteMask toMTLColorWriteMask(ColorWriteMask mask) +{ + switch (mask) { - switch (factor) { - case BlendFactor::ZERO: - return MTLBlendFactorZero; - case BlendFactor::ONE: - return MTLBlendFactorOne; - case BlendFactor::SRC_COLOR: - return MTLBlendFactorSourceColor; - case BlendFactor::ONE_MINUS_SRC_COLOR: - return MTLBlendFactorOneMinusSourceColor; - case BlendFactor::SRC_ALPHA: - return MTLBlendFactorSourceAlpha; - case BlendFactor::ONE_MINUS_SRC_ALPHA: - return MTLBlendFactorOneMinusSourceAlpha; - case BlendFactor::DST_COLOR: - return MTLBlendFactorDestinationColor; - case BlendFactor::ONE_MINUS_DST_COLOR: - return MTLBlendFactorOneMinusDestinationColor; - case BlendFactor::DST_ALPHA: - return MTLBlendFactorDestinationAlpha; - case BlendFactor::ONE_MINUS_DST_ALPHA: - return MTLBlendFactorOneMinusDestinationAlpha; - case BlendFactor::SRC_ALPHA_SATURATE: - return MTLBlendFactorSourceAlphaSaturated; - case BlendFactor::BLEND_CLOLOR: - return MTLBlendFactorBlendColor; - default: - return MTLBlendFactorZero; - } + case ColorWriteMask::NONE: + return MTLColorWriteMaskNone; + case ColorWriteMask::RED: + return MTLColorWriteMaskRed; + case ColorWriteMask::GREEN: + return MTLColorWriteMaskGreen; + case ColorWriteMask::BLUE: + return MTLColorWriteMaskBlue; + case ColorWriteMask::ALPHA: + return MTLColorWriteMaskAlpha; + case ColorWriteMask::ALL: + return MTLColorWriteMaskAll; } - - MTLBlendOperation toMTLBlendOperation(BlendOperation operation) +} + +MTLBlendFactor toMTLBlendFactor(BlendFactor factor) +{ + switch (factor) { - switch (operation) { - case BlendOperation::ADD: - return MTLBlendOperationAdd; - case BlendOperation::SUBTRACT: - return MTLBlendOperationSubtract; - case BlendOperation::RESERVE_SUBTRACT: - return MTLBlendOperationReverseSubtract; - default: - return MTLBlendOperationAdd; - } + case BlendFactor::ZERO: + return MTLBlendFactorZero; + case BlendFactor::ONE: + return MTLBlendFactorOne; + case BlendFactor::SRC_COLOR: + return MTLBlendFactorSourceColor; + case BlendFactor::ONE_MINUS_SRC_COLOR: + return MTLBlendFactorOneMinusSourceColor; + case BlendFactor::SRC_ALPHA: + return MTLBlendFactorSourceAlpha; + case BlendFactor::ONE_MINUS_SRC_ALPHA: + return MTLBlendFactorOneMinusSourceAlpha; + case BlendFactor::DST_COLOR: + return MTLBlendFactorDestinationColor; + case BlendFactor::ONE_MINUS_DST_COLOR: + return MTLBlendFactorOneMinusDestinationColor; + case BlendFactor::DST_ALPHA: + return MTLBlendFactorDestinationAlpha; + case BlendFactor::ONE_MINUS_DST_ALPHA: + return MTLBlendFactorOneMinusDestinationAlpha; + case BlendFactor::SRC_ALPHA_SATURATE: + return MTLBlendFactorSourceAlphaSaturated; + case BlendFactor::BLEND_CLOLOR: + return MTLBlendFactorBlendColor; + default: + return MTLBlendFactorZero; } } -RenderPipelineMTL::RenderPipelineMTL(id mtlDevice) -: _mtlDevice(mtlDevice) +MTLBlendOperation toMTLBlendOperation(BlendOperation operation) { + switch (operation) + { + case BlendOperation::ADD: + return MTLBlendOperationAdd; + case BlendOperation::SUBTRACT: + return MTLBlendOperationSubtract; + case BlendOperation::RESERVE_SUBTRACT: + return MTLBlendOperationReverseSubtract; + default: + return MTLBlendOperationAdd; + } +} } -void RenderPipelineMTL::update(const RenderTarget* renderTarget, const PipelineDescriptor & pipelineDescirptor) +RenderPipelineMTL::RenderPipelineMTL(id mtlDevice) : _mtlDevice(mtlDevice) {} + +void RenderPipelineMTL::update(const RenderTarget* renderTarget, const PipelineDescriptor& pipelineDescirptor) { struct { @@ -179,135 +179,140 @@ MTLBlendOperation toMTLBlendOperation(BlendOperation operation) unsigned int destinationRGBBlendFactor; unsigned int sourceAlphaBlendFactor; unsigned int destinationAlphaBlendFactor; - }hashMe; - + } hashMe; + memset(&hashMe, 0, sizeof(hashMe)); const auto& blendDescriptor = pipelineDescirptor.blendDescriptor; chooseAttachmentFormat(renderTarget, _colorAttachmentsFormat, _depthAttachmentFormat, _stencilAttachmentFormat); - auto program = static_cast(pipelineDescirptor.programState->getProgram()); - hashMe.vertexShaderHash = program->getVertexShader()->getHashValue(); + auto program = static_cast(pipelineDescirptor.programState->getProgram()); + hashMe.vertexShaderHash = program->getVertexShader()->getHashValue(); hashMe.fragmentShaderHash = program->getFragmentShader()->getHashValue(); memcpy(&hashMe.colorAttachment, &_colorAttachmentsFormat, sizeof(_colorAttachmentsFormat)); - hashMe.depthAttachment = _depthAttachmentFormat; - hashMe.stencilAttachment =_stencilAttachmentFormat; - hashMe.blendEnabled = blendDescriptor.blendEnabled; - hashMe.writeMask = (unsigned int)blendDescriptor.writeMask; - hashMe.rgbBlendOperation = (unsigned int)blendDescriptor.rgbBlendOperation; - hashMe.alphaBlendOperation = (unsigned int)blendDescriptor.alphaBlendOperation; - hashMe.sourceRGBBlendFactor = (unsigned int)blendDescriptor.sourceRGBBlendFactor; - hashMe.destinationRGBBlendFactor = (unsigned int)blendDescriptor.destinationRGBBlendFactor; - hashMe.sourceAlphaBlendFactor = (unsigned int)blendDescriptor.sourceAlphaBlendFactor; + hashMe.depthAttachment = _depthAttachmentFormat; + hashMe.stencilAttachment = _stencilAttachmentFormat; + hashMe.blendEnabled = blendDescriptor.blendEnabled; + hashMe.writeMask = (unsigned int)blendDescriptor.writeMask; + hashMe.rgbBlendOperation = (unsigned int)blendDescriptor.rgbBlendOperation; + hashMe.alphaBlendOperation = (unsigned int)blendDescriptor.alphaBlendOperation; + hashMe.sourceRGBBlendFactor = (unsigned int)blendDescriptor.sourceRGBBlendFactor; + hashMe.destinationRGBBlendFactor = (unsigned int)blendDescriptor.destinationRGBBlendFactor; + hashMe.sourceAlphaBlendFactor = (unsigned int)blendDescriptor.sourceAlphaBlendFactor; hashMe.destinationAlphaBlendFactor = (unsigned int)blendDescriptor.destinationAlphaBlendFactor; - int index = 0; - auto vertexLayout = pipelineDescirptor.programState->getVertexLayout(); - const auto& attributes = vertexLayout->getAttributes(); + int index = 0; + auto vertexLayout = pipelineDescirptor.programState->getVertexLayout(); + const auto& attributes = vertexLayout->getAttributes(); for (const auto& it : attributes) { - auto &attribute = it.second; + auto& attribute = it.second; /* stepFunction:1 stride:15 offest:10 format:5 needNormalized:1 bit31 bit30 ~ bit16 bit15 ~ bit6 bit5 ~ bit1 bit0 */ hashMe.vertexLayoutInfo[index++] = - ((unsigned int)vertexLayout->getVertexStepMode() & 0x1) << 31 | - ((unsigned int)(vertexLayout->getStride() & 0x7FFF)) << 16 | - ((unsigned int)attribute.offset & 0x3FF) << 6 | - ((unsigned int)attribute.format & 0x1F) << 1 | - ((unsigned int)attribute.needToBeNormallized & 0x1); + ((unsigned int)vertexLayout->getVertexStepMode() & 0x1) << 31 | + ((unsigned int)(vertexLayout->getStride() & 0x7FFF)) << 16 | ((unsigned int)attribute.offset & 0x3FF) << 6 | + ((unsigned int)attribute.format & 0x1F) << 1 | ((unsigned int)attribute.needToBeNormallized & 0x1); } - + unsigned int hash = XXH32((const void*)&hashMe, sizeof(hashMe), 0); - auto it = _mtlStateCache.find(hash); - if(it != _mtlStateCache.end()) { + auto it = _mtlStateCache.find(hash); + if (it != _mtlStateCache.end()) + { _mtlRenderPipelineState = it->second; return; } - + _mtlRenderPipelineDescriptor = [[MTLRenderPipelineDescriptor alloc] init]; - + setShaderModules(pipelineDescirptor); setVertexLayout(_mtlRenderPipelineDescriptor, pipelineDescirptor); - + setBlendStateAndFormat(pipelineDescirptor.blendDescriptor); - - NSError *error = nil; - _mtlRenderPipelineState = [_mtlDevice newRenderPipelineStateWithDescriptor:_mtlRenderPipelineDescriptor error:&error]; + + NSError* error = nil; + _mtlRenderPipelineState = [_mtlDevice newRenderPipelineStateWithDescriptor:_mtlRenderPipelineDescriptor + error:&error]; if (error) NSLog(@"Can not create renderpipeline state: %@", error); - + [_mtlRenderPipelineDescriptor release]; - + _mtlStateCache.emplace(hash, _mtlRenderPipelineState); } RenderPipelineMTL::~RenderPipelineMTL() { - for(auto& item : _mtlStateCache) + for (auto& item : _mtlStateCache) [item.second release]; } -void RenderPipelineMTL::setVertexLayout(MTLRenderPipelineDescriptor* mtlDescriptor, const PipelineDescriptor& descriptor) +void RenderPipelineMTL::setVertexLayout(MTLRenderPipelineDescriptor* mtlDescriptor, + const PipelineDescriptor& descriptor) { - int vertexIndex = 0; + int vertexIndex = 0; auto vertexLayout = descriptor.programState->getVertexLayout(); if (!vertexLayout->isValid()) return; - + mtlDescriptor.vertexDescriptor.layouts[vertexIndex].stride = vertexLayout->getStride(); - mtlDescriptor.vertexDescriptor.layouts[vertexIndex].stepFunction = toMTLVertexStepFunction(vertexLayout->getVertexStepMode()); - + mtlDescriptor.vertexDescriptor.layouts[vertexIndex].stepFunction = + toMTLVertexStepFunction(vertexLayout->getVertexStepMode()); + const auto& attributes = vertexLayout->getAttributes(); for (const auto& it : attributes) { auto attribute = it.second; - mtlDescriptor.vertexDescriptor.attributes[attribute.index].format = toMTLVertexFormat(attribute.format, attribute.needToBeNormallized); + mtlDescriptor.vertexDescriptor.attributes[attribute.index].format = + toMTLVertexFormat(attribute.format, attribute.needToBeNormallized); mtlDescriptor.vertexDescriptor.attributes[attribute.index].offset = attribute.offset; // Buffer index will always be 0; mtlDescriptor.vertexDescriptor.attributes[attribute.index].bufferIndex = 0; } - } void RenderPipelineMTL::setBlendState(MTLRenderPipelineColorAttachmentDescriptor* colorAttachmentDescriptor, const BlendDescriptor& blendDescriptor) { colorAttachmentDescriptor.blendingEnabled = blendDescriptor.blendEnabled; - colorAttachmentDescriptor.writeMask = toMTLColorWriteMask(blendDescriptor.writeMask); - - colorAttachmentDescriptor.rgbBlendOperation = toMTLBlendOperation(blendDescriptor.rgbBlendOperation); + colorAttachmentDescriptor.writeMask = toMTLColorWriteMask(blendDescriptor.writeMask); + + colorAttachmentDescriptor.rgbBlendOperation = toMTLBlendOperation(blendDescriptor.rgbBlendOperation); colorAttachmentDescriptor.alphaBlendOperation = toMTLBlendOperation(blendDescriptor.alphaBlendOperation); - - colorAttachmentDescriptor.sourceRGBBlendFactor = toMTLBlendFactor(blendDescriptor.sourceRGBBlendFactor); + + colorAttachmentDescriptor.sourceRGBBlendFactor = toMTLBlendFactor(blendDescriptor.sourceRGBBlendFactor); colorAttachmentDescriptor.destinationRGBBlendFactor = toMTLBlendFactor(blendDescriptor.destinationRGBBlendFactor); - colorAttachmentDescriptor.sourceAlphaBlendFactor = toMTLBlendFactor(blendDescriptor.sourceAlphaBlendFactor); - colorAttachmentDescriptor.destinationAlphaBlendFactor = toMTLBlendFactor(blendDescriptor.destinationAlphaBlendFactor); + colorAttachmentDescriptor.sourceAlphaBlendFactor = toMTLBlendFactor(blendDescriptor.sourceAlphaBlendFactor); + colorAttachmentDescriptor.destinationAlphaBlendFactor = + toMTLBlendFactor(blendDescriptor.destinationAlphaBlendFactor); } void RenderPipelineMTL::setShaderModules(const PipelineDescriptor& descriptor) { auto vertexShaderModule = static_cast(descriptor.programState->getProgram())->getVertexShader(); _mtlRenderPipelineDescriptor.vertexFunction = vertexShaderModule->getMTLFunction(); - + auto fragShaderModule = static_cast(descriptor.programState->getProgram())->getFragmentShader(); _mtlRenderPipelineDescriptor.fragmentFunction = fragShaderModule->getMTLFunction(); } void RenderPipelineMTL::chooseAttachmentFormat(const RenderTarget* renderTarget, - PixelFormat colorAttachmentsFormat[MAX_COLOR_ATTCHMENT], - PixelFormat& depthFormat, - PixelFormat& stencilFormat) + PixelFormat colorAttachmentsFormat[MAX_COLOR_ATTCHMENT], + PixelFormat& depthFormat, + PixelFormat& stencilFormat) { // Choose color attachment format - auto rtMTL = static_cast(renderTarget); + auto rtMTL = static_cast(renderTarget); auto rtflags = rtMTL->getTargetFlags(); - for(auto i = 0; i < MAX_COLOR_ATTCHMENT; ++i) { - colorAttachmentsFormat[i] = bitmask::any(rtflags, getMRTColorFlag(i)) ? rtMTL->getColorAttachmentPixelFormat(i) : PixelFormat::NONE; + for (auto i = 0; i < MAX_COLOR_ATTCHMENT; ++i) + { + colorAttachmentsFormat[i] = + bitmask::any(rtflags, getMRTColorFlag(i)) ? rtMTL->getColorAttachmentPixelFormat(i) : PixelFormat::NONE; } - + if (bitmask::any(rtflags, RenderTargetFlag::DEPTH_AND_STENCIL)) { - depthFormat = rtMTL->getDepthAttachmentPixelFormat(); - stencilFormat =rtMTL->getStencilAttachmentPixelFormat(); + depthFormat = rtMTL->getDepthAttachmentPixelFormat(); + stencilFormat = rtMTL->getStencilAttachmentPixelFormat(); } else { @@ -319,15 +324,17 @@ MTLBlendOperation toMTLBlendOperation(BlendOperation operation) { for (int i = 0; i < MAX_COLOR_ATTCHMENT; ++i) { - if (PixelFormat::NONE == _colorAttachmentsFormat[i]) { + if (PixelFormat::NONE == _colorAttachmentsFormat[i]) + { _mtlRenderPipelineDescriptor.colorAttachments[i].pixelFormat = MTLPixelFormat::MTLPixelFormatInvalid; continue; } - - _mtlRenderPipelineDescriptor.colorAttachments[i].pixelFormat = UtilsMTL::toMTLPixelFormat(_colorAttachmentsFormat[i]); + + _mtlRenderPipelineDescriptor.colorAttachments[i].pixelFormat = + UtilsMTL::toMTLPixelFormat(_colorAttachmentsFormat[i]); setBlendState(_mtlRenderPipelineDescriptor.colorAttachments[i], blendDescriptor); } - _mtlRenderPipelineDescriptor.depthAttachmentPixelFormat = UtilsMTL::toMTLPixelFormat(_depthAttachmentFormat); + _mtlRenderPipelineDescriptor.depthAttachmentPixelFormat = UtilsMTL::toMTLPixelFormat(_depthAttachmentFormat); _mtlRenderPipelineDescriptor.stencilAttachmentPixelFormat = UtilsMTL::toMTLPixelFormat(_stencilAttachmentFormat); } diff --git a/cocos/renderer/backend/metal/RenderTargetMTL.mm b/cocos/renderer/backend/metal/RenderTargetMTL.mm index cd9b46e1618b..d909f2efff5a 100644 --- a/cocos/renderer/backend/metal/RenderTargetMTL.mm +++ b/cocos/renderer/backend/metal/RenderTargetMTL.mm @@ -3,83 +3,77 @@ CC_BACKEND_BEGIN -static MTLLoadAction getLoadAction(const RenderPassDescriptor& params, - TargetBufferFlags buffer) { - const auto clearFlags = (TargetBufferFlags) params.flags.clear; +static MTLLoadAction getLoadAction(const RenderPassDescriptor& params, TargetBufferFlags buffer) +{ + const auto clearFlags = (TargetBufferFlags)params.flags.clear; const auto discardStartFlags = params.flags.discardStart; - if (bitmask::any(clearFlags, buffer)) { + if (bitmask::any(clearFlags, buffer)) + { return MTLLoadActionClear; - } else if (bitmask::any(discardStartFlags, buffer)) { + } + else if (bitmask::any(discardStartFlags, buffer)) + { return MTLLoadActionDontCare; } return MTLLoadActionLoad; } -static MTLStoreAction getStoreAction(const RenderPassDescriptor& params, - TargetBufferFlags buffer) { +static MTLStoreAction getStoreAction(const RenderPassDescriptor& params, TargetBufferFlags buffer) +{ const auto discardEndFlags = params.flags.discardEnd; - if (bitmask::any(discardEndFlags, buffer)) { + if (bitmask::any(discardEndFlags, buffer)) + { return MTLStoreActionDontCare; } return MTLStoreActionStore; } -RenderTargetMTL::RenderTargetMTL(bool defaultRenderTarget) : RenderTarget(defaultRenderTarget) -{ - -} -RenderTargetMTL::~RenderTargetMTL() -{ -} +RenderTargetMTL::RenderTargetMTL(bool defaultRenderTarget) : RenderTarget(defaultRenderTarget) {} +RenderTargetMTL::~RenderTargetMTL() {} -void RenderTargetMTL::bindFrameBuffer() const -{ -} +void RenderTargetMTL::bindFrameBuffer() const {} -void RenderTargetMTL::unbindFrameBuffer() const -{ -} +void RenderTargetMTL::unbindFrameBuffer() const {} void RenderTargetMTL::setColorAttachment(ColorAttachment attachment) { RenderTarget::setColorAttachment(attachment); - - } void RenderTargetMTL::setDepthAttachment(TextureBackend* attachment, int level) { RenderTarget::setDepthAttachment(attachment, level); - - } void RenderTargetMTL::setStencilAttachment(TextureBackend* attachment, int level) { RenderTarget::setStencilAttachment(attachment, level); - } -void RenderTargetMTL::applyRenderPassAttachments(const RenderPassDescriptor& params, MTLRenderPassDescriptor* descriptor) const +void RenderTargetMTL::applyRenderPassAttachments(const RenderPassDescriptor& params, + MTLRenderPassDescriptor* descriptor) const { // const auto discardFlags = params.flags.discardEnd; auto clearFlags = params.flags.clear; - - for (size_t i = 0; i < MAX_COLOR_ATTCHMENT; i++) { + + for (size_t i = 0; i < MAX_COLOR_ATTCHMENT; i++) + { auto attachment = getColorAttachment(i); - if (!attachment) { + if (!attachment) + { continue; } - + const auto MRTColorFlag = getMRTColorFlag(i); - + descriptor.colorAttachments[i].texture = attachment.texture; - descriptor.colorAttachments[i].level = attachment.level; + descriptor.colorAttachments[i].level = attachment.level; // descriptor.colorAttachments[i].slice = attachment.layer; - descriptor.colorAttachments[i].loadAction = getLoadAction(params, MRTColorFlag); - descriptor.colorAttachments[i].storeAction = getStoreAction(params,MRTColorFlag); - if(bitmask::any(clearFlags, MRTColorFlag)) - descriptor.colorAttachments[i].clearColor = MTLClearColorMake( - params.clearColorValue[0], params.clearColorValue[1], params.clearColorValue[2], params.clearColorValue[3]); + descriptor.colorAttachments[i].loadAction = getLoadAction(params, MRTColorFlag); + descriptor.colorAttachments[i].storeAction = getStoreAction(params, MRTColorFlag); + if (bitmask::any(clearFlags, MRTColorFlag)) + descriptor.colorAttachments[i].clearColor = + MTLClearColorMake(params.clearColorValue[0], params.clearColorValue[1], params.clearColorValue[2], + params.clearColorValue[3]); #if 0 if (multisampledColor[i]) { // We're rendering into our temporary MSAA texture and doing an automatic resolve. @@ -99,32 +93,35 @@ static MTLStoreAction getStoreAction(const RenderPassDescriptor& params, } #endif } - + // Sets descriptor depth and stencil params, should match RenderTargetMTL::chooseAttachmentFormat - if(bitmask::any(this->_flags, RenderTargetFlag::DEPTH_AND_STENCIL)) { + if (bitmask::any(this->_flags, RenderTargetFlag::DEPTH_AND_STENCIL)) + { auto depthAttachment = getDepthAttachment(); - if(depthAttachment){ + if (depthAttachment) + { descriptor.depthAttachment.texture = depthAttachment.texture; - descriptor.depthAttachment.level = depthAttachment.level; + descriptor.depthAttachment.level = depthAttachment.level; // descriptor.depthAttachment.slice = depthAttachment.layer; - descriptor.depthAttachment.loadAction = getLoadAction(params, TargetBufferFlags::DEPTH); + descriptor.depthAttachment.loadAction = getLoadAction(params, TargetBufferFlags::DEPTH); descriptor.depthAttachment.storeAction = getStoreAction(params, TargetBufferFlags::DEPTH); - if(bitmask::any(clearFlags, TargetBufferFlags::DEPTH)) + if (bitmask::any(clearFlags, TargetBufferFlags::DEPTH)) descriptor.depthAttachment.clearDepth = params.clearDepthValue; } - + auto stencilAttachment = getStencilAttachment(); - if(stencilAttachment) { + if (stencilAttachment) + { descriptor.stencilAttachment.texture = stencilAttachment.texture; - descriptor.stencilAttachment.level = stencilAttachment.level; + descriptor.stencilAttachment.level = stencilAttachment.level; // descriptor.stencilAttachment.slice = depthAttachment.layer; - descriptor.stencilAttachment.loadAction = getLoadAction(params, TargetBufferFlags::STENCIL); + descriptor.stencilAttachment.loadAction = getLoadAction(params, TargetBufferFlags::STENCIL); descriptor.stencilAttachment.storeAction = getStoreAction(params, TargetBufferFlags::STENCIL); - if(bitmask::any(clearFlags, TargetBufferFlags::STENCIL)) + if (bitmask::any(clearFlags, TargetBufferFlags::STENCIL)) descriptor.stencilAttachment.clearStencil = params.clearStencilValue; } } - + #if 0 if (multisampledDepth) { // We're rendering into our temporary MSAA texture and doing an automatic resolve. @@ -147,15 +144,16 @@ static MTLStoreAction getStoreAction(const RenderPassDescriptor& params, RenderTargetMTL::Attachment RenderTargetMTL::getColorAttachment(int index) const { - if(isDefaultRenderTarget() && index == 0) + if (isDefaultRenderTarget() && index == 0) return {DeviceMTL::getCurrentDrawable().texture, 0}; auto& rb = this->_color[index]; - return RenderTargetMTL::Attachment{static_cast(rb) ? (id)(rb.texture->getHandler()) : nil, rb.level}; + return RenderTargetMTL::Attachment{static_cast(rb) ? (id)(rb.texture->getHandler()) : nil, + rb.level}; } RenderTargetMTL::Attachment RenderTargetMTL::getDepthAttachment() const { - if(isDefaultRenderTarget()) + if (isDefaultRenderTarget()) return {UtilsMTL::getDefaultDepthStencilTexture(), 0}; auto& rb = this->_depth; return RenderTargetMTL::Attachment{!!rb ? (id)(rb.texture->getHandler()) : nil, rb.level}; @@ -163,7 +161,7 @@ static MTLStoreAction getStoreAction(const RenderPassDescriptor& params, RenderTargetMTL::Attachment RenderTargetMTL::getStencilAttachment() const { - if(isDefaultRenderTarget()) + if (isDefaultRenderTarget()) return RenderTargetMTL::Attachment{UtilsMTL::getDefaultDepthStencilTexture(), 0}; auto& rb = this->_stencil; return RenderTargetMTL::Attachment{!!rb ? (id)(rb.texture->getHandler()) : nil, rb.level}; @@ -173,16 +171,17 @@ static MTLStoreAction getStoreAction(const RenderPassDescriptor& params, { // !!!important // the default framebuffer pixel format is: MTLPixelFormatBGRA8Unorm - if(isDefaultRenderTarget() && index == 0) + if (isDefaultRenderTarget() && index == 0) return PixelFormat::BGRA8; auto& rb = this->_color[index]; return rb ? rb.texture->getTextureFormat() : PixelFormat::NONE; } PixelFormat RenderTargetMTL::getDepthAttachmentPixelFormat() const -{ // FIXME: adxe only support D24S8 - if(bitmask::any(_flags, TargetBufferFlags::DEPTH_AND_STENCIL)) { - if(isDefaultRenderTarget() || !_depth) +{ // FIXME: adxe only support D24S8 + if (bitmask::any(_flags, TargetBufferFlags::DEPTH_AND_STENCIL)) + { + if (isDefaultRenderTarget() || !_depth) return PixelFormat::D24S8; return _depth.texture->getTextureFormat(); } @@ -190,9 +189,10 @@ static MTLStoreAction getStoreAction(const RenderPassDescriptor& params, } PixelFormat RenderTargetMTL::getStencilAttachmentPixelFormat() const -{ // FIXME: adxe only support D24S8 - if(bitmask::any(_flags, TargetBufferFlags::DEPTH_AND_STENCIL)) { - if(isDefaultRenderTarget() || !_stencil) +{ // FIXME: adxe only support D24S8 + if (bitmask::any(_flags, TargetBufferFlags::DEPTH_AND_STENCIL)) + { + if (isDefaultRenderTarget() || !_stencil) return PixelFormat::D24S8; return _stencil.texture->getTextureFormat(); } diff --git a/cocos/renderer/backend/metal/ShaderModuleMTL.h b/cocos/renderer/backend/metal/ShaderModuleMTL.h index 1272c3b409a3..d8fe9df735da 100644 --- a/cocos/renderer/backend/metal/ShaderModuleMTL.h +++ b/cocos/renderer/backend/metal/ShaderModuleMTL.h @@ -52,7 +52,7 @@ class ShaderModuleMTL : public ShaderModule * @param stage Specify what kinds of shader to be created. * @param source Specify the shader source. */ - ShaderModuleMTL(id mtlDevice, ShaderStage stage, const std::string& source); + ShaderModuleMTL(id mtlDevice, ShaderStage stage, std::string_view source); ~ShaderModuleMTL(); /** @@ -71,7 +71,7 @@ class ShaderModuleMTL : public ShaderModule * Get all uniformInfos. * @return The uniformInfos. */ - inline const std::unordered_map& getAllActiveUniformInfo() const { return _uniformInfos; } + inline const hlookup::string_map& getAllActiveUniformInfo() const { return _uniformInfos; } /** * Get maximum uniform location. @@ -83,7 +83,7 @@ class ShaderModuleMTL : public ShaderModule * Get active attribute informations. * @return Active attribute informations. key is attribute name and Value is corresponding attribute info. */ - inline const std::unordered_map getAttributeInfo() const { return _attributeInfo; } + inline const hlookup::string_map getAttributeInfo() const { return _attributeInfo; } /** * Get uniform location by engine built-in uniform enum name. @@ -97,7 +97,7 @@ class ShaderModuleMTL : public ShaderModule * @param uniform Specifies the uniform name. * @return The uniform location. */ - int getUniformLocation(const std::string& name) const; + int getUniformLocation(std::string_view name) const; /** * Get attribute location by engine built-in attribute enum name. @@ -111,7 +111,7 @@ class ShaderModuleMTL : public ShaderModule * @param name Specifies the attribute name. * @return The attribute location. */ - int getAttributeLocation(std::string name); + int getAttributeLocation(std::string_view name); /** * Get uniform buffer size in bytes that holds all the uniforms. @@ -128,9 +128,9 @@ class ShaderModuleMTL : public ShaderModule id _mtlFunction = nil; - std::unordered_map _uniformInfos; + hlookup::string_map _uniformInfos; std::unordered_map _activeUniformInfos; - std::unordered_map _attributeInfo; + hlookup::string_map _attributeInfo; int _maxLocation = -1; int _uniformLocation[UNIFORM_MAX]; diff --git a/cocos/renderer/backend/metal/ShaderModuleMTL.mm b/cocos/renderer/backend/metal/ShaderModuleMTL.mm index d0f8291a41cd..f52e414a7868 100644 --- a/cocos/renderer/backend/metal/ShaderModuleMTL.mm +++ b/cocos/renderer/backend/metal/ShaderModuleMTL.mm @@ -21,7 +21,7 @@ of this software and associated documentation files (the "Software"), to deal OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + #include "ShaderModuleMTL.h" #include "DeviceMTL.h" @@ -29,43 +29,41 @@ of this software and associated documentation files (the "Software"), to deal CC_BACKEND_BEGIN -ShaderModuleMTL::ShaderModuleMTL(id mtlDevice, ShaderStage stage, const std::string& source) -: ShaderModule(stage) +ShaderModuleMTL::ShaderModuleMTL(id mtlDevice, ShaderStage stage, std::string_view source) + : ShaderModule(stage) { // Convert GLSL shader to metal shader - //TODO: don't crreate/destroy ctx every time. - glslopt_ctx* ctx = glslopt_initialize(kGlslTargetMetal); + // TODO: don't crreate/destroy ctx every time. + glslopt_ctx* ctx = glslopt_initialize(kGlslTargetMetal); glslopt_shader_type shaderType = stage == ShaderStage::VERTEX ? kGlslOptShaderVertex : kGlslOptShaderFragment; - glslopt_shader* glslShader = glslopt_optimize(ctx, shaderType, source.c_str(), 0); + glslopt_shader* glslShader = glslopt_optimize(ctx, shaderType, source.data(), 0); if (!glslShader) { NSLog(@"Can not translate GLSL shader to metal shader:"); - NSLog(@"%s", source.c_str()); + NSLog(@"%s", source.data()); return; } - + const char* metalShader = glslopt_get_output(glslShader); if (!metalShader) { NSLog(@"Can not get metal shader:"); - NSLog(@"%s", source.c_str()); + NSLog(@"%s", source.data()); glslopt_cleanup(ctx); return; } - -// NSLog(@"%s", metalShader); - + + // NSLog(@"%s", metalShader); + parseAttibute(mtlDevice, glslShader); parseUniform(mtlDevice, glslShader); parseTexture(mtlDevice, glslShader); setBuiltinUniformLocation(); setBuiltinAttributeLocation(); - + NSString* shader = [NSString stringWithUTF8String:metalShader]; NSError* error; - id library = [mtlDevice newLibraryWithSource:shader - options:nil - error:&error]; + id library = [mtlDevice newLibraryWithSource:shader options:nil error:&error]; if (!library) { NSLog(@"Can not compile metal shader: %@", error); @@ -74,7 +72,7 @@ of this software and associated documentation files (the "Software"), to deal glslopt_cleanup(ctx); return; } - + if (ShaderStage::VERTEX == stage) _mtlFunction = [library newFunctionWithName:@"xlatMtlMain1"]; else @@ -85,7 +83,7 @@ of this software and associated documentation files (the "Software"), to deal NSLog(@"%s", metalShader); assert(false); } - + glslopt_shader_delete(glslShader); glslopt_cleanup(ctx); [library release]; @@ -99,26 +97,27 @@ of this software and associated documentation files (the "Software"), to deal void ShaderModuleMTL::parseAttibute(id mtlDevice, glslopt_shader* shader) { const int attributeCount = glslopt_shader_get_input_count(shader); - for(int i = 0; i < attributeCount; i++) + for (int i = 0; i < attributeCount; i++) { const char* parName; glslopt_basic_type parType; glslopt_precision parPrec; int parVecSize, parMatSize, parArrSize, location; - glslopt_shader_get_input_desc(shader, i, &parName, &parType, &parPrec, &parVecSize, &parMatSize, &parArrSize, &location); - + glslopt_shader_get_input_desc(shader, i, &parName, &parType, &parPrec, &parVecSize, &parMatSize, &parArrSize, + &location); + AttributeBindInfo attributeInfo; attributeInfo.attributeName = parName; - attributeInfo.location = location; - _attributeInfo[parName] = attributeInfo; + attributeInfo.location = location; + _attributeInfo[parName] = attributeInfo; } } void ShaderModuleMTL::parseUniform(id mtlDevice, glslopt_shader* shader) { const int uniformCount = glslopt_shader_get_uniform_count(shader); - _uniformBufferSize = glslopt_shader_get_uniform_total_size(shader); - + _uniformBufferSize = glslopt_shader_get_uniform_total_size(shader); + for (int i = 0; i < uniformCount; ++i) { int nextLocation = -1; @@ -126,31 +125,33 @@ of this software and associated documentation files (the "Software"), to deal glslopt_basic_type parType; glslopt_precision parPrec; int parVecSize, parMatSize, parArrSize, location; - if( i+1 < uniformCount) + if (i + 1 < uniformCount) { - glslopt_shader_get_uniform_desc(shader, i+1, &parName, &parType, &parPrec, &parVecSize, &parMatSize, &parArrSize, &location); + glslopt_shader_get_uniform_desc(shader, i + 1, &parName, &parType, &parPrec, &parVecSize, &parMatSize, + &parArrSize, &location); nextLocation = location; } else { nextLocation = static_cast(_uniformBufferSize); } - - glslopt_shader_get_uniform_desc(shader, i, &parName, &parType, &parPrec, &parVecSize, &parMatSize, &parArrSize, &location); - + + glslopt_shader_get_uniform_desc(shader, i, &parName, &parType, &parPrec, &parVecSize, &parMatSize, &parArrSize, + &location); + parArrSize = (parArrSize > 0) ? parArrSize : 1; UniformInfo uniform; - uniform.count = parArrSize; - uniform.location = location; - uniform.isArray = parArrSize; - uniform.size = nextLocation - location; - uniform.bufferOffset = location; - uniform.needConvert = (parVecSize == 3) ? true : false; - uniform.type = static_cast(parType); - uniform.isMatrix = (parMatSize > 1) ? true : false; - _uniformInfos[parName] = uniform; + uniform.count = parArrSize; + uniform.location = location; + uniform.isArray = parArrSize; + uniform.size = nextLocation - location; + uniform.bufferOffset = location; + uniform.needConvert = (parVecSize == 3) ? true : false; + uniform.type = static_cast(parType); + uniform.isMatrix = (parMatSize > 1) ? true : false; + _uniformInfos[parName] = uniform; _activeUniformInfos[location] = uniform; - _maxLocation = _maxLocation < location ? (location + 1) : _maxLocation; + _maxLocation = _maxLocation < location ? (location + 1) : _maxLocation; } } @@ -159,12 +160,12 @@ of this software and associated documentation files (the "Software"), to deal return _uniformLocation[name]; } -int ShaderModuleMTL::getUniformLocation(const std::string& name) const +int ShaderModuleMTL::getUniformLocation(std::string_view name) const { - const auto& iter = _uniformInfos.find(name); - if(iter != _uniformInfos.end()) + auto iter = _uniformInfos.find(name); + if (iter != _uniformInfos.end()) { - return _uniformInfos.at(name).location; + return iter->second.location; } else return -1; @@ -173,44 +174,44 @@ of this software and associated documentation files (the "Software"), to deal void ShaderModuleMTL::setBuiltinUniformLocation() { std::fill(_uniformLocation, _uniformLocation + UNIFORM_MAX, -1); - ///u_mvpMatrix + /// u_mvpMatrix auto iter = _uniformInfos.find(UNIFORM_NAME_MVP_MATRIX); - if(iter != _uniformInfos.end()) + if (iter != _uniformInfos.end()) { _uniformLocation[Uniform::MVP_MATRIX] = iter->second.location; } - - ///u_textColor + + /// u_textColor iter = _uniformInfos.find(UNIFORM_NAME_TEXT_COLOR); - if(iter != _uniformInfos.end()) + if (iter != _uniformInfos.end()) { _uniformLocation[Uniform::TEXT_COLOR] = iter->second.location; } - - ///u_effectColor + + /// u_effectColor iter = _uniformInfos.find(UNIFORM_NAME_EFFECT_COLOR); - if(iter != _uniformInfos.end()) + if (iter != _uniformInfos.end()) { _uniformLocation[Uniform::EFFECT_COLOR] = iter->second.location; } - - ///u_effectType + + /// u_effectType iter = _uniformInfos.find(UNIFORM_NAME_EFFECT_TYPE); - if(iter != _uniformInfos.end()) + if (iter != _uniformInfos.end()) { _uniformLocation[Uniform::EFFECT_TYPE] = iter->second.location; } - - ///u_texture + + /// u_texture iter = _uniformInfos.find(UNIFORM_NAME_TEXTURE); - if(iter != _uniformInfos.end()) + if (iter != _uniformInfos.end()) { _uniformLocation[Uniform::TEXTURE] = iter->second.location; } - - ///u_texture1 + + /// u_texture1 iter = _uniformInfos.find(UNIFORM_NAME_TEXTURE1); - if(iter != _uniformInfos.end()) + if (iter != _uniformInfos.end()) { _uniformLocation[Uniform::TEXTURE1] = iter->second.location; } @@ -221,10 +222,10 @@ of this software and associated documentation files (the "Software"), to deal return _attributeLocation[name]; } -int ShaderModuleMTL::getAttributeLocation(std::string name) +int ShaderModuleMTL::getAttributeLocation(std::string_view name) { auto iter = _attributeInfo.find(name); - if(iter != _attributeInfo.end()) + if (iter != _attributeInfo.end()) return _attributeInfo[name].location; else return -1; @@ -233,23 +234,23 @@ of this software and associated documentation files (the "Software"), to deal void ShaderModuleMTL::setBuiltinAttributeLocation() { std::fill(_attributeLocation, _attributeLocation + ATTRIBUTE_MAX, -1); - ///a_position + /// a_position auto iter = _attributeInfo.find(ATTRIBUTE_NAME_POSITION); - if(iter != _attributeInfo.end()) + if (iter != _attributeInfo.end()) { _attributeLocation[Attribute::POSITION] = iter->second.location; } - - ///a_color + + /// a_color iter = _attributeInfo.find(ATTRIBUTE_NAME_COLOR); - if(iter != _attributeInfo.end()) + if (iter != _attributeInfo.end()) { _attributeLocation[Attribute::COLOR] = iter->second.location; } - - ///a_texCoord + + /// a_texCoord iter = _attributeInfo.find(ATTRIBUTE_NAME_TEXCOORD); - if(iter != _attributeInfo.end()) + if (iter != _attributeInfo.end()) { _attributeLocation[Attribute::TEXCOORD] = iter->second.location; } @@ -264,12 +265,13 @@ of this software and associated documentation files (the "Software"), to deal glslopt_basic_type parType; glslopt_precision parPrec; int parVecSize, parMatSize, parArrSize, location; - glslopt_shader_get_texture_desc(shader, i, &parName, &parType, &parPrec, &parVecSize, &parMatSize, &parArrSize, &location); - + glslopt_shader_get_texture_desc(shader, i, &parName, &parType, &parPrec, &parVecSize, &parMatSize, &parArrSize, + &location); + UniformInfo uniform; - uniform.count = parArrSize; - uniform.location = location; - uniform.isArray = parArrSize > 0; + uniform.count = parArrSize; + uniform.location = location; + uniform.isArray = parArrSize > 0; _uniformInfos[parName] = uniform; } } diff --git a/cocos/renderer/backend/metal/TextureMTL.mm b/cocos/renderer/backend/metal/TextureMTL.mm index ff1929f104cd..332aa6f1e08a 100644 --- a/cocos/renderer/backend/metal/TextureMTL.mm +++ b/cocos/renderer/backend/metal/TextureMTL.mm @@ -21,7 +21,7 @@ of this software and associated documentation files (the "Software"), to deal OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + #include "TextureMTL.h" #include "UtilsMTL.h" #include "base/ccMacros.h" @@ -31,78 +31,86 @@ of this software and associated documentation files (the "Software"), to deal namespace { - MTLSamplerAddressMode toMTLSamplerAddressMode(SamplerAddressMode mode) +MTLSamplerAddressMode toMTLSamplerAddressMode(SamplerAddressMode mode) +{ + MTLSamplerAddressMode ret = MTLSamplerAddressModeRepeat; + switch (mode) { - MTLSamplerAddressMode ret = MTLSamplerAddressModeRepeat; - switch (mode) { - case SamplerAddressMode::REPEAT: - ret = MTLSamplerAddressModeRepeat; - break; - case SamplerAddressMode::MIRROR_REPEAT: - ret = MTLSamplerAddressModeMirrorRepeat; - break; - case SamplerAddressMode::CLAMP_TO_EDGE: - ret = MTLSamplerAddressModeClampToEdge; - break; - default: - CCASSERT(false, "Not supported sampler address mode!"); - break; - } - return ret; + case SamplerAddressMode::REPEAT: + ret = MTLSamplerAddressModeRepeat; + break; + case SamplerAddressMode::MIRROR_REPEAT: + ret = MTLSamplerAddressModeMirrorRepeat; + break; + case SamplerAddressMode::CLAMP_TO_EDGE: + ret = MTLSamplerAddressModeClampToEdge; + break; + default: + CCASSERT(false, "Not supported sampler address mode!"); + break; } - - MTLSamplerMinMagFilter toMTLSamplerMinMagFilter(SamplerFilter mode) + return ret; +} + +MTLSamplerMinMagFilter toMTLSamplerMinMagFilter(SamplerFilter mode) +{ + switch (mode) { - switch (mode) { - case SamplerFilter::NEAREST: - case SamplerFilter::NEAREST_MIPMAP_LINEAR: - case SamplerFilter::NEAREST_MIPMAP_NEAREST: - return MTLSamplerMinMagFilterNearest; - case SamplerFilter::LINEAR: - case SamplerFilter::LINEAR_MIPMAP_LINEAR: - case SamplerFilter::LINEAR_MIPMAP_NEAREST: - return MTLSamplerMinMagFilterLinear; - case SamplerFilter::DONT_CARE: - return MTLSamplerMinMagFilterNearest; - } + case SamplerFilter::NEAREST: + case SamplerFilter::NEAREST_MIPMAP_LINEAR: + case SamplerFilter::NEAREST_MIPMAP_NEAREST: + return MTLSamplerMinMagFilterNearest; + case SamplerFilter::LINEAR: + case SamplerFilter::LINEAR_MIPMAP_LINEAR: + case SamplerFilter::LINEAR_MIPMAP_NEAREST: + return MTLSamplerMinMagFilterLinear; + case SamplerFilter::DONT_CARE: + return MTLSamplerMinMagFilterNearest; } - - bool isColorRenderable(PixelFormat textureFormat) +} + +bool isColorRenderable(PixelFormat textureFormat) +{ + switch (textureFormat) { - switch (textureFormat) - { - case PixelFormat::RGBA8: - case PixelFormat::RGBA4: - case PixelFormat::RGB565: - case PixelFormat::RGB5A1: - return true; - default: - return false; - } + case PixelFormat::RGBA8: + case PixelFormat::RGBA4: + case PixelFormat::RGB565: + case PixelFormat::RGB5A1: + return true; + default: + return false; } } +} /// CLASS TextureInfoMTL id TextureInfoMTL::ensure(int index, int target) { - if(index < CC_META_TEXTURES) { + if (index < CC_META_TEXTURES) + { id& mtlTexture = _mtlTextures[index]; - if(mtlTexture) return mtlTexture; + if (mtlTexture) + return mtlTexture; mtlTexture = createTexture(_mtlDevice, _descriptor, target); - if(_maxIdx < index) _maxIdx = index; + if (_maxIdx < index) + _maxIdx = index; return mtlTexture; } return nil; } -void TextureInfoMTL::destroy() { - if(_maxIdx == -1) return; +void TextureInfoMTL::destroy() +{ + if (_maxIdx == -1) + return; id texture; int i = 0; - while((texture = _mtlTextures[i++])) + while ((texture = _mtlTextures[i++])) [texture release]; - if(_mtlSamplerState) { + if (_mtlSamplerState) + { [_mtlSamplerState release]; _mtlSamplerState = nil; } @@ -112,120 +120,143 @@ bool isColorRenderable(PixelFormat textureFormat) id TextureInfoMTL::createTexture(id mtlDevice, const TextureDescriptor& descriptor, int target) { MTLPixelFormat pixelFormat = UtilsMTL::toMTLPixelFormat(descriptor.textureFormat); - if(pixelFormat == MTLPixelFormatInvalid) + if (pixelFormat == MTLPixelFormatInvalid) return nil; - + MTLTextureDescriptor* textureDescriptor = nil; - switch(target) { + switch (target) + { case MTL_TEXTURE_2D: textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:pixelFormat - width:descriptor.width - height:descriptor.height - mipmapped:YES]; + width:descriptor.width + height:descriptor.height + mipmapped:YES]; break; case MTL_TEXTURE_CUBE: - textureDescriptor = [MTLTextureDescriptor textureCubeDescriptorWithPixelFormat:pixelFormat size:descriptor.width mipmapped:YES]; + textureDescriptor = [MTLTextureDescriptor textureCubeDescriptorWithPixelFormat:pixelFormat + size:descriptor.width + mipmapped:YES]; break; - default: return nil; + default: + return nil; } - + if (TextureUsage::RENDER_TARGET == descriptor.textureUsage) { - //DepthStencil, and Multisample textures must be allocated with the MTLResourceStorageModePrivate resource option - if(PixelFormat::D24S8 == descriptor.textureFormat && target == MTL_TEXTURE_2D) + // DepthStencil, and Multisample textures must be allocated with the MTLResourceStorageModePrivate resource + // option + if (PixelFormat::D24S8 == descriptor.textureFormat && target == MTL_TEXTURE_2D) textureDescriptor.resourceOptions = MTLResourceStorageModePrivate; textureDescriptor.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead; } - + return [mtlDevice newTextureWithDescriptor:textureDescriptor]; } -void TextureInfoMTL::recreateSampler(const SamplerDescriptor &descriptor) +void TextureInfoMTL::recreateSampler(const SamplerDescriptor& descriptor) { - MTLSamplerDescriptor *mtlDescriptor = [MTLSamplerDescriptor new]; - mtlDescriptor.sAddressMode = descriptor.sAddressMode == SamplerAddressMode::DONT_CARE ? _sAddressMode : toMTLSamplerAddressMode(descriptor.sAddressMode); - mtlDescriptor.tAddressMode = descriptor.tAddressMode == SamplerAddressMode::DONT_CARE ? _tAddressMode : toMTLSamplerAddressMode(descriptor.tAddressMode); - - mtlDescriptor.minFilter = descriptor.minFilter == SamplerFilter::DONT_CARE ? _minFilter : toMTLSamplerMinMagFilter(descriptor.minFilter); - mtlDescriptor.magFilter = descriptor.magFilter == SamplerFilter::DONT_CARE ? _magFilter : toMTLSamplerMinMagFilter(descriptor.magFilter); - - if(_mtlSamplerState) + MTLSamplerDescriptor* mtlDescriptor = [MTLSamplerDescriptor new]; + mtlDescriptor.sAddressMode = descriptor.sAddressMode == SamplerAddressMode::DONT_CARE + ? _sAddressMode + : toMTLSamplerAddressMode(descriptor.sAddressMode); + mtlDescriptor.tAddressMode = descriptor.tAddressMode == SamplerAddressMode::DONT_CARE + ? _tAddressMode + : toMTLSamplerAddressMode(descriptor.tAddressMode); + + mtlDescriptor.minFilter = + descriptor.minFilter == SamplerFilter::DONT_CARE ? _minFilter : toMTLSamplerMinMagFilter(descriptor.minFilter); + mtlDescriptor.magFilter = + descriptor.magFilter == SamplerFilter::DONT_CARE ? _magFilter : toMTLSamplerMinMagFilter(descriptor.magFilter); + + if (_mtlSamplerState) { [_mtlSamplerState release]; _mtlSamplerState = nil; } - + _sAddressMode = mtlDescriptor.sAddressMode; _tAddressMode = mtlDescriptor.tAddressMode; - _minFilter = mtlDescriptor.minFilter; - _magFilter = mtlDescriptor.magFilter; - _mipFilter = mtlDescriptor.mipFilter; - + _minFilter = mtlDescriptor.minFilter; + _magFilter = mtlDescriptor.magFilter; + _mipFilter = mtlDescriptor.mipFilter; + _mtlSamplerState = [_mtlDevice newSamplerStateWithDescriptor:mtlDescriptor]; - + [mtlDescriptor release]; } /// CLASS TextureMTL -TextureMTL::TextureMTL(id mtlDevice, const TextureDescriptor& descriptor) -: _textureInfo(mtlDevice) +TextureMTL::TextureMTL(id mtlDevice, const TextureDescriptor& descriptor) : _textureInfo(mtlDevice) { updateTextureDescriptor(descriptor); } -TextureMTL::~TextureMTL() -{ -} +TextureMTL::~TextureMTL() {} -void TextureMTL::updateSamplerDescriptor(const SamplerDescriptor &sampler) +void TextureMTL::updateSamplerDescriptor(const SamplerDescriptor& sampler) { _textureInfo.recreateSampler(sampler); } -void TextureMTL::updateTextureDescriptor(const cocos2d::backend::TextureDescriptor &descriptor, int index) +void TextureMTL::updateTextureDescriptor(const cocos2d::backend::TextureDescriptor& descriptor, int index) { TextureBackend::updateTextureDescriptor(descriptor, index); _textureInfo._descriptor = descriptor; _textureInfo.ensure(index, MTL_TEXTURE_2D); updateSamplerDescriptor(descriptor.samplerDescriptor); - + _textureInfo._bytesPerRow = PixelFormatUtils::computeRowPitch(descriptor.textureFormat, descriptor.width); } -void TextureMTL::updateData(uint8_t* data, std::size_t width , std::size_t height, std::size_t level, int index) +void TextureMTL::updateData(uint8_t* data, std::size_t width, std::size_t height, std::size_t level, int index) { updateSubData(0, 0, width, height, level, data, index); } -void TextureMTL::updateSubData(std::size_t xoffset, std::size_t yoffset, std::size_t width, std::size_t height, std::size_t level, uint8_t* data, int index) +void TextureMTL::updateSubData(std::size_t xoffset, + std::size_t yoffset, + std::size_t width, + std::size_t height, + std::size_t level, + uint8_t* data, + int index) { auto mtlTexture = _textureInfo.ensure(index, MTL_TEXTURE_2D); - if(!mtlTexture) return; - - MTLRegion region = - { + if (!mtlTexture) + return; + + MTLRegion region = { {xoffset, yoffset, 0}, // MTLOrigin {width, height, 1} // MTLSize }; - + auto bytesPerRow = PixelFormatUtils::computeRowPitch(_textureFormat, width); - - [mtlTexture replaceRegion:region - mipmapLevel:level - withBytes:data - bytesPerRow:bytesPerRow]; - - if(!_hasMipmaps && level > 0) + + [mtlTexture replaceRegion:region mipmapLevel:level withBytes:data bytesPerRow:bytesPerRow]; + + if (!_hasMipmaps && level > 0) _hasMipmaps = true; } -void TextureMTL::updateCompressedData(uint8_t *data, std::size_t width, std::size_t height, std::size_t dataLen, std::size_t level, int index) +void TextureMTL::updateCompressedData(uint8_t* data, + std::size_t width, + std::size_t height, + std::size_t dataLen, + std::size_t level, + int index) { updateCompressedSubData(0, 0, width, height, dataLen, level, data, index); } -void TextureMTL::updateCompressedSubData(std::size_t xoffset, std::size_t yoffset, std::size_t width, std::size_t height, std::size_t dataLen, std::size_t level, uint8_t *data, int index) +void TextureMTL::updateCompressedSubData(std::size_t xoffset, + std::size_t yoffset, + std::size_t width, + std::size_t height, + std::size_t dataLen, + std::size_t level, + uint8_t* data, + int index) { updateSubData(xoffset, yoffset, width, height, level, data, index); } @@ -234,8 +265,8 @@ bool isColorRenderable(PixelFormat textureFormat) { if (TextureUsage::RENDER_TARGET == _textureUsage || isColorRenderable(_textureFormat) == false) return; - - if(!_hasMipmaps) + + if (!_hasMipmaps) { _hasMipmaps = true; UtilsMTL::generateMipmaps(reinterpret_cast>(this->getHandler())); @@ -243,54 +274,52 @@ bool isColorRenderable(PixelFormat textureFormat) } /// CLASS TextureCubeMTL -TextureCubeMTL::TextureCubeMTL(id mtlDevice, const TextureDescriptor& descriptor) -: _textureInfo(mtlDevice) +TextureCubeMTL::TextureCubeMTL(id mtlDevice, const TextureDescriptor& descriptor) : _textureInfo(mtlDevice) { updateTextureDescriptor(descriptor); } -TextureCubeMTL::~TextureCubeMTL() -{ -} +TextureCubeMTL::~TextureCubeMTL() {} -void TextureCubeMTL::updateTextureDescriptor(const cocos2d::backend::TextureDescriptor &descriptor, int index) +void TextureCubeMTL::updateTextureDescriptor(const cocos2d::backend::TextureDescriptor& descriptor, int index) { TextureBackend::updateTextureDescriptor(descriptor, index); _textureInfo._descriptor = descriptor; _textureInfo.ensure(index, MTL_TEXTURE_CUBE); updateSamplerDescriptor(descriptor.samplerDescriptor); - + _textureInfo._bytesPerRow = PixelFormatUtils::computeRowPitch(descriptor.textureFormat, descriptor.width); - _bytesPerImage = _textureInfo._bytesPerRow * descriptor.width; - _region = MTLRegionMake2D(0, 0, descriptor.width, descriptor.height); + _bytesPerImage = _textureInfo._bytesPerRow * descriptor.width; + _region = MTLRegionMake2D(0, 0, descriptor.width, descriptor.height); } -void TextureCubeMTL::updateSamplerDescriptor(const SamplerDescriptor &sampler) +void TextureCubeMTL::updateSamplerDescriptor(const SamplerDescriptor& sampler) { _textureInfo.recreateSampler(sampler); } -void TextureCubeMTL::updateFaceData(TextureCubeFace side, void *data, int index) +void TextureCubeMTL::updateFaceData(TextureCubeFace side, void* data, int index) { NSUInteger slice = static_cast(side); - auto mtlTexture = _textureInfo.ensure(index, MTL_TEXTURE_CUBE); - if(!mtlTexture) return; + auto mtlTexture = _textureInfo.ensure(index, MTL_TEXTURE_CUBE); + if (!mtlTexture) + return; [mtlTexture replaceRegion:_region - mipmapLevel:0 - slice:slice - withBytes:data - bytesPerRow:_textureInfo._bytesPerRow - bytesPerImage:_bytesPerImage]; + mipmapLevel:0 + slice:slice + withBytes:data + bytesPerRow:_textureInfo._bytesPerRow + bytesPerImage:_bytesPerImage]; } void TextureCubeMTL::generateMipmaps() { if (TextureUsage::RENDER_TARGET == _textureUsage || isColorRenderable(_textureFormat) == false) return; - - if(!_hasMipmaps) + + if (!_hasMipmaps) { _hasMipmaps = true; UtilsMTL::generateMipmaps(reinterpret_cast>(this->getHandler())); diff --git a/cocos/renderer/backend/metal/UtilsMTL.mm b/cocos/renderer/backend/metal/UtilsMTL.mm index f37389d967f6..7b5ac87a265a 100644 --- a/cocos/renderer/backend/metal/UtilsMTL.mm +++ b/cocos/renderer/backend/metal/UtilsMTL.mm @@ -22,7 +22,7 @@ of this software and associated documentation files (the "Software"), to deal OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + #include "UtilsMTL.h" #include "DeviceMTL.h" #include "DeviceInfoMTL.h" @@ -32,20 +32,21 @@ of this software and associated documentation files (the "Software"), to deal CC_BACKEND_BEGIN -id UtilsMTL::_defaultColorAttachmentTexture = nil; +id UtilsMTL::_defaultColorAttachmentTexture = nil; id UtilsMTL::_defaultDepthStencilAttachmentTexture = nil; -namespace { - MTLPixelFormat getSupportedDepthStencilFormat() - { - MTLPixelFormat pixelFormat = MTLPixelFormatDepth32Float_Stencil8; +namespace +{ +MTLPixelFormat getSupportedDepthStencilFormat() +{ + MTLPixelFormat pixelFormat = MTLPixelFormatDepth32Float_Stencil8; #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) - bool isDepth24Stencil8PixelFormatSupported = DeviceInfoMTL::supportD24S8(); - if(isDepth24Stencil8PixelFormatSupported) - pixelFormat = MTLPixelFormatDepth24Unorm_Stencil8; + bool isDepth24Stencil8PixelFormatSupported = DeviceInfoMTL::supportD24S8(); + if (isDepth24Stencil8PixelFormatSupported) + pixelFormat = MTLPixelFormatDepth24Unorm_Stencil8; #endif - return pixelFormat; - } + return pixelFormat; +} } struct GPUTextureFormatInfo @@ -54,76 +55,77 @@ MTLPixelFormat getSupportedDepthStencilFormat() MTLPixelFormat fmtSrgb; }; -static GPUTextureFormatInfo s_textureFormats[] = -{ +static GPUTextureFormatInfo s_textureFormats[] = { /* pvrtc v1 */ - { MTLPixelFormat(162/*PVRTC_RGB_4BPP*/), MTLPixelFormat(163/*PVRTC_RGB_4BPP_sRGB*/) }, // PTC14 - { MTLPixelFormat(166/*PVRTC_RGBA_4BPP*/), MTLPixelFormat(167/*PVRTC_RGBA_4BPP_sRGB*/) }, // PTC14A - { MTLPixelFormat(160/*PVRTC_RGB_2BPP*/), MTLPixelFormat(161/*PVRTC_RGB_2BPP_sRGB*/) }, // PTC12 - { MTLPixelFormat(164/*PVRTC_RGBA_2BPP*/), MTLPixelFormat(165/*PVRTC_RGBA_2BPP_sRGB*/) }, // PTC12A - + {MTLPixelFormat(162 /*PVRTC_RGB_4BPP*/), MTLPixelFormat(163 /*PVRTC_RGB_4BPP_sRGB*/)}, // PTC14 + {MTLPixelFormat(166 /*PVRTC_RGBA_4BPP*/), MTLPixelFormat(167 /*PVRTC_RGBA_4BPP_sRGB*/)}, // PTC14A + {MTLPixelFormat(160 /*PVRTC_RGB_2BPP*/), MTLPixelFormat(161 /*PVRTC_RGB_2BPP_sRGB*/)}, // PTC12 + {MTLPixelFormat(164 /*PVRTC_RGBA_2BPP*/), MTLPixelFormat(165 /*PVRTC_RGBA_2BPP_sRGB*/)}, // PTC12A + /* etc */ - { MTLPixelFormat(180/*ETC2_RGB8*/), MTLPixelFormat(181/*ETC2_RGB8_sRGB*/) }, // ETC1 - { MTLPixelFormat(180/*ETC2_RGB8*/), MTLPixelFormat(181/*ETC2_RGB8_sRGB*/) }, // ETC2 - { MTLPixelFormat(178/*EAC_RGBA8*/), MTLPixelFormat(179/*EAC_RGBA8_sRGB*/) }, // ETC2A - + {MTLPixelFormat(180 /*ETC2_RGB8*/), MTLPixelFormat(181 /*ETC2_RGB8_sRGB*/)}, // ETC1 + {MTLPixelFormat(180 /*ETC2_RGB8*/), MTLPixelFormat(181 /*ETC2_RGB8_sRGB*/)}, // ETC2 + {MTLPixelFormat(178 /*EAC_RGBA8*/), MTLPixelFormat(179 /*EAC_RGBA8_sRGB*/)}, // ETC2A + /* s3tc */ - { MTLPixelFormat(130/*BC1_RGBA*/), MTLPixelFormat(131/*BC1_RGBA_sRGB*/) }, // S3TC_DXT1/BC1 - { MTLPixelFormat(132/*BC2_RGBA*/), MTLPixelFormat(133/*BC2_RGBA_sRGB*/) }, // S3TC_DXT3/BC2 - { MTLPixelFormat(134/*BC3_RGBA*/), MTLPixelFormat(135/*BC3_RGBA_sRGB*/) }, // S3TC_DXT5/BC3 - + {MTLPixelFormat(130 /*BC1_RGBA*/), MTLPixelFormat(131 /*BC1_RGBA_sRGB*/)}, // S3TC_DXT1/BC1 + {MTLPixelFormat(132 /*BC2_RGBA*/), MTLPixelFormat(133 /*BC2_RGBA_sRGB*/)}, // S3TC_DXT3/BC2 + {MTLPixelFormat(134 /*BC3_RGBA*/), MTLPixelFormat(135 /*BC3_RGBA_sRGB*/)}, // S3TC_DXT5/BC3 + /* atc */ - { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ATC_RGB - { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ATC_EXPLICIT_ALPHA - { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ATC_INTERPOLATED_ALPHA - - /* astc */ + {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // ATC_RGB + {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // ATC_EXPLICIT_ALPHA + {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // ATC_INTERPOLATED_ALPHA + +/* astc */ #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) - { MTLPixelFormatASTC_4x4_LDR, MTLPixelFormatASTC_4x4_sRGB }, // ASTC4x4 - { MTLPixelFormatASTC_5x5_LDR, MTLPixelFormatASTC_5x5_sRGB }, // ASTC5x5 - { MTLPixelFormatASTC_6x6_LDR, MTLPixelFormatASTC_6x6_sRGB }, // ASTC6x6 - { MTLPixelFormatASTC_8x5_LDR, MTLPixelFormatASTC_8x5_sRGB }, // ASTC8x5 - { MTLPixelFormatASTC_8x6_LDR, MTLPixelFormatASTC_8x6_sRGB }, // ASTC8x6 - { MTLPixelFormatASTC_8x8_LDR, MTLPixelFormatASTC_8x8_sRGB }, // ASTC8x8 - { MTLPixelFormatASTC_10x5_LDR, MTLPixelFormatASTC_10x5_sRGB }, // ASTC10x5 + {MTLPixelFormatASTC_4x4_LDR, MTLPixelFormatASTC_4x4_sRGB}, // ASTC4x4 + {MTLPixelFormatASTC_5x5_LDR, MTLPixelFormatASTC_5x5_sRGB}, // ASTC5x5 + {MTLPixelFormatASTC_6x6_LDR, MTLPixelFormatASTC_6x6_sRGB}, // ASTC6x6 + {MTLPixelFormatASTC_8x5_LDR, MTLPixelFormatASTC_8x5_sRGB}, // ASTC8x5 + {MTLPixelFormatASTC_8x6_LDR, MTLPixelFormatASTC_8x6_sRGB}, // ASTC8x6 + {MTLPixelFormatASTC_8x8_LDR, MTLPixelFormatASTC_8x8_sRGB}, // ASTC8x8 + {MTLPixelFormatASTC_10x5_LDR, MTLPixelFormatASTC_10x5_sRGB}, // ASTC10x5 #else - { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ASTC4x4 - { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ASTC5x5 - { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ASTC6x6 - { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ASTC8x5 - { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ASTC8x6 - { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ASTC8x8 - { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // ASTC10x5 + {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // ASTC4x4 + {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // ASTC5x5 + {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // ASTC6x6 + {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // ASTC8x5 + {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // ASTC8x6 + {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // ASTC8x8 + {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // ASTC10x5 #endif - + /* normal */ - { MTLPixelFormatRGBA8Unorm, MTLPixelFormatRGBA8Unorm_sRGB }, // RGBA8 - { MTLPixelFormatBGRA8Unorm, MTLPixelFormatBGRA8Unorm_sRGB }, // BGRA8 - { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // RGB8 - { MTLPixelFormat(40/*B5G6R5Unorm*/), MTLPixelFormatInvalid }, // R5G6B5 - { MTLPixelFormat(42/*ABGR4Unorm*/), MTLPixelFormatInvalid }, // RGBA4 - { MTLPixelFormat(41/*A1BGR5Unorm*/), MTLPixelFormatInvalid }, // RGB5A1 - { MTLPixelFormatA8Unorm, MTLPixelFormatInvalid }, // A8 - { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // L8 - { MTLPixelFormatInvalid, MTLPixelFormatInvalid }, // LA8 - + {MTLPixelFormatRGBA8Unorm, MTLPixelFormatRGBA8Unorm_sRGB}, // RGBA8 + {MTLPixelFormatBGRA8Unorm, MTLPixelFormatBGRA8Unorm_sRGB}, // BGRA8 + {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // RGB8 + {MTLPixelFormat(40 /*B5G6R5Unorm*/), MTLPixelFormatInvalid}, // R5G6B5 + {MTLPixelFormat(42 /*ABGR4Unorm*/), MTLPixelFormatInvalid}, // RGBA4 + {MTLPixelFormat(41 /*A1BGR5Unorm*/), MTLPixelFormatInvalid}, // RGB5A1 + {MTLPixelFormatA8Unorm, MTLPixelFormatInvalid}, // A8 + {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // L8 + {MTLPixelFormatInvalid, MTLPixelFormatInvalid}, // LA8 + /* depth stencil */ - { MTLPixelFormat(255/*Depth24Unorm_Stencil8*/), MTLPixelFormatInvalid }, // D24S8 + {MTLPixelFormat(255 /*Depth24Unorm_Stencil8*/), MTLPixelFormatInvalid}, // D24S8 }; -static_assert(CC_ARRAYSIZE(s_textureFormats) == (int)PixelFormat::COUNT, "The OpenGL GPU texture format info table incomplete!"); +static_assert(CC_ARRAYSIZE(s_textureFormats) == (int)PixelFormat::COUNT, + "The OpenGL GPU texture format info table incomplete!"); void UtilsMTL::initGPUTextureFormats() { - //on mac, D24S8 means MTLPixelFormatDepth24Unorm_Stencil8, while on ios it means MTLPixelFormatDepth32Float_Stencil8 + // on mac, D24S8 means MTLPixelFormatDepth24Unorm_Stencil8, while on ios it means + // MTLPixelFormatDepth32Float_Stencil8 auto& info = s_textureFormats[(int)PixelFormat::D24S8]; - info.fmt = getSupportedDepthStencilFormat(); + info.fmt = getSupportedDepthStencilFormat(); } id UtilsMTL::getDefaultDepthStencilTexture() { - if (! _defaultDepthStencilAttachmentTexture) + if (!_defaultDepthStencilAttachmentTexture) _defaultDepthStencilAttachmentTexture = UtilsMTL::createDepthStencilAttachmentTexture(); - + return _defaultDepthStencilAttachmentTexture; } @@ -134,7 +136,8 @@ MTLPixelFormat getSupportedDepthStencilFormat() MTLPixelFormat UtilsMTL::toMTLPixelFormat(PixelFormat textureFormat) { - if (UTILS_LIKELY(textureFormat < PixelFormat::COUNT)) { + if (UTILS_LIKELY(textureFormat < PixelFormat::COUNT)) + { return s_textureFormats[(int)textureFormat].fmt; } return MTLPixelFormatInvalid; @@ -149,48 +152,49 @@ MTLPixelFormat getSupportedDepthStencilFormat() id UtilsMTL::createDepthStencilAttachmentTexture() { - auto CAMetalLayer = DeviceMTL::getCAMetalLayer(); + auto CAMetalLayer = DeviceMTL::getCAMetalLayer(); MTLTextureDescriptor* textureDescriptor = [[MTLTextureDescriptor alloc] init]; - textureDescriptor.width = CAMetalLayer.drawableSize.width; - textureDescriptor.height = CAMetalLayer.drawableSize.height; - textureDescriptor.pixelFormat = s_textureFormats[(int)PixelFormat::D24S8].fmt; - textureDescriptor.resourceOptions = MTLResourceStorageModePrivate; - textureDescriptor.usage = MTLTextureUsageRenderTarget; - auto ret = [CAMetalLayer.device newTextureWithDescriptor:textureDescriptor]; + textureDescriptor.width = CAMetalLayer.drawableSize.width; + textureDescriptor.height = CAMetalLayer.drawableSize.height; + textureDescriptor.pixelFormat = s_textureFormats[(int)PixelFormat::D24S8].fmt; + textureDescriptor.resourceOptions = MTLResourceStorageModePrivate; + textureDescriptor.usage = MTLTextureUsageRenderTarget; + auto ret = [CAMetalLayer.device newTextureWithDescriptor:textureDescriptor]; [textureDescriptor release]; - + return ret; } void UtilsMTL::generateMipmaps(id texture) { - auto commandQueue = static_cast(DeviceMTL::getInstance())->getMTLCommandQueue(); - auto commandBuffer = [commandQueue commandBuffer]; + auto commandQueue = static_cast(DeviceMTL::getInstance())->getMTLCommandQueue(); + auto commandBuffer = [commandQueue commandBuffer]; id commandEncoder = [commandBuffer blitCommandEncoder]; [commandEncoder generateMipmapsForTexture:texture]; [commandEncoder endEncoding]; [commandBuffer commit]; } -void UtilsMTL::swizzleImage(unsigned char *image, std::size_t width, std::size_t height, MTLPixelFormat format) +void UtilsMTL::swizzleImage(unsigned char* image, std::size_t width, std::size_t height, MTLPixelFormat format) { - if(!image) + if (!image) return; - + auto len = width * height; - switch (format) { - //convert to RGBA - case MTLPixelFormatBGRA8Unorm: - for(int i=0; i ProgramGL::getActiveAttributes() const +const hlookup::string_map ProgramGL::getActiveAttributes() const { - std::unordered_map attributes; + hlookup::string_map attributes; if (!_program) return attributes; @@ -293,9 +293,9 @@ int ProgramGL::getAttributeLocation(Attribute name) const return _builtinAttributeLocation[name]; } -int ProgramGL::getAttributeLocation(const std::string& name) const +int ProgramGL::getAttributeLocation(std::string_view name) const { - return glGetAttribLocation(_program, name.c_str()); + return glGetAttribLocation(_program, name.data()); } UniformLocation ProgramGL::getUniformLocation(backend::Uniform name) const @@ -303,7 +303,7 @@ UniformLocation ProgramGL::getUniformLocation(backend::Uniform name) const return _builtinUniformLocation[name]; } -UniformLocation ProgramGL::getUniformLocation(const std::string& uniform) const +UniformLocation ProgramGL::getUniformLocation(std::string_view uniform) const { UniformLocation uniformLocation; if (_activeUniformInfos.find(uniform) != _activeUniformInfos.end()) @@ -352,7 +352,7 @@ const UniformInfo& ProgramGL::getActiveUniformInfo(ShaderStage stage, int locati return s_emptyInfo; } -const std::unordered_map& ProgramGL::getAllActiveUniformInfo(ShaderStage stage) const +const hlookup::string_map& ProgramGL::getAllActiveUniformInfo(ShaderStage stage) const { return _activeUniformInfos; } diff --git a/cocos/renderer/backend/opengl/ProgramGL.h b/cocos/renderer/backend/opengl/ProgramGL.h index 25be64d6f5aa..d433e94c7d16 100644 --- a/cocos/renderer/backend/opengl/ProgramGL.h +++ b/cocos/renderer/backend/opengl/ProgramGL.h @@ -68,7 +68,7 @@ class ProgramGL : public Program * @param vertexShader Specifes the vertex shader source. * @param fragmentShader Specifes the fragment shader source. */ - ProgramGL(const std::string& vertexShader, const std::string& fragmentShader); + ProgramGL(std::string_view vertexShader, std::string_view fragmentShader); ~ProgramGL(); @@ -89,7 +89,7 @@ class ProgramGL : public Program * @param uniform Specifies the uniform name. * @return The uniform location. */ - virtual UniformLocation getUniformLocation(const std::string& uniform) const override; + virtual UniformLocation getUniformLocation(std::string_view uniform) const override; /** * Get uniform location by engine built-in uniform enum name. @@ -103,7 +103,7 @@ class ProgramGL : public Program * @param name Specifies the attribute name. * @return The attribute location. */ - virtual int getAttributeLocation(const std::string& name) const override; + virtual int getAttributeLocation(std::string_view name) const override; /** * Get attribute location by engine built-in attribute enum name. @@ -128,7 +128,7 @@ class ProgramGL : public Program * Get active vertex attributes. * @return Active vertex attributes. key is active attribute name, Value is corresponding attribute info. */ - virtual const std::unordered_map getActiveAttributes() const override; + virtual const hlookup::string_map getActiveAttributes() const override; /** * Get uniform buffer size in bytes that can hold all the uniforms. @@ -149,12 +149,11 @@ class ProgramGL : public Program * Get all uniformInfos. * @return The uniformInfos. */ - virtual const std::unordered_map& getAllActiveUniformInfo( - ShaderStage stage) const override; + virtual const hlookup::string_map& getAllActiveUniformInfo(ShaderStage stage) const override; private: void compileProgram(); - bool getAttributeLocation(const std::string& attributeName, unsigned int& location) const; + bool getAttributeLocation(std::string_view attributeName, unsigned int& location) const; void computeUniformInfos(); void computeLocations(); #if CC_ENABLE_CACHE_TEXTURE_DATA @@ -172,7 +171,7 @@ class ProgramGL : public Program ShaderModuleGL* _fragmentShaderModule = nullptr; std::vector _attributeInfos; - std::unordered_map _activeUniformInfos; + hlookup::string_map _activeUniformInfos; #if CC_ENABLE_CACHE_TEXTURE_DATA std::unordered_map _originalUniformLocations; ///< record the uniform location when shader was first created. diff --git a/cocos/renderer/backend/opengl/ShaderModuleGL.cpp b/cocos/renderer/backend/opengl/ShaderModuleGL.cpp index 23c1a1629b6e..3b6f49e6dd8c 100644 --- a/cocos/renderer/backend/opengl/ShaderModuleGL.cpp +++ b/cocos/renderer/backend/opengl/ShaderModuleGL.cpp @@ -31,7 +31,7 @@ CC_BACKEND_BEGIN -ShaderModuleGL::ShaderModuleGL(ShaderStage stage, const std::string& source) : ShaderModule(stage) +ShaderModuleGL::ShaderModuleGL(ShaderStage stage, std::string_view source) : ShaderModule(stage) { compileShader(stage, source); } @@ -41,10 +41,10 @@ ShaderModuleGL::~ShaderModuleGL() deleteShader(); } -void ShaderModuleGL::compileShader(ShaderStage stage, const std::string& source) +void ShaderModuleGL::compileShader(ShaderStage stage, std::string_view source) { GLenum shaderType = stage == ShaderStage::VERTEX ? GL_VERTEX_SHADER : GL_FRAGMENT_SHADER; - const GLchar* sourcePtr = reinterpret_cast(source.c_str()); + const GLchar* sourcePtr = reinterpret_cast(source.data()); _shader = glCreateShader(shaderType); if (!_shader) return; @@ -64,7 +64,7 @@ void ShaderModuleGL::compileShader(ShaderStage stage, const std::string& source) cocos2d::Data errorLog{}; glGetShaderInfoLog(_shader, logLength, nullptr, (GLchar*)errorLog.resize(logLength)); cocos2d::log("cocos2d: ERROR: Failed to compile shader, detail: %s\n%s", errorLog.getBytes(), - source.c_str()); + source.data()); } else { diff --git a/cocos/renderer/backend/opengl/ShaderModuleGL.h b/cocos/renderer/backend/opengl/ShaderModuleGL.h index 5bae6962bbc9..81ea52691ad2 100644 --- a/cocos/renderer/backend/opengl/ShaderModuleGL.h +++ b/cocos/renderer/backend/opengl/ShaderModuleGL.h @@ -44,7 +44,7 @@ class ShaderModuleGL : public ShaderModule * @param stage Specifies whether is vertex shader or fragment shader. * @param source Specifies shader source. */ - ShaderModuleGL(ShaderStage stage, const std::string& source); + ShaderModuleGL(ShaderStage stage, std::string_view source); ~ShaderModuleGL(); /** @@ -54,7 +54,7 @@ class ShaderModuleGL : public ShaderModule inline GLuint getShader() const { return _shader; } private: - void compileShader(ShaderStage stage, const std::string& source); + void compileShader(ShaderStage stage, std::string_view source); void deleteShader(); GLuint _shader = 0; diff --git a/cocos/renderer/shaders/label_sdf.frag b/cocos/renderer/shaders/label_sdf.frag new file mode 100644 index 000000000000..00d9133694c8 --- /dev/null +++ b/cocos/renderer/shaders/label_sdf.frag @@ -0,0 +1,52 @@ +/**************************************************************************** + Copyright (c) 2018-2019 Xiamen Yaji Software Co., Ltd. + + 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. + ****************************************************************************/ + +const char* label_distanceNormal_frag = R"( + +#ifdef GL_ES +precision lowp float; +#endif + +varying vec4 v_fragmentColor; +varying vec2 v_texCoord; + +uniform vec4 u_textColor; +uniform sampler2D u_texture; + +void main() +{ + vec4 color = texture2D(u_texture, v_texCoord); + //the texture use dual channel 16-bit output for distance_map + //float dist = color.b+color.g/256.0; + // the texture use single channel 8-bit output for distance_map + float dist = color.a; + //TODO: Implementation 'fwidth' for glsl 1.0 + float width = fwidth(dist); + //assign width for constant will lead to a little bit fuzzy,it's temporary measure. + //float width = 0.04; + //float width = 1.0/16.0; + float alpha = smoothstep(0.5-width, 0.5+width, dist) * u_textColor.a; + gl_FragColor = v_fragmentColor * vec4(u_textColor.rgb,alpha); +} +)"; diff --git a/cocos/ui/CMakeLists.txt b/cocos/ui/CMakeLists.txt index 607206af8638..af648011fef2 100644 --- a/cocos/ui/CMakeLists.txt +++ b/cocos/ui/CMakeLists.txt @@ -1,14 +1,23 @@ if(WINDOWS) - set(COCOS_UI_SPECIFIC_HEADER - ui/UIEditBox/UIEditBoxImpl-win32.h - ui/UIWebView/UIWebViewImpl-win32.h - ui/UIWebView/UIWebView.h - ) - set(COCOS_UI_SPECIFIC_SRC - ui/UIEditBox/UIEditBoxImpl-win32.cpp - ui/UIWebView/UIWebViewImpl-win32.cpp - ui/UIWebView/UIWebView.cpp - ) + if(ADXE_ENABLE_WEBVIEW2) + set(COCOS_UI_SPECIFIC_HEADER + ui/UIEditBox/UIEditBoxImpl-win32.h + ui/UIWebView/UIWebViewImpl-win32.h + ui/UIWebView/UIWebView.h + ) + set(COCOS_UI_SPECIFIC_SRC + ui/UIEditBox/UIEditBoxImpl-win32.cpp + ui/UIWebView/UIWebViewImpl-win32.cpp + ui/UIWebView/UIWebView.cpp + ) + else() + set(COCOS_UI_SPECIFIC_HEADER + ui/UIEditBox/UIEditBoxImpl-win32.h + ) + set(COCOS_UI_SPECIFIC_SRC + ui/UIEditBox/UIEditBoxImpl-win32.cpp + ) + endif() elseif(APPLE) if(MACOSX) set(COCOS_UI_SPECIFIC_HEADER diff --git a/cocos/ui/UIAbstractCheckButton.cpp b/cocos/ui/UIAbstractCheckButton.cpp index aec8a369deb8..412a33b46b29 100644 --- a/cocos/ui/UIAbstractCheckButton.cpp +++ b/cocos/ui/UIAbstractCheckButton.cpp @@ -73,11 +73,11 @@ AbstractCheckButton::AbstractCheckButton() AbstractCheckButton::~AbstractCheckButton() {} -bool AbstractCheckButton::init(const std::string& backGround, - const std::string& backGroundSelected, - const std::string& cross, - const std::string& backGroundDisabled, - const std::string& frontCrossDisabled, +bool AbstractCheckButton::init(std::string_view backGround, + std::string_view backGroundSelected, + std::string_view cross, + std::string_view backGroundDisabled, + std::string_view frontCrossDisabled, TextureResType texType) { bool ret = true; @@ -120,11 +120,11 @@ void AbstractCheckButton::initRenderer() addProtectedChild(_frontCrossDisabledRenderer, FRONTCROSSDISABLED_RENDERER_Z, -1); } -void AbstractCheckButton::loadTextures(const std::string& backGround, - const std::string& backGroundSelected, - const std::string& cross, - const std::string& backGroundDisabled, - const std::string& frontCrossDisabled, +void AbstractCheckButton::loadTextures(std::string_view backGround, + std::string_view backGroundSelected, + std::string_view cross, + std::string_view backGroundDisabled, + std::string_view frontCrossDisabled, TextureResType texType) { loadTextureBackGround(backGround, texType); @@ -134,7 +134,7 @@ void AbstractCheckButton::loadTextures(const std::string& backGround, loadTextureFrontCrossDisabled(frontCrossDisabled, texType); } -void AbstractCheckButton::loadTextureBackGround(const std::string& backGround, TextureResType texType) +void AbstractCheckButton::loadTextureBackGround(std::string_view backGround, TextureResType texType) { _backGroundFileName = backGround; @@ -169,7 +169,7 @@ void AbstractCheckButton::loadTextureBackGround(SpriteFrame* spriteFrame) this->setupBackgroundTexture(); } -void AbstractCheckButton::loadTextureBackGroundSelected(const std::string& backGroundSelected, TextureResType texType) +void AbstractCheckButton::loadTextureBackGroundSelected(std::string_view backGroundSelected, TextureResType texType) { _backGroundSelectedFileName = backGroundSelected; _isBackgroundSelectedTextureLoaded = !backGroundSelected.empty(); @@ -203,7 +203,7 @@ void AbstractCheckButton::setupBackgroundSelectedTexture() _backGroundSelectedBoxRendererAdaptDirty = true; } -void AbstractCheckButton::loadTextureFrontCross(const std::string& cross, TextureResType texType) +void AbstractCheckButton::loadTextureFrontCross(std::string_view cross, TextureResType texType) { _frontCrossFileName = cross; @@ -234,7 +234,7 @@ void AbstractCheckButton::setupFrontCrossTexture() _frontCrossRendererAdaptDirty = true; } -void AbstractCheckButton::loadTextureBackGroundDisabled(const std::string& backGroundDisabled, TextureResType texType) +void AbstractCheckButton::loadTextureBackGroundDisabled(std::string_view backGroundDisabled, TextureResType texType) { _backGroundDisabledFileName = backGroundDisabled; _isBackgroundDisabledTextureLoaded = !backGroundDisabled.empty(); @@ -269,7 +269,7 @@ void AbstractCheckButton::setupBackgroundDisable() _backGroundBoxDisabledRendererAdaptDirty = true; } -void AbstractCheckButton::loadTextureFrontCrossDisabled(const std::string& frontCrossDisabled, TextureResType texType) +void AbstractCheckButton::loadTextureFrontCrossDisabled(std::string_view frontCrossDisabled, TextureResType texType) { _frontCrossDisabledFileName = frontCrossDisabled; _isFrontCrossDisabledTextureLoaded = !frontCrossDisabled.empty(); diff --git a/cocos/ui/UIAbstractCheckButton.h b/cocos/ui/UIAbstractCheckButton.h index 38f97b046ab8..7d801dba7630 100644 --- a/cocos/ui/UIAbstractCheckButton.h +++ b/cocos/ui/UIAbstractCheckButton.h @@ -57,11 +57,11 @@ class CC_GUI_DLL AbstractCheckButton : public Widget * @param frontCrossDisabled The front cross disabled state image name. * @param texType @see `Widget::TextureResType` */ - void loadTextures(const std::string& background, - const std::string& backgroundSelected, - const std::string& cross, - const std::string& backgroundDisabled, - const std::string& frontCrossDisabled, + void loadTextures(std::string_view background, + std::string_view backgroundSelected, + std::string_view cross, + std::string_view backgroundDisabled, + std::string_view frontCrossDisabled, TextureResType texType = TextureResType::LOCAL); /** @@ -70,7 +70,7 @@ class CC_GUI_DLL AbstractCheckButton : public Widget * @param backGround The background image name. * @param type @see `Widget::TextureResType` */ - void loadTextureBackGround(const std::string& backGround, TextureResType type = TextureResType::LOCAL); + void loadTextureBackGround(std::string_view backGround, TextureResType type = TextureResType::LOCAL); /** * Load background selected state texture for check button. @@ -78,7 +78,7 @@ class CC_GUI_DLL AbstractCheckButton : public Widget * @param backGroundSelected The background selected state image name. * @param texType @see `Widget::TextureResType` */ - void loadTextureBackGroundSelected(const std::string& backGroundSelected, + void loadTextureBackGroundSelected(std::string_view backGroundSelected, TextureResType texType = TextureResType::LOCAL); /** @@ -87,7 +87,7 @@ class CC_GUI_DLL AbstractCheckButton : public Widget * @param crossTextureName The cross texture name. * @param texType @see `Widget::TextureResType` */ - void loadTextureFrontCross(const std::string& crossTextureName, TextureResType texType = TextureResType::LOCAL); + void loadTextureFrontCross(std::string_view crossTextureName, TextureResType texType = TextureResType::LOCAL); /** * Load background disabled state texture for checkbox. @@ -96,7 +96,7 @@ class CC_GUI_DLL AbstractCheckButton : public Widget * * @param texType @see `Widget::TextureResType` */ - void loadTextureBackGroundDisabled(const std::string& backGroundDisabled, + void loadTextureBackGroundDisabled(std::string_view backGroundDisabled, TextureResType texType = TextureResType::LOCAL); /** @@ -105,7 +105,7 @@ class CC_GUI_DLL AbstractCheckButton : public Widget * @param frontCrossDisabled The front cross disabled state texture name. * @param texType @see `Widget::TextureResType` */ - void loadTextureFrontCrossDisabled(const std::string& frontCrossDisabled, + void loadTextureFrontCrossDisabled(std::string_view frontCrossDisabled, TextureResType texType = TextureResType::LOCAL); /** @@ -174,11 +174,11 @@ class CC_GUI_DLL AbstractCheckButton : public Widget ResourceData getCrossDisabledFile(); CC_CONSTRUCTOR_ACCESS : virtual bool init() override; - virtual bool init(const std::string& backGround, - const std::string& backGroundSelected, - const std::string& cross, - const std::string& backGroundDisabled, - const std::string& frontCrossDisabled, + virtual bool init(std::string_view backGround, + std::string_view backGroundSelected, + std::string_view cross, + std::string_view backGroundDisabled, + std::string_view frontCrossDisabled, TextureResType texType = TextureResType::LOCAL); protected: diff --git a/cocos/ui/UIButton.cpp b/cocos/ui/UIButton.cpp index 8b2025a1a784..195bdde8ebe4 100644 --- a/cocos/ui/UIButton.cpp +++ b/cocos/ui/UIButton.cpp @@ -92,9 +92,9 @@ Button* Button::create() return nullptr; } -Button* Button::create(const std::string& normalImage, - const std::string& selectedImage, - const std::string& disableImage, +Button* Button::create(std::string_view normalImage, + std::string_view selectedImage, + std::string_view disableImage, TextureResType texType) { Button* btn = new Button; @@ -107,9 +107,9 @@ Button* Button::create(const std::string& normalImage, return nullptr; } -bool Button::init(const std::string& normalImage, - const std::string& selectedImage, - const std::string& disableImage, +bool Button::init(std::string_view normalImage, + std::string_view selectedImage, + std::string_view disableImage, TextureResType texType) { @@ -250,9 +250,9 @@ void Button::ignoreContentAdaptWithSize(bool ignore) } } -void Button::loadTextures(const std::string& normal, - const std::string& selected, - const std::string& disabled, +void Button::loadTextures(std::string_view normal, + std::string_view selected, + std::string_view disabled, TextureResType texType) { loadTextureNormal(normal, texType); @@ -260,7 +260,7 @@ void Button::loadTextures(const std::string& normal, loadTextureDisabled(disabled, texType); } -void Button::loadTextureNormal(const std::string& normal, TextureResType texType) +void Button::loadTextureNormal(std::string_view normal, TextureResType texType) { _normalFileName = normal; _normalTexType = texType; @@ -319,7 +319,7 @@ void Button::loadTextureNormal(SpriteFrame* normalSpriteFrame) this->setupNormalTexture(nullptr != normalSpriteFrame); } -void Button::loadTexturePressed(const std::string& selected, TextureResType texType) +void Button::loadTexturePressed(std::string_view selected, TextureResType texType) { _clickedFileName = selected; _pressedTexType = texType; @@ -362,7 +362,7 @@ void Button::loadTexturePressed(SpriteFrame* pressedSpriteFrame) this->setupPressedTexture(nullptr != pressedSpriteFrame); } -void Button::loadTextureDisabled(const std::string& disabled, TextureResType texType) +void Button::loadTextureDisabled(std::string_view disabled, TextureResType texType) { _disabledFileName = disabled; _disabledTexType = texType; @@ -718,7 +718,7 @@ void Button::setTitleAlignment(TextHAlignment hAlignment, TextVAlignment vAlignm _titleRenderer->setAlignment(hAlignment, vAlignment); } -void Button::setTitleText(const std::string& text) +void Button::setTitleText(std::string_view text) { if (text.compare(getTitleText()) == 0) { @@ -737,7 +737,7 @@ void Button::setTitleText(const std::string& text) updateTitleLocation(); } -std::string Button::getTitleText() const +std::string_view Button::getTitleText() const { if (!_titleRenderer) { @@ -806,13 +806,13 @@ float Button::getZoomScale() const return _zoomScale; } -void Button::setTitleFontName(const std::string& fontName) +void Button::setTitleFontName(std::string_view fontName) { createTitleRendererIfNull(); if (FileUtils::getInstance()->isFileExist(fontName)) { - std::string lowerCasedFontName = fontName; + std::string lowerCasedFontName{fontName}; std::transform(lowerCasedFontName.begin(), lowerCasedFontName.end(), lowerCasedFontName.begin(), ::tolower); if (lowerCasedFontName.find(".fnt") != std::string::npos) { @@ -838,7 +838,7 @@ Label* Button::getTitleRenderer() const return _titleRenderer; } -std::string Button::getTitleFontName() const +std::string_view Button::getTitleFontName() const { if (_titleRenderer) { @@ -857,7 +857,7 @@ std::string Button::getTitleFontName() const } } - return ""; + return ""sv; } std::string Button::getDescription() const diff --git a/cocos/ui/UIButton.h b/cocos/ui/UIButton.h index 3db6e5c1231a..ad881f2d392a 100644 --- a/cocos/ui/UIButton.h +++ b/cocos/ui/UIButton.h @@ -80,10 +80,10 @@ class CC_GUI_DLL Button : public Widget * @param texType @see `TextureResType` * @return a Button instance. */ - static Button* create(const std::string& normalImage, - const std::string& selectedImage = "", - const std::string& disableImage = "", - TextureResType texType = TextureResType::LOCAL); + static Button* create(std::string_view normalImage, + std::string_view selectedImage = "", + std::string_view disableImage = "", + TextureResType texType = TextureResType::LOCAL); /** * Load textures for button. @@ -93,10 +93,10 @@ class CC_GUI_DLL Button : public Widget * @param disabled disabled state texture name. * @param texType @see `TextureResType` */ - void loadTextures(const std::string& normal, - const std::string& selected, - const std::string& disabled = "", - TextureResType texType = TextureResType::LOCAL); + void loadTextures(std::string_view normal, + std::string_view selected, + std::string_view disabled = "", + TextureResType texType = TextureResType::LOCAL); /** * Load normal state texture for button. @@ -104,7 +104,7 @@ class CC_GUI_DLL Button : public Widget * @param normal normal state texture. * @param texType @see `TextureResType` */ - void loadTextureNormal(const std::string& normal, TextureResType texType = TextureResType::LOCAL); + void loadTextureNormal(std::string_view normal, TextureResType texType = TextureResType::LOCAL); /** * Load selected state texture for button. @@ -112,7 +112,7 @@ class CC_GUI_DLL Button : public Widget * @param selected selected state texture. * @param texType @see `TextureResType` */ - void loadTexturePressed(const std::string& selected, TextureResType texType = TextureResType::LOCAL); + void loadTexturePressed(std::string_view selected, TextureResType texType = TextureResType::LOCAL); /** * Load disabled state texture for button. @@ -120,7 +120,7 @@ class CC_GUI_DLL Button : public Widget * @param disabled dark state texture. * @param texType @see `TextureResType` */ - void loadTextureDisabled(const std::string& disabled, TextureResType texType = TextureResType::LOCAL); + void loadTextureDisabled(std::string_view disabled, TextureResType texType = TextureResType::LOCAL); /** * Sets capInsets for button. @@ -206,13 +206,13 @@ class CC_GUI_DLL Button : public Widget * Change the content of button's title. *@param text The title in std::string. */ - void setTitleText(const std::string& text); + void setTitleText(std::string_view text); /** * Query the button title content. *@return Get the button's title content. */ - std::string getTitleText() const; + std::string_view getTitleText() const; /** * Change the color of button's title. @@ -242,13 +242,13 @@ class CC_GUI_DLL Button : public Widget * Change the font name of button's title *@param fontName a font name string. */ - void setTitleFontName(const std::string& fontName); + void setTitleFontName(std::string_view fontName); /** * Query the font name of button's title *@return font name in std::string */ - std::string getTitleFontName() const; + std::string_view getTitleFontName() const; /** * Sets the title's text horizontal alignment. @@ -314,10 +314,10 @@ class CC_GUI_DLL Button : public Widget ResourceData getDisabledFile(); CC_CONSTRUCTOR_ACCESS : virtual bool init() override; - virtual bool init(const std::string& normalImage, - const std::string& selectedImage = "", - const std::string& disableImage = "", - TextureResType texType = TextureResType::LOCAL); + virtual bool init(std::string_view normalImage, + std::string_view selectedImage = "", + std::string_view disableImage = "", + TextureResType texType = TextureResType::LOCAL); virtual Vec2 getNormalTextureSize() const; diff --git a/cocos/ui/UICheckBox.cpp b/cocos/ui/UICheckBox.cpp index 6cce622d6f73..c98813b25166 100644 --- a/cocos/ui/UICheckBox.cpp +++ b/cocos/ui/UICheckBox.cpp @@ -48,11 +48,11 @@ CheckBox* CheckBox::create() return nullptr; } -CheckBox* CheckBox::create(const std::string& backGround, - const std::string& backGroundSelected, - const std::string& cross, - const std::string& backGroundDisabled, - const std::string& frontCrossDisabled, +CheckBox* CheckBox::create(std::string_view backGround, + std::string_view backGroundSelected, + std::string_view cross, + std::string_view backGroundDisabled, + std::string_view frontCrossDisabled, TextureResType texType) { CheckBox* pWidget = new CheckBox; @@ -65,7 +65,7 @@ CheckBox* CheckBox::create(const std::string& backGround, return nullptr; } -CheckBox* CheckBox::create(const std::string& backGround, const std::string& cross, TextureResType texType) +CheckBox* CheckBox::create(std::string_view backGround, std::string_view cross, TextureResType texType) { CheckBox* pWidget = new CheckBox; if (pWidget->init(backGround, "", cross, "", "", texType)) diff --git a/cocos/ui/UICheckBox.h b/cocos/ui/UICheckBox.h index ec29f433b162..5d3d43d02cc3 100644 --- a/cocos/ui/UICheckBox.h +++ b/cocos/ui/UICheckBox.h @@ -93,11 +93,11 @@ class CC_GUI_DLL CheckBox : public AbstractCheckButton * * @return A CheckBox instance pointer. */ - static CheckBox* create(const std::string& backGround, - const std::string& backGroundSelected, - const std::string& cross, - const std::string& backGroundDisabled, - const std::string& frontCrossDisabled, + static CheckBox* create(std::string_view backGround, + std::string_view backGroundSelected, + std::string_view cross, + std::string_view backGroundDisabled, + std::string_view frontCrossDisabled, TextureResType texType = TextureResType::LOCAL); /** @@ -108,8 +108,8 @@ class CC_GUI_DLL CheckBox : public AbstractCheckButton * @param texType The texture's resource type in `Widget::TextureResType`. * @return A CheckBox instance pointer */ - static CheckBox* create(const std::string& backGround, - const std::string& cross, + static CheckBox* create(std::string_view backGround, + std::string_view cross, TextureResType texType = TextureResType::LOCAL); /** diff --git a/cocos/ui/UIEditBox/Mac/CCUIEditBoxMac.mm b/cocos/ui/UIEditBox/Mac/CCUIEditBoxMac.mm index bd2cf3d9d2f5..36411c3fd349 100644 --- a/cocos/ui/UIEditBox/Mac/CCUIEditBoxMac.mm +++ b/cocos/ui/UIEditBox/Mac/CCUIEditBoxMac.mm @@ -2,19 +2,19 @@ Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2013-2016 zilongshanren Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -30,92 +30,94 @@ of this software and associated documentation files (the "Software"), to deal #include "ui/UIEditBox/Mac/CCUIPasswordTextField.h" #include "ui/UIEditBox/Mac/CCUIMultilineTextField.h" -#define getEditBoxImplMac() ((cocos2d::ui::EditBoxImplMac *)_editBox) - +#define getEditBoxImplMac() ((cocos2d::ui::EditBoxImplMac*)_editBox) @implementation UIEditBoxImplMac -- (instancetype)initWithFrame:(NSRect)frameRect editBox:(void *)editBox +- (instancetype)initWithFrame:(NSRect)frameRect editBox:(void*)editBox { self = [super init]; - - if (self) { - - _editState = NO; + + if (self) + { + + _editState = NO; self.frameRect = frameRect; - - self.editBox = editBox; - self.dataInputMode = cocos2d::ui::EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS; + + self.editBox = editBox; + self.dataInputMode = cocos2d::ui::EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS; self.keyboardReturnType = cocos2d::ui::EditBox::KeyboardReturnType::DEFAULT; - + [self createMultiLineTextField]; } - + return self; } - (void)createSingleLineTextField { - CCUISingleLineTextField *textField = [[[CCUISingleLineTextField alloc] initWithFrame:self.frameRect] autorelease]; - + CCUISingleLineTextField* textField = [[[CCUISingleLineTextField alloc] initWithFrame:self.frameRect] autorelease]; + self.textInput = textField; } - (void)createMultiLineTextField { - CCUIMultilineTextField *textView = [[[CCUIMultilineTextField alloc] initWithFrame:self.frameRect] autorelease]; + CCUIMultilineTextField* textView = [[[CCUIMultilineTextField alloc] initWithFrame:self.frameRect] autorelease]; [textView setVerticallyResizable:NO]; self.textInput = textView; } - (void)createPasswordTextField { - CCUIPasswordTextField *textField = [[[CCUIPasswordTextField alloc] initWithFrame:self.frameRect] autorelease]; - + CCUIPasswordTextField* textField = [[[CCUIPasswordTextField alloc] initWithFrame:self.frameRect] autorelease]; + self.textInput = textField; } -- (void)setTextInput:(NSView *)textInput +- (void)setTextInput:(NSView*)textInput { - if (_textInput == textInput) { + if (_textInput == textInput) + { return; } // Migrate properties - textInput.ccui_textColor = _textInput.ccui_textColor ?: [NSColor whiteColor]; - textInput.ccui_text = _textInput.ccui_text ?: @""; + textInput.ccui_textColor = _textInput.ccui_textColor ?: [NSColor whiteColor]; + textInput.ccui_text = _textInput.ccui_text ?: @""; textInput.ccui_placeholder = _textInput.ccui_placeholder ?: @""; - textInput.ccui_font = _textInput.ccui_font ?: [NSFont systemFontOfSize:self.frameRect.size.height*3/2]; - textInput.ccui_maxLength = getEditBoxImplMac()->getMaxLength(); - textInput.ccui_alignment = _textInput.ccui_alignment; - + textInput.ccui_font = _textInput.ccui_font ?: [NSFont systemFontOfSize:self.frameRect.size.height * 3 / 2]; + textInput.ccui_maxLength = getEditBoxImplMac()->getMaxLength(); + textInput.ccui_alignment = _textInput.ccui_alignment; + [_textInput removeFromSuperview]; [_textInput release]; - + _textInput = [textInput retain]; - + [_textInput performSelector:@selector(setTextColor:) withObject:_textInput.ccui_textColor]; [_textInput performSelector:@selector(setBackgroundColor:) withObject:[NSColor clearColor]]; - - if (![_textInput isKindOfClass:[NSTextView class]]) { + + if (![_textInput isKindOfClass:[NSTextView class]]) + { [_textInput performSelector:@selector(setBordered:) withObject:nil]; } - _textInput.hidden = NO; + _textInput.hidden = NO; _textInput.wantsLayer = YES; - + [_textInput ccui_setDelegate:self]; - + [self setInputFlag:self.dataInputMode]; [self setReturnType:self.keyboardReturnType]; } - (void)updateFrame:(CGRect)rect { - NSRect frame = self.textInput.frame; - frame.origin.x = rect.origin.x; - frame.origin.y = rect.origin.y; + NSRect frame = self.textInput.frame; + frame.origin.x = rect.origin.x; + frame.origin.y = rect.origin.y; frame.size.height = rect.size.height; - frame.size.width = rect.size.width; + frame.size.width = rect.size.width; self.textInput.frame = frame; } @@ -123,11 +125,11 @@ - (void)updateFrame:(CGRect)rect - (void)dealloc { self.textInput = nil; - + [super dealloc]; } -- (NSWindow *)window +- (NSWindow*)window { auto glview = cocos2d::Director::getInstance()->getOpenGLView(); return glview->getCocoaWindow(); @@ -137,41 +139,44 @@ - (void)openKeyboard { [self.window.contentView addSubview:self.textInput]; - if (![self.textInput isKindOfClass:[NSTextView class]]) { + if (![self.textInput isKindOfClass:[NSTextView class]]) + { [self.textInput becomeFirstResponder]; - }else { + } + else + { [self.window makeFirstResponder:self.textInput]; } - + auto editbox = getEditBoxImplMac()->getEditBox(); - auto oldPos = editbox->getPosition(); - editbox->setPosition(oldPos + cocos2d::Vec2(10,20)); + auto oldPos = editbox->getPosition(); + editbox->setPosition(oldPos + cocos2d::Vec2(10, 20)); editbox->setPosition(oldPos); } - (void)closeKeyboard { - if (![self.textInput isKindOfClass:[NSTextView class]]) { + if (![self.textInput isKindOfClass:[NSTextView class]]) + { [self.textInput resignFirstResponder]; } [self.textInput removeFromSuperview]; } - -- (const char*) getText +- (const char*)getText { return [self.textInput.ccui_text UTF8String]; } -- (void)controlTextDidBeginEditing:(NSNotification *)notification +- (void)controlTextDidBeginEditing:(NSNotification*)notification { _editState = YES; - + getEditBoxImplMac()->editBoxEditingDidBegin(); } -- (void)controlTextDidEndEditing:(NSNotification *)notification +- (void)controlTextDidEndEditing:(NSNotification*)notification { _editState = NO; @@ -186,27 +191,32 @@ - (void)setMaxLength:(int)length /** * Called each time when the text field's text has changed. */ -- (void)controlTextDidChange:(NSNotification *)notification +- (void)controlTextDidChange:(NSNotification*)notification { getEditBoxImplMac()->editBoxEditingChanged([self getText]); } -- (NSString *)getDefaultFontName +- (NSString*)getDefaultFontName { return self.textInput.ccui_font.fontName ?: @""; } - (void)setInputMode:(cocos2d::ui::EditBox::InputMode)inputMode { - //multiline input - if (inputMode == cocos2d::ui::EditBox::InputMode::ANY) { - if (![self.textInput isKindOfClass:[NSTextView class]]) { + // multiline input + if (inputMode == cocos2d::ui::EditBox::InputMode::ANY) + { + if (![self.textInput isKindOfClass:[NSTextView class]]) + { [self createMultiLineTextField]; } } - else { - if (self.dataInputMode != cocos2d::ui::EditBox::InputFlag::PASSWORD) { - if (![self.textInput isKindOfClass:[NSTextField class]]) { + else + { + if (self.dataInputMode != cocos2d::ui::EditBox::InputFlag::PASSWORD) + { + if (![self.textInput isKindOfClass:[NSTextField class]]) + { [self createSingleLineTextField]; } } @@ -215,42 +225,45 @@ - (void)setInputMode:(cocos2d::ui::EditBox::InputMode)inputMode - (void)setInputFlag:(cocos2d::ui::EditBox::InputFlag)inputFlag { - if (self.dataInputMode == inputFlag) { + if (self.dataInputMode == inputFlag) + { return; } - - if (self.dataInputMode == cocos2d::ui::EditBox::InputFlag::PASSWORD - && inputFlag != cocos2d::ui::EditBox::InputFlag::PASSWORD) { + + if (self.dataInputMode == cocos2d::ui::EditBox::InputFlag::PASSWORD && + inputFlag != cocos2d::ui::EditBox::InputFlag::PASSWORD) + { [self createSingleLineTextField]; } - - if (self.dataInputMode != cocos2d::ui::EditBox::InputFlag::PASSWORD - && inputFlag == cocos2d::ui::EditBox::InputFlag::PASSWORD) { + + if (self.dataInputMode != cocos2d::ui::EditBox::InputFlag::PASSWORD && + inputFlag == cocos2d::ui::EditBox::InputFlag::PASSWORD) + { [self createPasswordTextField]; } switch (inputFlag) { - case cocos2d::ui::EditBox::InputFlag::PASSWORD: - self.dataInputMode = inputFlag; - break; - case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_WORD: - CCLOG("INITIAL_CAPS_WORD not implemented"); - break; - case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_SENTENCE: - CCLOG("INITIAL_CAPS_SENTENCE not implemented"); - break; - case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_ALL_CHARACTERS: - CCLOG("INITIAL_CAPS_ALL_CHARACTERS not implemented"); - break; - case cocos2d::ui::EditBox::InputFlag::SENSITIVE: - CCLOG("SENSITIVE not implemented"); - break; - case cocos2d::ui::EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS: - CCLOG("LOWERCASE_ALL_CHARACTERS not implemented"); - break; - default: - break; + case cocos2d::ui::EditBox::InputFlag::PASSWORD: + self.dataInputMode = inputFlag; + break; + case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_WORD: + CCLOG("INITIAL_CAPS_WORD not implemented"); + break; + case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_SENTENCE: + CCLOG("INITIAL_CAPS_SENTENCE not implemented"); + break; + case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_ALL_CHARACTERS: + CCLOG("INITIAL_CAPS_ALL_CHARACTERS not implemented"); + break; + case cocos2d::ui::EditBox::InputFlag::SENSITIVE: + CCLOG("SENSITIVE not implemented"); + break; + case cocos2d::ui::EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS: + CCLOG("LOWERCASE_ALL_CHARACTERS not implemented"); + break; + default: + break; } } @@ -262,12 +275,14 @@ - (void)setReturnType:(cocos2d::ui::EditBox::KeyboardReturnType)returnType - (void)setTextHorizontalAlignment:(cocos2d::TextHAlignment)alignment { // swizzle center & right, for some reason they're backwards on !TARGET_OS_IPHONE - if (alignment == cocos2d::TextHAlignment::CENTER) alignment = cocos2d::TextHAlignment::RIGHT; - else if (alignment == cocos2d::TextHAlignment::RIGHT) alignment = cocos2d::TextHAlignment::CENTER; + if (alignment == cocos2d::TextHAlignment::CENTER) + alignment = cocos2d::TextHAlignment::RIGHT; + else if (alignment == cocos2d::TextHAlignment::RIGHT) + alignment = cocos2d::TextHAlignment::CENTER; self.textInput.ccui_alignment = static_cast(alignment); } -- (void)setPlaceHolder:(const char *)text +- (void)setPlaceHolder:(const char*)text { self.textInput.ccui_placeholder = [NSString stringWithUTF8String:text]; } @@ -282,14 +297,15 @@ - (void)setTextColor:(NSColor*)color self.textInput.ccui_textColor = color; } -- (void)setFont:(NSFont *)font +- (void)setFont:(NSFont*)font { - if (font != nil) { + if (font != nil) + { self.textInput.ccui_font = font; } } -- (void)setPlaceholderFontColor:(NSColor *)color +- (void)setPlaceholderFontColor:(NSColor*)color { self.textInput.ccui_placeholderColor = color; } @@ -299,70 +315,76 @@ - (void)setPlaceholderFont:(NSFont*)font self.textInput.ccui_placeholderFont = font; } -- (void)setText:(NSString *)text +- (void)setText:(NSString*)text { self.textInput.ccui_text = text; } -- (BOOL)textShouldBeginEditing:(NSText *)textObject // YES means do it +- (BOOL)textShouldBeginEditing:(NSText*)textObject // YES means do it { _editState = YES; - + getEditBoxImplMac()->editBoxEditingDidBegin(); return YES; } -- (void)textDidEndEditing:(NSNotification *)notification +- (void)textDidEndEditing:(NSNotification*)notification { _editState = NO; getEditBoxImplMac()->editBoxEditingDidEnd([self getText], [self getEndAction:notification]); } -- (cocos2d::ui::EditBoxDelegate::EditBoxEndAction)getEndAction:(NSNotification *)notification +- (cocos2d::ui::EditBoxDelegate::EditBoxEndAction)getEndAction:(NSNotification*)notification { - auto type = cocos2d::ui::EditBoxDelegate::EditBoxEndAction::UNKNOWN; + auto type = cocos2d::ui::EditBoxDelegate::EditBoxEndAction::UNKNOWN; NSUInteger reasonForEnding = [[[notification userInfo] objectForKey:@"NSTextMovement"] unsignedIntValue]; - if (reasonForEnding == NSTabTextMovement) { + if (reasonForEnding == NSTabTextMovement) + { type = cocos2d::ui::EditBoxDelegate::EditBoxEndAction::TAB_TO_NEXT; - } else if (reasonForEnding == NSBacktabTextMovement) { + } + else if (reasonForEnding == NSBacktabTextMovement) + { type = cocos2d::ui::EditBoxDelegate::EditBoxEndAction::TAB_TO_PREVIOUS; - } else if (reasonForEnding == NSReturnTextMovement) { + } + else if (reasonForEnding == NSReturnTextMovement) + { type = cocos2d::ui::EditBoxDelegate::EditBoxEndAction::RETURN; } return type; } -- (void)textDidChange:(NSNotification *)notification +- (void)textDidChange:(NSNotification*)notification { NSTextView* textView = notification.object; - + const char* inputText = [textView.string UTF8String]; - + getEditBoxImplMac()->editBoxEditingChanged(inputText); } -- (BOOL)textView:(NSTextView *)textView shouldChangeTextInRange:(NSRange)affectedCharRange replacementString:(NSString *)replacementString +- (BOOL)textView:(NSTextView*)textView + shouldChangeTextInRange:(NSRange)affectedCharRange + replacementString:(NSString*)replacementString { int maxLength = getEditBoxImplMac()->getMaxLength(); if (maxLength < 0) { return YES; } - - if (affectedCharRange.length + affectedCharRange.location > textView.string.length) { + + if (affectedCharRange.length + affectedCharRange.location > textView.string.length) + { return NO; } - - NSUInteger oldLength = textView.string.length; + + NSUInteger oldLength = textView.string.length; NSUInteger replacementLength = replacementString.length; - NSUInteger rangeLength = affectedCharRange.length; - + NSUInteger rangeLength = affectedCharRange.length; + NSUInteger newLength = oldLength - rangeLength + replacementLength; - + return newLength <= maxLength; } - - @end diff --git a/cocos/ui/UIEditBox/UIEditBox.cpp b/cocos/ui/UIEditBox/UIEditBox.cpp index 78c7eb1c0460..fefa1cdcb303 100644 --- a/cocos/ui/UIEditBox/UIEditBox.cpp +++ b/cocos/ui/UIEditBox/UIEditBox.cpp @@ -56,15 +56,15 @@ void EditBox::openKeyboard() const _editBoxImpl->openKeyboard(); } -EditBox* EditBox::create(const Vec2& size, const std::string& normalImage, TextureResType texType) +EditBox* EditBox::create(const Vec2& size, std::string_view normalImage, TextureResType texType) { return EditBox::create(size, normalImage, "", "", texType); } EditBox* EditBox::create(const Vec2& size, - const std::string& normalImage, - const std::string& pressedImage /* = "" */, - const std::string& disabledImage /* = "" */, + std::string_view normalImage, + std::string_view pressedImage /* = "" */, + std::string_view disabledImage /* = "" */, TextureResType texType /* = TextureResType::LOCAL */) { EditBox* pRet = new EditBox(); @@ -136,16 +136,16 @@ bool EditBox::initWithSizeAndBackgroundSprite(const Vec2& size, } bool EditBox::initWithSizeAndBackgroundSprite(const Vec2& size, - const std::string& pNormal9SpriteBg, + std::string_view pNormal9SpriteBg, TextureResType texType) { return initWithSizeAndTexture(size, pNormal9SpriteBg, "", "", texType); } bool EditBox::initWithSizeAndTexture(const Vec2& size, - const std::string& normalImage, - const std::string& pressedImage /* = "" */, - const std::string& disabledImage /* = "" */, + std::string_view normalImage, + std::string_view pressedImage /* = "" */, + std::string_view disabledImage /* = "" */, TextureResType texType /* = TextureResType::LOCAL */) { if (Widget::init()) @@ -178,9 +178,9 @@ void EditBox::initRenderer() addProtectedChild(_disabledRenderer, DISABLED_RENDERER_Z, -1); } -void EditBox::loadTextures(const std::string& normal, - const std::string& pressed, - const std::string& disabled, +void EditBox::loadTextures(std::string_view normal, + std::string_view pressed, + std::string_view disabled, TextureResType texType) { loadTextureNormal(normal, texType); @@ -188,7 +188,7 @@ void EditBox::loadTextures(const std::string& normal, loadTextureDisabled(disabled, texType); } -void EditBox::loadTextureNormal(const std::string& normal, TextureResType texType) +void EditBox::loadTextureNormal(std::string_view normal, TextureResType texType) { _normalFileName = normal; _normalTexType = texType; @@ -236,7 +236,7 @@ void EditBox::loadTextureNormal(SpriteFrame* normalSpriteFrame) this->setupNormalTexture(nullptr != normalSpriteFrame); } -void EditBox::loadTexturePressed(const std::string& pressed, TextureResType texType) +void EditBox::loadTexturePressed(std::string_view pressed, TextureResType texType) { _pressedFileName = pressed; _pressedTexType = texType; @@ -279,7 +279,7 @@ void EditBox::loadTexturePressed(SpriteFrame* pressedSpriteFrame) this->setupPressedTexture(nullptr != pressedSpriteFrame); } -void EditBox::loadTextureDisabled(const std::string& disabled, TextureResType texType) +void EditBox::loadTextureDisabled(std::string_view disabled, TextureResType texType) { _disabledFileName = disabled; _disabledTexType = texType; diff --git a/cocos/ui/UIEditBox/UIEditBox.h b/cocos/ui/UIEditBox/UIEditBox.h index 9d76b3bf785a..990e4ab84358 100644 --- a/cocos/ui/UIEditBox/UIEditBox.h +++ b/cocos/ui/UIEditBox/UIEditBox.h @@ -78,7 +78,7 @@ class CC_GUI_DLL EditBoxDelegate * @param editBox The edit box object that generated the event. * @param text The new text. */ - virtual void editBoxTextChanged(EditBox* /*editBox*/, const std::string& /*text*/) {} + virtual void editBoxTextChanged(EditBox* /*editBox*/, std::string_view /*text*/) {} /** * This method is called when the return button was pressed or the outside area of keyboard was touched. @@ -214,17 +214,17 @@ class CC_GUI_DLL EditBox : public Widget, public IMEDelegate * create a edit box with size. * @return An autorelease pointer of EditBox, you don't need to release it only if you retain it again. */ - static EditBox* create(const Size& size, const std::string& normalImage, TextureResType texType); + static EditBox* create(const Size& size, std::string_view normalImage, TextureResType texType); /** * create a edit box with size. * @return An autorelease pointer of EditBox, you don't need to release it only if you retain it again. */ static EditBox* create(const Size& size, - const std::string& normalImage, - const std::string& pressedImage = "", - const std::string& disabledImage = "", - TextureResType texType = TextureResType::LOCAL); + std::string_view normalImage, + std::string_view pressedImage = "", + std::string_view disabledImage = "", + TextureResType texType = TextureResType::LOCAL); /** * Constructor. @@ -248,7 +248,7 @@ class CC_GUI_DLL EditBox : public Widget, public IMEDelegate * @return Whether initialization is successfully or not. */ bool initWithSizeAndBackgroundSprite(const Size& size, - const std::string& normal9SpriteBg, + std::string_view normal9SpriteBg, TextureResType texType = TextureResType::LOCAL); /** @@ -281,10 +281,10 @@ class CC_GUI_DLL EditBox : public Widget, public IMEDelegate * @return Whether initialization is successfully or not. */ bool initWithSizeAndTexture(const Size& size, - const std::string& normalImage, - const std::string& pressedImage = "", - const std::string& disabledImage = "", - TextureResType texType = TextureResType::LOCAL); + std::string_view normalImage, + std::string_view pressedImage = "", + std::string_view disabledImage = "", + TextureResType texType = TextureResType::LOCAL); /** * Load textures for edit box. @@ -294,10 +294,10 @@ class CC_GUI_DLL EditBox : public Widget, public IMEDelegate * @param disabled disabled state texture name. * @param texType @see `TextureResType` */ - void loadTextures(const std::string& normal, - const std::string& pressed, - const std::string& disabled = "", - TextureResType texType = TextureResType::LOCAL); + void loadTextures(std::string_view normal, + std::string_view pressed, + std::string_view disabled = "", + TextureResType texType = TextureResType::LOCAL); /** * Load normal state texture for edit box. @@ -305,7 +305,7 @@ class CC_GUI_DLL EditBox : public Widget, public IMEDelegate * @param normal normal state texture. * @param texType @see `TextureResType` */ - void loadTextureNormal(const std::string& normal, TextureResType texType = TextureResType::LOCAL); + void loadTextureNormal(std::string_view normal, TextureResType texType = TextureResType::LOCAL); /** * Load pressed state texture for edit box. @@ -313,7 +313,7 @@ class CC_GUI_DLL EditBox : public Widget, public IMEDelegate * @param pressed pressed state texture. * @param texType @see `TextureResType` */ - void loadTexturePressed(const std::string& pressed, TextureResType texType = TextureResType::LOCAL); + void loadTexturePressed(std::string_view pressed, TextureResType texType = TextureResType::LOCAL); /** * Load disabled state texture for edit box. @@ -321,7 +321,7 @@ class CC_GUI_DLL EditBox : public Widget, public IMEDelegate * @param disabled dark state texture. * @param texType @see `TextureResType` */ - void loadTextureDisabled(const std::string& disabled, TextureResType texType = TextureResType::LOCAL); + void loadTextureDisabled(std::string_view disabled, TextureResType texType = TextureResType::LOCAL); /** * Sets capInsets for edit box. diff --git a/cocos/ui/UIEditBox/UIEditBoxImpl-android.cpp b/cocos/ui/UIEditBox/UIEditBoxImpl-android.cpp index f23a4345c0aa..d99aaea1cd38 100644 --- a/cocos/ui/UIEditBox/UIEditBoxImpl-android.cpp +++ b/cocos/ui/UIEditBox/UIEditBoxImpl-android.cpp @@ -43,15 +43,15 @@ NS_CC_BEGIN -static const std::string editBoxClassName = "org.cocos2dx.lib.Cocos2dxEditBoxHelper"; +static const char* editBoxClassName = "org.cocos2dx.lib.Cocos2dxEditBoxHelper"; namespace ui { # define LOGD(...) __android_log_print(ANDROID_LOG_ERROR, "", __VA_ARGS__) static void editBoxEditingDidBegin(int index); -static void editBoxEditingDidChanged(int index, const std::string& text); -static void editBoxEditingDidEnd(int index, const std::string& text, int action); +static void editBoxEditingDidChanged(int index, std::string_view text); +static void editBoxEditingDidEnd(int index, std::string_view text, int action); extern "C" { JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxEditBoxHelper_editBoxEditingDidBegin(JNIEnv*, jclass, jint index) { @@ -221,7 +221,7 @@ void editBoxEditingDidBegin(int index) s_allEditBoxes[index]->editBoxEditingDidBegin(); } } -void editBoxEditingDidChanged(int index, const std::string& text) +void editBoxEditingDidChanged(int index, std::string_view text) { auto it = s_allEditBoxes.find(index); if (it != s_allEditBoxes.end()) @@ -230,7 +230,7 @@ void editBoxEditingDidChanged(int index, const std::string& text) } } -void editBoxEditingDidEnd(int index, const std::string& text, int action) +void editBoxEditingDidEnd(int index, std::string_view text, int action) { auto it = s_allEditBoxes.find(index); if (it != s_allEditBoxes.end()) diff --git a/cocos/ui/UIEditBox/UIEditBoxImpl-common.cpp b/cocos/ui/UIEditBox/UIEditBoxImpl-common.cpp index bf99aa2f5db2..bd3fe9ba63a8 100644 --- a/cocos/ui/UIEditBox/UIEditBoxImpl-common.cpp +++ b/cocos/ui/UIEditBox/UIEditBoxImpl-common.cpp @@ -346,7 +346,7 @@ void EditBoxImplCommon::closeKeyboard() _editingMode = false; } -void EditBoxImplCommon::onEndEditing(const std::string& /*text*/) +void EditBoxImplCommon::onEndEditing(std::string_view /*text*/) { _editBox->setBrightStyle(Widget::BrightStyle::NORMAL); _editingMode = false; @@ -374,7 +374,7 @@ void EditBoxImplCommon::editBoxEditingDidBegin() #endif } -void EditBoxImplCommon::editBoxEditingDidEnd(const std::string& text, EditBoxDelegate::EditBoxEndAction action) +void EditBoxImplCommon::editBoxEditingDidEnd(std::string_view text, EditBoxDelegate::EditBoxEndAction action) { // LOGD("textFieldShouldEndEditing..."); _text = text; @@ -405,7 +405,7 @@ void EditBoxImplCommon::editBoxEditingDidEnd(const std::string& text, EditBoxDel } } -void EditBoxImplCommon::editBoxEditingChanged(const std::string& text) +void EditBoxImplCommon::editBoxEditingChanged(std::string_view text) { // LOGD("editBoxTextChanged..."); cocos2d::ui::EditBoxDelegate* pDelegate = _editBox->getDelegate(); diff --git a/cocos/ui/UIEditBox/UIEditBoxImpl-common.h b/cocos/ui/UIEditBox/UIEditBoxImpl-common.h index 419ce7a0c923..b14e41fe6b4b 100644 --- a/cocos/ui/UIEditBox/UIEditBoxImpl-common.h +++ b/cocos/ui/UIEditBox/UIEditBoxImpl-common.h @@ -107,11 +107,11 @@ class CC_GUI_DLL EditBoxImplCommon : public EditBoxImpl virtual void openKeyboard() override; virtual void closeKeyboard() override; - virtual void onEndEditing(const std::string& text); + virtual void onEndEditing(std::string_view text); void editBoxEditingDidBegin(); - void editBoxEditingChanged(const std::string& text); - void editBoxEditingDidEnd(const std::string& text, + void editBoxEditingChanged(std::string_view text); + void editBoxEditingDidEnd(std::string_view text, EditBoxDelegate::EditBoxEndAction action = EditBoxDelegate::EditBoxEndAction::UNKNOWN); virtual bool isEditing() override = 0; diff --git a/cocos/ui/UIEditBox/UIEditBoxImpl-ios.mm b/cocos/ui/UIEditBox/UIEditBoxImpl-ios.mm index 9ac548fd8398..862e73f88b23 100644 --- a/cocos/ui/UIEditBox/UIEditBoxImpl-ios.mm +++ b/cocos/ui/UIEditBox/UIEditBoxImpl-ios.mm @@ -3,19 +3,19 @@ Copyright (c) 2012 James Chen Copyright (c) 2013-2015 zilongshanren Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -28,43 +28,38 @@ of this software and associated documentation files (the "Software"), to deal #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) -#define kLabelZOrder 9999 +# define kLabelZOrder 9999 -#include "ui/UIEditBox/UIEditBox.h" -#include "base/CCDirector.h" -#include "2d/CCLabel.h" -#import "platform/ios/CCEAGLView-ios.h" +# include "ui/UIEditBox/UIEditBox.h" +# include "base/CCDirector.h" +# include "2d/CCLabel.h" +# import "platform/ios/CCEAGLView-ios.h" -#import -#import +# import +# import -#import "ui/UIEditBox/iOS/CCUIEditBoxIOS.h" - -#define getEditBoxImplIOS() ((cocos2d::ui::EditBoxImplIOS *)_editBox) +# import "ui/UIEditBox/iOS/CCUIEditBoxIOS.h" +# define getEditBoxImplIOS() ((cocos2d::ui::EditBoxImplIOS*)_editBox) NS_CC_BEGIN -namespace ui { +namespace ui +{ EditBoxImpl* __createSystemEditBox(EditBox* pEditBox) { return new EditBoxImplIOS(pEditBox); } -EditBoxImplIOS::EditBoxImplIOS(EditBox* pEditText) -: EditBoxImplCommon(pEditText) -, _systemControl(nullptr) -{ - -} +EditBoxImplIOS::EditBoxImplIOS(EditBox* pEditText) : EditBoxImplCommon(pEditText), _systemControl(nullptr) {} EditBoxImplIOS::~EditBoxImplIOS() { [_systemControl release]; _systemControl = nil; } - + void EditBoxImplIOS::createNativeControl(const Rect& frame) { auto glview = cocos2d::Director::getInstance()->getOpenGLView(); @@ -75,13 +70,10 @@ of this software and associated documentation files (the "Software"), to deal rect.size.width /= factor; rect.size.height /= factor; - - _systemControl = [[UIEditBoxImplIOS_objc alloc] initWithFrame:CGRectMake(rect.origin.x, - rect.origin.y, - rect.size.width, - rect.size.height) - editBox:this]; + _systemControl = [[UIEditBoxImplIOS_objc alloc] + initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height) + editBox:this]; } bool EditBoxImplIOS::isEditing() @@ -91,32 +83,34 @@ of this software and associated documentation files (the "Software"), to deal void EditBoxImplIOS::doAnimationWhenKeyboardMove(float duration, float distance) { - if ([_systemControl isEditState] || distance < 0.0f) { + if ([_systemControl isEditState] || distance < 0.0f) + { [_systemControl doAnimationWhenKeyboardMoveWithDuration:duration distance:distance]; } } - + void EditBoxImplIOS::setNativeFont(const char* pFontName, int fontSize) { UIFont* textFont = constructFont(pFontName, fontSize); - if (textFont != nil) { + if (textFont != nil) + { [_systemControl setFont:textFont]; } } - + void EditBoxImplIOS::setNativeFontColor(const Color4B& color) { _systemControl.textColor = [UIColor colorWithRed:color.r / 255.0f - green:color.g / 255.0f - blue:color.b / 255.0f - alpha:color.a / 255.f]; - + green:color.g / 255.0f + blue:color.b / 255.0f + alpha:color.a / 255.f]; } void EditBoxImplIOS::setNativePlaceholderFont(const char* pFontName, int fontSize) { UIFont* textFont = constructFont(pFontName, fontSize); - if (textFont != nil) { + if (textFont != nil) + { [_systemControl setPlaceholderFont:textFont]; } } @@ -124,9 +118,9 @@ of this software and associated documentation files (the "Software"), to deal void EditBoxImplIOS::setNativePlaceholderFontColor(const Color4B& color) { [_systemControl setPlaceholderTextColor:[UIColor colorWithRed:color.r / 255.0f - green:color.g / 255.0f - blue:color.b / 255.0f - alpha:color.a / 255.f]]; + green:color.g / 255.0f + blue:color.b / 255.0f + alpha:color.a / 255.f]]; } void EditBoxImplIOS::setNativeInputMode(EditBox::InputMode inputMode) @@ -134,7 +128,7 @@ of this software and associated documentation files (the "Software"), to deal [_systemControl setInputMode:inputMode]; auto oldPos = _editBox->getPosition(); - _editBox->setPosition(oldPos + Vec2(10,10)); + _editBox->setPosition(oldPos + Vec2(10, 10)); _editBox->setPosition(oldPos); } @@ -142,7 +136,7 @@ of this software and associated documentation files (the "Software"), to deal { [_systemControl setInputFlag:inputFlag]; } - + NSString* removeSiriString(NSString* str) { NSString* siriString = @"\xef\xbf\xbc"; @@ -154,7 +148,6 @@ of this software and associated documentation files (the "Software"), to deal return [removeSiriString(_systemControl.text) UTF8String]; } - void EditBoxImplIOS::setNativeReturnType(EditBox::KeyboardReturnType returnType) { [_systemControl setReturnType:returnType]; @@ -167,8 +160,9 @@ of this software and associated documentation files (the "Software"), to deal void EditBoxImplIOS::setNativeText(const char* pText) { - NSString* nsText =[NSString stringWithUTF8String:pText]; - if ([nsText compare:_systemControl.text] != NSOrderedSame) { + NSString* nsText = [NSString stringWithUTF8String:pText]; + if ([nsText compare:_systemControl.text] != NSOrderedSame) + { _systemControl.text = nsText; } } @@ -185,16 +179,13 @@ of this software and associated documentation files (the "Software"), to deal void EditBoxImplIOS::updateNativeFrame(const Rect& rect) { - auto glview = cocos2d::Director::getInstance()->getOpenGLView(); - CCEAGLView *eaglview = (CCEAGLView *) glview->getEAGLView(); + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + CCEAGLView* eaglview = (CCEAGLView*)glview->getEAGLView(); float factor = eaglview.contentScaleFactor; - - [_systemControl updateFrame:CGRectMake(rect.origin.x / factor, - rect.origin.y / factor, - rect.size.width / factor, - rect.size.height / factor)]; + [_systemControl updateFrame:CGRectMake(rect.origin.x / factor, rect.origin.y / factor, rect.size.width / factor, + rect.size.height / factor)]; } const char* EditBoxImplIOS::getNativeDefaultFontName() @@ -213,33 +204,34 @@ of this software and associated documentation files (the "Software"), to deal { [_systemControl closeKeyboard]; } - -UIFont* EditBoxImplIOS::constructFont(const char *fontName, int fontSize) + +UIFont* EditBoxImplIOS::constructFont(const char* fontName, int fontSize) { CCASSERT(fontName != nullptr, "fontName can't be nullptr"); - CCEAGLView *eaglview = static_cast(cocos2d::Director::getInstance()->getOpenGLView()->getEAGLView()); - float retinaFactor = eaglview.contentScaleFactor; - NSString * fntName = [NSString stringWithUTF8String:fontName]; - + CCEAGLView* eaglview = static_cast(cocos2d::Director::getInstance()->getOpenGLView()->getEAGLView()); + float retinaFactor = eaglview.contentScaleFactor; + NSString* fntName = [NSString stringWithUTF8String:fontName]; + fntName = [[fntName lastPathComponent] stringByDeletingPathExtension]; - - auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); float scaleFactor = glview->getScaleX(); - + if (fontSize == -1) { - fontSize = _systemControl.frameRect.size.height*2/3; + fontSize = _systemControl.frameRect.size.height * 2 / 3; } else { fontSize = fontSize * scaleFactor / retinaFactor; } - - UIFont *textFont = nil; + + UIFont* textFont = nil; if (strlen(fontName) > 0) { textFont = [UIFont fontWithName:fntName size:fontSize]; - if (textFont == nil) { + if (textFont == nil) + { textFont = [UIFont systemFontOfSize:fontSize]; } } @@ -254,5 +246,3 @@ of this software and associated documentation files (the "Software"), to deal NS_CC_END #endif /* #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) */ - - diff --git a/cocos/ui/UIEditBox/UIEditBoxImpl-mac.mm b/cocos/ui/UIEditBox/UIEditBoxImpl-mac.mm index 50099ae059a2..800f9c916bf7 100644 --- a/cocos/ui/UIEditBox/UIEditBoxImpl-mac.mm +++ b/cocos/ui/UIEditBox/UIEditBoxImpl-mac.mm @@ -2,19 +2,19 @@ Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2012 Jozef Pridavok Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,24 +27,23 @@ of this software and associated documentation files (the "Software"), to deal #include "platform/CCPlatformConfig.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -#include "ui/UIEditBox/UIEditBoxImpl-mac.h" -#include "base/CCDirector.h" -#include "base/ccUTF8.h" -#include "ui/UIEditBox/UIEditBox.h" -#include "ui/UIEditBox/Mac/CCUIEditBoxMac.h" +# include "ui/UIEditBox/UIEditBoxImpl-mac.h" +# include "base/CCDirector.h" +# include "base/ccUTF8.h" +# include "ui/UIEditBox/UIEditBox.h" +# include "ui/UIEditBox/Mac/CCUIEditBoxMac.h" NS_CC_BEGIN -namespace ui { +namespace ui +{ EditBoxImpl* __createSystemEditBox(EditBox* pEditBox) { return new EditBoxImplMac(pEditBox); } -EditBoxImplMac::EditBoxImplMac(EditBox* pEditText) -: EditBoxImplCommon(pEditText) -, _sysEdit(nullptr) +EditBoxImplMac::EditBoxImplMac(EditBox* pEditText) : EditBoxImplCommon(pEditText), _sysEdit(nullptr) { //! TODO: Retina on Mac //! _inRetinaMode = [[CCEAGLView sharedEGLView] contentScaleFactor] == 2.0f ? true : false; @@ -56,42 +55,40 @@ of this software and associated documentation files (the "Software"), to deal [_sysEdit release]; } -void EditBoxImplMac::createNativeControl(const cocos2d::Rect &frame) +void EditBoxImplMac::createNativeControl(const cocos2d::Rect& frame) { auto glview = cocos2d::Director::getInstance()->getOpenGLView(); - Size size = frame.size; - NSRect rect = NSMakeRect(0, 0, - size.width * glview->getScaleX(), - size.height * glview->getScaleY()); - + Size size = frame.size; + NSRect rect = NSMakeRect(0, 0, size.width * glview->getScaleX(), size.height * glview->getScaleY()); + float factor = cocos2d::Director::getInstance()->getContentScaleFactor(); - + rect.size.width /= factor; rect.size.height /= factor; - + _sysEdit = [[UIEditBoxImplMac alloc] initWithFrame:rect editBox:this]; this->setNativeVisible(false); } - -NSFont* EditBoxImplMac::constructFont(const char *fontName, int fontSize) + +NSFont* EditBoxImplMac::constructFont(const char* fontName, int fontSize) { - NSString * fntName = [NSString stringWithUTF8String:fontName]; - fntName = [[fntName lastPathComponent] stringByDeletingPathExtension]; + NSString* fntName = [NSString stringWithUTF8String:fontName]; + fntName = [[fntName lastPathComponent] stringByDeletingPathExtension]; float retinaFactor = _inRetinaMode ? 2.0f : 1.0f; - auto glview = cocos2d::Director::getInstance()->getOpenGLView(); - float scaleFactor = glview->getScaleX(); - + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + float scaleFactor = glview->getScaleX(); + if (fontSize == -1) { NSRect frameRect = [_sysEdit.textInput frame]; - fontSize = frameRect.size.height*2/3; + fontSize = frameRect.size.height * 2 / 3; } else { fontSize = fontSize * scaleFactor / retinaFactor; } - - NSFont *textFont = nil; + + NSFont* textFont = nil; if (strlen(fontName) == 0) { textFont = [NSFont systemFontOfSize:fontSize]; @@ -99,47 +96,49 @@ of this software and associated documentation files (the "Software"), to deal else { textFont = [NSFont fontWithName:fntName size:fontSize]; - if (textFont == nil) { + if (textFont == nil) + { textFont = [NSFont systemFontOfSize:fontSize]; } } - + return textFont; } -void EditBoxImplMac::setNativeFont(const char *pFontName, int fontSize) +void EditBoxImplMac::setNativeFont(const char* pFontName, int fontSize) { NSFont* textFont = constructFont(pFontName, fontSize); [_sysEdit setFont:textFont]; } -void EditBoxImplMac::setNativePlaceholderFont(const char *pFontName, int fontSize) +void EditBoxImplMac::setNativePlaceholderFont(const char* pFontName, int fontSize) { - NSFont *textFont = constructFont(pFontName, fontSize); - - if (!textFont) { + NSFont* textFont = constructFont(pFontName, fontSize); + + if (!textFont) + { CCLOGWARN("Font not found: %s", pFontName); return; } [_sysEdit setPlaceholderFont:textFont]; } -void EditBoxImplMac::setNativeFontColor(const cocos2d::Color4B &color) +void EditBoxImplMac::setNativeFontColor(const cocos2d::Color4B& color) { - NSColor *newColor = [NSColor colorWithCalibratedRed:color.r / 255.0f + NSColor* newColor = [NSColor colorWithCalibratedRed:color.r / 255.0f green:color.g / 255.0f blue:color.b / 255.0f alpha:color.a / 255.f]; [_sysEdit setTextColor:newColor]; } - -void EditBoxImplMac::setNativePlaceholderFontColor(const cocos2d::Color4B &color) + +void EditBoxImplMac::setNativePlaceholderFontColor(const cocos2d::Color4B& color) { - NSColor *newColor = [NSColor colorWithCalibratedRed:color.r/255.f - green:color.g / 255.f - blue:color.b / 255.f - alpha:color.a / 255.f]; + NSColor* newColor = [NSColor colorWithCalibratedRed:color.r / 255.f + green:color.g / 255.f + blue:color.b / 255.f + alpha:color.a / 255.f]; [_sysEdit setPlaceholderFontColor:newColor]; } @@ -147,7 +146,7 @@ of this software and associated documentation files (the "Software"), to deal { [_sysEdit setInputMode:inputMode]; auto oldPosition = _editBox->getPosition(); - _editBox->setPosition(_editBox->getPosition() + Vec2(10,10)); + _editBox->setPosition(_editBox->getPosition() + Vec2(10, 10)); _editBox->setPosition(oldPosition); } @@ -156,7 +155,6 @@ of this software and associated documentation files (the "Software"), to deal [_sysEdit setMaxLength:maxLength]; } - void EditBoxImplMac::setNativeInputFlag(EditBox::InputFlag inputFlag) { [_sysEdit setInputFlag:inputFlag]; @@ -177,12 +175,12 @@ of this software and associated documentation files (the "Software"), to deal return [_sysEdit isEditState] ? true : false; } -void EditBoxImplMac::setNativeText(const char *pText) +void EditBoxImplMac::setNativeText(const char* pText) { - NSString *text = [NSString stringWithUTF8String:pText]; + NSString* text = [NSString stringWithUTF8String:pText]; [_sysEdit setText:text]; } - + void EditBoxImplMac::setNativePlaceHolder(const char* pText) { [_sysEdit setPlaceHolder:pText]; @@ -193,24 +191,21 @@ of this software and associated documentation files (the "Software"), to deal [_sysEdit setVisible:visible]; } -void EditBoxImplMac::updateNativeFrame(const cocos2d::Rect &rect) +void EditBoxImplMac::updateNativeFrame(const cocos2d::Rect& rect) { GLView* eglView = Director::getInstance()->getOpenGLView(); - auto frameSize = eglView->getFrameSize(); + auto frameSize = eglView->getFrameSize(); // Coordinate System on OSX has its origin at the lower left corner. -// https://developer.apple.com/library/ios/documentation/General/Conceptual/Devpedia-CocoaApp/CoordinateSystem.html + // https://developer.apple.com/library/ios/documentation/General/Conceptual/Devpedia-CocoaApp/CoordinateSystem.html auto screenPosY = frameSize.height - rect.origin.y - rect.size.height; - [_sysEdit updateFrame:CGRectMake(rect.origin.x, - screenPosY, - rect.size.width, rect.size.height)]; + [_sysEdit updateFrame:CGRectMake(rect.origin.x, screenPosY, rect.size.width, rect.size.height)]; } - + const char* EditBoxImplMac::getNativeDefaultFontName() { return [[_sysEdit getDefaultFontName] UTF8String]; } - void EditBoxImplMac::nativeOpenKeyboard() { [_sysEdit setVisible:YES]; @@ -226,6 +221,4 @@ of this software and associated documentation files (the "Software"), to deal NS_CC_END -#endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) - - +#endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) diff --git a/cocos/ui/UIEditBox/iOS/CCUIEditBoxIOS.mm b/cocos/ui/UIEditBox/iOS/CCUIEditBoxIOS.mm index eb33fd0a2bdd..134e0a540f7f 100644 --- a/cocos/ui/UIEditBox/iOS/CCUIEditBoxIOS.mm +++ b/cocos/ui/UIEditBox/iOS/CCUIEditBoxIOS.mm @@ -4,19 +4,19 @@ Copyright (c) 2013-2015 zilongshanren Copyright (c) 2015 Mazyad Alabduljaleel Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -33,8 +33,7 @@ of this software and associated documentation files (the "Software"), to deal #import "platform/ios/CCEAGLView-ios.h" #include "base/CCDirector.h" -#define getEditBoxImplIOS() ((cocos2d::ui::EditBoxImplIOS *)_editBox) - +#define getEditBoxImplIOS() ((cocos2d::ui::EditBoxImplIOS*)_editBox) @implementation UIEditBoxImplIOS_objc @@ -43,27 +42,28 @@ @implementation UIEditBoxImplIOS_objc + (void)initialize { [super initialize]; - + LoadUITextViewCCUITextInputCategory(); LoadUITextFieldCCUITextInputCategory(); } #pragma mark - Init & Dealloc -- (instancetype)initWithFrame:(CGRect)frameRect editBox:(void *)editBox +- (instancetype)initWithFrame:(CGRect)frameRect editBox:(void*)editBox { self = [super init]; - if (self) { - - _editState = NO; - self.frameRect = frameRect; - self.editBox = editBox; - self.dataInputMode = cocos2d::ui::EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS; + if (self) + { + + _editState = NO; + self.frameRect = frameRect; + self.editBox = editBox; + self.dataInputMode = cocos2d::ui::EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS; self.keyboardReturnType = cocos2d::ui::EditBox::KeyboardReturnType::DEFAULT; - + [self createMultiLineTextField]; } - + return self; } @@ -71,38 +71,39 @@ - (void)dealloc { // custom setter cleanup self.textInput = nil; - + [super dealloc]; } #pragma mark - Properties -- (void)setTextInput:(UIView *)textInput +- (void)setTextInput:(UIView*)textInput { - if (_textInput == textInput) { + if (_textInput == textInput) + { return; } - + // common init textInput.backgroundColor = [UIColor clearColor]; - textInput.hidden = true; - textInput.returnKeyType = UIReturnKeyDefault; + textInput.hidden = true; + textInput.returnKeyType = UIReturnKeyDefault; [textInput ccui_setDelegate:self]; - + // Migrate properties - textInput.ccui_textColor = _textInput.ccui_textColor ?: [UIColor whiteColor]; - textInput.ccui_text = _textInput.ccui_text ?: @""; + textInput.ccui_textColor = _textInput.ccui_textColor ?: [UIColor whiteColor]; + textInput.ccui_text = _textInput.ccui_text ?: @""; textInput.ccui_placeholder = _textInput.ccui_placeholder ?: @""; - textInput.ccui_font = _textInput.ccui_font ?: [UIFont systemFontOfSize:self.frameRect.size.height*2/3]; - textInput.ccui_placeholderFont = _textInput.ccui_placeholderFont ?: textInput.ccui_font; + textInput.ccui_font = _textInput.ccui_font ?: [UIFont systemFontOfSize:self.frameRect.size.height * 2 / 3]; + textInput.ccui_placeholderFont = _textInput.ccui_placeholderFont ?: textInput.ccui_font; textInput.ccui_placeholderTextColor = _textInput.ccui_placeholderTextColor ?: [UIColor lightGrayColor]; - + [_textInput resignFirstResponder]; [_textInput removeFromSuperview]; [_textInput release]; - + _textInput = [textInput retain]; - + [self setInputFlag:self.dataInputMode]; [self setReturnType:self.keyboardReturnType]; } @@ -111,24 +112,24 @@ - (void)setTextInput:(UIView *)textInput - (void)createSingleLineTextField { - CCUISingleLineTextField *textField = [[[CCUISingleLineTextField alloc] initWithFrame:self.frameRect] autorelease]; + CCUISingleLineTextField* textField = [[[CCUISingleLineTextField alloc] initWithFrame:self.frameRect] autorelease]; textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; - textField.borderStyle = UITextBorderStyleNone; - + textField.borderStyle = UITextBorderStyleNone; + [textField addTarget:self action:@selector(textChanged:) forControlEvents:UIControlEventEditingChanged]; - + self.textInput = textField; } - (void)createMultiLineTextField { - CCUIMultilineTextField *textView = [[[CCUIMultilineTextField alloc] initWithFrame:self.frameRect] autorelease]; - self.textInput = textView; + CCUIMultilineTextField* textView = [[[CCUIMultilineTextField alloc] initWithFrame:self.frameRect] autorelease]; + self.textInput = textView; } #pragma mark - Public methods -- (void)setFont:(UIFont *)font +- (void)setFont:(UIFont*)font { self.textInput.ccui_font = font; } @@ -138,53 +139,57 @@ - (void)setTextColor:(UIColor*)color self.textInput.ccui_textColor = color; } -- (void)setPlaceholderFont:(UIFont *)font +- (void)setPlaceholderFont:(UIFont*)font { self.textInput.ccui_placeholderFont = font; } -- (void)setPlaceholderTextColor:(UIColor *)color +- (void)setPlaceholderTextColor:(UIColor*)color { self.textInput.ccui_placeholderTextColor = color; } - (void)setInputMode:(cocos2d::ui::EditBox::InputMode)inputMode { - //multiline input - if (inputMode == cocos2d::ui::EditBox::InputMode::ANY) { - if (![self.textInput isKindOfClass:[UITextView class]]) { + // multiline input + if (inputMode == cocos2d::ui::EditBox::InputMode::ANY) + { + if (![self.textInput isKindOfClass:[UITextView class]]) + { [self createMultiLineTextField]; } } - else { - if (![self.textInput isKindOfClass:[UITextField class]]) { + else + { + if (![self.textInput isKindOfClass:[UITextField class]]) + { [self createSingleLineTextField]; } } - + switch (inputMode) { - case cocos2d::ui::EditBox::InputMode::EMAIL_ADDRESS: - self.keyboardType = UIKeyboardTypeEmailAddress; - break; - case cocos2d::ui::EditBox::InputMode::NUMERIC: - self.keyboardType = UIKeyboardTypeDecimalPad; - break; - case cocos2d::ui::EditBox::InputMode::PHONE_NUMBER: - self.keyboardType = UIKeyboardTypePhonePad; - break; - case cocos2d::ui::EditBox::InputMode::URL: - self.keyboardType = UIKeyboardTypeURL; - break; - case cocos2d::ui::EditBox::InputMode::DECIMAL: - self.keyboardType = UIKeyboardTypeDecimalPad; - break; - case cocos2d::ui::EditBox::InputMode::SINGLE_LINE: - self.keyboardType = UIKeyboardTypeDefault; - break; - default: - self.keyboardType = UIKeyboardTypeDefault; - break; + case cocos2d::ui::EditBox::InputMode::EMAIL_ADDRESS: + self.keyboardType = UIKeyboardTypeEmailAddress; + break; + case cocos2d::ui::EditBox::InputMode::NUMERIC: + self.keyboardType = UIKeyboardTypeDecimalPad; + break; + case cocos2d::ui::EditBox::InputMode::PHONE_NUMBER: + self.keyboardType = UIKeyboardTypePhonePad; + break; + case cocos2d::ui::EditBox::InputMode::URL: + self.keyboardType = UIKeyboardTypeURL; + break; + case cocos2d::ui::EditBox::InputMode::DECIMAL: + self.keyboardType = UIKeyboardTypeDecimalPad; + break; + case cocos2d::ui::EditBox::InputMode::SINGLE_LINE: + self.keyboardType = UIKeyboardTypeDefault; + break; + default: + self.keyboardType = UIKeyboardTypeDefault; + break; } } @@ -198,67 +203,68 @@ - (void)setInputFlag:(cocos2d::ui::EditBox::InputFlag)flag self.dataInputMode = flag; switch (flag) { - case cocos2d::ui::EditBox::InputFlag::PASSWORD: - //textView can't be used for input password - self.textInput.ccui_secureTextEntry = YES; - break; - - case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_WORD: - self.textInput.autocapitalizationType = UITextAutocapitalizationTypeWords; - break; - - case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_SENTENCE: - self.textInput.autocapitalizationType = UITextAutocapitalizationTypeSentences; - break; - - case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_ALL_CHARACTERS: - self.textInput.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters; - break; - - case cocos2d::ui::EditBox::InputFlag::SENSITIVE: - self.textInput.autocorrectionType = UITextAutocorrectionTypeNo; - break; - - case cocos2d::ui::EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS: - self.textInput.autocapitalizationType = UITextAutocapitalizationTypeNone; - break; - - default: - break; + case cocos2d::ui::EditBox::InputFlag::PASSWORD: + // textView can't be used for input password + self.textInput.ccui_secureTextEntry = YES; + break; + + case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_WORD: + self.textInput.autocapitalizationType = UITextAutocapitalizationTypeWords; + break; + + case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_SENTENCE: + self.textInput.autocapitalizationType = UITextAutocapitalizationTypeSentences; + break; + + case cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_ALL_CHARACTERS: + self.textInput.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters; + break; + + case cocos2d::ui::EditBox::InputFlag::SENSITIVE: + self.textInput.autocorrectionType = UITextAutocorrectionTypeNo; + break; + + case cocos2d::ui::EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS: + self.textInput.autocapitalizationType = UITextAutocapitalizationTypeNone; + break; + + default: + break; } } - (void)setReturnType:(cocos2d::ui::EditBox::KeyboardReturnType)returnType { self.keyboardReturnType = returnType; - switch (returnType) { - case cocos2d::ui::EditBox::KeyboardReturnType::DEFAULT: - self.textInput.returnKeyType = UIReturnKeyDefault; - break; - - case cocos2d::ui::EditBox::KeyboardReturnType::DONE: - self.textInput.returnKeyType = UIReturnKeyDone; - break; - - case cocos2d::ui::EditBox::KeyboardReturnType::SEND: - self.textInput.returnKeyType = UIReturnKeySend; - break; - - case cocos2d::ui::EditBox::KeyboardReturnType::SEARCH: - self.textInput.returnKeyType = UIReturnKeySearch; - break; - - case cocos2d::ui::EditBox::KeyboardReturnType::GO: - self.textInput.returnKeyType = UIReturnKeyGo; - break; - - case cocos2d::ui::EditBox::KeyboardReturnType::NEXT: - self.textInput.returnKeyType = UIReturnKeyNext; - break; - - default: - self.textInput.returnKeyType = UIReturnKeyDefault; - break; + switch (returnType) + { + case cocos2d::ui::EditBox::KeyboardReturnType::DEFAULT: + self.textInput.returnKeyType = UIReturnKeyDefault; + break; + + case cocos2d::ui::EditBox::KeyboardReturnType::DONE: + self.textInput.returnKeyType = UIReturnKeyDone; + break; + + case cocos2d::ui::EditBox::KeyboardReturnType::SEND: + self.textInput.returnKeyType = UIReturnKeySend; + break; + + case cocos2d::ui::EditBox::KeyboardReturnType::SEARCH: + self.textInput.returnKeyType = UIReturnKeySearch; + break; + + case cocos2d::ui::EditBox::KeyboardReturnType::GO: + self.textInput.returnKeyType = UIReturnKeyGo; + break; + + case cocos2d::ui::EditBox::KeyboardReturnType::NEXT: + self.textInput.returnKeyType = UIReturnKeyNext; + break; + + default: + self.textInput.returnKeyType = UIReturnKeyDefault; + break; } } @@ -267,12 +273,12 @@ - (void)setTextHorizontalAlignment:(cocos2d::TextHAlignment)alignment self.textInput.ccui_alignment = static_cast(alignment); } -- (void)setText:(NSString *)text +- (void)setText:(NSString*)text { self.textInput.ccui_text = text; } -- (NSString *)text +- (NSString*)text { return self.textInput.ccui_text ?: @""; } @@ -282,7 +288,7 @@ - (void)setVisible:(BOOL)visible self.textInput.hidden = !visible; } -- (NSString *)getDefaultFontName +- (NSString*)getDefaultFontName { return self.textInput.ccui_font.fontName ?: @""; } @@ -290,28 +296,32 @@ - (NSString *)getDefaultFontName - (cocos2d::ui::EditBoxDelegate::EditBoxEndAction)getEndAction { cocos2d::ui::EditBoxDelegate::EditBoxEndAction action = cocos2d::ui::EditBoxDelegate::EditBoxEndAction::UNKNOWN; - if (self.returnPressed) { - if (self.keyboardReturnType == cocos2d::ui::EditBox::KeyboardReturnType::NEXT) { + if (self.returnPressed) + { + if (self.keyboardReturnType == cocos2d::ui::EditBox::KeyboardReturnType::NEXT) + { action = cocos2d::ui::EditBoxDelegate::EditBoxEndAction::TAB_TO_NEXT; - } else if (self.keyboardReturnType == cocos2d::ui::EditBox::KeyboardReturnType::GO || - self.keyboardReturnType == cocos2d::ui::EditBox::KeyboardReturnType::SEND || - self.keyboardReturnType == cocos2d::ui::EditBox::KeyboardReturnType::SEARCH) { + } + else if (self.keyboardReturnType == cocos2d::ui::EditBox::KeyboardReturnType::GO || + self.keyboardReturnType == cocos2d::ui::EditBox::KeyboardReturnType::SEND || + self.keyboardReturnType == cocos2d::ui::EditBox::KeyboardReturnType::SEARCH) + { action = cocos2d::ui::EditBoxDelegate::EditBoxEndAction::RETURN; } } return action; } -- (void)setPlaceHolder:(NSString *)text +- (void)setPlaceHolder:(NSString*)text { self.textInput.ccui_placeholder = text; } - (void)doAnimationWhenKeyboardMoveWithDuration:(float)duration distance:(float)distance { - auto view = cocos2d::Director::getInstance()->getOpenGLView(); - CCEAGLView *eaglview = (CCEAGLView *)view->getEAGLView(); - + auto view = cocos2d::Director::getInstance()->getOpenGLView(); + CCEAGLView* eaglview = (CCEAGLView*)view->getEAGLView(); + [eaglview doAnimationWhenKeyboardMoveWithDuration:duration distance:distance]; } @@ -319,16 +329,16 @@ - (void)updateFrame:(CGRect)rect { CGRect frame = self.textInput.frame; frame.origin = rect.origin; - frame.size = rect.size; - + frame.size = rect.size; + self.textInput.frame = frame; } - (void)openKeyboard { - auto view = cocos2d::Director::getInstance()->getOpenGLView(); - CCEAGLView *eaglview = (CCEAGLView *)view->getEAGLView(); - + auto view = cocos2d::Director::getInstance()->getOpenGLView(); + CCEAGLView* eaglview = (CCEAGLView*)view->getEAGLView(); + [eaglview addSubview:self.textInput]; [self.textInput becomeFirstResponder]; } @@ -339,9 +349,10 @@ - (void)closeKeyboard [self.textInput removeFromSuperview]; } -- (BOOL)textFieldShouldReturn:(UITextField *)sender +- (BOOL)textFieldShouldReturn:(UITextField*)sender { - if (sender == self.textInput) { + if (sender == self.textInput) + { self.returnPressed = YES; [sender resignFirstResponder]; } @@ -350,32 +361,33 @@ - (BOOL)textFieldShouldReturn:(UITextField *)sender - (void)animationSelector { - auto view = cocos2d::Director::getInstance()->getOpenGLView(); - CCEAGLView *eaglview = (CCEAGLView *)view->getEAGLView(); - + auto view = cocos2d::Director::getInstance()->getOpenGLView(); + CCEAGLView* eaglview = (CCEAGLView*)view->getEAGLView(); + [eaglview doAnimationWhenAnotherEditBeClicked]; } #pragma mark - UITextView delegate methods -- (BOOL)textViewShouldBeginEditing:(UITextView *)textView +- (BOOL)textViewShouldBeginEditing:(UITextView*)textView { CCLOG("textFieldShouldBeginEditing..."); - _editState = YES; + _editState = YES; _returnPressed = NO; - - auto view = cocos2d::Director::getInstance()->getOpenGLView(); - CCEAGLView *eaglview = (CCEAGLView *) view->getEAGLView(); - - if ([eaglview isKeyboardShown]) { + + auto view = cocos2d::Director::getInstance()->getOpenGLView(); + CCEAGLView* eaglview = (CCEAGLView*)view->getEAGLView(); + + if ([eaglview isKeyboardShown]) + { [self performSelector:@selector(animationSelector) withObject:nil afterDelay:0.0f]; } - + getEditBoxImplIOS()->editBoxEditingDidBegin(); return YES; } -- (BOOL)textViewShouldEndEditing:(UITextView *)textView +- (BOOL)textViewShouldEndEditing:(UITextView*)textView { CCLOG("textFieldShouldEndEditing..."); _editState = NO; @@ -383,94 +395,99 @@ - (BOOL)textViewShouldEndEditing:(UITextView *)textView const char* inputText = [textView.text UTF8String]; getEditBoxImplIOS()->editBoxEditingDidEnd(inputText, [self getEndAction]); - + return YES; } -- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text +- (BOOL)textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text { - if ( self.keyboardReturnType == cocos2d::ui::EditBox::KeyboardReturnType::DONE && - [text isEqualToString: @"\n"] ) + if (self.keyboardReturnType == cocos2d::ui::EditBox::KeyboardReturnType::DONE && [text isEqualToString:@"\n"]) { [self closeKeyboard]; } - + int maxLength = getEditBoxImplIOS()->getMaxLength(); if (maxLength < 0) { return YES; } - - // Prevent crashing undo bug http://stackoverflow.com/questions/433337/set-the-maximum-character-length-of-a-uitextfield - if (range.length + range.location > textView.text.length) { + + // Prevent crashing undo bug + // http://stackoverflow.com/questions/433337/set-the-maximum-character-length-of-a-uitextfield + if (range.length + range.location > textView.text.length) + { return NO; } - - NSUInteger oldLength = textView.text.length; + + NSUInteger oldLength = textView.text.length; NSUInteger replacementLength = text.length; - NSUInteger rangeLength = range.length; - + NSUInteger rangeLength = range.length; + NSUInteger newLength = oldLength - rangeLength + replacementLength; - + return newLength <= maxLength; } -- (void)textViewDidChange:(UITextView *)textView +- (void)textViewDidChange:(UITextView*)textView { int maxLength = getEditBoxImplIOS()->getMaxLength(); - if (textView.markedTextRange == nil) { - if (textView.text.length > maxLength) { + if (textView.markedTextRange == nil) + { + if (textView.text.length > maxLength) + { textView.text = [textView.text substringToIndex:maxLength]; } - + const char* inputText = [textView.text UTF8String]; getEditBoxImplIOS()->editBoxEditingChanged(inputText); } } - #pragma mark - UITextField delegate methods /** * Called each time when the text field's text has changed. */ -- (void)textChanged:(UITextField *)textField +- (void)textChanged:(UITextField*)textField { int maxLength = getEditBoxImplIOS()->getMaxLength(); - if (textField.markedTextRange == nil) { - if (textField.text.length > maxLength) { + if (textField.markedTextRange == nil) + { + if (textField.text.length > maxLength) + { textField.text = [textField.text substringToIndex:maxLength]; } - + const char* inputText = [textField.text UTF8String]; getEditBoxImplIOS()->editBoxEditingChanged(inputText); } } -- (BOOL)textFieldShouldBeginEditing:(UITextField *)sender // return NO to disallow editing. +- (BOOL)textFieldShouldBeginEditing:(UITextField*)sender // return NO to disallow editing. { CCLOG("textFieldShouldBeginEditing..."); - _editState = YES; + _editState = YES; _returnPressed = NO; - - auto view = cocos2d::Director::getInstance()->getOpenGLView(); - CCEAGLView *eaglview = (CCEAGLView *)view->getEAGLView(); - - if ([eaglview isKeyboardShown]) { + + auto view = cocos2d::Director::getInstance()->getOpenGLView(); + CCEAGLView* eaglview = (CCEAGLView*)view->getEAGLView(); + + if ([eaglview isKeyboardShown]) + { [self performSelector:@selector(animationSelector) withObject:nil afterDelay:0.0f]; } - + getEditBoxImplIOS()->editBoxEditingDidBegin(); return YES; } -- (BOOL)textFieldShouldEndEditing:(UITextField *)sender +- (BOOL)textFieldShouldEndEditing:(UITextField*)sender { CCLOG("textFieldShouldEndEditing..."); - _editState = NO; + _editState = NO; const char* inputText = [sender.text UTF8String]; getEditBoxImplIOS()->editBoxEditingDidEnd(inputText, [self getEndAction]); - + return YES; } @@ -481,24 +498,29 @@ - (BOOL)textFieldShouldEndEditing:(UITextField *)sender * @param string The replacement string. * @return YES if the specified text range should be replaced; otherwise, NO to keep the old text. */ -- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string +- (BOOL)textField:(UITextField*)textField + shouldChangeCharactersInRange:(NSRange)range + replacementString:(NSString*)string { int maxLength = getEditBoxImplIOS()->getMaxLength(); - if (maxLength < 0) { + if (maxLength < 0) + { return YES; } - - // Prevent crashing undo bug http://stackoverflow.com/questions/433337/set-the-maximum-character-length-of-a-uitextfield - if (range.length + range.location > textField.text.length) { + + // Prevent crashing undo bug + // http://stackoverflow.com/questions/433337/set-the-maximum-character-length-of-a-uitextfield + if (range.length + range.location > textField.text.length) + { return NO; } - - NSUInteger oldLength = textField.text.length; + + NSUInteger oldLength = textField.text.length; NSUInteger replacementLength = string.length; - NSUInteger rangeLength = range.length; - + NSUInteger rangeLength = range.length; + NSUInteger newLength = oldLength - rangeLength + replacementLength; - + return newLength <= maxLength; } diff --git a/cocos/ui/UIEditBox/iOS/CCUIMultilineTextField.mm b/cocos/ui/UIEditBox/iOS/CCUIMultilineTextField.mm index 0f84f752dc9c..d574b8269b4f 100644 --- a/cocos/ui/UIEditBox/iOS/CCUIMultilineTextField.mm +++ b/cocos/ui/UIEditBox/iOS/CCUIMultilineTextField.mm @@ -3,19 +3,19 @@ Copyright (c) 2012 James Chen Copyright (c) 2015 Mazyad Alabduljaleel Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,7 +34,6 @@ of this software and associated documentation files (the "Software"), to deal */ CGFloat const UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION = 0.25; - @implementation CCUIMultilineTextField #pragma mark - Init & Dealloc @@ -42,8 +41,9 @@ @implementation CCUIMultilineTextField - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; - if (self) { - + if (self) + { + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification @@ -55,51 +55,50 @@ - (instancetype)initWithFrame:(CGRect)frame - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; - + [_placeHolderLabel release]; - + [super dealloc]; } #pragma mark - Properties -- (NSString *)placeholder +- (NSString*)placeholder { return self.placeHolderLabel.text; } -- (void)setPlaceholder:(NSString *)placeholder +- (void)setPlaceholder:(NSString*)placeholder { self.placeHolderLabel.text = placeholder; [self.placeHolderLabel sizeToFit]; } -- (void)setText:(NSString *)text +- (void)setText:(NSString*)text { [super setText:text]; [self textChanged:nil]; } -- (UILabel *)placeHolderLabel +- (UILabel*)placeHolderLabel { - if (_placeHolderLabel == nil) { - auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + if (_placeHolderLabel == nil) + { + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); float padding = CC_EDIT_BOX_PADDING * glview->getScaleX() / glview->getContentScaleFactor(); - _placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(padding, - padding, - self.bounds.size.width - padding * 2, - 0)]; - _placeHolderLabel.lineBreakMode = NSLineBreakByWordWrapping; - _placeHolderLabel.numberOfLines = 0; - _placeHolderLabel.font = self.font; + _placeHolderLabel = + [[UILabel alloc] initWithFrame:CGRectMake(padding, padding, self.bounds.size.width - padding * 2, 0)]; + _placeHolderLabel.lineBreakMode = NSLineBreakByWordWrapping; + _placeHolderLabel.numberOfLines = 0; + _placeHolderLabel.font = self.font; _placeHolderLabel.backgroundColor = [UIColor clearColor]; - _placeHolderLabel.textColor = [UIColor lightGrayColor]; - _placeHolderLabel.alpha = 0; - + _placeHolderLabel.textColor = [UIColor lightGrayColor]; + _placeHolderLabel.alpha = 0; + [self addSubview:_placeHolderLabel]; } - + return _placeHolderLabel; } @@ -108,7 +107,7 @@ - (UILabel *)placeHolderLabel - (CGRect)textRectForBounds:(CGRect)bounds { auto glview = cocos2d::Director::getInstance()->getOpenGLView(); - + float padding = CC_EDIT_BOX_PADDING * glview->getScaleX() / glview->getContentScaleFactor(); return CGRectInset(bounds, padding, padding); } @@ -121,34 +120,37 @@ - (CGRect)editingRectForBounds:(CGRect)bounds - (void)layoutSubviews { [super layoutSubviews]; - - if (self.placeholder.length > 0) { + + if (self.placeholder.length > 0) + { [self sendSubviewToBack:self.placeHolderLabel]; } } - (void)drawRect:(CGRect)rect { - if (self.text.length == 0 && self.placeholder.length > 0) { + if (self.text.length == 0 && self.placeholder.length > 0) + { self.placeHolderLabel.alpha = 1; } - + [super drawRect:rect]; } #pragma mark - NSNotification Observers -- (void)textChanged:(NSNotification *)notification +- (void)textChanged:(NSNotification*)notification { - if (self.placeholder.length == 0) { + if (self.placeholder.length == 0) + { return; } - - [UIView animateWithDuration:UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION animations:^{ - - CGFloat alpha = (self.text.length == 0 ? 1 : 0); - self.placeHolderLabel.alpha = alpha; - }]; + + [UIView animateWithDuration:UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION + animations:^{ + CGFloat alpha = (self.text.length == 0 ? 1 : 0); + self.placeHolderLabel.alpha = alpha; + }]; } @end diff --git a/cocos/ui/UIEditBox/iOS/CCUISingleLineTextField.mm b/cocos/ui/UIEditBox/iOS/CCUISingleLineTextField.mm index 2c4b28e624cb..6a4e1b3f3c4c 100644 --- a/cocos/ui/UIEditBox/iOS/CCUISingleLineTextField.mm +++ b/cocos/ui/UIEditBox/iOS/CCUISingleLineTextField.mm @@ -3,19 +3,19 @@ Copyright (c) 2012 James Chen Copyright (c) 2015 Mazyad Alabduljaleel Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,7 +34,6 @@ of this software and associated documentation files (the "Software"), to deal * http://stackoverflow.com/questions/18244790/changing-uitextfield-placeholder-font */ - @implementation CCUISingleLineTextField #pragma mark - Init & Dealloc @@ -49,29 +48,28 @@ - (void)dealloc #pragma mark - Properties -- (UIColor *)placeholderTextColor +- (UIColor*)placeholderTextColor { return _placeholderTextColor; } -- (UIFont *)placeholderFont +- (UIFont*)placeholderFont { return _placeholderFont; } #pragma mark - Public methods -- (void)drawPlaceholderInRect:(CGRect)rect { - NSDictionary *attributes = @{ - NSForegroundColorAttributeName:_placeholderTextColor, - NSFontAttributeName:_placeholderFont - }; - +- (void)drawPlaceholderInRect:(CGRect)rect +{ + NSDictionary* attributes = + @{NSForegroundColorAttributeName : _placeholderTextColor, NSFontAttributeName : _placeholderFont}; + // center vertically CGSize textSize = [self.placeholder sizeWithAttributes:attributes]; - CGFloat hdif = rect.size.height - textSize.height; - hdif = MAX(0, hdif); - rect.origin.y += ceil(hdif/2.0); + CGFloat hdif = rect.size.height - textSize.height; + hdif = MAX(0, hdif); + rect.origin.y += ceil(hdif / 2.0); [[self placeholder] drawInRect:rect withAttributes:attributes]; } @@ -79,7 +77,7 @@ - (void)drawPlaceholderInRect:(CGRect)rect { - (CGRect)textRectForBounds:(CGRect)bounds { auto glview = cocos2d::Director::getInstance()->getOpenGLView(); - + float padding = CC_EDIT_BOX_PADDING * glview->getScaleX() / glview->getContentScaleFactor(); return CGRectInset(bounds, padding, padding); } diff --git a/cocos/ui/UIEditBox/iOS/UITextField+CCUITextInput.mm b/cocos/ui/UIEditBox/iOS/UITextField+CCUITextInput.mm index 07fdd0a955c7..77f51f2a3c9d 100644 --- a/cocos/ui/UIEditBox/iOS/UITextField+CCUITextInput.mm +++ b/cocos/ui/UIEditBox/iOS/UITextField+CCUITextInput.mm @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2015 Mazyad Alabduljaleel Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,86 +27,90 @@ of this software and associated documentation files (the "Software"), to deal @implementation UITextField (CCUITextInput) -- (NSString *)ccui_text +- (NSString*)ccui_text { return self.text; } -- (void)ccui_setText:(NSString *)ccui_text +- (void)ccui_setText:(NSString*)ccui_text { self.text = ccui_text; } -- (NSString *)ccui_placeholder +- (NSString*)ccui_placeholder { return self.placeholder; } -- (void)ccui_setPlaceholder:(NSString *)ccui_placeholder +- (void)ccui_setPlaceholder:(NSString*)ccui_placeholder { self.placeholder = ccui_placeholder; } -- (UIColor *)ccui_textColor +- (UIColor*)ccui_textColor { return self.textColor; } -- (void)ccui_setTextColor:(UIColor *)ccui_textColor +- (void)ccui_setTextColor:(UIColor*)ccui_textColor { self.textColor = ccui_textColor; } -- (UIFont *)ccui_font +- (UIFont*)ccui_font { return self.font; } -- (void)ccui_setFont:(UIFont *)ccui_font +- (void)ccui_setFont:(UIFont*)ccui_font { self.font = ccui_font; } - (NSTextAlignment)ccui_alignment { - return self.textAlignment; + return self.textAlignment; } - (void)ccui_setTextHorizontalAlignment:(NSTextAlignment)ccui_alignment { - self.textAlignment = ccui_alignment; + self.textAlignment = ccui_alignment; } -- (UIColor *)ccui_placeholderTextColor +- (UIColor*)ccui_placeholderTextColor { SEL selector = NSSelectorFromString(@"placeholderTextColor"); - if ([self respondsToSelector:selector]) { + if ([self respondsToSelector:selector]) + { return [self performSelector:selector]; } return nil; } -- (void)ccui_setPlaceholderTextColor:(UIColor *)ccui_placeholderTextColor +- (void)ccui_setPlaceholderTextColor:(UIColor*)ccui_placeholderTextColor { SEL selector = NSSelectorFromString(@"setPlaceholderTextColor:"); - if ([self respondsToSelector:selector]) { + if ([self respondsToSelector:selector]) + { [self performSelector:selector withObject:ccui_placeholderTextColor]; } } -- (UIFont *)ccui_placeholderFont +- (UIFont*)ccui_placeholderFont { SEL selector = NSSelectorFromString(@"placeholderFont"); - if ([self respondsToSelector:selector]) { + if ([self respondsToSelector:selector]) + { return [self performSelector:selector]; } return nil; } -- (void)ccui_setPlaceholderFont:(UIFont *)ccui_placeholderFont +- (void)ccui_setPlaceholderFont:(UIFont*)ccui_placeholderFont { SEL selector = NSSelectorFromString(@"setPlaceholderFont:"); - if ([self respondsToSelector:selector]) { + if ([self respondsToSelector:selector]) + { [self performSelector:selector withObject:ccui_placeholderFont]; } } @@ -121,14 +125,14 @@ - (void)ccui_setSecureTextEntry:(BOOL)ccui_secureTextEntry self.secureTextEntry = ccui_secureTextEntry; } -- (void)ccui_setDelegate:(id)delegate +- (void)ccui_setDelegate:(id)delegate { self.delegate = delegate; } @end - -void LoadUITextFieldCCUITextInputCategory() { +void LoadUITextFieldCCUITextInputCategory() +{ // noop } diff --git a/cocos/ui/UIEditBox/iOS/UITextView+CCUITextInput.mm b/cocos/ui/UIEditBox/iOS/UITextView+CCUITextInput.mm index 04fc84d87f4e..94ce69956aed 100644 --- a/cocos/ui/UIEditBox/iOS/UITextView+CCUITextInput.mm +++ b/cocos/ui/UIEditBox/iOS/UITextView+CCUITextInput.mm @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2015 Mazyad Alabduljaleel Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -25,52 +25,53 @@ of this software and associated documentation files (the "Software"), to deal #import "ui/UIEditBox/iOS/UITextView+CCUITextInput.h" - @implementation UITextView (CCUITextInput) -- (NSString *)ccui_text +- (NSString*)ccui_text { return self.text; } -- (void)ccui_setText:(NSString *)ccui_text +- (void)ccui_setText:(NSString*)ccui_text { self.text = ccui_text; } -- (NSString *)ccui_placeholder +- (NSString*)ccui_placeholder { SEL selector = @selector(placeholder); - if ([self respondsToSelector:selector]) { + if ([self respondsToSelector:selector]) + { return [self performSelector:selector]; } return nil; } -- (void)ccui_setPlaceholder:(NSString *)ccui_placeholder +- (void)ccui_setPlaceholder:(NSString*)ccui_placeholder { SEL selector = @selector(setPlaceholder:); - if ([self respondsToSelector:selector]) { + if ([self respondsToSelector:selector]) + { [self performSelector:selector withObject:ccui_placeholder]; } } -- (UIColor *)ccui_textColor +- (UIColor*)ccui_textColor { return self.textColor; } -- (void)ccui_setTextColor:(UIColor *)ccui_textColor +- (void)ccui_setTextColor:(UIColor*)ccui_textColor { self.textColor = ccui_textColor; } -- (UIFont *)ccui_font +- (UIFont*)ccui_font { return self.font; } -- (void)ccui_setFont:(UIFont *)ccui_font +- (void)ccui_setFont:(UIFont*)ccui_font { self.font = ccui_font; } @@ -85,37 +86,41 @@ - (void)ccui_setTextHorizontalAlignment:(NSTextAlignment)ccui_alignment self.textAlignment = ccui_alignment; } -- (UIColor *)ccui_placeholderTextColor +- (UIColor*)ccui_placeholderTextColor { SEL selector = NSSelectorFromString(@"placeHolderLabel"); - if ([self respondsToSelector:selector]) { - return ((UILabel *)[self performSelector:selector]).textColor; + if ([self respondsToSelector:selector]) + { + return ((UILabel*)[self performSelector:selector]).textColor; } return nil; } -- (void)ccui_setPlaceholderTextColor:(UIColor *)ccui_placeholderTextColor +- (void)ccui_setPlaceholderTextColor:(UIColor*)ccui_placeholderTextColor { SEL selector = NSSelectorFromString(@"placeHolderLabel"); - if ([self respondsToSelector:selector]) { - ((UILabel *)[self performSelector:selector]).textColor = ccui_placeholderTextColor; + if ([self respondsToSelector:selector]) + { + ((UILabel*)[self performSelector:selector]).textColor = ccui_placeholderTextColor; } } -- (UIFont *)ccui_placeholderFont +- (UIFont*)ccui_placeholderFont { SEL selector = NSSelectorFromString(@"placeHolderLabel"); - if ([self respondsToSelector:selector]) { - return ((UILabel *)[self performSelector:selector]).font; + if ([self respondsToSelector:selector]) + { + return ((UILabel*)[self performSelector:selector]).font; } return nil; } -- (void)ccui_setPlaceholderFont:(UIFont *)ccui_placeholderFont +- (void)ccui_setPlaceholderFont:(UIFont*)ccui_placeholderFont { SEL selector = NSSelectorFromString(@"placeHolderLabel"); - if ([self respondsToSelector:selector]) { - ((UILabel *)[self performSelector:selector]).font = ccui_placeholderFont; + if ([self respondsToSelector:selector]) + { + ((UILabel*)[self performSelector:selector]).font = ccui_placeholderFont; } } @@ -129,14 +134,11 @@ - (void)ccui_setSecureTextEntry:(BOOL)ccui_secureTextEntry self.secureTextEntry = ccui_secureTextEntry; } -- (void)ccui_setDelegate:(id)delegate +- (void)ccui_setDelegate:(id)delegate { self.delegate = delegate; } @end - -void LoadUITextViewCCUITextInputCategory() { - -} +void LoadUITextViewCCUITextInputCategory() {} diff --git a/cocos/ui/UIHelper.cpp b/cocos/ui/UIHelper.cpp index 60f3a98ebbc1..eaa645c707b7 100644 --- a/cocos/ui/UIHelper.cpp +++ b/cocos/ui/UIHelper.cpp @@ -63,7 +63,7 @@ Widget* Helper::seekWidgetByTag(Widget* root, int tag) return nullptr; } -Widget* Helper::seekWidgetByName(Widget* root, const std::string& name) +Widget* Helper::seekWidgetByName(Widget* root, std::string_view name) { if (!root) { @@ -116,25 +116,25 @@ Widget* Helper::seekActionWidgetByActionTag(Widget* root, int tag) return nullptr; } -std::string Helper::getSubStringOfUTF8String(const std::string& str, +std::string Helper::getSubStringOfUTF8String(std::string_view str, std::string::size_type start, std::string::size_type length) { std::u32string utf32; if (!StringUtils::UTF8ToUTF32(str, utf32)) { - CCLOGERROR("Can't convert string to UTF-32: %s", str.c_str()); + CCLOGERROR("Can't convert string to UTF-32: %s", str.data()); return ""; } if (utf32.size() < start) { - CCLOGERROR("'start' is out of range: %d, %s", static_cast(start), str.c_str()); + CCLOGERROR("'start' is out of range: %d, %s", static_cast(start), str.data()); return ""; } std::string result; if (!StringUtils::UTF32ToUTF8(utf32.substr(start, length), result)) { - CCLOGERROR("Can't convert internal UTF-32 string to UTF-8: %s", str.c_str()); + CCLOGERROR("Can't convert internal UTF-32 string to UTF-8: %s", str.data()); return ""; } return result; diff --git a/cocos/ui/UIHelper.h b/cocos/ui/UIHelper.h index 9f833bef1884..9d49b129c7b8 100644 --- a/cocos/ui/UIHelper.h +++ b/cocos/ui/UIHelper.h @@ -66,7 +66,7 @@ class CC_GUI_DLL Helper * @param name The widget name. * @return Widget instance pointer. */ - static Widget* seekWidgetByName(Widget* root, const std::string& name); + static Widget* seekWidgetByName(Widget* root, std::string_view name); /** * Find a widget with a specific action tag from root widget @@ -87,7 +87,7 @@ class CC_GUI_DLL Helper * @return a UTF8 substring * @js NA */ - static std::string getSubStringOfUTF8String(const std::string& str, + static std::string getSubStringOfUTF8String(std::string_view str, std::string::size_type start, std::string::size_type length); diff --git a/cocos/ui/UIImageView.cpp b/cocos/ui/UIImageView.cpp index da9ed8c515d1..ffa039153654 100644 --- a/cocos/ui/UIImageView.cpp +++ b/cocos/ui/UIImageView.cpp @@ -50,7 +50,7 @@ ImageView::ImageView() ImageView::~ImageView() {} -ImageView* ImageView::create(const std::string& imageFileName, TextureResType texType) +ImageView* ImageView::create(std::string_view imageFileName, TextureResType texType) { ImageView* widget = new ImageView(); if (widget->init(imageFileName, texType)) @@ -89,7 +89,7 @@ bool ImageView::init() return ret; } -bool ImageView::init(const std::string& imageFileName, TextureResType texType) +bool ImageView::init(std::string_view imageFileName, TextureResType texType) { bool bRet = true; do @@ -113,7 +113,7 @@ void ImageView::initRenderer() addProtectedChild(_imageRenderer, IMAGE_RENDERER_Z, -1); } -void ImageView::loadTexture(const std::string& fileName, TextureResType texType) +void ImageView::loadTexture(std::string_view fileName, TextureResType texType) { if (fileName.empty()) { diff --git a/cocos/ui/UIImageView.h b/cocos/ui/UIImageView.h index 525cdd2195a3..5fbb2cbde5fd 100644 --- a/cocos/ui/UIImageView.h +++ b/cocos/ui/UIImageView.h @@ -75,7 +75,7 @@ class CC_GUI_DLL ImageView : public Widget, public cocos2d::BlendProtocol * @param texType @see `Widget::TextureResType` * @return A ImageView instance. */ - static ImageView* create(const std::string& imageFileName, TextureResType texType = TextureResType::LOCAL); + static ImageView* create(std::string_view imageFileName, TextureResType texType = TextureResType::LOCAL); /** * Load texture for imageview. @@ -83,7 +83,7 @@ class CC_GUI_DLL ImageView : public Widget, public cocos2d::BlendProtocol * @param fileName file name of texture. * @param texType @see `Widget::TextureResType` */ - void loadTexture(const std::string& fileName, TextureResType texType = TextureResType::LOCAL); + void loadTexture(std::string_view fileName, TextureResType texType = TextureResType::LOCAL); /** * Updates the texture rect of the ImageView in points. @@ -150,7 +150,7 @@ class CC_GUI_DLL ImageView : public Widget, public cocos2d::BlendProtocol // initializes state of widget. virtual bool init() override; - virtual bool init(const std::string& imageFileName, TextureResType texType = TextureResType::LOCAL); + virtual bool init(std::string_view imageFileName, TextureResType texType = TextureResType::LOCAL); protected: virtual void initRenderer() override; diff --git a/cocos/ui/UILayout.cpp b/cocos/ui/UILayout.cpp index d3c914d1ebcb..a8444a5d644f 100644 --- a/cocos/ui/UILayout.cpp +++ b/cocos/ui/UILayout.cpp @@ -166,7 +166,7 @@ void Layout::addChild(Node* child, int zOrder, int tag) _doLayoutDirty = true; } -void Layout::addChild(Node* child, int zOrder, const std::string& name) +void Layout::addChild(Node* child, int zOrder, std::string_view name) { if (dynamic_cast(child)) { @@ -566,7 +566,7 @@ bool Layout::isBackGroundImageScale9Enabled() const return _backGroundScale9Enabled; } -void Layout::setBackGroundImage(const std::string& fileName, TextureResType texType) +void Layout::setBackGroundImage(std::string_view fileName, TextureResType texType) { if (fileName.empty()) { diff --git a/cocos/ui/UILayout.h b/cocos/ui/UILayout.h index 33c8903a3da9..d1dba4fbceff 100644 --- a/cocos/ui/UILayout.h +++ b/cocos/ui/UILayout.h @@ -171,7 +171,7 @@ class CC_GUI_DLL Layout : public Widget, public LayoutProtocol * @param fileName image file path. * @param texType @see TextureResType. */ - void setBackGroundImage(const std::string& fileName, TextureResType texType = TextureResType::LOCAL); + void setBackGroundImage(std::string_view fileName, TextureResType texType = TextureResType::LOCAL); /** * Sets a background image capinsets for layout, it only affects the scale9 enabled background image @@ -371,7 +371,7 @@ class CC_GUI_DLL Layout : public Widget, public LayoutProtocol * @param tag A integer to identify the node easily. Please refer to setTag(int) */ virtual void addChild(Node* child, int localZOrder, int tag) override; - virtual void addChild(Node* child, int localZOrder, const std::string& name) override; + virtual void addChild(Node* child, int localZOrder, std::string_view name) override; virtual void visit(Renderer* renderer, const Mat4& parentTransform, uint32_t parentFlags) override; diff --git a/cocos/ui/UILayoutManager.cpp b/cocos/ui/UILayoutManager.cpp index 6c40796bae3d..7213065df7da 100644 --- a/cocos/ui/UILayoutManager.cpp +++ b/cocos/ui/UILayoutManager.cpp @@ -236,7 +236,7 @@ Widget* RelativeLayoutManager::getRelativeWidget(Widget* widget) { Widget* relativeWidget = nullptr; RelativeLayoutParameter* layoutParameter = dynamic_cast(widget->getLayoutParameter()); - const std::string relativeName = layoutParameter->getRelativeToWidgetName(); + auto relativeName = layoutParameter->getRelativeToWidgetName(); if (!relativeName.empty()) { diff --git a/cocos/ui/UILayoutParameter.cpp b/cocos/ui/UILayoutParameter.cpp index 0bf409a4dc1f..d80d751a16ed 100644 --- a/cocos/ui/UILayoutParameter.cpp +++ b/cocos/ui/UILayoutParameter.cpp @@ -146,22 +146,22 @@ RelativeLayoutParameter::RelativeAlign RelativeLayoutParameter::getAlign() const return _relativeAlign; } -void RelativeLayoutParameter::setRelativeToWidgetName(const std::string& name) +void RelativeLayoutParameter::setRelativeToWidgetName(std::string_view name) { _relativeWidgetName = name; } -const std::string& RelativeLayoutParameter::getRelativeToWidgetName() const +std::string_view RelativeLayoutParameter::getRelativeToWidgetName() const { return _relativeWidgetName; } -void RelativeLayoutParameter::setRelativeName(const std::string& name) +void RelativeLayoutParameter::setRelativeName(std::string_view name) { _relativeLayoutName = name; } -const std::string& RelativeLayoutParameter::getRelativeName() const +std::string_view RelativeLayoutParameter::getRelativeName() const { return _relativeLayoutName; } diff --git a/cocos/ui/UILayoutParameter.h b/cocos/ui/UILayoutParameter.h index 1a2615da8fda..9e6b92a5d816 100644 --- a/cocos/ui/UILayoutParameter.h +++ b/cocos/ui/UILayoutParameter.h @@ -363,27 +363,27 @@ class CC_GUI_DLL RelativeLayoutParameter : public LayoutParameter * * @param name Relative widget name. */ - void setRelativeToWidgetName(const std::string& name); + void setRelativeToWidgetName(std::string_view name); /** * Get the relative widget name. * @return name A relative widget name in string. */ - const std::string& getRelativeToWidgetName() const; + std::string_view getRelativeToWidgetName() const; /** * Set a name for LayoutParameter in Relative Layout. * * @param name A string name. */ - void setRelativeName(const std::string& name); + void setRelativeName(std::string_view name); /** * Get a name of LayoutParameter in Relative Layout. * * @return name Relative name in string. */ - const std::string& getRelativeName() const; + std::string_view getRelativeName() const; // override functions. virtual LayoutParameter* createCloneInstance() override; diff --git a/cocos/ui/UIListView.cpp b/cocos/ui/UIListView.cpp index 32616f2bb58f..68b62f2c1722 100644 --- a/cocos/ui/UIListView.cpp +++ b/cocos/ui/UIListView.cpp @@ -292,7 +292,7 @@ void ListView::addChild(cocos2d::Node* child, int zOrder) ListView::addChild(child, zOrder, child->getName()); } -void ListView::addChild(Node* child, int zOrder, const std::string& name) +void ListView::addChild(Node* child, int zOrder, std::string_view name) { ScrollView::addChild(child, zOrder, name); diff --git a/cocos/ui/UIListView.h b/cocos/ui/UIListView.h index b1b54b8e5632..2b961b2a9b77 100644 --- a/cocos/ui/UIListView.h +++ b/cocos/ui/UIListView.h @@ -309,7 +309,7 @@ class CC_GUI_DLL ListView : public ScrollView virtual void addChild(Node* child) override; virtual void addChild(Node* child, int localZOrder) override; virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, const std::string& name) override; + virtual void addChild(Node* child, int zOrder, std::string_view name) override; virtual void removeAllChildren() override; virtual void removeAllChildrenWithCleanup(bool cleanup) override; virtual void removeChild(Node* child, bool cleanup = true) override; diff --git a/cocos/ui/UILoadingBar.cpp b/cocos/ui/UILoadingBar.cpp index e1a9e518dfb5..b3518941ce98 100644 --- a/cocos/ui/UILoadingBar.cpp +++ b/cocos/ui/UILoadingBar.cpp @@ -71,12 +71,12 @@ LoadingBar* LoadingBar::create() return nullptr; } -LoadingBar* LoadingBar::create(const std::string& textureName, float percentage) +LoadingBar* LoadingBar::create(std::string_view textureName, float percentage) { return LoadingBar::create(textureName, TextureResType::LOCAL, percentage); } -LoadingBar* LoadingBar::create(const std::string& textureName, TextureResType texType, float percentage) +LoadingBar* LoadingBar::create(std::string_view textureName, TextureResType texType, float percentage) { LoadingBar* widget = new LoadingBar; if (widget->init()) @@ -125,7 +125,7 @@ LoadingBar::Direction LoadingBar::getDirection() const return _direction; } -void LoadingBar::loadTexture(const std::string& texture, TextureResType texType) +void LoadingBar::loadTexture(std::string_view texture, TextureResType texType) { if (texture.empty()) { diff --git a/cocos/ui/UILoadingBar.h b/cocos/ui/UILoadingBar.h index b83b298db69c..6206bf32f1dc 100644 --- a/cocos/ui/UILoadingBar.h +++ b/cocos/ui/UILoadingBar.h @@ -88,7 +88,7 @@ class CC_GUI_DLL LoadingBar : public Widget * @param percentage A percentage in float. * @return A LoadingBar instance. */ - static LoadingBar* create(const std::string& textureName, float percentage = 0); + static LoadingBar* create(std::string_view textureName, float percentage = 0); /** * @brief Create a LoadingBar with a texture name along with its texture type and a predefined progress value. @@ -98,7 +98,7 @@ class CC_GUI_DLL LoadingBar : public Widget * @param percentage A percentage in float, default value is 0. * @return A LoadingBar instance. */ - static LoadingBar* create(const std::string& textureName, TextureResType texType, float percentage = 0); + static LoadingBar* create(std::string_view textureName, TextureResType texType, float percentage = 0); /** * Change the progress direction of LoadingBar. @@ -122,7 +122,7 @@ class CC_GUI_DLL LoadingBar : public Widget * @param texture File name of texture. * @param texType Texture resource type,@see TextureResType. */ - void loadTexture(const std::string& texture, TextureResType texType = TextureResType::LOCAL); + void loadTexture(std::string_view texture, TextureResType texType = TextureResType::LOCAL); /** * Changes the progress value of LoadingBar. diff --git a/cocos/ui/UIPageView.cpp b/cocos/ui/UIPageView.cpp index 06a56f3258f6..b92f56a7b6a4 100644 --- a/cocos/ui/UIPageView.cpp +++ b/cocos/ui/UIPageView.cpp @@ -465,7 +465,7 @@ float PageView::getIndicatorIndexNodesScale() const return _indicator->getIndexNodesScale(); } -void PageView::setIndicatorIndexNodesTexture(const std::string& texName, Widget::TextureResType texType) +void PageView::setIndicatorIndexNodesTexture(std::string_view texName, Widget::TextureResType texType) { if (_indicator != nullptr) { diff --git a/cocos/ui/UIPageView.h b/cocos/ui/UIPageView.h index 97d8320ddf37..6325e9561c86 100644 --- a/cocos/ui/UIPageView.h +++ b/cocos/ui/UIPageView.h @@ -314,7 +314,7 @@ class CC_GUI_DLL PageView : public ListView * @param fileName File name of texture. * @param resType @see TextureResType . */ - void setIndicatorIndexNodesTexture(const std::string& texName, + void setIndicatorIndexNodesTexture(std::string_view texName, Widget::TextureResType texType = Widget::TextureResType::LOCAL); /** diff --git a/cocos/ui/UIPageViewIndicator.cpp b/cocos/ui/UIPageViewIndicator.cpp index 530df5a82ce2..94590ced01fe 100644 --- a/cocos/ui/UIPageViewIndicator.cpp +++ b/cocos/ui/UIPageViewIndicator.cpp @@ -195,7 +195,7 @@ void PageViewIndicator::setIndexNodesScale(float indexNodesScale) rearrange(); } -void PageViewIndicator::setIndexNodesTexture(const std::string& texName, Widget::TextureResType texType) +void PageViewIndicator::setIndexNodesTexture(std::string_view texName, Widget::TextureResType texType) { _useDefaultTexture = false; _indexNodesTextureFile = texName; diff --git a/cocos/ui/UIPageViewIndicator.h b/cocos/ui/UIPageViewIndicator.h index d498c4cdfdd6..21c0360b04a1 100644 --- a/cocos/ui/UIPageViewIndicator.h +++ b/cocos/ui/UIPageViewIndicator.h @@ -74,8 +74,7 @@ class PageViewIndicator : public ProtectedNode * @param fileName File name of texture. * @param resType @see TextureResType . */ - void setIndexNodesTexture(const std::string& texName, - Widget::TextureResType texType = Widget::TextureResType::LOCAL); + void setIndexNodesTexture(std::string_view texName, Widget::TextureResType texType = Widget::TextureResType::LOCAL); protected: bool init() override; diff --git a/cocos/ui/UIRadioButton.cpp b/cocos/ui/UIRadioButton.cpp index 14d9e639d974..ff1ad49f1dca 100644 --- a/cocos/ui/UIRadioButton.cpp +++ b/cocos/ui/UIRadioButton.cpp @@ -52,11 +52,11 @@ RadioButton* RadioButton::create() return nullptr; } -RadioButton* RadioButton::create(const std::string& backGround, - const std::string& backGroundSelected, - const std::string& cross, - const std::string& backGroundDisabled, - const std::string& frontCrossDisabled, +RadioButton* RadioButton::create(std::string_view backGround, + std::string_view backGroundSelected, + std::string_view cross, + std::string_view backGroundDisabled, + std::string_view frontCrossDisabled, TextureResType texType) { RadioButton* pWidget = new RadioButton(); @@ -69,7 +69,7 @@ RadioButton* RadioButton::create(const std::string& backGround, return nullptr; } -RadioButton* RadioButton::create(const std::string& backGround, const std::string& cross, TextureResType texType) +RadioButton* RadioButton::create(std::string_view backGround, std::string_view cross, TextureResType texType) { RadioButton* pWidget = new RadioButton(); if (pWidget->init(backGround, "", cross, "", "", texType)) diff --git a/cocos/ui/UIRadioButton.h b/cocos/ui/UIRadioButton.h index 9adb3c83577f..43deb3b92e02 100644 --- a/cocos/ui/UIRadioButton.h +++ b/cocos/ui/UIRadioButton.h @@ -98,11 +98,11 @@ class CC_GUI_DLL RadioButton : public AbstractCheckButton * * @return A RadioButton instance pointer. */ - static RadioButton* create(const std::string& backGround, - const std::string& backGroundSelected, - const std::string& cross, - const std::string& backGroundDisabled, - const std::string& frontCrossDisabled, + static RadioButton* create(std::string_view backGround, + std::string_view backGroundSelected, + std::string_view cross, + std::string_view backGroundDisabled, + std::string_view frontCrossDisabled, TextureResType texType = TextureResType::LOCAL); /** @@ -113,8 +113,8 @@ class CC_GUI_DLL RadioButton : public AbstractCheckButton * @param texType The texture's resource type in `Widget::TextureResType`. * @return A RadioButton instance pointer */ - static RadioButton* create(const std::string& backGround, - const std::string& cross, + static RadioButton* create(std::string_view backGround, + std::string_view cross, TextureResType texType = TextureResType::LOCAL); /** diff --git a/cocos/ui/UIRichText.cpp b/cocos/ui/UIRichText.cpp index e46456085bba..a65700cc4ea2 100644 --- a/cocos/ui/UIRichText.cpp +++ b/cocos/ui/UIRichText.cpp @@ -1,8 +1,9 @@ /**************************************************************************** Copyright (c) 2013 cocos2d-x.org Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2021 Bytedance Inc. - http://www.cocos2d-x.org + https://adxeproject.github.io Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -51,7 +52,7 @@ class ListenerComponent : public Component static const std::string COMPONENT_NAME; /*!< component name */ static ListenerComponent* create(Node* parent, - const std::string& url, + std::string_view url, const RichText::OpenUrlHandler handleOpenUrl = nullptr) { auto component = new ListenerComponent(parent, url, std::move(handleOpenUrl)); @@ -59,7 +60,7 @@ class ListenerComponent : public Component return component; } - explicit ListenerComponent(Node* parent, const std::string& url, const RichText::OpenUrlHandler handleOpenUrl) + explicit ListenerComponent(Node* parent, std::string_view url, const RichText::OpenUrlHandler handleOpenUrl) : _parent(parent), _url(url), _handleOpenUrl(std::move(handleOpenUrl)) { setName(ListenerComponent::COMPONENT_NAME); @@ -124,11 +125,11 @@ void RichElement::setColor(const Color3B& color) RichElementText* RichElementText::create(int tag, const Color3B& color, uint8_t opacity, - const std::string& text, - const std::string& fontName, + std::string_view text, + std::string_view fontName, float fontSize, uint32_t flags, - const std::string& url, + std::string_view url, const Color3B& outlineColor, int outlineSize, const Color3B& shadowColor, @@ -150,11 +151,11 @@ RichElementText* RichElementText::create(int tag, bool RichElementText::init(int tag, const Color3B& color, uint8_t opacity, - const std::string& text, - const std::string& fontName, + std::string_view text, + std::string_view fontName, float fontSize, uint32_t flags, - const std::string& url, + std::string_view url, const Color3B& outlineColor, int outlineSize, const Color3B& shadowColor, @@ -183,8 +184,8 @@ bool RichElementText::init(int tag, RichElementImage* RichElementImage::create(int tag, const Color3B& color, uint8_t opacity, - const std::string& filePath, - const std::string& url, + std::string_view filePath, + std::string_view url, Widget::TextureResType texType) { RichElementImage* element = new RichElementImage(); @@ -200,8 +201,8 @@ RichElementImage* RichElementImage::create(int tag, bool RichElementImage::init(int tag, const Color3B& color, uint8_t opacity, - const std::string& filePath, - const std::string& url, + std::string_view filePath, + std::string_view url, Widget::TextureResType texType) { if (RichElement::init(tag, color, opacity)) @@ -226,7 +227,7 @@ void RichElementImage::setHeight(int height) _height = height; } -void RichElementImage::setUrl(const std::string& url) +void RichElementImage::setUrl(std::string_view url) { _url = url; } @@ -334,7 +335,7 @@ class MyXMLVisitor : public SAXDelegator bool isFontElement; RichText::VisitEnterHandler handleVisitEnter; }; - typedef std::unordered_map TagTables; + typedef hlookup::string_map TagTables; static TagTables _tagTables; @@ -376,11 +377,11 @@ class MyXMLVisitor : public SAXDelegator void pushBackElement(RichElement* element); - static void setTagDescription(const std::string& tag, + static void setTagDescription(std::string_view tag, bool isFontElement, RichText::VisitEnterHandler&& handleVisitEnter); - static void removeTagDescription(const std::string& tag); + static void removeTagDescription(std::string_view tag); private: ValueMap tagAttrMapWithXMLElement(const char** attrs); @@ -907,14 +908,19 @@ void MyXMLVisitor::pushBackElement(RichElement* element) _richText->pushBackElement(element); } -void MyXMLVisitor::setTagDescription(const std::string& tag, +void MyXMLVisitor::setTagDescription(std::string_view tag, bool isFontElement, RichText::VisitEnterHandler&& handleVisitEnter) { - MyXMLVisitor::_tagTables[tag] = {isFontElement, std::move(handleVisitEnter)}; + hlookup::set_item( + MyXMLVisitor::_tagTables, tag, + TagBehavior{ + isFontElement, + std::move( + handleVisitEnter)}); // MyXMLVisitor::_tagTables[tag] = {isFontElement, std::move(handleVisitEnter)}; } -void MyXMLVisitor::removeTagDescription(const std::string& tag) +void MyXMLVisitor::removeTagDescription(std::string_view tag) { MyXMLVisitor::_tagTables.erase(tag); } @@ -1004,7 +1010,7 @@ RichText* RichText::create() return nullptr; } -RichText* RichText::createWithXML(const std::string& xml, const ValueMap& defaults, const OpenUrlHandler& handleOpenUrl) +RichText* RichText::createWithXML(std::string_view xml, const ValueMap& defaults, const OpenUrlHandler& handleOpenUrl) { RichText* widget = new RichText(); if (widget->initWithXML(xml, defaults, handleOpenUrl)) @@ -1025,7 +1031,7 @@ bool RichText::init() return false; } -bool RichText::initWithXML(const std::string& origxml, const ValueMap& defaults, const OpenUrlHandler& handleOpenUrl) +bool RichText::initWithXML(std::string_view origxml, const ValueMap& defaults, const OpenUrlHandler& handleOpenUrl) { static std::function startTagFont = [](RichText* richText) { std::string fontFace = richText->getFontFace(); @@ -1109,7 +1115,7 @@ void RichText::setHorizontalAlignment(cocos2d::ui::RichText::HorizontalAlignment } } -void RichText::setFontColor(const std::string& color) +void RichText::setFontColor(std::string_view color) { _defaults[KEY_FONT_COLOR_STRING] = color; } @@ -1134,7 +1140,7 @@ float RichText::getFontSize() return _defaults.at(KEY_FONT_SIZE).asFloat(); } -void RichText::setFontFace(const std::string& face) +void RichText::setFontFace(std::string_view face) { _defaults[KEY_FONT_FACE] = face; } @@ -1144,7 +1150,7 @@ std::string RichText::getFontFace() return _defaults.at(KEY_FONT_FACE).asString(); } -void RichText::setAnchorFontColor(const std::string& color) +void RichText::setAnchorFontColor(std::string_view color) { _defaults[KEY_ANCHOR_FONT_COLOR_STRING] = color; } @@ -1393,12 +1399,12 @@ ValueMap RichText::getDefaults() const return defaults; } -cocos2d::Color3B RichText::color3BWithString(const std::string& color) +cocos2d::Color3B RichText::color3BWithString(std::string_view color) { if (color.length() == 4) { - int r, g, b; - sscanf(color.c_str(), "%*c%1x%1x%1x", &r, &g, &b); + unsigned int r, g, b; + sscanf(color.data(), "%*c%1x%1x%1x", &r, &g, &b); r += r * 16; g += g * 16; b += b * 16; @@ -1406,14 +1412,14 @@ cocos2d::Color3B RichText::color3BWithString(const std::string& color) } else if (color.length() == 7) { - int r, g, b; - sscanf(color.c_str(), "%*c%2x%2x%2x", &r, &g, &b); + unsigned int r, g, b; + sscanf(color.data(), "%*c%2x%2x%2x", &r, &g, &b); return Color3B(r, g, b); } else if (color.length() == 9) { - int r, g, b, a; - sscanf(color.c_str(), "%*c%2x%2x%2x%2x", &r, &g, &b, &a); + unsigned int r, g, b, a; + sscanf(color.data(), "%*c%2x%2x%2x%2x", &r, &g, &b, &a); return Color3B(r, g, b); } return Color3B::WHITE; @@ -1440,17 +1446,17 @@ std::string RichText::stringWithColor4B(const cocos2d::Color4B& color4b) return std::string(buf, 9); } -void RichText::setTagDescription(const std::string& tag, bool isFontElement, VisitEnterHandler handleVisitEnter) +void RichText::setTagDescription(std::string_view tag, bool isFontElement, VisitEnterHandler handleVisitEnter) { MyXMLVisitor::setTagDescription(tag, isFontElement, std::move(handleVisitEnter)); } -void RichText::removeTagDescription(const std::string& tag) +void RichText::removeTagDescription(std::string_view tag) { MyXMLVisitor::removeTagDescription(tag); } -void RichText::openUrl(const std::string& url) +void RichText::openUrl(std::string_view url) { if (_handleOpenUrl) { @@ -1767,13 +1773,13 @@ int findSplitPositionForChar(Label* label, } } // namespace -void RichText::handleTextRenderer(const std::string& text, - const std::string& fontName, +void RichText::handleTextRenderer(std::string_view text, + std::string_view fontName, float fontSize, const Color3B& color, uint8_t opacity, uint32_t flags, - const std::string& url, + std::string_view url, const Color3B& outlineColor, int outlineSize, const Color3B& shadowColor, @@ -1785,7 +1791,8 @@ void RichText::handleTextRenderer(const std::string& text, RichText::WrapMode wrapMode = static_cast(_defaults.at(KEY_WRAP_MODE).asInt()); // split text by \n - std::stringstream ss(text); + std::stringstream ss; + ss << text; std::string currentText; size_t realLines = 0; while (std::getline(ss, currentText, '\n')) @@ -1877,13 +1884,13 @@ void RichText::handleTextRenderer(const std::string& text, } } -void RichText::handleImageRenderer(const std::string& filePath, +void RichText::handleImageRenderer(std::string_view filePath, Widget::TextureResType textureType, const Color3B& /*color*/, uint8_t /*opacity*/, int width, int height, - const std::string& url) + std::string_view url) { Sprite* imageRenderer; if (textureType == Widget::TextureResType::LOCAL) @@ -2062,10 +2069,9 @@ bool isWhitespace(char c) { return std::isspace(c, std::locale()); } -std::string rtrim(std::string s) +void rtrim(std::string& s) { s.erase(std::find_if_not(s.rbegin(), s.rend(), isWhitespace).base(), s.end()); - return s; } } // namespace @@ -2075,8 +2081,9 @@ float RichText::stripTrailingWhitespace(const Vector& row) { if (auto label = dynamic_cast(row.back())) { - const auto width = label->getContentSize().width; - const auto trimmedString = rtrim(label->getString()); + const auto width = label->getContentSize().width; + std::string trimmedString{label->getString()}; + rtrim(trimmedString); if (label->getString() != trimmedString) { label->setString(trimmedString); diff --git a/cocos/ui/UIRichText.h b/cocos/ui/UIRichText.h index 4c694c8af9c2..7428a38bc1c3 100644 --- a/cocos/ui/UIRichText.h +++ b/cocos/ui/UIRichText.h @@ -148,11 +148,11 @@ class CC_GUI_DLL RichElementText : public RichElement bool init(int tag, const Color3B& color, uint8_t opacity, - const std::string& text, - const std::string& fontName, + std::string_view text, + std::string_view fontName, float fontSize, uint32_t flags, - const std::string& url, + std::string_view url, const Color3B& outlineColor = Color3B::WHITE, int outlineSize = -1, const Color3B& shadowColor = Color3B::BLACK, @@ -182,11 +182,11 @@ class CC_GUI_DLL RichElementText : public RichElement static RichElementText* create(int tag, const Color3B& color, uint8_t opacity, - const std::string& text, - const std::string& fontName, + std::string_view text, + std::string_view fontName, float fontSize, uint32_t flags = 0, - const std::string& url = "", + std::string_view url = "", const Color3B& outlineColor = Color3B::WHITE, int outlineSize = -1, const Color3B& shadowColor = Color3B::BLACK, @@ -244,8 +244,8 @@ class CC_GUI_DLL RichElementImage : public RichElement bool init(int tag, const Color3B& color, uint8_t opacity, - const std::string& filePath, - const std::string& url = "", + std::string_view filePath, + std::string_view url = "", Widget::TextureResType texType = Widget::TextureResType::LOCAL); /** @@ -262,13 +262,13 @@ class CC_GUI_DLL RichElementImage : public RichElement static RichElementImage* create(int tag, const Color3B& color, uint8_t opacity, - const std::string& filePath, - const std::string& url = "", + std::string_view filePath, + std::string_view url = "", Widget::TextureResType texType = Widget::TextureResType::LOCAL); void setWidth(int width); void setHeight(int height); - void setUrl(const std::string& url); + void setUrl(std::string_view url); protected: std::string _filePath; @@ -386,7 +386,7 @@ class CC_GUI_DLL RichText : public Widget * @brief call to open a resource specified by a URL * @param url a URL */ - typedef std::function OpenUrlHandler; + typedef std::function OpenUrlHandler; /** * @brief called on the specified tag @@ -461,7 +461,7 @@ class CC_GUI_DLL RichText : public Widget * * @return RichText instance. */ - static RichText* createWithXML(const std::string& xml, + static RichText* createWithXML(std::string_view xml, const ValueMap& defaults = ValueMap(), const OpenUrlHandler& handleOpenUrl = nullptr); @@ -517,24 +517,24 @@ class CC_GUI_DLL RichText : public Widget HorizontalAlignment a); /*!< sets the horizontal alignment mode: LEFT, CENTER, or RIGHT */ HorizontalAlignment getHorizontalAlignment() const; /*!< returns the current horizontal alignment mode */ void setFontColor( - const std::string& color); /*!< Set the font color. @param color the #RRGGBB hexadecimal notation. */ - std::string getFontColor(); /*!< return the current font color */ - Color3B getFontColor3B(); /*!< return the current font color */ - void setFontSize(float size); /*!< Set the font size. @param size the font size. */ - float getFontSize(); /*!< return the current font size */ - void setFontFace(const std::string& face); /*!< Set the font face. @param face the font face. */ - std::string getFontFace(); /*!< return the current font face */ - void setAnchorFontColor(const std::string& color); /*!< Set the font color of a-tag. @param face the font color. */ - std::string getAnchorFontColor(); /*!< return the current font color of a-tag */ - cocos2d::Color3B getAnchorFontColor3B(); /*!< return the current font color of a-tag */ - void setAnchorTextBold(bool enable); /*!< enable bold text of a-tag */ - bool isAnchorTextBoldEnabled(); /*!< valid style is bold text of a-tag? */ - void setAnchorTextItalic(bool enable); /*!< enable italic text of a-tag */ - bool isAnchorTextItalicEnabled(); /*!< valid style is italic text of a-tag? */ - void setAnchorTextDel(bool enable); /*!< enable the strikethrough of a-tag */ - bool isAnchorTextDelEnabled(); /*!< valid strikethrough of a-tag? */ - void setAnchorTextUnderline(bool enable); /*!< enable the underline of a-tag */ - bool isAnchorTextUnderlineEnabled(); /*!< valid underline of a-tag? */ + std::string_view color); /*!< Set the font color. @param color the #RRGGBB hexadecimal notation. */ + std::string getFontColor(); /*!< return the current font color */ + Color3B getFontColor3B(); /*!< return the current font color */ + void setFontSize(float size); /*!< Set the font size. @param size the font size. */ + float getFontSize(); /*!< return the current font size */ + void setFontFace(std::string_view face); /*!< Set the font face. @param face the font face. */ + std::string getFontFace(); /*!< return the current font face */ + void setAnchorFontColor(std::string_view color); /*!< Set the font color of a-tag. @param face the font color. */ + std::string getAnchorFontColor(); /*!< return the current font color of a-tag */ + cocos2d::Color3B getAnchorFontColor3B(); /*!< return the current font color of a-tag */ + void setAnchorTextBold(bool enable); /*!< enable bold text of a-tag */ + bool isAnchorTextBoldEnabled(); /*!< valid style is bold text of a-tag? */ + void setAnchorTextItalic(bool enable); /*!< enable italic text of a-tag */ + bool isAnchorTextItalicEnabled(); /*!< valid style is italic text of a-tag? */ + void setAnchorTextDel(bool enable); /*!< enable the strikethrough of a-tag */ + bool isAnchorTextDelEnabled(); /*!< valid strikethrough of a-tag? */ + void setAnchorTextUnderline(bool enable); /*!< enable the underline of a-tag */ + bool isAnchorTextUnderlineEnabled(); /*!< valid underline of a-tag? */ /** @brief enable the outline of a-tag */ void setAnchorTextOutline(bool enable, const Color3B& outlineColor = Color3B::WHITE, int outlineSize = -1); bool isAnchorTextOutlineEnabled(); /*!< valid outline of a-tag? */ @@ -555,7 +555,7 @@ class CC_GUI_DLL RichText : public Widget void setDefaults(const ValueMap& defaults); /*!< set the default values */ ValueMap getDefaults() const; /*!< returns the default values */ - cocos2d::Color3B color3BWithString(const std::string& color); /*!< convert a color string into a Color3B. */ + cocos2d::Color3B color3BWithString(std::string_view color); /*!< convert a color string into a Color3B. */ std::string stringWithColor3B(const cocos2d::Color3B& color3b); /*!< convert a Color3B into a color string. */ std::string stringWithColor4B(const cocos2d::Color4B& color4b); /*!< convert a Color4B into a color string. */ @@ -565,15 +565,15 @@ class CC_GUI_DLL RichText : public Widget * @param isFontElement use attributes of text tag * @param handleVisitEnter callback */ - static void setTagDescription(const std::string& tag, bool isFontElement, VisitEnterHandler handleVisitEnter); + static void setTagDescription(std::string_view tag, bool isFontElement, VisitEnterHandler handleVisitEnter); /** * @brief remove a callback to own tag. * @param tag tag's name */ - static void removeTagDescription(const std::string& tag); + static void removeTagDescription(std::string_view tag); - void openUrl(const std::string& url); + void openUrl(std::string_view url); /** * @brief Asks the callback to open a resource specified by a URL. @@ -584,7 +584,7 @@ class CC_GUI_DLL RichText : public Widget CC_CONSTRUCTOR_ACCESS : virtual bool init() override; - bool initWithXML(const std::string& xml, + bool initWithXML(std::string_view xml, const ValueMap& defaults = ValueMap(), const OpenUrlHandler& handleOpenUrl = nullptr); @@ -593,26 +593,26 @@ class CC_GUI_DLL RichText : public Widget virtual void initRenderer() override; void pushToContainer(Node* renderer); - void handleTextRenderer(const std::string& text, - const std::string& fontName, + void handleTextRenderer(std::string_view text, + std::string_view fontName, float fontSize, const Color3B& color, uint8_t opacity, uint32_t flags, - const std::string& url = "", + std::string_view url = "", const Color3B& outlineColor = Color3B::WHITE, int outlineSize = -1, const Color3B& shadowColor = Color3B::BLACK, const Vec2& shadowOffset = Vec2(2.0, -2.0), int shadowBlurRadius = 0, const Color3B& glowColor = Color3B::WHITE); - void handleImageRenderer(const std::string& filePath, + void handleImageRenderer(std::string_view filePath, Widget::TextureResType textureType, const Color3B& color, uint8_t opacity, int width, int height, - const std::string& url); + std::string_view url); void handleCustomRenderer(Node* renderer); void formatRenderers(); void addNewLine(); diff --git a/cocos/ui/UIScale9Sprite.cpp b/cocos/ui/UIScale9Sprite.cpp index dba22480e45f..eedb3152d40c 100644 --- a/cocos/ui/UIScale9Sprite.cpp +++ b/cocos/ui/UIScale9Sprite.cpp @@ -53,7 +53,7 @@ Scale9Sprite* Scale9Sprite::create() return nullptr; } -Scale9Sprite* Scale9Sprite::create(const std::string& filename, const Rect& rect, const Rect& capInsets) +Scale9Sprite* Scale9Sprite::create(std::string_view filename, const Rect& rect, const Rect& capInsets) { Scale9Sprite* ret = new Scale9Sprite(); if (ret->initWithFile(filename, rect, capInsets)) @@ -65,12 +65,12 @@ Scale9Sprite* Scale9Sprite::create(const std::string& filename, const Rect& rect return nullptr; } -Scale9Sprite* Scale9Sprite::create(const std::string& filename, const Rect& rect) +Scale9Sprite* Scale9Sprite::create(std::string_view filename, const Rect& rect) { return create(filename, rect, Rect::ZERO); } -Scale9Sprite* Scale9Sprite::create(const Rect& capInsets, const std::string& file) +Scale9Sprite* Scale9Sprite::create(const Rect& capInsets, std::string_view file) { Scale9Sprite* ret = new Scale9Sprite(); if (ret->initWithFile(capInsets, file)) @@ -82,7 +82,7 @@ Scale9Sprite* Scale9Sprite::create(const Rect& capInsets, const std::string& fil return nullptr; } -Scale9Sprite* Scale9Sprite::create(const std::string& fileaname) +Scale9Sprite* Scale9Sprite::create(std::string_view fileaname) { return create(Rect::ZERO, fileaname); } @@ -104,7 +104,7 @@ Scale9Sprite* Scale9Sprite::createWithSpriteFrame(SpriteFrame* spriteFrame) return createWithSpriteFrame(spriteFrame, Rect::ZERO); } -Scale9Sprite* Scale9Sprite::createWithSpriteFrameName(const std::string& spriteFrameName, const Rect& capInsets) +Scale9Sprite* Scale9Sprite::createWithSpriteFrameName(std::string_view spriteFrameName, const Rect& capInsets) { Scale9Sprite* ret = new Scale9Sprite(); if (ret->initWithSpriteFrameName(spriteFrameName, capInsets)) @@ -116,7 +116,7 @@ Scale9Sprite* Scale9Sprite::createWithSpriteFrameName(const std::string& spriteF return nullptr; } -Scale9Sprite* Scale9Sprite::createWithSpriteFrameName(const std::string& spriteFrameName) +Scale9Sprite* Scale9Sprite::createWithSpriteFrameName(std::string_view spriteFrameName) { Scale9Sprite* ret = new Scale9Sprite(); if (ret->initWithSpriteFrameName(spriteFrameName, Rect::ZERO)) @@ -142,7 +142,7 @@ Scale9Sprite::Scale9Sprite() Scale9Sprite::~Scale9Sprite() {} -bool Scale9Sprite::initWithFile(const Rect& capInsets, const std::string& file) +bool Scale9Sprite::initWithFile(const Rect& capInsets, std::string_view file) { // calls super bool ret = Sprite::initWithFile(file); @@ -150,7 +150,7 @@ bool Scale9Sprite::initWithFile(const Rect& capInsets, const std::string& file) return ret; } -bool Scale9Sprite::initWithFile(const std::string& filename) +bool Scale9Sprite::initWithFile(std::string_view filename) { // calls super auto originalCapInsets = this->getCapInsets(); @@ -159,7 +159,7 @@ bool Scale9Sprite::initWithFile(const std::string& filename) return ret; } -bool Scale9Sprite::initWithFile(const std::string& filename, const Rect& rect) +bool Scale9Sprite::initWithFile(std::string_view filename, const Rect& rect) { // calls super auto originalCapInsets = this->getCapInsets(); @@ -176,7 +176,7 @@ bool Scale9Sprite::initWithSpriteFrame(SpriteFrame* spriteFrame, const Rect& cap return ret; } -bool Scale9Sprite::initWithSpriteFrameName(const std::string& spriteFrameName, const Rect& capInsets) +bool Scale9Sprite::initWithSpriteFrameName(std::string_view spriteFrameName, const Rect& capInsets) { // calls super bool ret = Sprite::initWithSpriteFrameName(spriteFrameName); @@ -184,7 +184,7 @@ bool Scale9Sprite::initWithSpriteFrameName(const std::string& spriteFrameName, c return ret; } -bool Scale9Sprite::initWithSpriteFrameName(const std::string& spriteFrameName) +bool Scale9Sprite::initWithSpriteFrameName(std::string_view spriteFrameName) { // calls super auto originalCapInsets = this->getCapInsets(); @@ -242,7 +242,7 @@ bool Scale9Sprite::init(Sprite* sprite, return ret; } -bool Scale9Sprite::initWithFile(const std::string& filename, const Rect& rect, const Rect& capInsets) +bool Scale9Sprite::initWithFile(std::string_view filename, const Rect& rect, const Rect& capInsets) { // calls super bool ret = false; diff --git a/cocos/ui/UIScale9Sprite.h b/cocos/ui/UIScale9Sprite.h index 94c4226d5839..3e11d0743ca8 100644 --- a/cocos/ui/UIScale9Sprite.h +++ b/cocos/ui/UIScale9Sprite.h @@ -108,7 +108,7 @@ class CC_GUI_DLL Scale9Sprite : public Sprite * @param capInsets A specified cap insets. * @return A Scale9Sprite instance. */ - static Scale9Sprite* create(const std::string& file, const Rect& rect, const Rect& capInsets); + static Scale9Sprite* create(std::string_view file, const Rect& rect, const Rect& capInsets); /** * Creates a 9-slice sprite with a texture file. The whole texture will be @@ -119,7 +119,7 @@ class CC_GUI_DLL Scale9Sprite : public Sprite * @param file A texture file name. * @return A Scale9Sprite instance. */ - static Scale9Sprite* create(const Rect& capInsets, const std::string& file); + static Scale9Sprite* create(const Rect& capInsets, std::string_view file); /** * Creates a 9-slice sprite with a texture file and a delimitation zone. The @@ -130,7 +130,7 @@ class CC_GUI_DLL Scale9Sprite : public Sprite * @param rect A delimitation zone. * @return A Scale9Sprite instance. */ - static Scale9Sprite* create(const std::string& file, const Rect& rect); + static Scale9Sprite* create(std::string_view file, const Rect& rect); /** * Creates a 9-slice sprite with a texture file. The whole texture will be @@ -140,7 +140,7 @@ class CC_GUI_DLL Scale9Sprite : public Sprite * @param file A texture file name. * @return A Scale9Sprite instance. */ - static Scale9Sprite* create(const std::string& file); + static Scale9Sprite* create(std::string_view file); /** * Creates a 9-slice sprite with an sprite frame. @@ -177,7 +177,7 @@ class CC_GUI_DLL Scale9Sprite : public Sprite * @param spriteFrameName A sprite frame name. * @return A Scale9Sprite instance. */ - static Scale9Sprite* createWithSpriteFrameName(const std::string& spriteFrameName); + static Scale9Sprite* createWithSpriteFrameName(std::string_view spriteFrameName); /** * Creates a 9-slice sprite with an sprite frame name and the centre of its zone. @@ -190,7 +190,7 @@ class CC_GUI_DLL Scale9Sprite : public Sprite * @param capInsets A delimitation zone. * @return A Scale9Sprite instance. */ - static Scale9Sprite* createWithSpriteFrameName(const std::string& spriteFrameName, const Rect& capInsets); + static Scale9Sprite* createWithSpriteFrameName(std::string_view spriteFrameName, const Rect& capInsets); // overridden methods that takes different parameters using Sprite::initWithFile; @@ -212,7 +212,7 @@ class CC_GUI_DLL Scale9Sprite : public Sprite * @param capInsets The values to use for the cap insets. * @return True if initialize success, false otherwise. */ - virtual bool initWithFile(const std::string& file, const Rect& rect, const Rect& capInsets); + virtual bool initWithFile(std::string_view file, const Rect& rect, const Rect& capInsets); /** * Initializes a 9-slice sprite with a texture file and with the specified cap @@ -225,7 +225,7 @@ class CC_GUI_DLL Scale9Sprite : public Sprite * @param capInsets The values to use for the cap insets. * @return True if initializes success, false otherwise. */ - virtual bool initWithFile(const Rect& capInsets, const std::string& file); + virtual bool initWithFile(const Rect& capInsets, std::string_view file); /** * Initializes a 9-slice sprite with an sprite frame and with the specified @@ -251,7 +251,7 @@ class CC_GUI_DLL Scale9Sprite : public Sprite * @param capInsets The values to use for the cap insets. * @return True if initializes success, false otherwise. */ - virtual bool initWithSpriteFrameName(const std::string& spriteFrameName, const Rect& capInsets); + virtual bool initWithSpriteFrameName(std::string_view spriteFrameName, const Rect& capInsets); // override function @@ -268,7 +268,7 @@ class CC_GUI_DLL Scale9Sprite : public Sprite * texture's full rect. * @return True if initializes success, false otherwise. */ - virtual bool initWithFile(const std::string& file, const Rect& rect) override; + virtual bool initWithFile(std::string_view file, const Rect& rect) override; /** * Initializes a 9-slice sprite with a texture file. The whole texture will be @@ -280,7 +280,7 @@ class CC_GUI_DLL Scale9Sprite : public Sprite * @param file The name of the texture file. * @return True if initializes success, false otherwise. */ - virtual bool initWithFile(const std::string& file) override; + virtual bool initWithFile(std::string_view file) override; /** * Initializes a 9-slice sprite with an sprite frame name. @@ -291,7 +291,7 @@ class CC_GUI_DLL Scale9Sprite : public Sprite * @param spriteFrameName The sprite frame name. * @return True if initializes success, false otherwise. */ - virtual bool initWithSpriteFrameName(const std::string& spriteFrameName) override; + virtual bool initWithSpriteFrameName(std::string_view spriteFrameName) override; virtual bool init() override; diff --git a/cocos/ui/UIScrollView.cpp b/cocos/ui/UIScrollView.cpp index ae12b010d55a..b0df2ffd9ebc 100644 --- a/cocos/ui/UIScrollView.cpp +++ b/cocos/ui/UIScrollView.cpp @@ -287,7 +287,7 @@ void ScrollView::addChild(Node* child, int zOrder, int tag) _innerContainer->addChild(child, zOrder, tag); } -void ScrollView::addChild(Node* child, int zOrder, const std::string& name) +void ScrollView::addChild(Node* child, int zOrder, std::string_view name) { child->setGlobalZOrder(_globalZOrder); _innerContainer->addChild(child, zOrder, name); @@ -328,7 +328,7 @@ Node* ScrollView::getChildByTag(int tag) const return _innerContainer->getChildByTag(tag); } -Node* ScrollView::getChildByName(const std::string& name) const +Node* ScrollView::getChildByName(std::string_view name) const { return _innerContainer->getChildByName(name); } diff --git a/cocos/ui/UIScrollView.h b/cocos/ui/UIScrollView.h index 96d9949a77b6..c1cbe9ba8cba 100644 --- a/cocos/ui/UIScrollView.h +++ b/cocos/ui/UIScrollView.h @@ -343,7 +343,7 @@ class CC_GUI_DLL ScrollView : public Layout virtual void addChild(Node* child) override; virtual void addChild(Node* child, int localZOrder) override; virtual void addChild(Node* child, int localZOrder, int tag) override; - virtual void addChild(Node* child, int localZOrder, const std::string& name) override; + virtual void addChild(Node* child, int localZOrder, std::string_view name) override; virtual void removeAllChildren() override; virtual void removeAllChildrenWithCleanup(bool cleanup) override; virtual void removeChild(Node* child, bool cleanup = true) override; @@ -351,7 +351,7 @@ class CC_GUI_DLL ScrollView : public Layout virtual const Vector& getChildren() const override; virtual ssize_t getChildrenCount() const override; virtual Node* getChildByTag(int tag) const override; - virtual Node* getChildByName(const std::string& name) const override; + virtual Node* getChildByName(std::string_view name) const override; // touch event callback virtual bool onTouchBegan(Touch* touch, Event* unusedEvent) override; virtual void onTouchMoved(Touch* touch, Event* unusedEvent) override; diff --git a/cocos/ui/UISlider.cpp b/cocos/ui/UISlider.cpp index c28cfbbca51e..2baeabcf2726 100644 --- a/cocos/ui/UISlider.cpp +++ b/cocos/ui/UISlider.cpp @@ -103,9 +103,7 @@ Slider* Slider::create() return nullptr; } -Slider* Slider::create(const std::string& barTextureName, - const std::string& normalBallTextureName, - TextureResType resType) +Slider* Slider::create(std::string_view barTextureName, std::string_view normalBallTextureName, TextureResType resType) { Slider* widget = new Slider(); if (widget->init()) @@ -157,7 +155,7 @@ void Slider::initRenderer() addProtectedChild(_slidBallRenderer, SLIDBALL_RENDERER_Z, -1); } -void Slider::loadBarTexture(const std::string& fileName, TextureResType texType) +void Slider::loadBarTexture(std::string_view fileName, TextureResType texType) { _textureFile = fileName; _barTexType = texType; @@ -202,7 +200,7 @@ void Slider::setupBarTexture() _originalBarRect = _barRenderer->getTextureRect(); } -void Slider::loadProgressBarTexture(const std::string& fileName, TextureResType texType) +void Slider::loadProgressBarTexture(std::string_view fileName, TextureResType texType) { _progressBarTextureFile = fileName; _progressBarTexType = texType; @@ -330,9 +328,9 @@ const Rect& Slider::getCapInsetsProgressBarRenderer() const return _capInsetsProgressBarRenderer; } -void Slider::loadSlidBallTextures(const std::string& normal, - const std::string& pressed, - const std::string& disabled, +void Slider::loadSlidBallTextures(std::string_view normal, + std::string_view pressed, + std::string_view disabled, TextureResType texType) { loadSlidBallTextureNormal(normal, texType); @@ -340,7 +338,7 @@ void Slider::loadSlidBallTextures(const std::string& normal, loadSlidBallTextureDisabled(disabled, texType); } -void Slider::loadSlidBallTextureNormal(const std::string& normal, TextureResType texType) +void Slider::loadSlidBallTextureNormal(std::string_view normal, TextureResType texType) { _slidBallNormalTextureFile = normal; _ballNTexType = texType; @@ -370,7 +368,7 @@ void Slider::loadSlidBallTextureNormal(SpriteFrame* spriteframe) this->updateChildrenDisplayedRGBA(); } -void Slider::loadSlidBallTexturePressed(const std::string& pressed, TextureResType texType) +void Slider::loadSlidBallTexturePressed(std::string_view pressed, TextureResType texType) { _slidBallPressedTextureFile = pressed; _isSliderBallPressedTextureLoaded = !pressed.empty(); @@ -402,7 +400,7 @@ void Slider::loadSlidBallTexturePressed(SpriteFrame* spriteframe) this->updateChildrenDisplayedRGBA(); } -void Slider::loadSlidBallTextureDisabled(const std::string& disabled, TextureResType texType) +void Slider::loadSlidBallTextureDisabled(std::string_view disabled, TextureResType texType) { _slidBallDisabledTextureFile = disabled; _isSliderBallDisabledTexturedLoaded = !disabled.empty(); diff --git a/cocos/ui/UISlider.h b/cocos/ui/UISlider.h index b0b30ad0c94b..63a3e62bad56 100644 --- a/cocos/ui/UISlider.h +++ b/cocos/ui/UISlider.h @@ -98,8 +98,8 @@ class CC_GUI_DLL Slider : public Widget * @param resType Texture resource type. * @return An autoreleased Slider object. */ - static Slider* create(const std::string& barTextureName, - const std::string& normalBallTextureName, + static Slider* create(std::string_view barTextureName, + std::string_view normalBallTextureName, TextureResType resType = TextureResType::LOCAL); /** @@ -108,7 +108,7 @@ class CC_GUI_DLL Slider : public Widget * @param fileName File name of texture. * @param resType @see TextureResType . */ - void loadBarTexture(const std::string& fileName, TextureResType resType = TextureResType::LOCAL); + void loadBarTexture(std::string_view fileName, TextureResType resType = TextureResType::LOCAL); /** * Sets if slider is using scale9 renderer. @@ -162,10 +162,10 @@ class CC_GUI_DLL Slider : public Widget * @param disabled Disabled state texture. * @param texType @see TextureResType . */ - void loadSlidBallTextures(const std::string& normal, - const std::string& pressed = "", - const std::string& disabled = "", - TextureResType texType = TextureResType::LOCAL); + void loadSlidBallTextures(std::string_view normal, + std::string_view pressed = "", + std::string_view disabled = "", + TextureResType texType = TextureResType::LOCAL); /** * Load normal state texture for slider ball. @@ -173,7 +173,7 @@ class CC_GUI_DLL Slider : public Widget * @param normal Normal state texture. * @param resType @see TextureResType . */ - void loadSlidBallTextureNormal(const std::string& normal, TextureResType resType = TextureResType::LOCAL); + void loadSlidBallTextureNormal(std::string_view normal, TextureResType resType = TextureResType::LOCAL); /** * Load pressed state texture for slider ball. @@ -181,7 +181,7 @@ class CC_GUI_DLL Slider : public Widget * @param pressed Pressed state texture. * @param resType @see TextureResType . */ - void loadSlidBallTexturePressed(const std::string& pressed, TextureResType resType = TextureResType::LOCAL); + void loadSlidBallTexturePressed(std::string_view pressed, TextureResType resType = TextureResType::LOCAL); /** * Load disabled state texture for slider ball. @@ -189,7 +189,7 @@ class CC_GUI_DLL Slider : public Widget * @param disabled Disabled state texture. * @param resType @see TextureResType . */ - void loadSlidBallTextureDisabled(const std::string& disabled, TextureResType resType = TextureResType::LOCAL); + void loadSlidBallTextureDisabled(std::string_view disabled, TextureResType resType = TextureResType::LOCAL); /** * Load dark state texture for slider progress bar. @@ -197,7 +197,7 @@ class CC_GUI_DLL Slider : public Widget * @param fileName File path of texture. * @param resType @see TextureResType . */ - void loadProgressBarTexture(const std::string& fileName, TextureResType resType = TextureResType::LOCAL); + void loadProgressBarTexture(std::string_view fileName, TextureResType resType = TextureResType::LOCAL); /** * Changes the progress direction of slider. diff --git a/cocos/ui/UITabControl.cpp b/cocos/ui/UITabControl.cpp index 65c9b54f9aee..37e9c39614e5 100644 --- a/cocos/ui/UITabControl.cpp +++ b/cocos/ui/UITabControl.cpp @@ -487,9 +487,9 @@ TabHeader* TabHeader::create() return nullptr; } -TabHeader* TabHeader::create(const std::string& titleStr, - const std::string& backGround, - const std::string& cross, +TabHeader* TabHeader::create(std::string_view titleStr, + std::string_view backGround, + std::string_view cross, TextureResType texType) { TabHeader* tabcell = new TabHeader; @@ -505,12 +505,12 @@ TabHeader* TabHeader::create(const std::string& titleStr, return nullptr; } -TabHeader* TabHeader::create(const std::string& titleStr, - const std::string& backGround, - const std::string& backGroundSelected, - const std::string& cross, - const std::string& backGroundDisabled, - const std::string& frontCrossDisabled, +TabHeader* TabHeader::create(std::string_view titleStr, + std::string_view backGround, + std::string_view backGroundSelected, + std::string_view cross, + std::string_view backGroundDisabled, + std::string_view frontCrossDisabled, TextureResType texType /*= TextureResType::LOCAL*/) { TabHeader* tabcell = new TabHeader; @@ -543,7 +543,7 @@ void TabHeader::initRenderer() addProtectedChild(_tabLabelRender, -1, -1); } -void TabHeader::setTitleText(const std::string& text) +void TabHeader::setTitleText(std::string_view text) { if (text == getTitleText()) { @@ -555,11 +555,11 @@ void TabHeader::setTitleText(const std::string& text) _tabLabelRender->setPosition(_contentSize * 0.5f); } -std::string TabHeader::getTitleText() const +std::string_view TabHeader::getTitleText() const { if (nullptr == _tabLabelRender) { - return ""; + return ""sv; } return _tabLabelRender->getString(); } @@ -609,11 +609,11 @@ void TabHeader::updateContentSize() onSizeChanged(); } -void TabHeader::setTitleFontName(const std::string& fontName) +void TabHeader::setTitleFontName(std::string_view fontName) { if (FileUtils::getInstance()->isFileExist(fontName)) { - std::string lowerCasedFontName = fontName; + std::string lowerCasedFontName{fontName}; std::transform(lowerCasedFontName.begin(), lowerCasedFontName.end(), lowerCasedFontName.begin(), ::tolower); if (lowerCasedFontName.find(".fnt") != std::string::npos) { @@ -647,7 +647,7 @@ Label* TabHeader::getTitleRenderer() const return _tabLabelRender; } -std::string TabHeader::getTitleFontName() const +std::string_view TabHeader::getTitleFontName() const { if (this->_fontType == FontType::SYSTEM) { @@ -661,7 +661,7 @@ std::string TabHeader::getTitleFontName() const { return _tabLabelRender->getBMFontFilePath(); } - return ""; + return ""sv; } void TabHeader::onSizeChanged() diff --git a/cocos/ui/UITabControl.h b/cocos/ui/UITabControl.h index 7da800751dea..98765bdde408 100644 --- a/cocos/ui/UITabControl.h +++ b/cocos/ui/UITabControl.h @@ -70,9 +70,9 @@ class CC_GUI_DLL TabHeader : public AbstractCheckButton * @param texType The texture's resource type in `Widget::TextureResType`. * @return A TabHeader instance pointer */ - static TabHeader* create(const std::string& titleStr, - const std::string& backGround, - const std::string& cross, + static TabHeader* create(std::string_view titleStr, + std::string_view backGround, + std::string_view cross, TextureResType texType = TextureResType::LOCAL); /** @@ -87,12 +87,12 @@ class CC_GUI_DLL TabHeader : public AbstractCheckButton * * @return A TabHeader instance pointer. */ - static TabHeader* create(const std::string& titleStr, - const std::string& backGround, - const std::string& backGroundSelected, - const std::string& cross, - const std::string& backGroundDisabled, - const std::string& frontCrossDisabled, + static TabHeader* create(std::string_view titleStr, + std::string_view backGround, + std::string_view backGroundSelected, + std::string_view cross, + std::string_view backGroundDisabled, + std::string_view frontCrossDisabled, TextureResType texType = TextureResType::LOCAL); /** * Return the inner Label renderer of TabHeader. @@ -104,13 +104,13 @@ class CC_GUI_DLL TabHeader : public AbstractCheckButton * Change the content of Header's text. *@param text The Header's text. */ - void setTitleText(const std::string& text); + void setTitleText(std::string_view text); /** * get the TabHeader text *@return he TabHeader text */ - std::string getTitleText() const; + std::string_view getTitleText() const; /** * Change the color of he TabHeader text @@ -140,13 +140,13 @@ class CC_GUI_DLL TabHeader : public AbstractCheckButton * Change the font name of TabHeader text *@param fontName a font name string. */ - void setTitleFontName(const std::string& fontName); + void setTitleFontName(std::string_view fontName); /** * get the font name of TabHeader text *@return font name in std::string */ - std::string getTitleFontName() const; + std::string_view getTitleFontName() const; /** * get the index this header in the TabControl diff --git a/cocos/ui/UIText.cpp b/cocos/ui/UIText.cpp index db2457e21610..554e02429263 100644 --- a/cocos/ui/UIText.cpp +++ b/cocos/ui/UIText.cpp @@ -71,7 +71,7 @@ bool Text::init() return false; } -Text* Text::create(const std::string& textContent, const std::string& fontName, float fontSize) +Text* Text::create(std::string_view textContent, std::string_view fontName, float fontSize) { Text* text = new Text(); if (text->init(textContent, fontName, fontSize)) @@ -83,7 +83,7 @@ Text* Text::create(const std::string& textContent, const std::string& fontName, return nullptr; } -bool Text::init(const std::string& textContent, const std::string& fontName, float fontSize) +bool Text::init(std::string_view textContent, std::string_view fontName, float fontSize) { bool ret = true; do @@ -117,7 +117,7 @@ void Text::setString(std::string_view text) _labelRendererAdaptDirty = true; } -const std::string& Text::getString() const +std::string_view Text::getString() const { return _labelRenderer->getString(); } @@ -149,7 +149,7 @@ float Text::getFontSize() const return _fontSize; } -void Text::setFontName(const std::string& name) +void Text::setFontName(std::string_view name) { if (FileUtils::getInstance()->isFileExist(name)) { @@ -173,7 +173,7 @@ void Text::setFontName(const std::string& name) _labelRendererAdaptDirty = true; } -const std::string& Text::getFontName() const +std::string_view Text::getFontName() const { return _fontName; } diff --git a/cocos/ui/UIText.h b/cocos/ui/UIText.h index 39721ef6973b..10b980a381d4 100644 --- a/cocos/ui/UIText.h +++ b/cocos/ui/UIText.h @@ -96,7 +96,7 @@ class CC_GUI_DLL Text : public Widget, public cocos2d::BlendProtocol * @param fontSize A given font size. * @return An autoreleased Text object. */ - static Text* create(const std::string& textContent, const std::string& fontName, float fontSize); + static Text* create(std::string_view textContent, std::string_view fontName, float fontSize); /** * Changes the string value of label. @@ -110,7 +110,7 @@ class CC_GUI_DLL Text : public Widget, public cocos2d::BlendProtocol * * @return String value. */ - const std::string& getString() const; + std::string_view getString() const; /** * Gets the string length of the label. @@ -151,13 +151,13 @@ class CC_GUI_DLL Text : public Widget, public cocos2d::BlendProtocol * @endcode * @param name Font name. */ - void setFontName(const std::string& name); + void setFontName(std::string_view name); /** Gets the font name. * * @return Font name. */ - const std::string& getFontName() const; + std::string_view getFontName() const; /** Gets the font type. * @return The font type. @@ -342,7 +342,7 @@ class CC_GUI_DLL Text : public Widget, public cocos2d::BlendProtocol virtual const BlendFunc& getBlendFunc() const override; CC_CONSTRUCTOR_ACCESS : virtual bool init() override; - virtual bool init(const std::string& textContent, const std::string& fontName, float fontSize); + virtual bool init(std::string_view textContent, std::string_view fontName, float fontSize); protected: virtual void initRenderer() override; diff --git a/cocos/ui/UITextAtlas.cpp b/cocos/ui/UITextAtlas.cpp index 98eb85c0e801..e6ab8300fedd 100644 --- a/cocos/ui/UITextAtlas.cpp +++ b/cocos/ui/UITextAtlas.cpp @@ -66,11 +66,11 @@ void TextAtlas::initRenderer() addProtectedChild(_labelAtlasRenderer, LABELATLAS_RENDERER_Z, -1); } -TextAtlas* TextAtlas::create(const std::string& stringValue, - const std::string& charMapFile, +TextAtlas* TextAtlas::create(std::string_view stringValue, + std::string_view charMapFile, int itemWidth, int itemHeight, - const std::string& startCharMap) + std::string_view startCharMap) { TextAtlas* widget = new TextAtlas(); if (widget->init()) @@ -83,11 +83,11 @@ TextAtlas* TextAtlas::create(const std::string& stringValue, return nullptr; } -void TextAtlas::setProperty(const std::string& stringValue, - const std::string& charMapFile, +void TextAtlas::setProperty(std::string_view stringValue, + std::string_view charMapFile, int itemWidth, int itemHeight, - const std::string& startCharMap) + std::string_view startCharMap) { _stringValue = stringValue; _charMapFileName = charMapFile; @@ -116,7 +116,7 @@ void TextAtlas::setString(std::string_view value) // CCLOG("cssss w %f, h %f", _contentSize.width, _contentSize.height); } -const std::string& TextAtlas::getString() const +std::string_view TextAtlas::getString() const { return _labelAtlasRenderer->getString(); } diff --git a/cocos/ui/UITextAtlas.h b/cocos/ui/UITextAtlas.h index f84739ada084..25b9817f570c 100644 --- a/cocos/ui/UITextAtlas.h +++ b/cocos/ui/UITextAtlas.h @@ -82,11 +82,11 @@ class CC_GUI_DLL TextAtlas : public Widget * @param startCharMap The starting char of the atlas. * @return An autoreleased TextAtlas object. */ - static TextAtlas* create(const std::string& stringValue, - const std::string& charMapFile, + static TextAtlas* create(std::string_view stringValue, + std::string_view charMapFile, int itemWidth, int itemHeight, - const std::string& startCharMap); + std::string_view startCharMap); /** 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. @@ -98,11 +98,11 @@ class CC_GUI_DLL TextAtlas : public Widget * @param startCharMap The starting char of the atlas. */ - void setProperty(const std::string& stringValue, - const std::string& charMapFile, + void setProperty(std::string_view stringValue, + std::string_view charMapFile, int itemWidth, int itemHeight, - const std::string& startCharMap); + std::string_view startCharMap); /**Set string value for labelatlas. * @@ -114,7 +114,7 @@ class CC_GUI_DLL TextAtlas : public Widget * * @return The string value of TextAtlas. */ - const std::string& getString() const; + std::string_view getString() const; /** * Gets the string length of the label. diff --git a/cocos/ui/UITextBMFont.cpp b/cocos/ui/UITextBMFont.cpp index 125f921598cc..28de90891b2e 100644 --- a/cocos/ui/UITextBMFont.cpp +++ b/cocos/ui/UITextBMFont.cpp @@ -53,7 +53,7 @@ TextBMFont* TextBMFont::create() return nullptr; } -TextBMFont* TextBMFont::create(const std::string& text, const std::string& filename) +TextBMFont* TextBMFont::create(std::string_view text, std::string_view filename) { TextBMFont* widget = new TextBMFont(); if (widget->init()) @@ -73,7 +73,7 @@ void TextBMFont::initRenderer() addProtectedChild(_labelBMFontRenderer, LABELBMFONT_RENDERER_Z, -1); } -void TextBMFont::setFntFile(const std::string& fileName) +void TextBMFont::setFntFile(std::string_view fileName) { if (fileName.empty()) { @@ -86,7 +86,7 @@ void TextBMFont::setFntFile(const std::string& fileName) _labelBMFontRendererAdaptDirty = true; } -void TextBMFont::setString(const std::string& value) +void TextBMFont::setString(std::string_view value) { if (value == _labelBMFontRenderer->getString()) { @@ -98,7 +98,7 @@ void TextBMFont::setString(const std::string& value) _labelBMFontRendererAdaptDirty = true; } -const std::string& TextBMFont::getString() const +std::string_view TextBMFont::getString() const { return _stringValue; } diff --git a/cocos/ui/UITextBMFont.h b/cocos/ui/UITextBMFont.h index 70fb5564d1fd..eb3f16fc6756 100644 --- a/cocos/ui/UITextBMFont.h +++ b/cocos/ui/UITextBMFont.h @@ -69,16 +69,16 @@ class CC_GUI_DLL TextBMFont : public Widget */ static TextBMFont* create(); - static TextBMFont* create(const std::string& text, const std::string& filename); + static TextBMFont* create(std::string_view text, std::string_view filename); /** init a bitmap font atlas with an initial string and the FNT file */ - void setFntFile(const std::string& fileName); + void setFntFile(std::string_view fileName); /** set string value for labelbmfont*/ - void setString(const std::string& value); + void setString(std::string_view value); /** get string value for labelbmfont*/ - const std::string& getString() const; + std::string_view getString() const; /** * Gets the string length of the label. diff --git a/cocos/ui/UITextField.cpp b/cocos/ui/UITextField.cpp index 25b75a61e23b..8e16b2a83a8a 100644 --- a/cocos/ui/UITextField.cpp +++ b/cocos/ui/UITextField.cpp @@ -52,7 +52,7 @@ UICCTextField::UICCTextField() UICCTextField::~UICCTextField() {} -UICCTextField* UICCTextField::create(const std::string& placeholder, const std::string& fontName, float fontSize) +UICCTextField* UICCTextField::create(std::string_view placeholder, std::string_view fontName, float fontSize) { UICCTextField* pRet = new UICCTextField(); @@ -191,12 +191,12 @@ bool UICCTextField::isPasswordEnabled() const return this->isSecureTextEntry(); } -void UICCTextField::setPasswordStyleText(const std::string& styleText) +void UICCTextField::setPasswordStyleText(std::string_view styleText) { this->setPasswordTextStyle(styleText); } -void UICCTextField::setPasswordText(const std::string& text) +void UICCTextField::setPasswordText(std::string_view text) { std::string tempStr = ""; int32_t text_count = StringUtils::getCharacterCountInUTF8String(text); @@ -292,7 +292,7 @@ TextField* TextField::create() return nullptr; } -TextField* TextField::create(const std::string& placeholder, const std::string& fontName, int fontSize) +TextField* TextField::create(std::string_view placeholder, std::string_view fontName, int fontSize) { TextField* widget = new TextField(); if (widget->init()) @@ -358,7 +358,7 @@ Vec2 TextField::getTouchSize() const return Vec2(_touchWidth, _touchHeight); } -void TextField::setString(const std::string& text) +void TextField::setString(std::string_view text) { std::string strText(text); @@ -386,14 +386,14 @@ void TextField::setString(const std::string& text) updateContentSizeWithTextureSize(_textFieldRenderer->getContentSize()); } -void TextField::setPlaceHolder(const std::string& value) +void TextField::setPlaceHolder(std::string_view value) { _textFieldRenderer->setPlaceHolder(value); _textFieldRendererAdaptDirty = true; updateContentSizeWithTextureSize(_textFieldRenderer->getContentSize()); } -const std::string& TextField::getPlaceHolder() const +std::string_view TextField::getPlaceHolder() const { return _textFieldRenderer->getPlaceHolder(); } @@ -449,11 +449,11 @@ int TextField::getFontSize() const return _fontSize; } -void TextField::setFontName(const std::string& name) +void TextField::setFontName(std::string_view name) { if (FileUtils::getInstance()->isFileExist(name)) { - std::string lcName = name; + std::string lcName{name}; std::transform(lcName.begin(), lcName.end(), lcName.begin(), ::tolower); if (lcName.substr(lcName.length() - 4) == ".fnt") { @@ -483,7 +483,7 @@ void TextField::setFontName(const std::string& name) updateContentSizeWithTextureSize(_textFieldRenderer->getContentSize()); } -const std::string& TextField::getFontName() const +std::string_view TextField::getFontName() const { return _fontName; } @@ -493,7 +493,7 @@ void TextField::didNotSelectSelf() _textFieldRenderer->detachWithIME(); } -const std::string& TextField::getString() const +std::string_view TextField::getString() const { return _textFieldRenderer->getString(); } @@ -563,7 +563,7 @@ void TextField::setPasswordStyleText(const char* styleText) const char* TextField::getPasswordStyleText() const { - return _textFieldRenderer->getPasswordTextStyle().c_str(); + return _textFieldRenderer->getPasswordTextStyle().data(); } void TextField::update(float /*dt*/) diff --git a/cocos/ui/UITextField.h b/cocos/ui/UITextField.h index 2e9c8a8362fc..c39bcc410b6d 100644 --- a/cocos/ui/UITextField.h +++ b/cocos/ui/UITextField.h @@ -74,7 +74,7 @@ class CC_GUI_DLL UICCTextField : public TextFieldTTF, public TextFieldDelegate *@param fontSize Font size in float. *@return A UICCTextField instance. */ - static UICCTextField* create(const std::string& placeholder, const std::string& fontName, float fontSize); + static UICCTextField* create(std::string_view placeholder, std::string_view fontName, float fontSize); // override functions virtual bool onTextFieldAttachWithIME(TextFieldTTF* pSender) override; @@ -142,14 +142,14 @@ class CC_GUI_DLL UICCTextField : public TextFieldTTF, public TextFieldDelegate * * @param styleText The styleText for password mask, the default value is "*". */ - void setPasswordStyleText(const std::string& styleText); + void setPasswordStyleText(std::string_view styleText); /** * @brief Set the password text content. * * @param text The content of password. */ - void setPasswordText(const std::string& text); + void setPasswordText(std::string_view text); /** * @brief Toggle attach with IME. @@ -270,7 +270,7 @@ class CC_GUI_DLL TextField : public Widget * @param fontSize The font size. * @return A TextField instance. */ - static TextField* create(const std::string& placeholder, const std::string& fontName, int fontSize); + static TextField* create(std::string_view placeholder, std::string_view fontName, int fontSize); /** * @brief Set the touch size @@ -300,14 +300,14 @@ class CC_GUI_DLL TextField : public Widget * * @param value The string value of placeholder. */ - void setPlaceHolder(const std::string& value); + void setPlaceHolder(std::string_view value); /** * @brief Get the placeholder of TextField. * * @return A placeholder string. */ - const std::string& getPlaceHolder() const; + std::string_view getPlaceHolder() const; /** * @brief Query the placeholder string color. @@ -363,14 +363,14 @@ class CC_GUI_DLL TextField : public Widget * * @param name The font name string. */ - void setFontName(const std::string& name); + void setFontName(std::string_view name); /** * @brief Query the TextField's font name. * * @return The font name string. */ - const std::string& getFontName() const; + std::string_view getFontName() const; /** * @brief Detach the IME. @@ -381,13 +381,13 @@ class CC_GUI_DLL TextField : public Widget *Change content of TextField. *@param text A string content. */ - void setString(const std::string& text); + void setString(std::string_view text); /** *Query the content of TextField. *@return The string value of TextField. */ - const std::string& getString() const; + std::string_view getString() const; virtual bool onTouchBegan(Touch* touch, Event* unusedEvent) override; diff --git a/cocos/ui/UITextFieldEx.cpp b/cocos/ui/UITextFieldEx.cpp index 90e45b4a2854..a14258c1b8c3 100644 --- a/cocos/ui/UITextFieldEx.cpp +++ b/cocos/ui/UITextFieldEx.cpp @@ -28,8 +28,8 @@ NS_CC_BEGIN # define nxbeep(t) #endif -static Label* createLabel(const std::string& text, - const std::string& font, +static Label* createLabel(std::string_view text, + std::string_view font, float fontSize, const Vec2& dimensions = Vec2::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT, @@ -161,7 +161,7 @@ static int _truncateUTF8String(const char* text, int limit, int& nb) return n; } -static void internalSetLableFont(Label* l, const std::string& fontName, float fontSize) +static void internalSetLableFont(Label* l, std::string_view fontName, float fontSize) { if (FileUtils::getInstance()->isFileExist(fontName)) { @@ -178,7 +178,7 @@ static void internalSetLableFont(Label* l, const std::string& fontName, float fo } } -static float internalCalcStringWidth(std::string_view s, const std::string& fontName, float fontSize) +static float internalCalcStringWidth(std::string_view s, std::string_view fontName, float fontSize) { auto label = createLabel(std::string{s}, fontName, fontSize); return label->getContentSize().width; @@ -269,8 +269,8 @@ TextFieldEx::~TextFieldEx() ////////////////////////////////////////////////////////////////////////// // static constructor ////////////////////////////////////////////////////////////////////////// -TextFieldEx* TextFieldEx::create(const std::string& placeholder, - const std::string& fontName, +TextFieldEx* TextFieldEx::create(std::string_view placeholder, + std::string_view fontName, float fontSize, float cursorWidth, const Color4B& cursorColor) @@ -292,8 +292,8 @@ TextFieldEx* TextFieldEx::create(const std::string& placeholder, ////////////////////////////////////////////////////////////////////////// // initialize ////////////////////////////////////////////////////////////////////////// -bool TextFieldEx::initWithPlaceHolder(const std::string& placeholder, - const std::string& fontName, +bool TextFieldEx::initWithPlaceHolder(std::string_view placeholder, + std::string_view fontName, float fontSize, float cursorWidth, const Color4B& cursorColor) @@ -316,12 +316,12 @@ bool TextFieldEx::initWithPlaceHolder(const std::string& placeholder, return true; } -const std::string& TextFieldEx::getTextFontName() const +std::string_view TextFieldEx::getTextFontName() const { return this->fontName; } -void TextFieldEx::setTextFontName(const std::string& fontName) +void TextFieldEx::setTextFontName(std::string_view fontName) { if (FileUtils::getInstance()->isFileExist(fontName)) { @@ -740,7 +740,7 @@ void TextFieldEx::handleDeleteKeyEvent() this->onTextModify(); } -const std::string& TextFieldEx::getContentText() +std::string_view TextFieldEx::getContentText() { return inputText; } @@ -784,7 +784,7 @@ void TextFieldEx::setPlaceholderColor(const Color4B& color) ////////////////////////////////////////////////////////////////////////// // input text property -void TextFieldEx::setString(const std::string& text) +void TextFieldEx::setString(std::string_view text) { static char bulletString[] = {(char)0xe2, (char)0x80, (char)0xa2, (char)0x00}; @@ -838,13 +838,13 @@ void TextFieldEx::updateContentSize(void) this->setContentSize(renderLabel->getContentSize()); } -const std::string& TextFieldEx::getString() const +std::string_view TextFieldEx::getString() const { return inputText; } // place holder text property -void TextFieldEx::setPlaceholderText(const std::string& text) +void TextFieldEx::setPlaceholderText(std::string_view text) { placeHolder = text; if (inputText.empty()) @@ -854,7 +854,7 @@ void TextFieldEx::setPlaceholderText(const std::string& text) } } -const std::string& TextFieldEx::getPlaceholderText() const +std::string_view TextFieldEx::getPlaceholderText() const { return placeHolder; } diff --git a/cocos/ui/UITextFieldEx.h b/cocos/ui/UITextFieldEx.h index b94a7c7a2b65..a337388c0f94 100644 --- a/cocos/ui/UITextFieldEx.h +++ b/cocos/ui/UITextFieldEx.h @@ -29,14 +29,14 @@ class CC_DLL TextFieldEx : public cocos2d::Node, public IMEDelegate */ virtual ~TextFieldEx(); - static TextFieldEx* create(const std::string& placeholder, - const std::string& fontName, + static TextFieldEx* create(std::string_view placeholder, + std::string_view fontName, float fontSize, float cursorWidth = 2, const Color4B& color = Color4B::WHITE); - bool initWithPlaceHolder(const std::string& placeholder, - const std::string& fontName, + bool initWithPlaceHolder(std::string_view placeholder, + std::string_view fontName, float fontSize, float cursorWidth = 2, const Color4B& color = Color4B::WHITE); @@ -58,8 +58,8 @@ class CC_DLL TextFieldEx : public cocos2d::Node, public IMEDelegate const Color3B& getCursorColor(void) const; // input text property - virtual void setString(const std::string& text); - virtual const std::string& getString() const; + virtual void setString(std::string_view text); + virtual std::string_view getString() const; // Continuous touch event trigger support. void setContinuousTouchDelayTime(float delay) { _continuousTouchDelayTime = delay; } @@ -71,8 +71,8 @@ class CC_DLL TextFieldEx : public cocos2d::Node, public IMEDelegate // place holder text property // place holder text displayed when there is no text in the text field. - virtual void setPlaceholderText(const std::string& text); - virtual const std::string& getPlaceholderText(void) const; + virtual void setPlaceholderText(std::string_view text); + virtual std::string_view getPlaceholderText(void) const; virtual void setPasswordEnabled(bool value); virtual bool isPasswordEnabled() const; @@ -97,8 +97,8 @@ class CC_DLL TextFieldEx : public cocos2d::Node, public IMEDelegate /// fonts void setTextFontSize(float size); float getTextFontSize() const; - void setTextFontName(const std::string& fontName); - const std::string& getTextFontName() const; + void setTextFontName(std::string_view fontName); + std::string_view getTextFontName() const; CC_SYNTHESIZE(size_t, charLimit, CharLimit); @@ -122,7 +122,7 @@ class CC_DLL TextFieldEx : public cocos2d::Node, public IMEDelegate virtual bool canDetachWithIME() override; virtual void deleteBackward() override; - virtual const std::string& getContentText() override; + virtual std::string_view getContentText() override; void handleDeleteKeyEvent(); diff --git a/cocos/ui/UIVideoPlayer-android.cpp b/cocos/ui/UIVideoPlayer-android.cpp index dab2aafc7be2..0f61d490fc31 100644 --- a/cocos/ui/UIVideoPlayer-android.cpp +++ b/cocos/ui/UIVideoPlayer-android.cpp @@ -38,7 +38,7 @@ //----------------------------------------------------------------------------------------------------------- -static const std::string videoHelperClassName = "org.cocos2dx.lib.Cocos2dxVideoHelper"; +static const char* videoHelperClassName = "org.cocos2dx.lib.Cocos2dxVideoHelper"; USING_NS_CC; @@ -60,7 +60,7 @@ int createVideoWidgetJNI() { JniMethodInfo t; int ret = -1; - if (JniHelper::getStaticMethodInfo(t, videoHelperClassName.c_str(), "createVideoWidget", "()I")) + if (JniHelper::getStaticMethodInfo(t, videoHelperClassName, "createVideoWidget", "()I")) { ret = t.env->CallStaticIntMethod(t.classID, t.methodID); @@ -73,7 +73,7 @@ int createVideoWidgetJNI() void setLoopingJNI(int index, bool looping) { JniMethodInfo t; - if (JniHelper::getStaticMethodInfo(t, videoHelperClassName.c_str(), "setLooping", "(IZ)V")) + if (JniHelper::getStaticMethodInfo(t, videoHelperClassName, "setLooping", "(IZ)V")) { t.env->CallStaticVoidMethod(t.classID, t.methodID, index, looping); @@ -84,7 +84,7 @@ void setLoopingJNI(int index, bool looping) void setUserInputEnabledJNI(int index, bool enableInput) { JniMethodInfo t; - if (JniHelper::getStaticMethodInfo(t, videoHelperClassName.c_str(), "setUserInputEnabled", "(IZ)V")) + if (JniHelper::getStaticMethodInfo(t, videoHelperClassName, "setUserInputEnabled", "(IZ)V")) { t.env->CallStaticVoidMethod(t.classID, t.methodID, index, enableInput); @@ -124,7 +124,7 @@ VideoPlayer::~VideoPlayer() JniHelper::callStaticVoidMethod(videoHelperClassName, "removeVideoWidget", _videoPlayerIndex); } -void VideoPlayer::setFileName(const std::string& fileName) +void VideoPlayer::setFileName(std::string_view fileName) { _videoURL = FileUtils::getInstance()->fullPathForFilename(fileName); _videoSource = VideoPlayer::Source::FILENAME; @@ -132,7 +132,7 @@ void VideoPlayer::setFileName(const std::string& fileName) _videoURL); } -void VideoPlayer::setURL(const std::string& videoUrl) +void VideoPlayer::setURL(std::string_view videoUrl) { _videoURL = videoUrl; _videoSource = VideoPlayer::Source::URL; diff --git a/cocos/ui/UIVideoPlayer-ios.mm b/cocos/ui/UIVideoPlayer-ios.mm index f41d63a57f75..c1494ed51161 100644 --- a/cocos/ui/UIVideoPlayer-ios.mm +++ b/cocos/ui/UIVideoPlayer-ios.mm @@ -31,11 +31,11 @@ of this software and associated documentation files (the "Software"), to deal using namespace cocos2d::ui; //------------------------------------------------------------------------------------- -#include "platform/ios/CCEAGLView-ios.h" -#import -#import -#include "base/CCDirector.h" -#include "platform/CCFileUtils.h" +# include "platform/ios/CCEAGLView-ios.h" +# import +# import +# include "base/CCDirector.h" +# include "platform/CCFileUtils.h" @interface UIVideoViewWrapperIos : NSObject @@ -47,31 +47,29 @@ typedef NS_ENUM(NSInteger, PlayerbackState) { PlayerbackStateCompleted }; -@property (assign, nonatomic) AVPlayerViewController * playerController; - -- (void) setFrame:(int) left :(int) top :(int) width :(int) height; -- (void) setURL:(int) videoSource :(std::string&) videoUrl; -- (void) play; -- (void) pause; -- (void) resume; -- (void) stop; -- (void) seekTo:(float) sec; -- (void) setVisible:(BOOL) visible; -- (void) setKeepRatioEnabled:(BOOL) enabled; -- (void) setFullScreenEnabled:(BOOL) enabled; -- (BOOL) isFullScreenEnabled; -- (void) showPlaybackControls:(BOOL) value; -- (void) setRepeatEnabled:(BOOL)enabled; -- (void) setUserInteractionEnabled:(BOOL)userInteractionEnabled; - - --(id) init:(void*) videoPlayer; --(void) videoFinished:(NSNotification*) notification; +@property(assign, nonatomic) AVPlayerViewController* playerController; + +- (void)setFrame:(int)left:(int)top:(int)width:(int)height; +- (void)setURL:(int)videoSource:(std::string&)videoUrl; +- (void)play; +- (void)pause; +- (void)resume; +- (void)stop; +- (void)seekTo:(float)sec; +- (void)setVisible:(BOOL)visible; +- (void)setKeepRatioEnabled:(BOOL)enabled; +- (void)setFullScreenEnabled:(BOOL)enabled; +- (BOOL)isFullScreenEnabled; +- (void)showPlaybackControls:(BOOL)value; +- (void)setRepeatEnabled:(BOOL)enabled; +- (void)setUserInteractionEnabled:(BOOL)userInteractionEnabled; + +- (id)init:(void*)videoPlayer; +- (void)videoFinished:(NSNotification*)notification; @end -@implementation UIVideoViewWrapperIos -{ +@implementation UIVideoViewWrapperIos { int _left; int _top; int _width; @@ -84,24 +82,25 @@ @implementation UIVideoViewWrapperIos VideoPlayer* _videoPlayer; } --(id)init:(void*)videoPlayer +- (id)init:(void*)videoPlayer { - if (self = [super init]) { + if (self = [super init]) + { self.playerController = [AVPlayerViewController new]; [self setRepeatEnabled:FALSE]; [self showPlaybackControls:TRUE]; [self setUserInteractionEnabled:TRUE]; [self setKeepRatioEnabled:FALSE]; - + _videoPlayer = (VideoPlayer*)videoPlayer; - _state = PlayerbackStateUnknown; + _state = PlayerbackStateUnknown; } return self; } --(void) dealloc +- (void)dealloc { _videoPlayer = nullptr; [self clean]; @@ -109,44 +108,44 @@ -(void) dealloc [super dealloc]; } --(void) clean +- (void)clean { [self stop]; [self removePlayerEventListener]; [self.playerController.view removeFromSuperview]; } --(void) setFrame:(int)left :(int)top :(int)width :(int)height +- (void)setFrame:(int)left:(int)top:(int)width:(int)height { - _left = left; - _width = width; - _top = top; + _left = left; + _width = width; + _top = top; _height = height; [self.playerController.view setFrame:CGRectMake(left, top, width, height)]; } --(void) setFullScreenEnabled:(BOOL) enabled +- (void)setFullScreenEnabled:(BOOL)enabled { // AVPlayerViewController doesn't provide API to enable fullscreen. But you can toggle // fullsreen by the playback controllers. } --(BOOL) isFullScreenEnabled +- (BOOL)isFullScreenEnabled { return false; } - --(void) showPlaybackControls:(BOOL)value +- (void)showPlaybackControls:(BOOL)value { - _showPlaybackControls = value; + _showPlaybackControls = value; self.playerController.showsPlaybackControls = value; } --(void) setRepeatEnabled:(BOOL)enabled +- (void)setRepeatEnabled:(BOOL)enabled { _repeatEnabled = enabled; - if (self.playerController.player) { + if (self.playerController.player) + { if (_repeatEnabled) self.playerController.player.actionAtItemEnd = AVPlayerActionAtItemEndNone; else @@ -154,57 +153,61 @@ -(void) setRepeatEnabled:(BOOL)enabled } } --(void) setUserInteractionEnabled:(BOOL)userInteractionEnabled +- (void)setUserInteractionEnabled:(BOOL)userInteractionEnabled { - _userInteractionEnabled = userInteractionEnabled; + _userInteractionEnabled = userInteractionEnabled; self.playerController.view.userInteractionEnabled = _userInteractionEnabled; } --(void) setURL:(int)videoSource :(std::string &)videoUrl +- (void)setURL:(int)videoSource:(std::string&)videoUrl { [self clean]; if (videoSource == 1) - self.playerController.player = [[[AVPlayer alloc] initWithURL:[NSURL URLWithString:@(videoUrl.c_str())]] autorelease]; + self.playerController.player = + [[[AVPlayer alloc] initWithURL:[NSURL URLWithString:@(videoUrl.c_str())]] autorelease]; else - self.playerController.player = [[[AVPlayer alloc] initWithURL:[NSURL fileURLWithPath:@(videoUrl.c_str())]] autorelease]; + self.playerController.player = + [[[AVPlayer alloc] initWithURL:[NSURL fileURLWithPath:@(videoUrl.c_str())]] autorelease]; [self setRepeatEnabled:_repeatEnabled]; [self setKeepRatioEnabled:_keepRatioEnabled]; [self setUserInteractionEnabled:_userInteractionEnabled]; [self showPlaybackControls:_showPlaybackControls]; - auto view = cocos2d::Director::getInstance()->getOpenGLView(); - auto eaglview = (CCEAGLView *) view->getEAGLView(); + auto view = cocos2d::Director::getInstance()->getOpenGLView(); + auto eaglview = (CCEAGLView*)view->getEAGLView(); [eaglview addSubview:self.playerController.view]; [self registerPlayerEventListener]; } --(void) videoFinished:(NSNotification *)notification +- (void)videoFinished:(NSNotification*)notification { - if(_videoPlayer != nullptr) { + if (_videoPlayer != nullptr) + { _videoPlayer->onPlayEvent((int)VideoPlayer::EventType::COMPLETED); _state = PlayerbackStateCompleted; - if (_repeatEnabled) { + if (_repeatEnabled) + { [self seekTo:0]; [self play]; } } } --(void) seekTo:(float)sec +- (void)seekTo:(float)sec { if (self.playerController.player) [self.playerController.player seekToTime:CMTimeMake(sec, 1)]; } --(void) setVisible:(BOOL)visible +- (void)setVisible:(BOOL)visible { [self.playerController.view setHidden:!visible]; } --(void) setKeepRatioEnabled:(BOOL)enabled +- (void)setKeepRatioEnabled:(BOOL)enabled { _keepRatioEnabled = enabled; if (_keepRatioEnabled) @@ -213,38 +216,41 @@ -(void) setKeepRatioEnabled:(BOOL)enabled self.playerController.videoGravity = AVLayerVideoGravityResizeAspectFill; } --(void) play +- (void)play { - if (self.playerController.player && _state != PlayerbackStatePlaying) { + if (self.playerController.player && _state != PlayerbackStatePlaying) + { [self.playerController.player play]; _state = PlayerbackStatePlaying; _videoPlayer->onPlayEvent((int)VideoPlayer::EventType::PLAYING); } } --(void) pause +- (void)pause { - if (self.playerController.player && _state == PlayerbackStatePlaying) { + if (self.playerController.player && _state == PlayerbackStatePlaying) + { [self.playerController.player pause]; _state = PlayerbackStatePaused; _videoPlayer->onPlayEvent((int)VideoPlayer::EventType::PAUSED); } } --(void) resume +- (void)resume { if (self.playerController.player && _state == PlayerbackStatePaused) [self play]; } --(void) stop +- (void)stop { // AVPlayer doesn't have stop, so just pause it, and seek time to 0. - if (self.playerController.player && _state != PlayerbackStopped) { + if (self.playerController.player && _state != PlayerbackStopped) + { [self seekTo:0]; [self.playerController.player pause]; _state = PlayerbackStopped; - + // stop() will be invoked in dealloc, which is invoked by _videoPlayer's destructor, // so do't send the message when _videoPlayer is being deleted. if (_videoPlayer) @@ -252,21 +258,21 @@ -(void) stop } } --(void) registerPlayerEventListener +- (void)registerPlayerEventListener { if (self.playerController.player) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoFinished:) - name:AVPlayerItemDidPlayToEndTimeNotification - object:self.playerController.player.currentItem]; + name:AVPlayerItemDidPlayToEndTimeNotification + object:self.playerController.player.currentItem]; } --(void) removePlayerEventListener +- (void)removePlayerEventListener { if (self.playerController.player) [[NSNotificationCenter defaultCenter] removeObserver:self - name:AVPlayerItemDidPlayToEndTimeNotification - object:self.playerController.player.currentItem]; + name:AVPlayerItemDidPlayToEndTimeNotification + object:self.playerController.player.currentItem]; } @end @@ -276,32 +282,32 @@ -(void) removePlayerEventListener { _videoView = [[UIVideoViewWrapperIos alloc] init:this]; -#if CC_VIDEOPLAYER_DEBUG_DRAW +# if CC_VIDEOPLAYER_DEBUG_DRAW _debugDrawNode = DrawNode::create(); addChild(_debugDrawNode); -#endif +# endif } VideoPlayer::~VideoPlayer() { - if(_videoView) + if (_videoView) { [((UIVideoViewWrapperIos*)_videoView) dealloc]; } } -void VideoPlayer::setFileName(const std::string& fileName) +void VideoPlayer::setFileName(std::string_view fileName) { - _videoURL = FileUtils::getInstance()->fullPathForFilename(fileName); + _videoURL = FileUtils::getInstance()->fullPathForFilename(fileName); _videoSource = VideoPlayer::Source::FILENAME; - [((UIVideoViewWrapperIos*)_videoView) setURL:(int)_videoSource :_videoURL]; + [((UIVideoViewWrapperIos*)_videoView) setURL:(int) _videoSource:_videoURL]; } -void VideoPlayer::setURL(const std::string& videoUrl) +void VideoPlayer::setURL(std::string_view videoUrl) { - _videoURL = videoUrl; + _videoURL = videoUrl; _videoSource = VideoPlayer::Source::URL; - [((UIVideoViewWrapperIos*)_videoView) setURL:(int)_videoSource :_videoURL]; + [((UIVideoViewWrapperIos*)_videoView) setURL:(int) _videoSource:_videoURL]; } void VideoPlayer::setLooping(bool looping) @@ -320,56 +326,52 @@ -(void) removePlayerEventListener { _styleType = style; - switch (style) { - case StyleType::DEFAULT: - [((UIVideoViewWrapperIos*)_videoView) showPlaybackControls:TRUE]; - break; + switch (style) + { + case StyleType::DEFAULT: + [((UIVideoViewWrapperIos*)_videoView) showPlaybackControls:TRUE]; + break; - case StyleType::NONE: - [((UIVideoViewWrapperIos*)_videoView) showPlaybackControls:FALSE]; - break; + case StyleType::NONE: + [((UIVideoViewWrapperIos*)_videoView) showPlaybackControls:FALSE]; + break; } } -void VideoPlayer::draw(Renderer* renderer, const Mat4 &transform, uint32_t flags) +void VideoPlayer::draw(Renderer* renderer, const Mat4& transform, uint32_t flags) { - cocos2d::ui::Widget::draw(renderer,transform,flags); + cocos2d::ui::Widget::draw(renderer, transform, flags); if (flags & FLAGS_TRANSFORM_DIRTY) { auto directorInstance = Director::getInstance(); - auto glView = directorInstance->getOpenGLView(); - auto frameSize = glView->getFrameSize(); - auto scaleFactor = [static_cast(glView->getEAGLView()) contentScaleFactor]; + auto glView = directorInstance->getOpenGLView(); + auto frameSize = glView->getFrameSize(); + auto scaleFactor = [static_cast(glView->getEAGLView()) contentScaleFactor]; auto winSize = directorInstance->getWinSize(); auto leftBottom = convertToWorldSpace(Vec2::ZERO); - auto rightTop = convertToWorldSpace(Vec2(_contentSize.width,_contentSize.height)); + auto rightTop = convertToWorldSpace(Vec2(_contentSize.width, _contentSize.height)); - auto uiLeft = (frameSize.width / 2 + (leftBottom.x - winSize.width / 2 ) * glView->getScaleX()) / scaleFactor; - auto uiTop = (frameSize.height /2 - (rightTop.y - winSize.height / 2) * glView->getScaleY()) / scaleFactor; + auto uiLeft = (frameSize.width / 2 + (leftBottom.x - winSize.width / 2) * glView->getScaleX()) / scaleFactor; + auto uiTop = (frameSize.height / 2 - (rightTop.y - winSize.height / 2) * glView->getScaleY()) / scaleFactor; - [((UIVideoViewWrapperIos*)_videoView) setFrame :uiLeft :uiTop - :(rightTop.x - leftBottom.x) * glView->getScaleX() / scaleFactor - :( (rightTop.y - leftBottom.y) * glView->getScaleY()/scaleFactor)]; + [((UIVideoViewWrapperIos*)_videoView) setFrame: + uiLeft:uiTop:(rightTop.x - leftBottom.x) * glView->getScaleX() / + scaleFactor:((rightTop.y - leftBottom.y) * glView->getScaleY() / + scaleFactor)]; } -#if CC_VIDEOPLAYER_DEBUG_DRAW +# if CC_VIDEOPLAYER_DEBUG_DRAW _debugDrawNode->clear(); - auto size = getContentSize(); - Point vertices[4]= - { - Point::ZERO, - Point(size.width, 0), - Point(size.width, size.height), - Point(0, size.height) - }; + auto size = getContentSize(); + Point vertices[4] = {Point::ZERO, Point(size.width, 0), Point(size.width, size.height), Point(0, size.height)}; _debugDrawNode->drawPoly(vertices, 4, true, Color4F(1.0, 1.0, 1.0, 1.0)); -#endif +# endif } -bool VideoPlayer::isFullScreenEnabled()const +bool VideoPlayer::isFullScreenEnabled() const { return [((UIVideoViewWrapperIos*)_videoView) isFullScreenEnabled]; } @@ -390,7 +392,7 @@ -(void) removePlayerEventListener void VideoPlayer::play() { - if (! _videoURL.empty()) + if (!_videoURL.empty()) { [((UIVideoViewWrapperIos*)_videoView) play]; } @@ -398,7 +400,7 @@ -(void) removePlayerEventListener void VideoPlayer::pause() { - if (! _videoURL.empty()) + if (!_videoURL.empty()) { [((UIVideoViewWrapperIos*)_videoView) pause]; } @@ -406,7 +408,7 @@ -(void) removePlayerEventListener void VideoPlayer::resume() { - if (! _videoURL.empty()) + if (!_videoURL.empty()) { [((UIVideoViewWrapperIos*)_videoView) resume]; } @@ -414,7 +416,7 @@ -(void) removePlayerEventListener void VideoPlayer::stop() { - if (! _videoURL.empty()) + if (!_videoURL.empty()) { [((UIVideoViewWrapperIos*)_videoView) stop]; } @@ -422,7 +424,7 @@ -(void) removePlayerEventListener void VideoPlayer::seekTo(float sec) { - if (! _videoURL.empty()) + if (!_videoURL.empty()) { [((UIVideoViewWrapperIos*)_videoView) seekTo:sec]; } @@ -451,7 +453,7 @@ -(void) removePlayerEventListener { [((UIVideoViewWrapperIos*)_videoView) setVisible:NO]; } - else if(isRunning()) + else if (isRunning()) { [((UIVideoViewWrapperIos*)_videoView) setVisible:YES]; } @@ -462,14 +464,14 @@ -(void) removePlayerEventListener Widget::onEnter(); if (isVisible()) { - [((UIVideoViewWrapperIos*)_videoView) setVisible: YES]; + [((UIVideoViewWrapperIos*)_videoView) setVisible:YES]; } } void VideoPlayer::onExit() { Widget::onExit(); - [((UIVideoViewWrapperIos*)_videoView) setVisible: NO]; + [((UIVideoViewWrapperIos*)_videoView) setVisible:NO]; } void VideoPlayer::addEventListener(const VideoPlayer::ccVideoPlayerCallback& callback) @@ -479,9 +481,12 @@ -(void) removePlayerEventListener void VideoPlayer::onPlayEvent(int event) { - if (event == (int)VideoPlayer::EventType::PLAYING) { + if (event == (int)VideoPlayer::EventType::PLAYING) + { _isPlaying = true; - } else { + } + else + { _isPlaying = false; } @@ -496,23 +501,23 @@ -(void) removePlayerEventListener return VideoPlayer::create(); } -void VideoPlayer::copySpecialProperties(Widget *widget) +void VideoPlayer::copySpecialProperties(Widget* widget) { VideoPlayer* videoPlayer = dynamic_cast(widget); if (videoPlayer) { - _isPlaying = videoPlayer->_isPlaying; - _isLooping = videoPlayer->_isLooping; - _isUserInputEnabled = videoPlayer->_isUserInputEnabled; - _styleType = videoPlayer->_styleType; - _fullScreenEnabled = videoPlayer->_fullScreenEnabled; - _fullScreenDirty = videoPlayer->_fullScreenDirty; - _videoURL = videoPlayer->_videoURL; + _isPlaying = videoPlayer->_isPlaying; + _isLooping = videoPlayer->_isLooping; + _isUserInputEnabled = videoPlayer->_isUserInputEnabled; + _styleType = videoPlayer->_styleType; + _fullScreenEnabled = videoPlayer->_fullScreenEnabled; + _fullScreenDirty = videoPlayer->_fullScreenDirty; + _videoURL = videoPlayer->_videoURL; _keepAspectRatioEnabled = videoPlayer->_keepAspectRatioEnabled; - _videoSource = videoPlayer->_videoSource; - _videoPlayerIndex = videoPlayer->_videoPlayerIndex; - _eventCallback = videoPlayer->_eventCallback; - _videoView = videoPlayer->_videoView; + _videoSource = videoPlayer->_videoSource; + _videoPlayerIndex = videoPlayer->_videoPlayerIndex; + _eventCallback = videoPlayer->_eventCallback; + _videoView = videoPlayer->_videoView; } } diff --git a/cocos/ui/UIVideoPlayer.h b/cocos/ui/UIVideoPlayer.h index c97d5c3b7bae..76e82663f23f 100644 --- a/cocos/ui/UIVideoPlayer.h +++ b/cocos/ui/UIVideoPlayer.h @@ -86,26 +86,26 @@ class VideoPlayer : public cocos2d::ui::Widget /** * Sets a file path as a video source for VideoPlayer. */ - virtual void setFileName(const std::string& videoPath); + virtual void setFileName(std::string_view videoPath); /** * @brief Get the local video file name. * * @return The video file name. */ - virtual const std::string& getFileName() const { return _videoURL; } + virtual std::string_view getFileName() const { return _videoURL; } /** * Sets a URL as a video source for VideoPlayer. */ - virtual void setURL(const std::string& _videoURL); + virtual void setURL(std::string_view _videoURL); /** * @brief Get the URL of remoting video source. * * @return A remoting URL address. */ - virtual const std::string& getURL() const { return _videoURL; } + virtual std::string_view getURL() const { return _videoURL; } /** * @brief Set if playback is done in loop mode diff --git a/cocos/ui/UIWebView/UIWebView-inl.h b/cocos/ui/UIWebView/UIWebView-inl.h index 586aecc8e58f..8f510b017723 100644 --- a/cocos/ui/UIWebView/UIWebView-inl.h +++ b/cocos/ui/UIWebView/UIWebView-inl.h @@ -53,35 +53,35 @@ WebView* WebView::create() return nullptr; } -void WebView::setJavascriptInterfaceScheme(const std::string& scheme) +void WebView::setJavascriptInterfaceScheme(std::string_view scheme) { _impl->setJavascriptInterfaceScheme(scheme); } void WebView::loadData(const cocos2d::Data& data, - const std::string& MIMEType, - const std::string& encoding, - const std::string& baseURL) + std::string_view MIMEType, + std::string_view encoding, + std::string_view baseURL) { _impl->loadData(data, MIMEType, encoding, baseURL); } -void WebView::loadHTMLString(const std::string& string, const std::string& baseURL) +void WebView::loadHTMLString(std::string_view string, std::string_view baseURL) { _impl->loadHTMLString(string, baseURL); } -void WebView::loadURL(const std::string& url) +void WebView::loadURL(std::string_view url) { this->loadURL(url, false); } -void WebView::loadURL(const std::string& url, bool cleanCachedData) +void WebView::loadURL(std::string_view url, bool cleanCachedData) { _impl->loadURL(url, cleanCachedData); } -void WebView::loadFile(const std::string& fileName) +void WebView::loadFile(std::string_view fileName) { _impl->loadFile(fileName); } @@ -116,7 +116,7 @@ void WebView::goForward() _impl->goForward(); } -void WebView::evaluateJS(const std::string& js) +void WebView::evaluateJS(std::string_view js) { _impl->evaluateJS(js); } @@ -204,7 +204,7 @@ void WebView::setOnDidFinishLoading(const ccWebViewCallback& callback) _onDidFinishLoading = callback; } -void WebView::setOnShouldStartLoading(const std::function& callback) +void WebView::setOnShouldStartLoading(const std::function& callback) { _onShouldStartLoading = callback; } @@ -214,7 +214,7 @@ void WebView::setOnJSCallback(const ccWebViewCallback& callback) _onJSCallback = callback; } -std::function WebView::getOnShouldStartLoading() const +std::function WebView::getOnShouldStartLoading() const { return _onShouldStartLoading; } diff --git a/cocos/ui/UIWebView/UIWebView.h b/cocos/ui/UIWebView/UIWebView.h index bc37e130d2ff..a685f7af7309 100644 --- a/cocos/ui/UIWebView/UIWebView.h +++ b/cocos/ui/UIWebView/UIWebView.h @@ -59,7 +59,7 @@ class CC_GUI_DLL WebView : public cocos2d::ui::Widget * * @see WebView::setOnJSCallback() */ - void setJavascriptInterfaceScheme(const std::string& scheme); + void setJavascriptInterfaceScheme(std::string_view scheme); /** * Sets the main page contents, MIME type, content encoding, and base URL. @@ -70,9 +70,9 @@ class CC_GUI_DLL WebView : public cocos2d::ui::Widget * @param baseURL The base URL for the content. */ void loadData(const cocos2d::Data& data, - const std::string& MIMEType, - const std::string& encoding, - const std::string& baseURL); + std::string_view MIMEType, + std::string_view encoding, + std::string_view baseURL); /** * Sets the main page content and base URL. @@ -80,28 +80,28 @@ class CC_GUI_DLL WebView : public cocos2d::ui::Widget * @param string The content for the main page. * @param baseURL The base URL for the content. */ - void loadHTMLString(const std::string& string, const std::string& baseURL = ""); + void loadHTMLString(std::string_view string, std::string_view baseURL = ""); /** * Loads the given URL. It doesn't clean cached data. * * @param url Content URL. */ - void loadURL(const std::string& url); + void loadURL(std::string_view url); /** * Loads the given URL with cleaning cached data or not. * @param url Content URL. * @cleanCachedData Whether to clean cached data. */ - void loadURL(const std::string& url, bool cleanCachedData); + void loadURL(std::string_view url, bool cleanCachedData); /** * Loads the given fileName. * * @param fileName Content fileName. */ - void loadFile(const std::string& fileName); + void loadFile(std::string_view fileName); /** * Stops the current load. @@ -140,7 +140,7 @@ class CC_GUI_DLL WebView : public cocos2d::ui::Widget /** * Evaluates JavaScript in the context of the currently displayed page. */ - void evaluateJS(const std::string& js); + void evaluateJS(std::string_view js); /** * Set WebView should support zooming. The default value is false. @@ -153,12 +153,12 @@ class CC_GUI_DLL WebView : public cocos2d::ui::Widget * @param callback The web view that is about to load new content. * @return YES if the web view should begin loading content; otherwise, NO. */ - void setOnShouldStartLoading(const std::function& callback); + void setOnShouldStartLoading(const std::function& callback); /** * A callback which will be called when a WebView event happens. */ - typedef std::function ccWebViewCallback; + typedef std::function ccWebViewCallback; /** * Call after a web view finishes loading. @@ -182,7 +182,7 @@ class CC_GUI_DLL WebView : public cocos2d::ui::Widget /** * Get the callback when WebView is about to start. */ - std::function getOnShouldStartLoading() const; + std::function getOnShouldStartLoading() const; /** * Get the callback when WebView has finished loading. @@ -231,10 +231,10 @@ class CC_GUI_DLL WebView : public cocos2d::ui::Widget virtual cocos2d::ui::Widget* createCloneInstance() override; virtual void copySpecialProperties(Widget* model) override; - std::function _onShouldStartLoading = nullptr; - ccWebViewCallback _onDidFinishLoading = nullptr; - ccWebViewCallback _onDidFailLoading = nullptr; - ccWebViewCallback _onJSCallback = nullptr; + std::function _onShouldStartLoading = nullptr; + ccWebViewCallback _onDidFinishLoading = nullptr; + ccWebViewCallback _onDidFailLoading = nullptr; + ccWebViewCallback _onJSCallback = nullptr; CC_CONSTRUCTOR_ACCESS : /** diff --git a/cocos/ui/UIWebView/UIWebView.mm b/cocos/ui/UIWebView/UIWebView.mm index 31a5694674cb..a80e16512cdf 100644 --- a/cocos/ui/UIWebView/UIWebView.mm +++ b/cocos/ui/UIWebView/UIWebView.mm @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2014-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 diff --git a/cocos/ui/UIWebView/UIWebViewImpl-android.cpp b/cocos/ui/UIWebView/UIWebViewImpl-android.cpp index cd61a73d6e45..b5ec6cac0f9c 100644 --- a/cocos/ui/UIWebView/UIWebViewImpl-android.cpp +++ b/cocos/ui/UIWebView/UIWebViewImpl-android.cpp @@ -37,14 +37,14 @@ #include "ui/UIHelper.h" #include "yasio/cxx17/string_view.hpp" -static const std::string className = "org.cocos2dx.lib.Cocos2dxWebViewHelper"; +static const char* className = "org.cocos2dx.lib.Cocos2dxWebViewHelper"; #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, "", __VA_ARGS__) -static const std::string s_defaultBaseUrl = "file:///android_asset/"; -static const std::string s_sdRootBaseUrl = "file://"; +static constexpr std::string_view s_defaultBaseUrl = "file:///android_asset/"sv; +static constexpr std::string_view s_sdRootBaseUrl = "file://"sv; -static std::string getFixedBaseUrl(const std::string& baseUrl) +static std::string getFixedBaseUrl(std::string_view baseUrl) { std::string fixedBaseUrl; if (baseUrl.empty()) @@ -55,26 +55,26 @@ static std::string getFixedBaseUrl(const std::string& baseUrl) { fixedBaseUrl = baseUrl; } - else if (baseUrl.c_str()[0] != '/') + else if (baseUrl[0] != '/') { using namespace cxx17; // for cxx17::string_view literal - if (cxx20::starts_with(cxx17::string_view{baseUrl}, "assets/"_sv)) + if (cxx20::starts_with(baseUrl, "assets/"_sv)) { - fixedBaseUrl = s_defaultBaseUrl + baseUrl.c_str()[7]; + fixedBaseUrl.assign(s_defaultBaseUrl).push_back(baseUrl[7]); } else { - fixedBaseUrl = s_defaultBaseUrl + baseUrl; + fixedBaseUrl.assign(s_defaultBaseUrl).append(baseUrl); } } else { - fixedBaseUrl = s_sdRootBaseUrl + baseUrl; + fixedBaseUrl.assign(s_sdRootBaseUrl).append(baseUrl); } if (fixedBaseUrl.c_str()[fixedBaseUrl.length() - 1] != '/') { - fixedBaseUrl += "/"; + fixedBaseUrl.push_back('/'); } return fixedBaseUrl; @@ -155,7 +155,7 @@ namespace int createWebViewJNI() { cocos2d::JniMethodInfo t; - if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), "createWebView", "()I")) + if (cocos2d::JniHelper::getStaticMethodInfo(t, className, "createWebView", "()I")) { // LOGD("error: %s,%d",__func__,__LINE__); jint viewTag = t.env->CallStaticIntMethod(t.classID, t.methodID); @@ -165,7 +165,7 @@ int createWebViewJNI() return -1; } -std::string getUrlStringByFileName(const std::string& fileName) +std::string getUrlStringByFileName(std::string_view fileName) { // LOGD("error: %s,%d",__func__,__LINE__); const std::string basePath("file:///android_asset/"); @@ -214,31 +214,31 @@ WebViewImpl::~WebViewImpl() } void WebViewImpl::loadData(const Data& data, - const std::string& MIMEType, - const std::string& encoding, - const std::string& baseURL) + std::string_view MIMEType, + std::string_view encoding, + std::string_view baseURL) { std::string dataString(reinterpret_cast(data.getBytes()), static_cast(data.getSize())); JniHelper::callStaticVoidMethod(className, "setJavascriptInterfaceScheme", _viewTag, dataString, MIMEType, encoding, baseURL); } -void WebViewImpl::loadHTMLString(const std::string& string, const std::string& baseURL) +void WebViewImpl::loadHTMLString(std::string_view string, std::string_view baseURL) { JniHelper::callStaticVoidMethod(className, "loadHTMLString", _viewTag, string, getFixedBaseUrl(baseURL)); } -void WebViewImpl::loadURL(const std::string& url) +void WebViewImpl::loadURL(std::string_view url) { this->loadURL(url, false); } -void WebViewImpl::loadURL(const std::string& url, bool cleanCachedData) +void WebViewImpl::loadURL(std::string_view url, bool cleanCachedData) { JniHelper::callStaticVoidMethod(className, "loadUrl", _viewTag, url, cleanCachedData); } -void WebViewImpl::loadFile(const std::string& fileName) +void WebViewImpl::loadFile(std::string_view fileName) { auto fullPath = getUrlStringByFileName(fileName); JniHelper::callStaticVoidMethod(className, "loadFile", _viewTag, fullPath); @@ -274,12 +274,12 @@ void WebViewImpl::goForward() JniHelper::callStaticVoidMethod(className, "goForward", _viewTag); } -void WebViewImpl::setJavascriptInterfaceScheme(const std::string& scheme) +void WebViewImpl::setJavascriptInterfaceScheme(std::string_view scheme) { JniHelper::callStaticVoidMethod(className, "setJavascriptInterfaceScheme", _viewTag, scheme); } -void WebViewImpl::evaluateJS(const std::string& js) +void WebViewImpl::evaluateJS(std::string_view js) { JniHelper::callStaticVoidMethod(className, "evaluateJS", _viewTag, js); } @@ -289,7 +289,7 @@ void WebViewImpl::setScalesPageToFit(const bool scalesPageToFit) JniHelper::callStaticVoidMethod(className, "setScalesPageToFit", _viewTag, scalesPageToFit); } -bool WebViewImpl::shouldStartLoading(const int viewTag, const std::string& url) +bool WebViewImpl::shouldStartLoading(const int viewTag, std::string_view url) { bool allowLoad = true; auto it = s_WebViewImpls.find(viewTag); @@ -304,7 +304,7 @@ bool WebViewImpl::shouldStartLoading(const int viewTag, const std::string& url) return allowLoad; } -void WebViewImpl::didFinishLoading(const int viewTag, const std::string& url) +void WebViewImpl::didFinishLoading(const int viewTag, std::string_view url) { auto it = s_WebViewImpls.find(viewTag); if (it != s_WebViewImpls.end()) @@ -317,7 +317,7 @@ void WebViewImpl::didFinishLoading(const int viewTag, const std::string& url) } } -void WebViewImpl::didFailLoading(const int viewTag, const std::string& url) +void WebViewImpl::didFailLoading(const int viewTag, std::string_view url) { auto it = s_WebViewImpls.find(viewTag); if (it != s_WebViewImpls.end()) @@ -330,7 +330,7 @@ void WebViewImpl::didFailLoading(const int viewTag, const std::string& url) } } -void WebViewImpl::onJsCallback(const int viewTag, const std::string& message) +void WebViewImpl::onJsCallback(const int viewTag, std::string_view message) { auto it = s_WebViewImpls.find(viewTag); if (it != s_WebViewImpls.end()) diff --git a/cocos/ui/UIWebView/UIWebViewImpl-android.h b/cocos/ui/UIWebView/UIWebViewImpl-android.h index 653078cc28ab..9f1a178a5afe 100644 --- a/cocos/ui/UIWebView/UIWebViewImpl-android.h +++ b/cocos/ui/UIWebView/UIWebViewImpl-android.h @@ -28,6 +28,8 @@ #include #include +#include +#include namespace cocos2d { @@ -53,19 +55,19 @@ class WebViewImpl virtual ~WebViewImpl(); - void setJavascriptInterfaceScheme(const std::string& scheme); + void setJavascriptInterfaceScheme(std::string_view scheme); void loadData(const cocos2d::Data& data, - const std::string& MIMEType, - const std::string& encoding, - const std::string& baseURL); + std::string_view MIMEType, + std::string_view encoding, + std::string_view baseURL); - void loadHTMLString(const std::string& string, const std::string& baseURL); + void loadHTMLString(std::string_view string, std::string_view baseURL); - void loadURL(const std::string& url); - void loadURL(const std::string& url, bool cleanCachedData); + void loadURL(std::string_view url); + void loadURL(std::string_view url, bool cleanCachedData); - void loadFile(const std::string& fileName); + void loadFile(std::string_view fileName); void stopLoading(); @@ -79,7 +81,7 @@ class WebViewImpl void goForward(); - void evaluateJS(const std::string& js); + void evaluateJS(std::string_view js); void setScalesPageToFit(const bool scalesPageToFit); @@ -95,10 +97,10 @@ class WebViewImpl void setBackgroundTransparent(); - static bool shouldStartLoading(const int viewTag, const std::string& url); - static void didFinishLoading(const int viewTag, const std::string& url); - static void didFailLoading(const int viewTag, const std::string& url); - static void onJsCallback(const int viewTag, const std::string& message); + static bool shouldStartLoading(const int viewTag, std::string_view url); + static void didFinishLoading(const int viewTag, std::string_view url); + static void didFailLoading(const int viewTag, std::string_view url); + static void onJsCallback(const int viewTag, std::string_view message); private: int _viewTag; diff --git a/cocos/ui/UIWebView/UIWebViewImpl-ios.h b/cocos/ui/UIWebView/UIWebViewImpl-ios.h index 03fe18cc860b..0d9294fd541c 100644 --- a/cocos/ui/UIWebView/UIWebViewImpl-ios.h +++ b/cocos/ui/UIWebView/UIWebViewImpl-ios.h @@ -27,6 +27,8 @@ #include #include +#include +#include @class UIWebViewWrapper; @@ -49,19 +51,19 @@ class WebViewImpl virtual ~WebViewImpl(); - void setJavascriptInterfaceScheme(const std::string& scheme); + void setJavascriptInterfaceScheme(std::string_view scheme); void loadData(const cocos2d::Data& data, - const std::string& MIMEType, - const std::string& encoding, - const std::string& baseURL); + std::string_view MIMEType, + std::string_view encoding, + std::string_view baseURL); - void loadHTMLString(const std::string& string, const std::string& baseURL); + void loadHTMLString(std::string_view string, std::string_view baseURL); - void loadURL(const std::string& url); - void loadURL(const std::string& url, bool cleanCachedData); + void loadURL(std::string_view url); + void loadURL(std::string_view url, bool cleanCachedData); - void loadFile(const std::string& fileName); + void loadFile(std::string_view fileName); void stopLoading(); @@ -75,7 +77,7 @@ class WebViewImpl void goForward(); - void evaluateJS(const std::string& js); + void evaluateJS(std::string_view js); void setScalesPageToFit(const bool scalesPageToFit); diff --git a/cocos/ui/UIWebView/UIWebViewImpl-ios.mm b/cocos/ui/UIWebView/UIWebViewImpl-ios.mm index e2c448249e3f..7c1979f0a6de 100644 --- a/cocos/ui/UIWebView/UIWebViewImpl-ios.mm +++ b/cocos/ui/UIWebView/UIWebViewImpl-ios.mm @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2014-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -35,10 +35,10 @@ of this software and associated documentation files (the "Software"), to deal #include "platform/CCFileUtils.h" @interface UIWebViewWrapper : NSObject -@property (nonatomic) std::function shouldStartLoading; -@property (nonatomic) std::function didFinishLoading; -@property (nonatomic) std::function didFailLoading; -@property (nonatomic) std::function onJsCallback; +@property(nonatomic) std::function shouldStartLoading; +@property(nonatomic) std::function didFinishLoading; +@property(nonatomic) std::function didFailLoading; +@property(nonatomic) std::function onJsCallback; @property(nonatomic, readonly, getter=canGoBack) BOOL canGoBack; @property(nonatomic, readonly, getter=canGoForward) BOOL canGoForward; @@ -57,21 +57,24 @@ - (void)setBackgroundTransparent; - (void)setFrameWithX:(float)x y:(float)y width:(float)width height:(float)height; -- (void)setJavascriptInterfaceScheme:(const std::string &)scheme; +- (void)setJavascriptInterfaceScheme:(std::string_view)scheme; -- (void)loadData:(const std::string &)data MIMEType:(const std::string &)MIMEType textEncodingName:(const std::string &)encodingName baseURL:(const std::string &)baseURL; +- (void)loadData:(std::string_view)data + MIMEType:(std::string_view)MIMEType + textEncodingName:(std::string_view)encodingName + baseURL:(std::string_view)baseURL; -- (void)loadHTMLString:(const std::string &)string baseURL:(const std::string &)baseURL; +- (void)loadHTMLString:(std::string_view)string baseURL:(std::string_view)baseURL; -- (void)loadUrl:(const std::string &)urlString cleanCachedData:(BOOL) needCleanCachedData; +- (void)loadUrl:(std::string_view)urlString cleanCachedData:(BOOL)needCleanCachedData; -- (void)loadFile:(const std::string &)filePath; +- (void)loadFile:(std::string_view)filePath; - (void)stopLoading; - (void)reload; -- (void)evaluateJS:(const std::string &)js; +- (void)evaluateJS:(std::string_view)js; - (void)goBack; @@ -80,178 +83,236 @@ - (void)goForward; - (void)setScalesPageToFit:(const bool)scalesPageToFit; @end - @interface UIWebViewWrapper () -@property(nonatomic) WKWebView *wkWebView; +@property(nonatomic) WKWebView* wkWebView; -@property(nonatomic, copy) NSString *jsScheme; +@property(nonatomic, copy) NSString* jsScheme; @end @implementation UIWebViewWrapper { - } -+ (instancetype) newWebViewWrapper { ++ (instancetype)newWebViewWrapper +{ return [[self alloc] init]; } -- (instancetype)init { +- (instancetype)init +{ self = [super init]; - if (self) { - self.wkWebView = nil; + if (self) + { + self.wkWebView = nil; self.shouldStartLoading = nullptr; - self.didFinishLoading = nullptr; - self.didFailLoading = nullptr; + self.didFinishLoading = nullptr; + self.didFailLoading = nullptr; } return self; } -- (void)dealloc { - self.wkWebView.UIDelegate = nil; +- (void)dealloc +{ + self.wkWebView.UIDelegate = nil; self.wkWebView.navigationDelegate = nil; [self.wkWebView removeFromSuperview]; [self.wkWebView release]; self.wkWebView = nil; - self.jsScheme = nil; + self.jsScheme = nil; [super dealloc]; } -- (void)setupWebView { - if (!self.wkWebView) { - self.wkWebView = [[WKWebView alloc] init]; - self.wkWebView.UIDelegate = self; +- (void)setupWebView +{ + if (!self.wkWebView) + { + self.wkWebView = [[WKWebView alloc] init]; + self.wkWebView.UIDelegate = self; self.wkWebView.navigationDelegate = self; } - if (!self.wkWebView.superview) { - auto view = cocos2d::Director::getInstance()->getOpenGLView(); - auto eaglview = (CCEAGLView *) view->getEAGLView(); + if (!self.wkWebView.superview) + { + auto view = cocos2d::Director::getInstance()->getOpenGLView(); + auto eaglview = (CCEAGLView*)view->getEAGLView(); [eaglview addSubview:self.wkWebView]; } } -- (void)setVisible:(bool)visible { - if (!self.wkWebView) {[self setupWebView];} +- (void)setVisible:(bool)visible +{ + if (!self.wkWebView) + { + [self setupWebView]; + } self.wkWebView.hidden = !visible; } -- (void)setBounces:(bool)bounces { - self.wkWebView.scrollView.bounces = bounces; +- (void)setBounces:(bool)bounces +{ + self.wkWebView.scrollView.bounces = bounces; } -- (void)setOpacityWebView:(float)opacity { - if (!self.wkWebView) { [self setupWebView]; } +- (void)setOpacityWebView:(float)opacity +{ + if (!self.wkWebView) + { + [self setupWebView]; + } self.wkWebView.alpha = opacity; [self.wkWebView setOpaque:YES]; } --(float) getOpacityWebView{ +- (float)getOpacityWebView +{ return self.wkWebView.alpha; } --(void) setBackgroundTransparent{ - if (!self.wkWebView) {[self setupWebView];} +- (void)setBackgroundTransparent +{ + if (!self.wkWebView) + { + [self setupWebView]; + } [self.wkWebView setOpaque:NO]; [self.wkWebView setBackgroundColor:[UIColor clearColor]]; } -- (void)setFrameWithX:(float)x y:(float)y width:(float)width height:(float)height { - if (!self.wkWebView) {[self setupWebView];} +- (void)setFrameWithX:(float)x y:(float)y width:(float)width height:(float)height +{ + if (!self.wkWebView) + { + [self setupWebView]; + } CGRect newFrame = CGRectMake(x, y, width, height); - if (!CGRectEqualToRect(self.wkWebView.frame, newFrame)) { + if (!CGRectEqualToRect(self.wkWebView.frame, newFrame)) + { self.wkWebView.frame = CGRectMake(x, y, width, height); } } -- (void)setJavascriptInterfaceScheme:(const std::string &)scheme { - self.jsScheme = @(scheme.c_str()); +- (void)setJavascriptInterfaceScheme:(std::string_view)scheme +{ + self.jsScheme = @(scheme.data()); } -- (void)loadData:(const std::string &)data MIMEType:(const std::string &)MIMEType textEncodingName:(const std::string &)encodingName baseURL:(const std::string &)baseURL { +- (void)loadData:(std::string_view)data + MIMEType:(std::string_view)MIMEType + textEncodingName:(std::string_view)encodingName + baseURL:(std::string_view)baseURL +{ auto path = [[NSBundle mainBundle] resourcePath]; - path = [path stringByAppendingPathComponent:@(baseURL.c_str() )]; - auto url = [NSURL fileURLWithPath:path]; + path = [path stringByAppendingPathComponent:@(baseURL.data())]; + auto url = [NSURL fileURLWithPath:path]; - [self.wkWebView loadData:[NSData dataWithBytes:data.c_str() length:data.length()] - MIMEType:@(MIMEType.c_str()) - characterEncodingName:@(encodingName.c_str()) - baseURL:url]; + [self.wkWebView loadData:[NSData dataWithBytes:data.data() length:data.length()] + MIMEType:@(MIMEType.data()) + characterEncodingName:@(encodingName.data()) + baseURL:url]; } -- (void)loadHTMLString:(const std::string &)string baseURL:(const std::string &)baseURL { - if (!self.wkWebView) {[self setupWebView];} +- (void)loadHTMLString:(std::string_view)string baseURL:(std::string_view)baseURL +{ + if (!self.wkWebView) + { + [self setupWebView]; + } auto path = [[NSBundle mainBundle] resourcePath]; - path = [path stringByAppendingPathComponent:@(baseURL.c_str() )]; - auto url = [NSURL fileURLWithPath:path]; - [self.wkWebView loadHTMLString:@(string.c_str()) baseURL:url]; + path = [path stringByAppendingPathComponent:@(baseURL.data())]; + auto url = [NSURL fileURLWithPath:path]; + [self.wkWebView loadHTMLString:@(string.data()) baseURL:url]; } -- (void)loadUrl:(const std::string &)urlString cleanCachedData:(BOOL) needCleanCachedData { - if (!self.wkWebView) {[self setupWebView];} - NSURL *url = [NSURL URLWithString:@(urlString.c_str())]; +- (void)loadUrl:(std::string_view)urlString cleanCachedData:(BOOL)needCleanCachedData +{ + if (!self.wkWebView) + { + [self setupWebView]; + } + NSURL* url = [NSURL URLWithString:@(urlString.data())]; - NSURLRequest *request = nil; + NSURLRequest* request = nil; if (needCleanCachedData) - request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60]; + request = [NSURLRequest requestWithURL:url + cachePolicy:NSURLRequestReloadIgnoringLocalCacheData + timeoutInterval:60]; else request = [NSURLRequest requestWithURL:url]; [self.wkWebView loadRequest:request]; } -- (void)loadFile:(const std::string &)filePath { - if (!self.wkWebView) {[self setupWebView];} - NSURL *url = [NSURL fileURLWithPath:@(filePath.c_str())]; - NSURLRequest *request = [NSURLRequest requestWithURL:url]; +- (void)loadFile:(std::string_view)filePath +{ + if (!self.wkWebView) + { + [self setupWebView]; + } + NSURL* url = [NSURL fileURLWithPath:@(filePath.data())]; + NSURLRequest* request = [NSURLRequest requestWithURL:url]; [self.wkWebView loadRequest:request]; } -- (void)stopLoading { +- (void)stopLoading +{ [self.wkWebView stopLoading]; } -- (void)reload { +- (void)reload +{ [self.wkWebView reload]; } -- (BOOL)canGoForward { +- (BOOL)canGoForward +{ return self.wkWebView.canGoForward; } -- (BOOL)canGoBack { +- (BOOL)canGoBack +{ return self.wkWebView.canGoBack; } -- (void)goBack { +- (void)goBack +{ [self.wkWebView goBack]; } -- (void)goForward { +- (void)goForward +{ [self.wkWebView goForward]; } -- (void)evaluateJS:(const std::string &)js { - if (!self.wkWebView) {[self setupWebView];} - [self.wkWebView evaluateJavaScript:@(js.c_str()) completionHandler:nil]; +- (void)evaluateJS:(std::string_view)js +{ + if (!self.wkWebView) + { + [self setupWebView]; + } + [self.wkWebView evaluateJavaScript:@(js.data()) completionHandler:nil]; } -- (void)setScalesPageToFit:(const bool)scalesPageToFit { -// TODO: there is not corresponding API in WK. -// https://stackoverflow.com/questions/26295277/wkwebview-equivalent-for-uiwebviews-scalespagetofit/43048514 seems has a solution, -// but it doesn't support setting it dynamically. If we want to set this feature dynamically, then it will be too complex. +- (void)setScalesPageToFit:(const bool)scalesPageToFit +{ + // TODO: there is not corresponding API in WK. + // https://stackoverflow.com/questions/26295277/wkwebview-equivalent-for-uiwebviews-scalespagetofit/43048514 seems + // has a solution, but it doesn't support setting it dynamically. If we want to set this feature dynamically, then + // it will be too complex. } - - #pragma mark - WKNavigationDelegate -- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { - NSString *url = [[[navigationAction request] URL] absoluteString]; - if ([[webView.URL scheme] isEqualToString:self.jsScheme]) { +- (void)webView:(WKWebView*)webView + decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction + decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler +{ + NSString* url = [[[navigationAction request] URL] absoluteString]; + if ([[webView.URL scheme] isEqualToString:self.jsScheme]) + { self.onJsCallback([url UTF8String]); decisionHandler(WKNavigationActionPolicyCancel); return; } - if (self.shouldStartLoading && url) { - if (self.shouldStartLoading([url UTF8String]) ) + if (self.shouldStartLoading && url) + { + if (self.shouldStartLoading([url UTF8String])) decisionHandler(WKNavigationActionPolicyAllow); else decisionHandler(WKNavigationActionPolicyCancel); @@ -262,17 +323,22 @@ - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigati decisionHandler(WKNavigationActionPolicyAllow); } -- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { - if (self.didFinishLoading) { - NSString *url = [webView.URL absoluteString]; +- (void)webView:(WKWebView*)webView didFinishNavigation:(WKNavigation*)navigation +{ + if (self.didFinishLoading) + { + NSString* url = [webView.URL absoluteString]; self.didFinishLoading([url UTF8String]); } } -- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error { - if (self.didFailLoading) { - NSString *errorInfo = error.userInfo[NSURLErrorFailingURLStringErrorKey]; - if (errorInfo) { +- (void)webView:(WKWebView*)webView didFailProvisionalNavigation:(WKNavigation*)navigation withError:(NSError*)error +{ + if (self.didFailLoading) + { + NSString* errorInfo = error.userInfo[NSURLErrorFailingURLStringErrorKey]; + if (errorInfo) + { self.didFailLoading([errorInfo UTF8String]); } } @@ -281,168 +347,196 @@ - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation #pragma WKUIDelegate // Implement js alert function. -- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)())completionHandler +- (void)webView:(WKWebView*)webView + runJavaScriptAlertPanelWithMessage:(NSString*)message + initiatedByFrame:(WKFrameInfo*)frame + completionHandler:(void (^)())completionHandler { - UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message + UIAlertController* alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert]; [alertController addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel - handler:^(UIAlertAction *action) { - completionHandler(); + handler:^(UIAlertAction* action) { + completionHandler(); }]]; auto rootViewController = [UIApplication sharedApplication].windows[0].rootViewController; - [rootViewController presentViewController:alertController animated:YES completion:^{}]; + [rootViewController presentViewController:alertController + animated:YES + completion:^{ + }]; } @end +namespace cocos2d +{ +namespace ui +{ +WebViewImpl::WebViewImpl(WebView* webView) : _uiWebViewWrapper([UIWebViewWrapper newWebViewWrapper]), _webView(webView) +{ -namespace cocos2d { -namespace ui{ - -WebViewImpl::WebViewImpl(WebView *webView) - : _uiWebViewWrapper([UIWebViewWrapper newWebViewWrapper]), - _webView(webView) { - _uiWebViewWrapper.shouldStartLoading = [this](std::string url) { - if (this->_webView->_onShouldStartLoading) { + if (this->_webView->_onShouldStartLoading) + { return this->_webView->_onShouldStartLoading(this->_webView, url); } return true; }; _uiWebViewWrapper.didFinishLoading = [this](std::string url) { - if (this->_webView->_onDidFinishLoading) { + if (this->_webView->_onDidFinishLoading) + { this->_webView->_onDidFinishLoading(this->_webView, url); } }; _uiWebViewWrapper.didFailLoading = [this](std::string url) { - if (this->_webView->_onDidFailLoading) { + if (this->_webView->_onDidFailLoading) + { this->_webView->_onDidFailLoading(this->_webView, url); } }; _uiWebViewWrapper.onJsCallback = [this](std::string url) { - if (this->_webView->_onJSCallback) { + if (this->_webView->_onJSCallback) + { this->_webView->_onJSCallback(this->_webView, url); } }; } -WebViewImpl::~WebViewImpl(){ +WebViewImpl::~WebViewImpl() +{ [_uiWebViewWrapper release]; _uiWebViewWrapper = nullptr; } -void WebViewImpl::setJavascriptInterfaceScheme(const std::string &scheme) { +void WebViewImpl::setJavascriptInterfaceScheme(std::string_view scheme) +{ [_uiWebViewWrapper setJavascriptInterfaceScheme:scheme]; } -void WebViewImpl::loadData(const Data &data, - const std::string &MIMEType, - const std::string &encoding, - const std::string &baseURL) { - - std::string dataString(reinterpret_cast(data.getBytes()), static_cast(data.getSize())); +void WebViewImpl::loadData(const Data& data, + std::string_view MIMEType, + std::string_view encoding, + std::string_view baseURL) +{ + + std::string dataString(reinterpret_cast(data.getBytes()), static_cast(data.getSize())); [_uiWebViewWrapper loadData:dataString MIMEType:MIMEType textEncodingName:encoding baseURL:baseURL]; } -void WebViewImpl::loadHTMLString(const std::string &string, const std::string &baseURL) { +void WebViewImpl::loadHTMLString(std::string_view string, std::string_view baseURL) +{ [_uiWebViewWrapper loadHTMLString:string baseURL:baseURL]; } -void WebViewImpl::loadURL(const std::string &url) { +void WebViewImpl::loadURL(std::string_view url) +{ this->loadURL(url, false); } -void WebViewImpl::loadURL(const std::string &url, bool cleanCachedData) { +void WebViewImpl::loadURL(std::string_view url, bool cleanCachedData) +{ [_uiWebViewWrapper loadUrl:url cleanCachedData:cleanCachedData]; } -void WebViewImpl::loadFile(const std::string &fileName) { +void WebViewImpl::loadFile(std::string_view fileName) +{ auto fullPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(fileName); [_uiWebViewWrapper loadFile:fullPath]; } -void WebViewImpl::stopLoading() { +void WebViewImpl::stopLoading() +{ [_uiWebViewWrapper stopLoading]; } -void WebViewImpl::reload() { +void WebViewImpl::reload() +{ [_uiWebViewWrapper reload]; } -bool WebViewImpl::canGoBack() { +bool WebViewImpl::canGoBack() +{ return _uiWebViewWrapper.canGoBack; } -bool WebViewImpl::canGoForward() { +bool WebViewImpl::canGoForward() +{ return _uiWebViewWrapper.canGoForward; } -void WebViewImpl::goBack() { +void WebViewImpl::goBack() +{ [_uiWebViewWrapper goBack]; } -void WebViewImpl::goForward() { +void WebViewImpl::goForward() +{ [_uiWebViewWrapper goForward]; } -void WebViewImpl::evaluateJS(const std::string &js) { +void WebViewImpl::evaluateJS(std::string_view js) +{ [_uiWebViewWrapper evaluateJS:js]; } -void WebViewImpl::setBounces(bool bounces) { +void WebViewImpl::setBounces(bool bounces) +{ [_uiWebViewWrapper setBounces:bounces]; } -void WebViewImpl::setScalesPageToFit(const bool scalesPageToFit) { +void WebViewImpl::setScalesPageToFit(const bool scalesPageToFit) +{ [_uiWebViewWrapper setScalesPageToFit:scalesPageToFit]; } -void WebViewImpl::draw(cocos2d::Renderer *renderer, cocos2d::Mat4 const &transform, uint32_t flags) { - if (flags & cocos2d::Node::FLAGS_TRANSFORM_DIRTY) { - - auto director = cocos2d::Director::getInstance(); - auto glView = director->getOpenGLView(); +void WebViewImpl::draw(cocos2d::Renderer* renderer, cocos2d::Mat4 const& transform, uint32_t flags) +{ + if (flags & cocos2d::Node::FLAGS_TRANSFORM_DIRTY) + { + + auto director = cocos2d::Director::getInstance(); + auto glView = director->getOpenGLView(); auto frameSize = glView->getFrameSize(); - - auto scaleFactor = [static_cast(glView->getEAGLView()) contentScaleFactor]; + + auto scaleFactor = [static_cast(glView->getEAGLView()) contentScaleFactor]; auto winSize = director->getWinSize(); auto leftBottom = this->_webView->convertToWorldSpace(cocos2d::Vec2::ZERO); - auto rightTop = this->_webView->convertToWorldSpace(cocos2d::Vec2(this->_webView->getContentSize().width, this->_webView->getContentSize().height)); + auto rightTop = this->_webView->convertToWorldSpace( + cocos2d::Vec2(this->_webView->getContentSize().width, this->_webView->getContentSize().height)); - auto x = (frameSize.width / 2 + (leftBottom.x - winSize.width / 2) * glView->getScaleX()) / scaleFactor; - auto y = (frameSize.height / 2 - (rightTop.y - winSize.height / 2) * glView->getScaleY()) / scaleFactor; - auto width = (rightTop.x - leftBottom.x) * glView->getScaleX() / scaleFactor; + auto x = (frameSize.width / 2 + (leftBottom.x - winSize.width / 2) * glView->getScaleX()) / scaleFactor; + auto y = (frameSize.height / 2 - (rightTop.y - winSize.height / 2) * glView->getScaleY()) / scaleFactor; + auto width = (rightTop.x - leftBottom.x) * glView->getScaleX() / scaleFactor; auto height = (rightTop.y - leftBottom.y) * glView->getScaleY() / scaleFactor; - [_uiWebViewWrapper setFrameWithX:x - y:y - width:width - height:height]; + [_uiWebViewWrapper setFrameWithX:x y:y width:width height:height]; } } -void WebViewImpl::setVisible(bool visible){ +void WebViewImpl::setVisible(bool visible) +{ [_uiWebViewWrapper setVisible:visible]; } - -void WebViewImpl::setOpacityWebView(float opacity){ - [_uiWebViewWrapper setOpacityWebView: opacity]; + +void WebViewImpl::setOpacityWebView(float opacity) +{ + [_uiWebViewWrapper setOpacityWebView:opacity]; } - -float WebViewImpl::getOpacityWebView() const{ + +float WebViewImpl::getOpacityWebView() const +{ return [_uiWebViewWrapper getOpacityWebView]; } -void WebViewImpl::setBackgroundTransparent(){ +void WebViewImpl::setBackgroundTransparent() +{ [_uiWebViewWrapper setBackgroundTransparent]; } - -} // namespace ui -} //namespace cocos2d +} // namespace ui +} // namespace cocos2d diff --git a/cocos/ui/UIWebView/UIWebViewImpl-win32.cpp b/cocos/ui/UIWebView/UIWebViewImpl-win32.cpp index 89ecd6d0522f..4ec42ecfb08d 100644 --- a/cocos/ui/UIWebView/UIWebViewImpl-win32.cpp +++ b/cocos/ui/UIWebView/UIWebViewImpl-win32.cpp @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 +#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 && defined(ADXE_HAVE_WEBVIEW2) # include "UIWebViewImpl-win32.h" # include "UIWebView.h" @@ -57,9 +57,9 @@ USING_NS_CC; using namespace rapidjson; -using msg_cb_t = std::function; +using msg_cb_t = std::function; -inline std::string htmlFromUri(const std::string& s) +inline std::string htmlFromUri(std::string_view s) { if (s.substr(0, 15) == "data:text/html,") { @@ -139,14 +139,14 @@ inline int jsonUnescape(const char* s, size_t n, char* out) // The following is a special case, where the exact json string is not returned due // to how rapidjson re-creates the nested object, original: "{"bar": 1}", parsed result: "{"bar":1}" // assert(jsonParse(R"({"foo": {"bar": 1}})", "foo", -1) == R"({"bar":1})"); -inline std::string jsonParse(const std::string& s, const std::string& key, const int index) +inline std::string jsonParse(std::string_view s, std::string_view key, const int index) { const char* value = nullptr; size_t value_sz{}; StringBuffer sb; Writer writer(sb); Document d; - d.Parse(s.c_str()); + d.Parse(s.data()); if (key.empty() && index > -1) { if (d.IsArray()) @@ -162,7 +162,7 @@ inline std::string jsonParse(const std::string& s, const std::string& key, const } else { - auto&& fieldItr = d.FindMember(key.c_str()); + auto&& fieldItr = d.FindMember(key.data()); if (fieldItr != d.MemberEnd()) { auto&& jsonValue = fieldItr->value; @@ -214,12 +214,12 @@ static std::string getUriStringFromArgs(ArgType* args) return {}; } -static std::string getDataURI(const std::string& data, const std::string& mime_type) +static std::string getDataURI(std::string_view data, std::string_view mime_type) { char* encodedData; cocos2d::base64Encode(reinterpret_cast(data.data()), static_cast(data.size()), &encodedData); - return "data:" + mime_type + ";base64," + utils::urlEncode(encodedData); + return std::string{"data:"}.append(mime_type).append(";base64,").append(utils::urlEncode(encodedData)); } static double getDeviceScaleFactor() @@ -250,24 +250,24 @@ class Win32WebControl public: Win32WebControl(); - bool createWebView(const std::function& shouldStartLoading, - const std::function& didFinishLoading, - const std::function& didFailLoading, - const std::function& onJsCallback); + bool createWebView(const std::function& shouldStartLoading, + const std::function& didFinishLoading, + const std::function& didFailLoading, + const std::function& onJsCallback); void removeWebView(); void setWebViewRect(const int left, const int top, const int width, const int height); - void setJavascriptInterfaceScheme(const std::string& scheme); - void loadHTMLString(const std::string& html, const std::string& baseURL); - void loadURL(const std::string& url, bool cleanCachedData); - void loadFile(const std::string& filePath); + void setJavascriptInterfaceScheme(std::string_view scheme); + void loadHTMLString(std::string_view html, std::string_view baseURL); + void loadURL(std::string_view url, bool cleanCachedData); + void loadFile(std::string_view filePath); void stopLoading(); void reload() const; bool canGoBack() const; bool canGoForward() const; void goBack() const; void goForward() const; - void evaluateJS(const std::string& js); + void evaluateJS(std::string_view js); void setScalesPageToFit(const bool scalesPageToFit); void setWebViewVisible(const bool visible) const; void setBounces(bool bounces); @@ -286,19 +286,19 @@ class Win32WebControl std::string m_jsScheme; bool _scalesPageToFit{}; - std::function _shouldStartLoading; - std::function _didFinishLoading; - std::function _didFailLoading; - std::function _onJsCallback; + std::function _shouldStartLoading; + std::function _didFinishLoading; + std::function _didFailLoading; + std::function _onJsCallback; static bool s_isInitialized; static void lazyInit(); - static LPWSTR to_lpwstr(const std::string s) + static LPWSTR to_lpwstr(std::string_view s) { - const int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, NULL, 0); + const int n = MultiByteToWideChar(CP_UTF8, 0, s.data(), -1, NULL, 0); auto* ws = new wchar_t[n]; - MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, ws, n); + MultiByteToWideChar(CP_UTF8, 0, s.data(), -1, ws, n); return ws; } @@ -325,7 +325,7 @@ class Win32WebControl m_webview->AddRef(); flag.clear(); }, - [this](const std::string& url) -> bool { + [this](std::string_view url) -> bool { const auto scheme = url.substr(0, url.find_first_of(':')); if (scheme == m_jsScheme) { @@ -358,7 +358,7 @@ class Win32WebControl if (_didFailLoading) _didFailLoading(result); }, - [this](const std::string& url) { loadURL(url, false); })); + [this](std::string_view url) { loadURL(url, false); })); if (res != S_OK) { @@ -386,28 +386,28 @@ class Win32WebControl m_controller->put_Bounds(bounds); } - void navigate(const std::string url) + void navigate(std::string_view url) { auto wurl = to_lpwstr(url); m_webview->Navigate(wurl); delete[] wurl; } - void init(const std::string js) + void init(std::string_view js) { LPCWSTR wjs = to_lpwstr(js); m_webview->AddScriptToExecuteOnDocumentCreated(wjs, nullptr); delete[] wjs; } - void eval(const std::string js) + void eval(std::string_view js) { LPCWSTR wjs = to_lpwstr(js); m_webview->ExecuteScript(wjs, nullptr); delete[] wjs; } - void on_message(const std::string msg) + void on_message(std::string_view msg) { const auto seq = jsonParse(msg, "id", 0); const auto name = jsonParse(msg, "method", 0); @@ -440,10 +440,10 @@ class Win32WebControl webview2_com_handler(HWND hwnd, msg_cb_t msgCb, webview2_com_handler_cb_t cb, - std::function navStartingCallback, + std::function navStartingCallback, std::function navCompleteCallback, std::function navErrorCallback, - std::function loadUrlCallback) + std::function loadUrlCallback) : m_window(hwnd) , m_msgCb(std::move(msgCb)) , m_cb(std::move(cb)) @@ -587,10 +587,10 @@ class Win32WebControl HWND m_window; msg_cb_t m_msgCb; webview2_com_handler_cb_t m_cb; - std::function m_navStartingCallback; + std::function m_navStartingCallback; std::function m_navCompleteCallback; std::function m_navErrorCallback; - std::function m_loadUrlCallback; + std::function m_loadUrlCallback; }; }; @@ -607,7 +607,7 @@ WebViewImpl::WebViewImpl(WebView* webView) : _createSucceeded(false), _systemWeb } _createSucceeded = _systemWebControl->createWebView( - [this](const std::string& url) -> bool { + [this](std::string_view url) -> bool { const auto shouldStartLoading = _webView->getOnShouldStartLoading(); if (shouldStartLoading != nullptr) { @@ -615,21 +615,21 @@ WebViewImpl::WebViewImpl(WebView* webView) : _createSucceeded(false), _systemWeb } return true; }, - [this](const std::string& url) { + [this](std::string_view url) { WebView::ccWebViewCallback didFinishLoading = _webView->getOnDidFinishLoading(); if (didFinishLoading != nullptr) { didFinishLoading(_webView, url); } }, - [this](const std::string& url) { + [this](std::string_view url) { WebView::ccWebViewCallback didFailLoading = _webView->getOnDidFailLoading(); if (didFailLoading != nullptr) { didFailLoading(_webView, url); } }, - [this](const std::string& url) { + [this](std::string_view url) { WebView::ccWebViewCallback onJsCallback = _webView->getOnJSCallback(); if (onJsCallback != nullptr) { @@ -649,9 +649,9 @@ WebViewImpl::~WebViewImpl() } void WebViewImpl::loadData(const Data& data, - const std::string& MIMEType, - const std::string& encoding, - const std::string& baseURL) + std::string_view MIMEType, + std::string_view encoding, + std::string_view baseURL) { if (_createSucceeded) { @@ -662,7 +662,7 @@ void WebViewImpl::loadData(const Data& data, } } -void WebViewImpl::loadHTMLString(const std::string& string, const std::string& baseURL) +void WebViewImpl::loadHTMLString(std::string_view string, std::string_view baseURL) { if (_createSucceeded) { @@ -684,7 +684,7 @@ void WebViewImpl::loadHTMLString(const std::string& string, const std::string& b } } -void WebViewImpl::loadURL(const std::string& url, bool cleanCachedData) +void WebViewImpl::loadURL(std::string_view url, bool cleanCachedData) { if (_createSucceeded) { @@ -692,7 +692,7 @@ void WebViewImpl::loadURL(const std::string& url, bool cleanCachedData) } } -void WebViewImpl::loadFile(const std::string& fileName) +void WebViewImpl::loadFile(std::string_view fileName) { if (_createSucceeded) { @@ -751,7 +751,7 @@ void WebViewImpl::goForward() } } -void WebViewImpl::setJavascriptInterfaceScheme(const std::string& scheme) +void WebViewImpl::setJavascriptInterfaceScheme(std::string_view scheme) { if (_createSucceeded) { @@ -759,7 +759,7 @@ void WebViewImpl::setJavascriptInterfaceScheme(const std::string& scheme) } } -void WebViewImpl::evaluateJS(const std::string& js) +void WebViewImpl::evaluateJS(std::string_view js) { if (_createSucceeded) { @@ -838,10 +838,10 @@ Win32WebControl::Win32WebControl() : _shouldStartLoading(nullptr), _didFinishLoa } } -bool Win32WebControl::createWebView(const std::function& shouldStartLoading, - const std::function& didFinishLoading, - const std::function& didFailLoading, - const std::function& onJsCallback) +bool Win32WebControl::createWebView(const std::function& shouldStartLoading, + const std::function& didFinishLoading, + const std::function& didFailLoading, + const std::function& onJsCallback) { bool ret = false; do @@ -905,7 +905,7 @@ bool Win32WebControl::createWebView(const std::functionput_ZoomFactor(_scalesPageToFit ? getDeviceScaleFactor() : 1.0); } -void Win32WebControl::setJavascriptInterfaceScheme(const std::string& scheme) +void Win32WebControl::setJavascriptInterfaceScheme(std::string_view scheme) { m_jsScheme = scheme; } -void Win32WebControl::loadHTMLString(const std::string& html, const std::string& baseURL) +void Win32WebControl::loadHTMLString(std::string_view html, std::string_view baseURL) { if (!html.empty()) { @@ -971,7 +971,7 @@ void Win32WebControl::loadHTMLString(const std::string& html, const std::string& } } -void Win32WebControl::loadURL(const std::string& url, bool cleanCachedData) +void Win32WebControl::loadURL(std::string_view url, bool cleanCachedData) { if (cleanCachedData) { @@ -980,7 +980,7 @@ void Win32WebControl::loadURL(const std::string& url, bool cleanCachedData) navigate(url); } -void Win32WebControl::loadFile(const std::string& filePath) +void Win32WebControl::loadFile(std::string_view filePath) { auto fullPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(filePath); if (fullPath.find("file:///") != 0) @@ -1029,7 +1029,7 @@ void Win32WebControl::goForward() const m_webview->GoForward(); } -void Win32WebControl::evaluateJS(const std::string& js) +void Win32WebControl::evaluateJS(std::string_view js) { eval(js); } diff --git a/cocos/ui/UIWebView/UIWebViewImpl-win32.h b/cocos/ui/UIWebView/UIWebViewImpl-win32.h index b963ba4a868a..4f56727d1756 100644 --- a/cocos/ui/UIWebView/UIWebViewImpl-win32.h +++ b/cocos/ui/UIWebView/UIWebViewImpl-win32.h @@ -28,7 +28,7 @@ #include "platform/CCPlatformConfig.h" -#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 +#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 && defined(ADXE_HAVE_WEBVIEW2) # include # include "CCStdC.h" @@ -58,21 +58,21 @@ class WebViewImpl WebViewImpl(cocos2d::ui::WebView* webView); virtual ~WebViewImpl(); - void setJavascriptInterfaceScheme(const std::string& scheme); + void setJavascriptInterfaceScheme(std::string_view scheme); void loadData(const cocos2d::Data& data, - const std::string& MIMEType, - const std::string& encoding, - const std::string& baseURL); - void loadHTMLString(const std::string& string, const std::string& baseURL); - void loadURL(const std::string& url, bool cleanCachedData); - void loadFile(const std::string& fileName); + std::string_view MIMEType, + std::string_view encoding, + std::string_view baseURL); + void loadHTMLString(std::string_view string, std::string_view baseURL); + void loadURL(std::string_view url, bool cleanCachedData); + void loadFile(std::string_view fileName); void stopLoading(); void reload(); bool canGoBack(); bool canGoForward(); void goBack(); void goForward(); - void evaluateJS(const std::string& js); + void evaluateJS(std::string_view js); void setScalesPageToFit(const bool scalesPageToFit); virtual void draw(cocos2d::Renderer* renderer, cocos2d::Mat4 const& transform, uint32_t flags); diff --git a/cocos/ui/UIWidget.h b/cocos/ui/UIWidget.h index 98e841c53863..29c9a3786fcd 100644 --- a/cocos/ui/UIWidget.h +++ b/cocos/ui/UIWidget.h @@ -684,25 +684,25 @@ class CC_GUI_DLL Widget : public ProtectedNode, public LayoutParameterProtocol * Set callback name. *@param callbackName A string representation of callback name. */ - void setCallbackName(const std::string& callbackName) { _callbackName = callbackName; } + void setCallbackName(std::string_view callbackName) { _callbackName = callbackName; } /** * Query callback name. *@return The callback name. */ - const std::string& getCallbackName() const { return _callbackName; } + std::string_view getCallbackName() const { return _callbackName; } /** * Set callback type. * @param callbackType A string representation of callback type. */ - void setCallbackType(const std::string& callbackType) { _callbackType = callbackType; } + void setCallbackType(std::string_view callbackType) { _callbackType = callbackType; } /** * Query callback type. *@return Callback type string. */ - const std::string& getCallbackType() const { return _callbackType; } + std::string_view getCallbackType() const { return _callbackType; } /** * Toggle layout component enable. diff --git a/extensions/DragonBones/CCArmatureDisplay.cpp b/extensions/DragonBones/CCArmatureDisplay.cpp index 5f11f16381d7..81c12b564e6c 100644 --- a/extensions/DragonBones/CCArmatureDisplay.cpp +++ b/extensions/DragonBones/CCArmatureDisplay.cpp @@ -1,4 +1,4 @@ -#include "CCArmatureDisplay.h" +#include "CCArmatureDisplay.h" #include "CCSlot.h" DRAGONBONES_NAMESPACE_BEGIN @@ -56,7 +56,7 @@ void CCArmatureDisplay::dbUpdate() } } -void CCArmatureDisplay::addDBEventListener(const std::string& type, const std::function& callback) +void CCArmatureDisplay::addDBEventListener(std::string_view type, const std::function& callback) { auto lambda = [callback](cocos2d::EventCustom* event) -> void { callback(static_cast(event->getUserData())); @@ -64,13 +64,12 @@ void CCArmatureDisplay::addDBEventListener(const std::string& type, const std::f _dispatcher->addCustomEventListener(type, lambda); } -void CCArmatureDisplay::dispatchDBEvent(const std::string& type, EventObject* value) +void CCArmatureDisplay::dispatchDBEvent(std::string_view type, EventObject* value) { _dispatcher->dispatchCustomEvent(type, value); } -void CCArmatureDisplay::removeDBEventListener(const std::string& type, - const std::function& callback) +void CCArmatureDisplay::removeDBEventListener(std::string_view type, const std::function& callback) { // TODO _dispatcher->removeCustomEventListeners(type); diff --git a/extensions/DragonBones/CCArmatureDisplay.h b/extensions/DragonBones/CCArmatureDisplay.h index 2e594a566c23..a055e6add01f 100644 --- a/extensions/DragonBones/CCArmatureDisplay.h +++ b/extensions/DragonBones/CCArmatureDisplay.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -83,20 +83,19 @@ class CCArmatureDisplay : public cocos2d::Node, public virtual IArmatureProxy /** * @inheritDoc */ - inline virtual bool hasDBEventListener(const std::string& type) const override { return _dispatcher->isEnabled(); } + inline virtual bool hasDBEventListener(std::string_view type) const override { return _dispatcher->isEnabled(); } /** * @inheritDoc */ - virtual void dispatchDBEvent(const std::string& type, EventObject* value) override; + virtual void dispatchDBEvent(std::string_view type, EventObject* value) override; /** * @inheritDoc */ - virtual void addDBEventListener(const std::string& type, - const std::function& listener) override; + virtual void addDBEventListener(std::string_view type, const std::function& listener) override; /** * @inheritDoc */ - virtual void removeDBEventListener(const std::string& type, + virtual void removeDBEventListener(std::string_view type, const std::function& listener) override; /** * @inheritDoc diff --git a/extensions/DragonBones/CCFactory.cpp b/extensions/DragonBones/CCFactory.cpp index 85c8565d040b..ee24fc555c92 100644 --- a/extensions/DragonBones/CCFactory.cpp +++ b/extensions/DragonBones/CCFactory.cpp @@ -1,4 +1,4 @@ -#include "CCFactory.h" +#include "CCFactory.h" #include "CCTextureAtlasData.h" #include "CCArmatureDisplay.h" #include "CCSlot.h" @@ -144,7 +144,7 @@ Slot* CCFactory::_buildSlot(const BuildArmaturePackage& dataPackage, const SlotD return slot; } -DragonBonesData* CCFactory::loadDragonBonesData(const std::string& filePath, const std::string& name, float scale) +DragonBonesData* CCFactory::loadDragonBonesData(std::string_view filePath, std::string_view name, float scale) { if (!name.empty()) { @@ -185,7 +185,7 @@ DragonBonesData* CCFactory::loadDragonBonesData(const std::string& filePath, con return nullptr; } -TextureAtlasData* CCFactory::loadTextureAtlasData(const std::string& filePath, const std::string& name, float scale) +TextureAtlasData* CCFactory::loadTextureAtlasData(std::string_view filePath, std::string_view name, float scale) { _prevPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(filePath); const auto data = cocos2d::FileUtils::getInstance()->getStringFromFile(_prevPath); @@ -197,10 +197,10 @@ TextureAtlasData* CCFactory::loadTextureAtlasData(const std::string& filePath, c return static_cast(BaseFactory::parseTextureAtlasData(data.c_str(), nullptr, name, scale)); } -CCArmatureDisplay* CCFactory::buildArmatureDisplay(const std::string& armatureName, - const std::string& dragonBonesName, - const std::string& skinName, - const std::string& textureAtlasName) const +CCArmatureDisplay* CCFactory::buildArmatureDisplay(std::string_view armatureName, + std::string_view dragonBonesName, + std::string_view skinName, + std::string_view textureAtlasName) const { const auto armature = buildArmature(armatureName, dragonBonesName, skinName, textureAtlasName); if (armature != nullptr) @@ -213,7 +213,7 @@ CCArmatureDisplay* CCFactory::buildArmatureDisplay(const std::string& armatureNa return nullptr; } -cocos2d::Sprite* CCFactory::getTextureDisplay(const std::string& textureName, const std::string& dragonBonesName) const +cocos2d::Sprite* CCFactory::getTextureDisplay(std::string_view textureName, std::string_view dragonBonesName) const { const auto textureData = static_cast(_getTextureData(dragonBonesName, textureName)); if (textureData != nullptr && textureData->spriteFrame != nullptr) diff --git a/extensions/DragonBones/CCFactory.h b/extensions/DragonBones/CCFactory.h index 4ffa18400803..d4fbfdc4eb4d 100644 --- a/extensions/DragonBones/CCFactory.h +++ b/extensions/DragonBones/CCFactory.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -102,9 +102,9 @@ class CCFactory : public BaseFactory Armature* armature) const override; public: - virtual DragonBonesData* loadDragonBonesData(const std::string& filePath, - const std::string& name = "", - float scale = 1.0f); + virtual DragonBonesData* loadDragonBonesData(std::string_view filePath, + std::string_view name = "", + float scale = 1.0f); /** * - Load and parse a texture atlas data and texture from the local and cache them to the factory. * @param filePath - The file path of texture atlas data. @@ -132,9 +132,9 @@ class CCFactory : public BaseFactory * * @language zh_CN */ - virtual TextureAtlasData* loadTextureAtlasData(const std::string& filePath, - const std::string& name = "", - float scale = 1.0f); + virtual TextureAtlasData* loadTextureAtlasData(std::string_view filePath, + std::string_view name = "", + float scale = 1.0f); /** * - Create a armature from cached DragonBonesData instances and TextureAtlasData instances, then use the {@link * #clock} to update it. The difference is that the armature created by {@link #buildArmature} is not WorldClock @@ -168,10 +168,10 @@ class CCFactory : public BaseFactory * * @language zh_CN */ - virtual CCArmatureDisplay* buildArmatureDisplay(const std::string& armatureName, - const std::string& dragonBonesName = "", - const std::string& skinName = "", - const std::string& textureAtlasName = "") const; + virtual CCArmatureDisplay* buildArmatureDisplay(std::string_view armatureName, + std::string_view dragonBonesName = "", + std::string_view skinName = "", + std::string_view textureAtlasName = "") const; /** * - Create the display object with the specified texture. * @param textureName - The texture data name. @@ -186,8 +186,8 @@ class CCFactory : public BaseFactory * @version DragonBones 3.0 * @language zh_CN */ - virtual cocos2d::Sprite* getTextureDisplay(const std::string& textureName, - const std::string& dragonBonesName = "") const; + virtual cocos2d::Sprite* getTextureDisplay(std::string_view textureName, + std::string_view dragonBonesName = "") const; /** * - A global sound event manager. * Sound events can be listened to uniformly from the manager. diff --git a/extensions/DragonBones/animation/Animation.cpp b/extensions/DragonBones/animation/Animation.cpp index 56de8389225a..20dd91bafd9a 100644 --- a/extensions/DragonBones/animation/Animation.cpp +++ b/extensions/DragonBones/animation/Animation.cpp @@ -1,4 +1,4 @@ -#include "Animation.h" +#include "Animation.h" #include "../model/DisplayData.h" #include "../model/AnimationConfig.h" #include "../model/AnimationData.h" @@ -216,7 +216,7 @@ void Animation::reset() _lastAnimationState = nullptr; } -void Animation::stop(const std::string& animationName) +void Animation::stop(std::string_view animationName) { if (!animationName.empty()) { @@ -384,7 +384,7 @@ AnimationState* Animation::playConfig(AnimationConfig* animationConfig) return animationState; } -AnimationState* Animation::play(const std::string& animationName, int playTimes) +AnimationState* Animation::play(std::string_view animationName, int playTimes) { _animationConfig->clear(); _animationConfig->resetToPose = true; @@ -418,18 +418,18 @@ AnimationState* Animation::play(const std::string& animationName, int playTimes) return _lastAnimationState; } #ifdef EGRET_WASM -AnimationState* Animation::fadeIn(const std::string& animationName, +AnimationState* Animation::fadeIn(std::string_view animationName, float fadeInTime, int playTimes, int layer, - const std::string& group, + std::string_view group, int fadeOutMode /*AnimationFadeOutMode*/ #else -AnimationState* Animation::fadeIn(const std::string& animationName, +AnimationState* Animation::fadeIn(std::string_view animationName, float fadeInTime, int playTimes, int layer, - const std::string& group, + std::string_view group, AnimationFadeOutMode fadeOutMode #endif // EGRET_WASM ) @@ -445,7 +445,7 @@ AnimationState* Animation::fadeIn(const std::string& animationName, return playConfig(_animationConfig); } -AnimationState* Animation::gotoAndPlayByTime(const std::string& animationName, float time, int playTimes) +AnimationState* Animation::gotoAndPlayByTime(std::string_view animationName, float time, int playTimes) { _animationConfig->clear(); _animationConfig->resetToPose = true; @@ -457,7 +457,7 @@ AnimationState* Animation::gotoAndPlayByTime(const std::string& animationName, f return playConfig(_animationConfig); } -AnimationState* Animation::gotoAndPlayByFrame(const std::string& animationName, unsigned frame, int playTimes) +AnimationState* Animation::gotoAndPlayByFrame(std::string_view animationName, unsigned frame, int playTimes) { _animationConfig->clear(); _animationConfig->resetToPose = true; @@ -474,7 +474,7 @@ AnimationState* Animation::gotoAndPlayByFrame(const std::string& animationName, return playConfig(_animationConfig); } -AnimationState* Animation::gotoAndPlayByProgress(const std::string& animationName, float progress, int playTimes) +AnimationState* Animation::gotoAndPlayByProgress(std::string_view animationName, float progress, int playTimes) { _animationConfig->clear(); _animationConfig->resetToPose = true; @@ -491,7 +491,7 @@ AnimationState* Animation::gotoAndPlayByProgress(const std::string& animationNam return playConfig(_animationConfig); } -AnimationState* Animation::gotoAndStopByTime(const std::string& animationName, float time) +AnimationState* Animation::gotoAndStopByTime(std::string_view animationName, float time) { const auto animationState = gotoAndPlayByTime(animationName, time, 1); if (animationState != nullptr) @@ -502,7 +502,7 @@ AnimationState* Animation::gotoAndStopByTime(const std::string& animationName, f return animationState; } -AnimationState* Animation::gotoAndStopByFrame(const std::string& animationName, unsigned frame) +AnimationState* Animation::gotoAndStopByFrame(std::string_view animationName, unsigned frame) { const auto animationState = gotoAndPlayByFrame(animationName, frame, 1); if (animationState != nullptr) @@ -513,7 +513,7 @@ AnimationState* Animation::gotoAndStopByFrame(const std::string& animationName, return animationState; } -AnimationState* Animation::gotoAndStopByProgress(const std::string& animationName, float progress) +AnimationState* Animation::gotoAndStopByProgress(std::string_view animationName, float progress) { const auto animationState = gotoAndPlayByProgress(animationName, progress, 1); if (animationState != nullptr) @@ -524,7 +524,7 @@ AnimationState* Animation::gotoAndStopByProgress(const std::string& animationNam return animationState; } -AnimationState* Animation::getState(const std::string& animationName) const +AnimationState* Animation::getState(std::string_view animationName) const { int i = _animationStates.size(); while (i--) @@ -539,7 +539,7 @@ AnimationState* Animation::getState(const std::string& animationName) const return nullptr; } -bool Animation::hasAnimation(const std::string& animationName) const +bool Animation::hasAnimation(std::string_view animationName) const { return _animations.find(animationName) != _animations.end(); } @@ -570,7 +570,7 @@ bool Animation::isCompleted() const return !_animationStates.empty(); } -const std::string& Animation::getLastAnimationName() const +std::string_view Animation::getLastAnimationName() const { if (_lastAnimationState != nullptr) { @@ -581,7 +581,7 @@ const std::string& Animation::getLastAnimationName() const return DEFAULT_NAME; } -void Animation::setAnimations(const std::map& value) +void Animation::setAnimations(const hlookup::string_map& value) { if (_animations == value) { diff --git a/extensions/DragonBones/animation/Animation.h b/extensions/DragonBones/animation/Animation.h index 33927b75ab66..524ade25fbd3 100644 --- a/extensions/DragonBones/animation/Animation.h +++ b/extensions/DragonBones/animation/Animation.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -64,7 +64,7 @@ class Animation final : public BaseObject float _inheritTimeScale; std::vector _animationNames; std::vector _animationStates; - std::map _animations; + hlookup::string_map _animations; Armature* _armature; AnimationConfig* _animationConfig; AnimationState* _lastAnimationState; @@ -115,7 +115,7 @@ class Animation final : public BaseObject * @version DragonBones 3.0 * @language zh_CN */ - void stop(const std::string& animationName); + void stop(std::string_view animationName); /** * - Play animation with a specific animation config. * The API is still in the experimental phase and may encounter bugs or stability or compatibility issues when used. @@ -166,7 +166,7 @@ class Animation final : public BaseObject * @version DragonBones 3.0 * @language zh_CN */ - AnimationState* play(const std::string& animationName = "", int playTimes = -1); + AnimationState* play(std::string_view animationName = "", int playTimes = -1); /** * - Fade in a specific animation. * @param animationName - The name of animation data. @@ -211,11 +211,11 @@ class Animation final : public BaseObject * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* fadeIn(const std::string& animationName, + AnimationState* fadeIn(std::string_view animationName, float fadeInTime = -1.f, int playTimes = -1, int layer = 0, - const std::string& group = "", + std::string_view group = "", AnimationFadeOutMode fadeOutMode = AnimationFadeOutMode::SameLayerAndGroup); /** * - Play a specific animation from the specific time. @@ -236,7 +236,7 @@ class Animation final : public BaseObject * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* gotoAndPlayByTime(const std::string& animationName, float time = 0.f, int playTimes = -1); + AnimationState* gotoAndPlayByTime(std::string_view animationName, float time = 0.f, int playTimes = -1); /** * - Play a specific animation from the specific frame. * @param animationName - The name of animation data. @@ -256,7 +256,7 @@ class Animation final : public BaseObject * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* gotoAndPlayByFrame(const std::string& animationName, unsigned frame = 0, int playTimes = -1); + AnimationState* gotoAndPlayByFrame(std::string_view animationName, unsigned frame = 0, int playTimes = -1); /** * - Play a specific animation from the specific progress. * @param animationName - The name of animation data. @@ -276,7 +276,7 @@ class Animation final : public BaseObject * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* gotoAndPlayByProgress(const std::string& animationName, float progress = 0.f, int playTimes = -1); + AnimationState* gotoAndPlayByProgress(std::string_view animationName, float progress = 0.f, int playTimes = -1); /** * - Stop a specific animation at the specific time. * @param animationName - The name of animation data. @@ -293,7 +293,7 @@ class Animation final : public BaseObject * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* gotoAndStopByTime(const std::string& animationName, float time = 0.f); + AnimationState* gotoAndStopByTime(std::string_view animationName, float time = 0.f); /** * - Stop a specific animation at the specific frame. * @param animationName - The name of animation data. @@ -310,7 +310,7 @@ class Animation final : public BaseObject * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* gotoAndStopByFrame(const std::string& animationName, unsigned frame = 0); + AnimationState* gotoAndStopByFrame(std::string_view animationName, unsigned frame = 0); /** * - Stop a specific animation at the specific progress. * @param animationName - The name of animation data. @@ -327,7 +327,7 @@ class Animation final : public BaseObject * @version DragonBones 4.5 * @language zh_CN */ - AnimationState* gotoAndStopByProgress(const std::string& animationName, float progress = 0.f); + AnimationState* gotoAndStopByProgress(std::string_view animationName, float progress = 0.f); /** * - Get a specific animation state. * @param animationName - The name of animation state. @@ -354,7 +354,7 @@ class Animation final : public BaseObject * @version DragonBones 3.0 * @language zh_CN */ - AnimationState* getState(const std::string& animationName) const; + AnimationState* getState(std::string_view animationName) const; /** * - Check whether a specific animation data is included. * @param animationName - The name of animation data. @@ -369,7 +369,7 @@ class Animation final : public BaseObject * @version DragonBones 3.0 * @language zh_CN */ - bool hasAnimation(const std::string& animationName) const; + bool hasAnimation(std::string_view animationName) const; /** * - Get all the animation states. * @version DragonBones 5.1 @@ -419,7 +419,7 @@ class Animation final : public BaseObject * @version DragonBones 3.0 * @language zh_CN */ - const std::string& getLastAnimationName() const; + std::string_view getLastAnimationName() const; /** * - The name of all animation data * @version DragonBones 4.5 @@ -441,8 +441,8 @@ class Animation final : public BaseObject * @version DragonBones 4.5 * @language zh_CN */ - inline const std::map& getAnimations() const { return _animations; } - void setAnimations(const std::map& value); + inline const hlookup::string_map& getAnimations() const { return _animations; } + void setAnimations(const hlookup::string_map& value); /** * - An AnimationConfig instance that can be used quickly. * @see dragonBones.AnimationConfig diff --git a/extensions/DragonBones/animation/AnimationState.cpp b/extensions/DragonBones/animation/AnimationState.cpp index 48274df1946b..0540ce842f2d 100644 --- a/extensions/DragonBones/animation/AnimationState.cpp +++ b/extensions/DragonBones/animation/AnimationState.cpp @@ -1,4 +1,4 @@ -#include "AnimationState.h" +#include "AnimationState.h" #include "WorldClock.h" #include "../model/DisplayData.h" #include "../model/AnimationConfig.h" @@ -83,7 +83,7 @@ void AnimationState::_onClear() void AnimationState::_updateTimelines() { { // Update constraint timelines. - std::map> constraintTimelines; + hlookup::string_map> constraintTimelines; for (const auto timeline : _constraintTimelines) // Create constraint timelines map. { constraintTimelines[timeline->constraint->getName()].push_back(timeline); @@ -137,7 +137,7 @@ void AnimationState::_updateTimelines() void AnimationState::_updateBoneAndSlotTimelines() { { // Update bone timelines. - std::map> boneTimelines; + hlookup::string_map> boneTimelines; for (const auto timeline : _boneTimelines) // Create bone timelines map. { boneTimelines[timeline->bone->getName()].push_back(timeline); @@ -238,7 +238,7 @@ void AnimationState::_updateBoneAndSlotTimelines() } { // Update slot timelines. - std::map> slotTimelines; + hlookup::string_map> slotTimelines; std::vector ffdFlags; for (const auto timeline : _slotTimelines) // Create slot timelines map. { @@ -745,12 +745,12 @@ void AnimationState::fadeOut(float fadeOutTime, bool pausePlayhead) _fadeTime = fadeTotalTime * (1.0f - _fadeProgress); } -bool AnimationState::containsBoneMask(const std::string& boneName) const +bool AnimationState::containsBoneMask(std::string_view boneName) const { return _boneMask.empty() || std::find(_boneMask.cbegin(), _boneMask.cend(), boneName) != _boneMask.cend(); } -void AnimationState::addBoneMask(const std::string& boneName, bool recursive) +void AnimationState::addBoneMask(std::string_view boneName, bool recursive) { const auto currentBone = _armature->getBone(boneName); if (currentBone == nullptr) @@ -760,7 +760,7 @@ void AnimationState::addBoneMask(const std::string& boneName, bool recursive) if (std::find(_boneMask.cbegin(), _boneMask.cend(), boneName) == _boneMask.cend()) { - _boneMask.push_back(boneName); + _boneMask.push_back(std::string{boneName}); } if (recursive) // Add recursive mixing. @@ -770,7 +770,7 @@ void AnimationState::addBoneMask(const std::string& boneName, bool recursive) if (std::find(_boneMask.cbegin(), _boneMask.cend(), bone->getName()) == _boneMask.cend() && currentBone->contains(bone)) { - _boneMask.push_back(bone->getName()); + _boneMask.push_back(std::string{bone->getName()}); } } } @@ -778,7 +778,7 @@ void AnimationState::addBoneMask(const std::string& boneName, bool recursive) _timelineDirty = 1; } -void AnimationState::removeBoneMask(const std::string& boneName, bool recursive) +void AnimationState::removeBoneMask(std::string_view boneName, bool recursive) { { auto iterator = std::find(_boneMask.begin(), _boneMask.end(), boneName); @@ -816,7 +816,7 @@ void AnimationState::removeBoneMask(const std::string& boneName, bool recursive) if (!currentBone->contains(bone)) { - _boneMask.push_back(bone->getName()); + _boneMask.push_back(std::string{bone->getName()}); } } } diff --git a/extensions/DragonBones/animation/AnimationState.h b/extensions/DragonBones/animation/AnimationState.h index a99da36f0e58..faf9d3ab1763 100644 --- a/extensions/DragonBones/animation/AnimationState.h +++ b/extensions/DragonBones/animation/AnimationState.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -251,7 +251,7 @@ class AnimationState : public BaseObject std::vector _slotTimelines; std::vector _constraintTimelines; std::vector> _poseTimelines; - std::map _bonePoses; + hlookup::string_map _bonePoses; Armature* _armature; ZOrderTimelineState* _zOrderTimeline; @@ -325,7 +325,7 @@ class AnimationState : public BaseObject * @version DragonBones 3.0 * @language zh_CN */ - bool containsBoneMask(const std::string& boneName) const; + bool containsBoneMask(std::string_view boneName) const; /** * - Add a specific bone mask. * @param boneName - The bone name. @@ -340,7 +340,7 @@ class AnimationState : public BaseObject * @version DragonBones 3.0 * @language zh_CN */ - void addBoneMask(const std::string& boneName, bool recursive = true); + void addBoneMask(std::string_view boneName, bool recursive = true); /** * - Remove the mask of a specific bone. * @param boneName - The bone name. @@ -355,7 +355,7 @@ class AnimationState : public BaseObject * @version DragonBones 3.0 * @language zh_CN */ - void removeBoneMask(const std::string& boneName, bool recursive = true); + void removeBoneMask(std::string_view boneName, bool recursive = true); /** * - Remove all bone masks. * @version DragonBones 3.0 @@ -456,7 +456,7 @@ class AnimationState : public BaseObject */ float getCurrentTime() const; void setCurrentTime(float value); - inline const std::string& getName() const { return name; } + inline std::string_view getName() const { return name; } /** * - The animation data. diff --git a/extensions/DragonBones/armature/Armature.cpp b/extensions/DragonBones/armature/Armature.cpp index 7e6cc57b9544..e4aabc2763d0 100644 --- a/extensions/DragonBones/armature/Armature.cpp +++ b/extensions/DragonBones/armature/Armature.cpp @@ -1,4 +1,4 @@ -#include "Armature.h" +#include "Armature.h" #include "../model/TextureAtlasData.h" #include "../model/UserData.h" #include "../animation/WorldClock.h" @@ -275,7 +275,7 @@ void Armature::advanceTime(float passedTime) _proxy->dbUpdate(); } -void Armature::invalidUpdate(const std::string& boneName, bool updateSlot) +void Armature::invalidUpdate(std::string_view boneName, bool updateSlot) { if (!boneName.empty()) { @@ -431,7 +431,7 @@ Slot* Armature::intersectsSegment(float xA, return intSlotA; } -Bone* Armature::getBone(const std::string& name) const +Bone* Armature::getBone(std::string_view name) const { for (const auto& bone : _bones) { @@ -451,7 +451,7 @@ Bone* Armature::getBoneByDisplay(void* display) const return slot != nullptr ? slot->getParent() : nullptr; } -Slot* Armature::getSlot(const std::string& name) const +Slot* Armature::getSlot(std::string_view name) const { for (const auto slot : _slots) { diff --git a/extensions/DragonBones/armature/Armature.h b/extensions/DragonBones/armature/Armature.h index 6f6f5f7bbecb..c78d0fe9a232 100644 --- a/extensions/DragonBones/armature/Armature.h +++ b/extensions/DragonBones/armature/Armature.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -201,7 +201,7 @@ class Armature : public virtual IAnimatable, public BaseObject * @version DragonBones 3.0 * @language zh_CN */ - void invalidUpdate(const std::string& boneName = "", bool updateSlot = false); + void invalidUpdate(std::string_view boneName = "", bool updateSlot = false); /** * - Check whether a specific point is inside a custom bounding box in a slot. * The coordinate system of the point is the inner coordinate system of the armature. @@ -278,7 +278,7 @@ class Armature : public virtual IAnimatable, public BaseObject * @version DragonBones 3.0 * @language zh_CN */ - Bone* getBone(const std::string& name) const; + Bone* getBone(std::string_view name) const; /** * - Get a specific bone by the display. * @param display - The display object. @@ -308,7 +308,7 @@ class Armature : public virtual IAnimatable, public BaseObject * @version DragonBones 3.0 * @language zh_CN */ - Slot* getSlot(const std::string& name) const; + Slot* getSlot(std::string_view name) const; /** * - Get a specific slot by the display. * @param display - The display object. @@ -426,7 +426,7 @@ class Armature : public virtual IAnimatable, public BaseObject * @version DragonBones 3.0 * @language zh_CN */ - inline const std::string& getName() const { return _armatureData->name; } + inline std::string_view getName() const { return _armatureData->name; } /** * - The armature data. * @see dragonBones.ArmatureData diff --git a/extensions/DragonBones/armature/Bone.h b/extensions/DragonBones/armature/Bone.h index cba7c2d65068..3541143b0b58 100644 --- a/extensions/DragonBones/armature/Bone.h +++ b/extensions/DragonBones/armature/Bone.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -198,7 +198,7 @@ class Bone final : public TransformObject * @version DragonBones 3.0 * @language zh_CN */ - inline const std::string& getName() const { return _boneData->name; } + inline std::string_view getName() const { return _boneData->name; } /** * - The parent bone to which it belongs. * @version DragonBones 3.0 diff --git a/extensions/DragonBones/armature/Constraint.h b/extensions/DragonBones/armature/Constraint.h index 92ba6e9f5041..99d38b15ec14 100644 --- a/extensions/DragonBones/armature/Constraint.h +++ b/extensions/DragonBones/armature/Constraint.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -75,7 +75,7 @@ class Constraint : public BaseObject virtual void update() = 0; virtual void invalidUpdate() = 0; - inline const std::string& getName() { return _constraintData->name; } + inline std::string_view getName() { return _constraintData->name; } }; /** * @internal diff --git a/extensions/DragonBones/armature/Slot.h b/extensions/DragonBones/armature/Slot.h index 234e2f79c687..6700737b08b9 100644 --- a/extensions/DragonBones/armature/Slot.h +++ b/extensions/DragonBones/armature/Slot.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -343,7 +343,7 @@ class Slot : public TransformObject * @version DragonBones 3.0 * @language zh_CN */ - inline const std::string& getName() const { return _slotData->name; } + inline std::string_view getName() const { return _slotData->name; } /** * - Contains a display list of display objects or child armatures. * @version DragonBones 3.0 diff --git a/extensions/DragonBones/core/DragonBones.h b/extensions/DragonBones/core/DragonBones.h index 9ddab3b97aaf..336357fecfbd 100644 --- a/extensions/DragonBones/core/DragonBones.h +++ b/extensions/DragonBones/core/DragonBones.h @@ -33,6 +33,7 @@ #include #include #include +#include "base/hlookup.h" // dragonBones assert #define DRAGONBONES_ASSERT(cond, msg) \ do \ @@ -359,15 +360,15 @@ inline int indexOf(const std::vector& vector, const T& value) return -1; } -template -inline T* mapFind(const std::map& map, const std::string& key) +template +inline auto mapFind(Cont& map, std::string_view key) { auto iterator = map.find(key); return (iterator != map.end()) ? iterator->second : nullptr; } -template -inline T* mapFindB(std::map& map, const std::string& key) +template +inline auto mapFindB(Cont& map, std::string_view key) { auto iterator = map.find(key); return (iterator != map.end()) ? &iterator->second : nullptr; diff --git a/extensions/DragonBones/event/IEventDispatcher.h b/extensions/DragonBones/event/IEventDispatcher.h index ded91d92db61..26476941ee3a 100644 --- a/extensions/DragonBones/event/IEventDispatcher.h +++ b/extensions/DragonBones/event/IEventDispatcher.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -56,7 +56,7 @@ class IEventDispatcher * @version DragonBones 4.5 * @language zh_CN */ - virtual bool hasDBEventListener(const std::string& type) const = 0; + virtual bool hasDBEventListener(std::string_view type) const = 0; /** * - Dispatches an event into the event flow. * @param type - Event type. @@ -73,7 +73,7 @@ class IEventDispatcher * @version DragonBones 4.5 * @language zh_CN */ - virtual void dispatchDBEvent(const std::string& type, EventObject* value) = 0; + virtual void dispatchDBEvent(std::string_view type, EventObject* value) = 0; /** * - Add an event listener object so that the listener receives notification of an event. * @param type - Event type. @@ -90,7 +90,7 @@ class IEventDispatcher * @version DragonBones 4.5 * @language zh_CN */ - virtual void addDBEventListener(const std::string& type, const std::function& listener) = 0; + virtual void addDBEventListener(std::string_view type, const std::function& listener) = 0; /** * - Removes a listener from the object. * @param type - Event type. @@ -107,7 +107,7 @@ class IEventDispatcher * @version DragonBones 4.5 * @language zh_CN */ - virtual void removeDBEventListener(const std::string& type, const std::function& listener) = 0; + virtual void removeDBEventListener(std::string_view type, const std::function& listener) = 0; }; DRAGONBONES_NAMESPACE_END diff --git a/extensions/DragonBones/factory/BaseFactory.cpp b/extensions/DragonBones/factory/BaseFactory.cpp index c7eb5242e242..afa0b9fa13c4 100644 --- a/extensions/DragonBones/factory/BaseFactory.cpp +++ b/extensions/DragonBones/factory/BaseFactory.cpp @@ -1,11 +1,11 @@ -#include "BaseFactory.h" +#include "BaseFactory.h" DRAGONBONES_NAMESPACE_BEGIN JSONDataParser BaseFactory::_jsonParser; BinaryDataParser BaseFactory::_binaryParser; -TextureData* BaseFactory::_getTextureData(const std::string& textureAtlasName, const std::string& textureName) const +TextureData* BaseFactory::_getTextureData(std::string_view textureAtlasName, std::string_view textureName) const { const auto iterator = _textureAtlasDataMap.find(textureAtlasName); if (iterator != _textureAtlasDataMap.end()) @@ -42,12 +42,12 @@ TextureData* BaseFactory::_getTextureData(const std::string& textureAtlasName, c } bool BaseFactory::_fillBuildArmaturePackage(BuildArmaturePackage& dataPackage, - const std::string& dragonBonesName, - const std::string& armatureName, - const std::string& skinName, - const std::string& textureAtlasName) const + std::string_view dragonBonesName, + std::string_view armatureName, + std::string_view skinName, + std::string_view textureAtlasName) const { - std::string mapName = dragonBonesName; + auto mapName = dragonBonesName; DragonBonesData* dragonBonesData = nullptr; ArmatureData* armatureData = nullptr; @@ -141,7 +141,7 @@ void BaseFactory::_buildSlots(const BuildArmaturePackage& dataPackage, Armature* return; } - std::map*> skinSlots; + hlookup::string_map*> skinSlots; for (auto& pair : defaultSkin->displays) { auto& displays = pair.second; @@ -309,7 +309,7 @@ std::pair BaseFactory::_getSlotDisplay(const BuildArmaturePa return display; } -DragonBonesData* BaseFactory::parseDragonBonesData(const char* rawData, const std::string& name, float scale) +DragonBonesData* BaseFactory::parseDragonBonesData(const char* rawData, std::string_view name, float scale) { DRAGONBONES_ASSERT(rawData != nullptr, ""); @@ -350,7 +350,7 @@ DragonBonesData* BaseFactory::parseDragonBonesData(const char* rawData, const st TextureAtlasData* BaseFactory::parseTextureAtlasData(const char* rawData, void* textureAtlas, - const std::string& name, + std::string_view name, float scale) { const auto textureAtlasData = _buildTextureAtlasData(nullptr, nullptr); @@ -361,7 +361,7 @@ TextureAtlasData* BaseFactory::parseTextureAtlasData(const char* rawData, return textureAtlasData; } -void BaseFactory::addDragonBonesData(DragonBonesData* data, const std::string& name) +void BaseFactory::addDragonBonesData(DragonBonesData* data, std::string_view name) { const auto& mapName = !name.empty() ? name : data->name; if (_dragonBonesDataMap.find(mapName) != _dragonBonesDataMap.cend()) @@ -378,7 +378,7 @@ void BaseFactory::addDragonBonesData(DragonBonesData* data, const std::string& n _dragonBonesDataMap[mapName] = data; } -void BaseFactory::removeDragonBonesData(const std::string& name, bool disposeData) +void BaseFactory::removeDragonBonesData(std::string_view name, bool disposeData) { const auto iterator = _dragonBonesDataMap.find(name); if (iterator != _dragonBonesDataMap.cend()) @@ -392,7 +392,7 @@ void BaseFactory::removeDragonBonesData(const std::string& name, bool disposeDat } } -void BaseFactory::addTextureAtlasData(TextureAtlasData* data, const std::string& name) +void BaseFactory::addTextureAtlasData(TextureAtlasData* data, std::string_view name) { const auto& mapName = !name.empty() ? name : data->name; auto& textureAtlasList = _textureAtlasDataMap[mapName]; @@ -402,7 +402,7 @@ void BaseFactory::addTextureAtlasData(TextureAtlasData* data, const std::string& } } -void BaseFactory::removeTextureAtlasData(const std::string& name, bool disposeData) +void BaseFactory::removeTextureAtlasData(std::string_view name, bool disposeData) { const auto iterator = _textureAtlasDataMap.find(name); if (iterator != _textureAtlasDataMap.end()) @@ -419,7 +419,7 @@ void BaseFactory::removeTextureAtlasData(const std::string& name, bool disposeDa } } -ArmatureData* BaseFactory::getArmatureData(const std::string& name, const std::string& dragonBonesName) const +ArmatureData* BaseFactory::getArmatureData(std::string_view name, std::string_view dragonBonesName) const { BuildArmaturePackage dataPackage; if (!_fillBuildArmaturePackage(dataPackage, dragonBonesName, name, "", "")) @@ -452,10 +452,10 @@ void BaseFactory::clear(bool disposeData) _textureAtlasDataMap.clear(); } -Armature* BaseFactory::buildArmature(const std::string& armatureName, - const std::string& dragonBonesName, - const std::string& skinName, - const std::string& textureAtlasName) const +Armature* BaseFactory::buildArmature(std::string_view armatureName, + std::string_view dragonBonesName, + std::string_view skinName, + std::string_view textureAtlasName) const { BuildArmaturePackage dataPackage; if (!_fillBuildArmaturePackage(dataPackage, dragonBonesName, armatureName, skinName, textureAtlasName)) @@ -512,10 +512,10 @@ void BaseFactory::replaceDisplay(Slot* slot, DisplayData* displayData, int displ slot->setDisplayList(displayList); } -bool BaseFactory::replaceSlotDisplay(const std::string& dragonBonesName, - const std::string& armatureName, - const std::string& slotName, - const std::string& displayName, +bool BaseFactory::replaceSlotDisplay(std::string_view dragonBonesName, + std::string_view armatureName, + std::string_view slotName, + std::string_view displayName, Slot* slot, int displayIndex) const { @@ -538,9 +538,9 @@ bool BaseFactory::replaceSlotDisplay(const std::string& dragonBonesName, return true; } -bool BaseFactory::replaceSlotDisplayList(const std::string& dragonBonesName, - const std::string& armatureName, - const std::string& slotName, +bool BaseFactory::replaceSlotDisplayList(std::string_view dragonBonesName, + std::string_view armatureName, + std::string_view slotName, Slot* slot) const { DRAGONBONES_ASSERT(slot, "Arguments error."); diff --git a/extensions/DragonBones/factory/BaseFactory.h b/extensions/DragonBones/factory/BaseFactory.h index 8d9329d57982..dcd8d8d3348e 100644 --- a/extensions/DragonBones/factory/BaseFactory.h +++ b/extensions/DragonBones/factory/BaseFactory.h @@ -68,8 +68,8 @@ class BaseFactory bool autoSearch; protected: - std::map _dragonBonesDataMap; - std::map> _textureAtlasDataMap; + hlookup::string_map _dragonBonesDataMap; + hlookup::string_map> _textureAtlasDataMap; DragonBones* _dragonBones; DataParser* _dataParser; @@ -99,12 +99,12 @@ class BaseFactory protected: virtual inline bool _isSupportMesh() const { return true; } - virtual TextureData* _getTextureData(const std::string& textureAtlasName, const std::string& textureName) const; + virtual TextureData* _getTextureData(std::string_view textureAtlasName, std::string_view textureName) const; virtual bool _fillBuildArmaturePackage(BuildArmaturePackage& dataPackage, - const std::string& dragonBonesName, - const std::string& armatureName, - const std::string& skinName, - const std::string& textureAtlasName) const; + std::string_view dragonBonesName, + std::string_view armatureName, + std::string_view skinName, + std::string_view textureAtlasName) const; virtual void _buildBones(const BuildArmaturePackage& dataPackage, Armature* armature) const; /** * @private @@ -151,9 +151,7 @@ class BaseFactory * @version DragonBones 4.5 * @language zh_CN */ - virtual DragonBonesData* parseDragonBonesData(const char* rawData, - const std::string& name = "", - float scale = 1.0f); + virtual DragonBonesData* parseDragonBonesData(const char* rawData, std::string_view name = "", float scale = 1.0f); /** * - Parse the raw texture atlas data and the texture atlas object to a TextureAtlasData instance and cache it to * the factory. @@ -186,8 +184,8 @@ class BaseFactory */ virtual TextureAtlasData* parseTextureAtlasData(const char* rawData, void* textureAtlas, - const std::string& name = "", - float scale = 1.0f); + std::string_view name = "", + float scale = 1.0f); /** * - Get a specific DragonBonesData instance. * @param name - The DragonBonesData instance cache name. @@ -210,7 +208,7 @@ class BaseFactory * @version DragonBones 3.0 * @language zh_CN */ - inline DragonBonesData* getDragonBonesData(const std::string& name) const + inline DragonBonesData* getDragonBonesData(std::string_view name) const { return mapFind(_dragonBonesDataMap, name); } @@ -237,7 +235,7 @@ class BaseFactory * @version DragonBones 3.0 * @language zh_CN */ - virtual void addDragonBonesData(DragonBonesData* data, const std::string& name = ""); + virtual void addDragonBonesData(DragonBonesData* data, std::string_view name = ""); /** * - Remove a DragonBonesData instance. * @param name - The DragonBonesData instance cache name. @@ -260,7 +258,7 @@ class BaseFactory * @version DragonBones 3.0 * @language zh_CN */ - virtual void removeDragonBonesData(const std::string& name, bool disposeData = true); + virtual void removeDragonBonesData(std::string_view name, bool disposeData = true); /** * - Get a list of specific TextureAtlasData instances. * @param name - The TextureAtlasData cahce name. @@ -281,7 +279,7 @@ class BaseFactory * @version DragonBones 3.0 * @language zh_CN */ - inline std::vector* getTextureAtlasData(const std::string& name) + inline std::vector* getTextureAtlasData(std::string_view name) { return mapFindB(_textureAtlasDataMap, name); } @@ -308,7 +306,7 @@ class BaseFactory * @version DragonBones 3.0 * @language zh_CN */ - virtual void addTextureAtlasData(TextureAtlasData* data, const std::string& name = ""); + virtual void addTextureAtlasData(TextureAtlasData* data, std::string_view name = ""); /** * - Remove a TextureAtlasData instance. * @param name - The TextureAtlasData instance cache name. @@ -331,7 +329,7 @@ class BaseFactory * @version DragonBones 3.0 * @language zh_CN */ - virtual void removeTextureAtlasData(const std::string& name, bool disposeData = true); + virtual void removeTextureAtlasData(std::string_view name, bool disposeData = true); /** * - Get a specific armature data. * @param name - The armature data name. @@ -348,7 +346,7 @@ class BaseFactory * @version DragonBones 5.1 * @language zh_CN */ - virtual ArmatureData* getArmatureData(const std::string& name, const std::string& dragonBonesName = "") const; + virtual ArmatureData* getArmatureData(std::string_view name, std::string_view dragonBonesName = "") const; /** * - Clear all cached DragonBonesData instances and TextureAtlasData instances. * @param disposeData - Whether to dispose data. @@ -403,10 +401,10 @@ class BaseFactory * @version DragonBones 3.0 * @language zh_CN */ - virtual Armature* buildArmature(const std::string& armatureName, - const std::string& dragonBonesName = "", - const std::string& skinName = "", - const std::string& textureAtlasName = "") const; + virtual Armature* buildArmature(std::string_view armatureName, + std::string_view dragonBonesName = "", + std::string_view skinName = "", + std::string_view textureAtlasName = "") const; /** * @private */ @@ -448,18 +446,18 @@ class BaseFactory * @version DragonBones 4.5 * @language zh_CN */ - virtual bool replaceSlotDisplay(const std::string& dragonBonesName, - const std::string& armatureName, - const std::string& slotName, - const std::string& displayName, + virtual bool replaceSlotDisplay(std::string_view dragonBonesName, + std::string_view armatureName, + std::string_view slotName, + std::string_view displayName, Slot* slot, int displayIndex = -1) const; /** * @private */ - virtual bool replaceSlotDisplayList(const std::string& dragonBonesName, - const std::string& armatureName, - const std::string& slotName, + virtual bool replaceSlotDisplayList(std::string_view dragonBonesName, + std::string_view armatureName, + std::string_view slotName, Slot* slot) const; /** * - Share specific skin data with specific armature. @@ -550,14 +548,14 @@ class BaseFactory /** * @private */ - inline const std::map>& getAllTextureAtlasData() const + inline const hlookup::string_map>& getAllTextureAtlasData() const { return _textureAtlasDataMap; } /** * @private */ - inline const std::map& getAllDragonBonesData() const { return _dragonBonesDataMap; } + inline const hlookup::string_map& getAllDragonBonesData() const { return _dragonBonesDataMap; } /** * - An Worldclock instance updated by engine. * @version DragonBones 5.7 diff --git a/extensions/DragonBones/model/AnimationConfig.cpp b/extensions/DragonBones/model/AnimationConfig.cpp index 26d198f630dd..8ee7dac7d60c 100644 --- a/extensions/DragonBones/model/AnimationConfig.cpp +++ b/extensions/DragonBones/model/AnimationConfig.cpp @@ -1,4 +1,4 @@ -#include "AnimationConfig.h" +#include "AnimationConfig.h" #include "../armature/Armature.h" #include "../armature/Bone.h" @@ -63,12 +63,12 @@ void AnimationConfig::copyFrom(AnimationConfig* value) boneMask = value->boneMask; } -bool AnimationConfig::containsBoneMask(const std::string& boneName) const +bool AnimationConfig::containsBoneMask(std::string_view boneName) const { return boneMask.empty() || std::find(boneMask.cbegin(), boneMask.cend(), boneName) != boneMask.cend(); } -void AnimationConfig::addBoneMask(Armature* armature, const std::string& boneName, bool recursive) +void AnimationConfig::addBoneMask(Armature* armature, std::string_view boneName, bool recursive) { const auto currentBone = armature->getBone(boneName); if (currentBone == nullptr) @@ -78,7 +78,7 @@ void AnimationConfig::addBoneMask(Armature* armature, const std::string& boneNam if (std::find(boneMask.cbegin(), boneMask.cend(), boneName) == boneMask.cend()) // Add mixing { - boneMask.push_back(boneName); + boneMask.push_back(std::string{boneName}); } if (recursive) // Add recursive mixing. @@ -88,13 +88,13 @@ void AnimationConfig::addBoneMask(Armature* armature, const std::string& boneNam if (std::find(boneMask.cbegin(), boneMask.cend(), bone->getName()) == boneMask.cend() && currentBone->contains(bone)) { - boneMask.push_back(bone->getName()); + boneMask.push_back(std::string{bone->getName()}); } } } } -void AnimationConfig::removeBoneMask(Armature* armature, const std::string& boneName, bool recursive) +void AnimationConfig::removeBoneMask(Armature* armature, std::string_view boneName, bool recursive) { { auto iterator = std::find(boneMask.begin(), boneMask.end(), boneName); @@ -131,7 +131,7 @@ void AnimationConfig::removeBoneMask(Armature* armature, const std::string& bone if (!currentBone->contains(bone)) { - boneMask.push_back(bone->getName()); + boneMask.push_back(std::string{bone->getName()}); } } } diff --git a/extensions/DragonBones/model/AnimationConfig.h b/extensions/DragonBones/model/AnimationConfig.h index c53fe730c14a..dd90b4e7c817 100644 --- a/extensions/DragonBones/model/AnimationConfig.h +++ b/extensions/DragonBones/model/AnimationConfig.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -296,15 +296,15 @@ class AnimationConfig : public BaseObject /** * @private */ - bool containsBoneMask(const std::string& boneName) const; + bool containsBoneMask(std::string_view boneName) const; /** * @private */ - void addBoneMask(Armature* armature, const std::string& boneName, bool recursive); + void addBoneMask(Armature* armature, std::string_view boneName, bool recursive); /** * @private */ - void removeBoneMask(Armature* armature, const std::string& boneName, bool recursive); + void removeBoneMask(Armature* armature, std::string_view boneName, bool recursive); public: // For WebAssembly. int getFadeOutMode() const { return (int)fadeOutMode; } diff --git a/extensions/DragonBones/model/AnimationData.h b/extensions/DragonBones/model/AnimationData.h index 8d7a37708ea4..64e7be54df46 100644 --- a/extensions/DragonBones/model/AnimationData.h +++ b/extensions/DragonBones/model/AnimationData.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -126,23 +126,23 @@ class AnimationData : public BaseObject /** * @private */ - std::map> boneTimelines; + hlookup::string_map> boneTimelines; /** * @private */ - std::map> slotTimelines; + hlookup::string_map> slotTimelines; /** * @private */ - std::map> constraintTimelines; + hlookup::string_map> constraintTimelines; /** * @private */ - std::map> boneCachedFrameIndices; + hlookup::string_map> boneCachedFrameIndices; /** * @private */ - std::map> slotCachedFrameIndices; + hlookup::string_map> slotCachedFrameIndices; /** * @private */ @@ -181,35 +181,35 @@ class AnimationData : public BaseObject /** * @private */ - std::vector* getBoneTimelines(const std::string& timelineName) + std::vector* getBoneTimelines(std::string_view timelineName) { return mapFindB(boneTimelines, timelineName); } /** * @private */ - inline std::vector* getSlotTimelines(const std::string& timelineName) + inline std::vector* getSlotTimelines(std::string_view timelineName) { return mapFindB(slotTimelines, timelineName); } /** * @private */ - inline std::vector* getConstraintTimelines(const std::string& timelineName) + inline std::vector* getConstraintTimelines(std::string_view timelineName) { return mapFindB(constraintTimelines, timelineName); } /** * @private */ - inline std::vector* getBoneCachedFrameIndices(const std::string& boneName) + inline std::vector* getBoneCachedFrameIndices(std::string_view boneName) { return mapFindB(boneCachedFrameIndices, boneName); } /** * @private */ - inline std::vector* getSlotCachedFrameIndices(const std::string& slotName) + inline std::vector* getSlotCachedFrameIndices(std::string_view slotName) { return mapFindB(slotCachedFrameIndices, slotName); } diff --git a/extensions/DragonBones/model/ArmatureData.cpp b/extensions/DragonBones/model/ArmatureData.cpp index 9cc86af721c4..66f9dfca75d5 100644 --- a/extensions/DragonBones/model/ArmatureData.cpp +++ b/extensions/DragonBones/model/ArmatureData.cpp @@ -1,4 +1,4 @@ -#include "ArmatureData.h" +#include "ArmatureData.h" #include "UserData.h" #include "DragonBonesData.h" #include "ConstraintData.h" @@ -264,9 +264,9 @@ void ArmatureData::addAction(ActionData* value, bool isDefault) } } -MeshDisplayData* ArmatureData::getMesh(const std::string& skinName, - const std::string& slotName, - const std::string& meshName) const +MeshDisplayData* ArmatureData::getMesh(std::string_view skinName, + std::string_view slotName, + std::string_view meshName) const { const auto skin = getSkin(skinName); if (skin == nullptr) diff --git a/extensions/DragonBones/model/ArmatureData.h b/extensions/DragonBones/model/ArmatureData.h index 838df4adb7b8..7c39c718bb55 100644 --- a/extensions/DragonBones/model/ArmatureData.h +++ b/extensions/DragonBones/model/ArmatureData.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -113,23 +113,23 @@ class ArmatureData : public BaseObject /** * @private */ - std::map bones; + hlookup::string_map bones; /** * @private */ - std::map slots; + hlookup::string_map slots; /** * @private */ - std::map constraints; + hlookup::string_map constraints; /** * @private */ - std::map skins; + hlookup::string_map skins; /** * @private */ - std::map animations; + hlookup::string_map animations; /** * - The default skin data. * @version DragonBones 4.5 @@ -223,7 +223,7 @@ class ArmatureData : public BaseObject * @version DragonBones 3.0 * @language zh_CN */ - inline BoneData* getBone(const std::string& boneName) const { return mapFind(bones, boneName); } + inline BoneData* getBone(std::string_view boneName) const { return mapFind(bones, boneName); } /** * - Get a specific slot data. * @param slotName - The slot name. @@ -236,13 +236,13 @@ class ArmatureData : public BaseObject * @version DragonBones 3.0 * @language zh_CN */ - inline SlotData* getSlot(const std::string& slotName) const { return mapFind(slots, slotName); } + inline SlotData* getSlot(std::string_view slotName) const { return mapFind(slots, slotName); } /** * @private */ - inline ConstraintData* getConstraint(const std::string& constraintName) const + inline ConstraintData* getConstraint(std::string_view constraintName) const { - return mapFind(constraints, constraintName); + return mapFind(constraints, constraintName); } /** * - Get a specific skin data. @@ -256,13 +256,11 @@ class ArmatureData : public BaseObject * @version DragonBones 3.0 * @language zh_CN */ - inline SkinData* getSkin(const std::string& skinName) const { return mapFind(skins, skinName); } + inline SkinData* getSkin(std::string_view skinName) const { return mapFind(skins, skinName); } /** * @private */ - MeshDisplayData* getMesh(const std::string& skinName, - const std::string& slotName, - const std::string& meshName) const; + MeshDisplayData* getMesh(std::string_view skinName, std::string_view slotName, std::string_view meshName) const; /** * - Get a specific animation data. * @param animationName - The animation animationName. @@ -275,7 +273,7 @@ class ArmatureData : public BaseObject * @version DragonBones 3.0 * @language zh_CN */ - inline AnimationData* getAnimation(const std::string& animationName) const + inline AnimationData* getAnimation(std::string_view animationName) const { return mapFind(animations, animationName); } diff --git a/extensions/DragonBones/model/DragonBonesData.h b/extensions/DragonBones/model/DragonBonesData.h index eef82b2b87e2..539d34896f6b 100644 --- a/extensions/DragonBones/model/DragonBonesData.h +++ b/extensions/DragonBones/model/DragonBonesData.h @@ -107,7 +107,7 @@ class DragonBonesData : public BaseObject /** * @private */ - std::map armatures; + hlookup::string_map armatures; /** * @internal */ @@ -158,10 +158,7 @@ class DragonBonesData : public BaseObject * @version DragonBones 3.0 * @language zh_CN */ - inline ArmatureData* getArmature(const std::string& armatureName) const - { - return mapFind(armatures, armatureName); - } + inline ArmatureData* getArmature(std::string_view armatureName) const { return mapFind(armatures, armatureName); } protected: virtual void _onClear() override; diff --git a/extensions/DragonBones/model/SkinData.cpp b/extensions/DragonBones/model/SkinData.cpp index 7e6fe2501152..7f53de7acfe2 100644 --- a/extensions/DragonBones/model/SkinData.cpp +++ b/extensions/DragonBones/model/SkinData.cpp @@ -1,4 +1,4 @@ -#include "SkinData.h" +#include "SkinData.h" #include "DisplayData.h" DRAGONBONES_NAMESPACE_BEGIN @@ -21,7 +21,7 @@ void SkinData::_onClear() parent = nullptr; } -void SkinData::addDisplay(const std::string& slotName, DisplayData* value) +void SkinData::addDisplay(std::string_view slotName, DisplayData* value) { if (value != nullptr) { @@ -31,7 +31,7 @@ void SkinData::addDisplay(const std::string& slotName, DisplayData* value) displays[slotName].push_back(value); // TODO clear prev } -DisplayData* SkinData::getDisplay(const std::string& slotName, const std::string& displayName) +DisplayData* SkinData::getDisplay(std::string_view slotName, std::string_view displayName) { const auto slotDisplays = getDisplays(slotName); if (slotDisplays != nullptr) diff --git a/extensions/DragonBones/model/SkinData.h b/extensions/DragonBones/model/SkinData.h index e054e9f96c35..89e7abfc997b 100644 --- a/extensions/DragonBones/model/SkinData.h +++ b/extensions/DragonBones/model/SkinData.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -24,6 +24,7 @@ #define DRAGONBONES_SKIN_DATA_H #include "../core/BaseObject.h" +#include "base/hlookup.h" DRAGONBONES_NAMESPACE_BEGIN /** @@ -55,7 +56,7 @@ class SkinData : public BaseObject /** * @private */ - std::map> displays; + hlookup::string_map> displays; /** * @private */ @@ -68,18 +69,18 @@ class SkinData : public BaseObject /** * @internal */ - void addDisplay(const std::string& slotName, DisplayData* value); + void addDisplay(std::string_view slotName, DisplayData* value); /** * @private */ - DisplayData* getDisplay(const std::string& slotName, const std::string& displayName); + DisplayData* getDisplay(std::string_view slotName, std::string_view displayName); /** * @private */ - std::vector* getDisplays(const std::string& slotName) { return mapFindB(displays, slotName); } + std::vector* getDisplays(std::string_view slotName) { return mapFindB(displays, slotName); } public: // For WebAssembly. TODO parent - const std::map>& getSlotDisplays() const { return displays; } + const hlookup::string_map>& getSlotDisplays() const { return displays; } }; DRAGONBONES_NAMESPACE_END diff --git a/extensions/DragonBones/model/TextureAtlasData.h b/extensions/DragonBones/model/TextureAtlasData.h index ad5bcb504b49..08b266d356db 100644 --- a/extensions/DragonBones/model/TextureAtlasData.h +++ b/extensions/DragonBones/model/TextureAtlasData.h @@ -84,7 +84,7 @@ class TextureAtlasData : public BaseObject /** * @private */ - std::map textures; + hlookup::string_map textures; /** * @private */ @@ -100,13 +100,13 @@ class TextureAtlasData : public BaseObject /** * @private */ - inline TextureData* getTexture(const std::string& textureName) const { return mapFind(textures, textureName); } + inline TextureData* getTexture(std::string_view textureName) const { return mapFind(textures, textureName); } protected: virtual void _onClear() override; public: // For WebAssembly. - const std::map& getTextures() const { return textures; } + const hlookup::string_map& getTextures() const { return textures; } }; /** * @internal diff --git a/extensions/DragonBones/parser/DataParser.cpp b/extensions/DragonBones/parser/DataParser.cpp index 684d192e257d..3d0207d8d9a5 100644 --- a/extensions/DragonBones/parser/DataParser.cpp +++ b/extensions/DragonBones/parser/DataParser.cpp @@ -1,4 +1,4 @@ -#include "DataParser.h" +#include "DataParser.h" DRAGONBONES_NAMESPACE_BEGIN @@ -125,9 +125,9 @@ const char* DataParser::GOTO_AND_PLAY = "gotoAndPlay"; const char* DataParser::DEFAULT_NAME = "default"; -TextureFormat DataParser::_getTextureFormat(const std::string& value) +TextureFormat DataParser::_getTextureFormat(std::string_view value) { - auto lower = value; + std::string lower{value}; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); if (lower == "rgba8888") @@ -158,9 +158,9 @@ TextureFormat DataParser::_getTextureFormat(const std::string& value) return TextureFormat::DEFAULT; } -ArmatureType DataParser::_getArmatureType(const std::string& value) +ArmatureType DataParser::_getArmatureType(std::string_view value) { - auto lower = value; + std::string lower{value}; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); if (lower == "armature") @@ -179,9 +179,9 @@ ArmatureType DataParser::_getArmatureType(const std::string& value) return ArmatureType::Armature; } -DisplayType DataParser::_getDisplayType(const std::string& value) +DisplayType DataParser::_getDisplayType(std::string_view value) { - auto lower = value; + std::string lower{value}; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); if (lower == "image") @@ -204,9 +204,9 @@ DisplayType DataParser::_getDisplayType(const std::string& value) return DisplayType::Image; } -BoundingBoxType DataParser::_getBoundingBoxType(const std::string& value) +BoundingBoxType DataParser::_getBoundingBoxType(std::string_view value) { - auto lower = value; + std::string lower{value}; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); if (lower == "rectangle") @@ -225,9 +225,9 @@ BoundingBoxType DataParser::_getBoundingBoxType(const std::string& value) return BoundingBoxType::Rectangle; } -ActionType DataParser::_getActionType(const std::string& value) +ActionType DataParser::_getActionType(std::string_view value) { - auto lower = value; + std::string lower{value}; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); if (lower == "play") @@ -246,9 +246,9 @@ ActionType DataParser::_getActionType(const std::string& value) return ActionType::Play; } -BlendMode DataParser::_getBlendMode(const std::string& value) +BlendMode DataParser::_getBlendMode(std::string_view value) { - auto lower = value; + std::string lower{value}; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); if (lower == "normal") diff --git a/extensions/DragonBones/parser/DataParser.h b/extensions/DragonBones/parser/DataParser.h index 08328ccd5fca..ccad44049d8a 100644 --- a/extensions/DragonBones/parser/DataParser.h +++ b/extensions/DragonBones/parser/DataParser.h @@ -1,4 +1,4 @@ -/** +/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors @@ -166,12 +166,12 @@ class DataParser static const char* DEFAULT_NAME; - static TextureFormat _getTextureFormat(const std::string& value); - static ArmatureType _getArmatureType(const std::string& value); - static DisplayType _getDisplayType(const std::string& value); - static BoundingBoxType _getBoundingBoxType(const std::string& value); - static ActionType _getActionType(const std::string& value); - static BlendMode _getBlendMode(const std::string& value); + static TextureFormat _getTextureFormat(std::string_view value); + static ArmatureType _getArmatureType(std::string_view value); + static DisplayType _getDisplayType(std::string_view value); + static BoundingBoxType _getBoundingBoxType(std::string_view value); + static ActionType _getActionType(std::string_view value); + static BlendMode _getBlendMode(std::string_view value); public: virtual DragonBonesData* parseDragonBonesData(const char* rawData, float scale = 1.0f) = 0; diff --git a/extensions/DragonBones/parser/JSONDataParser.h b/extensions/DragonBones/parser/JSONDataParser.h index afa6e045d4c6..21a437dac364 100644 --- a/extensions/DragonBones/parser/JSONDataParser.h +++ b/extensions/DragonBones/parser/JSONDataParser.h @@ -1,4 +1,4 @@ -#ifndef DRAGONBONES_JSON_DATA_PARSER_H +#ifndef DRAGONBONES_JSON_DATA_PARSER_H #define DRAGONBONES_JSON_DATA_PARSER_H #include "DataParser.h" @@ -81,7 +81,7 @@ class JSONDataParser : public DataParser inline static std::string _getString(const rapidjson::Value& rawData, const char* key, - const std::string& defaultValue) + std::string_view defaultValue) { if (rawData.HasMember(key)) { @@ -93,7 +93,7 @@ class JSONDataParser : public DataParser return dragonBones::to_string(rawData[key].GetDouble()); } - return defaultValue; + return std::string{defaultValue}; } inline static int _getParameter(const rapidjson::Value& rawData, std::size_t index, int defaultValue) @@ -118,14 +118,14 @@ class JSONDataParser : public DataParser inline static std::string _getParameter(const rapidjson::Value& rawData, std::size_t index, - const std::string& defaultValue) + std::string_view defaultValue) { if (rawData.Size() > index) { return rawData[(int)index].GetString(); } - return defaultValue; + return std::string{defaultValue}; } protected: @@ -160,10 +160,10 @@ class JSONDataParser : public DataParser std::vector _cacheRawMeshes; std::vector _cacheMeshes; std::vector _actionFrames; - std::map _weightSlotPose; - std::map _weightBonePoses; - std::map> _cacheBones; - std::map> _slotChildActions; + hlookup::string_map _weightSlotPose; + hlookup::string_map _weightBonePoses; + hlookup::string_map> _cacheBones; + hlookup::string_map> _slotChildActions; public: JSONDataParser() diff --git a/extensions/GUI/CCControlExtension/CCControlButton.cpp b/extensions/GUI/CCControlExtension/CCControlButton.cpp index ba95b0ed8e91..1d9ea36046a7 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.cpp +++ b/extensions/GUI/CCControlExtension/CCControlButton.cpp @@ -141,15 +141,15 @@ ControlButton* ControlButton::create(Node* label, return pRet; } -bool ControlButton::initWithTitleAndFontNameAndFontSize(const std::string& title, - const std::string& fontName, +bool ControlButton::initWithTitleAndFontNameAndFontSize(std::string_view title, + std::string_view fontName, float fontSize) { return initWithLabelAndBackgroundSprite(Label::createWithSystemFont(title, fontName, fontSize), cocos2d::ui::Scale9Sprite::create(), true); } -ControlButton* ControlButton::create(const std::string& title, const std::string& fontName, float fontSize) +ControlButton* ControlButton::create(std::string_view title, std::string_view fontName, float fontSize) { ControlButton* pRet = new ControlButton(); pRet->initWithTitleAndFontNameAndFontSize(title, fontName, fontSize); @@ -291,7 +291,7 @@ std::string ControlButton::getTitleForState(State state) return iter != _titleDispatchTable.end() ? iter->second : ""; } -void ControlButton::setTitleForState(const std::string& title, State state) +void ControlButton::setTitleForState(std::string_view title, State state) { _titleDispatchTable.erase((int)state); @@ -371,12 +371,12 @@ void ControlButton::setTitleLabelForState(Node* titleLabel, State state) } } -void ControlButton::setTitleTTFForState(const std::string& fontName, State state) +void ControlButton::setTitleTTFForState(std::string_view fontName, State state) { this->setTitleLabelForState(Label::createWithSystemFont(getTitleForState(state), fontName, 12), state); } -const std::string& ControlButton::getTitleTTFForState(State state) +std::string_view ControlButton::getTitleTTFForState(State state) { LabelProtocol* label = dynamic_cast(this->getTitleLabelForState(state)); Label* labelTTF = dynamic_cast(label); @@ -416,13 +416,13 @@ float ControlButton::getTitleTTFSizeForState(State state) } } -void ControlButton::setTitleBMFontForState(const std::string& fntFile, State state) +void ControlButton::setTitleBMFontForState(std::string_view fntFile, State state) { std::string title = this->getTitleForState(state); this->setTitleLabelForState(Label::createWithBMFont(fntFile, title), state); } -const std::string& ControlButton::getTitleBMFontForState(State state) +std::string_view ControlButton::getTitleBMFontForState(State state) { LabelProtocol* label = dynamic_cast(this->getTitleLabelForState(state)); auto labelBMFont = dynamic_cast(label); diff --git a/extensions/GUI/CCControlExtension/CCControlButton.h b/extensions/GUI/CCControlExtension/CCControlButton.h index 51a8fcac34db..9a5f80734fb2 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.h +++ b/extensions/GUI/CCControlExtension/CCControlButton.h @@ -57,7 +57,7 @@ class CC_EX_DLL ControlButton : public Control static ControlButton* create(); static ControlButton* create(cocos2d::ui::Scale9Sprite* sprite); static ControlButton* create(Node* label, cocos2d::ui::Scale9Sprite* backgroundSprite); - static ControlButton* create(const std::string& title, const std::string& fontName, float fontSize); + static ControlButton* create(std::string_view title, std::string_view fontName, float fontSize); static ControlButton* create(Node* label, cocos2d::ui::Scale9Sprite* backgroundSprite, bool adjustBackGroundSize); virtual void needsLayout() override; @@ -87,7 +87,7 @@ class CC_EX_DLL ControlButton : public Control * @param state The state that uses the specified title. The values are described * in "CCControlState". */ - virtual void setTitleForState(const std::string& title, State state); + virtual void setTitleForState(std::string_view title, State state); /** * Returns the title color used for a state. @@ -128,8 +128,8 @@ class CC_EX_DLL ControlButton : public Control */ virtual void setTitleLabelForState(Node* label, State state); - virtual void setTitleTTFForState(const std::string& fntFile, State state); - virtual const std::string& getTitleTTFForState(State state); + virtual void setTitleTTFForState(std::string_view fntFile, State state); + virtual std::string_view getTitleTTFForState(State state); virtual void setTitleTTFSizeForState(float size, State state); virtual float getTitleTTFSizeForState(State state); @@ -140,8 +140,8 @@ class CC_EX_DLL ControlButton : public Control * @param state The state that uses the specified fntFile. The values are described * in "CCControlState". */ - virtual void setTitleBMFontForState(const std::string& fntFile, State state); - virtual const std::string& getTitleBMFontForState(State state); + virtual void setTitleBMFontForState(std::string_view fntFile, State state); + virtual std::string_view getTitleBMFontForState(State state); /** * Returns the background sprite used for a state. @@ -188,7 +188,7 @@ class CC_EX_DLL ControlButton : public Control virtual void setColor(const Color3B&) override; virtual void updateDisplayedColor(const Color3B& parentColor) override; - const std::string& getCurrentTitle() const { return _currentTitle; }; + std::string_view getCurrentTitle() const { return _currentTitle; }; std::string getCurrentTitle() { return _currentTitle; }; CC_CONSTRUCTOR_ACCESS : @@ -207,9 +207,7 @@ class CC_EX_DLL ControlButton : public Control cocos2d::ui::Scale9Sprite* backgroundSprite, bool adjustBackGroundSize); virtual bool initWithBackgroundSprite(cocos2d::ui::Scale9Sprite* sprite); - virtual bool initWithTitleAndFontNameAndFontSize(const std::string& title, - const std::string& fontName, - float fontSize); + virtual bool initWithTitleAndFontNameAndFontSize(std::string_view title, std::string_view fontName, float fontSize); protected: bool _isPushed; diff --git a/extensions/GUI/CCControlExtension/CCControlSwitch.cpp b/extensions/GUI/CCControlExtension/CCControlSwitch.cpp index 09d14b6e6a00..431b465a6c6f 100644 --- a/extensions/GUI/CCControlExtension/CCControlSwitch.cpp +++ b/extensions/GUI/CCControlExtension/CCControlSwitch.cpp @@ -78,7 +78,7 @@ class ControlSwitchSprite : public Sprite, public ActionTweenDelegate * @js NA * @lua NA */ - virtual void updateTweenAction(float value, const std::string& key) override; + virtual void updateTweenAction(float value, std::string_view key) override; /** Contains the position (in x-axis) of the slider inside the receiver. */ float _sliderXPosition; @@ -214,7 +214,7 @@ bool ControlSwitchSprite::initWithMaskSprite(Sprite* maskSprite, return false; } -void ControlSwitchSprite::updateTweenAction(float value, const std::string& key) +void ControlSwitchSprite::updateTweenAction(float value, std::string_view key) { CCLOGINFO("key = %s, value = %f", key.c_str(), value); setSliderXPosition(value); diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index 6bf9f47288ec..bfa2cf5e127e 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -327,7 +327,7 @@ void ScrollView::setZoomScaleInDuration(float s, float dt) } } -void ScrollView::updateTweenAction(float value, const std::string& /*key*/) +void ScrollView::updateTweenAction(float value, std::string_view /*key*/) { this->setZoomScale(value); } @@ -551,7 +551,7 @@ void ScrollView::removeAllChildren() removeAllChildrenWithCleanup(true); } -void ScrollView::addChild(Node* child, int zOrder, const std::string& name) +void ScrollView::addChild(Node* child, int zOrder, std::string_view name) { if (_container != child) { diff --git a/extensions/GUI/CCScrollView/CCScrollView.h b/extensions/GUI/CCScrollView/CCScrollView.h index 304f4cab750b..9aef265af42f 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.h +++ b/extensions/GUI/CCScrollView/CCScrollView.h @@ -251,7 +251,7 @@ class CC_EX_DLL ScrollView : public Layer, public ActionTweenDelegate using Node::addChild; virtual void addChild(Node* child, int zOrder, int tag) override; - virtual void addChild(Node* child, int zOrder, const std::string& name) override; + virtual void addChild(Node* child, int zOrder, std::string_view name) override; virtual void removeAllChildren() override; virtual void removeAllChildrenWithCleanup(bool cleanup) override; @@ -259,7 +259,7 @@ class CC_EX_DLL ScrollView : public Layer, public ActionTweenDelegate /** * CCActionTweenDelegate */ - void updateTweenAction(float value, const std::string& key) override; + void updateTweenAction(float value, std::string_view key) override; bool hasVisibleParents() const; diff --git a/extensions/ImGuiEXT/CCImGuiEXT.cpp b/extensions/ImGuiEXT/CCImGuiEXT.cpp index b3b801a33e65..000806050e14 100644 --- a/extensions/ImGuiEXT/CCImGuiEXT.cpp +++ b/extensions/ImGuiEXT/CCImGuiEXT.cpp @@ -5,12 +5,12 @@ NS_CC_EXT_BEGIN -static uint32_t fourccValue(const std::string& str) +static uint32_t fourccValue(std::string_view str) { if (str.empty() || str[0] != '#') return (uint32_t)-1; uint32_t value = 0; - memcpy(&value, str.c_str() + 1, std::min(sizeof(value), str.size() - 1)); + memcpy(&value, str.data() + 1, std::min(sizeof(value), str.size() - 1)); return value; } @@ -246,7 +246,7 @@ float ImGuiEXT::scaleAllByDPI(float userScale) return zoomFactor; } -void ImGuiEXT::addFont(const std::string& fontFile, float fontSize, CHS_GLYPH_RANGE glyphRange) +void ImGuiEXT::addFont(std::string_view fontFile, float fontSize, CHS_GLYPH_RANGE glyphRange) { if (FileUtils::getInstance()->isFileExistInternal(fontFile)) { @@ -255,7 +255,7 @@ void ImGuiEXT::addFont(const std::string& fontFile, float fontSize, CHS_GLYPH_RA } } -void ImGuiEXT::removeFont(const std::string& fontFile) +void ImGuiEXT::removeFont(std::string_view fontFile) { auto count = _fontsInfoMap.size(); _fontsInfoMap.erase(fontFile); @@ -339,7 +339,7 @@ void ImGuiEXT::update() // commands will be processed after update } -bool ImGuiEXT::addRenderLoop(const std::string& id, std::function func, Scene* target) +bool ImGuiEXT::addRenderLoop(std::string_view id, std::function func, Scene* target) { // TODO: check whether exist auto fourccId = fourccValue(id); @@ -362,7 +362,7 @@ bool ImGuiEXT::addRenderLoop(const std::string& id, std::function func, return false; } -void ImGuiEXT::removeRenderLoop(const std::string& id) +void ImGuiEXT::removeRenderLoop(std::string_view id) { auto fourccId = fourccValue(id); const auto iter = _renderPiplines.find(fourccId); @@ -603,16 +603,16 @@ void ImGuiEXT::setLabelColor(Label* label, ImGuiCol col) setLabelColor(label, ImGui::GetStyleColorVec4(col)); } -ImWchar* ImGuiEXT::addGlyphRanges(const std::string& key, const std::vector& ranges) +ImWchar* ImGuiEXT::addGlyphRanges(std::string_view key, const std::vector& ranges) { auto it = glyphRanges.find(key); // the pointer must be persistant, do not replace if (it != glyphRanges.end()) return it->second.data(); - glyphRanges[key] = ranges; + it = glyphRanges.emplace(key, ranges).first; // glyphRanges[key] = ranges; if (ranges.empty()) - glyphRanges[key].push_back(0); - return glyphRanges[key].data(); + it->second.push_back(0); + return it->second.data(); } void ImGuiEXT::mergeFontGlyphs(ImFont* dst, ImFont* src, ImWchar start, ImWchar end) @@ -712,13 +712,13 @@ void ImGuiEXT::setMarkdownFont(int index, ImFont* font, bool seperator, float sc ImGuiMarkdownConfig.headingScales[index] = scale; } -void ImGuiEXT::setMarkdownLinkIcon(const std::string& icon) +void ImGuiEXT::setMarkdownLinkIcon(std::string_view icon) { ImGuiMarkdownLinkIcon = icon; ImGuiMarkdownConfig.linkIcon = ImGuiMarkdownLinkIcon.c_str(); } -void ImGuiEXT::markdown(const std::string& content) +void ImGuiEXT::markdown(std::string_view content) { ImGui::Markdown(content.c_str(), content.size(), ImGuiMarkdownConfig); } diff --git a/extensions/ImGuiEXT/CCImGuiEXT.h b/extensions/ImGuiEXT/CCImGuiEXT.h index 7c80b711c7f1..c03cddc0c241 100644 --- a/extensions/ImGuiEXT/CCImGuiEXT.h +++ b/extensions/ImGuiEXT/CCImGuiEXT.h @@ -50,10 +50,10 @@ class ImGuiEXT /// /// /// - void addFont(const std::string& fontFile, + void addFont(std::string_view fontFile, float fontSize = DEFAULT_FONT_SIZE, CHS_GLYPH_RANGE glyphRange = CHS_GLYPH_RANGE::NONE); - void removeFont(const std::string& fontFile); + void removeFont(std::string_view fontFile); void clearFonts(); /// @@ -62,13 +62,13 @@ class ImGuiEXT /// The FOURCC id of render loop, starts with '#', such as "#abcd" /// the ImGui render loop /// The target scene to track event, nullptr for global, useful for global GM tools - bool addRenderLoop(const std::string& id, std::function func, Scene* target); + bool addRenderLoop(std::string_view id, std::function func, Scene* target); /// /// Remove ImGui render loop /// /// FOURCC starts with '#', such as "#abcd" - void removeRenderLoop(const std::string& id); + void removeRenderLoop(std::string_view id); void end(); @@ -112,7 +112,7 @@ class ImGuiEXT static void setLabelColor(Label* label, bool disabled = false); static void setLabelColor(Label* label, ImGuiCol col); - ImWchar* addGlyphRanges(const std::string& key, const std::vector& ranges); + ImWchar* addGlyphRanges(std::string_view key, const std::vector& ranges); static void mergeFontGlyphs(ImFont* dst, ImFont* src, ImWchar start, ImWchar end); int getCCRefId(Ref* p); @@ -126,8 +126,8 @@ class ImGuiEXT void setMarkdownLinkCallback(const MdLinkCallback& f); void setMarkdownImageCallback(const MdImageCallback& f); void setMarkdownFont(int index, ImFont* font, bool seperator, float scale = 1.f); - void setMarkdownLinkIcon(const std::string& icon); - void markdown(const std::string& content); + void setMarkdownLinkIcon(std::string_view icon); + void markdown(std::string_view content); #endif private: @@ -154,7 +154,7 @@ class ImGuiEXT std::unordered_map usedCCRefIdMap; // cocos objects should be retained until next frame Vector usedCCRef; - std::unordered_map> glyphRanges; + hlookup::string_map> glyphRanges; float _contentZoomFactor = 1.0f; @@ -168,7 +168,7 @@ class ImGuiEXT CHS_GLYPH_RANGE glyphRange; }; - std::unordered_map _fontsInfoMap; + hlookup::string_map _fontsInfoMap; bool _purgeNextLoop = false; }; diff --git a/extensions/ImGuiEXT/imgui/imconfig.h b/extensions/ImGuiEXT/imgui/imconfig.h index d84c59423bbe..768377be307d 100644 --- a/extensions/ImGuiEXT/imgui/imconfig.h +++ b/extensions/ImGuiEXT/imgui/imconfig.h @@ -32,36 +32,36 @@ //#define IMGUI_API __declspec( dllimport ) //---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to avoid -//using soon-to-be obsolete function/names. #define IMGUI_DISABLE_OBSOLETE_FUNCTIONS +// using soon-to-be obsolete function/names. #define IMGUI_DISABLE_OBSOLETE_FUNCTIONS //---- Disable all of Dear ImGui or don't implement standard windows. // It is very strongly recommended to NOT disable the demo windows during development. Please read comments in // imgui_demo.cpp. //#define IMGUI_DISABLE // Disable everything: all headers and source files will be -//empty. #define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: -//ShowDemoWindow()/ShowStyleEditor() will be empty. Not recommended. #define IMGUI_DISABLE_METRICS_WINDOW // Disable -//metrics/debugger window: ShowMetricsWindow() will be empty. +// empty. #define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: +// ShowDemoWindow()/ShowStyleEditor() will be empty. Not recommended. #define IMGUI_DISABLE_METRICS_WINDOW // Disable +// metrics/debugger window: ShowMetricsWindow() will be empty. //---- Don't implement some functions to reduce linkage requirements. //#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't -//use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a) #define -//IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with Visual Studio] Implement default IME -//handler (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW) #define -//IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't -//implement default IME handler (won't require imm32.lib/.a) #define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use -//and link with any Win32 function (clipboard, ime). #define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] -//Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not -//the default). #define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement -//ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf) +// use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a) #define +// IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with Visual Studio] Implement default IME +// handler (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW) #define +// IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't +// implement default IME handler (won't require imm32.lib/.a) #define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use +// and link with any Win32 function (clipboard, ime). #define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] +// Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not +// the default). #define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement +// ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf) //#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement -//ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself. #define -//IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and -//ImFileHandle at all (replace them with dummies) #define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't -//implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you -//don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function. #define -//IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to -//avoid linking with them. You will need to call ImGui::SetAllocatorFunctions(). #define IMGUI_DISABLE_SSE // Disable -//use of SSE intrinsics even if available +// ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself. #define +// IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite +// and ImFileHandle at all (replace them with dummies) #define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // +// Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if +// you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function. #define +// IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to +// avoid linking with them. You will need to call ImGui::SetAllocatorFunctions(). #define IMGUI_DISABLE_SSE // Disable +// use of SSE intrinsics even if available //---- Include imgui_user.h at the end of imgui.h as a convenience //#define IMGUI_INCLUDE_IMGUI_USER_H @@ -70,7 +70,7 @@ //#define IMGUI_USE_BGRA_PACKED_COLOR //---- Use 32-bit for ImWchar (default is 16-bit) to support unicode planes 1-16. (e.g. point beyond 0xFFFF like -//emoticons, dingbats, symbols, shapes, ancient languages, etc...) #define IMGUI_USE_WCHAR32 +// emoticons, dingbats, symbols, shapes, ancient languages, etc...) #define IMGUI_USE_WCHAR32 //---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version // By default the embedded implementations are declared static and not available outside of Dear ImGui sources files. @@ -80,13 +80,13 @@ //#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION //---- Use stb_printf's faster implementation of vsnprintf instead of the one from libc (unless -//IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined) +// IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined) // Requires 'stb_sprintf.h' to be available in the include path. Compatibility checks of arguments and formats done by // clang and GCC will be disabled in order to support the extra formats provided by STB sprintf. #define // IMGUI_USE_STB_SPRINTF //---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear -//ImGui) +// ImGui) // Requires FreeType headers to be available in the include path. Requires program to be compiled with // 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided). On Windows you may use // vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'. diff --git a/extensions/ImGuiEXT/imgui/imgui.cpp b/extensions/ImGuiEXT/imgui/imgui.cpp index e8f0481d3958..e9c52c3bf07d 100644 --- a/extensions/ImGuiEXT/imgui/imgui.cpp +++ b/extensions/ImGuiEXT/imgui/imgui.cpp @@ -1115,7 +1115,7 @@ you share your issues (on GitHub or privately). # endif # pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' # pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more - // terse. + // terse. # pragma clang diagnostic ignored \ "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing // against same constants (typically 0.0f) is ok. @@ -19477,7 +19477,7 @@ void ImGui::DebugNodeViewport(ImGuiViewportP* viewport) } BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags, //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is - //the standard + // the standard (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "", (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "", (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "", diff --git a/extensions/ImGuiEXT/imgui/imgui.h b/extensions/ImGuiEXT/imgui/imgui.h index 279b0073191b..91c3a68e895f 100644 --- a/extensions/ImGuiEXT/imgui/imgui.h +++ b/extensions/ImGuiEXT/imgui/imgui.h @@ -2114,9 +2114,9 @@ enum ImGuiTableFlags_ // Obsolete names (will be removed soon) # ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS //, ImGuiTableFlags_ColumnsWidthFixed = ImGuiTableFlags_SizingFixedFit, ImGuiTableFlags_ColumnsWidthStretch = -//ImGuiTableFlags_SizingStretchSame // WIP Tables 2020/12 , ImGuiTableFlags_SizingPolicyFixed = -//ImGuiTableFlags_SizingFixedFit, ImGuiTableFlags_SizingPolicyStretch = ImGuiTableFlags_SizingStretchSame // WIP -//Tables 2021/01 +// ImGuiTableFlags_SizingStretchSame // WIP Tables 2020/12 , ImGuiTableFlags_SizingPolicyFixed = +// ImGuiTableFlags_SizingFixedFit, ImGuiTableFlags_SizingPolicyStretch = ImGuiTableFlags_SizingStretchSame // WIP +// Tables 2021/01 # endif }; diff --git a/extensions/ImGuiEXT/imgui/imgui_demo.cpp b/extensions/ImGuiEXT/imgui/imgui_demo.cpp index 1818e5ff63d6..26d3e0c97a04 100644 --- a/extensions/ImGuiEXT/imgui/imgui_demo.cpp +++ b/extensions/ImGuiEXT/imgui/imgui_demo.cpp @@ -112,7 +112,7 @@ Index of this file: # endif # pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' # pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more - // terse. + // terse. # pragma clang diagnostic ignored \ "-Wdeprecated-declarations" // warning: 'xx' is deprecated: The POSIX name for this.. // for strdup used // in demo code (so user can copy & paste the code) diff --git a/extensions/ImGuiEXT/imgui/imgui_draw.cpp b/extensions/ImGuiEXT/imgui/imgui_draw.cpp index 7732f201057e..b251bc25fa97 100644 --- a/extensions/ImGuiEXT/imgui/imgui_draw.cpp +++ b/extensions/ImGuiEXT/imgui/imgui_draw.cpp @@ -81,7 +81,7 @@ Index of this file: # endif # pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' # pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more - // terse. + // terse. # pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // // storing and comparing against same constants ok. # pragma clang diagnostic ignored \ diff --git a/extensions/ImGuiEXT/imgui/imgui_tables.cpp b/extensions/ImGuiEXT/imgui/imgui_tables.cpp index beac7c628789..c29b320b6fad 100644 --- a/extensions/ImGuiEXT/imgui/imgui_tables.cpp +++ b/extensions/ImGuiEXT/imgui/imgui_tables.cpp @@ -260,7 +260,7 @@ Index of this file: # endif # pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' # pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more - // terse. + // terse. # pragma clang diagnostic ignored \ "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing // against same constants (typically 0.0f) is ok. diff --git a/extensions/ImGuiEXT/imgui/imgui_widgets.cpp b/extensions/ImGuiEXT/imgui/imgui_widgets.cpp index 9b68c0359f58..02be44862595 100644 --- a/extensions/ImGuiEXT/imgui/imgui_widgets.cpp +++ b/extensions/ImGuiEXT/imgui/imgui_widgets.cpp @@ -78,7 +78,7 @@ Index of this file: # endif # pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' # pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more - // terse. + // terse. # pragma clang diagnostic ignored \ "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing // against same constants (typically 0.0f) is ok. diff --git a/extensions/Particle3D/CCParticle3DRender.cpp b/extensions/Particle3D/CCParticle3DRender.cpp index 58b022430ec8..d2907930af07 100644 --- a/extensions/Particle3D/CCParticle3DRender.cpp +++ b/extensions/Particle3D/CCParticle3DRender.cpp @@ -51,7 +51,7 @@ Particle3DQuadRender::~Particle3DQuadRender() CC_SAFE_RELEASE(_indexBuffer); } -Particle3DQuadRender* Particle3DQuadRender::create(const std::string& texFile) +Particle3DQuadRender* Particle3DQuadRender::create(std::string_view texFile) { auto ret = new Particle3DQuadRender(); if (ret->initQuadRender(texFile)) @@ -185,7 +185,7 @@ void Particle3DQuadRender::render(Renderer* renderer, const Mat4& transform, Par renderer->addCommand(&_afterCommand); } -bool Particle3DQuadRender::initQuadRender(const std::string& texFile) +bool Particle3DQuadRender::initQuadRender(std::string_view texFile) { CC_SAFE_RELEASE_NULL(_programState); @@ -285,7 +285,7 @@ Particle3DModelRender::~Particle3DModelRender() } } -Particle3DModelRender* Particle3DModelRender::create(const std::string& modelFile, const std::string& texFile) +Particle3DModelRender* Particle3DModelRender::create(std::string_view modelFile, std::string_view texFile) { auto ret = new Particle3DModelRender(); ret->_modelFile = modelFile; diff --git a/extensions/Particle3D/CCParticle3DRender.h b/extensions/Particle3D/CCParticle3DRender.h index aaa0d70104f1..0d2d0b018885 100644 --- a/extensions/Particle3D/CCParticle3DRender.h +++ b/extensions/Particle3D/CCParticle3DRender.h @@ -95,7 +95,7 @@ class CC_EX_DLL Particle3DRender : public Ref class CC_EX_DLL Particle3DQuadRender : public Particle3DRender { public: - static Particle3DQuadRender* create(const std::string& texFile = ""); + static Particle3DQuadRender* create(std::string_view texFile = ""); virtual void render(Renderer* renderer, const Mat4& transform, ParticleSystem3D* particleSystem) override; @@ -104,7 +104,7 @@ class CC_EX_DLL Particle3DQuadRender : public Particle3DRender virtual ~Particle3DQuadRender(); protected: - bool initQuadRender(const std::string& texFile); + bool initQuadRender(std::string_view texFile); void onBeforeDraw(); void onAfterDraw(); @@ -145,7 +145,7 @@ class CC_EX_DLL Particle3DQuadRender : public Particle3DRender class CC_EX_DLL Particle3DModelRender : public Particle3DRender { public: - static Particle3DModelRender* create(const std::string& modelFile, const std::string& texFile = ""); + static Particle3DModelRender* create(std::string_view modelFile, std::string_view texFile = ""); virtual void render(Renderer* renderer, const Mat4& transform, ParticleSystem3D* particleSystem) override; diff --git a/extensions/Particle3D/PU/CCPUAffector.cpp b/extensions/Particle3D/PU/CCPUAffector.cpp index 7f0ea5bbdd3f..a41dfc001dee 100644 --- a/extensions/Particle3D/PU/CCPUAffector.cpp +++ b/extensions/Particle3D/PU/CCPUAffector.cpp @@ -161,16 +161,16 @@ void PUAffector::copyAttributesTo(PUAffector* affector) affector->_excludedEmitters = _excludedEmitters; } -void PUAffector::addEmitterToExclude(const std::string& emitterName) +void PUAffector::addEmitterToExclude(std::string_view emitterName) { auto iter = std::find(_excludedEmitters.begin(), _excludedEmitters.end(), emitterName); if (iter == _excludedEmitters.end()) { - _excludedEmitters.push_back(emitterName); + _excludedEmitters.push_back(std::string{emitterName}); } } -void PUAffector::removeEmitterToExclude(const std::string& emitterName) +void PUAffector::removeEmitterToExclude(std::string_view emitterName) { auto iter = std::find(_excludedEmitters.begin(), _excludedEmitters.end(), emitterName); if (iter != _excludedEmitters.end()) @@ -189,8 +189,8 @@ void PUAffector::process(PUParticle3D* particle, float delta, bool firstParticle if (!_excludedEmitters.empty() && particle->parentEmitter) { // Return if the emitter which emits this particle is part of the vector - std::string emitterName = particle->parentEmitter->getName(); - auto iter = std::find(_excludedEmitters.begin(), _excludedEmitters.end(), emitterName); + auto emitterName = particle->parentEmitter->getName(); + auto iter = std::find(_excludedEmitters.begin(), _excludedEmitters.end(), emitterName); if (iter != _excludedEmitters.end()) { return; diff --git a/extensions/Particle3D/PU/CCPUAffector.h b/extensions/Particle3D/PU/CCPUAffector.h index 219d620568d5..255401c9a6f8 100644 --- a/extensions/Particle3D/PU/CCPUAffector.h +++ b/extensions/Particle3D/PU/CCPUAffector.h @@ -91,22 +91,22 @@ class CC_EX_DLL PUAffector : public Particle3DAffector /** Todo */ - const std::string& getAffectorType() const { return _affectorType; }; - void setAffectorType(const std::string& affectorType) { _affectorType = affectorType; }; + std::string_view getAffectorType() const { return _affectorType; }; + void setAffectorType(std::string_view affectorType) { _affectorType = affectorType; }; /** Add a ParticleEmitter name that excludes Particles emitted by this ParticleEmitter from being affected. */ - void addEmitterToExclude(const std::string& emitterName); + void addEmitterToExclude(std::string_view emitterName); /** Remove a ParticleEmitter name that excludes Particles emitted by this ParticleEmitter. */ - void removeEmitterToExclude(const std::string& emitterName); + void removeEmitterToExclude(std::string_view emitterName); /** Todo */ - const std::string& getName() const { return _name; }; - void setName(const std::string& name) { _name = name; }; + std::string_view getName() const { return _name; }; + void setName(std::string_view name) { _name = name; }; virtual void copyAttributesTo(PUAffector* affector); diff --git a/extensions/Particle3D/PU/CCPUAffectorManager.cpp b/extensions/Particle3D/PU/CCPUAffectorManager.cpp index e9b4e5e00f6d..c5be72d24dbf 100644 --- a/extensions/Particle3D/PU/CCPUAffectorManager.cpp +++ b/extensions/Particle3D/PU/CCPUAffectorManager.cpp @@ -63,7 +63,7 @@ PUAffectorManager* PUAffectorManager::Instance() return &pam; } -PUScriptTranslator* PUAffectorManager::getTranslator(const std::string& type) +PUScriptTranslator* PUAffectorManager::getTranslator(std::string_view type) { if (type == "Align") { @@ -172,7 +172,7 @@ PUScriptTranslator* PUAffectorManager::getTranslator(const std::string& type) return nullptr; } -PUAffector* PUAffectorManager::createAffector(const std::string& type) +PUAffector* PUAffectorManager::createAffector(std::string_view type) { if (type == "Align") { diff --git a/extensions/Particle3D/PU/CCPUAffectorManager.h b/extensions/Particle3D/PU/CCPUAffectorManager.h index 8fe439c10f2e..9a768d52fe58 100644 --- a/extensions/Particle3D/PU/CCPUAffectorManager.h +++ b/extensions/Particle3D/PU/CCPUAffectorManager.h @@ -66,8 +66,8 @@ class CC_EX_DLL PUAffectorManager /** */ - PUScriptTranslator* getTranslator(const std::string& type); - PUAffector* createAffector(const std::string& type); + PUScriptTranslator* getTranslator(std::string_view type); + PUAffector* createAffector(std::string_view type); CC_CONSTRUCTOR_ACCESS : PUAffectorManager(); ~PUAffectorManager(); diff --git a/extensions/Particle3D/PU/CCPUBeamRender.cpp b/extensions/Particle3D/PU/CCPUBeamRender.cpp index c68c2f603ee7..d278f52dc818 100644 --- a/extensions/Particle3D/PU/CCPUBeamRender.cpp +++ b/extensions/Particle3D/PU/CCPUBeamRender.cpp @@ -49,7 +49,7 @@ const float PUBeamRender::DEFAULT_DEVIATION const size_t PUBeamRender::DEFAULT_NUMBER_OF_SEGMENTS = 2; const PUBillboardChain::TexCoordDirection PUBeamRender::DEFAULT_TEXTURE_DIRECTION = PUBillboardChain::TCD_V; -PUBeamRender* PUBeamRender::create(const std::string& texFile) +PUBeamRender* PUBeamRender::create(std::string_view texFile) { auto br = new PUBeamRender(); br->autorelease(); diff --git a/extensions/Particle3D/PU/CCPUBeamRender.h b/extensions/Particle3D/PU/CCPUBeamRender.h index 0d0ccc8ed6a1..6d6e270295d0 100644 --- a/extensions/Particle3D/PU/CCPUBeamRender.h +++ b/extensions/Particle3D/PU/CCPUBeamRender.h @@ -87,7 +87,7 @@ class CC_EX_DLL PUBeamRender : public PURender, public PUListener static const size_t DEFAULT_NUMBER_OF_SEGMENTS; static const PUBillboardChain::TexCoordDirection DEFAULT_TEXTURE_DIRECTION; - static PUBeamRender* create(const std::string& texFile = ""); + static PUBeamRender* create(std::string_view texFile = ""); virtual void prepare() override; virtual void unPrepare() override; diff --git a/extensions/Particle3D/PU/CCPUBehaviour.h b/extensions/Particle3D/PU/CCPUBehaviour.h index 15d098d43901..745cfb669ac3 100644 --- a/extensions/Particle3D/PU/CCPUBehaviour.h +++ b/extensions/Particle3D/PU/CCPUBehaviour.h @@ -45,8 +45,8 @@ class CC_EX_DLL PUBehaviour : public Ref public: /** Todo */ - const std::string& getBehaviourType() const { return _behaviourType; }; - void setBehaviourType(const std::string& behaviourType) { _behaviourType = behaviourType; }; + std::string_view getBehaviourType() const { return _behaviourType; }; + void setBehaviourType(std::string_view behaviourType) { _behaviourType = behaviourType; }; /** Notify that the Behaviour is rescaled. */ diff --git a/extensions/Particle3D/PU/CCPUBehaviourManager.cpp b/extensions/Particle3D/PU/CCPUBehaviourManager.cpp index 6ff319f6161d..2ce24c156a7d 100644 --- a/extensions/Particle3D/PU/CCPUBehaviourManager.cpp +++ b/extensions/Particle3D/PU/CCPUBehaviourManager.cpp @@ -38,7 +38,7 @@ PUBehaviourManager* PUBehaviourManager::Instance() return &pam; } -PUScriptTranslator* PUBehaviourManager::getTranslator(const std::string& type) +PUScriptTranslator* PUBehaviourManager::getTranslator(std::string_view type) { if (type == "Slave") { @@ -47,7 +47,7 @@ PUScriptTranslator* PUBehaviourManager::getTranslator(const std::string& type) return nullptr; } -PUBehaviour* PUBehaviourManager::createBehaviour(const std::string& type) +PUBehaviour* PUBehaviourManager::createBehaviour(std::string_view type) { if (type == "Slave") { diff --git a/extensions/Particle3D/PU/CCPUBehaviourManager.h b/extensions/Particle3D/PU/CCPUBehaviourManager.h index 91dfffb450bd..7f468f173a9d 100644 --- a/extensions/Particle3D/PU/CCPUBehaviourManager.h +++ b/extensions/Particle3D/PU/CCPUBehaviourManager.h @@ -41,8 +41,8 @@ class PUBehaviourManager /** */ - PUScriptTranslator* getTranslator(const std::string& type); - PUBehaviour* createBehaviour(const std::string& type); + PUScriptTranslator* getTranslator(std::string_view type); + PUBehaviour* createBehaviour(std::string_view type); CC_CONSTRUCTOR_ACCESS : PUBehaviourManager(); ~PUBehaviourManager(); diff --git a/extensions/Particle3D/PU/CCPUBillboardChain.cpp b/extensions/Particle3D/PU/CCPUBillboardChain.cpp index b83a9dcb4ec2..f0646533e284 100644 --- a/extensions/Particle3D/PU/CCPUBillboardChain.cpp +++ b/extensions/Particle3D/PU/CCPUBillboardChain.cpp @@ -48,8 +48,8 @@ PUBillboardChain::Element::Element(const Vec3& pos, float w, float tex, const Ve : position(pos), width(w), texCoord(tex), color(col), orientation(ori) {} //----------------------------------------------------------------------- -PUBillboardChain::PUBillboardChain(const std::string& /*name*/, - const std::string& texFile, +PUBillboardChain::PUBillboardChain(std::string_view /*name*/, + std::string_view texFile, size_t maxElements, size_t numberOfChains, bool useTextureCoords, @@ -627,7 +627,7 @@ void PUBillboardChain::updateIndexBuffer() } } //----------------------------------------------------------------------- -void PUBillboardChain::init(const std::string& texFile) +void PUBillboardChain::init(std::string_view texFile) { CC_SAFE_RELEASE_NULL(_programState); diff --git a/extensions/Particle3D/PU/CCPUBillboardChain.h b/extensions/Particle3D/PU/CCPUBillboardChain.h index 329029d2aca0..ce4b77cac54d 100644 --- a/extensions/Particle3D/PU/CCPUBillboardChain.h +++ b/extensions/Particle3D/PU/CCPUBillboardChain.h @@ -77,13 +77,13 @@ class PUBillboardChain @param useVertexColours If true, use vertex colours from the chain elements @param dynamic If true, buffers are created with the intention of being updated */ - PUBillboardChain(const std::string& name, - const std::string& texFile = "", - size_t maxElements = 20, - size_t numberOfChains = 1, - bool useTextureCoords = true, - bool useColours = true, - bool dynamic = true); + PUBillboardChain(std::string_view name, + std::string_view texFile = "", + size_t maxElements = 20, + size_t numberOfChains = 1, + bool useTextureCoords = true, + bool useColours = true, + bool dynamic = true); /// destructor virtual ~PUBillboardChain(); @@ -245,7 +245,7 @@ class PUBillboardChain /// Update the contents of the index buffer virtual void updateIndexBuffer(); - void init(const std::string& texFile); + void init(std::string_view texFile); private: void onBeforeDraw(); diff --git a/extensions/Particle3D/PU/CCPUDoAffectorEventHandler.h b/extensions/Particle3D/PU/CCPUDoAffectorEventHandler.h index 3c2985c3d1b0..b4425d880c75 100644 --- a/extensions/Particle3D/PU/CCPUDoAffectorEventHandler.h +++ b/extensions/Particle3D/PU/CCPUDoAffectorEventHandler.h @@ -57,11 +57,11 @@ class CC_EX_DLL PUDoAffectorEventHandler : public PUEventHandler /** Get the name of the affector that must be enabled or disabled. */ - const std::string& getAffectorName() const { return _affectorName; }; + std::string_view getAffectorName() const { return _affectorName; }; /** Set the name of the affector. */ - void setAffectorName(const std::string& affectorName) { _affectorName = affectorName; }; + void setAffectorName(std::string_view affectorName) { _affectorName = affectorName; }; /** If the _handle() function of this class is invoked (by an Observer), it searches the ParticleAffector defined by the its name. diff --git a/extensions/Particle3D/PU/CCPUDoEnableComponentEventHandler.h b/extensions/Particle3D/PU/CCPUDoEnableComponentEventHandler.h index 9c9ff4c0fdd2..94e56865f26e 100644 --- a/extensions/Particle3D/PU/CCPUDoEnableComponentEventHandler.h +++ b/extensions/Particle3D/PU/CCPUDoEnableComponentEventHandler.h @@ -47,11 +47,11 @@ class CC_EX_DLL PUDoEnableComponentEventHandler : public PUEventHandler /** Get the name of the component that must be enabled or disabled. */ - const std::string& getComponentName() const { return _componentName; }; + std::string_view getComponentName() const { return _componentName; }; /** Set the name of the component that must be enabled or disables. */ - void setComponentName(const std::string& componentName) { _componentName = componentName; }; + void setComponentName(std::string_view componentName) { _componentName = componentName; }; /** Get the value that identifies whether the component must be enabled or disabled. */ diff --git a/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.cpp b/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.cpp index f70ba179ff43..d572be111809 100644 --- a/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.cpp +++ b/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.cpp @@ -241,7 +241,7 @@ void PUDoPlacementParticleEventHandler::particleExpired(PUParticleSystem3D* /*pa {} //----------------------------------------------------------------------- -void PUDoPlacementParticleEventHandler::setForceEmitterName(const std::string& forceEmitterName) +void PUDoPlacementParticleEventHandler::setForceEmitterName(std::string_view forceEmitterName) { _forceEmitterName = forceEmitterName; } diff --git a/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.h b/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.h index cb33bb8cbd2f..3304e7309499 100644 --- a/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.h +++ b/extensions/Particle3D/PU/CCPUDoPlacementParticleEventHandler.h @@ -78,11 +78,11 @@ class CC_EX_DLL PUDoPlacementParticleEventHandler : public PUEventHandler, publi /** Get the name of the emitter that is used to emit its particles. */ - const std::string& getForceEmitterName() const { return _forceEmitterName; }; + std::string_view getForceEmitterName() const { return _forceEmitterName; }; /** Set the name of the emitter that is used to emit its particles. */ - void setForceEmitterName(const std::string& forceEmitterName); + void setForceEmitterName(std::string_view forceEmitterName); /** Returns a pointer to the emitter that is used as a force emitter. */ diff --git a/extensions/Particle3D/PU/CCPUEmitter.cpp b/extensions/Particle3D/PU/CCPUEmitter.cpp index fdf3ac0487a3..2914895a70a0 100644 --- a/extensions/Particle3D/PU/CCPUEmitter.cpp +++ b/extensions/Particle3D/PU/CCPUEmitter.cpp @@ -497,7 +497,7 @@ void PUEmitter::setParticleTextureCoordsRangeEnd(const unsigned short& particleT } //----------------------------------------------------------------------- -void PUEmitter::setEmitsName(const std::string& emitsName) +void PUEmitter::setEmitsName(std::string_view emitsName) { _emitsName = emitsName; _emitsEntity = nullptr; diff --git a/extensions/Particle3D/PU/CCPUEmitter.h b/extensions/Particle3D/PU/CCPUEmitter.h index 4aa3c3a1634a..bccc699bdf6c 100644 --- a/extensions/Particle3D/PU/CCPUEmitter.h +++ b/extensions/Particle3D/PU/CCPUEmitter.h @@ -112,13 +112,13 @@ class CC_EX_DLL PUEmitter : public Particle3DEmitter /** Todo */ - const std::string& getEmitterType() const { return _emitterType; } - void setEmitterType(const std::string& emitterType) { _emitterType = emitterType; }; + std::string_view getEmitterType() const { return _emitterType; } + void setEmitterType(std::string_view emitterType) { _emitterType = emitterType; }; /** Todo */ - const std::string& getName() const { return _name; } - void setName(const std::string& name) { _name = name; }; + std::string_view getName() const { return _name; } + void setName(std::string_view name) { _name = name; }; /** Todo */ @@ -188,8 +188,8 @@ class CC_EX_DLL PUEmitter : public Particle3DEmitter /** Todo */ - const std::string& getEmitsName() const { return _emitsName; } - void setEmitsName(const std::string& emitsName); + std::string_view getEmitsName() const { return _emitsName; } + void setEmitsName(std::string_view emitsName); PUParticle3D::ParticleType getEmitsType() const { return _emitsType; } void setEmitsType(PUParticle3D::ParticleType type) { _emitsType = type; }; Ref* getEmitsEntityPtr() const; diff --git a/extensions/Particle3D/PU/CCPUEmitterManager.cpp b/extensions/Particle3D/PU/CCPUEmitterManager.cpp index f18566fc94eb..4c587b04aa49 100644 --- a/extensions/Particle3D/PU/CCPUEmitterManager.cpp +++ b/extensions/Particle3D/PU/CCPUEmitterManager.cpp @@ -45,7 +45,7 @@ PUEmitterManager* PUEmitterManager::Instance() return &ptm; } -PUScriptTranslator* PUEmitterManager::getTranslator(const std::string& type) +PUScriptTranslator* PUEmitterManager::getTranslator(std::string_view type) { if (type == "Box") { @@ -86,7 +86,7 @@ PUScriptTranslator* PUEmitterManager::getTranslator(const std::string& type) return nullptr; } -PUEmitter* PUEmitterManager::createEmitter(const std::string& type) +PUEmitter* PUEmitterManager::createEmitter(std::string_view type) { if (type == "Box") { diff --git a/extensions/Particle3D/PU/CCPUEmitterManager.h b/extensions/Particle3D/PU/CCPUEmitterManager.h index 00ee4c33ae65..5affa49ef8be 100644 --- a/extensions/Particle3D/PU/CCPUEmitterManager.h +++ b/extensions/Particle3D/PU/CCPUEmitterManager.h @@ -48,8 +48,8 @@ class PUEmitterManager /** */ - PUScriptTranslator* getTranslator(const std::string& type); - PUEmitter* createEmitter(const std::string& type); + PUScriptTranslator* getTranslator(std::string_view type); + PUEmitter* createEmitter(std::string_view type); CC_CONSTRUCTOR_ACCESS : PUEmitterManager(); ~PUEmitterManager(); diff --git a/extensions/Particle3D/PU/CCPUEventHandler.h b/extensions/Particle3D/PU/CCPUEventHandler.h index 771252122f71..a9f4582b7780 100644 --- a/extensions/Particle3D/PU/CCPUEventHandler.h +++ b/extensions/Particle3D/PU/CCPUEventHandler.h @@ -44,8 +44,8 @@ class CC_EX_DLL PUEventHandler : public Ref public: /** Todo */ - const std::string& getName() const { return _name; }; - void setName(const std::string& name) { _name = name; }; + std::string_view getName() const { return _name; }; + void setName(std::string_view name) { _name = name; }; /** Todo */ @@ -54,8 +54,8 @@ class CC_EX_DLL PUEventHandler : public Ref /** Todo */ - const std::string& getEventHandlerType() const { return _eventHandlerType; }; - void setEventHandlerType(const std::string& eventHandlerType) { _eventHandlerType = eventHandlerType; }; + std::string_view getEventHandlerType() const { return _eventHandlerType; }; + void setEventHandlerType(std::string_view eventHandlerType) { _eventHandlerType = eventHandlerType; }; /** Notify that the event handler is rescaled. */ diff --git a/extensions/Particle3D/PU/CCPUEventHandlerManager.cpp b/extensions/Particle3D/PU/CCPUEventHandlerManager.cpp index df3803a8f43d..06206b7b9936 100644 --- a/extensions/Particle3D/PU/CCPUEventHandlerManager.cpp +++ b/extensions/Particle3D/PU/CCPUEventHandlerManager.cpp @@ -44,7 +44,7 @@ PUEventHandlerManager* PUEventHandlerManager::Instance() return &pem; } -PUScriptTranslator* PUEventHandlerManager::getTranslator(const std::string& type) +PUScriptTranslator* PUEventHandlerManager::getTranslator(std::string_view type) { if (type == "DoAffector") { @@ -77,7 +77,7 @@ PUScriptTranslator* PUEventHandlerManager::getTranslator(const std::string& type return nullptr; } -PUEventHandler* PUEventHandlerManager::createEventHandler(const std::string& type) +PUEventHandler* PUEventHandlerManager::createEventHandler(std::string_view type) { if (type == "DoAffector") { diff --git a/extensions/Particle3D/PU/CCPUEventHandlerManager.h b/extensions/Particle3D/PU/CCPUEventHandlerManager.h index 2cc470c60bb7..bd09e1487c7b 100644 --- a/extensions/Particle3D/PU/CCPUEventHandlerManager.h +++ b/extensions/Particle3D/PU/CCPUEventHandlerManager.h @@ -45,8 +45,8 @@ class PUEventHandlerManager /** */ - PUScriptTranslator* getTranslator(const std::string& type); - PUEventHandler* createEventHandler(const std::string& type); + PUScriptTranslator* getTranslator(std::string_view type); + PUEventHandler* createEventHandler(std::string_view type); CC_CONSTRUCTOR_ACCESS : diff --git a/extensions/Particle3D/PU/CCPULineEmitter.cpp b/extensions/Particle3D/PU/CCPULineEmitter.cpp index 394307f312ec..674822c247d9 100644 --- a/extensions/Particle3D/PU/CCPULineEmitter.cpp +++ b/extensions/Particle3D/PU/CCPULineEmitter.cpp @@ -92,7 +92,7 @@ unsigned short PULineEmitter::calculateRequestedParticles(float timeElapsed) //{ // notifyStart(); // mParentTechnique->lockAllParticles(); // Needed to set the first generated particle also first in the - //list with particles + // list with particles // } } diff --git a/extensions/Particle3D/PU/CCPUMaterialManager.cpp b/extensions/Particle3D/PU/CCPUMaterialManager.cpp index 05aa70292cf6..3e1d3469e5a3 100644 --- a/extensions/Particle3D/PU/CCPUMaterialManager.cpp +++ b/extensions/Particle3D/PU/CCPUMaterialManager.cpp @@ -77,7 +77,7 @@ PUMaterialCache* PUMaterialCache::Instance() return &pmm; } -PUMaterial* PUMaterialCache::getMaterial(const std::string& name) +PUMaterial* PUMaterialCache::getMaterial(std::string_view name) { for (auto iter : _materialMap) { @@ -87,7 +87,7 @@ PUMaterial* PUMaterialCache::getMaterial(const std::string& name) return nullptr; } -bool PUMaterialCache::loadMaterials(const std::string& file) +bool PUMaterialCache::loadMaterials(std::string_view file) { bool isFirstCompile = true; auto list = PUScriptCompiler::Instance()->compile(file, isFirstCompile); @@ -128,53 +128,59 @@ int iterPath(const char* fpath, const struct stat* /*sb*/, int typeflag) } #endif -bool PUMaterialCache::loadMaterialsFromSearchPaths(const std::string& fileFolder) +bool PUMaterialCache::loadMaterialsFromSearchPaths(std::string_view fileFolder) { bool state = false; #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) std::string seg("/"); - std::string fullPath = fileFolder + seg + std::string("*.material"); + std::string fullPath{fileFolder}; + fullPath += seg; + fullPath += std::string("*.material"); _finddata_t data; intptr_t handle = _findfirst(fullPath.c_str(), &data); int done = 0; while ((handle != -1) && (done == 0)) { - loadMaterials(fileFolder + seg + std::string(data.name)); + fullPath = fileFolder; + fullPath += seg; + fullPath += data.name; + loadMaterials(fullPath); done = _findnext(handle, &data); state = true; } _findclose(handle); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID /* || CC_TARGET_PLATFORM == CC_PLATFORM_LINUX*/) - std::string::size_type pos = fileFolder.find("assets/"); - std::string relativePath = fileFolder; + std::string::size_type pos = fileFolder.find("assets/"); + std::string_view relativePath = fileFolder; if (pos != std::string::npos) { // "assets/" is at the beginning of the path and we don't want it relativePath = fileFolder.substr(pos + strlen("assets/")); } - AAssetDir* dir = AAssetManager_openDir(FileUtilsAndroid::getAssetManager(), relativePath.c_str()); + AAssetDir* dir = AAssetManager_openDir(FileUtilsAndroid::getAssetManager(), relativePath.data()); const char* fileName = nullptr; - std::string seg("/"); + std::string_view seg("/", 1); + std::string fullpath; while ((fileName = AAssetDir_getNextFileName(dir)) != nullptr) { if (FileUtils::getInstance()->getFileExtension(fileName) == ".material") { - std::string fullpath = fileFolder + seg + std::string(fileName); + fullpath.assign(fileFolder).append(seg).append(fileName); loadMaterials(fullpath); } } AAssetDir_close(dir); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) - ftw(fileFolder.c_str(), iterPath, 500); + ftw(fileFolder.data(), iterPath, 500); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX || CC_TARGET_PLATFORM == CC_PLATFORM_TIZEN) DIR* d; // dir handle struct dirent* file; // readdir struct stat statbuf; - if (!(d = opendir(fileFolder.c_str()))) + if (!(d = opendir(fileFolder.data()))) { - CCLOG("error opendir %s!!!\n", fileFolder.c_str()); + CCLOG("error opendir %s!!!\n", fileFolder.data()); return false; } while ((file = readdir(d)) != NULL) @@ -186,7 +192,8 @@ bool PUMaterialCache::loadMaterialsFromSearchPaths(const std::string& fileFolder if (FileUtils::getInstance()->getFileExtension(file->d_name) == ".material") { - std::string fullpath = fileFolder + "/" + file->d_name; + std::string fullpath{fileFolder}; + fullpath.append("/"sv).append(file->d_name); CCLOG("%s", fullpath.c_str()); loadMaterials(fullpath); state = true; diff --git a/extensions/Particle3D/PU/CCPUMaterialManager.h b/extensions/Particle3D/PU/CCPUMaterialManager.h index 54543ce34919..a5cbac89349b 100644 --- a/extensions/Particle3D/PU/CCPUMaterialManager.h +++ b/extensions/Particle3D/PU/CCPUMaterialManager.h @@ -63,9 +63,9 @@ class CC_EX_DLL PUMaterialCache static PUMaterialCache* Instance(); - bool loadMaterials(const std::string& file); - bool loadMaterialsFromSearchPaths(const std::string& fileFolder); - PUMaterial* getMaterial(const std::string& name); + bool loadMaterials(std::string_view file); + bool loadMaterialsFromSearchPaths(std::string_view fileFolder); + PUMaterial* getMaterial(std::string_view name); void addMaterial(PUMaterial* material); protected: diff --git a/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.cpp b/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.cpp index b453dc4126c8..2c787ebd3e71 100644 --- a/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.cpp +++ b/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.cpp @@ -162,7 +162,7 @@ const PUTriangle::PositionAndNormal PUTriangle::getRandomVertexAndNormal() //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- -MeshInfo::MeshInfo(const std::string& /*meshName*/, +MeshInfo::MeshInfo(std::string_view /*meshName*/, MeshSurfaceDistribution distribution, const Quaternion& /*orientation*/, const Vec3& /*scale*/) @@ -307,7 +307,7 @@ const PUTriangle::PositionAndNormal MeshInfo::getRandomPositionAndNormal(const s // { // Ogre::SubMesh* submesh = mesh->getSubMesh(i); // Ogre::VertexData* vertex_data = submesh->useSharedVertices ? mesh->sharedVertexData : -//submesh->vertexData; +// submesh->vertexData; // // if((!submesh->useSharedVertices)||(submesh->useSharedVertices && !added_shared)) // { @@ -318,10 +318,11 @@ const PUTriangle::PositionAndNormal MeshInfo::getRandomPositionAndNormal(const s // } // // const Ogre::VertexElement* posElem = -//vertex_data->vertexDeclaration->findElementBySemantic(Ogre::VES_POSITION); const Ogre::VertexElement* normalElem = -//vertex_data->vertexDeclaration->findElementBySemantic(Ogre::VES_NORMAL); Ogre::HardwareVertexBufferSharedPtr vbuf = -//vertex_data->vertexBufferBinding->getBuffer(posElem->getSource()); unsigned char* vertex = static_cast(vbuf->lock(Ogre::HardwareBuffer::HBL_READ_ONLY)); float* pReal; +// vertex_data->vertexDeclaration->findElementBySemantic(Ogre::VES_POSITION); const +// Ogre::VertexElement* normalElem = vertex_data->vertexDeclaration->findElementBySemantic(Ogre::VES_NORMAL); +// Ogre::HardwareVertexBufferSharedPtr vbuf = vertex_data->vertexBufferBinding->getBuffer(posElem->getSource()); +// unsigned char* vertex = static_cast(vbuf->lock(Ogre::HardwareBuffer::HBL_READ_ONLY)); +// float* pReal; // // for( size_t j = 0; j < vertex_data->vertexCount; ++j, vertex += vbuf->getVertexSize()) // { @@ -359,7 +360,7 @@ const PUTriangle::PositionAndNormal MeshInfo::getRandomPositionAndNormal(const s // for ( size_t k = 0; k < numTrisMultThree; ++k) // { // indices[index_offset++] = static_cast(pShort[k]) + static_cast(offset); +// long>(offset); // } // } // @@ -527,12 +528,12 @@ void PUMeshSurfaceEmitter::initParticleDirection(PUParticle3D* particle) } } //----------------------------------------------------------------------- -const std::string& PUMeshSurfaceEmitter::getMeshName() const +std::string_view PUMeshSurfaceEmitter::getMeshName() const { return _meshName; } //----------------------------------------------------------------------- -void PUMeshSurfaceEmitter::setMeshName(const std::string& meshName, bool doBuild) +void PUMeshSurfaceEmitter::setMeshName(std::string_view meshName, bool doBuild) { _meshName = meshName; diff --git a/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.h b/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.h index 9f1cd8389f03..553d10117623 100644 --- a/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.h +++ b/extensions/Particle3D/PU/CCPUMeshSurfaceEmitter.h @@ -119,7 +119,7 @@ class MeshInfo }; /** Constructor **/ - MeshInfo(const std::string& meshName, + MeshInfo(std::string_view meshName, const MeshSurfaceDistribution distribution = MSD_HOMOGENEOUS, const Quaternion& orientation = Quaternion(), const Vec3& scale = Vec3::ZERO); @@ -173,11 +173,11 @@ class CC_EX_DLL PUMeshSurfaceEmitter : public PUEmitter /** Returns the mesh name. */ - const std::string& getMeshName() const; + std::string_view getMeshName() const; /** Sets the mesh name. */ - void setMeshName(const std::string& meshName, bool doBuild = true); + void setMeshName(std::string_view meshName, bool doBuild = true); /** Returns true if normals are used for the particle direction. */ diff --git a/extensions/Particle3D/PU/CCPUObserver.cpp b/extensions/Particle3D/PU/CCPUObserver.cpp index 6b93991b2a71..edfc370560a3 100644 --- a/extensions/Particle3D/PU/CCPUObserver.cpp +++ b/extensions/Particle3D/PU/CCPUObserver.cpp @@ -130,7 +130,7 @@ void PUObserver::notifyRescaled(const Vec3& scale) } } //----------------------------------------------------------------------- -PUEventHandler* PUObserver::createEventHandler(const std::string& eventHandlerType) +PUEventHandler* PUObserver::createEventHandler(std::string_view eventHandlerType) { PUEventHandler* eventHandler = PUEventHandlerManager::Instance()->createEventHandler(eventHandlerType); addEventHandler(eventHandler); @@ -168,7 +168,7 @@ PUEventHandler* PUObserver::getEventHandler(size_t index) const return _eventHandlers[index]; } //----------------------------------------------------------------------- -PUEventHandler* PUObserver::getEventHandler(const std::string& eventHandlerName) const +PUEventHandler* PUObserver::getEventHandler(std::string_view eventHandlerName) const { if (eventHandlerName.empty()) return nullptr; diff --git a/extensions/Particle3D/PU/CCPUObserver.h b/extensions/Particle3D/PU/CCPUObserver.h index c2455aa0368e..dcb354bc02ac 100644 --- a/extensions/Particle3D/PU/CCPUObserver.h +++ b/extensions/Particle3D/PU/CCPUObserver.h @@ -63,8 +63,8 @@ class CC_EX_DLL PUObserver : public Ref /** Todo */ - const std::string& getObserverType() const { return _observerType; }; - void setObserverType(const std::string& observerType) { _observerType = observerType; }; + std::string_view getObserverType() const { return _observerType; }; + void setObserverType(std::string_view observerType) { _observerType = observerType; }; /** Todo */ @@ -93,8 +93,8 @@ class CC_EX_DLL PUObserver : public Ref /** Todo */ - const std::string& getName() const { return _name; }; - void setName(const std::string& name) { _name = name; }; + std::string_view getName() const { return _name; }; + void setName(std::string_view name) { _name = name; }; /** Todo */ @@ -115,7 +115,7 @@ class CC_EX_DLL PUObserver : public Ref /** Todo */ - PUEventHandler* createEventHandler(const std::string& eventHandlerType); + PUEventHandler* createEventHandler(std::string_view eventHandlerType); /** Todo */ @@ -131,7 +131,7 @@ class CC_EX_DLL PUObserver : public Ref /** Todo */ - PUEventHandler* getEventHandler(const std::string& eventHandlerName) const; + PUEventHandler* getEventHandler(std::string_view eventHandlerName) const; /** Todo */ diff --git a/extensions/Particle3D/PU/CCPUObserverManager.cpp b/extensions/Particle3D/PU/CCPUObserverManager.cpp index 3ac7859ed6d9..a90e2fdb0941 100644 --- a/extensions/Particle3D/PU/CCPUObserverManager.cpp +++ b/extensions/Particle3D/PU/CCPUObserverManager.cpp @@ -48,7 +48,7 @@ PUObserverManager* PUObserverManager::Instance() return &pem; } -PUScriptTranslator* PUObserverManager::getTranslator(const std::string& type) +PUScriptTranslator* PUObserverManager::getTranslator(std::string_view type) { if (type == "OnClear") { @@ -97,7 +97,7 @@ PUScriptTranslator* PUObserverManager::getTranslator(const std::string& type) return nullptr; } -PUObserver* PUObserverManager::createObserver(const std::string& type) +PUObserver* PUObserverManager::createObserver(std::string_view type) { if (type == "OnClear") { diff --git a/extensions/Particle3D/PU/CCPUObserverManager.h b/extensions/Particle3D/PU/CCPUObserverManager.h index cd1a69dac889..8134843e1b34 100644 --- a/extensions/Particle3D/PU/CCPUObserverManager.h +++ b/extensions/Particle3D/PU/CCPUObserverManager.h @@ -50,8 +50,8 @@ class PUObserverManager /** */ - PUScriptTranslator* getTranslator(const std::string& type); - PUObserver* createObserver(const std::string& type); + PUScriptTranslator* getTranslator(std::string_view type); + PUObserver* createObserver(std::string_view type); CC_CONSTRUCTOR_ACCESS : diff --git a/extensions/Particle3D/PU/CCPUParticleSystem3D.cpp b/extensions/Particle3D/PU/CCPUParticleSystem3D.cpp index e9818e3a2512..4f5ea0c39366 100644 --- a/extensions/Particle3D/PU/CCPUParticleSystem3D.cpp +++ b/extensions/Particle3D/PU/CCPUParticleSystem3D.cpp @@ -259,7 +259,7 @@ PUParticleSystem3D* PUParticleSystem3D::create() return pups; } -PUParticleSystem3D* PUParticleSystem3D::create(const std::string& filePath, const std::string& materialPath) +PUParticleSystem3D* PUParticleSystem3D::create(std::string_view filePath, std::string_view materialPath) { PUParticleSystem3D* ret = new PUParticleSystem3D(); if (ret->initWithFilePathAndMaterialPath(filePath, materialPath)) @@ -274,7 +274,7 @@ PUParticleSystem3D* PUParticleSystem3D::create(const std::string& filePath, cons } } -PUParticleSystem3D* PUParticleSystem3D::create(const std::string& filePath) +PUParticleSystem3D* PUParticleSystem3D::create(std::string_view filePath) { PUParticleSystem3D* ret = new PUParticleSystem3D(); if (ret->initWithFilePath(filePath)) @@ -289,7 +289,7 @@ PUParticleSystem3D* PUParticleSystem3D::create(const std::string& filePath) } } -bool PUParticleSystem3D::initWithFilePath(const std::string& filePath) +bool PUParticleSystem3D::initWithFilePath(std::string_view filePath) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); convertToUnixStylePath(fullPath); @@ -318,7 +318,7 @@ bool PUParticleSystem3D::initWithFilePath(const std::string& filePath) return true; } -bool PUParticleSystem3D::initWithFilePathAndMaterialPath(const std::string& filePath, const std::string& materialPath) +bool PUParticleSystem3D::initWithFilePathAndMaterialPath(std::string_view filePath, std::string_view materialPath) { std::string matfullPath = FileUtils::getInstance()->fullPathForFilename(materialPath); convertToUnixStylePath(matfullPath); @@ -629,24 +629,24 @@ void PUParticleSystem3D::unPrepared() _particlePool.lockAllDatas(); for (auto& iter : _emittedEmitterParticlePool) { - PUParticle3D* particle = static_cast(iter.second.getFirst()); + PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->unPrepare(); - particle = static_cast(iter.second.getNext()); + particle = static_cast(const_cast(iter.second).getNext()); } - iter.second.lockAllDatas(); + const_cast(iter.second).lockAllDatas(); } for (auto& iter : _emittedSystemParticlePool) { - PUParticle3D* particle = static_cast(iter.second.getFirst()); + PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->unPrepared(); - particle = static_cast(iter.second.getNext()); + particle = static_cast(const_cast(iter.second).getNext()); } - iter.second.lockAllDatas(); + const_cast(iter.second).lockAllDatas(); } _prepared = false; } @@ -692,21 +692,21 @@ void PUParticleSystem3D::preUpdator(float elapsedTime) for (auto& iter : _emittedEmitterParticlePool) { - PUParticle3D* particle = static_cast(iter.second.getFirst()); + PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->preUpdateEmitter(elapsedTime); - particle = static_cast(iter.second.getNext()); + particle = static_cast(const_cast(iter.second).getNext()); } } for (auto& iter : _emittedSystemParticlePool) { - PUParticle3D* particle = static_cast(iter.second.getFirst()); + PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->preUpdator(elapsedTime); - particle = static_cast(iter.second.getNext()); + particle = static_cast(const_cast(iter.second).getNext()); } } } @@ -719,12 +719,12 @@ void PUParticleSystem3D::updator(float elapsedTime) for (auto& iter : _emittedEmitterParticlePool) { - processParticle(iter.second, firstActiveParticle, firstParticle, elapsedTime); + processParticle(const_cast(iter.second), firstActiveParticle, firstParticle, elapsedTime); } for (auto& iter : _emittedSystemParticlePool) { - processParticle(iter.second, firstActiveParticle, firstParticle, elapsedTime); + processParticle(const_cast(iter.second), firstActiveParticle, firstParticle, elapsedTime); } } @@ -763,21 +763,21 @@ void PUParticleSystem3D::postUpdator(float elapsedTime) for (auto& iter : _emittedEmitterParticlePool) { - PUParticle3D* particle = static_cast(iter.second.getFirst()); + PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->postUpdateEmitter(elapsedTime); - particle = static_cast(iter.second.getNext()); + particle = static_cast(const_cast(iter.second).getNext()); } } for (auto& iter : _emittedSystemParticlePool) { - PUParticle3D* particle = static_cast(iter.second.getFirst()); + PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->postUpdator(elapsedTime); - particle = static_cast(iter.second.getNext()); + particle = static_cast(const_cast(iter.second).getNext()); } } } @@ -901,7 +901,7 @@ void PUParticleSystem3D::setMaxVelocity(float maxVelocity) _maxVelocitySet = true; } -bool PUParticleSystem3D::initSystem(const std::string& filePath) +bool PUParticleSystem3D::initSystem(std::string_view filePath) { bool isFirstCompile = true; auto list = PUScriptCompiler::Instance()->compile(filePath, isFirstCompile); @@ -922,7 +922,7 @@ void PUParticleSystem3D::addEmitter(PUEmitter* emitter) } } -PUAffector* PUParticleSystem3D::getAffector(const std::string& name) +PUAffector* PUParticleSystem3D::getAffector(std::string_view name) { for (auto iter : _affectors) { @@ -934,7 +934,7 @@ PUAffector* PUParticleSystem3D::getAffector(const std::string& name) return nullptr; } -PUEmitter* PUParticleSystem3D::getEmitter(const std::string& name) +PUEmitter* PUParticleSystem3D::getEmitter(std::string_view name) { for (auto iter : _emitters) { @@ -1040,7 +1040,7 @@ void PUParticleSystem3D::addObserver(PUObserver* observer) } } -PUObserver* PUParticleSystem3D::getObserver(const std::string& name) +PUObserver* PUParticleSystem3D::getObserver(std::string_view name) { for (auto iter : _observers) { @@ -1074,21 +1074,21 @@ void PUParticleSystem3D::notifyRescaled(const Vec3& scl) for (auto& iter : _emittedEmitterParticlePool) { - PUParticle3D* particle = static_cast(iter.second.getFirst()); + PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->notifyRescaled(scl); - particle = static_cast(iter.second.getNext()); + particle = static_cast(const_cast(iter.second).getNext()); } } for (auto& iter : _emittedSystemParticlePool) { - PUParticle3D* particle = static_cast(iter.second.getFirst()); + PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->notifyRescaled(scl); - particle = static_cast(iter.second.getNext()); + particle = static_cast(const_cast(iter.second).getNext()); } } } @@ -1113,7 +1113,7 @@ void PUParticleSystem3D::initParticleForExpiration(PUParticle3D* particle, float it->particleExpired(this, particle); } ///** Externs are also called to perform expiration activities. If needed, affectors and emitters may be added, but - ///at the moment + /// at the moment // there is no reason for (and we don't want to waste cpu resources). //*/ // if (!mExterns.empty()) @@ -1164,12 +1164,12 @@ void PUParticleSystem3D::clearAllParticles() _particlePool.lockAllDatas(); for (auto& iter : _emittedEmitterParticlePool) { - iter.second.lockAllDatas(); + const_cast(iter.second).lockAllDatas(); } for (auto& iter : _emittedSystemParticlePool) { - iter.second.lockAllDatas(); + const_cast(iter.second).lockAllDatas(); } } @@ -1303,11 +1303,11 @@ void PUParticleSystem3D::draw(Renderer* renderer, const Mat4& transform, uint32_ { for (auto& iter : _emittedSystemParticlePool) { - PUParticle3D* particle = static_cast(iter.second.getFirst()); + PUParticle3D* particle = static_cast(const_cast(iter.second).getFirst()); while (particle) { static_cast(particle->particleEntityPtr)->draw(renderer, transform, flags); - particle = static_cast(iter.second.getNext()); + particle = static_cast(const_cast(iter.second).getNext()); } } } diff --git a/extensions/Particle3D/PU/CCPUParticleSystem3D.h b/extensions/Particle3D/PU/CCPUParticleSystem3D.h index 4b73e26c1d2a..d7773d9892df 100644 --- a/extensions/Particle3D/PU/CCPUParticleSystem3D.h +++ b/extensions/Particle3D/PU/CCPUParticleSystem3D.h @@ -207,7 +207,7 @@ struct CC_EX_DLL PUParticle3D : public Particle3D class CC_EX_DLL PUParticleSystem3D : public ParticleSystem3D { public: - typedef std::unordered_map ParticlePoolMap; + typedef hlookup::string_map ParticlePoolMap; static const float DEFAULT_WIDTH; static const float DEFAULT_HEIGHT; @@ -218,8 +218,8 @@ class CC_EX_DLL PUParticleSystem3D : public ParticleSystem3D static const float DEFAULT_MAX_VELOCITY; static PUParticleSystem3D* create(); - static PUParticleSystem3D* create(const std::string& filePath); - static PUParticleSystem3D* create(const std::string& filePath, const std::string& materialPath); + static PUParticleSystem3D* create(std::string_view filePath); + static PUParticleSystem3D* create(std::string_view filePath, std::string_view materialPath); virtual void draw(Renderer* renderer, const Mat4& transform, uint32_t flags) override; @@ -296,8 +296,8 @@ class CC_EX_DLL PUParticleSystem3D : public ParticleSystem3D */ void setMaxVelocity(float maxVelocity); - void setMaterialName(const std::string& name) { _matName = name; }; - const std::string& getMaterialName() const { return _matName; }; + void setMaterialName(std::string_view name) { _matName = name; }; + std::string_view getMaterialName() const { return _matName; }; /** Forces emission of particles. * @remarks The number of requested particles are the exact number that are emitted. No down-scaling is applied. @@ -309,8 +309,8 @@ class CC_EX_DLL PUParticleSystem3D : public ParticleSystem3D */ void addEmitter(PUEmitter* emitter); - PUAffector* getAffector(const std::string& name); - PUEmitter* getEmitter(const std::string& name); + PUAffector* getAffector(std::string_view name); + PUEmitter* getEmitter(std::string_view name); void removeAllEmitter(); void addListener(PUListener* listener); @@ -318,7 +318,7 @@ class CC_EX_DLL PUParticleSystem3D : public ParticleSystem3D void removeAllListener(); void addObserver(PUObserver* observer); - PUObserver* getObserver(const std::string& name); + PUObserver* getObserver(std::string_view name); void removerAllObserver(); void addBehaviourTemplate(PUBehaviour* behaviour); @@ -346,13 +346,13 @@ class CC_EX_DLL PUParticleSystem3D : public ParticleSystem3D virtual PUParticleSystem3D* clone(); virtual void copyAttributesTo(PUParticleSystem3D* system); - bool initSystem(const std::string& filePath); + bool initSystem(std::string_view filePath); CC_CONSTRUCTOR_ACCESS : PUParticleSystem3D(); virtual ~PUParticleSystem3D(); - bool initWithFilePath(const std::string& filePath); - bool initWithFilePathAndMaterialPath(const std::string& filePath, const std::string& materialPath); + bool initWithFilePath(std::string_view filePath); + bool initWithFilePathAndMaterialPath(std::string_view filePath, std::string_view materialPath); protected: void prepared(); diff --git a/extensions/Particle3D/PU/CCPUParticleSystem3DTranslator.cpp b/extensions/Particle3D/PU/CCPUParticleSystem3DTranslator.cpp index 29b6e0869717..819aa25f7d9e 100644 --- a/extensions/Particle3D/PU/CCPUParticleSystem3DTranslator.cpp +++ b/extensions/Particle3D/PU/CCPUParticleSystem3DTranslator.cpp @@ -107,7 +107,7 @@ void PUParticleSystem3DTranslator::translate(PUScriptCompiler* compiler, PUAbstr // else // { // compiler->addError(PUScriptCompiler::CE_NUMBEREXPECTED, prop->file, - //prop->line, + // prop->line, // "PU Compiler: lod_distances expects only numbers as // arguments"); // } @@ -238,7 +238,8 @@ void PUParticleSystem3DTranslator::translate(PUScriptCompiler* compiler, PUAbstr // { // ParticleTechnique* technique = static_cast(alias); // ParticleTechnique* newTechnique = - //ParticleSystemManager::getSingletonPtr()->cloneTechnique(technique); mSystem->addTechnique(newTechnique); + // ParticleSystemManager::getSingletonPtr()->cloneTechnique(technique); + // mSystem->addTechnique(newTechnique); // } // } // } diff --git a/extensions/Particle3D/PU/CCPURender.cpp b/extensions/Particle3D/PU/CCPURender.cpp index d22e2c977f01..62c250500702 100644 --- a/extensions/Particle3D/PU/CCPURender.cpp +++ b/extensions/Particle3D/PU/CCPURender.cpp @@ -56,7 +56,7 @@ void PURender::copyAttributesTo(PURender* render) // return left->depthInView > right->depthInView; // } -PUParticle3DQuadRender* PUParticle3DQuadRender::create(const std::string& texFile) +PUParticle3DQuadRender* PUParticle3DQuadRender::create(std::string_view texFile) { auto ret = new PUParticle3DQuadRender(); if (ret->initRender(texFile)) @@ -227,25 +227,25 @@ void PUParticle3DQuadRender::render(Renderer* renderer, const Mat4& transform, P //_posuvcolors[vertexindex].position = (position + (- halfwidth - halfheight + halfwidth * offsetX + halfheight //* offsetY)); _posuvcolors[vertexindex].color = particle->color; _posuvcolors[vertexindex].uv.set(val.x + - //texOffset.x, val.y + texOffset.y); + // texOffset.x, val.y + texOffset.y); // val.set(particle->rt_uv.x - texOffset.x, particle->lb_uv.y - texOffset.y); // val.set(val.x * costheta - val.y * sintheta, val.x * sintheta + val.y * costheta); //_posuvcolors[vertexindex + 1].position = (position + (halfwidth - halfheight + halfwidth * offsetX + - //halfheight * offsetY)); _posuvcolors[vertexindex + 1].color = particle->color; _posuvcolors[vertexindex + - //1].uv.set(val.x + texOffset.x, val.y + texOffset.y); + // halfheight * offsetY)); _posuvcolors[vertexindex + 1].color = particle->color; _posuvcolors[vertexindex + + // 1].uv.set(val.x + texOffset.x, val.y + texOffset.y); // // val.set(particle->lb_uv.x - texOffset.x, particle->rt_uv.y - texOffset.y); // val.set(val.x * costheta - val.y * sintheta, val.x * sintheta + val.y * costheta); //_posuvcolors[vertexindex + 2].position = (position + (- halfwidth + halfheight + halfwidth * offsetX + - //halfheight * offsetY)); _posuvcolors[vertexindex + 2].color = particle->color; _posuvcolors[vertexindex + - //2].uv.set(val.x + texOffset.x, val.y + texOffset.y); + // halfheight * offsetY)); _posuvcolors[vertexindex + 2].color = particle->color; _posuvcolors[vertexindex + + // 2].uv.set(val.x + texOffset.x, val.y + texOffset.y); // // val.set(particle->rt_uv.x - texOffset.x, particle->rt_uv.y - texOffset.y); // val.set(val.x * costheta - val.y * sintheta, val.x * sintheta + val.y * costheta); //_posuvcolors[vertexindex + 3].position = (position + (halfwidth + halfheight + halfwidth * offsetX + - //halfheight * offsetY)); _posuvcolors[vertexindex + 3].color = particle->color; _posuvcolors[vertexindex + - //3].uv.set(val.x + texOffset.x, val.y + texOffset.y); + // halfheight * offsetY)); _posuvcolors[vertexindex + 3].color = particle->color; _posuvcolors[vertexindex + + // 3].uv.set(val.x + texOffset.x, val.y + texOffset.y); // // //_indexData[index] = vertexindex; @@ -488,8 +488,7 @@ PUParticle3DQuadRender* PUParticle3DQuadRender::clone() return render; } -PUParticle3DModelRender* PUParticle3DModelRender::create(const std::string& modelFile, - const std::string& texFile /*= ""*/) +PUParticle3DModelRender* PUParticle3DModelRender::create(std::string_view modelFile, std::string_view texFile /*= ""*/) { auto ret = new PUParticle3DModelRender(); ret->_modelFile = modelFile; @@ -614,7 +613,7 @@ PUParticle3DEntityRender::~PUParticle3DEntityRender() CC_SAFE_RELEASE(_indexBuffer); } -bool PUParticle3DEntityRender::initRender(const std::string& texFile) +bool PUParticle3DEntityRender::initRender(std::string_view texFile) { CC_SAFE_RELEASE_NULL(_programState); if (!texFile.empty()) @@ -693,7 +692,7 @@ PUParticle3DBoxRender::PUParticle3DBoxRender() PUParticle3DBoxRender::~PUParticle3DBoxRender() {} -PUParticle3DBoxRender* PUParticle3DBoxRender::create(const std::string& texFile) +PUParticle3DBoxRender* PUParticle3DBoxRender::create(std::string_view texFile) { auto ret = new PUParticle3DBoxRender(); if (ret->initRender(texFile)) @@ -883,7 +882,7 @@ PUParticle3DBoxRender* PUParticle3DBoxRender::clone() return render; } -PUSphereRender* PUSphereRender::create(const std::string& texFile) +PUSphereRender* PUSphereRender::create(std::string_view texFile) { auto ret = new PUSphereRender(); if (ret->initRender(texFile)) diff --git a/extensions/Particle3D/PU/CCPURender.h b/extensions/Particle3D/PU/CCPURender.h index e4076c656534..002f333daf68 100644 --- a/extensions/Particle3D/PU/CCPURender.h +++ b/extensions/Particle3D/PU/CCPURender.h @@ -47,8 +47,8 @@ class CC_EX_DLL PURender : public Particle3DRender virtual void unPrepare(){}; virtual void updateRender(PUParticle3D* particle, float deltaTime, bool firstParticle); - const std::string& getRenderType() const { return _renderType; }; - void setRenderType(const std::string& observerType) { _renderType = observerType; }; + std::string_view getRenderType() const { return _renderType; }; + void setRenderType(std::string_view observerType) { _renderType = observerType; }; virtual PURender* clone() = 0; void copyAttributesTo(PURender* render); @@ -70,7 +70,7 @@ class CC_EX_DLL PUParticle3DEntityRender : public PURender virtual ~PUParticle3DEntityRender(); protected: - bool initRender(const std::string& texFile); + bool initRender(std::string_view texFile); void onBeforeDraw(); @@ -141,7 +141,7 @@ class CC_EX_DLL PUParticle3DQuadRender : public PUParticle3DEntityRender VERTEX }; - static PUParticle3DQuadRender* create(const std::string& texFile = ""); + static PUParticle3DQuadRender* create(std::string_view texFile = ""); void setType(Type type); Type getType() const { return _type; } @@ -191,7 +191,7 @@ class CC_EX_DLL PUParticle3DQuadRender : public PUParticle3DEntityRender class CC_EX_DLL PUParticle3DModelRender : public PURender { public: - static PUParticle3DModelRender* create(const std::string& modelFile, const std::string& texFile = ""); + static PUParticle3DModelRender* create(std::string_view modelFile, std::string_view texFile = ""); virtual void render(Renderer* renderer, const Mat4& transform, ParticleSystem3D* particleSystem) override; @@ -212,7 +212,7 @@ class CC_EX_DLL PUParticle3DModelRender : public PURender class CC_EX_DLL PUParticle3DBoxRender : public PUParticle3DEntityRender { public: - static PUParticle3DBoxRender* create(const std::string& texFile = ""); + static PUParticle3DBoxRender* create(std::string_view texFile = ""); virtual void render(Renderer* renderer, const Mat4& transform, ParticleSystem3D* particleSystem) override; @@ -228,7 +228,7 @@ class CC_EX_DLL PUParticle3DBoxRender : public PUParticle3DEntityRender class CC_EX_DLL PUSphereRender : public PUParticle3DEntityRender { public: - static PUSphereRender* create(const std::string& texFile = ""); + static PUSphereRender* create(std::string_view texFile = ""); virtual void render(Renderer* renderer, const Mat4& transform, ParticleSystem3D* particleSystem) override; diff --git a/extensions/Particle3D/PU/CCPURibbonTrail.cpp b/extensions/Particle3D/PU/CCPURibbonTrail.cpp index b5bc2fc10b8e..fe05c3897704 100644 --- a/extensions/Particle3D/PU/CCPURibbonTrail.cpp +++ b/extensions/Particle3D/PU/CCPURibbonTrail.cpp @@ -36,8 +36,8 @@ NS_CC_BEGIN -PURibbonTrail::PURibbonTrail(const std::string& name, - const std::string& texFile, +PURibbonTrail::PURibbonTrail(std::string_view name, + std::string_view texFile, size_t maxElements, size_t numberOfChains, bool useTextureCoords, diff --git a/extensions/Particle3D/PU/CCPURibbonTrail.h b/extensions/Particle3D/PU/CCPURibbonTrail.h index e57ccf58e606..e2fa1183e9f0 100644 --- a/extensions/Particle3D/PU/CCPURibbonTrail.h +++ b/extensions/Particle3D/PU/CCPURibbonTrail.h @@ -48,12 +48,12 @@ class PURibbonTrail : public PUBillboardChain @param useVertexColors If true, use vertex colors from the chain elements (must be true if you intend to use fading) */ - PURibbonTrail(const std::string& name, - const std::string& texFile = "", - size_t maxElements = 20, - size_t numberOfChains = 1, - bool useTextureCoords = true, - bool useColours = true); + PURibbonTrail(std::string_view name, + std::string_view texFile = "", + size_t maxElements = 20, + size_t numberOfChains = 1, + bool useTextureCoords = true, + bool useColours = true); /// destructor virtual ~PURibbonTrail(); diff --git a/extensions/Particle3D/PU/CCPURibbonTrailRender.cpp b/extensions/Particle3D/PU/CCPURibbonTrailRender.cpp index 8a924a9c4b14..207957111507 100644 --- a/extensions/Particle3D/PU/CCPURibbonTrailRender.cpp +++ b/extensions/Particle3D/PU/CCPURibbonTrailRender.cpp @@ -48,7 +48,7 @@ const bool PURibbonTrailRender::DEFAULT_RANDOM_INITIAL_COLOUR = true; const Vec4 PURibbonTrailRender::DEFAULT_INITIAL_COLOUR(1, 1, 1, 1); const Vec4 PURibbonTrailRender::DEFAULT_COLOUR_CHANGE(0.5, 0.5, 0.5, 0.5); -PURibbonTrailRender* PURibbonTrailRender::create(const std::string& texFile) +PURibbonTrailRender* PURibbonTrailRender::create(std::string_view texFile) { auto br = new PURibbonTrailRender(); br->autorelease(); @@ -233,7 +233,7 @@ void PURibbonTrailRender::prepare() ss << this; std::string childNodeNodeName = "ParticleUniverse" + ss.str(); //_childNode = - //mParentTechnique->getParentSystem()->getParentSceneNode()->createChildSceneNode(childNodeNodeName); + // mParentTechnique->getParentSystem()->getParentSceneNode()->createChildSceneNode(childNodeNodeName); //_childNode->setInheritOrientation(false); auto parent = _particleSystem->getParent(); if (parent) @@ -270,7 +270,7 @@ void PURibbonTrailRender::prepare() // sceneNodeName = "ParticleUniverse" + ss.str() + StringConverter::toString(i); // RibbonTrailRendererVisualData* visualData = // PU_NEW_T(RibbonTrailRendererVisualData, - //MEMCATEGORY_SCENE_OBJECTS)(_childNode->createChildSceneNode(sceneNodeName), _trail); + // MEMCATEGORY_SCENE_OBJECTS)(_childNode->createChildSceneNode(sceneNodeName), _trail); // visualData->node->setInheritOrientation(false); auto node = Node::create(); _childNode->addChild(node); diff --git a/extensions/Particle3D/PU/CCPURibbonTrailRender.h b/extensions/Particle3D/PU/CCPURibbonTrailRender.h index 54ac52539ba9..ec3bb3870571 100644 --- a/extensions/Particle3D/PU/CCPURibbonTrailRender.h +++ b/extensions/Particle3D/PU/CCPURibbonTrailRender.h @@ -83,7 +83,7 @@ class CC_EX_DLL PURibbonTrailRender : public PURender, public PUListener static const Vec4 DEFAULT_INITIAL_COLOUR; static const Vec4 DEFAULT_COLOUR_CHANGE; - static PURibbonTrailRender* create(const std::string& texFile = ""); + static PURibbonTrailRender* create(std::string_view texFile = ""); virtual void notifyRescaled(const Vec3& scale) override; virtual void prepare() override; diff --git a/extensions/Particle3D/PU/CCPUScriptCompiler.cpp b/extensions/Particle3D/PU/CCPUScriptCompiler.cpp index c4b55f4abbc2..026311ffc588 100644 --- a/extensions/Particle3D/PU/CCPUScriptCompiler.cpp +++ b/extensions/Particle3D/PU/CCPUScriptCompiler.cpp @@ -67,19 +67,20 @@ std::string PUObjectAbstractNode::getValue() const return cls; } -void PUObjectAbstractNode::addVariable(const std::string& inName) +void PUObjectAbstractNode::addVariable(std::string_view inName) { _env.emplace(inName, ""); } -void PUObjectAbstractNode::setVariable(const std::string& inName, const std::string& value) +void PUObjectAbstractNode::setVariable(std::string_view inName, std::string_view value) { - _env[inName] = value; + // _env[inName] = value; + hlookup::set_item(_env, inName, value); } -std::pair PUObjectAbstractNode::getVariable(const std::string& inName) const +std::pair PUObjectAbstractNode::getVariable(std::string_view inName) const { - std::unordered_map::const_iterator i = _env.find(inName); + auto i = _env.find(inName); if (i != _env.end()) return std::make_pair(true, i->second); @@ -94,7 +95,7 @@ std::pair PUObjectAbstractNode::getVariable(const std::string return std::make_pair(false, ""); } -const std::unordered_map& PUObjectAbstractNode::getVariables() const +const hlookup::string_map& PUObjectAbstractNode::getVariables() const { return _env; } @@ -187,15 +188,16 @@ PUScriptCompiler::~PUScriptCompiler() _compiledScripts.clear(); } -bool PUScriptCompiler::compile(const PUConcreteNodeList& nodes, const std::string& file) +hlookup::string_map::iterator PUScriptCompiler::compile(const PUConcreteNodeList& nodes, + std::string_view file) { if (nodes.empty()) - return false; + return _compiledScripts.end(); PUAbstractNodeList aNodes; convertToAST(nodes, aNodes); - _compiledScripts[file] = aNodes; + return hlookup::set_item(_compiledScripts, file, aNodes); // _compiledScripts[file] = aNodes; // for(PUAbstractNodeList::iterator i = aNodes.begin(); i != aNodes.end(); ++i) //{ // PUScriptTranslator *translator = PUTranslateManager::Instance()->getTranslator(*i); @@ -212,10 +214,10 @@ bool PUScriptCompiler::compile(const PUConcreteNodeList& nodes, const std::strin // for (auto iter : aNodes){ // delete iter; // } - return true; + // return true; } -const PUAbstractNodeList* PUScriptCompiler::compile(const std::string& file, bool& isFirstCompile) +const PUAbstractNodeList* PUScriptCompiler::compile(std::string_view file, bool& isFirstCompile) { auto iter = _compiledScripts.find(file); if (iter != _compiledScripts.end()) @@ -231,7 +233,7 @@ const PUAbstractNodeList* PUScriptCompiler::compile(const std::string& file, boo PUConcreteNodeList creteNodeList; lexer.openLexer(data, file, tokenList); parser.parse(creteNodeList, tokenList); - bool state = compile(creteNodeList, file); + auto it = compile(creteNodeList, file); for (auto iter1 : creteNodeList) { @@ -244,9 +246,9 @@ const PUAbstractNodeList* PUScriptCompiler::compile(const std::string& file, boo } isFirstCompile = true; - if (state) + if (it != _compiledScripts.end()) { - return &_compiledScripts[file]; + return &it->second; } return nullptr; } diff --git a/extensions/Particle3D/PU/CCPUScriptCompiler.h b/extensions/Particle3D/PU/CCPUScriptCompiler.h index 4834595f5948..e5bc4cc7b8fe 100644 --- a/extensions/Particle3D/PU/CCPUScriptCompiler.h +++ b/extensions/Particle3D/PU/CCPUScriptCompiler.h @@ -72,7 +72,7 @@ class CC_EX_DLL PUAbstractNode class CC_EX_DLL PUObjectAbstractNode : public PUAbstractNode { private: - std::unordered_map _env; + hlookup::string_map _env; public: std::string name, cls; @@ -88,10 +88,10 @@ class CC_EX_DLL PUObjectAbstractNode : public PUAbstractNode PUAbstractNode* clone() const; std::string getValue() const; - void addVariable(const std::string& name); - void setVariable(const std::string& name, const std::string& value); - std::pair getVariable(const std::string& name) const; - const std::unordered_map& getVariables() const; + void addVariable(std::string_view name); + void setVariable(std::string_view name, std::string_view value); + std::pair getVariable(std::string_view name) const; + const hlookup::string_map& getVariables() const; }; /** This abstract node represents a script property */ @@ -130,9 +130,9 @@ class CC_EX_DLL PUScriptCompiler { private: - bool compile(const PUConcreteNodeList& nodes, const std::string& file); + hlookup::string_map::iterator compile(const PUConcreteNodeList& nodes, std::string_view file); // is it excluded?// - bool isNameExcluded(const std::string& cls, PUAbstractNode* parent); + bool isNameExcluded(std::string_view cls, PUAbstractNode* parent); public: typedef std::unordered_map IdMap; @@ -141,7 +141,7 @@ class CC_EX_DLL PUScriptCompiler void setParticleSystem3D(PUParticleSystem3D* pu); - const PUAbstractNodeList* compile(const std::string& file, bool& isFirstCompile); + const PUAbstractNodeList* compile(std::string_view file, bool& isFirstCompile); void convertToAST(const PUConcreteNodeList& nodes, PUAbstractNodeList& aNodes); @@ -155,7 +155,7 @@ class CC_EX_DLL PUScriptCompiler void visit(PUConcreteNode* node); private: - std::unordered_map _compiledScripts; + hlookup::string_map _compiledScripts; PUAbstractNode* _current; PUAbstractNodeList* _nodes; PUParticleSystem3D* _PUParticleSystem3D; diff --git a/extensions/Particle3D/PU/CCPUScriptLexer.cpp b/extensions/Particle3D/PU/CCPUScriptLexer.cpp index a8720fca0fac..75aca400f7ed 100644 --- a/extensions/Particle3D/PU/CCPUScriptLexer.cpp +++ b/extensions/Particle3D/PU/CCPUScriptLexer.cpp @@ -31,7 +31,7 @@ PUScriptLexer::PUScriptLexer() {} PUScriptLexer::~PUScriptLexer() {} -void PUScriptLexer::openLexer(const std::string& str, const std::string& source, PUScriptTokenList& tokens) +void PUScriptLexer::openLexer(std::string_view str, std::string_view source, PUScriptTokenList& tokens) { enum { @@ -55,7 +55,7 @@ void PUScriptLexer::openLexer(const std::string& str, const std::string& source, // // Iterate over the input - std::string::const_iterator i = str.begin(), end = str.end(); + std::string_view::const_iterator i = str.begin(), end = str.end(); while (i != end) { lastc = c; @@ -233,7 +233,7 @@ void PUScriptLexer::openLexer(const std::string& str, const std::string& source, } } -void PUScriptLexer::setToken(const std::string& lexeme, int line, const std::string& source, PUScriptTokenList* tokens) +void PUScriptLexer::setToken(std::string_view lexeme, int line, std::string_view source, PUScriptTokenList* tokens) { const char openBracket = '{', closeBracket = '}', colon = ':', quote = '\"', var = '$'; diff --git a/extensions/Particle3D/PU/CCPUScriptLexer.h b/extensions/Particle3D/PU/CCPUScriptLexer.h index e5133cf323ef..907ef09a7bed 100644 --- a/extensions/Particle3D/PU/CCPUScriptLexer.h +++ b/extensions/Particle3D/PU/CCPUScriptLexer.h @@ -67,12 +67,12 @@ class PUScriptLexer PUScriptLexer(); ~PUScriptLexer(); - void openLexer(const std::string& str, const std::string& source, PUScriptTokenList& tokenList); + void openLexer(std::string_view str, std::string_view source, PUScriptTokenList& tokenList); /** Tokenizes the given input and returns the list of tokens found */ // tokenize(const std::string &str, const std::string &source); private: // Private utility operations - void setToken(const std::string& lexeme, int line, const std::string& source, PUScriptTokenList* tokens); + void setToken(std::string_view lexeme, int line, std::string_view source, PUScriptTokenList* tokens); bool isWhitespace(char c) const; bool isNewline(char c) const; }; diff --git a/extensions/Particle3D/PU/CCPUScriptTranslator.cpp b/extensions/Particle3D/PU/CCPUScriptTranslator.cpp index a73539e24a7a..3eeb334127e0 100644 --- a/extensions/Particle3D/PU/CCPUScriptTranslator.cpp +++ b/extensions/Particle3D/PU/CCPUScriptTranslator.cpp @@ -517,7 +517,7 @@ bool PUScriptTranslator::getQuaternion(PUAbstractNodeList::const_iterator i, //------------------------------------------------------------------------- bool PUScriptTranslator::passValidateProperty(PUScriptCompiler* compiler, PUPropertyAbstractNode* prop, - const std::string& token2, + std::string_view token2, ValidationType validationType) { if (!passValidatePropertyNoValues(compiler, prop, token2)) @@ -594,7 +594,7 @@ bool PUScriptTranslator::passValidateProperty(PUScriptCompiler* compiler, //------------------------------------------------------------------------- bool PUScriptTranslator::passValidatePropertyNoValues(PUScriptCompiler* /*compiler*/, PUPropertyAbstractNode* prop, - const std::string& /*token2*/) + std::string_view /*token2*/) { if (prop->values.empty()) { @@ -607,7 +607,7 @@ bool PUScriptTranslator::passValidatePropertyNoValues(PUScriptCompiler* /*compil //------------------------------------------------------------------------- bool PUScriptTranslator::passValidatePropertyNumberOfValues(PUScriptCompiler* /*compiler*/, PUPropertyAbstractNode* prop, - const std::string& /*token2*/, + std::string_view /*token2*/, unsigned short numberOfValues) { if (prop->values.size() > numberOfValues) @@ -619,7 +619,7 @@ bool PUScriptTranslator::passValidatePropertyNumberOfValues(PUScriptCompiler* /* //------------------------------------------------------------------------- bool PUScriptTranslator::passValidatePropertyNumberOfValuesRange(PUScriptCompiler* /*compiler*/, PUPropertyAbstractNode* prop, - const std::string& /*token2*/, + std::string_view /*token2*/, unsigned short minNumberOfValues, unsigned short maxNumberOfValues) { diff --git a/extensions/Particle3D/PU/CCPUScriptTranslator.h b/extensions/Particle3D/PU/CCPUScriptTranslator.h index 0e9af6d757f6..623bec8d13d8 100644 --- a/extensions/Particle3D/PU/CCPUScriptTranslator.h +++ b/extensions/Particle3D/PU/CCPUScriptTranslator.h @@ -679,27 +679,25 @@ class PUScriptTranslator */ bool passValidateProperty(PUScriptCompiler* compiler, PUPropertyAbstractNode* prop, - const std::string& token, + std::string_view token, ValidationType validationType); /** Validate whether a property has values. */ - bool passValidatePropertyNoValues(PUScriptCompiler* compiler, - PUPropertyAbstractNode* prop, - const std::string& token); + bool passValidatePropertyNoValues(PUScriptCompiler* compiler, PUPropertyAbstractNode* prop, std::string_view token); /** Validate whether the number of values is correct. */ bool passValidatePropertyNumberOfValues(PUScriptCompiler* compiler, PUPropertyAbstractNode* prop, - const std::string& token, + std::string_view token, unsigned short numberOfValues); /** Validate whether the number of values is between a range. */ bool passValidatePropertyNumberOfValuesRange(PUScriptCompiler* compiler, PUPropertyAbstractNode* prop, - const std::string& token, + std::string_view token, unsigned short minNumberOfValues, unsigned short maxNumberOfValues); diff --git a/extensions/Particle3D/PU/CCPUSlaveEmitter.cpp b/extensions/Particle3D/PU/CCPUSlaveEmitter.cpp index 904cab168e9e..e5880b2f9c8d 100644 --- a/extensions/Particle3D/PU/CCPUSlaveEmitter.cpp +++ b/extensions/Particle3D/PU/CCPUSlaveEmitter.cpp @@ -39,22 +39,22 @@ PUSlaveEmitter::PUSlaveEmitter() , _masterEmitterNameSet(false) {} //----------------------------------------------------------------------- -const std::string& PUSlaveEmitter::getMasterTechniqueName() const +std::string_view PUSlaveEmitter::getMasterTechniqueName() const { return _masterTechniqueName; } //----------------------------------------------------------------------- -void PUSlaveEmitter::setMasterTechniqueName(const std::string& masterTechniqueName) +void PUSlaveEmitter::setMasterTechniqueName(std::string_view masterTechniqueName) { _masterTechniqueName = masterTechniqueName; } //----------------------------------------------------------------------- -const std::string& PUSlaveEmitter::getMasterEmitterName() const +std::string_view PUSlaveEmitter::getMasterEmitterName() const { return _masterEmitterName; } //----------------------------------------------------------------------- -void PUSlaveEmitter::setMasterEmitterName(const std::string& masterEmitterName) +void PUSlaveEmitter::setMasterEmitterName(std::string_view masterEmitterName) { _masterEmitterName = masterEmitterName; _masterEmitterNameSet = true; diff --git a/extensions/Particle3D/PU/CCPUSlaveEmitter.h b/extensions/Particle3D/PU/CCPUSlaveEmitter.h index 32ab26c3c081..c260cf59e479 100644 --- a/extensions/Particle3D/PU/CCPUSlaveEmitter.h +++ b/extensions/Particle3D/PU/CCPUSlaveEmitter.h @@ -39,15 +39,15 @@ class CC_EX_DLL PUSlaveEmitter : public PUEmitter, public PUListener /** */ - const std::string& getMasterTechniqueName() const; + std::string_view getMasterTechniqueName() const; /** */ - void setMasterTechniqueName(const std::string& masterTechniqueName); + void setMasterTechniqueName(std::string_view masterTechniqueName); /** */ - const std::string& getMasterEmitterName() const; + std::string_view getMasterEmitterName() const; /** See ParticleEmitter. */ @@ -79,7 +79,7 @@ class CC_EX_DLL PUSlaveEmitter : public PUEmitter, public PUListener /** */ - void setMasterEmitterName(const std::string& masterEmitterName); + void setMasterEmitterName(std::string_view masterEmitterName); virtual PUSlaveEmitter* clone() override; virtual void copyAttributesTo(PUEmitter* emitter) override; diff --git a/extensions/Particle3D/PU/CCPUVertexEmitter.cpp b/extensions/Particle3D/PU/CCPUVertexEmitter.cpp index c7fcbb0276d3..97f9fc2a2226 100644 --- a/extensions/Particle3D/PU/CCPUVertexEmitter.cpp +++ b/extensions/Particle3D/PU/CCPUVertexEmitter.cpp @@ -84,12 +84,12 @@ NS_CC_BEGIN // mStep = step; // } ////----------------------------------------------------------------------- -// const std::string& Particle3DVertexEmitter::getMeshName() const +// std::string_view Particle3DVertexEmitter::getMeshName() const //{ // return mMeshName; // } ////----------------------------------------------------------------------- -// void Particle3DVertexEmitter::setMeshName(const std::string& meshName) +// void Particle3DVertexEmitter::setMeshName(std::string_view meshName) //{ // _setDefaults(); // Triggers loading the new mesh // mMeshName = meshName; @@ -184,7 +184,7 @@ NS_CC_BEGIN // void Particle3DVertexEmitter::_loadMesh () //{ // Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().load(mMeshName, -//Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); mMesh = mesh.getPointer(); mMeshProcessed = false; +// Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); mMesh = mesh.getPointer(); mMeshProcessed = false; // // if (mMesh->getNumSubMeshes() > 0) // { diff --git a/extensions/Particle3D/PU/CCPUVertexEmitter.h b/extensions/Particle3D/PU/CCPUVertexEmitter.h index 7db52020dd36..b808d43acd36 100644 --- a/extensions/Particle3D/PU/CCPUVertexEmitter.h +++ b/extensions/Particle3D/PU/CCPUVertexEmitter.h @@ -148,7 +148,7 @@ NS_CC_BEGIN // // /** // */ -// const std::string& getMeshName() const; +// std::string_view getMeshName() const; // // /** // */ @@ -156,7 +156,7 @@ NS_CC_BEGIN // // /** // */ -// void setMeshName(const std::string& meshName); +// void setMeshName(std::string_view meshName); // // /** // */ diff --git a/extensions/assets-manager/AssetsManager.cpp b/extensions/assets-manager/AssetsManager.cpp index 2566e7b0c248..8b9b571df10e 100644 --- a/extensions/assets-manager/AssetsManager.cpp +++ b/extensions/assets-manager/AssetsManager.cpp @@ -182,7 +182,7 @@ AssetsManager::AssetsManager(const char* packageUrl /* =nullptr */, checkStoragePath(); // convert downloader error code to AssetsManager::ErrorCode _downloader->onTaskError = [this](const DownloadTask& /*task*/, int errorCode, int /*errorCodeInternal*/, - const std::string& /*errorStr*/) { + std::string_view /*errorStr*/) { _isDownloading = false; if (nullptr == _delegate) @@ -278,10 +278,10 @@ void AssetsManager::checkStoragePath() } // Multiple key names -static std::string keyWithHash(const char* prefix, const std::string& url) +static std::string keyWithHash(const char* prefix, std::string_view url) { char buf[256]; - sprintf(buf, "%s%zd", prefix, std::hash()(url)); + sprintf(buf, "%s%zd", prefix, std::hash()(url)); return buf; } @@ -565,9 +565,9 @@ void AssetsManager::setVersionFileUrl(const char* versionFileUrl) _versionFileUrl = versionFileUrl; } -string AssetsManager::getVersion() +std::string_view AssetsManager::getVersion() { - return UserDefault::getInstance()->getStringForKey(keyOfVersion().c_str()); + return UserDefault::getInstance()->getStringForKey(keyOfVersion().data()); } void AssetsManager::deleteVersion() diff --git a/extensions/assets-manager/AssetsManager.h b/extensions/assets-manager/AssetsManager.h index 34a1fb8125a8..b6587157a1ef 100644 --- a/extensions/assets-manager/AssetsManager.h +++ b/extensions/assets-manager/AssetsManager.h @@ -137,7 +137,7 @@ class CC_EX_DLL AssetsManager : public Node /* @brief Gets current version code. */ - std::string getVersion(); + std::string_view getVersion(); /* @brief Deletes recorded version code. */ diff --git a/extensions/assets-manager/AssetsManagerEx.cpp b/extensions/assets-manager/AssetsManagerEx.cpp index 10f555c1ce98..8636f4523e11 100644 --- a/extensions/assets-manager/AssetsManagerEx.cpp +++ b/extensions/assets-manager/AssetsManagerEx.cpp @@ -168,8 +168,7 @@ int AssetManagerEx_error_file_func(voidpf opaque, voidpf stream) // Implementation of AssetsManagerEx -AssetsManagerEx::AssetsManagerEx(const std::string& manifestUrl, const std::string& storagePath) - : _manifestUrl(manifestUrl) +AssetsManagerEx::AssetsManagerEx(std::string_view manifestUrl, std::string_view storagePath) : _manifestUrl(manifestUrl) { // Init variables _eventDispatcher = Director::getInstance()->getEventDispatcher(); @@ -208,14 +207,14 @@ AssetsManagerEx::~AssetsManagerEx() CC_SAFE_RELEASE(_remoteManifest); } -AssetsManagerEx* AssetsManagerEx::create(const std::string& manifestUrl, const std::string& storagePath) +AssetsManagerEx* AssetsManagerEx::create(std::string_view manifestUrl, std::string_view storagePath) { AssetsManagerEx* ret = new AssetsManagerEx(manifestUrl, storagePath); ret->autorelease(); return ret; } -void AssetsManagerEx::initManifests(const std::string& manifestUrl) +void AssetsManagerEx::initManifests(std::string_view manifestUrl) { _inited = true; // Init and load local manifest @@ -260,7 +259,7 @@ void AssetsManagerEx::prepareLocalManifest() _localManifest->prependSearchPaths(); } -void AssetsManagerEx::loadLocalManifest(const std::string& /*manifestUrl*/) +void AssetsManagerEx::loadLocalManifest(std::string_view /*manifestUrl*/) { Manifest* cachedManifest = nullptr; // Find the cached manifest file @@ -329,7 +328,7 @@ void AssetsManagerEx::loadLocalManifest(const std::string& /*manifestUrl*/) } } -std::string AssetsManagerEx::basename(const std::string& path) const +std::string_view AssetsManagerEx::basename(std::string_view path) const { size_t found = path.find_last_of("/\\"); @@ -343,7 +342,7 @@ std::string AssetsManagerEx::basename(const std::string& path) const } } -std::string AssetsManagerEx::get(const std::string& key) const +std::string AssetsManagerEx::get(std::string_view key) const { auto it = _assets->find(key); if (it != _assets->cend()) @@ -364,12 +363,12 @@ const Manifest* AssetsManagerEx::getRemoteManifest() const return _remoteManifest; } -const std::string& AssetsManagerEx::getStoragePath() const +std::string_view AssetsManagerEx::getStoragePath() const { return _storagePath; } -void AssetsManagerEx::setStoragePath(const std::string& storagePath) +void AssetsManagerEx::setStoragePath(std::string_view storagePath) { _storagePath = storagePath; adjustPath(_storagePath); @@ -389,16 +388,16 @@ void AssetsManagerEx::adjustPath(std::string& path) } } -bool AssetsManagerEx::decompress(const std::string& zip) +bool AssetsManagerEx::decompress(std::string_view zip) { // Find root path for zip file size_t pos = zip.find_last_of("/\\"); if (pos == std::string::npos) { - CCLOG("AssetsManagerEx : no root path specified for zip file %s\n", zip.c_str()); + CCLOG("AssetsManagerEx : no root path specified for zip file %s\n", zip.data()); return false; } - const std::string rootPath = zip.substr(0, pos + 1); + const std::string_view rootPath = zip.substr(0, pos + 1); zlib_filefunc_def_s zipFunctionOverrides; fillZipFunctionOverrides(zipFunctionOverrides); @@ -409,10 +408,10 @@ bool AssetsManagerEx::decompress(const std::string& zip) zipFunctionOverrides.opaque = &zipFileInfo; // Open the zip file - unzFile zipfile = unzOpen2(zip.c_str(), &zipFunctionOverrides); + unzFile zipfile = unzOpen2(zip.data(), &zipFunctionOverrides); if (!zipfile) { - CCLOG("AssetsManagerEx : can not open downloaded zip file %s\n", zip.c_str()); + CCLOG("AssetsManagerEx : can not open downloaded zip file %s\n", zip.data()); return false; } @@ -420,7 +419,7 @@ bool AssetsManagerEx::decompress(const std::string& zip) unz_global_info global_info; if (unzGetGlobalInfo(zipfile, &global_info) != UNZ_OK) { - CCLOG("AssetsManagerEx : can not read file global info of %s\n", zip.c_str()); + CCLOG("AssetsManagerEx : can not read file global info of %s\n", zip.data()); unzClose(zipfile); return false; } @@ -440,7 +439,8 @@ bool AssetsManagerEx::decompress(const std::string& zip) unzClose(zipfile); return false; } - const std::string fullPath = rootPath + fileName; + std::string fullPath{rootPath}; + fullPath += fileName; // Check if this entry is a directory or a file. const size_t filenameLength = strlen(fileName); @@ -459,7 +459,7 @@ bool AssetsManagerEx::decompress(const std::string& zip) else { // Create all directories in advance to avoid issue - std::string dir = basename(fullPath); + std::string_view dir = basename(fullPath); if (!_fileUtils->isDirectoryExist(dir)) { if (!_fileUtils->createDirectory(dir)) @@ -531,7 +531,7 @@ bool AssetsManagerEx::decompress(const std::string& zip) return true; } -void AssetsManagerEx::decompressDownloadedZip(const std::string& customId, const std::string& storagePath) +void AssetsManagerEx::decompressDownloadedZip(std::string_view customId, std::string_view storagePath) { struct AsyncData { @@ -573,8 +573,8 @@ void AssetsManagerEx::decompressDownloadedZip(const std::string& customId, const } void AssetsManagerEx::dispatchUpdateEvent(EventAssetsManagerEx::EventCode code, - const std::string& assetId /* = ""*/, - const std::string& message /* = ""*/, + std::string_view assetId /* = ""*/, + std::string_view message /* = ""*/, int curle_code /* = CURLE_OK*/, int curlm_code /* = CURLM_OK*/) { @@ -619,7 +619,7 @@ void AssetsManagerEx::downloadVersion() if (_updateState > State::PREDOWNLOAD_VERSION) return; - std::string versionUrl = _localManifest->getVersionFileUrl(); + std::string_view versionUrl = _localManifest->getVersionFileUrl(); if (!versionUrl.empty()) { @@ -786,7 +786,7 @@ void AssetsManagerEx::startUpdate() _tempManifest = _remoteManifest; // Check difference between local manifest and remote manifest - std::unordered_map diff_map = _localManifest->genDiff(_remoteManifest); + hlookup::string_map diff_map = _localManifest->genDiff(_remoteManifest); if (diff_map.empty()) { updateSucceed(); @@ -794,7 +794,7 @@ void AssetsManagerEx::startUpdate() else { // Generate download units for all assets that need to be updated or added - std::string packageUrl = _remoteManifest->getPackageUrl(); + std::string_view packageUrl = _remoteManifest->getPackageUrl(); // Save current download manifest information for resuming _tempManifest->saveToFile(_tempManifestPath); // Preprocessing local files in previous version and creating download folders @@ -803,10 +803,11 @@ void AssetsManagerEx::startUpdate() Manifest::AssetDiff diff = it->second; if (diff.type != Manifest::DiffType::DELETED) { - std::string path = diff.asset.path; + const std::string& path = diff.asset.path; DownloadUnit unit; - unit.customId = it->first; - unit.srcUrl = packageUrl + path; + unit.customId = it->first; + unit.srcUrl = packageUrl; + unit.srcUrl += path; unit.storagePath = _tempStoragePath + path; unit.size = diff.asset.size; _downloadUnits.emplace(unit.customId, unit); @@ -1034,8 +1035,8 @@ void AssetsManagerEx::downloadFailedAssets() updateAssets(_failedUnits); } -void AssetsManagerEx::fileError(const std::string& identifier, - const std::string& errorStr, +void AssetsManagerEx::fileError(std::string_view identifier, + std::string_view errorStr, int errorCode, int errorCodeInternal) { @@ -1056,7 +1057,7 @@ void AssetsManagerEx::fileError(const std::string& identifier, queueDowload(); } -void AssetsManagerEx::fileSuccess(const std::string& customId, const std::string& storagePath) +void AssetsManagerEx::fileSuccess(std::string_view customId, std::string_view storagePath) { // Set download state to SUCCESSED _tempManifest->setAssetDownloadState(customId, Manifest::DownloadState::SUCCESSED); @@ -1089,7 +1090,7 @@ void AssetsManagerEx::fileSuccess(const std::string& customId, const std::string void AssetsManagerEx::onError(const network::DownloadTask& task, int errorCode, int errorCodeInternal, - const std::string& errorStr) + std::string_view errorStr) { // Skip version error occurred if (task.identifier == VERSION_ID) @@ -1110,10 +1111,7 @@ void AssetsManagerEx::onError(const network::DownloadTask& task, } } -void AssetsManagerEx::onProgress(double total, - double downloaded, - const std::string& /*url*/, - const std::string& customId) +void AssetsManagerEx::onProgress(double total, double downloaded, std::string_view /*url*/, std::string_view customId) { if (customId == VERSION_ID || customId == MANIFEST_ID) { @@ -1170,9 +1168,7 @@ void AssetsManagerEx::onProgress(double total, } } -void AssetsManagerEx::onSuccess(const std::string& /*srcUrl*/, - const std::string& storagePath, - const std::string& customId) +void AssetsManagerEx::onSuccess(std::string_view /*srcUrl*/, std::string_view storagePath, std::string_view customId) { if (customId == VERSION_ID) { diff --git a/extensions/assets-manager/AssetsManagerEx.h b/extensions/assets-manager/AssetsManagerEx.h index 7180323d2d65..7a77db5b44c8 100644 --- a/extensions/assets-manager/AssetsManagerEx.h +++ b/extensions/assets-manager/AssetsManagerEx.h @@ -77,7 +77,7 @@ class CC_EX_DLL AssetsManagerEx : public Ref @warning The cached manifest in your storage path have higher priority and will be searched first, only if it doesn't exist, AssetsManagerEx will use the given manifestUrl. */ - static AssetsManagerEx* create(const std::string& manifestUrl, const std::string& storagePath); + static AssetsManagerEx* create(std::string_view manifestUrl, std::string_view storagePath); /** @brief Check out if there is a new version of manifest. * You may use this method before updating, then let user determine whether @@ -99,7 +99,7 @@ class CC_EX_DLL AssetsManagerEx : public Ref /** @brief Gets storage path. */ - const std::string& getStoragePath() const; + std::string_view getStoragePath() const; /** @brief Function for retrieving the local manifest object */ @@ -120,8 +120,7 @@ class CC_EX_DLL AssetsManagerEx : public Ref /** @brief Set the handle function for comparing manifests versions * @param handle The compare function */ - void setVersionCompareHandle( - const std::function& handle) + void setVersionCompareHandle(const std::function& handle) { _versionCompareHandle = handle; }; @@ -130,37 +129,37 @@ class CC_EX_DLL AssetsManagerEx : public Ref * verification * @param callback The verify callback function */ - void setVerifyCallback(const std::function& callback) + void setVerifyCallback(const std::function& callback) { _verifyCallback = callback; }; CC_CONSTRUCTOR_ACCESS : - AssetsManagerEx(const std::string& manifestUrl, const std::string& storagePath); + AssetsManagerEx(std::string_view manifestUrl, std::string_view storagePath); virtual ~AssetsManagerEx(); protected: - std::string basename(const std::string& path) const; + std::string_view basename(std::string_view path) const; - std::string get(const std::string& key) const; + std::string get(std::string_view key) const; - void initManifests(const std::string& manifestUrl); + void initManifests(std::string_view manifestUrl); - void loadLocalManifest(const std::string& manifestUrl); + void loadLocalManifest(std::string_view manifestUrl); void prepareLocalManifest(); - void setStoragePath(const std::string& storagePath); + void setStoragePath(std::string_view storagePath); void adjustPath(std::string& path); void dispatchUpdateEvent(EventAssetsManagerEx::EventCode code, - const std::string& message = "", - const std::string& assetId = "", - int curle_code = 0, - int curlm_code = 0); + std::string_view message = "", + std::string_view assetId = "", + int curle_code = 0, + int curlm_code = 0); void downloadVersion(); void parseVersion(); @@ -168,8 +167,8 @@ class CC_EX_DLL AssetsManagerEx : public Ref void parseManifest(); void startUpdate(); void updateSucceed(); - bool decompress(const std::string& filename); - void decompressDownloadedZip(const std::string& customId, const std::string& storagePath); + bool decompress(std::string_view filename); + void decompressDownloadedZip(std::string_view customId, std::string_view storagePath); /** @brief Update a list of assets under the current AssetsManagerEx context */ @@ -187,12 +186,12 @@ class CC_EX_DLL AssetsManagerEx : public Ref */ void queueDowload(); - void fileError(const std::string& identifier, - const std::string& errorStr, + void fileError(std::string_view identifier, + std::string_view errorStr, int errorCode = 0, int errorCodeInternal = 0); - void fileSuccess(const std::string& customId, const std::string& storagePath); + void fileSuccess(std::string_view customId, std::string_view storagePath); /** @brief Call back function for error handling, the error will then be reported to user's listener registed in addUpdateEventListener @@ -204,7 +203,7 @@ class CC_EX_DLL AssetsManagerEx : public Ref virtual void onError(const network::DownloadTask& task, int errorCode, int errorCodeInternal, - const std::string& errorStr); + std::string_view errorStr); /** @brief Call back function for recording downloading percent of the current asset, the progression will then be reported to user's listener registed in addUpdateProgressEventListener @@ -216,7 +215,7 @@ class CC_EX_DLL AssetsManagerEx : public Ref * @js NA * @lua NA */ - virtual void onProgress(double total, double downloaded, const std::string& url, const std::string& customId); + virtual void onProgress(double total, double downloaded, std::string_view url, std::string_view customId); /** @brief Call back function for success of the current asset the success event will then be send to user's listener registed in addUpdateEventListener @@ -226,7 +225,7 @@ class CC_EX_DLL AssetsManagerEx : public Ref * @js NA * @lua NA */ - virtual void onSuccess(const std::string& srcUrl, const std::string& storagePath, const std::string& customId); + virtual void onSuccess(std::string_view srcUrl, std::string_view storagePath, std::string_view customId); private: void batchDownload(); @@ -250,7 +249,7 @@ class CC_EX_DLL AssetsManagerEx : public Ref std::shared_ptr _downloader; //! The reference to the local assets - const std::unordered_map* _assets = nullptr; + const hlookup::string_map* _assets = nullptr; //! The path to store successfully downloaded version. std::string _storagePath; @@ -320,7 +319,7 @@ class CC_EX_DLL AssetsManagerEx : public Ref double _totalSize; //! Downloaded size for each file - std::unordered_map _downloadedSize; + hlookup::string_map _downloadedSize; //! Total number of assets to download int _totalToDownload = 0; @@ -330,10 +329,10 @@ class CC_EX_DLL AssetsManagerEx : public Ref float _nextSavePoint = 0.f; //! Handle function to compare versions between different manifests - std::function _versionCompareHandle = nullptr; + std::function _versionCompareHandle = nullptr; //! Callback function to verify the downloaded assets - std::function _verifyCallback = nullptr; + std::function _verifyCallback = nullptr; //! Marker for whether the assets manager is inited bool _inited = false; diff --git a/extensions/assets-manager/CCEventAssetsManagerEx.cpp b/extensions/assets-manager/CCEventAssetsManagerEx.cpp index 183daae66016..e14a7eed3025 100644 --- a/extensions/assets-manager/CCEventAssetsManagerEx.cpp +++ b/extensions/assets-manager/CCEventAssetsManagerEx.cpp @@ -30,13 +30,13 @@ NS_CC_EXT_BEGIN -EventAssetsManagerEx::EventAssetsManagerEx(const std::string& eventName, +EventAssetsManagerEx::EventAssetsManagerEx(std::string_view eventName, cocos2d::extension::AssetsManagerEx* manager, const EventCode& code, float percent /* = 0 */, float percentByFile /* = 0*/, - const std::string& assetId /* = "" */, - const std::string& message /* = "" */, + std::string_view assetId /* = "" */, + std::string_view message /* = "" */, int curle_code /* = CURLE_OK*/, int curlm_code /* = CURLM_OK*/) : EventCustom(eventName) diff --git a/extensions/assets-manager/CCEventAssetsManagerEx.h b/extensions/assets-manager/CCEventAssetsManagerEx.h index 0d261ac5b958..11a6ad1220f3 100644 --- a/extensions/assets-manager/CCEventAssetsManagerEx.h +++ b/extensions/assets-manager/CCEventAssetsManagerEx.h @@ -74,15 +74,15 @@ class CC_EX_DLL EventAssetsManagerEx : public cocos2d::EventCustom CC_CONSTRUCTOR_ACCESS : /** Constructor */ - EventAssetsManagerEx(const std::string& eventName, + EventAssetsManagerEx(std::string_view eventName, cocos2d::extension::AssetsManagerEx* manager, const EventCode& code, - float percent = 0, - float percentByFile = 0, - const std::string& assetId = "", - const std::string& message = "", - int curle_code = 0, - int curlm_code = 0); + float percent = 0, + float percentByFile = 0, + std::string_view assetId = "", + std::string_view message = "", + int curle_code = 0, + int curlm_code = 0); private: EventCode _code; diff --git a/extensions/assets-manager/Manifest.cpp b/extensions/assets-manager/Manifest.cpp index 43dc418e19e7..98af1eb1e191 100644 --- a/extensions/assets-manager/Manifest.cpp +++ b/extensions/assets-manager/Manifest.cpp @@ -50,16 +50,16 @@ NS_CC_EXT_BEGIN -static int cmpVersion(const std::string& v1, const std::string& v2) +static int cmpVersion(std::string_view v1, std::string_view v2) { int i; int oct_v1[4] = {0}, oct_v2[4] = {0}; - int filled1 = std::sscanf(v1.c_str(), "%d.%d.%d.%d", &oct_v1[0], &oct_v1[1], &oct_v1[2], &oct_v1[3]); - int filled2 = std::sscanf(v2.c_str(), "%d.%d.%d.%d", &oct_v2[0], &oct_v2[1], &oct_v2[2], &oct_v2[3]); + int filled1 = std::sscanf(v1.data(), "%d.%d.%d.%d", &oct_v1[0], &oct_v1[1], &oct_v1[2], &oct_v1[3]); + int filled2 = std::sscanf(v2.data(), "%d.%d.%d.%d", &oct_v2[0], &oct_v2[1], &oct_v2[2], &oct_v2[3]); if (filled1 == 0 || filled2 == 0) { - return strcmp(v1.c_str(), v2.c_str()); + return v1 != v2; // strcmp(v1.data(), v2.data()); } for (i = 0; i < 4; i++) { @@ -71,7 +71,7 @@ static int cmpVersion(const std::string& v1, const std::string& v2) return 0; } -Manifest::Manifest(const std::string& manifestUrl /* = ""*/) +Manifest::Manifest(std::string_view manifestUrl /* = ""*/) : _versionLoaded(false) , _loaded(false) , _manifestRoot("") @@ -86,7 +86,7 @@ Manifest::Manifest(const std::string& manifestUrl /* = ""*/) parse(manifestUrl); } -void Manifest::loadJson(const std::string& url) +void Manifest::loadJson(std::string_view url) { clear(); std::string content; @@ -97,7 +97,7 @@ void Manifest::loadJson(const std::string& url) if (content.empty()) { - CCLOG("Fail to retrieve local file content: %s\n", url.c_str()); + CCLOG("Fail to retrieve local file content: %s\n", url.data()); } else { @@ -116,7 +116,7 @@ void Manifest::loadJson(const std::string& url) } } -void Manifest::parseVersion(const std::string& versionUrl) +void Manifest::parseVersion(std::string_view versionUrl) { loadJson(versionUrl); @@ -126,7 +126,7 @@ void Manifest::parseVersion(const std::string& versionUrl) } } -void Manifest::parse(const std::string& manifestUrl) +void Manifest::parse(std::string_view manifestUrl) { loadJson(manifestUrl); @@ -161,8 +161,8 @@ bool Manifest::versionEquals(const Manifest* b) const // Check group versions else { - std::vector bGroups = b->getGroups(); - std::unordered_map bGroupVer = b->getGroupVerions(); + std::vector bGroups = b->getGroups(); + auto& bGroupVer = b->getGroupVerions(); // Check group size if (bGroups.size() != _groups.size()) return false; @@ -184,10 +184,10 @@ bool Manifest::versionEquals(const Manifest* b) const bool Manifest::versionGreater( const Manifest* b, - const std::function& handle) const + const std::function& handle) const { - std::string localVersion = getVersion(); - const std::string& bVersion = b->getVersion(); + std::string_view localVersion = getVersion(); + std::string_view bVersion = b->getVersion(); bool greater; if (handle) { @@ -200,16 +200,16 @@ bool Manifest::versionGreater( return greater; } -std::unordered_map Manifest::genDiff(const Manifest* b) const +hlookup::string_map Manifest::genDiff(const Manifest* b) const { - std::unordered_map diff_map; - const std::unordered_map& bAssets = b->getAssets(); + hlookup::string_map diff_map; + auto& bAssets = b->getAssets(); std::string key; Asset valueA; Asset valueB; - std::unordered_map::const_iterator valueIt, it; + hlookup::string_map::const_iterator valueIt, it; for (it = _assets.begin(); it != _assets.end(); ++it) { key = it->first; @@ -317,22 +317,22 @@ void Manifest::prependSearchPaths() } } -const std::string& Manifest::getPackageUrl() const +std::string_view Manifest::getPackageUrl() const { return _packageUrl; } -const std::string& Manifest::getManifestFileUrl() const +std::string_view Manifest::getManifestFileUrl() const { return _remoteManifestUrl; } -const std::string& Manifest::getVersionFileUrl() const +std::string_view Manifest::getVersionFileUrl() const { return _remoteVersionUrl; } -const std::string& Manifest::getVersion() const +std::string_view Manifest::getVersion() const { return _version; } @@ -342,22 +342,22 @@ const std::vector& Manifest::getGroups() const return _groups; } -const std::unordered_map& Manifest::getGroupVerions() const +const hlookup::string_map& Manifest::getGroupVerions() const { return _groupVer; } -const std::string& Manifest::getGroupVersion(const std::string& group) const +std::string_view Manifest::getGroupVersion(std::string_view group) const { return _groupVer.at(group); } -const std::unordered_map& Manifest::getAssets() const +const hlookup::string_map& Manifest::getAssets() const { return _assets; } -void Manifest::setAssetDownloadState(const std::string& key, const Manifest::DownloadState& state) +void Manifest::setAssetDownloadState(std::string_view key, const Manifest::DownloadState& state) { auto valueIt = _assets.find(key); if (valueIt != _assets.end()) @@ -372,9 +372,9 @@ void Manifest::setAssetDownloadState(const std::string& key, const Manifest::Dow rapidjson::Value& assets = _json[KEY_ASSETS]; if (assets.IsObject()) { - if (assets.HasMember(key.c_str())) + if (assets.HasMember(key.data())) { - rapidjson::Value& entry = assets[key.c_str()]; + rapidjson::Value& entry = assets[key.data()]; if (entry.HasMember(KEY_DOWNLOAD_STATE) && entry[KEY_DOWNLOAD_STATE].IsInt()) { entry[KEY_DOWNLOAD_STATE].SetInt((int)state); @@ -413,7 +413,7 @@ void Manifest::clear() } } -Manifest::Asset Manifest::parseAsset(const std::string& path, const rapidjson::Value& json) +Manifest::Asset Manifest::parseAsset(std::string_view path, const rapidjson::Value& json) { Asset asset; asset.path = path; @@ -553,7 +553,7 @@ void Manifest::loadManifest(const rapidjson::Document& json) _loaded = true; } -void Manifest::saveToFile(const std::string& filepath) +void Manifest::saveToFile(std::string_view filepath) { rapidjson::StringBuffer buffer; rapidjson::PrettyWriter writer(buffer); diff --git a/extensions/assets-manager/Manifest.h b/extensions/assets-manager/Manifest.h index 695cbe55c7e9..d58260810881 100644 --- a/extensions/assets-manager/Manifest.h +++ b/extensions/assets-manager/Manifest.h @@ -56,7 +56,7 @@ struct ManifestAsset int downloadState; }; -typedef std::unordered_map DownloadUnits; +typedef hlookup::string_map DownloadUnits; class CC_EX_DLL Manifest : public Ref { @@ -99,19 +99,19 @@ class CC_EX_DLL Manifest : public Ref /** @brief Gets remote package url. */ - const std::string& getPackageUrl() const; + std::string_view getPackageUrl() const; /** @brief Gets remote manifest file url. */ - const std::string& getManifestFileUrl() const; + std::string_view getManifestFileUrl() const; /** @brief Gets remote version file url. */ - const std::string& getVersionFileUrl() const; + std::string_view getVersionFileUrl() const; /** @brief Gets manifest version. */ - const std::string& getVersion() const; + std::string_view getVersion() const; /** @brief Get the search paths list related to the Manifest. */ @@ -121,22 +121,22 @@ class CC_EX_DLL Manifest : public Ref /** @brief Constructor for Manifest class * @param manifestUrl Url of the local manifest */ - Manifest(const std::string& manifestUrl = ""); + Manifest(std::string_view manifestUrl = ""); /** @brief Load the json file into local json object * @param url Url of the json file */ - void loadJson(const std::string& url); + void loadJson(std::string_view url); /** @brief Parse the version file information into this manifest * @param versionUrl Url of the local version file */ - void parseVersion(const std::string& versionUrl); + void parseVersion(std::string_view versionUrl); /** @brief Parse the manifest file information into this manifest * @param manifestUrl Url of the local manifest */ - void parse(const std::string& manifestUrl); + void parse(std::string_view manifestUrl); /** @brief Check whether the version of this manifest equals to another. * @param b The other manifest @@ -149,14 +149,13 @@ class CC_EX_DLL Manifest : public Ref * @param [handle] Customized comparasion handle function * @return Greater or not */ - bool versionGreater( - const Manifest* b, - const std::function& handle) const; + bool versionGreater(const Manifest* b, + const std::function& handle) const; /** @brief Generate difference between this Manifest and another. * @param b The other manifest */ - std::unordered_map genDiff(const Manifest* b) const; + hlookup::string_map genDiff(const Manifest* b) const; /** @brief Generate resuming download assets list * @param units The download units reference to be modified by the generation result @@ -171,9 +170,9 @@ class CC_EX_DLL Manifest : public Ref void loadManifest(const rapidjson::Document& json); - void saveToFile(const std::string& filepath); + void saveToFile(std::string_view filepath); - Asset parseAsset(const std::string& path, const rapidjson::Value& json); + Asset parseAsset(std::string_view path, const rapidjson::Value& json); void clear(); @@ -183,26 +182,26 @@ class CC_EX_DLL Manifest : public Ref /** @brief Gets all groups version. */ - const std::unordered_map& getGroupVerions() const; + const hlookup::string_map& getGroupVerions() const; /** @brief Gets version for the given group. * @param group Key of the requested group */ - const std::string& getGroupVersion(const std::string& group) const; + std::string_view getGroupVersion(std::string_view group) const; /** * @brief Gets assets. * @lua NA */ - const std::unordered_map& getAssets() const; + const hlookup::string_map& getAssets() const; /** @brief Set the download state for an asset * @param key Key of the asset to set * @param state The current download state of the asset */ - void setAssetDownloadState(const std::string& key, const DownloadState& state); + void setAssetDownloadState(std::string_view key, const DownloadState& state); - void setManifestRoot(const std::string& root) { _manifestRoot = root; }; + void setManifestRoot(std::string_view root) { _manifestRoot = root; }; private: //! Indicate whether the version informations have been fully loaded @@ -233,13 +232,13 @@ class CC_EX_DLL Manifest : public Ref std::vector _groups; //! The versions of all local group [Optional] - std::unordered_map _groupVer; + hlookup::string_map _groupVer; //! The version of local engine std::string _engineVer; //! Full assets list - std::unordered_map _assets; + hlookup::string_map _assets; //! All search paths std::vector _searchPaths; diff --git a/extensions/cocostudio/ActionTimeline/CCActionTimeline.cpp b/extensions/cocostudio/ActionTimeline/CCActionTimeline.cpp index bf4dd8ac18b8..6edbb870737a 100644 --- a/extensions/cocostudio/ActionTimeline/CCActionTimeline.cpp +++ b/extensions/cocostudio/ActionTimeline/CCActionTimeline.cpp @@ -319,12 +319,12 @@ void ActionTimeline::removeAnimationInfo(std::string animationName) _animationInfos.erase(animationName); } -bool ActionTimeline::IsAnimationInfoExists(const std::string& animationName) +bool ActionTimeline::IsAnimationInfoExists(std::string_view animationName) { return _animationInfos.find(animationName) != _animationInfos.end(); } -const AnimationInfo& ActionTimeline::getAnimationInfo(const std::string& animationName) +const AnimationInfo& ActionTimeline::getAnimationInfo(std::string_view animationName) { return _animationInfos.find(animationName)->second; } @@ -369,7 +369,7 @@ void ActionTimeline::emitFrameEvent(Frame* frame) } } -void ActionTimeline::addFrameEndCallFunc(int frameIndex, const std::string& funcKey, std::function func) +void ActionTimeline::addFrameEndCallFunc(int frameIndex, std::string_view funcKey, std::function func) { if (func != nullptr) { @@ -377,7 +377,7 @@ void ActionTimeline::addFrameEndCallFunc(int frameIndex, const std::string& func } } -void ActionTimeline::removeFrameEndCallFunc(int frameIndex, const std::string& funcKey) +void ActionTimeline::removeFrameEndCallFunc(int frameIndex, std::string_view funcKey) { auto endClipCallsIter = _frameEndCallFuncs.find(frameIndex); if (endClipCallsIter != _frameEndCallFuncs.end()) diff --git a/extensions/cocostudio/ActionTimeline/CCActionTimeline.h b/extensions/cocostudio/ActionTimeline/CCActionTimeline.h index 6437359ff4ec..0d57dea4a181 100644 --- a/extensions/cocostudio/ActionTimeline/CCActionTimeline.h +++ b/extensions/cocostudio/ActionTimeline/CCActionTimeline.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013 cocos2d-x.org http://www.cocos2d-x.org @@ -37,7 +37,7 @@ typedef struct AnimationInfo { AnimationInfo() : startIndex(0), endIndex(0) {} - AnimationInfo(const std::string& otherName, int otherStartIndex, int otherEndIndex) + AnimationInfo(std::string_view otherName, int otherStartIndex, int otherEndIndex) : name(otherName), startIndex(otherStartIndex), endIndex(otherEndIndex) {} @@ -150,8 +150,8 @@ class CCS_DLL ActionTimeline : public cocos2d::Action, public cocos2d::PlayableP /** AnimationInfo*/ virtual void addAnimationInfo(const AnimationInfo& animationInfo); virtual void removeAnimationInfo(std::string animationName); - virtual bool IsAnimationInfoExists(const std::string& animationName); - virtual const AnimationInfo& getAnimationInfo(const std::string& animationName); + virtual bool IsAnimationInfoExists(std::string_view animationName); + virtual const AnimationInfo& getAnimationInfo(std::string_view animationName); /**add a frame end call back to animation's end frame * @param animationName @addFrameEndCallFunc, make the animationName as funcKey * @param func the callback function @@ -171,9 +171,9 @@ class CCS_DLL ActionTimeline : public cocos2d::Action, public cocos2d::PlayableP * @param funcKey for identity the callback function * @param func the callback function */ - virtual void addFrameEndCallFunc(int frameIndex, const std::string& funcKey, std::function func); + virtual void addFrameEndCallFunc(int frameIndex, std::string_view funcKey, std::function func); // remove callback function after frameIndex which identified with funcKey - virtual void removeFrameEndCallFunc(int frameIndex, const std::string& funcKey); + virtual void removeFrameEndCallFunc(int frameIndex, std::string_view funcKey); // clear callback functions after frameIndex virtual void removeFrameEndCallFuncs(int frameIndex); // clear all the callback functions after frameIndexs in this actiontimeline @@ -224,8 +224,8 @@ class CCS_DLL ActionTimeline : public cocos2d::Action, public cocos2d::PlayableP std::function _frameEventListener; std::function _lastFrameListener; - std::map>> _frameEndCallFuncs; - std::map _animationInfos; + std::map>> _frameEndCallFuncs; + hlookup::string_map _animationInfos; }; NS_TIMELINE_END diff --git a/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.cpp b/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.cpp index 44af85a5c594..5ca337f08400 100644 --- a/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.cpp +++ b/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.cpp @@ -126,7 +126,7 @@ void ActionTimelineCache::init() */ } -void ActionTimelineCache::removeAction(const std::string& fileName) +void ActionTimelineCache::removeAction(std::string_view fileName) { if (_animationActions.find(fileName) != _animationActions.end()) { @@ -134,11 +134,11 @@ void ActionTimelineCache::removeAction(const std::string& fileName) } } -ActionTimeline* ActionTimelineCache::createAction(const std::string& filename) +ActionTimeline* ActionTimelineCache::createAction(std::string_view filename) { - std::string path = filename; - size_t pos = path.find_last_of('.'); - std::string suffix = path.substr(pos + 1, path.length()); + auto path = filename; + size_t pos = path.find_last_of('.'); + auto suffix = path.substr(pos + 1, path.length()); ActionTimelineCache* cache = ActionTimelineCache::getInstance(); @@ -154,7 +154,7 @@ ActionTimeline* ActionTimelineCache::createAction(const std::string& filename) return nullptr; } -ActionTimeline* ActionTimelineCache::createActionFromJson(const std::string& fileName) +ActionTimeline* ActionTimelineCache::createActionFromJson(std::string_view fileName) { ActionTimeline* action = _animationActions.at(fileName); if (action == nullptr) @@ -164,7 +164,7 @@ ActionTimeline* ActionTimelineCache::createActionFromJson(const std::string& fil return action->clone(); } -ActionTimeline* ActionTimelineCache::createActionFromContent(const std::string& fileName, const std::string& content) +ActionTimeline* ActionTimelineCache::createActionFromContent(std::string_view fileName, std::string_view content) { ActionTimeline* action = _animationActions.at(fileName); if (action == nullptr) @@ -174,7 +174,7 @@ ActionTimeline* ActionTimelineCache::createActionFromContent(const std::string& return action->clone(); } -ActionTimeline* ActionTimelineCache::loadAnimationActionWithFile(const std::string& fileName) +ActionTimeline* ActionTimelineCache::loadAnimationActionWithFile(std::string_view fileName) { // Read content from file std::string fullPath = FileUtils::getInstance()->fullPathForFilename(fileName); @@ -183,8 +183,7 @@ ActionTimeline* ActionTimelineCache::loadAnimationActionWithFile(const std::stri return loadAnimationActionWithContent(fileName, contentStr); } -ActionTimeline* ActionTimelineCache::loadAnimationActionWithContent(const std::string& fileName, - const std::string& content) +ActionTimeline* ActionTimelineCache::loadAnimationActionWithContent(std::string_view fileName, std::string_view content) { // if already exists an action with filename, then return this action ActionTimeline* action = _animationActions.at(fileName); @@ -192,7 +191,7 @@ ActionTimeline* ActionTimelineCache::loadAnimationActionWithContent(const std::s return action; rapidjson::Document doc; - doc.Parse<0>(content.c_str()); + doc.Parse<0>(content.data(), content.length()); if (doc.HasParseError()) { CCLOG("GetParseError %d\n", doc.GetParseError()); @@ -415,7 +414,7 @@ Frame* ActionTimelineCache::loadZOrderFrame(const rapidjson::Value& json) return frame; } -ActionTimeline* ActionTimelineCache::createActionWithFlatBuffersFile(const std::string& fileName) +ActionTimeline* ActionTimelineCache::createActionWithFlatBuffersFile(std::string_view fileName) { ActionTimeline* action = _animationActions.at(fileName); if (action == NULL) @@ -425,7 +424,7 @@ ActionTimeline* ActionTimelineCache::createActionWithFlatBuffersFile(const std:: return action->clone(); } -ActionTimeline* ActionTimelineCache::createActionWithDataBuffer(Data data, const std::string& fileName) +ActionTimeline* ActionTimelineCache::createActionWithDataBuffer(Data data, std::string_view fileName) { ActionTimeline* action = _animationActions.at(fileName); if (action == NULL) @@ -435,15 +434,13 @@ ActionTimeline* ActionTimelineCache::createActionWithDataBuffer(Data data, const return action->clone(); } -ActionTimeline* ActionTimelineCache::loadAnimationActionWithFlatBuffersFile(const std::string& fileName) +ActionTimeline* ActionTimelineCache::loadAnimationActionWithFlatBuffersFile(std::string_view fileName) { // if already exists an action with filename, then return this action ActionTimeline* action = _animationActions.at(fileName); if (action) return action; - std::string path = fileName; - std::string fullPath = FileUtils::getInstance()->fullPathForFilename(fileName); CC_ASSERT(FileUtils::getInstance()->isFileExist(fullPath)); @@ -455,15 +452,13 @@ ActionTimeline* ActionTimelineCache::loadAnimationActionWithFlatBuffersFile(cons return action; } -ActionTimeline* ActionTimelineCache::loadAnimationWithDataBuffer(const cocos2d::Data& data, const std::string& fileName) +ActionTimeline* ActionTimelineCache::loadAnimationWithDataBuffer(const cocos2d::Data& data, std::string_view fileName) { // if already exists an action with filename, then return this action ActionTimeline* action = _animationActions.at(fileName); if (action) return action; - std::string path = fileName; - std::string fullPath = FileUtils::getInstance()->fullPathForFilename(fileName); CC_ASSERT(FileUtils::getInstance()->isFileExist(fullPath)); @@ -953,7 +948,7 @@ void ActionTimelineCache::loadEasingDataWithFlatBuffers(cocostudio::timeline::Fr } } -ActionTimeline* ActionTimelineCache::createActionWithFlatBuffersForSimulator(const std::string& fileName) +ActionTimeline* ActionTimelineCache::createActionWithFlatBuffersForSimulator(std::string_view fileName) { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); fbs->_isSimulator = true; diff --git a/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.h b/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.h index 052280d16485..ff3ecc26a04a 100644 --- a/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.h +++ b/extensions/cocostudio/ActionTimeline/CCActionTimelineCache.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013 cocos2d-x.org http://www.cocos2d-x.org @@ -71,24 +71,24 @@ class CCS_DLL ActionTimelineCache void init(); /** Remove action with filename, and also remove other resource relate with this file */ - void removeAction(const std::string& fileName); + void removeAction(std::string_view fileName); - static ActionTimeline* createAction(const std::string& fileName); + static ActionTimeline* createAction(std::string_view fileName); /** Clone a action with the specified name from the container. */ - ActionTimeline* createActionFromJson(const std::string& fileName); - ActionTimeline* createActionFromContent(const std::string& fileName, const std::string& content); + ActionTimeline* createActionFromJson(std::string_view fileName); + ActionTimeline* createActionFromContent(std::string_view fileName, std::string_view content); - ActionTimeline* loadAnimationActionWithFile(const std::string& fileName); - ActionTimeline* loadAnimationActionWithContent(const std::string& fileName, const std::string& content); + ActionTimeline* loadAnimationActionWithFile(std::string_view fileName); + ActionTimeline* loadAnimationActionWithContent(std::string_view fileName, std::string_view content); - ActionTimeline* createActionWithFlatBuffersFile(const std::string& fileName); - ActionTimeline* createActionWithDataBuffer(cocos2d::Data data, const std::string& fileName); + ActionTimeline* createActionWithFlatBuffersFile(std::string_view fileName); + ActionTimeline* createActionWithDataBuffer(cocos2d::Data data, std::string_view fileName); - ActionTimeline* loadAnimationActionWithFlatBuffersFile(const std::string& fileName); - ActionTimeline* loadAnimationWithDataBuffer(const cocos2d::Data& data, const std::string& fileName); + ActionTimeline* loadAnimationActionWithFlatBuffersFile(std::string_view fileName); + ActionTimeline* loadAnimationWithDataBuffer(const cocos2d::Data& data, std::string_view fileName); - ActionTimeline* createActionWithFlatBuffersForSimulator(const std::string& fileName); + ActionTimeline* createActionWithFlatBuffersForSimulator(std::string_view fileName); protected: Timeline* loadTimeline(const rapidjson::Value& json); @@ -128,8 +128,8 @@ class CCS_DLL ActionTimelineCache typedef std::function FrameCreateFunc; typedef std::pair Pair; - std::unordered_map _funcs; - cocos2d::Map _animationActions; + hlookup::string_map _funcs; + cocos2d::StringMap _animationActions; }; NS_TIMELINE_END diff --git a/extensions/cocostudio/ActionTimeline/CCBoneNode.cpp b/extensions/cocostudio/ActionTimeline/CCBoneNode.cpp index de7d55ca31d5..b812c36371ee 100644 --- a/extensions/cocostudio/ActionTimeline/CCBoneNode.cpp +++ b/extensions/cocostudio/ActionTimeline/CCBoneNode.cpp @@ -75,20 +75,20 @@ bool BoneNode::init() setProgramState(new cocos2d::backend::ProgramState(program), false); pipelineDescriptor.programState = _programState; - _mvpLocation = _programState->getUniformLocation("u_MVPMatrix"); + _mvpLocation = _programState->getUniformLocation("u_MVPMatrix"sv); auto vertexLayout = _programState->getVertexLayout(); const auto& attributeInfo = _programState->getProgram()->getActiveAttributes(); - auto iter = attributeInfo.find("a_position"); + auto iter = attributeInfo.find("a_position"sv); if (iter != attributeInfo.end()) { - vertexLayout->setAttribute("a_position", iter->second.location, cocos2d::backend::VertexFormat::FLOAT3, 0, + vertexLayout->setAttribute("a_position"sv, iter->second.location, cocos2d::backend::VertexFormat::FLOAT3, 0, false); } - iter = attributeInfo.find("a_color"); + iter = attributeInfo.find("a_color"sv); if (iter != attributeInfo.end()) { - vertexLayout->setAttribute("a_color", iter->second.location, cocos2d::backend::VertexFormat::FLOAT4, + vertexLayout->setAttribute("a_color"sv, iter->second.location, cocos2d::backend::VertexFormat::FLOAT4, 3 * sizeof(float), false); } vertexLayout->setLayout(7 * sizeof(float)); @@ -108,7 +108,7 @@ void BoneNode::addChild(cocos2d::Node* child, int localZOrder, int tag) Node::addChild(child, localZOrder, tag); } -void BoneNode::addChild(Node* child, int localZOrder, const std::string& name) +void BoneNode::addChild(Node* child, int localZOrder, std::string_view name) { addToChildrenListHelper(child); Node::addChild(child, localZOrder, name); @@ -152,7 +152,7 @@ void BoneNode::removeFromBoneList(BoneNode* bone) { auto subBones = bone->getAllSubBones(); subBones.pushBack(bone); - for (auto& subBone : subBones) + for (auto subBone : subBones) { if (subBone->_rootSkeleton == nullptr) continue; @@ -186,7 +186,7 @@ void BoneNode::addToBoneList(BoneNode* bone) { auto subBones = bone->getAllSubBones(); subBones.pushBack(bone); - for (auto& subBone : subBones) + for (auto subBone : subBones) { subBone->_rootSkeleton = _rootSkeleton; auto bonename = subBone->getName(); @@ -198,8 +198,8 @@ void BoneNode::addToBoneList(BoneNode* bone) _rootSkeleton->_subBonesOrderDirty = true; } else - CCLOG("already has a bone named %s in skeleton %s", bonename.c_str(), - _rootSkeleton->getName().c_str()); + CCLOG("already has a bone named %s in skeleton %s", bonename.data(), + _rootSkeleton->getName().data()); } } else @@ -240,7 +240,7 @@ void BoneNode::displaySkin(SkinNode* skin, bool hideOthers) } } -void BoneNode::displaySkin(const std::string& skinName, bool hideOthers) +void BoneNode::displaySkin(std::string_view skinName, bool hideOthers) { for (auto& skin : _boneSkins) { @@ -661,7 +661,7 @@ void BoneNode::setLocalZOrder(int localZOrder) _rootSkeleton->_subBonesOrderDirty = true; } -void BoneNode::setName(const std::string& name) +void BoneNode::setName(std::string_view name) { auto oldname = getName(); Node::setName(name); diff --git a/extensions/cocostudio/ActionTimeline/CCBoneNode.h b/extensions/cocostudio/ActionTimeline/CCBoneNode.h index 02003d3ce76c..60450caa799c 100644 --- a/extensions/cocostudio/ActionTimeline/CCBoneNode.h +++ b/extensions/cocostudio/ActionTimeline/CCBoneNode.h @@ -52,7 +52,7 @@ class CCS_DLL BoneNode : public cocos2d::Node, public cocos2d::BlendProtocol using Node::addChild; // add child, and add child to bone list and skeleton's sub bone map or add it to skin list - virtual void addChild(cocos2d::Node* child, int localZOrder, const std::string& name) override; + virtual void addChild(cocos2d::Node* child, int localZOrder, std::string_view name) override; virtual void addChild(cocos2d::Node* child, int localZOrder, int tag) override; // remove child, and remove child from bone list and skeleton's sub bone map or remove it from skin list @@ -94,7 +94,7 @@ class CCS_DLL BoneNode : public cocos2d::Node, public cocos2d::BlendProtocol * prefer to use display(SkinNode* skin, bool hideOthers = false) * @param: hideOthers, set other skins invisible */ - virtual void displaySkin(const std::string& skinName, bool hideOthers); + virtual void displaySkin(std::string_view skinName, bool hideOthers); // get the skins which is visible (displaying skins) virtual cocos2d::Vector getVisibleSkins() const; @@ -146,7 +146,7 @@ class CCS_DLL BoneNode : public cocos2d::Node, public cocos2d::BlendProtocol virtual void setLocalZOrder(int localZOrder) override; // set name, and replace the subbone map in skeleton - virtual void setName(const std::string& name) override; + virtual void setName(std::string_view name) override; // set visible, and dirty the debugdraw to make debugdraw's render layer right virtual void setVisible(bool visible) override; diff --git a/extensions/cocostudio/ActionTimeline/CCFrame.cpp b/extensions/cocostudio/ActionTimeline/CCFrame.cpp index 2b410c5f27c3..fff31a344d80 100644 --- a/extensions/cocostudio/ActionTimeline/CCFrame.cpp +++ b/extensions/cocostudio/ActionTimeline/CCFrame.cpp @@ -548,7 +548,7 @@ void InnerActionFrame::setEndFrameIndex(int frameIndex) _endFrameIndex = frameIndex; } -void InnerActionFrame::setAnimationName(const std::string& animationName) +void InnerActionFrame::setAnimationName(std::string_view animationName) { if (!_enterWithName) { diff --git a/extensions/cocostudio/ActionTimeline/CCFrame.h b/extensions/cocostudio/ActionTimeline/CCFrame.h index f9c0ccd37c98..715972ca554d 100644 --- a/extensions/cocostudio/ActionTimeline/CCFrame.h +++ b/extensions/cocostudio/ActionTimeline/CCFrame.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013 cocos2d-x.org http://www.cocos2d-x.org @@ -119,8 +119,8 @@ class CCS_DLL TextureFrame : public Frame virtual void onEnter(Frame* nextFrame, int currentFrameIndex) override; virtual Frame* clone() override; - inline void setTextureName(std::string textureName) { _textureName = textureName; } - inline std::string getTextureName() const { return _textureName; } + inline void setTextureName(std::string_view textureName) { _textureName = textureName; } + inline std::string_view getTextureName() const { return _textureName; } protected: cocos2d::Sprite* _sprite; @@ -293,7 +293,7 @@ class CCS_DLL InnerActionFrame : public Frame void setEndFrameIndex(int frameIndex); inline int getEndFrameIndex() const { return _endFrameIndex; } - void setAnimationName(const std::string& animationNamed); + void setAnimationName(std::string_view animationNamed); inline void setSingleFrameIndex(int frameIndex) { _singleFrameIndex = frameIndex; } inline int getSingleFrameIndex() const { return _singleFrameIndex; } @@ -366,8 +366,8 @@ class CCS_DLL EventFrame : public Frame virtual void onEnter(Frame* nextFrame, int currentFrameIndex) override; virtual Frame* clone() override; - inline void setEvent(std::string event) { _event = event; } - inline std::string getEvent() const { return _event; } + inline void setEvent(std::string_view event) { _event = event; } + inline std::string_view getEvent() const { return _event; } protected: std::string _event; diff --git a/extensions/cocostudio/ActionTimeline/CCSkeletonNode.cpp b/extensions/cocostudio/ActionTimeline/CCSkeletonNode.cpp index 69417e6a473b..d0a07494151d 100644 --- a/extensions/cocostudio/ActionTimeline/CCSkeletonNode.cpp +++ b/extensions/cocostudio/ActionTimeline/CCSkeletonNode.cpp @@ -298,7 +298,7 @@ void SkeletonNode::batchDrawAllSubBones() #endif // CC_STUDIO_ENABLED_VIEW } -void SkeletonNode::changeSkins(const std::map& boneSkinNameMap) +void SkeletonNode::changeSkins(const hlookup::string_map& boneSkinNameMap) { for (auto& boneskin : boneSkinNameMap) { @@ -308,7 +308,7 @@ void SkeletonNode::changeSkins(const std::map& boneSki } } -void SkeletonNode::changeSkins(const std::string& skinGroupName) +void SkeletonNode::changeSkins(std::string_view skinGroupName) { auto suit = _skinGroupMap.find(skinGroupName); if (suit != _skinGroupMap.end()) @@ -317,7 +317,7 @@ void SkeletonNode::changeSkins(const std::string& skinGroupName) } } -BoneNode* SkeletonNode::getBoneNode(const std::string& boneName) +BoneNode* SkeletonNode::getBoneNode(std::string_view boneName) { auto iter = _subBonesMap.find(boneName); if (iter != _subBonesMap.end()) @@ -327,14 +327,14 @@ BoneNode* SkeletonNode::getBoneNode(const std::string& boneName) return nullptr; } -const cocos2d::Map& SkeletonNode::getAllSubBonesMap() const +const cocos2d::StringMap& SkeletonNode::getAllSubBonesMap() const { return _subBonesMap; } -void SkeletonNode::addSkinGroup(std::string groupName, std::map boneSkinNameMap) +void SkeletonNode::addSkinGroup(std::string groupName, hlookup::string_map boneSkinNameMap) { - _skinGroupMap.emplace(groupName, boneSkinNameMap); + _skinGroupMap.emplace(groupName, std::move(boneSkinNameMap)); } void SkeletonNode::checkSubBonesDirty() diff --git a/extensions/cocostudio/ActionTimeline/CCSkeletonNode.h b/extensions/cocostudio/ActionTimeline/CCSkeletonNode.h index e6117bdcb91c..7e004a393805 100644 --- a/extensions/cocostudio/ActionTimeline/CCSkeletonNode.h +++ b/extensions/cocostudio/ActionTimeline/CCSkeletonNode.h @@ -44,31 +44,31 @@ class CCS_DLL SkeletonNode : public BoneNode /** *get bonenode in skeleton node by bone name */ - BoneNode* getBoneNode(const std::string& boneName); + BoneNode* getBoneNode(std::string_view boneName); /** *get All bones in this skeleton, */ - const cocos2d::Map& getAllSubBonesMap() const; + const cocos2d::StringMap& getAllSubBonesMap() const; /** *@brief: change displays *@param: boneSkinNameMap, map */ - void changeSkins(const std::map& boneSkinNameMap); + void changeSkins(const hlookup::string_map& boneSkinNameMap); /** *@brief: change displays *@param: skinGroupName have */ - void changeSkins(const std::string& skinGroupName); + void changeSkins(std::string_view skinGroupName); /** *@brief: add a boneSkinNameMap as a SkinGroup named groupName *@param: groupName, key *@param: boneSkinNameMap, map */ - void addSkinGroup(std::string groupName, std::map boneSkinNameMap); + void addSkinGroup(std::string groupName, hlookup::string_map boneSkinNameMap); cocos2d::Rect getBoundingBox() const override; @@ -86,7 +86,7 @@ class CCS_DLL SkeletonNode : public BoneNode virtual void draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, uint32_t flags) override; protected: - cocos2d::Map _subBonesMap; + cocos2d::StringMap _subBonesMap; private: struct VertexData @@ -98,7 +98,7 @@ class CCS_DLL SkeletonNode : public BoneNode cocos2d::Vec2 _squareVertices[8]; VertexData _vertexData[8]; - std::map> + hlookup::string_map> _skinGroupMap; // map< suit name, map< bone name, skin name> > CC_DISALLOW_COPY_AND_ASSIGN(SkeletonNode); diff --git a/extensions/cocostudio/ActionTimeline/CSLoader.cpp b/extensions/cocostudio/ActionTimeline/CSLoader.cpp index fcb10cc04e0b..d414f5b7eaf2 100644 --- a/extensions/cocostudio/ActionTimeline/CSLoader.cpp +++ b/extensions/cocostudio/ActionTimeline/CSLoader.cpp @@ -280,11 +280,11 @@ void CSLoader::init() _componentFuncs.insert(ComponentPair(ClassName_ComAudio, std::bind(&CSLoader::loadComAudio, this, _1))); } -Node* CSLoader::createNode(const std::string& filename) +Node* CSLoader::createNode(std::string_view filename) { - std::string path = filename; - size_t pos = path.find_last_of('.'); - std::string suffix = path.substr(pos + 1, path.length()); + auto path = filename; + size_t pos = path.find_last_of('.'); + auto suffix = path.substr(pos + 1, path.length()); CSLoader* load = CSLoader::getInstance(); @@ -300,11 +300,11 @@ Node* CSLoader::createNode(const std::string& filename) return nullptr; } -Node* CSLoader::createNode(const std::string& filename, const ccNodeLoadCallback& callback) +Node* CSLoader::createNode(std::string_view filename, const ccNodeLoadCallback& callback) { - std::string path = filename; - size_t pos = path.find_last_of('.'); - std::string suffix = path.substr(pos + 1, path.length()); + auto path = filename; + size_t pos = path.find_last_of('.'); + auto suffix = path.substr(pos + 1, path.length()); CSLoader* load = CSLoader::getInstance(); @@ -316,7 +316,7 @@ Node* CSLoader::createNode(const std::string& filename, const ccNodeLoadCallback return nullptr; } -Node* CSLoader::createNodeWithVisibleSize(const std::string& filename) +Node* CSLoader::createNodeWithVisibleSize(std::string_view filename) { auto node = createNode(filename); if (node != nullptr) @@ -328,7 +328,7 @@ Node* CSLoader::createNodeWithVisibleSize(const std::string& filename) return node; } -Node* CSLoader::createNodeWithVisibleSize(const std::string& filename, const ccNodeLoadCallback& callback) +Node* CSLoader::createNodeWithVisibleSize(std::string_view filename, const ccNodeLoadCallback& callback) { auto node = createNode(filename, callback); if (node != nullptr) @@ -340,18 +340,18 @@ Node* CSLoader::createNodeWithVisibleSize(const std::string& filename, const ccN return node; } -std::string CSLoader::getExtentionName(const std::string& name) +std::string_view CSLoader::getExtentionName(std::string_view name) { - std::string path = name; - size_t pos = path.find_last_of('.'); - std::string result = path.substr(pos + 1, path.length()); + auto path = name; + size_t pos = path.find_last_of('.'); + auto result = path.substr(pos + 1, path.length()); return result; } -ActionTimeline* CSLoader::createTimeline(const std::string& filename) +ActionTimeline* CSLoader::createTimeline(std::string_view filename) { - std::string suffix = getExtentionName(filename); + auto suffix = getExtentionName(filename); ActionTimelineCache* cache = ActionTimelineCache::getInstance(); @@ -367,9 +367,9 @@ ActionTimeline* CSLoader::createTimeline(const std::string& filename) return nullptr; } -ActionTimeline* CSLoader::createTimeline(const Data& data, const std::string& filename) +ActionTimeline* CSLoader::createTimeline(const Data& data, std::string_view filename) { - std::string suffix = getExtentionName(filename); + auto suffix = getExtentionName(filename); ActionTimelineCache* cache = ActionTimelineCache::getInstance(); @@ -379,7 +379,7 @@ ActionTimeline* CSLoader::createTimeline(const Data& data, const std::string& fi } else if (suffix == "json" || suffix == "ExportJson") { - std::string content((char*)data.getBytes(), data.getSize()); + std::string_view content((char*)data.getBytes(), data.getSize()); return cache->createActionFromContent(filename, content); } @@ -387,7 +387,7 @@ ActionTimeline* CSLoader::createTimeline(const Data& data, const std::string& fi } /* -ActionTimelineNode* CSLoader::createActionTimelineNode(const std::string& filename) +ActionTimelineNode* CSLoader::createActionTimelineNode(std::string_view filename) { Node* root = createNode(filename); ActionTimeline* action = createTimeline(filename); @@ -401,7 +401,7 @@ ActionTimelineNode* CSLoader::createActionTimelineNode(const std::string& filena ActionTimelineNode* node = ActionTimelineNode::create(root, action); return node; } -ActionTimelineNode* CSLoader::createActionTimelineNode(const std::string& filename, int startIndex, int endIndex, bool +ActionTimelineNode* CSLoader::createActionTimelineNode(std::string_view filename, int startIndex, int endIndex, bool loop) { ActionTimelineNode* node = createActionTimelineNode(filename); @@ -413,11 +413,11 @@ loop) } */ -Node* CSLoader::createNodeFromJson(const std::string& filename) +Node* CSLoader::createNodeFromJson(std::string_view filename) { if (_recordJsonPath) { - std::string jsonPath = filename.substr(0, filename.find_last_of('/') + 1); + auto jsonPath = filename.substr(0, filename.find_last_of('/') + 1); GUIReader::getInstance()->setFilePath(jsonPath); _jsonPath = jsonPath; @@ -432,7 +432,7 @@ Node* CSLoader::createNodeFromJson(const std::string& filename) return node; } -Node* CSLoader::loadNodeWithFile(const std::string& fileName) +Node* CSLoader::loadNodeWithFile(std::string_view fileName) { // Read content from file std::string contentStr = FileUtils::getInstance()->getStringFromFile(fileName); @@ -445,10 +445,10 @@ Node* CSLoader::loadNodeWithFile(const std::string& fileName) return node; } -Node* CSLoader::loadNodeWithContent(const std::string& content) +Node* CSLoader::loadNodeWithContent(std::string_view content) { rapidjson::Document doc; - doc.Parse<0>(content.c_str()); + doc.Parse<0>(content.data(), content.length()); if (doc.HasParseError()) { CCLOG("GetParseError %d\n", doc.GetParseError()); @@ -760,11 +760,11 @@ Node* CSLoader::loadWidget(const rapidjson::Value& json) if (isWidget(classname)) { - std::string readerName = getGUIClassName(classname); + std::string readerName{getGUIClassName(classname)}; readerName.append("Reader"); - std::string guiClassName = getGUIClassName(classname); - widget = dynamic_cast(ObjectFactory::getInstance()->createObject(guiClassName)); + std::string_view guiClassName = getGUIClassName(classname); + widget = dynamic_cast(ObjectFactory::getInstance()->createObject(guiClassName)); // fix memory leak for v3.3 // widget->retain(); @@ -785,7 +785,7 @@ Node* CSLoader::loadWidget(const rapidjson::Value& json) // // 1st., custom widget parse properties of parent widget with parent widget reader - std::string readerName = getWidgetReaderClassName(widget); + std::string_view readerName = getWidgetReaderClassName(widget); WidgetReaderProtocol* reader = dynamic_cast(ObjectFactory::getInstance()->createObject(readerName)); if (reader && widget) @@ -961,12 +961,12 @@ Node* CSLoader::createNode(const Data& data, const ccNodeLoadCallback& callback) return node; } -Node* CSLoader::createNodeWithFlatBuffersFile(const std::string& filename) +Node* CSLoader::createNodeWithFlatBuffersFile(std::string_view filename) { return createNodeWithFlatBuffersFile(filename, nullptr); } -Node* CSLoader::createNodeWithFlatBuffersFile(const std::string& filename, const ccNodeLoadCallback& callback) +Node* CSLoader::createNodeWithFlatBuffersFile(std::string_view filename, const ccNodeLoadCallback& callback) { Node* node = nodeWithFlatBuffersFile(filename, callback); @@ -990,17 +990,17 @@ inline void CSLoader::reconstructNestNode(cocos2d::Node* node) else { _rootNode = _callbackHandlers.back(); - CCLOG("after pop back _rootNode name = %s", _rootNode->getName().c_str()); + CCLOG("after pop back _rootNode name = %s", _rootNode->getName().data()); } } } -Node* CSLoader::nodeWithFlatBuffersFile(const std::string& fileName) +Node* CSLoader::nodeWithFlatBuffersFile(std::string_view fileName) { return nodeWithFlatBuffersFile(fileName, nullptr); } -Node* CSLoader::nodeWithFlatBuffersFile(const std::string& fileName, const ccNodeLoadCallback& callback) +Node* CSLoader::nodeWithFlatBuffersFile(std::string_view fileName, const ccNodeLoadCallback& callback) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(fileName); @@ -1010,7 +1010,7 @@ Node* CSLoader::nodeWithFlatBuffersFile(const std::string& fileName, const ccNod if (buf.isNull()) { - CCLOG("CSLoader::nodeWithFlatBuffersFile - failed read file: %s", fileName.c_str()); + CCLOG("CSLoader::nodeWithFlatBuffersFile - failed read file: %s", fileName.data()); CC_ASSERT(false); return nullptr; } @@ -1144,7 +1144,7 @@ Node* CSLoader::nodeWithFlatBuffers(const flatbuffers::NodeTree* nodetree, const { classname = customClassName; } - std::string readername = getGUIClassName(classname); + std::string readername{getGUIClassName(classname)}; readername.append("Reader"); NodeReaderProtocol* reader = @@ -1178,8 +1178,8 @@ Node* CSLoader::nodeWithFlatBuffers(const flatbuffers::NodeTree* nodetree, const Widget* widget = dynamic_cast(node); if (widget) { - std::string callbackName = widget->getCallbackName(); - std::string callbackType = widget->getCallbackType(); + auto callbackName = widget->getCallbackName(); + auto callbackType = widget->getCallbackType(); bindCallback(callbackName, callbackType, widget, _rootNode); } @@ -1248,8 +1248,8 @@ Node* CSLoader::nodeWithFlatBuffers(const flatbuffers::NodeTree* nodetree, const } } -bool CSLoader::bindCallback(const std::string& callbackName, - const std::string& callbackType, +bool CSLoader::bindCallback(std::string_view callbackName, + std::string_view callbackType, cocos2d::ui::Widget* sender, cocos2d::Node* handler) { @@ -1288,12 +1288,12 @@ bool CSLoader::bindCallback(const std::string& callbackName, } } - CCLOG("callBackName %s cannot be found", callbackName.c_str()); + CCLOG("callBackName %s cannot be found", callbackName.data()); return false; } -bool CSLoader::isWidget(const std::string& type) +bool CSLoader::isWidget(std::string_view type) { return (type == ClassName_Panel || type == ClassName_Button || type == ClassName_CheckBox || type == ClassName_ImageView || type == ClassName_TextAtlas || type == ClassName_LabelAtlas || @@ -1303,7 +1303,7 @@ bool CSLoader::isWidget(const std::string& type) type == ClassName_PageView || type == ClassName_Widget || type == ClassName_Label); } -bool CSLoader::isCustomWidget(const std::string& type) +bool CSLoader::isCustomWidget(std::string_view type) { Widget* widget = dynamic_cast(ObjectFactory::getInstance()->createObject(type)); if (widget) @@ -1315,40 +1315,42 @@ bool CSLoader::isCustomWidget(const std::string& type) return false; } -std::string CSLoader::getGUIClassName(const std::string& name) +std::string_view CSLoader::getGUIClassName(std::string_view name) { - std::string convertedClassName = name; + std::string_view convertedClassName; if (name == "Panel") { - convertedClassName = "Layout"; + convertedClassName = "Layout"sv; } else if (name == "TextArea") { - convertedClassName = "Text"; + convertedClassName = "Text"sv; } else if (name == "TextButton") { - convertedClassName = "Button"; + convertedClassName = "Button"sv; } else if (name == "Label") { - convertedClassName = "Text"; + convertedClassName = "Text"sv; } else if (name == "LabelAtlas") { - convertedClassName = "TextAtlas"; + convertedClassName = "TextAtlas"sv; } else if (name == "LabelBMFont") { - convertedClassName = "TextBMFont"; + convertedClassName = "TextBMFont"sv; } + else + convertedClassName = name; return convertedClassName; } -std::string CSLoader::getWidgetReaderClassName(Widget* widget) +std::string_view CSLoader::getWidgetReaderClassName(Widget* widget) { - std::string readerName; + std::string_view readerName; // 1st., custom widget parse properties of parent widget with parent widget reader if (dynamic_cast(widget)) @@ -1408,11 +1410,13 @@ std::string CSLoader::getWidgetReaderClassName(Widget* widget) { readerName = "WidgetReader"; } + else + readerName = hlookup::empty_sv; return readerName; } -void CSLoader::registReaderObject(const std::string& className, ObjectFactory::Instance ins) +void CSLoader::registReaderObject(std::string_view className, ObjectFactory::Instance ins) { ObjectFactory::TInfo t; t._class = className; @@ -1421,7 +1425,7 @@ void CSLoader::registReaderObject(const std::string& className, ObjectFactory::I ObjectFactory::getInstance()->registerType(t); } -Node* CSLoader::createNodeWithFlatBuffersForSimulator(const std::string& filename) +Node* CSLoader::createNodeWithFlatBuffersForSimulator(std::string_view filename) { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); fbs->_isSimulator = true; @@ -1495,7 +1499,7 @@ Node* CSLoader::nodeWithFlatBuffersForSimulator(const flatbuffers::NodeTree* nod } else { - std::string readername = getGUIClassName(classname); + std::string readername{getGUIClassName(classname)}; readername.append("Reader"); NodeReaderProtocol* reader = @@ -1508,8 +1512,8 @@ Node* CSLoader::nodeWithFlatBuffersForSimulator(const flatbuffers::NodeTree* nod Widget* widget = dynamic_cast(node); if (widget) { - std::string callbackName = widget->getCallbackName(); - std::string callbackType = widget->getCallbackType(); + auto callbackName = widget->getCallbackName(); + auto callbackType = widget->getCallbackType(); bindCallback(callbackName, callbackType, widget, _rootNode); } diff --git a/extensions/cocostudio/ActionTimeline/CSLoader.h b/extensions/cocostudio/ActionTimeline/CSLoader.h index afcd41f583d9..3ba1e7fedc1e 100644 --- a/extensions/cocostudio/ActionTimeline/CSLoader.h +++ b/extensions/cocostudio/ActionTimeline/CSLoader.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013 cocos2d-x.org http://www.cocos2d-x.org @@ -79,25 +79,25 @@ class CCS_DLL CSLoader void init(); - static cocos2d::Node* createNode(const std::string& filename); - static cocos2d::Node* createNode(const std::string& filename, const ccNodeLoadCallback& callback); + static cocos2d::Node* createNode(std::string_view filename); + static cocos2d::Node* createNode(std::string_view filename, const ccNodeLoadCallback& callback); static cocos2d::Node* createNode(const Data& data); static cocos2d::Node* createNode(const Data& data, const ccNodeLoadCallback& callback); - static cocos2d::Node* createNodeWithVisibleSize(const std::string& filename); - static cocos2d::Node* createNodeWithVisibleSize(const std::string& filename, const ccNodeLoadCallback& callback); + static cocos2d::Node* createNodeWithVisibleSize(std::string_view filename); + static cocos2d::Node* createNodeWithVisibleSize(std::string_view filename, const ccNodeLoadCallback& callback); - static cocostudio::timeline::ActionTimeline* createTimeline(const std::string& filename); - static cocostudio::timeline::ActionTimeline* createTimeline(const Data& data, const std::string& filename); + static cocostudio::timeline::ActionTimeline* createTimeline(std::string_view filename); + static cocostudio::timeline::ActionTimeline* createTimeline(const Data& data, std::string_view filename); /* - static cocostudio::timeline::ActionTimelineNode* createActionTimelineNode(const std::string& filename); - static cocostudio::timeline::ActionTimelineNode* createActionTimelineNode(const std::string& filename, int + static cocostudio::timeline::ActionTimelineNode* createActionTimelineNode(std::string_view filename); + static cocostudio::timeline::ActionTimelineNode* createActionTimelineNode(std::string_view filename, int startIndex, int endIndex, bool loop); */ - cocos2d::Node* createNodeFromJson(const std::string& filename); - cocos2d::Node* loadNodeWithFile(const std::string& fileName); - cocos2d::Node* loadNodeWithContent(const std::string& content); + cocos2d::Node* createNodeFromJson(std::string_view filename); + cocos2d::Node* loadNodeWithFile(std::string_view fileName); + cocos2d::Node* loadNodeWithContent(std::string_view content); void setRecordJsonPath(bool record) { _recordJsonPath = record; } bool isRecordJsonPath() const { return _recordJsonPath; } @@ -105,23 +105,23 @@ class CCS_DLL CSLoader void setJsonPath(std::string jsonPath) { _jsonPath = jsonPath; } std::string getJsonPath() const { return _jsonPath; } - cocos2d::Node* createNodeWithFlatBuffersFile(const std::string& filename); - cocos2d::Node* nodeWithFlatBuffersFile(const std::string& fileName); + cocos2d::Node* createNodeWithFlatBuffersFile(std::string_view filename); + cocos2d::Node* nodeWithFlatBuffersFile(std::string_view fileName); cocos2d::Node* nodeWithFlatBuffers(const flatbuffers::NodeTree* nodetree); - bool bindCallback(const std::string& callbackName, - const std::string& callbackType, + bool bindCallback(std::string_view callbackName, + std::string_view callbackType, cocos2d::ui::Widget* sender, cocos2d::Node* handler); - void registReaderObject(const std::string& className, ObjectFactory::Instance ins); + void registReaderObject(std::string_view className, ObjectFactory::Instance ins); - cocos2d::Node* createNodeWithFlatBuffersForSimulator(const std::string& filename); + cocos2d::Node* createNodeWithFlatBuffersForSimulator(std::string_view filename); cocos2d::Node* nodeWithFlatBuffersForSimulator(const flatbuffers::NodeTree* nodetree); protected: - cocos2d::Node* createNodeWithFlatBuffersFile(const std::string& filename, const ccNodeLoadCallback& callback); - cocos2d::Node* nodeWithFlatBuffersFile(const std::string& fileName, const ccNodeLoadCallback& callback); + cocos2d::Node* createNodeWithFlatBuffersFile(std::string_view filename, const ccNodeLoadCallback& callback); + cocos2d::Node* nodeWithFlatBuffersFile(std::string_view fileName, const ccNodeLoadCallback& callback); cocos2d::Node* nodeWithFlatBuffers(const flatbuffers::NodeTree* nodetree, const ccNodeLoadCallback& callback); cocos2d::Node* loadNode(const rapidjson::Value& json); @@ -144,14 +144,14 @@ class CCS_DLL CSLoader cocos2d::Component* loadComponent(const rapidjson::Value& json); cocos2d::Component* loadComAudio(const rapidjson::Value& json); - bool isWidget(const std::string& type); - bool isCustomWidget(const std::string& type); + bool isWidget(std::string_view type); + bool isCustomWidget(std::string_view type); - std::string getGUIClassName(const std::string& name); - std::string getWidgetReaderClassName(cocos2d::ui::Widget* widget); + std::string_view getGUIClassName(std::string_view name); + std::string_view getWidgetReaderClassName(cocos2d::ui::Widget* widget); inline void reconstructNestNode(cocos2d::Node* node); - static inline std::string getExtentionName(const std::string& name); + static inline std::string_view getExtentionName(std::string_view name); typedef std::function NodeCreateFunc; typedef std::pair Pair; diff --git a/extensions/cocostudio/CCActionNode.cpp b/extensions/cocostudio/CCActionNode.cpp index 88ffc8b5edf1..b514296e3e45 100644 --- a/extensions/cocostudio/CCActionNode.cpp +++ b/extensions/cocostudio/CCActionNode.cpp @@ -188,11 +188,11 @@ void ActionNode::initWithDictionary(const rapidjson::Value& dic, Ref* root) initActionNodeFromRoot(root); } -int ActionNode::valueToInt(const std::string& value) +int ActionNode::valueToInt(std::string_view value) { - return atoi(value.c_str()); + return atoi(value.data()); } -bool ActionNode::valueToBool(const std::string& value) +bool ActionNode::valueToBool(std::string_view value) { int intValue = valueToInt(value); if (1 == intValue) @@ -204,9 +204,9 @@ bool ActionNode::valueToBool(const std::string& value) return false; } } -float ActionNode::valueToFloat(const std::string& value) +float ActionNode::valueToFloat(std::string_view value) { - return utils::atof(value.c_str()); + return utils::atof(value.data()); } void ActionNode::initWithBinary(CocoLoader* cocoLoader, stExpCocoNode* cocoNode, cocos2d::Ref* root) @@ -494,8 +494,9 @@ Spawn* ActionNode::refreshActionProperty() // #11173 Fixed every node of UI animation(json) is starting at frame 0. // if (frame->getFrameIndex() > 0) // { - // DelayTime* cDelayTime = DelayTime::create(frame->getFrameIndex() * - //getUnitTime()); if (cDelayTime != nullptr) + // DelayTime* cDelayTime = + // DelayTime::create(frame->getFrameIndex() + //* getUnitTime()); if (cDelayTime != nullptr) // cSequenceArray.pushBack(static_cast(cDelayTime)); // } } diff --git a/extensions/cocostudio/CCActionNode.h b/extensions/cocostudio/CCActionNode.h index 17c29ba996c0..ec1a6554c788 100644 --- a/extensions/cocostudio/CCActionNode.h +++ b/extensions/cocostudio/CCActionNode.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -162,9 +162,9 @@ class CCS_DLL ActionNode : public cocos2d::Ref virtual bool isActionDoneOnce(); protected: - int valueToInt(const std::string& value); - bool valueToBool(const std::string& value); - float valueToFloat(const std::string& value); + int valueToInt(std::string_view value); + bool valueToBool(std::string_view value); + float valueToFloat(std::string_view value); int _currentFrameIndex; int _destFrameIndex; diff --git a/extensions/cocostudio/CCActionObject.cpp b/extensions/cocostudio/CCActionObject.cpp index badd9c485281..48c85bac150d 100644 --- a/extensions/cocostudio/CCActionObject.cpp +++ b/extensions/cocostudio/CCActionObject.cpp @@ -184,11 +184,11 @@ void ActionObject::initWithBinary(CocoLoader* cocoLoader, stExpCocoNode* cocoNod } } -int ActionObject::valueToInt(const std::string& value) +int ActionObject::valueToInt(std::string_view value) { - return atoi(value.c_str()); + return atoi(value.data()); } -bool ActionObject::valueToBool(const std::string& value) +bool ActionObject::valueToBool(std::string_view value) { int intValue = valueToInt(value); if (1 == intValue) @@ -200,9 +200,9 @@ bool ActionObject::valueToBool(const std::string& value) return false; } } -float ActionObject::valueToFloat(const std::string& value) +float ActionObject::valueToFloat(std::string_view value) { - return utils::atof(value.c_str()); + return utils::atof(value.data()); } void ActionObject::addActionNode(ActionNode* node) diff --git a/extensions/cocostudio/CCActionObject.h b/extensions/cocostudio/CCActionObject.h index 195c741d5b9a..b151631ed454 100644 --- a/extensions/cocostudio/CCActionObject.h +++ b/extensions/cocostudio/CCActionObject.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -171,9 +171,9 @@ class CCS_DLL ActionObject : public cocos2d::Ref void simulationActionUpdate(float dt); protected: - int valueToInt(const std::string& value); - bool valueToBool(const std::string& value); - float valueToFloat(const std::string& value); + int valueToInt(std::string_view value); + bool valueToBool(std::string_view value); + float valueToFloat(std::string_view value); cocos2d::Vector _actionNodeList; std::string _name; diff --git a/extensions/cocostudio/CCArmature.cpp b/extensions/cocostudio/CCArmature.cpp index 985d3aec43f5..ab518eda85f6 100644 --- a/extensions/cocostudio/CCArmature.cpp +++ b/extensions/cocostudio/CCArmature.cpp @@ -57,7 +57,7 @@ Armature* Armature::create() return nullptr; } -Armature* Armature::create(const std::string& name) +Armature* Armature::create(std::string_view name) { Armature* armature = new Armature(); if (armature->init(name)) @@ -69,7 +69,7 @@ Armature* Armature::create(const std::string& name) return nullptr; } -Armature* Armature::create(const std::string& name, Bone* parentBone) +Armature* Armature::create(std::string_view name, Bone* parentBone) { Armature* armature = new Armature(); if (armature->init(name, parentBone)) @@ -102,7 +102,7 @@ bool Armature::init() return init(""); } -bool Armature::init(const std::string& name) +bool Armature::init(std::string_view name) { bool bRet = false; do @@ -182,13 +182,13 @@ bool Armature::init(const std::string& name) return bRet; } -bool Armature::init(const std::string& name, Bone* parentBone) +bool Armature::init(std::string_view name, Bone* parentBone) { _parentBone = parentBone; return init(name); } -Bone* Armature::createBone(const std::string& boneName) +Bone* Armature::createBone(std::string_view boneName) { Bone* existedBone = getBone(boneName); if (existedBone != nullptr) @@ -217,7 +217,7 @@ Bone* Armature::createBone(const std::string& boneName) return bone; } -void Armature::addBone(Bone* bone, const std::string& parentName) +void Armature::addBone(Bone* bone, std::string_view parentName) { CCASSERT(bone != nullptr, "Argument must be non-nil"); CCASSERT(_boneDic.at(bone->getName()) == nullptr, "bone already added. It can't be added again"); @@ -260,12 +260,12 @@ void Armature::removeBone(Bone* bone, bool recursion) removeChild(bone, true); } -Bone* Armature::getBone(const std::string& name) const +Bone* Armature::getBone(std::string_view name) const { return _boneDic.at(name); } -void Armature::changeBoneParent(Bone* bone, const std::string& parentName) +void Armature::changeBoneParent(Bone* bone, std::string_view parentName) { CCASSERT(bone != nullptr, "bone must be added to the bone dictionary!"); @@ -294,7 +294,7 @@ void Armature::changeBoneParent(Bone* bone, const std::string& parentName) } } -const cocos2d::Map& Armature::getBoneDic() const +const cocos2d::StringMap& Armature::getBoneDic() const { return _boneDic; } diff --git a/extensions/cocostudio/CCArmature.h b/extensions/cocostudio/CCArmature.h index d207940d85cb..66866ed2a89d 100644 --- a/extensions/cocostudio/CCArmature.h +++ b/extensions/cocostudio/CCArmature.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -85,9 +85,9 @@ class CCS_DLL Armature : public cocos2d::Node, public cocos2d::BlendProtocol * @param name Armature will use the name to find the ArmatureData to initializes it. * @return A initialized armature which is marked as "autorelease". */ - static Armature* create(const std::string& name); + static Armature* create(std::string_view name); - static Armature* create(const std::string& name, Bone* parentBone); + static Armature* create(std::string_view name, Bone* parentBone); public: /** @@ -109,29 +109,29 @@ class CCS_DLL Armature : public cocos2d::Node, public cocos2d::BlendProtocol * Init an armature with specified name * @param name Armature name */ - virtual bool init(const std::string& name); + virtual bool init(std::string_view name); - virtual bool init(const std::string& name, Bone* parentBone); + virtual bool init(std::string_view name, Bone* parentBone); /** * 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 nullptr, then set Armature to its parent */ - virtual void addBone(Bone* bone, const std::string& parentName); + virtual void addBone(Bone* bone, std::string_view parentName); /** * Get a bone with the specified name * * @param name The bone's name you want to get */ - virtual Bone* getBone(const std::string& name) const; + virtual Bone* getBone(std::string_view name) const; /** * Change a bone's parent with the specified parent name. * * @param bone The bone you want to change parent * @param parentName The new parent's name. */ - virtual void changeBoneParent(Bone* bone, const std::string& parentName); + virtual void changeBoneParent(Bone* bone, std::string_view parentName); /** * Remove a bone with the specified name. If recursion it will also remove child Bone recursionly. * @@ -144,7 +144,7 @@ class CCS_DLL Armature : public cocos2d::Node, public cocos2d::BlendProtocol * Get Armature's bone dictionary * @return Armature's bone dictionary */ - const cocos2d::Map& getBoneDic() const; + const cocos2d::StringMap& getBoneDic() const; /** * This boundingBox will calculate all bones' boundingBox every time @@ -246,7 +246,7 @@ class CCS_DLL Armature : public cocos2d::Node, public cocos2d::BlendProtocol * @js NA * @lua NA */ - Bone* createBone(const std::string& boneName); + Bone* createBone(std::string_view boneName); protected: ArmatureData* _armatureData; @@ -258,7 +258,7 @@ class CCS_DLL Armature : public cocos2d::Node, public cocos2d::BlendProtocol mutable bool _armatureTransformDirty; - cocos2d::Map + cocos2d::StringMap _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. diff --git a/extensions/cocostudio/CCArmatureAnimation.cpp b/extensions/cocostudio/CCArmatureAnimation.cpp index 5f02e393e171..3880ecabb326 100644 --- a/extensions/cocostudio/CCArmatureAnimation.cpp +++ b/extensions/cocostudio/CCArmatureAnimation.cpp @@ -138,7 +138,7 @@ void ArmatureAnimation::setSpeedScale(float speedScale) _processScale = !_movementData ? _speedScale : _speedScale * _movementData->scale; - const Map& map = _armature->getBoneDic(); + auto& map = _armature->getBoneDic(); for (auto& element : map) { Bone* bone = element.second; @@ -156,7 +156,7 @@ float ArmatureAnimation::getSpeedScale() const return _speedScale; } -void ArmatureAnimation::play(const std::string& animationName, int durationTo, int loop) +void ArmatureAnimation::play(std::string_view animationName, int durationTo, int loop) { if (animationName.empty()) { @@ -212,7 +212,7 @@ void ArmatureAnimation::play(const std::string& animationName, int durationTo, i MovementBoneData* movementBoneData = nullptr; _tweenList.clear(); - const Map& map = _armature->getBoneDic(); + auto& map = _armature->getBoneDic(); for (auto& element : map) { Bone* bone = element.second; @@ -469,12 +469,12 @@ void ArmatureAnimation::setFrameEventCallFunc(Ref* target, SEL_FrameEventCallFun } void ArmatureAnimation::setMovementEventCallFunc( - std::function listener) + std::function listener) { _movementEventListener = listener; } void ArmatureAnimation::setFrameEventCallFunc( - std::function + std::function listener) { _frameEventListener = listener; @@ -488,7 +488,7 @@ void ArmatureAnimation::setUserObject(Ref* pUserObject) } void ArmatureAnimation::frameEvent(Bone* bone, - const std::string& frameEventName, + std::string_view frameEventName, int originFrameIndex, int currentFrameIndex) { @@ -504,7 +504,7 @@ void ArmatureAnimation::frameEvent(Bone* bone, } } -void ArmatureAnimation::movementEvent(Armature* armature, MovementEventType movementType, const std::string& movementID) +void ArmatureAnimation::movementEvent(Armature* armature, MovementEventType movementType, std::string_view movementID) { if ((_movementEventTarget && _movementEventCallFunc) || _movementEventListener) { diff --git a/extensions/cocostudio/CCArmatureAnimation.h b/extensions/cocostudio/CCArmatureAnimation.h index 77eb5984a094..16ac00598010 100644 --- a/extensions/cocostudio/CCArmatureAnimation.h +++ b/extensions/cocostudio/CCArmatureAnimation.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -43,8 +43,8 @@ enum MovementEventType class Armature; class Bone; -typedef void (cocos2d::Ref::*SEL_MovementEventCallFunc)(Armature*, MovementEventType, const std::string&); -typedef void (cocos2d::Ref::*SEL_FrameEventCallFunc)(Bone*, const std::string&, int, int); +typedef void (cocos2d::Ref::*SEL_MovementEventCallFunc)(Armature*, MovementEventType, std::string_view); +typedef void (cocos2d::Ref::*SEL_FrameEventCallFunc)(Bone*, std::string_view, int, int); #define movementEvent_selector(_SELECTOR) (cocostudio::SEL_MovementEventCallFunc)(&_SELECTOR) #define frameEvent_selector(_SELECTOR) (cocostudio::SEL_FrameEventCallFunc)(&_SELECTOR) @@ -123,7 +123,7 @@ class CCS_DLL ArmatureAnimation : public ProcessBase * loop = 0 : this animation is not loop * loop > 0 : this animation is loop */ - virtual void play(const std::string& animationName, int durationTo = -1, int loop = -1); + virtual void play(std::string_view animationName, int durationTo = -1, int loop = -1); /** * Play animation by index, the other param is the same to play. @@ -192,10 +192,9 @@ class CCS_DLL ArmatureAnimation : public ProcessBase CC_DEPRECATED_ATTRIBUTE void setFrameEventCallFunc(cocos2d::Ref* target, SEL_FrameEventCallFunc callFunc); void setMovementEventCallFunc( - std::function - listener); + std::function listener); void setFrameEventCallFunc( - std::function + std::function listener); virtual void setAnimationData(AnimationData* data) @@ -257,12 +256,12 @@ class CCS_DLL ArmatureAnimation : public ProcessBase * @js NA * @lua NA */ - void frameEvent(Bone* bone, const std::string& frameEventName, int originFrameIndex, int currentFrameIndex); + void frameEvent(Bone* bone, std::string_view frameEventName, int originFrameIndex, int currentFrameIndex); /** * Emit a movement event */ - void movementEvent(Armature* armature, MovementEventType movementType, const std::string& movementID); + void movementEvent(Armature* armature, MovementEventType movementType, std::string_view movementID); void updateMovementList(); @@ -322,9 +321,9 @@ class CCS_DLL ArmatureAnimation : public ProcessBase cocos2d::Ref* _movementEventTarget; cocos2d::Ref* _frameEventTarget; - std::function + std::function _movementEventListener; - std::function + std::function _frameEventListener; }; diff --git a/extensions/cocostudio/CCArmatureDataManager.cpp b/extensions/cocostudio/CCArmatureDataManager.cpp index 20f716f0e30a..ca323b807ea2 100644 --- a/extensions/cocostudio/CCArmatureDataManager.cpp +++ b/extensions/cocostudio/CCArmatureDataManager.cpp @@ -87,7 +87,7 @@ bool ArmatureDataManager::init() return bRet; } -void ArmatureDataManager::removeArmatureFileInfo(const std::string& configFilePath) +void ArmatureDataManager::removeArmatureFileInfo(std::string_view configFilePath) { if (RelativeData* data = getRelativeData(configFilePath)) { @@ -116,73 +116,71 @@ void ArmatureDataManager::removeArmatureFileInfo(const std::string& configFilePa } } -void ArmatureDataManager::addArmatureData(const std::string& id, +void ArmatureDataManager::addArmatureData(std::string_view id, ArmatureData* armatureData, - const std::string& configFilePath) + std::string_view configFilePath) { if (RelativeData* data = getRelativeData(configFilePath)) { - data->armatures.push_back(id); + data->armatures.push_back(std::string{id}); } _armarureDatas.insert(id, armatureData); } -ArmatureData* ArmatureDataManager::getArmatureData(const std::string& id) +ArmatureData* ArmatureDataManager::getArmatureData(std::string_view id) { return dynamic_cast(_armarureDatas.at(id)); } -void ArmatureDataManager::removeArmatureData(const std::string& id) +void ArmatureDataManager::removeArmatureData(std::string_view id) { _armarureDatas.erase(id); } -void ArmatureDataManager::addAnimationData(const std::string& id, +void ArmatureDataManager::addAnimationData(std::string_view id, AnimationData* animationData, - const std::string& configFilePath) + std::string_view configFilePath) { if (RelativeData* data = getRelativeData(configFilePath)) { - data->animations.push_back(id); + data->animations.push_back(std::string{id}); } _animationDatas.insert(id, animationData); } -AnimationData* ArmatureDataManager::getAnimationData(const std::string& id) +AnimationData* ArmatureDataManager::getAnimationData(std::string_view id) { return dynamic_cast(_animationDatas.at(id)); } -void ArmatureDataManager::removeAnimationData(const std::string& id) +void ArmatureDataManager::removeAnimationData(std::string_view id) { _animationDatas.erase(id); } -void ArmatureDataManager::addTextureData(const std::string& id, - TextureData* textureData, - const std::string& configFilePath) +void ArmatureDataManager::addTextureData(std::string_view id, TextureData* textureData, std::string_view configFilePath) { if (RelativeData* data = getRelativeData(configFilePath)) { - data->textures.push_back(id); + data->textures.push_back(std::string{id}); } _textureDatas.insert(id, textureData); } -TextureData* ArmatureDataManager::getTextureData(const std::string& id) +TextureData* ArmatureDataManager::getTextureData(std::string_view id) { return dynamic_cast(_textureDatas.at(id)); } -void ArmatureDataManager::removeTextureData(const std::string& id) +void ArmatureDataManager::removeTextureData(std::string_view id) { _textureDatas.erase(id); } -void ArmatureDataManager::addArmatureFileInfo(const std::string& configFilePath) +void ArmatureDataManager::addArmatureFileInfo(std::string_view configFilePath) { addRelativeData(configFilePath); @@ -190,9 +188,7 @@ void ArmatureDataManager::addArmatureFileInfo(const std::string& configFilePath) DataReaderHelper::getInstance()->addDataFromFile(configFilePath); } -void ArmatureDataManager::addArmatureFileInfoAsync(const std::string& configFilePath, - Ref* target, - SEL_SCHEDULE selector) +void ArmatureDataManager::addArmatureFileInfoAsync(std::string_view configFilePath, Ref* target, SEL_SCHEDULE selector) { addRelativeData(configFilePath); @@ -200,9 +196,9 @@ void ArmatureDataManager::addArmatureFileInfoAsync(const std::string& configFile DataReaderHelper::getInstance()->addDataFromFileAsync("", "", configFilePath, target, selector); } -void ArmatureDataManager::addArmatureFileInfo(const std::string& imagePath, - const std::string& plistPath, - const std::string& configFilePath) +void ArmatureDataManager::addArmatureFileInfo(std::string_view imagePath, + std::string_view plistPath, + std::string_view configFilePath) { addRelativeData(configFilePath); @@ -211,9 +207,9 @@ void ArmatureDataManager::addArmatureFileInfo(const std::string& imagePath, addSpriteFrameFromFile(plistPath, imagePath, configFilePath); } -void ArmatureDataManager::addArmatureFileInfoAsync(const std::string& imagePath, - const std::string& plistPath, - const std::string& configFilePath, +void ArmatureDataManager::addArmatureFileInfoAsync(std::string_view imagePath, + std::string_view plistPath, + std::string_view configFilePath, Ref* target, SEL_SCHEDULE selector) { @@ -224,13 +220,13 @@ void ArmatureDataManager::addArmatureFileInfoAsync(const std::string& imagePath, addSpriteFrameFromFile(plistPath, imagePath, configFilePath); } -void ArmatureDataManager::addSpriteFrameFromFile(const std::string& plistPath, - const std::string& imagePath, - const std::string& configFilePath) +void ArmatureDataManager::addSpriteFrameFromFile(std::string_view plistPath, + std::string_view imagePath, + std::string_view configFilePath) { if (RelativeData* data = getRelativeData(configFilePath)) { - data->plistFiles.push_back(plistPath); + data->plistFiles.push_back(std::string{plistPath}); } SpriteFrameCacheHelper::getInstance()->addSpriteFrameFromFile(plistPath, imagePath); } @@ -240,20 +236,20 @@ bool ArmatureDataManager::isAutoLoadSpriteFile() return _autoLoadSpriteFile; } -const cocos2d::Map& ArmatureDataManager::getArmatureDatas() const +const cocos2d::StringMap& ArmatureDataManager::getArmatureDatas() const { return _armarureDatas; } -const cocos2d::Map& ArmatureDataManager::getAnimationDatas() const +const cocos2d::StringMap& ArmatureDataManager::getAnimationDatas() const { return _animationDatas; } -const cocos2d::Map& ArmatureDataManager::getTextureDatas() const +const cocos2d::StringMap& ArmatureDataManager::getTextureDatas() const { return _textureDatas; } -void ArmatureDataManager::addRelativeData(const std::string& configFilePath) +void ArmatureDataManager::addRelativeData(std::string_view configFilePath) { if (_relativeDatas.find(configFilePath) == _relativeDatas.end()) { @@ -261,7 +257,7 @@ void ArmatureDataManager::addRelativeData(const std::string& configFilePath) } } -RelativeData* ArmatureDataManager::getRelativeData(const std::string& configFilePath) +RelativeData* ArmatureDataManager::getRelativeData(std::string_view configFilePath) { return &_relativeDatas[configFilePath]; } diff --git a/extensions/cocostudio/CCArmatureDataManager.h b/extensions/cocostudio/CCArmatureDataManager.h index d7e9f5dd9783..6b549e17b1cf 100644 --- a/extensions/cocostudio/CCArmatureDataManager.h +++ b/extensions/cocostudio/CCArmatureDataManager.h @@ -80,112 +80,110 @@ class CCS_DLL ArmatureDataManager : public cocos2d::Ref * @param id The id of the armature data * @param armatureData ArmatureData * */ - void addArmatureData(const std::string& id, ArmatureData* armatureData, const std::string& configFilePath = ""); + void addArmatureData(std::string_view id, ArmatureData* armatureData, std::string_view configFilePath = ""); /** * @brief get armature data * @param id the id of the armature data you want to get * @return ArmatureData * */ - ArmatureData* getArmatureData(const std::string& id); + ArmatureData* getArmatureData(std::string_view id); /** * @brief remove armature data * @param id the id of the armature data you want to get */ - void removeArmatureData(const std::string& id); + void removeArmatureData(std::string_view id); /** * @brief add animation data * @param id the id of the animation data * @return AnimationData * */ - void addAnimationData(const std::string& id, AnimationData* animationData, const std::string& configFilePath = ""); + void addAnimationData(std::string_view id, AnimationData* animationData, std::string_view configFilePath = ""); /** * @brief get animation data from _animationDatas(Dictionary) * @param id the id of the animation data you want to get * @return AnimationData * */ - AnimationData* getAnimationData(const std::string& id); + AnimationData* getAnimationData(std::string_view id); /** * @brief remove animation data * @param id the id of the animation data */ - void removeAnimationData(const std::string& id); + void removeAnimationData(std::string_view id); /** * @brief add texture data * @param id the id of the texture data * @return TextureData * */ - void addTextureData(const std::string& id, TextureData* textureData, const std::string& configFilePath = ""); + void addTextureData(std::string_view id, TextureData* textureData, std::string_view configFilePath = ""); /** * @brief get texture data * @param id the id of the texture data you want to get * @return TextureData * */ - TextureData* getTextureData(const std::string& id); + TextureData* getTextureData(std::string_view id); /** * @brief remove texture data * @param id the id of the texture data you want to get */ - void removeTextureData(const std::string& id); + void removeTextureData(std::string_view id); /** * @brief Add ArmatureFileInfo, it is managed by ArmatureDataManager. */ - void addArmatureFileInfo(const std::string& configFilePath); + void addArmatureFileInfo(std::string_view configFilePath); /** * @brief Add ArmatureFileInfo, it is managed by ArmatureDataManager. * It will load data in a new thread */ - void addArmatureFileInfoAsync(const std::string& configFilePath, + void addArmatureFileInfoAsync(std::string_view configFilePath, cocos2d::Ref* target, cocos2d::SEL_SCHEDULE selector); /** * @brief Add ArmatureFileInfo, it is managed by ArmatureDataManager. */ - void addArmatureFileInfo(const std::string& imagePath, - const std::string& plistPath, - const std::string& configFilePath); + void addArmatureFileInfo(std::string_view imagePath, std::string_view plistPath, std::string_view configFilePath); /** * @brief Add ArmatureFileInfo, it is managed by ArmatureDataManager. * It will load data in a new thread */ - void addArmatureFileInfoAsync(const std::string& imagePath, - const std::string& plistPath, - const std::string& configFilePath, + void addArmatureFileInfoAsync(std::string_view imagePath, + std::string_view plistPath, + std::string_view configFilePath, cocos2d::Ref* target, cocos2d::SEL_SCHEDULE selector); /** * @brief Add sprite frame to CCSpriteFrameCache, it will save display name and it's relative image name */ - void addSpriteFrameFromFile(const std::string& plistPath, - const std::string& imagePath, - const std::string& configFilePath = ""); + void addSpriteFrameFromFile(std::string_view plistPath, + std::string_view imagePath, + std::string_view configFilePath = ""); - virtual void removeArmatureFileInfo(const std::string& configFilePath); + virtual void removeArmatureFileInfo(std::string_view configFilePath); /** * @brief Judge whether or not need auto load sprite file */ bool isAutoLoadSpriteFile(); - const cocos2d::Map& getArmatureDatas() const; - const cocos2d::Map& getAnimationDatas() const; - const cocos2d::Map& getTextureDatas() const; + const cocos2d::StringMap& getArmatureDatas() const; + const cocos2d::StringMap& getAnimationDatas() const; + const cocos2d::StringMap& getTextureDatas() const; public: - void addRelativeData(const std::string& configFilePath); - RelativeData* getRelativeData(const std::string& configFilePath); + void addRelativeData(std::string_view configFilePath); + RelativeData* getRelativeData(std::string_view configFilePath); private: /** @@ -193,25 +191,25 @@ class CCS_DLL ArmatureDataManager : public cocos2d::Ref * @key std::string * @value ArmatureData * */ - cocos2d::Map _armarureDatas; + cocos2d::StringMap _armarureDatas; /** * @brief save animation datas * @key std::string * @value AnimationData * */ - cocos2d::Map _animationDatas; + cocos2d::StringMap _animationDatas; /** * @brief save texture datas * @key std::string * @value TextureData * */ - cocos2d::Map _textureDatas; + cocos2d::StringMap _textureDatas; bool _autoLoadSpriteFile; - std::unordered_map _relativeDatas; + hlookup::string_map _relativeDatas; }; } // namespace cocostudio diff --git a/extensions/cocostudio/CCBatchNode.cpp b/extensions/cocostudio/CCBatchNode.cpp index f7ec04f51914..4344dea84115 100644 --- a/extensions/cocostudio/CCBatchNode.cpp +++ b/extensions/cocostudio/CCBatchNode.cpp @@ -69,7 +69,7 @@ void BatchNode::addChild(Node* child, int zOrder, int tag) } } -void BatchNode::addChild(cocos2d::Node* child, int zOrder, const std::string& name) +void BatchNode::addChild(cocos2d::Node* child, int zOrder, std::string_view name) { Node::addChild(child, zOrder, name); Armature* armature = dynamic_cast(child); diff --git a/extensions/cocostudio/CCBatchNode.h b/extensions/cocostudio/CCBatchNode.h index 88a398345174..7269f6dcbb40 100644 --- a/extensions/cocostudio/CCBatchNode.h +++ b/extensions/cocostudio/CCBatchNode.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -58,7 +58,7 @@ class CCS_DLL BatchNode : public cocos2d::Node virtual bool init() override; using Node::addChild; virtual void addChild(cocos2d::Node* pChild, int zOrder, int tag) override; - virtual void addChild(cocos2d::Node* pChild, int zOrder, const std::string& name) override; + virtual void addChild(cocos2d::Node* pChild, int zOrder, std::string_view name) override; virtual void removeChild(cocos2d::Node* child, bool cleanup) override; virtual void visit(cocos2d::Renderer* renderer, const cocos2d::Mat4& parentTransform, diff --git a/extensions/cocostudio/CCBone.cpp b/extensions/cocostudio/CCBone.cpp index bbe38bb39087..1fe824b92f0a 100644 --- a/extensions/cocostudio/CCBone.cpp +++ b/extensions/cocostudio/CCBone.cpp @@ -47,7 +47,7 @@ Bone* Bone::create() return nullptr; } -Bone* Bone::create(const std::string& name) +Bone* Bone::create(std::string_view name) { Bone* pBone = new Bone(); @@ -95,7 +95,7 @@ bool Bone::init() return Bone::init(nullptr); } -bool Bone::init(const std::string& name) +bool Bone::init(std::string_view name) { bool bRet = false; do @@ -416,7 +416,7 @@ void Bone::changeDisplayByIndex(int index, bool force) changeDisplayWithIndex(index, force); } -void Bone::changeDisplayByName(const std::string& name, bool force) +void Bone::changeDisplayByName(std::string_view name, bool force) { changeDisplayWithName(name, force); } @@ -426,7 +426,7 @@ void Bone::changeDisplayWithIndex(int index, bool force) _displayManager->changeDisplayWithIndex(index, force); } -void Bone::changeDisplayWithName(const std::string& name, bool force) +void Bone::changeDisplayWithName(std::string_view name, bool force) { _displayManager->changeDisplayWithName(name, force); } diff --git a/extensions/cocostudio/CCBone.h b/extensions/cocostudio/CCBone.h index bea21a95dfa5..409a0a381e4b 100644 --- a/extensions/cocostudio/CCBone.h +++ b/extensions/cocostudio/CCBone.h @@ -53,7 +53,7 @@ class CCS_DLL Bone : public cocos2d::Node * @param name If name is not null, then set name to the bone's name * @return A initialized bone which is marked as "autorelease". */ - static Bone* create(const std::string& name); + static Bone* create(std::string_view name); public: /** @@ -75,7 +75,7 @@ class CCS_DLL Bone : public cocos2d::Node * Initializes a Bone with the specified name * @param name Bone's name. */ - virtual bool init(const std::string& name); + virtual bool init(std::string_view name); /** * Add display and use displayData to init the display. @@ -95,10 +95,10 @@ class CCS_DLL Bone : public cocos2d::Node void removeDisplay(int index); CC_DEPRECATED_ATTRIBUTE void changeDisplayByIndex(int index, bool force); - CC_DEPRECATED_ATTRIBUTE void changeDisplayByName(const std::string& name, bool force); + CC_DEPRECATED_ATTRIBUTE void changeDisplayByName(std::string_view name, bool force); void changeDisplayWithIndex(int index, bool force); - void changeDisplayWithName(const std::string& name, bool force); + void changeDisplayWithName(std::string_view name, bool force); /** * Add a child to this bone, and it will let this child call setParent(Bone *parent) function to set self to it's diff --git a/extensions/cocostudio/CCComAttribute.cpp b/extensions/cocostudio/CCComAttribute.cpp index 57cf1b07672d..f8c5381915d5 100644 --- a/extensions/cocostudio/CCComAttribute.cpp +++ b/extensions/cocostudio/CCComAttribute.cpp @@ -49,27 +49,27 @@ bool ComAttribute::init() return true; } -void ComAttribute::setInt(const std::string& key, int value) +void ComAttribute::setInt(std::string_view key, int value) { _dict[key] = cocos2d::Value(value); } -void ComAttribute::setFloat(const std::string& key, float value) +void ComAttribute::setFloat(std::string_view key, float value) { _dict[key] = cocos2d::Value(value); } -void ComAttribute::setBool(const std::string& key, bool value) +void ComAttribute::setBool(std::string_view key, bool value) { _dict[key] = cocos2d::Value(value); } -void ComAttribute::setString(const std::string& key, const std::string& value) +void ComAttribute::setString(std::string_view key, std::string_view value) { _dict[key] = cocos2d::Value(value); } -int ComAttribute::getInt(const std::string& key, int def) const +int ComAttribute::getInt(std::string_view key, int def) const { if (_dict.find(key) != _dict.end()) { @@ -77,15 +77,15 @@ int ComAttribute::getInt(const std::string& key, int def) const return v.asInt(); } - if (!DICTOOL->checkObjectExist_json(_doc, key.c_str())) + if (!DICTOOL->checkObjectExist_json(_doc, key.data())) { return def; } - return DICTOOL->getIntValue_json(_doc, key.c_str()); + return DICTOOL->getIntValue_json(_doc, key.data()); } -float ComAttribute::getFloat(const std::string& key, float def) const +float ComAttribute::getFloat(std::string_view key, float def) const { if (_dict.find(key) != _dict.end()) { @@ -93,14 +93,14 @@ float ComAttribute::getFloat(const std::string& key, float def) const return v.asFloat(); } - if (!DICTOOL->checkObjectExist_json(_doc, key.c_str())) + if (!DICTOOL->checkObjectExist_json(_doc, key.data())) { return def; } - return DICTOOL->getFloatValue_json(_doc, key.c_str()); + return DICTOOL->getFloatValue_json(_doc, key.data()); } -bool ComAttribute::getBool(const std::string& key, bool def) const +bool ComAttribute::getBool(std::string_view key, bool def) const { if (_dict.find(key) != _dict.end()) { @@ -108,15 +108,15 @@ bool ComAttribute::getBool(const std::string& key, bool def) const return v.asBool(); } - if (!DICTOOL->checkObjectExist_json(_doc, key.c_str())) + if (!DICTOOL->checkObjectExist_json(_doc, key.data())) { return def; } - return DICTOOL->getBooleanValue_json(_doc, key.c_str()); + return DICTOOL->getBooleanValue_json(_doc, key.data()); } -std::string ComAttribute::getString(const std::string& key, const std::string& def) const +std::string ComAttribute::getString(std::string_view key, std::string_view def) const { if (_dict.find(key) != _dict.end()) { @@ -124,12 +124,12 @@ std::string ComAttribute::getString(const std::string& key, const std::string& d return v.asString(); } - if (!DICTOOL->checkObjectExist_json(_doc, key.c_str())) + if (!DICTOOL->checkObjectExist_json(_doc, key.data())) { - return def; + return std::string{def}; } - return DICTOOL->getStringValue_json(_doc, key.c_str()); + return DICTOOL->getStringValue_json(_doc, key.data()); } ComAttribute* ComAttribute::create() @@ -206,7 +206,7 @@ bool ComAttribute::serialize(void* r) return ret; } -bool ComAttribute::parse(const std::string& jsonFile) +bool ComAttribute::parse(std::string_view jsonFile) { bool ret = false; do diff --git a/extensions/cocostudio/CCComAttribute.h b/extensions/cocostudio/CCComAttribute.h index 1a47ff8d055c..df368b8c462e 100644 --- a/extensions/cocostudio/CCComAttribute.h +++ b/extensions/cocostudio/CCComAttribute.h @@ -54,15 +54,15 @@ class CCS_DLL ComAttribute : public cocos2d::Component virtual bool init() override; virtual bool serialize(void* r) override; - void setInt(const std::string& key, int value); - void setFloat(const std::string& key, float value); - void setBool(const std::string& key, bool value); - void setString(const std::string& key, const std::string& value); - int getInt(const std::string& key, int def = 0) const; - float getFloat(const std::string& key, float def = 0.0f) const; - bool getBool(const std::string& key, bool def = false) const; - std::string getString(const std::string& key, const std::string& def = "") const; - bool parse(const std::string& jsonFile); + void setInt(std::string_view key, int value); + void setFloat(std::string_view key, float value); + void setBool(std::string_view key, bool value); + void setString(std::string_view key, std::string_view value); + int getInt(std::string_view key, int def = 0) const; + float getFloat(std::string_view key, float def = 0.0f) const; + bool getBool(std::string_view key, bool def = false) const; + std::string getString(std::string_view key, std::string_view def = "") const; + bool parse(std::string_view jsonFile); private: cocos2d::ValueMap _dict; diff --git a/extensions/cocostudio/CCComExtensionData.h b/extensions/cocostudio/CCComExtensionData.h index 0c5dcb7de01a..973549150616 100644 --- a/extensions/cocostudio/CCComExtensionData.h +++ b/extensions/cocostudio/CCComExtensionData.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2015 cocos2d-x.org http://www.cocos2d-x.org @@ -69,7 +69,7 @@ class CCS_DLL ComExtensionData : public cocos2d::Component static ComExtensionData* create(); virtual bool init() override; - virtual void setCustomProperty(const std::string& customProperty) { _customProperty = customProperty; } + virtual void setCustomProperty(std::string_view customProperty) { _customProperty = customProperty; } virtual std::string getCustomProperty() const { return _customProperty; }; virtual void setActionTag(int actionTag); diff --git a/extensions/cocostudio/CCComRender.cpp b/extensions/cocostudio/CCComRender.cpp index ad2262cf8de2..74cf487a8b24 100644 --- a/extensions/cocostudio/CCComRender.cpp +++ b/extensions/cocostudio/CCComRender.cpp @@ -383,7 +383,7 @@ ComRender* ComRender::create(cocos2d::Node* node, const char* comName) return ret; } -bool ComRender::readJson(const std::string& fileName, rapidjson::Document& doc) +bool ComRender::readJson(std::string_view fileName, rapidjson::Document& doc) { bool ret = false; do diff --git a/extensions/cocostudio/CCComRender.h b/extensions/cocostudio/CCComRender.h index 83bc28e58f8a..de0aaeebb17c 100644 --- a/extensions/cocostudio/CCComRender.h +++ b/extensions/cocostudio/CCComRender.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -79,7 +79,7 @@ class CCS_DLL ComRender : public cocos2d::Component virtual ~ComRender(); private: - bool readJson(const std::string& fileName, rapidjson::Document& doc); + bool readJson(std::string_view fileName, rapidjson::Document& doc); cocos2d::Node* _render; }; diff --git a/extensions/cocostudio/CCDataReaderHelper.cpp b/extensions/cocostudio/CCDataReaderHelper.cpp index 7cd5acea543d..59d2c7d51d29 100644 --- a/extensions/cocostudio/CCDataReaderHelper.cpp +++ b/extensions/cocostudio/CCDataReaderHelper.cpp @@ -133,7 +133,7 @@ static const char* COLOR_INFO = "color"; static const char* CONFIG_FILE_PATH = "config_file_path"; static const char* CONTENT_SCALE = "content_scale"; -static std::string readFileContent(const std::string& filename, bool binary) +static std::string readFileContent(std::string_view filename, bool binary) { auto fs = FileUtils::getInstance(); std::string s; @@ -264,7 +264,7 @@ DataReaderHelper::~DataReaderHelper() _dataReaderHelper = nullptr; } -void DataReaderHelper::addDataFromFile(const std::string& filePath) +void DataReaderHelper::addDataFromFile(std::string_view filePath) { /* * Check if file is already added to ArmatureDataManager, if then return. @@ -276,19 +276,15 @@ void DataReaderHelper::addDataFromFile(const std::string& filePath) return; } } - _configFileList.push_back(filePath); + _configFileList.push_back(std::string{filePath}); //! find the base file path - std::string basefilePath = filePath; - size_t pos = basefilePath.find_last_of('/'); + std::string basefilePath; + size_t pos = filePath.find_last_of('/'); if (pos != std::string::npos) { - basefilePath = basefilePath.substr(0, pos + 1); - } - else - { - basefilePath = ""; + basefilePath = filePath.substr(0, pos + 1); } std::string fileExtension = cocos2d::FileUtils::getInstance()->getFileExtension(filePath); @@ -319,9 +315,9 @@ void DataReaderHelper::addDataFromFile(const std::string& filePath) } } -void DataReaderHelper::addDataFromFileAsync(const std::string& imagePath, - const std::string& plistPath, - const std::string& filePath, +void DataReaderHelper::addDataFromFileAsync(std::string_view imagePath, + std::string_view plistPath, + std::string_view filePath, Ref* target, SEL_SCHEDULE selector) { @@ -346,19 +342,15 @@ void DataReaderHelper::addDataFromFileAsync(const std::string& imagePath, return; } } - _configFileList.push_back(filePath); + _configFileList.push_back(std::string{filePath}); //! find the base file path - std::string basefilePath = filePath; - size_t pos = basefilePath.find_last_of('/'); + std::string basefilePath; + size_t pos = filePath.find_last_of('/'); if (pos != std::string::npos) { - basefilePath = basefilePath.substr(0, pos + 1); - } - else - { - basefilePath = ""; + basefilePath = filePath.substr(0, pos + 1); } // lazy init @@ -490,7 +482,7 @@ void DataReaderHelper::addDataAsyncCallBack(float /*dt*/) } } -void DataReaderHelper::removeConfigFile(const std::string& configFile) +void DataReaderHelper::removeConfigFile(std::string_view configFile) { auto it_end = _configFileList.end(); for (auto it = _configFileList.begin(); it != it_end; ++it) @@ -503,10 +495,12 @@ void DataReaderHelper::removeConfigFile(const std::string& configFile) } } -void DataReaderHelper::addDataFromCache(const std::string& pFileContent, DataInfo* dataInfo) +void DataReaderHelper::addDataFromCache(std::string_view pFileContent, DataInfo* dataInfo) { pugi::xml_document document; - document.load_string(pFileContent.c_str()); + pugi::xml_parse_result ret = document.load_buffer(pFileContent.data(), pFileContent.length()); + if (!ret) + return; auto root = document.document_element(); dataInfo->flashToolVersion = root.attribute(VERSION).as_float(); @@ -1116,15 +1110,15 @@ ContourData* DataReaderHelper::decodeContour(pugi::xml_node& contourXML, DataInf return contourData; } -void DataReaderHelper::addDataFromJsonCache(const std::string& fileContent, DataInfo* dataInfo) +void DataReaderHelper::addDataFromJsonCache(std::string_view fileContent, DataInfo* dataInfo) { rapidjson::Document json; - rapidjson::StringStream stream(fileContent.c_str()); + rapidjson::StringStream stream(fileContent.data()); if (fileContent.size() >= 3) { // Skip BOM if exists - const unsigned char* c = (const unsigned char*)fileContent.c_str(); + const unsigned char* c = (const unsigned char*)fileContent.data(); unsigned bom = c[0] | (c[1] << 8) | (c[2] << 16); if (bom == 0xBFBBEF) // UTF8 BOM diff --git a/extensions/cocostudio/CCDataReaderHelper.h b/extensions/cocostudio/CCDataReaderHelper.h index aa511c27aba6..b3437f7cb6b7 100644 --- a/extensions/cocostudio/CCDataReaderHelper.h +++ b/extensions/cocostudio/CCDataReaderHelper.h @@ -114,16 +114,16 @@ class CCS_DLL DataReaderHelper : cocos2d::Ref */ ~DataReaderHelper(); - void addDataFromFile(const std::string& filePath); - void addDataFromFileAsync(const std::string& imagePath, - const std::string& plistPath, - const std::string& filePath, + void addDataFromFile(std::string_view filePath); + void addDataFromFileAsync(std::string_view imagePath, + std::string_view plistPath, + std::string_view filePath, cocos2d::Ref* target, cocos2d::SEL_SCHEDULE selector); void addDataAsyncCallBack(float dt); - void removeConfigFile(const std::string& configFile); + void removeConfigFile(std::string_view configFile); public: /** @@ -132,7 +132,7 @@ class CCS_DLL DataReaderHelper : cocos2d::Ref * * @param xmlPath The cache of the xml */ - static void addDataFromCache(const std::string& pFileContent, DataInfo* dataInfo = nullptr); + static void addDataFromCache(std::string_view pFileContent, DataInfo* dataInfo = nullptr); /** * Decode Armature Datas from xml export from Dragon Bone flash tool @@ -166,7 +166,7 @@ class CCS_DLL DataReaderHelper : cocos2d::Ref static ContourData* decodeContour(pugi::xml_node& contourXML, DataInfo* dataInfo); public: - static void addDataFromJsonCache(const std::string& fileContent, DataInfo* dataInfo = nullptr); + static void addDataFromJsonCache(std::string_view fileContent, DataInfo* dataInfo = nullptr); static ArmatureData* decodeArmature(const rapidjson::Value& json, DataInfo* dataInfo); static BoneData* decodeBone(const rapidjson::Value& json, DataInfo* dataInfo); diff --git a/extensions/cocostudio/CCDatas.cpp b/extensions/cocostudio/CCDatas.cpp index ff8d44569d0a..ef45d8bd45ff 100644 --- a/extensions/cocostudio/CCDatas.cpp +++ b/extensions/cocostudio/CCDatas.cpp @@ -136,16 +136,18 @@ Color4B BaseData::getColor() return Color4B(r, g, b, a); } -std::string DisplayData::changeDisplayToTexture(const std::string& displayName) +std::string DisplayData::changeDisplayToTexture(std::string_view displayName) { // remove .xxx - std::string textureName = displayName; - size_t startPos = textureName.find_last_of("."); + std::string textureName; + size_t startPos = displayName.find_last_of("."); if (startPos != std::string::npos) { - textureName = textureName.erase(startPos); + textureName.assign(displayName.data(), startPos); // textureName = textureName.erase(startPos); } + else + textureName = displayName; return textureName; } @@ -216,7 +218,7 @@ void ArmatureData::addBoneData(BoneData* boneData) boneDataDic.insert(boneData->name, boneData); } -BoneData* ArmatureData::getBoneData(const std::string& boneName) +BoneData* ArmatureData::getBoneData(std::string_view boneName) { return static_cast(boneDataDic.at(boneName)); } @@ -305,7 +307,7 @@ void MovementData::addMovementBoneData(MovementBoneData* movBoneData) movBoneDataDic.insert(movBoneData->name, movBoneData); } -MovementBoneData* MovementData::getMovementBoneData(const std::string& boneName) +MovementBoneData* MovementData::getMovementBoneData(std::string_view boneName) { return movBoneDataDic.at(boneName); } @@ -320,7 +322,7 @@ void AnimationData::addMovement(MovementData* movData) movementNames.push_back(movData->name); } -MovementData* AnimationData::getMovement(const std::string& movementName) +MovementData* AnimationData::getMovement(std::string_view movementName) { return movementDataDic.at(movementName); } diff --git a/extensions/cocostudio/CCDatas.h b/extensions/cocostudio/CCDatas.h index 08985516ec6f..dc2d76752648 100644 --- a/extensions/cocostudio/CCDatas.h +++ b/extensions/cocostudio/CCDatas.h @@ -140,7 +140,7 @@ class CCS_DLL DisplayData : public cocos2d::Ref public: CC_CREATE_NO_PARAM_NO_INIT(DisplayData) - static std::string changeDisplayToTexture(const std::string& displayName); + static std::string changeDisplayToTexture(std::string_view displayName); public: /** @@ -282,11 +282,11 @@ class CCS_DLL ArmatureData : public cocos2d::Ref bool init(); void addBoneData(BoneData* boneData); - BoneData* getBoneData(const std::string& boneName); + BoneData* getBoneData(std::string_view boneName); public: std::string name; - cocos2d::Map boneDataDic; + cocos2d::StringMap boneDataDic; float dataVersion; }; @@ -409,7 +409,7 @@ class CCS_DLL MovementData : public cocos2d::Ref ~MovementData(void); void addMovementBoneData(MovementBoneData* movBoneData); - MovementBoneData* getMovementBoneData(const std::string& boneName); + MovementBoneData* getMovementBoneData(std::string_view boneName); public: std::string name; @@ -443,10 +443,10 @@ class CCS_DLL MovementData : public cocos2d::Ref /** * @brief save movement bone data - * @key const std::string& + * @key std::string_view * @value MovementBoneData * */ - cocos2d::Map movBoneDataDic; + cocos2d::StringMap movBoneDataDic; }; /** @@ -472,12 +472,12 @@ class CCS_DLL AnimationData : public cocos2d::Ref ~AnimationData(void); void addMovement(MovementData* movData); - MovementData* getMovement(const std::string& movementName); + MovementData* getMovement(std::string_view movementName); ssize_t getMovementCount(); public: std::string name; - cocos2d::Map movementDataDic; + cocos2d::StringMap movementDataDic; std::vector movementNames; }; diff --git a/extensions/cocostudio/CCDisplayManager.cpp b/extensions/cocostudio/CCDisplayManager.cpp index f5a4377d0482..b6d07cc6fa0b 100644 --- a/extensions/cocostudio/CCDisplayManager.cpp +++ b/extensions/cocostudio/CCDisplayManager.cpp @@ -129,7 +129,7 @@ void DisplayManager::addDisplay(Node* display, int index) skin->setBone(_bone); displayData = SpriteDisplayData::create(); - DisplayFactory::initSpriteDisplay(_bone, decoDisplay, skin->getDisplayName().c_str(), skin); + DisplayFactory::initSpriteDisplay(_bone, decoDisplay, skin->getDisplayName().data(), skin); if (SpriteDisplayData* spriteDisplayData = (SpriteDisplayData*)decoDisplay->getDisplayData()) { @@ -239,7 +239,7 @@ void DisplayManager::changeDisplayWithIndex(int index, bool force) setCurrentDecorativeDisplay(decoDisplay); } -void DisplayManager::changeDisplayWithName(const std::string& name, bool force) +void DisplayManager::changeDisplayWithName(std::string_view name, bool force) { for (int i = 0; i < _decoDisplayList.size(); i++) { diff --git a/extensions/cocostudio/CCDisplayManager.h b/extensions/cocostudio/CCDisplayManager.h index 1e32d8f7a788..f43fb13e56ee 100644 --- a/extensions/cocostudio/CCDisplayManager.h +++ b/extensions/cocostudio/CCDisplayManager.h @@ -80,7 +80,7 @@ class CCS_DLL DisplayManager : public cocos2d::Ref * @deprecated, please use changeDisplayWithIndex and changeDisplayWithName */ CC_DEPRECATED_ATTRIBUTE void changeDisplayByIndex(int index, bool force); - CC_DEPRECATED_ATTRIBUTE void changeDisplayByName(const std::string& name, bool force); + CC_DEPRECATED_ATTRIBUTE void changeDisplayByName(std::string_view name, bool force); /** * Change display by index. You can just use this method to change display in the display list. @@ -93,7 +93,7 @@ class CCS_DLL DisplayManager : public cocos2d::Ref * index edit in the flash every key frame. */ void changeDisplayWithIndex(int index, bool force); - void changeDisplayWithName(const std::string& name, bool force); + void changeDisplayWithName(std::string_view name, bool force); cocos2d::Node* getDisplayRenderNode() const; DisplayType getDisplayRenderNodeType() const; diff --git a/extensions/cocostudio/CCSGUIReader.cpp b/extensions/cocostudio/CCSGUIReader.cpp index 0855bb102a0a..1edeaea0080f 100644 --- a/extensions/cocostudio/CCSGUIReader.cpp +++ b/extensions/cocostudio/CCSGUIReader.cpp @@ -160,7 +160,7 @@ cocos2d::Size GUIReader::getFileDesignSize(const char* fileName) const return Size(w, h); } -void GUIReader::registerTypeAndCallBack(const std::string& classType, +void GUIReader::registerTypeAndCallBack(std::string_view classType, ObjectFactory::Instance ins, Ref* object, SEL_ParseEvent callBack) @@ -181,7 +181,7 @@ void GUIReader::registerTypeAndCallBack(const std::string& classType, } } -void GUIReader::registerTypeAndCallBack(const std::string& classType, +void GUIReader::registerTypeAndCallBack(std::string_view classType, ObjectFactory::InstanceFunc ins, Ref* object, SEL_ParseEvent callBack) @@ -309,9 +309,9 @@ std::string WidgetPropertiesReader::getWidgetReaderClassName(Widget* widget) return readerName; } -std::string WidgetPropertiesReader::getGUIClassName(const std::string& name) +std::string WidgetPropertiesReader::getGUIClassName(std::string_view name) { - std::string convertedClassName = name; + std::string convertedClassName; if (name == "Panel") { convertedClassName = "Layout"; @@ -336,11 +336,13 @@ std::string WidgetPropertiesReader::getGUIClassName(const std::string& name) { convertedClassName = "TextBMFont"; } + else + convertedClassName = name; return convertedClassName; } -cocos2d::ui::Widget* WidgetPropertiesReader::createGUI(const std::string& classname) +cocos2d::ui::Widget* WidgetPropertiesReader::createGUI(std::string_view classname) { std::string name = this->getGUIClassName(classname); @@ -349,7 +351,7 @@ cocos2d::ui::Widget* WidgetPropertiesReader::createGUI(const std::string& classn return dynamic_cast(object); } -WidgetReaderProtocol* WidgetPropertiesReader::createWidgetReaderProtocol(const std::string& classname) +WidgetReaderProtocol* WidgetPropertiesReader::createWidgetReaderProtocol(std::string_view classname) { Ref* object = ObjectFactory::getInstance()->createObject(classname); @@ -426,10 +428,10 @@ Widget* GUIReader::widgetFromBinaryFile(const char* fileName) return widget; } -std::string WidgetPropertiesReader::getWidgetReaderClassName(const std::string& classname) +std::string WidgetPropertiesReader::getWidgetReaderClassName(std::string_view classname) { // create widget reader to parse properties of widget - std::string readerName = classname; + std::string readerName; if (readerName == "Panel") { readerName = "Layout"; @@ -454,6 +456,8 @@ std::string WidgetPropertiesReader::getWidgetReaderClassName(const std::string& { readerName = "TextBMFont"; } + else + readerName = classname; readerName.append("Reader"); return readerName; } @@ -1240,7 +1244,7 @@ void WidgetPropertiesReader0250::setPropsForAllWidgetFromJsonDictionary(WidgetRe const rapidjson::Value& /*options*/) {} -void WidgetPropertiesReader0250::setPropsForAllCustomWidgetFromJsonDictionary(const std::string& /*classType*/, +void WidgetPropertiesReader0250::setPropsForAllCustomWidgetFromJsonDictionary(std::string_view /*classType*/, cocos2d::ui::Widget* /*widget*/, const rapidjson::Value& /*customOptions*/) {} @@ -1542,7 +1546,7 @@ void WidgetPropertiesReader0300::setPropsForAllWidgetFromBinary(WidgetReaderProt reader->setPropsFromBinary(widget, cocoLoader, cocoNode); } -void WidgetPropertiesReader0300::setPropsForAllCustomWidgetFromBinary(const std::string& /*classType*/, +void WidgetPropertiesReader0300::setPropsForAllCustomWidgetFromBinary(std::string_view /*classType*/, cocos2d::ui::Widget* /*widget*/, CocoLoader* /*cocoLoader*/, stExpCocoNode* /*pCocoNode*/) @@ -1637,17 +1641,17 @@ void WidgetPropertiesReader0300::setPropsForAllWidgetFromJsonDictionary(WidgetRe reader->setPropsFromJsonDictionary(widget, options); } -void WidgetPropertiesReader0300::setPropsForAllCustomWidgetFromJsonDictionary(const std::string& classType, +void WidgetPropertiesReader0300::setPropsForAllCustomWidgetFromJsonDictionary(std::string_view classType, cocos2d::ui::Widget* widget, const rapidjson::Value& customOptions) { GUIReader* guiReader = GUIReader::getInstance(); - std::map* object_map = guiReader->getParseObjectMap(); - Ref* object = (*object_map)[classType]; + hlookup::string_map* object_map = guiReader->getParseObjectMap(); + Ref* object = (*object_map)[classType]; - std::map* selector_map = guiReader->getParseCallBackMap(); - SEL_ParseEvent selector = (*selector_map)[classType]; + hlookup::string_map* selector_map = guiReader->getParseCallBackMap(); + SEL_ParseEvent selector = (*selector_map)[classType]; if (object && selector) { diff --git a/extensions/cocostudio/CCSGUIReader.h b/extensions/cocostudio/CCSGUIReader.h index 5c277866ccb7..efec53063425 100644 --- a/extensions/cocostudio/CCSGUIReader.h +++ b/extensions/cocostudio/CCSGUIReader.h @@ -50,7 +50,7 @@ struct stExpCocoNode; #define kCCSVersion 1.0 -typedef void (cocos2d::Ref::*SEL_ParseEvent)(const std::string&, cocos2d::Ref*, const rapidjson::Value&); +typedef void (cocos2d::Ref::*SEL_ParseEvent)(std::string_view, cocos2d::Ref*, const rapidjson::Value&); #define parseselector(_SELECTOR) (SEL_ParseEvent)(&_SELECTOR) class CCS_DLL GUIReader : public cocos2d::Ref @@ -76,15 +76,15 @@ class CCS_DLL GUIReader : public cocos2d::Ref */ cocos2d::Size getFileDesignSize(const char* fileName) const; - void setFilePath(const std::string& strFilePath) { m_strFilePath = strFilePath; } - const std::string& getFilePath() const { return m_strFilePath; } + void setFilePath(std::string_view strFilePath) { m_strFilePath = strFilePath; } + std::string_view getFilePath() const { return m_strFilePath; } - void registerTypeAndCallBack(const std::string& classType, + void registerTypeAndCallBack(std::string_view classType, cocos2d::ObjectFactory::Instance ins, Ref* object, SEL_ParseEvent callBack); - void registerTypeAndCallBack(const std::string& classType, + void registerTypeAndCallBack(std::string_view classType, cocos2d::ObjectFactory::InstanceFunc ins, Ref* object, SEL_ParseEvent callBack); @@ -96,9 +96,9 @@ class CCS_DLL GUIReader : public cocos2d::Ref std::string m_strFilePath; cocos2d::ValueMap _fileDesignSizes; - typedef std::map ParseCallBackMap; + typedef hlookup::string_map ParseCallBackMap; ParseCallBackMap _mapParseSelector; - typedef std::map ParseObjectMap; + typedef hlookup::string_map ParseObjectMap; ParseObjectMap _mapObject; public: @@ -118,7 +118,7 @@ class CCS_DLL WidgetPropertiesReader : public cocos2d::Ref cocos2d::ui::Widget* widget, const rapidjson::Value& options) = 0; - virtual void setPropsForAllCustomWidgetFromJsonDictionary(const std::string& classType, + virtual void setPropsForAllCustomWidgetFromJsonDictionary(std::string_view classType, cocos2d::ui::Widget* widget, const rapidjson::Value& customOptions) = 0; @@ -134,12 +134,12 @@ class CCS_DLL WidgetPropertiesReader : public cocos2d::Ref protected: void setAnchorPointForWidget(cocos2d::ui::Widget* widget, const rapidjson::Value& options); - std::string getWidgetReaderClassName(const std::string& classname); + std::string getWidgetReaderClassName(std::string_view classname); std::string getWidgetReaderClassName(cocos2d::ui::Widget* widget); - std::string getGUIClassName(const std::string& name); - cocos2d::ui::Widget* createGUI(const std::string& classname); - WidgetReaderProtocol* createWidgetReaderProtocol(const std::string& classname); + std::string getGUIClassName(std::string_view name); + cocos2d::ui::Widget* createGUI(std::string_view classname); + WidgetReaderProtocol* createWidgetReaderProtocol(std::string_view classname); protected: std::string m_strFilePath; @@ -189,7 +189,7 @@ class CCS_DLL WidgetPropertiesReader0250 : public WidgetPropertiesReader virtual void setPropsForAllWidgetFromJsonDictionary(WidgetReaderProtocol* reader, cocos2d::ui::Widget* widget, const rapidjson::Value& options) override; - virtual void setPropsForAllCustomWidgetFromJsonDictionary(const std::string& classType, + virtual void setPropsForAllCustomWidgetFromJsonDictionary(std::string_view classType, cocos2d::ui::Widget* widget, const rapidjson::Value& customOptions) override; }; @@ -217,7 +217,7 @@ class CCS_DLL WidgetPropertiesReader0300 : public WidgetPropertiesReader CocoLoader* cocoLoader, stExpCocoNode* pCocoNode) override; - virtual void setPropsForAllCustomWidgetFromBinary(const std::string& classType, + virtual void setPropsForAllCustomWidgetFromBinary(std::string_view classType, cocos2d::ui::Widget* widget, CocoLoader* cocoLoader, stExpCocoNode* pCocoNode); @@ -228,7 +228,7 @@ class CCS_DLL WidgetPropertiesReader0300 : public WidgetPropertiesReader cocos2d::ui::Widget* widget, const rapidjson::Value& options) override; - virtual void setPropsForAllCustomWidgetFromJsonDictionary(const std::string& classType, + virtual void setPropsForAllCustomWidgetFromJsonDictionary(std::string_view classType, cocos2d::ui::Widget* widget, const rapidjson::Value& customOptions) override; }; diff --git a/extensions/cocostudio/CCSSceneReader.cpp b/extensions/cocostudio/CCSSceneReader.cpp index 477341309d48..c93c80f393ee 100644 --- a/extensions/cocostudio/CCSSceneReader.cpp +++ b/extensions/cocostudio/CCSSceneReader.cpp @@ -54,7 +54,7 @@ const char* SceneReader::sceneReaderVersion() } cocos2d::Node* SceneReader::createNodeWithSceneFile( - const std::string& fileName, + std::string_view fileName, AttachComponentType attachComponent /*= AttachComponentType::EMPTY_NODE*/) { std::string fileExtension = cocos2d::FileUtils::getInstance()->getFileExtension(fileName); @@ -161,12 +161,12 @@ cocos2d::Node* SceneReader::createNodeWithSceneFile( } else { - log("read file [%s] error!\n", fileName.c_str()); + log("read file [%s] error!\n", fileName.data()); } return nullptr; } -bool SceneReader::readJson(const std::string& fileName, rapidjson::Document& doc) +bool SceneReader::readJson(std::string_view fileName, rapidjson::Document& doc) { bool ret = false; do @@ -210,14 +210,14 @@ Node* SceneReader::nodeByTag(Node* parent, int tag) return _retNode; } -cocos2d::Component* SceneReader::createComponent(const std::string& classname) +cocos2d::Component* SceneReader::createComponent(std::string_view classname) { std::string name = this->getComponentClassName(classname); Ref* object = ObjectFactory::getInstance()->createObject(name); return dynamic_cast(object); } -std::string SceneReader::getComponentClassName(const std::string& name) +std::string SceneReader::getComponentClassName(std::string_view name) { std::string comName; if (name == "CCSprite" || name == "CCTMXTiledMap" || name == "CCParticleSystemQuad" || name == "CCArmature" || diff --git a/extensions/cocostudio/CCSSceneReader.h b/extensions/cocostudio/CCSSceneReader.h index 90163ac7e5b1..4cb2e599b217 100644 --- a/extensions/cocostudio/CCSSceneReader.h +++ b/extensions/cocostudio/CCSSceneReader.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. Copyright (c) 2021 Bytedance Inc. @@ -61,7 +61,7 @@ class CCS_DLL SceneReader */ static void destroyInstance(); static const char* sceneReaderVersion(); - cocos2d::Node* createNodeWithSceneFile(const std::string& fileName, + cocos2d::Node* createNodeWithSceneFile(std::string_view fileName, AttachComponentType attachComponent = AttachComponentType::EMPTY_NODE); void setTarget(const std::function& selector); cocos2d::Node* getNodeByTag(int nTag); @@ -70,15 +70,15 @@ class CCS_DLL SceneReader virtual ~SceneReader(); private: - std::string getComponentClassName(const std::string& name); + std::string getComponentClassName(std::string_view name); - cocos2d::Component* createComponent(const std::string& classname); + cocos2d::Component* createComponent(std::string_view classname); cocos2d::Node* createObject(const rapidjson::Value& dict, cocos2d::Node* parent, AttachComponentType attachComponent); void setPropertyFromJsonDict(const rapidjson::Value& dict, cocos2d::Node* node); - bool readJson(const std::string& fileName, rapidjson::Document& doc); + bool readJson(std::string_view fileName, rapidjson::Document& doc); cocos2d::Node* createObject(CocoLoader* cocoLoader, stExpCocoNode* cocoNode, diff --git a/extensions/cocostudio/CCSkin.cpp b/extensions/cocostudio/CCSkin.cpp index 253354a23517..a532988362fc 100644 --- a/extensions/cocostudio/CCSkin.cpp +++ b/extensions/cocostudio/CCSkin.cpp @@ -55,7 +55,7 @@ Skin* Skin::create() return nullptr; } -Skin* Skin::createWithSpriteFrameName(const std::string& pszSpriteFrameName) +Skin* Skin::createWithSpriteFrameName(std::string_view pszSpriteFrameName) { Skin* skin = new Skin(); if (skin->initWithSpriteFrameName(pszSpriteFrameName)) @@ -67,7 +67,7 @@ Skin* Skin::createWithSpriteFrameName(const std::string& pszSpriteFrameName) return nullptr; } -Skin* Skin::create(const std::string& pszFileName) +Skin* Skin::create(std::string_view pszFileName) { Skin* skin = new Skin(); if (skin->initWithFile(pszFileName)) @@ -81,7 +81,7 @@ Skin* Skin::create(const std::string& pszFileName) Skin::Skin() : _bone(nullptr), _armature(nullptr), _displayName(), _skinTransform(Mat4::IDENTITY) {} -bool Skin::initWithSpriteFrameName(const std::string& spriteFrameName) +bool Skin::initWithSpriteFrameName(std::string_view spriteFrameName) { CCAssert(spriteFrameName != "", ""); @@ -94,7 +94,7 @@ bool Skin::initWithSpriteFrameName(const std::string& spriteFrameName) } else { - CCLOG("Can't find CCSpriteFrame with %s. Please check your .plist file", spriteFrameName.c_str()); + CCLOG("Can't find CCSpriteFrame with %s. Please check your .plist file", spriteFrameName.data()); ret = false; } @@ -103,7 +103,7 @@ bool Skin::initWithSpriteFrameName(const std::string& spriteFrameName) return ret; } -bool Skin::initWithFile(const std::string& filename) +bool Skin::initWithFile(std::string_view filename) { bool ret = Sprite::initWithFile(filename); diff --git a/extensions/cocostudio/CCSkin.h b/extensions/cocostudio/CCSkin.h index 74046b428ad6..f1b0fc40b11d 100644 --- a/extensions/cocostudio/CCSkin.h +++ b/extensions/cocostudio/CCSkin.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -39,8 +39,8 @@ class CCS_DLL Skin : public cocos2d::Sprite { public: static Skin* create(); - static Skin* createWithSpriteFrameName(const std::string& pszSpriteFrameName); - static Skin* create(const std::string& pszFileName); + static Skin* createWithSpriteFrameName(std::string_view pszSpriteFrameName); + static Skin* create(std::string_view pszFileName); public: /** @@ -48,8 +48,8 @@ class CCS_DLL Skin : public cocos2d::Sprite */ Skin(); - virtual bool initWithSpriteFrameName(const std::string& spriteFrameName) override; - virtual bool initWithFile(const std::string& filename) override; + virtual bool initWithSpriteFrameName(std::string_view spriteFrameName) override; + virtual bool initWithFile(std::string_view filename) override; void updateArmatureTransform(); void updateTransform() override; @@ -73,7 +73,7 @@ class CCS_DLL Skin : public cocos2d::Sprite virtual void setBone(Bone* bone); virtual Bone* getBone() const; - virtual const std::string& getDisplayName() const { return _displayName; } + virtual std::string_view getDisplayName() const { return _displayName; } protected: BaseData _skinData; diff --git a/extensions/cocostudio/CCSpriteFrameCacheHelper.cpp b/extensions/cocostudio/CCSpriteFrameCacheHelper.cpp index ffa14bbaff6b..66f70f755213 100644 --- a/extensions/cocostudio/CCSpriteFrameCacheHelper.cpp +++ b/extensions/cocostudio/CCSpriteFrameCacheHelper.cpp @@ -50,7 +50,7 @@ void SpriteFrameCacheHelper::purge() _spriteFrameCacheHelper = nullptr; } -void SpriteFrameCacheHelper::retainSpriteFrames(const std::string& plistPath) +void SpriteFrameCacheHelper::retainSpriteFrames(std::string_view plistPath) { auto it = _usingSpriteFrames.find(plistPath); if (it != _usingSpriteFrames.end()) @@ -72,7 +72,7 @@ void SpriteFrameCacheHelper::retainSpriteFrames(const std::string& plistPath) _usingSpriteFrames[plistPath] = vec; } -void SpriteFrameCacheHelper::releaseSpriteFrames(const std::string& plistPath) +void SpriteFrameCacheHelper::releaseSpriteFrames(std::string_view plistPath) { auto it = _usingSpriteFrames.find(plistPath); if (it == _usingSpriteFrames.end()) @@ -89,13 +89,13 @@ void SpriteFrameCacheHelper::releaseSpriteFrames(const std::string& plistPath) _usingSpriteFrames.erase(it); } -void SpriteFrameCacheHelper::removeSpriteFrameFromFile(const std::string& plistPath) +void SpriteFrameCacheHelper::removeSpriteFrameFromFile(std::string_view plistPath) { SpriteFrameCache::getInstance()->removeSpriteFramesFromFile(plistPath); releaseSpriteFrames(plistPath); } -void SpriteFrameCacheHelper::addSpriteFrameFromFile(const std::string& plistPath, const std::string& imagePath) +void SpriteFrameCacheHelper::addSpriteFrameFromFile(std::string_view plistPath, std::string_view imagePath) { SpriteFrameCache::getInstance()->addSpriteFramesWithFile(plistPath, imagePath); retainSpriteFrames(plistPath); diff --git a/extensions/cocostudio/CCSpriteFrameCacheHelper.h b/extensions/cocostudio/CCSpriteFrameCacheHelper.h index a24be2704919..8f168b545231 100644 --- a/extensions/cocostudio/CCSpriteFrameCacheHelper.h +++ b/extensions/cocostudio/CCSpriteFrameCacheHelper.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -60,17 +60,17 @@ class CCS_DLL SpriteFrameCacheHelper /** * @brief Add sprite frame to CCSpriteFrameCache, it will save display name and it's relative image name */ - void addSpriteFrameFromFile(const std::string& plistPath, const std::string& imagePath); - void removeSpriteFrameFromFile(const std::string& plistPath); + void addSpriteFrameFromFile(std::string_view plistPath, std::string_view imagePath); + void removeSpriteFrameFromFile(std::string_view plistPath); private: - void retainSpriteFrames(const std::string& plistPath); - void releaseSpriteFrames(const std::string& plistPath); + void retainSpriteFrames(std::string_view plistPath); + void releaseSpriteFrames(std::string_view plistPath); SpriteFrameCacheHelper(); ~SpriteFrameCacheHelper(); - std::map> _usingSpriteFrames; + hlookup::string_map> _usingSpriteFrames; static SpriteFrameCacheHelper* _spriteFrameCacheHelper; }; diff --git a/extensions/cocostudio/CocosStudioExport.h b/extensions/cocostudio/CocosStudioExport.h index 89e1929c0dad..dcc448bf4074 100644 --- a/extensions/cocostudio/CocosStudioExport.h +++ b/extensions/cocostudio/CocosStudioExport.h @@ -31,4 +31,6 @@ # define CCS_DLL #endif +#include "base/hlookup.h" + #endif /* __CCEXTENSIONEXPORT_H__*/ \ No newline at end of file diff --git a/extensions/cocostudio/FlatBuffersSerialize.cpp b/extensions/cocostudio/FlatBuffersSerialize.cpp index 1ca0006455b0..bdd839b6e0e7 100644 --- a/extensions/cocostudio/FlatBuffersSerialize.cpp +++ b/extensions/cocostudio/FlatBuffersSerialize.cpp @@ -141,8 +141,8 @@ void FlatBuffersSerialize::deleteFlatBufferBuilder() } } -std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFile(const std::string& xmlFileName, - const std::string& flatbuffersFileName) +std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFile(std::string_view xmlFileName, + std::string_view flatbuffersFileName) { std::string inFullpath = FileUtils::getInstance()->fullPathForFilename(xmlFileName).c_str(); @@ -157,7 +157,7 @@ std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFile(const std::str } std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLBuffer(std::string& xmlBuffer, - const std::string& flatbuffersFileName) + std::string_view flatbuffersFileName) { // xml parse pugi::xml_document document; @@ -168,7 +168,7 @@ std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLBuffer(std::string& return ""; } -std::string FlatBuffersSerialize::serializeFlatBuffersWithOpaque(void* opaque, const std::string& flatbuffersFileName) +std::string FlatBuffersSerialize::serializeFlatBuffersWithOpaque(void* opaque, std::string_view flatbuffersFileName) { auto thiz = FlatBuffersSerialize::getInstance(); @@ -451,9 +451,9 @@ int FlatBuffersSerialize::getResourceType(std::string key) return 1; } -std::string FlatBuffersSerialize::getGUIClassName(const std::string& name) +std::string FlatBuffersSerialize::getGUIClassName(std::string_view name) { - std::string convertedClassName = name; + std::string convertedClassName; if (name == "Panel") { convertedClassName = "Layout"; @@ -478,6 +478,8 @@ std::string FlatBuffersSerialize::getGUIClassName(const std::string& name) { convertedClassName = "TextBMFont"; } + else + convertedClassName = name; return convertedClassName; } @@ -1231,7 +1233,7 @@ flatbuffers::Offset FlatBuffersSerialize::createEasingD } /* create flat buffers with XML */ -FlatBufferBuilder* FlatBuffersSerialize::createFlatBuffersWithXMLFileForSimulator(const std::string& xmlFileName) +FlatBufferBuilder* FlatBuffersSerialize::createFlatBuffersWithXMLFileForSimulator(std::string_view xmlFileName) { std::string inFullpath = FileUtils::getInstance()->fullPathForFilename(xmlFileName); @@ -1520,9 +1522,9 @@ Offset FlatBuffersSerialize::createProjectNodeOptionsForSimu } /* Serialize language XML file to Flat Buffers file. */ -std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFileForLanguageData(const std::string& xmlFilePath, - const std::string& flatBuffersFilePath, - const std::string& languageName) +std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFileForLanguageData(std::string_view xmlFilePath, + std::string_view flatBuffersFilePath, + std::string_view languageName) { // Read and parse XML data file. if (!FileUtils::getInstance()->isFileExist(xmlFilePath)) @@ -1560,7 +1562,7 @@ std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFileForLanguageData hasKeyReaded = true; } // Record corresponding text. - else if (strcmp(languageName.c_str(), childElement.name()) == 0) + else if (languageName == childElement.name()) { const char* langText = childElement.text().as_string(); if (langText && langText[0] != '\0') diff --git a/extensions/cocostudio/FlatBuffersSerialize.h b/extensions/cocostudio/FlatBuffersSerialize.h index 21582b2c624e..1e592e14e9d9 100644 --- a/extensions/cocostudio/FlatBuffersSerialize.h +++ b/extensions/cocostudio/FlatBuffersSerialize.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013 cocos2d-x.org http://www.cocos2d-x.org @@ -105,15 +105,14 @@ class CCS_DLL FlatBuffersSerialize void deleteFlatBufferBuilder(); - std::string test(const std::string& xmlFileName, const std::string& flatbuffersFileName); + std::string test(std::string_view xmlFileName, std::string_view flatbuffersFileName); /* serialize flat buffers with XML */ - static std::string serializeFlatBuffersWithXMLFile(const std::string& xmlFileName, - const std::string& flatbuffersFileName); + static std::string serializeFlatBuffersWithXMLFile(std::string_view xmlFileName, + std::string_view flatbuffersFileName); /* x-studio spec: serialize flat buffers with XML buffer */ - static std::string serializeFlatBuffersWithXMLBuffer(std::string& xmlBuffer, - const std::string& flatbuffersFileName); - static std::string serializeFlatBuffersWithOpaque(void* opaque, const std::string& flatbuffersFileName); + static std::string serializeFlatBuffersWithXMLBuffer(std::string& xmlBuffer, std::string_view flatbuffersFileName); + static std::string serializeFlatBuffersWithOpaque(void* opaque, std::string_view flatbuffersFileName); // NodeTree flatbuffers::Offset createNodeTree(pugi::xml_node objectData, std::string classType); @@ -138,11 +137,11 @@ class CCS_DLL FlatBuffersSerialize /**/ int getResourceType(std::string key); - std::string getGUIClassName(const std::string& name); + std::string getGUIClassName(std::string_view name); std::string getWidgetReaderClassName(cocos2d::ui::Widget* widget); /* create flat buffers with XML */ - flatbuffers::FlatBufferBuilder* createFlatBuffersWithXMLFileForSimulator(const std::string& xmlFileName); + flatbuffers::FlatBufferBuilder* createFlatBuffersWithXMLFileForSimulator(std::string_view xmlFileName); flatbuffers::Offset createNodeTreeForSimulator(pugi::xml_node objectData, std::string classType); flatbuffers::Offset createProjectNodeOptionsForSimulator( @@ -151,9 +150,9 @@ class CCS_DLL FlatBuffersSerialize std::string getCsdVersion() { return _csdVersion; } /* Serialize language XML file to Flat Buffers file. */ - std::string serializeFlatBuffersWithXMLFileForLanguageData(const std::string& xmlFilePath, - const std::string& flatBuffersFilePath, - const std::string& languageName); + std::string serializeFlatBuffersWithXMLFileForLanguageData(std::string_view xmlFilePath, + std::string_view flatBuffersFilePath, + std::string_view languageName); public: std::vector> _textures; diff --git a/extensions/cocostudio/SpineSkeletonDataCache.h b/extensions/cocostudio/SpineSkeletonDataCache.h index 317c64d06a32..51a3e1de4a23 100644 --- a/extensions/cocostudio/SpineSkeletonDataCache.h +++ b/extensions/cocostudio/SpineSkeletonDataCache.h @@ -39,7 +39,7 @@ class CCS_DLL SpineSkeletonDataCache void removeAllUnusedData(void); public: - std::map _cacheTable; + hlookup::string_map _cacheTable; void (*_reportError)(const char* pszFormat, ...); }; @@ -76,7 +76,7 @@ class SpineSkeletonDataCache void removeAllUnusedData(void); public: - std::map _cacheTable; + hlookup::string_map _cacheTable; void (*_reportError)(const char* pszFormat, ...); }; diff --git a/extensions/cocostudio/TriggerMng.cpp b/extensions/cocostudio/TriggerMng.cpp index 0ac9a3181dca..39ccd44571c3 100644 --- a/extensions/cocostudio/TriggerMng.cpp +++ b/extensions/cocostudio/TriggerMng.cpp @@ -505,7 +505,7 @@ ArmatureMovementDispatcher::~ArmatureMovementDispatcher(void) void ArmatureMovementDispatcher::animationEvent(Armature* armature, MovementEventType movementType, - const std::string& movementID) + std::string_view movementID) { for (auto iter = _mapEventAnimation->begin(); iter != _mapEventAnimation->end(); ++iter) { diff --git a/extensions/cocostudio/TriggerMng.h b/extensions/cocostudio/TriggerMng.h index 30474d2a0292..1830a67fe966 100644 --- a/extensions/cocostudio/TriggerMng.h +++ b/extensions/cocostudio/TriggerMng.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -46,7 +46,7 @@ class CCS_DLL ArmatureMovementDispatcher : public cocos2d::Ref public: void addAnimationEventCallBack(cocos2d::Ref* pTarget, SEL_MovementEventCallFunc mecf); void removeAnnimationEventCallBack(cocos2d::Ref* pTarget, SEL_MovementEventCallFunc mecf); - void animationEvent(Armature* armature, MovementEventType movementType, const std::string& movementID); + void animationEvent(Armature* armature, MovementEventType movementType, std::string_view movementID); private: std::unordered_map* _mapEventAnimation; diff --git a/extensions/cocostudio/WidgetCallBackHandlerProtocol.cpp b/extensions/cocostudio/WidgetCallBackHandlerProtocol.cpp index a8a6b59e7d10..d51149ba9d1d 100644 --- a/extensions/cocostudio/WidgetCallBackHandlerProtocol.cpp +++ b/extensions/cocostudio/WidgetCallBackHandlerProtocol.cpp @@ -4,15 +4,15 @@ namespace cocostudio { WidgetCallBackHandlerProtocol::~WidgetCallBackHandlerProtocol() {} -cocos2d::ui::Widget::ccWidgetTouchCallback WidgetCallBackHandlerProtocol::onLocateTouchCallback(const std::string&) +cocos2d::ui::Widget::ccWidgetTouchCallback WidgetCallBackHandlerProtocol::onLocateTouchCallback(std::string_view) { return nullptr; } -cocos2d::ui::Widget::ccWidgetClickCallback WidgetCallBackHandlerProtocol::onLocateClickCallback(const std::string&) +cocos2d::ui::Widget::ccWidgetClickCallback WidgetCallBackHandlerProtocol::onLocateClickCallback(std::string_view) { return nullptr; } -cocos2d::ui::Widget::ccWidgetEventCallback WidgetCallBackHandlerProtocol::onLocateEventCallback(const std::string&) +cocos2d::ui::Widget::ccWidgetEventCallback WidgetCallBackHandlerProtocol::onLocateEventCallback(std::string_view) { return nullptr; } diff --git a/extensions/cocostudio/WidgetCallBackHandlerProtocol.h b/extensions/cocostudio/WidgetCallBackHandlerProtocol.h index aae843e00e59..dd423e63ba28 100644 --- a/extensions/cocostudio/WidgetCallBackHandlerProtocol.h +++ b/extensions/cocostudio/WidgetCallBackHandlerProtocol.h @@ -36,9 +36,9 @@ class CCS_DLL WidgetCallBackHandlerProtocol public: virtual ~WidgetCallBackHandlerProtocol(); - virtual cocos2d::ui::Widget::ccWidgetTouchCallback onLocateTouchCallback(const std::string& callBackName); - virtual cocos2d::ui::Widget::ccWidgetClickCallback onLocateClickCallback(const std::string& callBackName); - virtual cocos2d::ui::Widget::ccWidgetEventCallback onLocateEventCallback(const std::string& callBackName); + virtual cocos2d::ui::Widget::ccWidgetTouchCallback onLocateTouchCallback(std::string_view callBackName); + virtual cocos2d::ui::Widget::ccWidgetClickCallback onLocateClickCallback(std::string_view callBackName); + virtual cocos2d::ui::Widget::ccWidgetEventCallback onLocateEventCallback(std::string_view callBackName); }; } // namespace cocostudio diff --git a/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.cpp b/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.cpp index 00861efbd7b5..9202f0824c3c 100644 --- a/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.cpp +++ b/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.cpp @@ -145,7 +145,7 @@ void ArmatureNodeReader::setPropsWithFlatBuffers(cocos2d::Node* node, const flat #if defined(CC_BUILD_WITH_DRANGBONES) && CC_BUILD_WITH_DRANGBONES auto filep = filepath.rfind('.'); if (filep != std::string::npos && strcmp(&filepath[filep], ".json") == 0) - { // Currently, adjust by file ext, regard as DragonBones 4.5/5.0 + { // Currently, adjust by file ext, regard as DragonBones 4.5/5.0 // 4.5 texture info is fixed as texture.png, texture.json // 5.o texture info is _tex.json _tex.png auto sharedFactory = dragonBones::CCFactory::getFactory(); @@ -230,7 +230,7 @@ cocos2d::Node* ArmatureNodeReader::createNodeWithFlatBuffers(const flatbuffers:: return node; } -std::string ArmatureNodeReader::getArmatureName(const std::string& exporJsonPath) +std::string ArmatureNodeReader::getArmatureName(std::string_view exporJsonPath) { // FileUtils.getFileData(exporJsonPath, "r", size) // need read armature name in exportJsonPath size_t end = exporJsonPath.find_last_of("."); @@ -241,5 +241,5 @@ std::string ArmatureNodeReader::getArmatureName(const std::string& exporJsonPath if (start == -1) start = 0; - return exporJsonPath.substr(start, end - start); + return std::string{exporJsonPath.substr(start, end - start)}; } diff --git a/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.h b/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.h index 3f7ae420b076..d37f2652ba85 100644 --- a/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.h +++ b/extensions/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2014 cocos2d-x.org http://www.cocos2d-x.org @@ -59,7 +59,7 @@ class ArmatureNodeReader : public cocos2d::Ref, public cocostudio::NodeReaderPro cocos2d::Node* createNodeWithFlatBuffers(const flatbuffers::Table* nodeOptions) override; private: - std::string getArmatureName(const std::string& exporJsonPath); + std::string getArmatureName(std::string_view exporJsonPath); }; #endif /* defined(__ARMATURENODEREADER_H_) */ diff --git a/extensions/cocostudio/WidgetReader/ImageViewReader/ImageViewReader.cpp b/extensions/cocostudio/WidgetReader/ImageViewReader/ImageViewReader.cpp index 6e417fcca679..f015d67a9f24 100644 --- a/extensions/cocostudio/WidgetReader/ImageViewReader/ImageViewReader.cpp +++ b/extensions/cocostudio/WidgetReader/ImageViewReader/ImageViewReader.cpp @@ -111,7 +111,7 @@ void ImageViewReader::setPropsFromJsonDictionary(Widget* widget, const rapidjson const rapidjson::Value& imageFileNameDic = DICTOOL->getSubDictionary_json(options, P_FileNameData); int imageFileNameType = DICTOOL->getIntValue_json(imageFileNameDic, P_ResourceType); - const std::string& imageFilePath = DICTOOL->getStringValue_json(imageFileNameDic, P_Path); + std::string_view imageFilePath = DICTOOL->getStringValue_json(imageFileNameDic, P_Path); if (!imageFilePath.empty()) { diff --git a/extensions/cocostudio/WidgetReader/NodeReaderProtocol.cpp b/extensions/cocostudio/WidgetReader/NodeReaderProtocol.cpp index 24997d4a98ba..5af14ee111d0 100644 --- a/extensions/cocostudio/WidgetReader/NodeReaderProtocol.cpp +++ b/extensions/cocostudio/WidgetReader/NodeReaderProtocol.cpp @@ -30,7 +30,7 @@ static cocos2d::Node* createArmatureNode() return cocostudio::Armature::create(); } -static cocos2d::ParticleSystemQuad* createParticleSystemQuad(const std::string& path) +static cocos2d::ParticleSystemQuad* createParticleSystemQuad(std::string_view path) { return cocos2d::ParticleSystemQuad::create(path); } @@ -56,13 +56,13 @@ namespace wext { bool (*onBeforeLoadObjectAsset)(cocos2d::Node*, cocos2d::ResourceData& assets, - int index /*= 0*/) = &onLoadObjectAssetDummy; + int index /*= 0*/) = &onLoadObjectAssetDummy; bool (*onAfterLoadObjectAsset)(cocos2d::Node*, cocos2d::ResourceData& assets, - int index /*= 0*/) = &onLoadObjectAssetDummy; -void (*onLoadSpriteFramesWithFile)(std::string& file) = nullptr; -void (*onNestingNodeLoading)(const std::string& filePath) = nullptr; -void (*onNestingNodeLoaded)(cocos2d::Node*, const std::string& filePath) = nullptr; + int index /*= 0*/) = &onLoadObjectAssetDummy; +void (*onLoadSpriteFramesWithFile)(std::string& file) = nullptr; +void (*onNestingNodeLoading)(std::string_view filePath) = nullptr; +void (*onNestingNodeLoaded)(cocos2d::Node*, std::string_view filePath) = nullptr; cocos2d::Node* (*aNode)(); cocos2d::ui::Widget* (*aWidget)(); cocos2d::Sprite* (*aSprite)(); @@ -79,7 +79,7 @@ cocos2d::ui::Layout* (*aLayout)(); cocos2d::ui::ScrollView* (*aScrollView)(); cocos2d::ui::ListView* (*aListView)(); cocos2d::ui::PageView* (*aPageView)(); -cocos2d::ParticleSystemQuad* (*aParticleSystemQuad)(const std::string&); +cocos2d::ParticleSystemQuad* (*aParticleSystemQuad)(std::string_view); cocos2d::Node* (*aArmatureNode)(); cocostudio::timeline::SkeletonNode* (*aSkeletonNode)(); cocostudio::timeline::BoneNode* (*aBoneNode)(); @@ -137,7 +137,7 @@ cocos2d::ResourceData cocos2d::wext::makeResourceData(const flatbuffers::Resourc return fileData; } -cocos2d::ResourceData cocos2d::wext::makeResourceData(const std::string& path, int type) +cocos2d::ResourceData cocos2d::wext::makeResourceData(std::string_view path, int type) { cocos2d::ResourceData fileData; fileData.file = path; diff --git a/extensions/cocostudio/WidgetReader/NodeReaderProtocol.h b/extensions/cocostudio/WidgetReader/NodeReaderProtocol.h index 7276307498eb..ad10606f443a 100644 --- a/extensions/cocostudio/WidgetReader/NodeReaderProtocol.h +++ b/extensions/cocostudio/WidgetReader/NodeReaderProtocol.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2014 cocos2d-x.org http://www.cocos2d-x.org @@ -141,7 +141,7 @@ CC_DLL extern APP_LOGERROR_FUNC getAppErrorLogFunc(); CCS_DLL extern void (*onLoadSpriteFramesWithFile)(std::string& file); CCS_DLL extern cocos2d::ResourceData makeResourceData(const flatbuffers::ResourceData* data); -CCS_DLL extern cocos2d::ResourceData makeResourceData(const std::string& path, int type = 0); +CCS_DLL extern cocos2d::ResourceData makeResourceData(std::string_view path, int type = 0); CCS_DLL extern cocos2d::ResourceData makeResourceData(std::string&& path, int type = 0); CCS_DLL extern void resetReaderAllHooks(); @@ -168,7 +168,7 @@ CCS_DLL extern cocos2d::ui::PageView* (*aPageView)(); CCS_DLL extern cocos2d::Node* (*aArmatureNode)(); CCS_DLL extern cocostudio::timeline::SkeletonNode* (*aSkeletonNode)(); CCS_DLL extern cocostudio::timeline::BoneNode* (*aBoneNode)(); -CCS_DLL extern cocos2d::ParticleSystemQuad* (*aParticleSystemQuad)(const std::string&); +CCS_DLL extern cocos2d::ParticleSystemQuad* (*aParticleSystemQuad)(std::string_view); CCS_DLL extern cocos2d::Node* (*aNestingNode)(std::string); ///// 3d objects ///// diff --git a/extensions/cocostudio/WidgetReader/TextAtlasReader/TextAtlasReader.cpp b/extensions/cocostudio/WidgetReader/TextAtlasReader/TextAtlasReader.cpp index 161a86263cff..61e22265d9c2 100644 --- a/extensions/cocostudio/WidgetReader/TextAtlasReader/TextAtlasReader.cpp +++ b/extensions/cocostudio/WidgetReader/TextAtlasReader/TextAtlasReader.cpp @@ -97,7 +97,7 @@ void TextAtlasReader::setPropsFromJsonDictionary(Widget* widget, const rapidjson { WidgetReader::setPropsFromJsonDictionary(widget, options); - std::string jsonPath = GUIReader::getInstance()->getFilePath(); + std::string_view jsonPath = GUIReader::getInstance()->getFilePath(); TextAtlas* labelAtlas = static_cast(widget); // bool sv = DICTOOL->checkObjectExist_json(options, P_StringValue); @@ -112,7 +112,7 @@ void TextAtlasReader::setPropsFromJsonDictionary(Widget* widget, const rapidjson { case 0: { - std::string tp_c = jsonPath; + std::string tp_c{jsonPath}; const char* cmfPath = DICTOOL->getStringValue_json(cmftDic, P_Path); const char* cmf_tp = tp_c.append(cmfPath).c_str(); labelAtlas->setProperty(DICTOOL->getStringValue_json(options, P_StringValue, "12345678"), cmf_tp, diff --git a/extensions/cocostudio/WidgetReader/TextBMFontReader/TextBMFontReader.cpp b/extensions/cocostudio/WidgetReader/TextBMFontReader/TextBMFontReader.cpp index fffff874b8a8..3ee6d357279b 100644 --- a/extensions/cocostudio/WidgetReader/TextBMFontReader/TextBMFontReader.cpp +++ b/extensions/cocostudio/WidgetReader/TextBMFontReader/TextBMFontReader.cpp @@ -82,7 +82,7 @@ void TextBMFontReader::setPropsFromJsonDictionary(Widget* widget, const rapidjso { WidgetReader::setPropsFromJsonDictionary(widget, options); - std::string jsonPath = GUIReader::getInstance()->getFilePath(); + std::string_view jsonPath = GUIReader::getInstance()->getFilePath(); TextBMFont* labelBMFont = static_cast(widget); @@ -92,7 +92,7 @@ void TextBMFontReader::setPropsFromJsonDictionary(Widget* widget, const rapidjso { case 0: { - std::string tp_c = jsonPath; + std::string tp_c{jsonPath}; const char* cmfPath = DICTOOL->getStringValue_json(cmftDic, P_Path); const char* cmf_tp = tp_c.append(cmfPath).c_str(); labelBMFont->setFntFile(cmf_tp); diff --git a/extensions/cocostudio/WidgetReader/TextFieldReader/TextFieldReader.cpp b/extensions/cocostudio/WidgetReader/TextFieldReader/TextFieldReader.cpp index 484dca151fdd..e63761291a20 100644 --- a/extensions/cocostudio/WidgetReader/TextFieldReader/TextFieldReader.cpp +++ b/extensions/cocostudio/WidgetReader/TextFieldReader/TextFieldReader.cpp @@ -101,9 +101,9 @@ void TextFieldReader::setPropsFromJsonDictionary(Widget* widget, const rapidjson textField->setFontSize(DICTOOL->getIntValue_json(options, P_FontSize, 20)); - std::string jsonPath = GUIReader::getInstance()->getFilePath(); - std::string fontName = DICTOOL->getStringValue_json(options, P_FontName, ""); - std::string fontFilePath = jsonPath.append(fontName); + std::string fontFilePath{GUIReader::getInstance()->getFilePath()}; + auto fontName = DICTOOL->getStringValue_json(options, P_FontName, ""); + fontFilePath.append(fontName); if (FileUtils::getInstance()->isFileExist(fontFilePath)) textField->setFontName(fontFilePath); else diff --git a/extensions/cocostudio/WidgetReader/TextReader/TextReader.cpp b/extensions/cocostudio/WidgetReader/TextReader/TextReader.cpp index a42748e5e2a8..05624cde11a0 100644 --- a/extensions/cocostudio/WidgetReader/TextReader/TextReader.cpp +++ b/extensions/cocostudio/WidgetReader/TextReader/TextReader.cpp @@ -57,7 +57,7 @@ void TextReader::setPropsFromBinary(cocos2d::ui::Widget* widget, CocoLoader* coc Text* label = static_cast(widget); - std::string binaryFilePath = GUIReader::getInstance()->getFilePath(); + std::string binaryFilePath{GUIReader::getInstance()->getFilePath()}; for (int i = 0; i < cocoNode->GetChildNum(); ++i) { @@ -96,7 +96,7 @@ void TextReader::setPropsFromJsonDictionary(Widget* widget, const rapidjson::Val { WidgetReader::setPropsFromJsonDictionary(widget, options); - std::string jsonPath = GUIReader::getInstance()->getFilePath(); + std::string fontFilePath{GUIReader::getInstance()->getFilePath()}; Text* label = static_cast(widget); bool touchScaleChangeAble = DICTOOL->getBooleanValue_json(options, P_TouchScaleEnable); @@ -106,9 +106,9 @@ void TextReader::setPropsFromJsonDictionary(Widget* widget, const rapidjson::Val label->setFontSize(DICTOOL->getIntValue_json(options, P_FontSize, 20)); - std::string fontName = DICTOOL->getStringValue_json(options, P_FontName, ""); + auto fontName = DICTOOL->getStringValue_json(options, P_FontName, ""); - std::string fontFilePath = jsonPath.append(fontName); + fontFilePath.append(fontName); if (FileUtils::getInstance()->isFileExist(fontFilePath)) { label->setFontName(fontFilePath); diff --git a/extensions/cocostudio/WidgetReader/WidgetReader.cpp b/extensions/cocostudio/WidgetReader/WidgetReader.cpp index e30e04d1c29e..14dcd1be8dd2 100644 --- a/extensions/cocostudio/WidgetReader/WidgetReader.cpp +++ b/extensions/cocostudio/WidgetReader/WidgetReader.cpp @@ -98,9 +98,9 @@ WidgetReader::WidgetReader() , _opacity(255) , _isAdaptScreen(false) { - valueToInt = [=](const std::string& str) -> int { return atoi(str.c_str()); }; + valueToInt = [=](std::string_view str) -> int { return atoi(str.data()); }; - valueToBool = [=](const std::string& str) -> bool { + valueToBool = [=](std::string_view str) -> bool { int intValue = valueToInt(str); if (1 == intValue) { @@ -112,7 +112,7 @@ WidgetReader::WidgetReader() } }; - valueToFloat = [=](const std::string& str) -> float { return utils::atof(str.c_str()); }; + valueToFloat = [=](std::string_view str) -> float { return utils::atof(str.data()); }; } WidgetReader::~WidgetReader() {} @@ -303,17 +303,17 @@ void WidgetReader::endSetBasicProperties(Widget* widget) } std::string WidgetReader::getResourcePath(const rapidjson::Value& dict, - const std::string& key, + std::string_view key, cocos2d::ui::Widget::TextureResType texType) { - std::string jsonPath = GUIReader::getInstance()->getFilePath(); - const char* imageFileName = DICTOOL->getStringValue_json(dict, key.c_str()); + std::string_view jsonPath = GUIReader::getInstance()->getFilePath(); + const char* imageFileName = DICTOOL->getStringValue_json(dict, key.data()); std::string imageFileName_tp; if (nullptr != imageFileName) { if (texType == ui::Widget::TextureResType::LOCAL) { - imageFileName_tp = jsonPath + imageFileName; + imageFileName_tp.append(jsonPath).append(imageFileName); } else if (texType == ui::Widget::TextureResType::PLIST) { @@ -339,14 +339,14 @@ std::string WidgetReader::getResourcePath(CocoLoader* cocoLoader, return ""; } - std::string binaryPath = GUIReader::getInstance()->getFilePath(); + std::string_view binaryPath = GUIReader::getInstance()->getFilePath(); std::string imageFileName_tp; if (!backgroundValue.empty()) { if (texType == ui::Widget::TextureResType::LOCAL) { - imageFileName_tp = binaryPath + backgroundValue; + imageFileName_tp.append(binaryPath).append(backgroundValue); } else if (texType == ui::Widget::TextureResType::PLIST) { @@ -940,20 +940,19 @@ Node* WidgetReader::createNodeWithFlatBuffers(const flatbuffers::Table* widgetOp return widget; } -std::string WidgetReader::getResourcePath(const std::string& path, cocos2d::ui::Widget::TextureResType texType) +std::string WidgetReader::getResourcePath(std::string_view path, cocos2d::ui::Widget::TextureResType texType) { - std::string filePath = GUIReader::getInstance()->getFilePath(); - const char* imageFileName = path.c_str(); + std::string_view filePath = GUIReader::getInstance()->getFilePath(); std::string imageFileName_tp; - if (nullptr != imageFileName && 0 != strcmp("", imageFileName)) + if (!path.empty()) { if (texType == ui::Widget::TextureResType::LOCAL) { - imageFileName_tp = filePath + imageFileName; + imageFileName_tp.append(filePath).append(path); } else if (texType == ui::Widget::TextureResType::PLIST) { - imageFileName_tp = imageFileName; + imageFileName_tp.assign(path); } else { diff --git a/extensions/cocostudio/WidgetReader/WidgetReader.h b/extensions/cocostudio/WidgetReader/WidgetReader.h index fb5e60d3d92f..0b9a86316b23 100644 --- a/extensions/cocostudio/WidgetReader/WidgetReader.h +++ b/extensions/cocostudio/WidgetReader/WidgetReader.h @@ -1,4 +1,4 @@ -/**************************************************************************** +/**************************************************************************** Copyright (c) 2014 cocos2d-x.org http://www.cocos2d-x.org @@ -66,7 +66,7 @@ class CCS_DLL WidgetReader : public cocos2d::Ref, public WidgetReaderProtocol, p protected: std::string getResourcePath(const rapidjson::Value& dict, - const std::string& key, + std::string_view key, cocos2d::ui::Widget::TextureResType texType); void setAnchorPointForWidget(cocos2d::ui::Widget* widget, const rapidjson::Value& options); @@ -74,14 +74,14 @@ class CCS_DLL WidgetReader : public cocos2d::Ref, public WidgetReaderProtocol, p stExpCocoNode* pCocoNode, cocos2d::ui::Widget::TextureResType texType); - std::string getResourcePath(const std::string& path, cocos2d::ui::Widget::TextureResType texType); + std::string getResourcePath(std::string_view path, cocos2d::ui::Widget::TextureResType texType); void beginSetBasicProperties(cocos2d::ui::Widget* widget); void endSetBasicProperties(cocos2d::ui::Widget* widget); - std::function valueToInt; - std::function valueToBool; - std::function valueToFloat; + std::function valueToInt; + std::function valueToBool; + std::function valueToFloat; float _sizePercentX; float _sizePercentY; diff --git a/extensions/fairygui/GTextInput.cpp b/extensions/fairygui/GTextInput.cpp index 3a9117675baf..902fc4be5244 100644 --- a/extensions/fairygui/GTextInput.cpp +++ b/extensions/fairygui/GTextInput.cpp @@ -122,7 +122,7 @@ void GTextInput::editBoxReturn(cocos2d::ui::EditBox * editBox) // dispatchEvent(UIEventType::Submit); } -void GTextInput::editBoxTextChanged(cocos2d::ui::EditBox* editBox, const std::string& text) +void GTextInput::editBoxTextChanged(cocos2d::ui::EditBox* editBox, std::string_view /*text*/) { _text.clear(); _text.append(_input->getText()); diff --git a/extensions/fairygui/GTextInput.h b/extensions/fairygui/GTextInput.h index 8ce76371ce75..7741843e0c7a 100644 --- a/extensions/fairygui/GTextInput.h +++ b/extensions/fairygui/GTextInput.h @@ -36,7 +36,7 @@ class GTextInput : public GTextField, cocos2d::ui::EditBoxDelegate virtual void setTextFieldText() override; virtual void editBoxReturn(cocos2d::ui::EditBox* editBox) override; - virtual void editBoxTextChanged(cocos2d::ui::EditBox* editBox, const std::string& text) override; + virtual void editBoxTextChanged(cocos2d::ui::EditBox* editBox, std::string_view text) override; private: FUIInput* _input; diff --git a/extensions/fairygui/ScrollPane.cpp b/extensions/fairygui/ScrollPane.cpp index f976666c3015..7e25cbb04387 100644 --- a/extensions/fairygui/ScrollPane.cpp +++ b/extensions/fairygui/ScrollPane.cpp @@ -722,13 +722,13 @@ void ScrollPane::changeContentSizeOnScrolling(float deltaWidth, float deltaHeigh if (deltaWidth != 0 && isRightmost) { _xPos = _overlapSize.width; - _container->setPositionX(_container->getPositionX() - _xPos); + _container->setPositionX(-_xPos); } if (deltaHeight != 0 && isBottom) { _yPos = _overlapSize.height; - _container->setPositionY2(_container->getPositionY2() - _yPos); + _container->setPositionY2(-_yPos); } } diff --git a/extensions/fairygui/UIPackage.cpp b/extensions/fairygui/UIPackage.cpp index 19e0ebb3dcb3..bdd97c41d299 100644 --- a/extensions/fairygui/UIPackage.cpp +++ b/extensions/fairygui/UIPackage.cpp @@ -200,7 +200,7 @@ string UIPackage::getItemURL(const string& pkgName, const string& resName) return STD_STRING_EMPTY; } -PackageItem* UIPackage::getItemByURL(const string& url) +PackageItem* UIPackage::getItemByURL(std::string_view url) { if (url.size() == 0) return nullptr; @@ -214,22 +214,22 @@ PackageItem* UIPackage::getItemByURL(const string& url) { if (url.size() > 13) { - string pkgId = url.substr(5, 8); + std::string pkgId{url.substr(5, 8)}; UIPackage* pkg = getById(pkgId); if (pkg != nullptr) { - string srcId = url.substr(13); + std::string srcId{url.substr(13)}; return pkg->getItem(srcId); } } } else { - string pkgName = url.substr(pos1 + 2, pos2 - pos1 - 2); + std::string pkgName{url.substr(pos1 + 2, pos2 - pos1 - 2)}; UIPackage* pkg = getByName(pkgName); if (pkg != nullptr) { - string srcName = url.substr(pos2 + 1); + std::string srcName{url.substr(pos2 + 1)}; return pkg->getItemByName(srcName); } } @@ -274,7 +274,7 @@ void* UIPackage::getItemAsset(const std::string& pkgName, const std::string& res return nullptr; } -void* UIPackage::getItemAssetByURL(const std::string& url, PackageItemType type) +void* UIPackage::getItemAssetByURL(std::string_view url, PackageItemType type) { PackageItem* pi = UIPackage::getItemByURL(url); if (pi) diff --git a/extensions/fairygui/UIPackage.h b/extensions/fairygui/UIPackage.h index 041a86822a3f..a2b0c754d4f9 100644 --- a/extensions/fairygui/UIPackage.h +++ b/extensions/fairygui/UIPackage.h @@ -25,10 +25,10 @@ class UIPackage : public cocos2d::Ref static GObject* createObject(const std::string& pkgName, const std::string& resName); static GObject* createObjectFromURL(const std::string& url); static std::string getItemURL(const std::string& pkgName, const std::string& resName); - static PackageItem* getItemByURL(const std::string& url); + static PackageItem* getItemByURL(std::string_view url); static std::string normalizeURL(const std::string& url); static void* getItemAsset(const std::string& pkgName, const std::string& resName, PackageItemType type = PackageItemType::UNKNOWN); - static void* getItemAssetByURL(const std::string& url, PackageItemType type = PackageItemType::UNKNOWN); + static void* getItemAssetByURL(std::string_view url, PackageItemType type = PackageItemType::UNKNOWN); static cocos2d::Texture2D* getEmptyTexture() { return _emptyTexture; } const std::string& getId() const { return _id; } diff --git a/extensions/fairygui/display/FUIContainer.cpp b/extensions/fairygui/display/FUIContainer.cpp index 3cd5ff0c97f7..9676cf133ea7 100644 --- a/extensions/fairygui/display/FUIContainer.cpp +++ b/extensions/fairygui/display/FUIContainer.cpp @@ -496,4 +496,14 @@ void FUIContainer::visit(cocos2d::Renderer * renderer, const cocos2d::Mat4 & par Node::visit(renderer, parentTransform, parentFlags); } +void FUIContainer::setGlobalZOrder(float globalZOrder) +{ + Node::setGlobalZOrder(globalZOrder); + if (_stencilClippingSupport && _stencilClippingSupport->_stencil) + { + _stencilClippingSupport->_stencil->setGlobalZOrder(globalZOrder); + } +} + + NS_FGUI_END diff --git a/extensions/fairygui/display/FUIContainer.h b/extensions/fairygui/display/FUIContainer.h index 8f9958e83d10..6e991b5ba504 100644 --- a/extensions/fairygui/display/FUIContainer.h +++ b/extensions/fairygui/display/FUIContainer.h @@ -77,6 +77,7 @@ class FUIContainer : public cocos2d::Node void onExit() override; void visit(cocos2d::Renderer *renderer, const cocos2d::Mat4 &parentTransform, uint32_t parentFlags) override; void setCameraMask(unsigned short mask, bool applyChildren = true) override; + void setGlobalZOrder(float globalZOrder) override; GObject* gOwner; private: diff --git a/extensions/fairygui/display/FUILabel.cpp b/extensions/fairygui/display/FUILabel.cpp index 173acf1e58b5..9917d986a334 100644 --- a/extensions/fairygui/display/FUILabel.cpp +++ b/extensions/fairygui/display/FUILabel.cpp @@ -118,7 +118,7 @@ void FUILabel::applyTextFormat() disableEffect(LabelEffect::SHADOW); } -bool FUILabel::setBMFontFilePath(const std::string& bmfontFilePath, const Vec2& imageOffset, float fontSize) +bool FUILabel::setBMFontFilePath(std::string_view bmfontFilePath, const Vec2& imageOffset, float fontSize) { BitmapFont* bmFont = (BitmapFont*)UIPackage::getItemAssetByURL(bmfontFilePath, PackageItemType::FONT); if (bmFont == nullptr) diff --git a/extensions/fairygui/display/FUILabel.h b/extensions/fairygui/display/FUILabel.h index 0f9448dff397..6733431730ea 100644 --- a/extensions/fairygui/display/FUILabel.h +++ b/extensions/fairygui/display/FUILabel.h @@ -23,7 +23,7 @@ class FUILabel : public cocos2d::Label void setUnderlineColor(const cocos2d::Color3B& value); - virtual bool setBMFontFilePath(const std::string& bmfontFilePath, const cocos2d::Vec2& imageOffset = cocos2d::Vec2::ZERO, float fontSize = 0) override; + virtual bool setBMFontFilePath(std::string_view bmfontFilePath, const cocos2d::Vec2& imageOffset = cocos2d::Vec2::ZERO, float fontSize = 0) override; void setGrayed(bool value); protected: diff --git a/extensions/fairygui/display/FUIRichText.cpp b/extensions/fairygui/display/FUIRichText.cpp index 8e41ead1aa0e..e98495b7b089 100644 --- a/extensions/fairygui/display/FUIRichText.cpp +++ b/extensions/fairygui/display/FUIRichText.cpp @@ -76,7 +76,7 @@ static float stripTrailingWhitespace(const std::vector& row) { if (!row.empty()) { if (auto label = dynamic_cast(row.back())) { const auto width = label->getContentSize().width; - auto str = label->getString(); + std::string str{label->getString()}; rtrim(str); if (label->getString() != str) { label->setString(str); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_3d_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_3d_auto.cpp index 73e05e7f3cdc..6a9652abdce7 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_3d_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_3d_auto.cpp @@ -32,12 +32,12 @@ int lua_cocos2dx_3d_Animation3D_initWithFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Animation3D:initWithFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Animation3D:initWithFile"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Animation3D:initWithFile"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Animation3D:initWithFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Animation3D_initWithFile'", nullptr); @@ -172,8 +172,8 @@ int lua_cocos2dx_3d_Animation3D_create(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Animation3D:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Animation3D:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Animation3D_create'", nullptr); @@ -185,10 +185,10 @@ int lua_cocos2dx_3d_Animation3D_create(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Animation3D:create"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Animation3D:create"); + std::string_view arg0; + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Animation3D:create"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Animation3D:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Animation3D_create'", nullptr); @@ -1341,18 +1341,18 @@ int lua_cocos2dx_3d_TextureCube_create(lua_State* tolua_S) if (argc == 6) { - std::string arg0; - std::string arg1; - std::string arg2; - std::string arg3; - std::string arg4; - std::string arg5; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TextureCube:create"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.TextureCube:create"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "cc.TextureCube:create"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "cc.TextureCube:create"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "cc.TextureCube:create"); - ok &= luaval_to_std_string(tolua_S, 7,&arg5, "cc.TextureCube:create"); + std::string_view arg0; + std::string_view arg1; + std::string_view arg2; + std::string_view arg3; + std::string_view arg4; + std::string_view arg5; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TextureCube:create"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.TextureCube:create"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "cc.TextureCube:create"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "cc.TextureCube:create"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "cc.TextureCube:create"); + ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "cc.TextureCube:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_TextureCube_create'", nullptr); @@ -1641,8 +1641,8 @@ int lua_cocos2dx_3d_BillBoard_create(lua_State* tolua_S) { if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.BillBoard:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.BillBoard:create"); if (!ok) { break; } cocos2d::BillBoard* ret = cocos2d::BillBoard::create(arg0); object_to_luaval(tolua_S, "cc.BillBoard",(cocos2d::BillBoard*)ret); @@ -1654,8 +1654,8 @@ int lua_cocos2dx_3d_BillBoard_create(lua_State* tolua_S) { if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.BillBoard:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.BillBoard:create"); if (!ok) { break; } cocos2d::BillBoard::Mode arg1; ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "cc.BillBoard:create"); @@ -1693,8 +1693,8 @@ int lua_cocos2dx_3d_BillBoard_create(lua_State* tolua_S) { if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.BillBoard:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.BillBoard:create"); if (!ok) { break; } cocos2d::Rect arg1; ok &= luaval_to_rect(tolua_S, 3, &arg1, "cc.BillBoard:create"); @@ -1709,8 +1709,8 @@ int lua_cocos2dx_3d_BillBoard_create(lua_State* tolua_S) { if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.BillBoard:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.BillBoard:create"); if (!ok) { break; } cocos2d::Rect arg1; ok &= luaval_to_rect(tolua_S, 3, &arg1, "cc.BillBoard:create"); @@ -2071,8 +2071,8 @@ int lua_cocos2dx_3d_Mesh_getName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Mesh_getName'", nullptr); return 0; } - const std::string& ret = cobj->getName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Mesh:getName",argc, 0); @@ -2325,9 +2325,9 @@ int lua_cocos2dx_3d_Mesh_setName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Mesh:setName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Mesh:setName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Mesh_setName'", nullptr); @@ -2938,9 +2938,9 @@ int lua_cocos2dx_3d_Skeleton3D_getBoneByName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Skeleton3D:getBoneByName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Skeleton3D:getBoneByName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Skeleton3D_getBoneByName'", nullptr); @@ -3392,24 +3392,24 @@ int lua_cocos2dx_3d_Skybox_init(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 6) { - std::string arg0; - std::string arg1; - std::string arg2; - std::string arg3; - std::string arg4; - std::string arg5; + std::string_view arg0; + std::string_view arg1; + std::string_view arg2; + std::string_view arg3; + std::string_view arg4; + std::string_view arg5; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Skybox:init"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Skybox:init"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Skybox:init"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Skybox:init"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "cc.Skybox:init"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "cc.Skybox:init"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "cc.Skybox:init"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "cc.Skybox:init"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "cc.Skybox:init"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "cc.Skybox:init"); - ok &= luaval_to_std_string(tolua_S, 7,&arg5, "cc.Skybox:init"); + ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "cc.Skybox:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Skybox_init'", nullptr); @@ -3497,23 +3497,23 @@ int lua_cocos2dx_3d_Skybox_create(lua_State* tolua_S) { if (argc == 6) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Skybox:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Skybox:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Skybox:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Skybox:create"); if (!ok) { break; } - std::string arg2; - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "cc.Skybox:create"); + std::string_view arg2; + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "cc.Skybox:create"); if (!ok) { break; } - std::string arg3; - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "cc.Skybox:create"); + std::string_view arg3; + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "cc.Skybox:create"); if (!ok) { break; } - std::string arg4; - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "cc.Skybox:create"); + std::string_view arg4; + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "cc.Skybox:create"); if (!ok) { break; } - std::string arg5; - ok &= luaval_to_std_string(tolua_S, 7,&arg5, "cc.Skybox:create"); + std::string_view arg5; + ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "cc.Skybox:create"); if (!ok) { break; } cocos2d::Skybox* ret = cocos2d::Skybox::create(arg0, arg1, arg2, arg3, arg4, arg5); object_to_luaval(tolua_S, "cc.Skybox",(cocos2d::Skybox*)ret); @@ -3685,8 +3685,8 @@ int lua_cocos2dx_3d_Sprite3D_setTexture(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite3D:setTexture"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite3D:setTexture"); if (!ok) { break; } cobj->setTexture(arg0); @@ -4321,9 +4321,9 @@ int lua_cocos2dx_3d_Sprite3D_getAttachNode(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite3D:getAttachNode"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite3D:getAttachNode"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Sprite3D_getAttachNode'", nullptr); @@ -4532,9 +4532,9 @@ int lua_cocos2dx_3d_Sprite3D_removeAttachNode(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite3D:removeAttachNode"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite3D:removeAttachNode"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Sprite3D_removeAttachNode'", nullptr); @@ -4679,9 +4679,9 @@ int lua_cocos2dx_3d_Sprite3D_getMeshByName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite3D:getMeshByName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite3D:getMeshByName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Sprite3D_getMeshByName'", nullptr); @@ -4719,8 +4719,8 @@ int lua_cocos2dx_3d_Sprite3D_create(lua_State* tolua_S) { if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite3D:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite3D:create"); if (!ok) { break; } cocos2d::Sprite3D* ret = cocos2d::Sprite3D::create(arg0); object_to_luaval(tolua_S, "cc.Sprite3D",(cocos2d::Sprite3D*)ret); @@ -4742,11 +4742,11 @@ int lua_cocos2dx_3d_Sprite3D_create(lua_State* tolua_S) { if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite3D:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite3D:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Sprite3D:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Sprite3D:create"); if (!ok) { break; } cocos2d::Sprite3D* ret = cocos2d::Sprite3D::create(arg0, arg1); object_to_luaval(tolua_S, "cc.Sprite3D",(cocos2d::Sprite3D*)ret); @@ -4832,9 +4832,9 @@ int lua_cocos2dx_3d_Sprite3DCache_removeSprite3DData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite3DCache:removeSprite3DData"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite3DCache:removeSprite3DData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Sprite3DCache_removeSprite3DData'", nullptr); @@ -5092,8 +5092,8 @@ int lua_cocos2dx_3d_Sprite3DMaterial_createWithFilename(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite3DMaterial:createWithFilename"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite3DMaterial:createWithFilename"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Sprite3DMaterial_createWithFilename'", nullptr); @@ -5316,9 +5316,9 @@ int lua_cocos2dx_3d_Terrain_initHeightMap(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Terrain:initHeightMap"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Terrain:initHeightMap"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Terrain_initHeightMap'", nullptr); @@ -5567,9 +5567,9 @@ int lua_cocos2dx_3d_Terrain_resetHeightMap(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Terrain:resetHeightMap"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Terrain:resetHeightMap"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Terrain_resetHeightMap'", nullptr); @@ -6026,8 +6026,8 @@ int lua_cocos2dx_3d_Terrain_getTerrainSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Terrain_getTerrainSize'", nullptr); return 0; } - cocos2d::Size ret = cobj->getTerrainSize(); - size_to_luaval(tolua_S, ret); + cocos2d::Vec2 ret = cobj->getTerrainSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Terrain:getTerrainSize",argc, 0); @@ -6221,9 +6221,9 @@ int lua_cocos2dx_3d_Terrain_setLightMap(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Terrain:setLightMap"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Terrain:setLightMap"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Terrain_setLightMap'", nullptr); @@ -6494,9 +6494,9 @@ int lua_cocos2dx_3d_Bundle3D_load(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Bundle3D:load"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Bundle3D:load"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Bundle3D_load'", nullptr); @@ -6544,10 +6544,10 @@ int lua_cocos2dx_3d_Bundle3D_loadSkinData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::SkinData* arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Bundle3D:loadSkinData"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Bundle3D:loadSkinData"); #pragma warning NO CONVERSION TO NATIVE FOR SkinData* ok = false; @@ -6747,10 +6747,10 @@ int lua_cocos2dx_3d_Bundle3D_loadAnimationData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::Animation3DData* arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Bundle3D:loadAnimationData"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Bundle3D:loadAnimationData"); #pragma warning NO CONVERSION TO NATIVE FOR Animation3DData* ok = false; @@ -6790,8 +6790,8 @@ int lua_cocos2dx_3d_Bundle3D_parseSamplerAddressMode(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Bundle3D:parseSamplerAddressMode"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Bundle3D:parseSamplerAddressMode"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_3d_Bundle3D_parseSamplerAddressMode'", nullptr); @@ -6896,9 +6896,9 @@ int lua_cocos2dx_3d_Bundle3D_parseGLDataType(lua_State* tolua_S) if (argc == 2) { - std::string arg0; + std::string_view arg0; int arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Bundle3D:parseGLDataType"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Bundle3D:parseGLDataType"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "cc.Bundle3D:parseGLDataType"); if(!ok) { diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_audioengine_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_audioengine_auto.cpp index c468bc15a430..fbc51b00723d 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_audioengine_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_audioengine_auto.cpp @@ -184,8 +184,8 @@ int lua_cocos2dx_audioengine_AudioEngine_uncache(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AudioEngine:uncache"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AudioEngine:uncache"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_audioengine_AudioEngine_uncache'", nullptr); @@ -607,8 +607,8 @@ int lua_cocos2dx_audioengine_AudioEngine_preload(lua_State* tolua_S) { if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AudioEngine:preload"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AudioEngine:preload"); if (!ok) { break; } std::function arg1; do { @@ -627,8 +627,8 @@ int lua_cocos2dx_audioengine_AudioEngine_preload(lua_State* tolua_S) { if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AudioEngine:preload"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AudioEngine:preload"); if (!ok) { break; } cocos2d::AudioEngine::preload(arg0); lua_settop(tolua_S, 1); @@ -697,8 +697,8 @@ int lua_cocos2dx_audioengine_AudioEngine_play2d(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AudioEngine:play2d"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AudioEngine:play2d"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_audioengine_AudioEngine_play2d'", nullptr); @@ -710,9 +710,9 @@ int lua_cocos2dx_audioengine_AudioEngine_play2d(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; bool arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AudioEngine:play2d"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AudioEngine:play2d"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.AudioEngine:play2d"); if(!ok) { @@ -725,10 +725,10 @@ int lua_cocos2dx_audioengine_AudioEngine_play2d(lua_State* tolua_S) } if (argc == 3) { - std::string arg0; + std::string_view arg0; bool arg1; double arg2; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AudioEngine:play2d"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AudioEngine:play2d"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.AudioEngine:play2d"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.AudioEngine:play2d"); if(!ok) @@ -742,11 +742,11 @@ int lua_cocos2dx_audioengine_AudioEngine_play2d(lua_State* tolua_S) } if (argc == 4) { - std::string arg0; + std::string_view arg0; bool arg1; double arg2; const cocos2d::AudioProfile* arg3; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AudioEngine:play2d"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AudioEngine:play2d"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.AudioEngine:play2d"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.AudioEngine:play2d"); ok &= luaval_to_object(tolua_S, 5, "cc.AudioProfile",&arg3, "cc.AudioEngine:play2d"); @@ -1035,8 +1035,8 @@ int lua_cocos2dx_audioengine_AudioEngine_getProfile(lua_State* tolua_S) { if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AudioEngine:getProfile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AudioEngine:getProfile"); if (!ok) { break; } cocos2d::AudioProfile* ret = cocos2d::AudioEngine::getProfile(arg0); object_to_luaval(tolua_S, "cc.AudioProfile",(cocos2d::AudioProfile*)ret); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp index ea1bbd26b656..8a8ea3665c9c 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp @@ -300,9 +300,9 @@ int lua_cocos2dx_Console_delCommand(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Console:delCommand"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Console:delCommand"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Console_delCommand'", nullptr); @@ -497,9 +497,9 @@ int lua_cocos2dx_Console_setBindAddress(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Console:setBindAddress"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Console:setBindAddress"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Console_setBindAddress'", nullptr); @@ -962,8 +962,8 @@ int lua_cocos2dx_ShaderCache_newVertexShaderModule(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccb.ShaderCache:newVertexShaderModule"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccb.ShaderCache:newVertexShaderModule"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ShaderCache_newVertexShaderModule'", nullptr); @@ -998,8 +998,8 @@ int lua_cocos2dx_ShaderCache_newFragmentShaderModule(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccb.ShaderCache:newFragmentShaderModule"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccb.ShaderCache:newFragmentShaderModule"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ShaderCache_newFragmentShaderModule'", nullptr); @@ -1648,8 +1648,8 @@ int lua_cocos2dx_Texture2D_initWithString(lua_State* tolua_S) std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "cc.Texture2D:initWithString"); arg0 = arg0_tmp.c_str(); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); if (!ok) { break; } double arg2; @@ -1668,16 +1668,16 @@ int lua_cocos2dx_Texture2D_initWithString(lua_State* tolua_S) std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "cc.Texture2D:initWithString"); arg0 = arg0_tmp.c_str(); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); if (!ok) { break; } double arg2; ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Texture2D:initWithString"); if (!ok) { break; } - cocos2d::Size arg3; - ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Texture2D:initWithString"); + cocos2d::Vec2 arg3; + ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Texture2D:initWithString"); if (!ok) { break; } bool ret = cobj->initWithString(arg0, arg1, arg2, arg3); @@ -1692,16 +1692,16 @@ int lua_cocos2dx_Texture2D_initWithString(lua_State* tolua_S) std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "cc.Texture2D:initWithString"); arg0 = arg0_tmp.c_str(); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); if (!ok) { break; } double arg2; ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Texture2D:initWithString"); if (!ok) { break; } - cocos2d::Size arg3; - ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Texture2D:initWithString"); + cocos2d::Vec2 arg3; + ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Texture2D:initWithString"); if (!ok) { break; } cocos2d::TextHAlignment arg4; @@ -1720,16 +1720,16 @@ int lua_cocos2dx_Texture2D_initWithString(lua_State* tolua_S) std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "cc.Texture2D:initWithString"); arg0 = arg0_tmp.c_str(); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); if (!ok) { break; } double arg2; ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Texture2D:initWithString"); if (!ok) { break; } - cocos2d::Size arg3; - ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Texture2D:initWithString"); + cocos2d::Vec2 arg3; + ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Texture2D:initWithString"); if (!ok) { break; } cocos2d::TextHAlignment arg4; @@ -1752,16 +1752,16 @@ int lua_cocos2dx_Texture2D_initWithString(lua_State* tolua_S) std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "cc.Texture2D:initWithString"); arg0 = arg0_tmp.c_str(); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); if (!ok) { break; } double arg2; ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Texture2D:initWithString"); if (!ok) { break; } - cocos2d::Size arg3; - ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Texture2D:initWithString"); + cocos2d::Vec2 arg3; + ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Texture2D:initWithString"); if (!ok) { break; } cocos2d::TextHAlignment arg4; @@ -1788,16 +1788,16 @@ int lua_cocos2dx_Texture2D_initWithString(lua_State* tolua_S) std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "cc.Texture2D:initWithString"); arg0 = arg0_tmp.c_str(); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Texture2D:initWithString"); if (!ok) { break; } double arg2; ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Texture2D:initWithString"); if (!ok) { break; } - cocos2d::Size arg3; - ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Texture2D:initWithString"); + cocos2d::Vec2 arg3; + ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Texture2D:initWithString"); if (!ok) { break; } cocos2d::TextHAlignment arg4; @@ -2062,8 +2062,8 @@ int lua_cocos2dx_Texture2D_getContentSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Texture2D_getContentSize'", nullptr); return 0; } - cocos2d::Size ret = cobj->getContentSize(); - size_to_luaval(tolua_S, ret); + cocos2d::Vec2 ret = cobj->getContentSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Texture2D:getContentSize",argc, 0); @@ -2463,8 +2463,8 @@ int lua_cocos2dx_Texture2D_getContentSizeInPixels(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Texture2D_getContentSizeInPixels'", nullptr); return 0; } - const cocos2d::Size& ret = cobj->getContentSizeInPixels(); - size_to_luaval(tolua_S, ret); + const cocos2d::Vec2& ret = cobj->getContentSizeInPixels(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Texture2D:getContentSizeInPixels",argc, 0); @@ -4259,9 +4259,9 @@ int lua_cocos2dx_Component_setName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Component:setName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Component:setName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Component_setName'", nullptr); @@ -4555,8 +4555,8 @@ int lua_cocos2dx_Component_getName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Component_getName'", nullptr); return 0; } - const std::string& ret = cobj->getName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Component:getName",argc, 0); @@ -4759,8 +4759,8 @@ int lua_cocos2dx_Node_addChild(lua_State* tolua_S) ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "cc.Node:addChild"); if (!ok) { break; } - std::string arg2; - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "cc.Node:addChild"); + std::string_view arg2; + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "cc.Node:addChild"); if (!ok) { break; } cobj->addChild(arg0, arg1, arg2); @@ -4814,8 +4814,8 @@ int lua_cocos2dx_Node_removeComponent(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Node:removeComponent"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Node:removeComponent"); if (!ok) { break; } bool ret = cobj->removeComponent(arg0); @@ -5454,9 +5454,9 @@ int lua_cocos2dx_Node_getChildByName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Node:getChildByName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Node:getChildByName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Node_getChildByName'", nullptr); @@ -7147,8 +7147,8 @@ int lua_cocos2dx_Node_getName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Node_getName'", nullptr); return 0; } - const std::string& ret = cobj->getName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Node:getName",argc, 0); @@ -8525,9 +8525,9 @@ int lua_cocos2dx_Node_removeChildByName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Node:removeChildByName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Node:removeChildByName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Node_removeChildByName'", nullptr); @@ -8539,10 +8539,10 @@ int lua_cocos2dx_Node_removeChildByName(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; bool arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Node:removeChildByName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Node:removeChildByName"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.Node:removeChildByName"); if(!ok) @@ -8564,6 +8564,59 @@ int lua_cocos2dx_Node_removeChildByName(lua_State* tolua_S) return 0; } +int lua_cocos2dx_Node_resetChild(lua_State* tolua_S) +{ + int argc = 0; + cocos2d::Node* cobj = nullptr; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(tolua_S,1,"cc.Node",0,&tolua_err)) goto tolua_lerror; +#endif + + cobj = (cocos2d::Node*)tolua_tousertype(tolua_S,1,0); + +#if COCOS2D_DEBUG >= 1 + if (!cobj) + { + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_Node_resetChild'", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S)-1; + if (argc == 2) + { + cocos2d::Node* arg0; + bool arg1; + + ok &= luaval_to_object(tolua_S, 2, "cc.Node",&arg0, "cc.Node:resetChild"); + + ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.Node:resetChild"); + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Node_resetChild'", nullptr); + return 0; + } + cobj->resetChild(arg0, arg1); + lua_settop(tolua_S, 1); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Node:resetChild",argc, 2); + return 0; + +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_Node_resetChild'.",&tolua_err); +#endif + + return 0; +} int lua_cocos2dx_Node_setScheduler(lua_State* tolua_S) { int argc = 0; @@ -8927,9 +8980,9 @@ int lua_cocos2dx_Node_setName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Node:setName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Node:setName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Node_setName'", nullptr); @@ -9861,9 +9914,9 @@ int lua_cocos2dx_Node_isScheduled(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Node:isScheduled"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Node:isScheduled"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Node_isScheduled'", nullptr); @@ -10455,9 +10508,9 @@ int lua_cocos2dx_Node_getComponent(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Node:getComponent"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Node:getComponent"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Node_getComponent'", nullptr); @@ -10510,8 +10563,8 @@ int lua_cocos2dx_Node_getContentSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Node_getContentSize'", nullptr); return 0; } - const cocos2d::Size& ret = cobj->getContentSize(); - size_to_luaval(tolua_S, ret); + const cocos2d::Vec2& ret = cobj->getContentSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Node:getContentSize",argc, 0); @@ -11940,6 +11993,7 @@ int lua_register_cocos2dx_Node(lua_State* tolua_S) tolua_function(tolua_S,"getPhysicsBody",lua_cocos2dx_Node_getPhysicsBody); tolua_function(tolua_S,"getAnchorPointInPoints",lua_cocos2dx_Node_getAnchorPointInPoints); tolua_function(tolua_S,"removeChildByName",lua_cocos2dx_Node_removeChildByName); + tolua_function(tolua_S,"resetChild",lua_cocos2dx_Node_resetChild); tolua_function(tolua_S,"setScheduler",lua_cocos2dx_Node_setScheduler); tolua_function(tolua_S,"stopAllActions",lua_cocos2dx_Node_stopAllActions); tolua_function(tolua_S,"getSkewX",lua_cocos2dx_Node_getSkewX); @@ -12403,9 +12457,9 @@ int lua_cocos2dx_Scene_initWithSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.Scene:initWithSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.Scene:initWithSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Scene_initWithSize'", nullptr); @@ -12489,8 +12543,8 @@ int lua_cocos2dx_Scene_createWithSize(lua_State* tolua_S) if (argc == 1) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.Scene:createWithSize"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.Scene:createWithSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Scene_createWithSize'", nullptr); @@ -13078,8 +13132,8 @@ int lua_cocos2dx_GLView_getViewName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_GLView_getViewName'", nullptr); return 0; } - const std::string& ret = cobj->getViewName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getViewName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.GLView:getViewName",argc, 0); @@ -13222,8 +13276,8 @@ int lua_cocos2dx_GLView_getFrameSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_GLView_getFrameSize'", nullptr); return 0; } - cocos2d::Size ret = cobj->getFrameSize(); - size_to_luaval(tolua_S, ret); + cocos2d::Vec2 ret = cobj->getFrameSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.GLView:getFrameSize",argc, 0); @@ -13507,8 +13561,8 @@ int lua_cocos2dx_GLView_getDesignResolutionSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_GLView_getDesignResolutionSize'", nullptr); return 0; } - const cocos2d::Size& ret = cobj->getDesignResolutionSize(); - size_to_luaval(tolua_S, ret); + const cocos2d::Vec2& ret = cobj->getDesignResolutionSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.GLView:getDesignResolutionSize",argc, 0); @@ -13544,8 +13598,8 @@ int lua_cocos2dx_GLView_setIcon(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 1) { - std::vector arg0; - ok &= luaval_to_std_vector_string(tolua_S, 2, &arg0, "cc.GLView:setIcon"); + std::vector arg0; + ok &= luaval_to_std_vector_string_view(tolua_S, 2, &arg0, "cc.GLView:setIcon"); if (!ok) { break; } cobj->setIcon(arg0); @@ -13556,8 +13610,8 @@ int lua_cocos2dx_GLView_setIcon(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.GLView:setIcon"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.GLView:setIcon"); if (!ok) { break; } cobj->setIcon(arg0); @@ -14101,9 +14155,9 @@ int lua_cocos2dx_GLView_setViewName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.GLView:setViewName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.GLView:setViewName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_GLView_setViewName'", nullptr); @@ -14203,8 +14257,8 @@ int lua_cocos2dx_GLView_getVisibleSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_GLView_getVisibleSize'", nullptr); return 0; } - cocos2d::Size ret = cobj->getVisibleSize(); - size_to_luaval(tolua_S, ret); + cocos2d::Vec2 ret = cobj->getVisibleSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.GLView:getVisibleSize",argc, 0); @@ -14711,8 +14765,8 @@ int lua_cocos2dx_Director_getWinSizeInPixels(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Director_getWinSizeInPixels'", nullptr); return 0; } - cocos2d::Size ret = cobj->getWinSizeInPixels(); - size_to_luaval(tolua_S, ret); + cocos2d::Vec2 ret = cobj->getWinSizeInPixels(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Director:getWinSizeInPixels",argc, 0); @@ -15049,8 +15103,8 @@ int lua_cocos2dx_Director_getWinSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Director_getWinSize'", nullptr); return 0; } - const cocos2d::Size& ret = cobj->getWinSize(); - size_to_luaval(tolua_S, ret); + const cocos2d::Vec2& ret = cobj->getWinSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Director:getWinSize",argc, 0); @@ -16163,6 +16217,53 @@ int lua_cocos2dx_Director_isNextDeltaTimeZero(lua_State* tolua_S) return 0; } +int lua_cocos2dx_Director_isChildrenIndexerEnabled(lua_State* tolua_S) +{ + int argc = 0; + cocos2d::Director* cobj = nullptr; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(tolua_S,1,"cc.Director",0,&tolua_err)) goto tolua_lerror; +#endif + + cobj = (cocos2d::Director*)tolua_tousertype(tolua_S,1,0); + +#if COCOS2D_DEBUG >= 1 + if (!cobj) + { + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_Director_isChildrenIndexerEnabled'", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S)-1; + if (argc == 0) + { + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Director_isChildrenIndexerEnabled'", nullptr); + return 0; + } + bool ret = cobj->isChildrenIndexerEnabled(); + tolua_pushboolean(tolua_S,(bool)ret); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Director:isChildrenIndexerEnabled",argc, 0); + return 0; + +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_Director_isChildrenIndexerEnabled'.",&tolua_err); +#endif + + return 0; +} int lua_cocos2dx_Director_setClearColor(lua_State* tolua_S) { int argc = 0; @@ -16554,6 +16655,56 @@ int lua_cocos2dx_Director_setNotificationNode(lua_State* tolua_S) return 0; } +int lua_cocos2dx_Director_setChildrenIndexerEnabled(lua_State* tolua_S) +{ + int argc = 0; + cocos2d::Director* cobj = nullptr; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(tolua_S,1,"cc.Director",0,&tolua_err)) goto tolua_lerror; +#endif + + cobj = (cocos2d::Director*)tolua_tousertype(tolua_S,1,0); + +#if COCOS2D_DEBUG >= 1 + if (!cobj) + { + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_Director_setChildrenIndexerEnabled'", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S)-1; + if (argc == 1) + { + bool arg0; + + ok &= luaval_to_boolean(tolua_S, 2,&arg0, "cc.Director:setChildrenIndexerEnabled"); + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Director_setChildrenIndexerEnabled'", nullptr); + return 0; + } + cobj->setChildrenIndexerEnabled(arg0); + lua_settop(tolua_S, 1); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Director:setChildrenIndexerEnabled",argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_Director_setChildrenIndexerEnabled'.",&tolua_err); +#endif + + return 0; +} int lua_cocos2dx_Director_drawScene(lua_State* tolua_S) { int argc = 0; @@ -17122,8 +17273,8 @@ int lua_cocos2dx_Director_getVisibleSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Director_getVisibleSize'", nullptr); return 0; } - cocos2d::Size ret = cobj->getVisibleSize(); - size_to_luaval(tolua_S, ret); + cocos2d::Vec2 ret = cobj->getVisibleSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Director:getVisibleSize",argc, 0); @@ -17653,6 +17804,7 @@ int lua_register_cocos2dx_Director(lua_State* tolua_S) tolua_function(tolua_S,"popToSceneStackLevel",lua_cocos2dx_Director_popToSceneStackLevel); tolua_function(tolua_S,"resume",lua_cocos2dx_Director_resume); tolua_function(tolua_S,"isNextDeltaTimeZero",lua_cocos2dx_Director_isNextDeltaTimeZero); + tolua_function(tolua_S,"isChildrenIndexerEnabled",lua_cocos2dx_Director_isChildrenIndexerEnabled); tolua_function(tolua_S,"setClearColor",lua_cocos2dx_Director_setClearColor); tolua_function(tolua_S,"endToLua",lua_cocos2dx_Director_end); tolua_function(tolua_S,"setOpenGLView",lua_cocos2dx_Director_setOpenGLView); @@ -17661,6 +17813,7 @@ int lua_register_cocos2dx_Director(lua_State* tolua_S) tolua_function(tolua_S,"getTotalFrames",lua_cocos2dx_Director_getTotalFrames); tolua_function(tolua_S,"runWithScene",lua_cocos2dx_Director_runWithScene); tolua_function(tolua_S,"setNotificationNode",lua_cocos2dx_Director_setNotificationNode); + tolua_function(tolua_S,"setChildrenIndexerEnabled",lua_cocos2dx_Director_setChildrenIndexerEnabled); tolua_function(tolua_S,"drawScene",lua_cocos2dx_Director_drawScene); tolua_function(tolua_S,"restart",lua_cocos2dx_Director_restart); tolua_function(tolua_S,"popScene",lua_cocos2dx_Director_popScene); @@ -20524,9 +20677,9 @@ int lua_cocos2dx_Image_initWithImageFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Image:initWithImageFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Image:initWithImageFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Image_initWithImageFile'", nullptr); @@ -20809,9 +20962,9 @@ int lua_cocos2dx_Image_saveToFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Image:saveToFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Image:saveToFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Image_saveToFile'", nullptr); @@ -20823,10 +20976,10 @@ int lua_cocos2dx_Image_saveToFile(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; bool arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Image:saveToFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Image:saveToFile"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.Image:saveToFile"); if(!ok) @@ -21065,8 +21218,8 @@ int lua_cocos2dx_PolygonInfo_getFilename(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_PolygonInfo_getFilename'", nullptr); return 0; } - const std::string& ret = cobj->getFilename(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getFilename(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.PolygonInfo:getFilename",argc, 0); @@ -21201,9 +21354,9 @@ int lua_cocos2dx_PolygonInfo_setFilename(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.PolygonInfo:setFilename"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.PolygonInfo:setFilename"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_PolygonInfo_setFilename'", nullptr); @@ -21603,9 +21756,9 @@ int lua_cocos2dx_AutoPolygon_constructor(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AutoPolygon:AutoPolygon"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AutoPolygon:AutoPolygon"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_AutoPolygon_constructor'", nullptr); @@ -21876,8 +22029,8 @@ int lua_cocos2dx_SpriteFrame_getOriginalSizeInPixels(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrame_getOriginalSizeInPixels'", nullptr); return 0; } - const cocos2d::Size& ret = cobj->getOriginalSizeInPixels(); - size_to_luaval(tolua_S, ret); + const cocos2d::Vec2& ret = cobj->getOriginalSizeInPixels(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.SpriteFrame:getOriginalSizeInPixels",argc, 0); @@ -21918,9 +22071,9 @@ int lua_cocos2dx_SpriteFrame_setOriginalSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.SpriteFrame:setOriginalSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.SpriteFrame:setOriginalSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrame_setOriginalSize'", nullptr); @@ -22207,8 +22360,8 @@ int lua_cocos2dx_SpriteFrame_initWithTextureFilename(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 5) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrame:initWithTextureFilename"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrame:initWithTextureFilename"); if (!ok) { break; } cocos2d::Rect arg1; @@ -22223,8 +22376,8 @@ int lua_cocos2dx_SpriteFrame_initWithTextureFilename(lua_State* tolua_S) ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.SpriteFrame:initWithTextureFilename"); if (!ok) { break; } - cocos2d::Size arg4; - ok &= luaval_to_size(tolua_S, 6, &arg4, "cc.SpriteFrame:initWithTextureFilename"); + cocos2d::Vec2 arg4; + ok &= luaval_to_vec2(tolua_S, 6, &arg4, "cc.SpriteFrame:initWithTextureFilename"); if (!ok) { break; } bool ret = cobj->initWithTextureFilename(arg0, arg1, arg2, arg3, arg4); @@ -22235,8 +22388,8 @@ int lua_cocos2dx_SpriteFrame_initWithTextureFilename(lua_State* tolua_S) ok = true; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrame:initWithTextureFilename"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrame:initWithTextureFilename"); if (!ok) { break; } cocos2d::Rect arg1; @@ -22348,8 +22501,8 @@ int lua_cocos2dx_SpriteFrame_initWithTexture(lua_State* tolua_S) ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.SpriteFrame:initWithTexture"); if (!ok) { break; } - cocos2d::Size arg4; - ok &= luaval_to_size(tolua_S, 6, &arg4, "cc.SpriteFrame:initWithTexture"); + cocos2d::Vec2 arg4; + ok &= luaval_to_vec2(tolua_S, 6, &arg4, "cc.SpriteFrame:initWithTexture"); if (!ok) { break; } bool ret = cobj->initWithTexture(arg0, arg1, arg2, arg3, arg4); @@ -22417,8 +22570,8 @@ int lua_cocos2dx_SpriteFrame_getOriginalSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrame_getOriginalSize'", nullptr); return 0; } - const cocos2d::Size& ret = cobj->getOriginalSize(); - size_to_luaval(tolua_S, ret); + const cocos2d::Vec2& ret = cobj->getOriginalSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.SpriteFrame:getOriginalSize",argc, 0); @@ -22744,9 +22897,9 @@ int lua_cocos2dx_SpriteFrame_setOriginalSizeInPixels(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.SpriteFrame:setOriginalSizeInPixels"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.SpriteFrame:setOriginalSizeInPixels"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrame_setOriginalSizeInPixels'", nullptr); @@ -22925,8 +23078,8 @@ int lua_cocos2dx_SpriteFrame_create(lua_State* tolua_S) { if (argc == 5) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrame:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrame:create"); if (!ok) { break; } cocos2d::Rect arg1; ok &= luaval_to_rect(tolua_S, 3, &arg1, "cc.SpriteFrame:create"); @@ -22937,8 +23090,8 @@ int lua_cocos2dx_SpriteFrame_create(lua_State* tolua_S) cocos2d::Vec2 arg3; ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.SpriteFrame:create"); if (!ok) { break; } - cocos2d::Size arg4; - ok &= luaval_to_size(tolua_S, 6, &arg4, "cc.SpriteFrame:create"); + cocos2d::Vec2 arg4; + ok &= luaval_to_vec2(tolua_S, 6, &arg4, "cc.SpriteFrame:create"); if (!ok) { break; } cocos2d::SpriteFrame* ret = cocos2d::SpriteFrame::create(arg0, arg1, arg2, arg3, arg4); object_to_luaval(tolua_S, "cc.SpriteFrame",(cocos2d::SpriteFrame*)ret); @@ -22950,8 +23103,8 @@ int lua_cocos2dx_SpriteFrame_create(lua_State* tolua_S) { if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrame:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrame:create"); if (!ok) { break; } cocos2d::Rect arg1; ok &= luaval_to_rect(tolua_S, 3, &arg1, "cc.SpriteFrame:create"); @@ -23000,8 +23153,8 @@ int lua_cocos2dx_SpriteFrame_createWithTexture(lua_State* tolua_S) cocos2d::Vec2 arg3; ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.SpriteFrame:createWithTexture"); if (!ok) { break; } - cocos2d::Size arg4; - ok &= luaval_to_size(tolua_S, 6, &arg4, "cc.SpriteFrame:createWithTexture"); + cocos2d::Vec2 arg4; + ok &= luaval_to_vec2(tolua_S, 6, &arg4, "cc.SpriteFrame:createWithTexture"); if (!ok) { break; } cocos2d::SpriteFrame* ret = cocos2d::SpriteFrame::createWithTexture(arg0, arg1, arg2, arg3, arg4); object_to_luaval(tolua_S, "cc.SpriteFrame",(cocos2d::SpriteFrame*)ret); @@ -24186,9 +24339,9 @@ int lua_cocos2dx_Animation_addSpriteFrameWithFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Animation:addSpriteFrameWithFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Animation:addSpriteFrameWithFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Animation_addSpriteFrameWithFile'", nullptr); @@ -31325,12 +31478,12 @@ int lua_cocos2dx_UserDefault_getStringForKey(lua_State* tolua_S) std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "cc.UserDefault:getStringForKey"); arg0 = arg0_tmp.c_str(); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.UserDefault:getStringForKey"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.UserDefault:getStringForKey"); if (!ok) { break; } - std::string ret = cobj->getStringForKey(arg0, arg1); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getStringForKey(arg0, arg1); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } }while(0); @@ -31341,8 +31494,8 @@ int lua_cocos2dx_UserDefault_getStringForKey(lua_State* tolua_S) std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "cc.UserDefault:getStringForKey"); arg0 = arg0_tmp.c_str(); if (!ok) { break; } - std::string ret = cobj->getStringForKey(arg0); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getStringForKey(arg0); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } }while(0); @@ -31386,11 +31539,11 @@ int lua_cocos2dx_UserDefault_setStringForKey(lua_State* tolua_S) if (argc == 2) { const char* arg0; - std::string arg1; + std::string_view arg1; std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "cc.UserDefault:setStringForKey"); arg0 = arg0_tmp.c_str(); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.UserDefault:setStringForKey"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.UserDefault:setStringForKey"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_UserDefault_setStringForKey'", nullptr); @@ -31498,8 +31651,8 @@ int lua_cocos2dx_UserDefault_setEncryptEnabled(lua_State* tolua_S) if (argc == 3) { bool arg0; - cxx17::string_view arg1; - cxx17::string_view arg2; + std::string_view arg1; + std::string_view arg2; ok &= luaval_to_boolean(tolua_S, 2,&arg0, "cc.UserDefault:setEncryptEnabled"); @@ -31843,9 +31996,9 @@ int lua_cocos2dx_FileUtils_fullPathForFilename(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:fullPathForFilename"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:fullPathForFilename"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_fullPathForFilename'", nullptr); @@ -31888,8 +32041,8 @@ int lua_cocos2dx_FileUtils_getStringFromFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:getStringFromFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:getStringFromFile"); if (!ok) { break; } std::function arg1; @@ -31908,8 +32061,8 @@ int lua_cocos2dx_FileUtils_getStringFromFile(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:getStringFromFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:getStringFromFile"); if (!ok) { break; } std::string ret = cobj->getStringFromFile(arg0); @@ -32048,8 +32201,8 @@ int lua_cocos2dx_FileUtils_removeFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:removeFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:removeFile"); if (!ok) { break; } std::function arg1; @@ -32068,8 +32221,8 @@ int lua_cocos2dx_FileUtils_removeFile(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:removeFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:removeFile"); if (!ok) { break; } bool ret = cobj->removeFile(arg0); @@ -32116,10 +32269,10 @@ int lua_cocos2dx_FileUtils_listFilesRecursivelyAsync(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; + std::string_view arg0; std::function)> arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:listFilesRecursivelyAsync"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:listFilesRecursivelyAsync"); do { // Lambda binding for lua is not supported. @@ -32173,9 +32326,9 @@ int lua_cocos2dx_FileUtils_isAbsolutePath(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:isAbsolutePath"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:isAbsolutePath"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_isAbsolutePath'", nullptr); @@ -32218,16 +32371,16 @@ int lua_cocos2dx_FileUtils_renameFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 4) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:renameFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:renameFile"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:renameFile"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:renameFile"); if (!ok) { break; } - std::string arg2; - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "cc.FileUtils:renameFile"); + std::string_view arg2; + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "cc.FileUtils:renameFile"); if (!ok) { break; } std::function arg3; @@ -32246,16 +32399,16 @@ int lua_cocos2dx_FileUtils_renameFile(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:renameFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:renameFile"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:renameFile"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:renameFile"); if (!ok) { break; } - std::string arg2; - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "cc.FileUtils:renameFile"); + std::string_view arg2; + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "cc.FileUtils:renameFile"); if (!ok) { break; } bool ret = cobj->renameFile(arg0, arg1, arg2); @@ -32266,12 +32419,12 @@ int lua_cocos2dx_FileUtils_renameFile(lua_State* tolua_S) ok = true; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:renameFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:renameFile"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:renameFile"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:renameFile"); if (!ok) { break; } bool ret = cobj->renameFile(arg0, arg1); @@ -32282,12 +32435,12 @@ int lua_cocos2dx_FileUtils_renameFile(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:renameFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:renameFile"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:renameFile"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:renameFile"); if (!ok) { break; } std::function arg2; @@ -32389,9 +32542,9 @@ int lua_cocos2dx_FileUtils_loadFilenameLookupDictionaryFromFile(lua_State* tolua argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:loadFilenameLookupDictionaryFromFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:loadFilenameLookupDictionaryFromFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_loadFilenameLookupDictionaryFromFile'", nullptr); @@ -32486,9 +32639,9 @@ int lua_cocos2dx_FileUtils_getValueVectorFromFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:getValueVectorFromFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:getValueVectorFromFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_getValueVectorFromFile'", nullptr); @@ -32584,11 +32737,11 @@ int lua_cocos2dx_FileUtils_writeToFile(lua_State* tolua_S) if (argc == 2) { cocos2d::ValueMap arg0; - std::string arg1; + std::string_view arg1; ok &= luaval_to_ccvaluemap(tolua_S, 2, &arg0, "cc.FileUtils:writeToFile"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:writeToFile"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:writeToFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_writeToFile'", nullptr); @@ -32683,9 +32836,9 @@ int lua_cocos2dx_FileUtils_getNewFilename(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:getNewFilename"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:getNewFilename"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_getNewFilename'", nullptr); @@ -32733,9 +32886,9 @@ int lua_cocos2dx_FileUtils_listFiles(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:listFiles"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:listFiles"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_listFiles'", nullptr); @@ -32783,9 +32936,9 @@ int lua_cocos2dx_FileUtils_getValueMapFromFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:getValueMapFromFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:getValueMapFromFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_getValueMapFromFile'", nullptr); @@ -32828,8 +32981,8 @@ int lua_cocos2dx_FileUtils_getFileSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:getFileSize"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:getFileSize"); if (!ok) { break; } std::function arg1; @@ -32848,8 +33001,8 @@ int lua_cocos2dx_FileUtils_getFileSize(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:getFileSize"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:getFileSize"); if (!ok) { break; } long long ret = cobj->getFileSize(arg0); @@ -32944,8 +33097,8 @@ int lua_cocos2dx_FileUtils_removeDirectory(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:removeDirectory"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:removeDirectory"); if (!ok) { break; } std::function arg1; @@ -32964,8 +33117,8 @@ int lua_cocos2dx_FileUtils_removeDirectory(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:removeDirectory"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:removeDirectory"); if (!ok) { break; } bool ret = cobj->removeDirectory(arg0); @@ -33061,8 +33214,8 @@ int lua_cocos2dx_FileUtils_writeStringToFile(lua_State* tolua_S) ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:writeStringToFile"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:writeStringToFile"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:writeStringToFile"); if (!ok) { break; } std::function arg2; @@ -33081,12 +33234,12 @@ int lua_cocos2dx_FileUtils_writeStringToFile(lua_State* tolua_S) ok = true; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:writeStringToFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:writeStringToFile"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:writeStringToFile"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:writeStringToFile"); if (!ok) { break; } bool ret = cobj->writeStringToFile(arg0, arg1); @@ -33133,9 +33286,9 @@ int lua_cocos2dx_FileUtils_isFileExistInternal(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:isFileExistInternal"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:isFileExistInternal"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_isFileExistInternal'", nullptr); @@ -33233,9 +33386,9 @@ int lua_cocos2dx_FileUtils_addSearchResolutionsOrder(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:addSearchResolutionsOrder"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:addSearchResolutionsOrder"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_addSearchResolutionsOrder'", nullptr); @@ -33247,10 +33400,10 @@ int lua_cocos2dx_FileUtils_addSearchResolutionsOrder(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; bool arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:addSearchResolutionsOrder"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:addSearchResolutionsOrder"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.FileUtils:addSearchResolutionsOrder"); if(!ok) @@ -33300,9 +33453,9 @@ int lua_cocos2dx_FileUtils_addSearchPath(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:addSearchPath"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:addSearchPath"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_addSearchPath'", nullptr); @@ -33314,10 +33467,10 @@ int lua_cocos2dx_FileUtils_addSearchPath(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; bool arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:addSearchPath"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:addSearchPath"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.FileUtils:addSearchPath"); if(!ok) @@ -33366,8 +33519,8 @@ int lua_cocos2dx_FileUtils_writeValueVectorToFile(lua_State* tolua_S) ok &= luaval_to_ccvaluevector(tolua_S, 2, &arg0, "cc.FileUtils:writeValueVectorToFile"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:writeValueVectorToFile"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:writeValueVectorToFile"); if (!ok) { break; } std::function arg2; @@ -33390,8 +33543,8 @@ int lua_cocos2dx_FileUtils_writeValueVectorToFile(lua_State* tolua_S) ok &= luaval_to_ccvaluevector(tolua_S, 2, &arg0, "cc.FileUtils:writeValueVectorToFile"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:writeValueVectorToFile"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:writeValueVectorToFile"); if (!ok) { break; } bool ret = cobj->writeValueVectorToFile(arg0, arg1); @@ -33433,8 +33586,8 @@ int lua_cocos2dx_FileUtils_isFileExist(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:isFileExist"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:isFileExist"); if (!ok) { break; } std::function arg1; @@ -33453,8 +33606,8 @@ int lua_cocos2dx_FileUtils_isFileExist(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:isFileExist"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:isFileExist"); if (!ok) { break; } bool ret = cobj->isFileExist(arg0); @@ -33548,12 +33701,12 @@ int lua_cocos2dx_FileUtils_fullPathFromRelativeFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:fullPathFromRelativeFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:fullPathFromRelativeFile"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:fullPathFromRelativeFile"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:fullPathFromRelativeFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_fullPathFromRelativeFile'", nullptr); @@ -33601,9 +33754,9 @@ int lua_cocos2dx_FileUtils_isDirectoryExistInternal(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:isDirectoryExistInternal"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:isDirectoryExistInternal"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_isDirectoryExistInternal'", nullptr); @@ -33650,8 +33803,8 @@ int lua_cocos2dx_FileUtils_writeValueMapToFile(lua_State* tolua_S) ok &= luaval_to_ccvaluemap(tolua_S, 2, &arg0, "cc.FileUtils:writeValueMapToFile"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:writeValueMapToFile"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:writeValueMapToFile"); if (!ok) { break; } std::function arg2; @@ -33674,8 +33827,8 @@ int lua_cocos2dx_FileUtils_writeValueMapToFile(lua_State* tolua_S) ok &= luaval_to_ccvaluemap(tolua_S, 2, &arg0, "cc.FileUtils:writeValueMapToFile"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FileUtils:writeValueMapToFile"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FileUtils:writeValueMapToFile"); if (!ok) { break; } bool ret = cobj->writeValueMapToFile(arg0, arg1); @@ -33722,9 +33875,9 @@ int lua_cocos2dx_FileUtils_getFileExtension(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:getFileExtension"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:getFileExtension"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_getFileExtension'", nullptr); @@ -33772,9 +33925,9 @@ int lua_cocos2dx_FileUtils_setWritablePath(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:setWritablePath"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:setWritablePath"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_setWritablePath'", nullptr); @@ -33867,8 +34020,8 @@ int lua_cocos2dx_FileUtils_isDirectoryExist(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:isDirectoryExist"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:isDirectoryExist"); if (!ok) { break; } std::function arg1; @@ -33887,8 +34040,8 @@ int lua_cocos2dx_FileUtils_isDirectoryExist(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:isDirectoryExist"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:isDirectoryExist"); if (!ok) { break; } bool ret = cobj->isDirectoryExist(arg0); @@ -33935,9 +34088,9 @@ int lua_cocos2dx_FileUtils_setDefaultResourceRootPath(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:setDefaultResourceRootPath"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:setDefaultResourceRootPath"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_setDefaultResourceRootPath'", nullptr); @@ -34027,8 +34180,8 @@ int lua_cocos2dx_FileUtils_createDirectory(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:createDirectory"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:createDirectory"); if (!ok) { break; } std::function arg1; @@ -34047,8 +34200,8 @@ int lua_cocos2dx_FileUtils_createDirectory(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:createDirectory"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:createDirectory"); if (!ok) { break; } bool ret = cobj->createDirectory(arg0); @@ -34095,10 +34248,10 @@ int lua_cocos2dx_FileUtils_listFilesAsync(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; + std::string_view arg0; std::function)> arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:listFilesAsync"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:listFilesAsync"); do { // Lambda binding for lua is not supported. @@ -34199,10 +34352,10 @@ int lua_cocos2dx_FileUtils_listFilesRecursively(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; + std::string_view arg0; std::vector* arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:listFilesRecursively"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:listFilesRecursively"); ok &= luaval_to_object>(tolua_S, 3, "std::vector*",&arg1, "cc.FileUtils:listFilesRecursively"); if(!ok) @@ -34224,7 +34377,48 @@ int lua_cocos2dx_FileUtils_listFilesRecursively(lua_State* tolua_S) return 0; } -int lua_cocos2dx_FileUtils_destroyInstance(lua_State* tolua_S) +int lua_cocos2dx_FileUtils_writeBinaryToFile(lua_State* tolua_S) +{ + int argc = 0; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertable(tolua_S,1,"cc.FileUtils",0,&tolua_err)) goto tolua_lerror; +#endif + + argc = lua_gettop(tolua_S) - 1; + + if (argc == 3) + { + const void* arg0; + unsigned int arg1; + std::string_view arg2; + #pragma warning NO CONVERSION TO NATIVE FOR void* + ok = false; + ok &= luaval_to_uint32(tolua_S, 3,&arg1, "cc.FileUtils:writeBinaryToFile"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "cc.FileUtils:writeBinaryToFile"); + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_writeBinaryToFile'", nullptr); + return 0; + } + bool ret = cocos2d::FileUtils::writeBinaryToFile(arg0, arg1, arg2); + tolua_pushboolean(tolua_S,(bool)ret); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "cc.FileUtils:writeBinaryToFile",argc, 3); + return 0; +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_FileUtils_writeBinaryToFile'.",&tolua_err); +#endif + return 0; +} +int lua_cocos2dx_FileUtils_getInstance(lua_State* tolua_S) { int argc = 0; bool ok = true; @@ -34243,22 +34437,22 @@ int lua_cocos2dx_FileUtils_destroyInstance(lua_State* tolua_S) { if(!ok) { - tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_destroyInstance'", nullptr); + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_getInstance'", nullptr); return 0; } - cocos2d::FileUtils::destroyInstance(); - lua_settop(tolua_S, 1); + cocos2d::FileUtils* ret = cocos2d::FileUtils::getInstance(); + object_to_luaval(tolua_S, "cc.FileUtils",(cocos2d::FileUtils*)ret); return 1; } - luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "cc.FileUtils:destroyInstance",argc, 0); + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "cc.FileUtils:getInstance",argc, 0); return 0; #if COCOS2D_DEBUG >= 1 tolua_lerror: - tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_FileUtils_destroyInstance'.",&tolua_err); + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_FileUtils_getInstance'.",&tolua_err); #endif return 0; } -int lua_cocos2dx_FileUtils_writeBinaryToFile(lua_State* tolua_S) +int lua_cocos2dx_FileUtils_isAbsolutePathInternal(lua_State* tolua_S) { int argc = 0; bool ok = true; @@ -34273,33 +34467,28 @@ int lua_cocos2dx_FileUtils_writeBinaryToFile(lua_State* tolua_S) argc = lua_gettop(tolua_S) - 1; - if (argc == 3) + if (argc == 1) { - const void* arg0; - unsigned int arg1; - std::string arg2; - #pragma warning NO CONVERSION TO NATIVE FOR void* - ok = false; - ok &= luaval_to_uint32(tolua_S, 3,&arg1, "cc.FileUtils:writeBinaryToFile"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "cc.FileUtils:writeBinaryToFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:isAbsolutePathInternal"); if(!ok) { - tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_writeBinaryToFile'", nullptr); + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_isAbsolutePathInternal'", nullptr); return 0; } - bool ret = cocos2d::FileUtils::writeBinaryToFile(arg0, arg1, arg2); + bool ret = cocos2d::FileUtils::isAbsolutePathInternal(arg0); tolua_pushboolean(tolua_S,(bool)ret); return 1; } - luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "cc.FileUtils:writeBinaryToFile",argc, 3); + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "cc.FileUtils:isAbsolutePathInternal",argc, 1); return 0; #if COCOS2D_DEBUG >= 1 tolua_lerror: - tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_FileUtils_writeBinaryToFile'.",&tolua_err); + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_FileUtils_isAbsolutePathInternal'.",&tolua_err); #endif return 0; } -int lua_cocos2dx_FileUtils_getInstance(lua_State* tolua_S) +int lua_cocos2dx_FileUtils_destroyInstance(lua_State* tolua_S) { int argc = 0; bool ok = true; @@ -34318,18 +34507,18 @@ int lua_cocos2dx_FileUtils_getInstance(lua_State* tolua_S) { if(!ok) { - tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_getInstance'", nullptr); + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_destroyInstance'", nullptr); return 0; } - cocos2d::FileUtils* ret = cocos2d::FileUtils::getInstance(); - object_to_luaval(tolua_S, "cc.FileUtils",(cocos2d::FileUtils*)ret); + cocos2d::FileUtils::destroyInstance(); + lua_settop(tolua_S, 1); return 1; } - luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "cc.FileUtils:getInstance",argc, 0); + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "cc.FileUtils:destroyInstance",argc, 0); return 0; #if COCOS2D_DEBUG >= 1 tolua_lerror: - tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_FileUtils_getInstance'.",&tolua_err); + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_FileUtils_destroyInstance'.",&tolua_err); #endif return 0; } @@ -34350,8 +34539,8 @@ int lua_cocos2dx_FileUtils_getFileShortName(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FileUtils:getFileShortName"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FileUtils:getFileShortName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FileUtils_getFileShortName'", nullptr); @@ -34424,9 +34613,10 @@ int lua_register_cocos2dx_FileUtils(lua_State* tolua_S) tolua_function(tolua_S,"listFilesAsync",lua_cocos2dx_FileUtils_listFilesAsync); tolua_function(tolua_S,"getWritablePath",lua_cocos2dx_FileUtils_getWritablePath); tolua_function(tolua_S,"listFilesRecursively",lua_cocos2dx_FileUtils_listFilesRecursively); - tolua_function(tolua_S,"destroyInstance", lua_cocos2dx_FileUtils_destroyInstance); tolua_function(tolua_S,"writeBinaryToFile", lua_cocos2dx_FileUtils_writeBinaryToFile); tolua_function(tolua_S,"getInstance", lua_cocos2dx_FileUtils_getInstance); + tolua_function(tolua_S,"isAbsolutePathInternal", lua_cocos2dx_FileUtils_isAbsolutePathInternal); + tolua_function(tolua_S,"destroyInstance", lua_cocos2dx_FileUtils_destroyInstance); tolua_function(tolua_S,"getFileShortName", lua_cocos2dx_FileUtils_getFileShortName); tolua_endmodule(tolua_S); auto typeName = typeid(cocos2d::FileUtils).name(); // rtti is literal storage @@ -34487,8 +34677,8 @@ int lua_cocos2dx_EventCustom_getEventName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_EventCustom_getEventName'", nullptr); return 0; } - const std::string& ret = cobj->getEventName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getEventName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.EventCustom:getEventName",argc, 0); @@ -34516,9 +34706,9 @@ int lua_cocos2dx_EventCustom_constructor(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventCustom:EventCustom"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventCustom:EventCustom"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_EventCustom_constructor'", nullptr); @@ -34863,9 +35053,9 @@ int lua_cocos2dx_EventDispatcher_dispatchCustomEvent(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventDispatcher:dispatchCustomEvent"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventDispatcher:dispatchCustomEvent"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_EventDispatcher_dispatchCustomEvent'", nullptr); @@ -34877,10 +35067,10 @@ int lua_cocos2dx_EventDispatcher_dispatchCustomEvent(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; void* arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventDispatcher:dispatchCustomEvent"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventDispatcher:dispatchCustomEvent"); #pragma warning NO CONVERSION TO NATIVE FOR void* ok = false; @@ -35118,10 +35308,10 @@ int lua_cocos2dx_EventDispatcher_addCustomEventListener(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; + std::string_view arg0; std::function arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventDispatcher:addCustomEventListener"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventDispatcher:addCustomEventListener"); do { // Lambda binding for lua is not supported. @@ -35225,9 +35415,9 @@ int lua_cocos2dx_EventDispatcher_hasEventListener(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::EventListener::ListenerID arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventDispatcher:hasEventListener"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventDispatcher:hasEventListener"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_EventDispatcher_hasEventListener'", nullptr); @@ -35322,9 +35512,9 @@ int lua_cocos2dx_EventDispatcher_removeCustomEventListeners(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventDispatcher:removeCustomEventListeners"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventDispatcher:removeCustomEventListeners"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_EventDispatcher_removeCustomEventListeners'", nullptr); @@ -43373,11 +43563,11 @@ int lua_cocos2dx_GridAction_initWithDuration(lua_State* tolua_S) if (argc == 2) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.GridAction:initWithDuration"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.GridAction:initWithDuration"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.GridAction:initWithDuration"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_GridAction_initWithDuration'", nullptr); @@ -43820,13 +44010,13 @@ int lua_cocos2dx_Waves3D_initWithDuration(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; unsigned int arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Waves3D:initWithDuration"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Waves3D:initWithDuration"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Waves3D:initWithDuration"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.Waves3D:initWithDuration"); @@ -44012,11 +44202,11 @@ int lua_cocos2dx_Waves3D_create(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; unsigned int arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Waves3D:create"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Waves3D:create"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Waves3D:create"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.Waves3D:create"); ok &= luaval_to_number(tolua_S, 5,&arg3, "cc.Waves3D:create"); if(!ok) @@ -44127,10 +44317,10 @@ int lua_cocos2dx_FlipX3D_initWithSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; double arg1; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.FlipX3D:initWithSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.FlipX3D:initWithSize"); ok &= luaval_to_number(tolua_S, 3,&arg1, "cc.FlipX3D:initWithSize"); if(!ok) @@ -44471,13 +44661,13 @@ int lua_cocos2dx_Lens3D_initWithDuration(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; cocos2d::Vec2 arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Lens3D:initWithDuration"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Lens3D:initWithDuration"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Lens3D:initWithDuration"); ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.Lens3D:initWithDuration"); @@ -44713,11 +44903,11 @@ int lua_cocos2dx_Lens3D_create(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; cocos2d::Vec2 arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Lens3D:create"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Lens3D:create"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Lens3D:create"); ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.Lens3D:create"); ok &= luaval_to_number(tolua_S, 5,&arg3, "cc.Lens3D:create"); if(!ok) @@ -44880,7 +45070,7 @@ int lua_cocos2dx_Ripple3D_initWithDuration(lua_State* tolua_S) if (argc == 6) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; cocos2d::Vec2 arg2; double arg3; unsigned int arg4; @@ -44888,7 +45078,7 @@ int lua_cocos2dx_Ripple3D_initWithDuration(lua_State* tolua_S) ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Ripple3D:initWithDuration"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Ripple3D:initWithDuration"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Ripple3D:initWithDuration"); ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.Ripple3D:initWithDuration"); @@ -45175,13 +45365,13 @@ int lua_cocos2dx_Ripple3D_create(lua_State* tolua_S) if (argc == 6) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; cocos2d::Vec2 arg2; double arg3; unsigned int arg4; double arg5; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Ripple3D:create"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Ripple3D:create"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Ripple3D:create"); ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.Ripple3D:create"); ok &= luaval_to_number(tolua_S, 5,&arg3, "cc.Ripple3D:create"); ok &= luaval_to_uint32(tolua_S, 6,&arg4, "cc.Ripple3D:create"); @@ -45297,13 +45487,13 @@ int lua_cocos2dx_Shaky3D_initWithDuration(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; int arg2; bool arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Shaky3D:initWithDuration"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Shaky3D:initWithDuration"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Shaky3D:initWithDuration"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.Shaky3D:initWithDuration"); @@ -45345,11 +45535,11 @@ int lua_cocos2dx_Shaky3D_create(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; int arg2; bool arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Shaky3D:create"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Shaky3D:create"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Shaky3D:create"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.Shaky3D:create"); ok &= luaval_to_boolean(tolua_S, 5,&arg3, "cc.Shaky3D:create"); if(!ok) @@ -45507,13 +45697,13 @@ int lua_cocos2dx_Liquid_initWithDuration(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; unsigned int arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Liquid:initWithDuration"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Liquid:initWithDuration"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Liquid:initWithDuration"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.Liquid:initWithDuration"); @@ -45699,11 +45889,11 @@ int lua_cocos2dx_Liquid_create(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; unsigned int arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Liquid:create"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Liquid:create"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Liquid:create"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.Liquid:create"); ok &= luaval_to_number(tolua_S, 5,&arg3, "cc.Liquid:create"); if(!ok) @@ -45865,7 +46055,7 @@ int lua_cocos2dx_Waves_initWithDuration(lua_State* tolua_S) if (argc == 6) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; unsigned int arg2; double arg3; bool arg4; @@ -45873,7 +46063,7 @@ int lua_cocos2dx_Waves_initWithDuration(lua_State* tolua_S) ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Waves:initWithDuration"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Waves:initWithDuration"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Waves:initWithDuration"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.Waves:initWithDuration"); @@ -46063,13 +46253,13 @@ int lua_cocos2dx_Waves_create(lua_State* tolua_S) if (argc == 6) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; unsigned int arg2; double arg3; bool arg4; bool arg5; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Waves:create"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Waves:create"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Waves:create"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.Waves:create"); ok &= luaval_to_number(tolua_S, 5,&arg3, "cc.Waves:create"); ok &= luaval_to_boolean(tolua_S, 6,&arg4, "cc.Waves:create"); @@ -46233,14 +46423,14 @@ int lua_cocos2dx_Twirl_initWithDuration(lua_State* tolua_S) if (argc == 5) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; cocos2d::Vec2 arg2; unsigned int arg3; double arg4; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Twirl:initWithDuration"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Twirl:initWithDuration"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Twirl:initWithDuration"); ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.Twirl:initWithDuration"); @@ -46525,12 +46715,12 @@ int lua_cocos2dx_Twirl_create(lua_State* tolua_S) if (argc == 5) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; cocos2d::Vec2 arg2; unsigned int arg3; double arg4; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.Twirl:create"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Twirl:create"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Twirl:create"); ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.Twirl:create"); ok &= luaval_to_uint32(tolua_S, 5,&arg3, "cc.Twirl:create"); ok &= luaval_to_number(tolua_S, 6,&arg4, "cc.Twirl:create"); @@ -47519,9 +47709,9 @@ int lua_cocos2dx_PageTurn3D_create(lua_State* tolua_S) if (argc == 2) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.PageTurn3D:create"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.PageTurn3D:create"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.PageTurn3D:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_PageTurn3D_create'", nullptr); @@ -47893,13 +48083,13 @@ int lua_cocos2dx_ShakyTiles3D_initWithDuration(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; int arg2; bool arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.ShakyTiles3D:initWithDuration"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.ShakyTiles3D:initWithDuration"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.ShakyTiles3D:initWithDuration"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.ShakyTiles3D:initWithDuration"); @@ -47941,11 +48131,11 @@ int lua_cocos2dx_ShakyTiles3D_create(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; int arg2; bool arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.ShakyTiles3D:create"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.ShakyTiles3D:create"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.ShakyTiles3D:create"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.ShakyTiles3D:create"); ok &= luaval_to_boolean(tolua_S, 5,&arg3, "cc.ShakyTiles3D:create"); if(!ok) @@ -48053,13 +48243,13 @@ int lua_cocos2dx_ShatteredTiles3D_initWithDuration(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; int arg2; bool arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.ShatteredTiles3D:initWithDuration"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.ShatteredTiles3D:initWithDuration"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.ShatteredTiles3D:initWithDuration"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.ShatteredTiles3D:initWithDuration"); @@ -48101,11 +48291,11 @@ int lua_cocos2dx_ShatteredTiles3D_create(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; int arg2; bool arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.ShatteredTiles3D:create"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.ShatteredTiles3D:create"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.ShatteredTiles3D:create"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.ShatteredTiles3D:create"); ok &= luaval_to_boolean(tolua_S, 5,&arg3, "cc.ShatteredTiles3D:create"); if(!ok) @@ -48213,12 +48403,12 @@ int lua_cocos2dx_ShuffleTiles_initWithDuration(lua_State* tolua_S) if (argc == 3) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; unsigned int arg2; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.ShuffleTiles:initWithDuration"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.ShuffleTiles:initWithDuration"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.ShuffleTiles:initWithDuration"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.ShuffleTiles:initWithDuration"); if(!ok) @@ -48268,16 +48458,16 @@ int lua_cocos2dx_ShuffleTiles_getDelta(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.ShuffleTiles:getDelta"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.ShuffleTiles:getDelta"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ShuffleTiles_getDelta'", nullptr); return 0; } - cocos2d::Size ret = cobj->getDelta(arg0); - size_to_luaval(tolua_S, ret); + cocos2d::Vec2 ret = cobj->getDelta(arg0); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.ShuffleTiles:getDelta",argc, 1); @@ -48308,10 +48498,10 @@ int lua_cocos2dx_ShuffleTiles_create(lua_State* tolua_S) if (argc == 3) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; unsigned int arg2; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.ShuffleTiles:create"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.ShuffleTiles:create"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.ShuffleTiles:create"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.ShuffleTiles:create"); if(!ok) { @@ -48571,10 +48761,10 @@ int lua_cocos2dx_FadeOutTRTiles_testFunc(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; double arg1; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.FadeOutTRTiles:testFunc"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.FadeOutTRTiles:testFunc"); ok &= luaval_to_number(tolua_S, 3,&arg1, "cc.FadeOutTRTiles:testFunc"); if(!ok) @@ -48614,9 +48804,9 @@ int lua_cocos2dx_FadeOutTRTiles_create(lua_State* tolua_S) if (argc == 2) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.FadeOutTRTiles:create"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.FadeOutTRTiles:create"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.FadeOutTRTiles:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FadeOutTRTiles_create'", nullptr); @@ -48714,9 +48904,9 @@ int lua_cocos2dx_FadeOutBLTiles_create(lua_State* tolua_S) if (argc == 2) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.FadeOutBLTiles:create"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.FadeOutBLTiles:create"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.FadeOutBLTiles:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FadeOutBLTiles_create'", nullptr); @@ -48810,9 +49000,9 @@ int lua_cocos2dx_FadeOutUpTiles_create(lua_State* tolua_S) if (argc == 2) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.FadeOutUpTiles:create"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.FadeOutUpTiles:create"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.FadeOutUpTiles:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FadeOutUpTiles_create'", nullptr); @@ -48906,9 +49096,9 @@ int lua_cocos2dx_FadeOutDownTiles_create(lua_State* tolua_S) if (argc == 2) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.FadeOutDownTiles:create"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.FadeOutDownTiles:create"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.FadeOutDownTiles:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FadeOutDownTiles_create'", nullptr); @@ -49113,12 +49303,12 @@ int lua_cocos2dx_TurnOffTiles_initWithDuration(lua_State* tolua_S) if (argc == 3) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; unsigned int arg2; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.TurnOffTiles:initWithDuration"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.TurnOffTiles:initWithDuration"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.TurnOffTiles:initWithDuration"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.TurnOffTiles:initWithDuration"); if(!ok) @@ -49161,8 +49351,8 @@ int lua_cocos2dx_TurnOffTiles_create(lua_State* tolua_S) double arg0; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.TurnOffTiles:create"); if (!ok) { break; } - cocos2d::Size arg1; - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.TurnOffTiles:create"); + cocos2d::Vec2 arg1; + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.TurnOffTiles:create"); if (!ok) { break; } unsigned int arg2; ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.TurnOffTiles:create"); @@ -49180,8 +49370,8 @@ int lua_cocos2dx_TurnOffTiles_create(lua_State* tolua_S) double arg0; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.TurnOffTiles:create"); if (!ok) { break; } - cocos2d::Size arg1; - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.TurnOffTiles:create"); + cocos2d::Vec2 arg1; + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.TurnOffTiles:create"); if (!ok) { break; } cocos2d::TurnOffTiles* ret = cocos2d::TurnOffTiles::create(arg0, arg1); object_to_luaval(tolua_S, "cc.TurnOffTiles",(cocos2d::TurnOffTiles*)ret); @@ -49337,13 +49527,13 @@ int lua_cocos2dx_WavesTiles3D_initWithDuration(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; unsigned int arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.WavesTiles3D:initWithDuration"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.WavesTiles3D:initWithDuration"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.WavesTiles3D:initWithDuration"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.WavesTiles3D:initWithDuration"); @@ -49529,11 +49719,11 @@ int lua_cocos2dx_WavesTiles3D_create(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; unsigned int arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.WavesTiles3D:create"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.WavesTiles3D:create"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.WavesTiles3D:create"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.WavesTiles3D:create"); ok &= luaval_to_number(tolua_S, 5,&arg3, "cc.WavesTiles3D:create"); if(!ok) @@ -49695,13 +49885,13 @@ int lua_cocos2dx_JumpTiles3D_initWithDuration(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; unsigned int arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.JumpTiles3D:initWithDuration"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.JumpTiles3D:initWithDuration"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.JumpTiles3D:initWithDuration"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.JumpTiles3D:initWithDuration"); @@ -49887,11 +50077,11 @@ int lua_cocos2dx_JumpTiles3D_create(lua_State* tolua_S) if (argc == 4) { double arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; unsigned int arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.JumpTiles3D:create"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.JumpTiles3D:create"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.JumpTiles3D:create"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "cc.JumpTiles3D:create"); ok &= luaval_to_number(tolua_S, 5,&arg3, "cc.JumpTiles3D:create"); if(!ok) @@ -50303,13 +50493,13 @@ int lua_cocos2dx_ActionTween_initWithDuration(lua_State* tolua_S) if (argc == 4) { double arg0; - std::string arg1; + std::string_view arg1; double arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.ActionTween:initWithDuration"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.ActionTween:initWithDuration"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.ActionTween:initWithDuration"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.ActionTween:initWithDuration"); @@ -50351,11 +50541,11 @@ int lua_cocos2dx_ActionTween_create(lua_State* tolua_S) if (argc == 4) { double arg0; - std::string arg1; + std::string_view arg1; double arg2; double arg3; ok &= luaval_to_number(tolua_S, 2,&arg0, "cc.ActionTween:create"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.ActionTween:create"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.ActionTween:create"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.ActionTween:create"); ok &= luaval_to_number(tolua_S, 5,&arg3, "cc.ActionTween:create"); if(!ok) @@ -50471,12 +50661,12 @@ int lua_cocos2dx_AtlasNode_initWithTileFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 4) { - std::string arg0; + std::string_view arg0; int arg1; int arg2; int arg3; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AtlasNode:initWithTileFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AtlasNode:initWithTileFile"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "cc.AtlasNode:initWithTileFile"); @@ -50966,11 +51156,11 @@ int lua_cocos2dx_AtlasNode_create(lua_State* tolua_S) if (argc == 4) { - std::string arg0; + std::string_view arg0; int arg1; int arg2; int arg3; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AtlasNode:create"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AtlasNode:create"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "cc.AtlasNode:create"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.AtlasNode:create"); ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "cc.AtlasNode:create"); @@ -51814,13 +52004,13 @@ int lua_cocos2dx_DrawNode_drawLine(lua_State* tolua_S) { cocos2d::Vec2 arg0; cocos2d::Vec2 arg1; - cocos2d::Color4F arg2; + cocos2d::Color4B arg2; ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.DrawNode:drawLine"); ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.DrawNode:drawLine"); - ok &=luaval_to_color4f(tolua_S, 4, &arg2, "cc.DrawNode:drawLine"); + ok &=luaval_to_color4b(tolua_S, 4, &arg2, "cc.DrawNode:drawLine"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_DrawNode_drawLine'", nullptr); @@ -51929,8 +52119,8 @@ int lua_cocos2dx_DrawNode_drawRect(lua_State* tolua_S) ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.DrawNode:drawRect"); if (!ok) { break; } - cocos2d::Color4F arg4; - ok &=luaval_to_color4f(tolua_S, 6, &arg4, "cc.DrawNode:drawRect"); + cocos2d::Color4B arg4; + ok &=luaval_to_color4b(tolua_S, 6, &arg4, "cc.DrawNode:drawRect"); if (!ok) { break; } cobj->drawRect(arg0, arg1, arg2, arg3, arg4); @@ -51949,8 +52139,8 @@ int lua_cocos2dx_DrawNode_drawRect(lua_State* tolua_S) ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.DrawNode:drawRect"); if (!ok) { break; } - cocos2d::Color4F arg2; - ok &=luaval_to_color4f(tolua_S, 4, &arg2, "cc.DrawNode:drawRect"); + cocos2d::Color4B arg2; + ok &=luaval_to_color4b(tolua_S, 4, &arg2, "cc.DrawNode:drawRect"); if (!ok) { break; } cobj->drawRect(arg0, arg1, arg2); @@ -52016,8 +52206,8 @@ int lua_cocos2dx_DrawNode_drawSolidCircle(lua_State* tolua_S) ok &= luaval_to_number(tolua_S, 7,&arg5, "cc.DrawNode:drawSolidCircle"); if (!ok) { break; } - cocos2d::Color4F arg6; - ok &=luaval_to_color4f(tolua_S, 8, &arg6, "cc.DrawNode:drawSolidCircle"); + cocos2d::Color4B arg6; + ok &=luaval_to_color4b(tolua_S, 8, &arg6, "cc.DrawNode:drawSolidCircle"); if (!ok) { break; } cobj->drawSolidCircle(arg0, arg1, arg2, arg3, arg4, arg5, arg6); @@ -52052,16 +52242,16 @@ int lua_cocos2dx_DrawNode_drawSolidCircle(lua_State* tolua_S) ok &= luaval_to_number(tolua_S, 7,&arg5, "cc.DrawNode:drawSolidCircle"); if (!ok) { break; } - cocos2d::Color4F arg6; - ok &=luaval_to_color4f(tolua_S, 8, &arg6, "cc.DrawNode:drawSolidCircle"); + cocos2d::Color4B arg6; + ok &=luaval_to_color4b(tolua_S, 8, &arg6, "cc.DrawNode:drawSolidCircle"); if (!ok) { break; } double arg7; ok &= luaval_to_number(tolua_S, 9,&arg7, "cc.DrawNode:drawSolidCircle"); if (!ok) { break; } - cocos2d::Color4F arg8; - ok &=luaval_to_color4f(tolua_S, 10, &arg8, "cc.DrawNode:drawSolidCircle"); + cocos2d::Color4B arg8; + ok &=luaval_to_color4b(tolua_S, 10, &arg8, "cc.DrawNode:drawSolidCircle"); if (!ok) { break; } cobj->drawSolidCircle(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); @@ -52088,8 +52278,8 @@ int lua_cocos2dx_DrawNode_drawSolidCircle(lua_State* tolua_S) ok &= luaval_to_uint32(tolua_S, 5,&arg3, "cc.DrawNode:drawSolidCircle"); if (!ok) { break; } - cocos2d::Color4F arg4; - ok &=luaval_to_color4f(tolua_S, 6, &arg4, "cc.DrawNode:drawSolidCircle"); + cocos2d::Color4B arg4; + ok &=luaval_to_color4b(tolua_S, 6, &arg4, "cc.DrawNode:drawSolidCircle"); if (!ok) { break; } cobj->drawSolidCircle(arg0, arg1, arg2, arg3, arg4); @@ -52188,13 +52378,13 @@ int lua_cocos2dx_DrawNode_drawDot(lua_State* tolua_S) { cocos2d::Vec2 arg0; double arg1; - cocos2d::Color4F arg2; + cocos2d::Color4B arg2; ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.DrawNode:drawDot"); ok &= luaval_to_number(tolua_S, 3,&arg1, "cc.DrawNode:drawDot"); - ok &=luaval_to_color4f(tolua_S, 4, &arg2, "cc.DrawNode:drawDot"); + ok &=luaval_to_color4b(tolua_S, 4, &arg2, "cc.DrawNode:drawDot"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_DrawNode_drawDot'", nullptr); @@ -52245,7 +52435,7 @@ int lua_cocos2dx_DrawNode_drawSegment(lua_State* tolua_S) cocos2d::Vec2 arg0; cocos2d::Vec2 arg1; double arg2; - cocos2d::Color4F arg3; + cocos2d::Color4B arg3; ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.DrawNode:drawSegment"); @@ -52253,7 +52443,7 @@ int lua_cocos2dx_DrawNode_drawSegment(lua_State* tolua_S) ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.DrawNode:drawSegment"); - ok &=luaval_to_color4f(tolua_S, 5, &arg3, "cc.DrawNode:drawSegment"); + ok &=luaval_to_color4b(tolua_S, 5, &arg3, "cc.DrawNode:drawSegment"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_DrawNode_drawSegment'", nullptr); @@ -52363,8 +52553,8 @@ int lua_cocos2dx_DrawNode_drawCircle(lua_State* tolua_S) ok &= luaval_to_boolean(tolua_S, 6,&arg4, "cc.DrawNode:drawCircle"); if (!ok) { break; } - cocos2d::Color4F arg5; - ok &=luaval_to_color4f(tolua_S, 7, &arg5, "cc.DrawNode:drawCircle"); + cocos2d::Color4B arg5; + ok &=luaval_to_color4b(tolua_S, 7, &arg5, "cc.DrawNode:drawCircle"); if (!ok) { break; } cobj->drawCircle(arg0, arg1, arg2, arg3, arg4, arg5); @@ -52403,8 +52593,8 @@ int lua_cocos2dx_DrawNode_drawCircle(lua_State* tolua_S) ok &= luaval_to_number(tolua_S, 8,&arg6, "cc.DrawNode:drawCircle"); if (!ok) { break; } - cocos2d::Color4F arg7; - ok &=luaval_to_color4f(tolua_S, 9, &arg7, "cc.DrawNode:drawCircle"); + cocos2d::Color4B arg7; + ok &=luaval_to_color4b(tolua_S, 9, &arg7, "cc.DrawNode:drawCircle"); if (!ok) { break; } cobj->drawCircle(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7); @@ -52455,7 +52645,7 @@ int lua_cocos2dx_DrawNode_drawQuadBezier(lua_State* tolua_S) cocos2d::Vec2 arg1; cocos2d::Vec2 arg2; unsigned int arg3; - cocos2d::Color4F arg4; + cocos2d::Color4B arg4; ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.DrawNode:drawQuadBezier"); @@ -52465,7 +52655,7 @@ int lua_cocos2dx_DrawNode_drawQuadBezier(lua_State* tolua_S) ok &= luaval_to_uint32(tolua_S, 5,&arg3, "cc.DrawNode:drawQuadBezier"); - ok &=luaval_to_color4f(tolua_S, 6, &arg4, "cc.DrawNode:drawQuadBezier"); + ok &=luaval_to_color4b(tolua_S, 6, &arg4, "cc.DrawNode:drawQuadBezier"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_DrawNode_drawQuadBezier'", nullptr); @@ -52516,7 +52706,7 @@ int lua_cocos2dx_DrawNode_drawTriangle(lua_State* tolua_S) cocos2d::Vec2 arg0; cocos2d::Vec2 arg1; cocos2d::Vec2 arg2; - cocos2d::Color4F arg3; + cocos2d::Color4B arg3; ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.DrawNode:drawTriangle"); @@ -52524,7 +52714,7 @@ int lua_cocos2dx_DrawNode_drawTriangle(lua_State* tolua_S) ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.DrawNode:drawTriangle"); - ok &=luaval_to_color4f(tolua_S, 5, &arg3, "cc.DrawNode:drawTriangle"); + ok &=luaval_to_color4b(tolua_S, 5, &arg3, "cc.DrawNode:drawTriangle"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_DrawNode_drawTriangle'", nullptr); @@ -52671,13 +52861,13 @@ int lua_cocos2dx_DrawNode_drawSolidRect(lua_State* tolua_S) { cocos2d::Vec2 arg0; cocos2d::Vec2 arg1; - cocos2d::Color4F arg2; + cocos2d::Color4B arg2; ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.DrawNode:drawSolidRect"); ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.DrawNode:drawSolidRect"); - ok &=luaval_to_color4f(tolua_S, 4, &arg2, "cc.DrawNode:drawSolidRect"); + ok &=luaval_to_color4b(tolua_S, 4, &arg2, "cc.DrawNode:drawSolidRect"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_DrawNode_drawSolidRect'", nullptr); @@ -52774,13 +52964,13 @@ int lua_cocos2dx_DrawNode_drawPoint(lua_State* tolua_S) { cocos2d::Vec2 arg0; double arg1; - cocos2d::Color4F arg2; + cocos2d::Color4B arg2; ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.DrawNode:drawPoint"); ok &= luaval_to_number(tolua_S, 3,&arg1, "cc.DrawNode:drawPoint"); - ok &=luaval_to_color4f(tolua_S, 4, &arg2, "cc.DrawNode:drawPoint"); + ok &=luaval_to_color4b(tolua_S, 4, &arg2, "cc.DrawNode:drawPoint"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_DrawNode_drawPoint'", nullptr); @@ -52880,7 +53070,7 @@ int lua_cocos2dx_DrawNode_drawCubicBezier(lua_State* tolua_S) cocos2d::Vec2 arg2; cocos2d::Vec2 arg3; unsigned int arg4; - cocos2d::Color4F arg5; + cocos2d::Color4B arg5; ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.DrawNode:drawCubicBezier"); @@ -52892,7 +53082,7 @@ int lua_cocos2dx_DrawNode_drawCubicBezier(lua_State* tolua_S) ok &= luaval_to_uint32(tolua_S, 6,&arg4, "cc.DrawNode:drawCubicBezier"); - ok &=luaval_to_color4f(tolua_S, 7, &arg5, "cc.DrawNode:drawCubicBezier"); + ok &=luaval_to_color4b(tolua_S, 7, &arg5, "cc.DrawNode:drawCubicBezier"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_DrawNode_drawCubicBezier'", nullptr); @@ -53153,11 +53343,11 @@ int lua_cocos2dx_Label_enableShadow(lua_State* tolua_S) if (argc == 2) { cocos2d::Color4B arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; ok &=luaval_to_color4b(tolua_S, 2, &arg0, "cc.Label:enableShadow"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Label:enableShadow"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Label:enableShadow"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Label_enableShadow'", nullptr); @@ -53170,12 +53360,12 @@ int lua_cocos2dx_Label_enableShadow(lua_State* tolua_S) if (argc == 3) { cocos2d::Color4B arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; int arg2; ok &=luaval_to_color4b(tolua_S, 2, &arg0, "cc.Label:enableShadow"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Label:enableShadow"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Label:enableShadow"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.Label:enableShadow"); if(!ok) @@ -53330,8 +53520,8 @@ int lua_cocos2dx_Label_getString(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Label_getString'", nullptr); return 0; } - const std::string& ret = cobj->getString(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getString(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Label:getString",argc, 0); @@ -53954,8 +54144,8 @@ int lua_cocos2dx_Label_getShadowOffset(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Label_getShadowOffset'", nullptr); return 0; } - cocos2d::Size ret = cobj->getShadowOffset(); - size_to_luaval(tolua_S, ret); + cocos2d::Vec2 ret = cobj->getShadowOffset(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Label:getShadowOffset",argc, 0); @@ -54093,9 +54283,9 @@ int lua_cocos2dx_Label_setString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:setString"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:setString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Label_setString'", nullptr); @@ -54143,9 +54333,9 @@ int lua_cocos2dx_Label_setSystemFontName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:setSystemFontName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:setSystemFontName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Label_setSystemFontName'", nullptr); @@ -54282,8 +54472,8 @@ int lua_cocos2dx_Label_setBMFontFilePath(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); if (!ok) { break; } cocos2d::Rect arg1; @@ -54302,8 +54492,8 @@ int lua_cocos2dx_Label_setBMFontFilePath(lua_State* tolua_S) ok = true; do{ if (argc == 4) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); if (!ok) { break; } cocos2d::Rect arg1; @@ -54326,8 +54516,8 @@ int lua_cocos2dx_Label_setBMFontFilePath(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); if (!ok) { break; } bool ret = cobj->setBMFontFilePath(arg0); @@ -54338,8 +54528,8 @@ int lua_cocos2dx_Label_setBMFontFilePath(lua_State* tolua_S) ok = true; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); if (!ok) { break; } double arg1; @@ -54354,12 +54544,12 @@ int lua_cocos2dx_Label_setBMFontFilePath(lua_State* tolua_S) ok = true; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:setBMFontFilePath"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:setBMFontFilePath"); if (!ok) { break; } bool ret = cobj->setBMFontFilePath(arg0, arg1); @@ -54370,12 +54560,12 @@ int lua_cocos2dx_Label_setBMFontFilePath(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:setBMFontFilePath"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:setBMFontFilePath"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:setBMFontFilePath"); if (!ok) { break; } double arg2; @@ -54425,8 +54615,8 @@ int lua_cocos2dx_Label_initWithTTF(lua_State* tolua_S) ok &= luaval_to_ttfconfig(tolua_S, 2, &arg0, "cc.Label:initWithTTF"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); if (!ok) { break; } bool ret = cobj->initWithTTF(arg0, arg1); @@ -54441,8 +54631,8 @@ int lua_cocos2dx_Label_initWithTTF(lua_State* tolua_S) ok &= luaval_to_ttfconfig(tolua_S, 2, &arg0, "cc.Label:initWithTTF"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); if (!ok) { break; } cocos2d::TextHAlignment arg2; @@ -54461,8 +54651,8 @@ int lua_cocos2dx_Label_initWithTTF(lua_State* tolua_S) ok &= luaval_to_ttfconfig(tolua_S, 2, &arg0, "cc.Label:initWithTTF"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); if (!ok) { break; } cocos2d::TextHAlignment arg2; @@ -54481,12 +54671,12 @@ int lua_cocos2dx_Label_initWithTTF(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:initWithTTF"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:initWithTTF"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); if (!ok) { break; } double arg2; @@ -54501,20 +54691,20 @@ int lua_cocos2dx_Label_initWithTTF(lua_State* tolua_S) ok = true; do{ if (argc == 4) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:initWithTTF"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:initWithTTF"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); if (!ok) { break; } double arg2; ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Label:initWithTTF"); if (!ok) { break; } - cocos2d::Size arg3; - ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Label:initWithTTF"); + cocos2d::Vec2 arg3; + ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Label:initWithTTF"); if (!ok) { break; } bool ret = cobj->initWithTTF(arg0, arg1, arg2, arg3); @@ -54525,20 +54715,20 @@ int lua_cocos2dx_Label_initWithTTF(lua_State* tolua_S) ok = true; do{ if (argc == 5) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:initWithTTF"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:initWithTTF"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); if (!ok) { break; } double arg2; ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Label:initWithTTF"); if (!ok) { break; } - cocos2d::Size arg3; - ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Label:initWithTTF"); + cocos2d::Vec2 arg3; + ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Label:initWithTTF"); if (!ok) { break; } cocos2d::TextHAlignment arg4; @@ -54553,20 +54743,20 @@ int lua_cocos2dx_Label_initWithTTF(lua_State* tolua_S) ok = true; do{ if (argc == 6) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:initWithTTF"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:initWithTTF"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:initWithTTF"); if (!ok) { break; } double arg2; ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Label:initWithTTF"); if (!ok) { break; } - cocos2d::Size arg3; - ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Label:initWithTTF"); + cocos2d::Vec2 arg3; + ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Label:initWithTTF"); if (!ok) { break; } cocos2d::TextHAlignment arg4; @@ -55286,8 +55476,8 @@ int lua_cocos2dx_Label_setCharMap(lua_State* tolua_S) ok = true; do{ if (argc == 4) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:setCharMap"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:setCharMap"); if (!ok) { break; } int arg1; @@ -55310,8 +55500,8 @@ int lua_cocos2dx_Label_setCharMap(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:setCharMap"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:setCharMap"); if (!ok) { break; } bool ret = cobj->setCharMap(arg0); @@ -55363,8 +55553,8 @@ int lua_cocos2dx_Label_getDimensions(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Label_getDimensions'", nullptr); return 0; } - const cocos2d::Size& ret = cobj->getDimensions(); - size_to_luaval(tolua_S, ret); + const cocos2d::Vec2& ret = cobj->getDimensions(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Label:getDimensions",argc, 0); @@ -55460,8 +55650,8 @@ int lua_cocos2dx_Label_getSystemFontName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Label_getSystemFontName'", nullptr); return 0; } - const std::string& ret = cobj->getSystemFontName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getSystemFontName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Label:getSystemFontName",argc, 0); @@ -56377,8 +56567,8 @@ int lua_cocos2dx_Label_getBMFontFilePath(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Label_getBMFontFilePath'", nullptr); return 0; } - const std::string& ret = cobj->getBMFontFilePath(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getBMFontFilePath(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Label:getBMFontFilePath",argc, 0); @@ -56756,11 +56946,11 @@ int lua_cocos2dx_Label_createWithBMFont(lua_State* tolua_S) { if (argc == 6) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithBMFont"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithBMFont"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:createWithBMFont"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:createWithBMFont"); if (!ok) { break; } cocos2d::TextHAlignment arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.Label:createWithBMFont"); @@ -56784,11 +56974,11 @@ int lua_cocos2dx_Label_createWithBMFont(lua_State* tolua_S) { if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithBMFont"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithBMFont"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:createWithBMFont"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:createWithBMFont"); if (!ok) { break; } cocos2d::Label* ret = cocos2d::Label::createWithBMFont(arg0, arg1); object_to_luaval(tolua_S, "cc.Label",(cocos2d::Label*)ret); @@ -56800,11 +56990,11 @@ int lua_cocos2dx_Label_createWithBMFont(lua_State* tolua_S) { if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithBMFont"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithBMFont"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:createWithBMFont"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:createWithBMFont"); if (!ok) { break; } cocos2d::TextHAlignment arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.Label:createWithBMFont"); @@ -56819,11 +57009,11 @@ int lua_cocos2dx_Label_createWithBMFont(lua_State* tolua_S) { if (argc == 4) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithBMFont"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithBMFont"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:createWithBMFont"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:createWithBMFont"); if (!ok) { break; } cocos2d::TextHAlignment arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.Label:createWithBMFont"); @@ -56841,11 +57031,11 @@ int lua_cocos2dx_Label_createWithBMFont(lua_State* tolua_S) { if (argc == 5) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithBMFont"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithBMFont"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:createWithBMFont"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:createWithBMFont"); if (!ok) { break; } cocos2d::TextHAlignment arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.Label:createWithBMFont"); @@ -56853,8 +57043,8 @@ int lua_cocos2dx_Label_createWithBMFont(lua_State* tolua_S) int arg3; ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "cc.Label:createWithBMFont"); if (!ok) { break; } - std::string arg4; - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "cc.Label:createWithBMFont"); + std::string_view arg4; + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "cc.Label:createWithBMFont"); if (!ok) { break; } cocos2d::Label* ret = cocos2d::Label::createWithBMFont(arg0, arg1, arg2, arg3, arg4); object_to_luaval(tolua_S, "cc.Label",(cocos2d::Label*)ret); @@ -56944,8 +57134,8 @@ int lua_cocos2dx_Label_createWithCharMap(lua_State* tolua_S) { if (argc == 4) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithCharMap"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithCharMap"); if (!ok) { break; } int arg1; ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "cc.Label:createWithCharMap"); @@ -56966,8 +57156,8 @@ int lua_cocos2dx_Label_createWithCharMap(lua_State* tolua_S) { if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithCharMap"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithCharMap"); if (!ok) { break; } cocos2d::Label* ret = cocos2d::Label::createWithCharMap(arg0); object_to_luaval(tolua_S, "cc.Label",(cocos2d::Label*)ret); @@ -57000,11 +57190,11 @@ int lua_cocos2dx_Label_createWithSystemFont(lua_State* tolua_S) if (argc == 3) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; double arg2; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithSystemFont"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:createWithSystemFont"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithSystemFont"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:createWithSystemFont"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Label:createWithSystemFont"); if(!ok) { @@ -57017,14 +57207,14 @@ int lua_cocos2dx_Label_createWithSystemFont(lua_State* tolua_S) } if (argc == 4) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; double arg2; - cocos2d::Size arg3; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithSystemFont"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:createWithSystemFont"); + cocos2d::Vec2 arg3; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithSystemFont"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:createWithSystemFont"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Label:createWithSystemFont"); - ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Label:createWithSystemFont"); + ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Label:createWithSystemFont"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Label_createWithSystemFont'", nullptr); @@ -57036,15 +57226,15 @@ int lua_cocos2dx_Label_createWithSystemFont(lua_State* tolua_S) } if (argc == 5) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; double arg2; - cocos2d::Size arg3; + cocos2d::Vec2 arg3; cocos2d::TextHAlignment arg4; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithSystemFont"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:createWithSystemFont"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithSystemFont"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:createWithSystemFont"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Label:createWithSystemFont"); - ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Label:createWithSystemFont"); + ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Label:createWithSystemFont"); ok &= luaval_to_int32(tolua_S, 6,(int *)&arg4, "cc.Label:createWithSystemFont"); if(!ok) { @@ -57057,16 +57247,16 @@ int lua_cocos2dx_Label_createWithSystemFont(lua_State* tolua_S) } if (argc == 6) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; double arg2; - cocos2d::Size arg3; + cocos2d::Vec2 arg3; cocos2d::TextHAlignment arg4; cocos2d::TextVAlignment arg5; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Label:createWithSystemFont"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.Label:createWithSystemFont"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Label:createWithSystemFont"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.Label:createWithSystemFont"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.Label:createWithSystemFont"); - ok &= luaval_to_size(tolua_S, 5, &arg3, "cc.Label:createWithSystemFont"); + ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.Label:createWithSystemFont"); ok &= luaval_to_int32(tolua_S, 6,(int *)&arg4, "cc.Label:createWithSystemFont"); ok &= luaval_to_int32(tolua_S, 7,(int *)&arg5, "cc.Label:createWithSystemFont"); if(!ok) @@ -57206,9 +57396,9 @@ int lua_cocos2dx_LabelAtlas_setString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.LabelAtlas:setString"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.LabelAtlas:setString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_LabelAtlas_setString'", nullptr); @@ -57251,12 +57441,12 @@ int lua_cocos2dx_LabelAtlas_initWithString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.LabelAtlas:initWithString"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.LabelAtlas:initWithString"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.LabelAtlas:initWithString"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.LabelAtlas:initWithString"); if (!ok) { break; } bool ret = cobj->initWithString(arg0, arg1); @@ -57267,12 +57457,12 @@ int lua_cocos2dx_LabelAtlas_initWithString(lua_State* tolua_S) ok = true; do{ if (argc == 5) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.LabelAtlas:initWithString"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.LabelAtlas:initWithString"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.LabelAtlas:initWithString"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.LabelAtlas:initWithString"); if (!ok) { break; } int arg2; @@ -57295,8 +57485,8 @@ int lua_cocos2dx_LabelAtlas_initWithString(lua_State* tolua_S) ok = true; do{ if (argc == 5) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.LabelAtlas:initWithString"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.LabelAtlas:initWithString"); if (!ok) { break; } cocos2d::Texture2D* arg1; @@ -57364,8 +57554,8 @@ int lua_cocos2dx_LabelAtlas_getString(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_LabelAtlas_getString'", nullptr); return 0; } - const std::string& ret = cobj->getString(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getString(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.LabelAtlas:getString",argc, 0); @@ -57396,11 +57586,11 @@ int lua_cocos2dx_LabelAtlas_create(lua_State* tolua_S) { if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.LabelAtlas:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.LabelAtlas:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.LabelAtlas:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.LabelAtlas:create"); if (!ok) { break; } cocos2d::LabelAtlas* ret = cocos2d::LabelAtlas::create(arg0, arg1); object_to_luaval(tolua_S, "cc.LabelAtlas",(cocos2d::LabelAtlas*)ret); @@ -57412,11 +57602,11 @@ int lua_cocos2dx_LabelAtlas_create(lua_State* tolua_S) { if (argc == 5) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.LabelAtlas:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.LabelAtlas:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.LabelAtlas:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.LabelAtlas:create"); if (!ok) { break; } int arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.LabelAtlas:create"); @@ -57437,8 +57627,8 @@ int lua_cocos2dx_LabelAtlas_create(lua_State* tolua_S) { if (argc == 5) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.LabelAtlas:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.LabelAtlas:create"); if (!ok) { break; } cocos2d::Texture2D* arg1; ok &= luaval_to_object(tolua_S, 3, "cc.Texture2D",&arg1, "cc.LabelAtlas:create"); @@ -60672,8 +60862,8 @@ int lua_cocos2dx_MenuItemLabel_getString(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_MenuItemLabel_getString'", nullptr); return 0; } - std::string ret = cobj->getString(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getString(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.MenuItemLabel:getString",argc, 0); @@ -60761,9 +60951,9 @@ int lua_cocos2dx_MenuItemLabel_setString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.MenuItemLabel:setString"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.MenuItemLabel:setString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_MenuItemLabel_setString'", nullptr); @@ -61029,16 +61219,16 @@ int lua_cocos2dx_MenuItemAtlasFont_initWithString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 6) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; int arg2; int arg3; int32_t arg4; std::function arg5; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.MenuItemAtlasFont:initWithString"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.MenuItemAtlasFont:initWithString"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.MenuItemAtlasFont:initWithString"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.MenuItemAtlasFont:initWithString"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.MenuItemAtlasFont:initWithString"); @@ -61161,8 +61351,8 @@ int lua_cocos2dx_MenuItemFont_getFontNameObj(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_MenuItemFont_getFontNameObj'", nullptr); return 0; } - const std::string& ret = cobj->getFontNameObj(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getFontNameObj(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.MenuItemFont:getFontNameObj",argc, 0); @@ -61203,9 +61393,9 @@ int lua_cocos2dx_MenuItemFont_setFontNameObj(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.MenuItemFont:setFontNameObj"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.MenuItemFont:setFontNameObj"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_MenuItemFont_setFontNameObj'", nullptr); @@ -61253,10 +61443,10 @@ int lua_cocos2dx_MenuItemFont_initWithString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; + std::string_view arg0; std::function arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.MenuItemFont:initWithString"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.MenuItemFont:initWithString"); do { // Lambda binding for lua is not supported. @@ -61396,8 +61586,8 @@ int lua_cocos2dx_MenuItemFont_setFontName(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.MenuItemFont:setFontName"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.MenuItemFont:setFontName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_MenuItemFont_setFontName'", nullptr); @@ -61471,8 +61661,8 @@ int lua_cocos2dx_MenuItemFont_getFontName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_MenuItemFont_getFontName'", nullptr); return 0; } - const std::string& ret = cocos2d::MenuItemFont::getFontName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cocos2d::MenuItemFont::getFontName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "cc.MenuItemFont:getFontName",argc, 0); @@ -62375,16 +62565,16 @@ int lua_cocos2dx_MenuItemImage_initWithNormalImage(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 4) { - std::string arg0; - std::string arg1; - std::string arg2; + std::string_view arg0; + std::string_view arg1; + std::string_view arg2; std::function arg3; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.MenuItemImage:initWithNormalImage"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.MenuItemImage:initWithNormalImage"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.MenuItemImage:initWithNormalImage"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.MenuItemImage:initWithNormalImage"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "cc.MenuItemImage:initWithNormalImage"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "cc.MenuItemImage:initWithNormalImage"); do { // Lambda binding for lua is not supported. @@ -63783,8 +63973,8 @@ int lua_cocos2dx_MotionStreak_initWithFade(lua_State* tolua_S) ok &= luaval_to_color3b(tolua_S, 5, &arg3, "cc.MotionStreak:initWithFade"); if (!ok) { break; } - std::string arg4; - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "cc.MotionStreak:initWithFade"); + std::string_view arg4; + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "cc.MotionStreak:initWithFade"); if (!ok) { break; } bool ret = cobj->initWithFade(arg0, arg1, arg2, arg3, arg4); @@ -63958,8 +64148,8 @@ int lua_cocos2dx_MotionStreak_create(lua_State* tolua_S) cocos2d::Color3B arg3; ok &= luaval_to_color3b(tolua_S, 5, &arg3, "cc.MotionStreak:create"); if (!ok) { break; } - std::string arg4; - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "cc.MotionStreak:create"); + std::string_view arg4; + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "cc.MotionStreak:create"); if (!ok) { break; } cocos2d::MotionStreak* ret = cocos2d::MotionStreak::create(arg0, arg1, arg2, arg3, arg4); object_to_luaval(tolua_S, "cc.MotionStreak",(cocos2d::MotionStreak*)ret); @@ -64676,10 +64866,10 @@ int lua_cocos2dx_ParticleBatchNode_initWithFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; + std::string_view arg0; int arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.ParticleBatchNode:initWithFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.ParticleBatchNode:initWithFile"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "cc.ParticleBatchNode:initWithFile"); if(!ok) @@ -65018,8 +65208,8 @@ int lua_cocos2dx_ParticleBatchNode_create(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.ParticleBatchNode:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.ParticleBatchNode:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ParticleBatchNode_create'", nullptr); @@ -65031,9 +65221,9 @@ int lua_cocos2dx_ParticleBatchNode_create(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; int arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.ParticleBatchNode:create"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.ParticleBatchNode:create"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "cc.ParticleBatchNode:create"); if(!ok) { @@ -68076,8 +68266,8 @@ int lua_cocos2dx_ParticleSystem_getResourceFile(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ParticleSystem_getResourceFile'", nullptr); return 0; } - const std::string& ret = cobj->getResourceFile(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getResourceFile(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.ParticleSystem:getResourceFile",argc, 0); @@ -68994,9 +69184,9 @@ int lua_cocos2dx_ParticleSystem_initWithFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.ParticleSystem:initWithFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.ParticleSystem:initWithFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ParticleSystem_initWithFile'", nullptr); @@ -70198,8 +70388,8 @@ int lua_cocos2dx_ParticleSystem_initWithDictionary(lua_State* tolua_S) ok &= luaval_to_ccvaluemap(tolua_S, 2, &arg0, "cc.ParticleSystem:initWithDictionary"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.ParticleSystem:initWithDictionary"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.ParticleSystem:initWithDictionary"); if (!ok) { break; } bool ret = cobj->initWithDictionary(arg0, arg1); @@ -70582,8 +70772,8 @@ int lua_cocos2dx_ParticleSystem_create(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.ParticleSystem:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.ParticleSystem:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ParticleSystem_create'", nullptr); @@ -71008,8 +71198,8 @@ int lua_cocos2dx_ParticleSystemQuad_create(lua_State* tolua_S) { if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.ParticleSystemQuad:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.ParticleSystemQuad:create"); if (!ok) { break; } cocos2d::ParticleSystemQuad* ret = cocos2d::ParticleSystemQuad::create(arg0); object_to_luaval(tolua_S, "cc.ParticleSystemQuad",(cocos2d::ParticleSystemQuad*)ret); @@ -74985,8 +75175,8 @@ int lua_cocos2dx_Sprite_setSpriteFrame(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite:setSpriteFrame"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite:setSpriteFrame"); if (!ok) { break; } cobj->setSpriteFrame(arg0); @@ -75040,8 +75230,8 @@ int lua_cocos2dx_Sprite_setTexture(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite:setTexture"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite:setTexture"); if (!ok) { break; } cobj->setTexture(arg0); @@ -75282,10 +75472,10 @@ int lua_cocos2dx_Sprite_setDisplayFrameWithAnimationName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; + std::string_view arg0; unsigned int arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite:setDisplayFrameWithAnimationName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite:setDisplayFrameWithAnimationName"); ok &= luaval_to_uint32(tolua_S, 3,&arg1, "cc.Sprite:setDisplayFrameWithAnimationName"); if(!ok) @@ -75576,8 +75766,8 @@ int lua_cocos2dx_Sprite_setTextureRect(lua_State* tolua_S) ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.Sprite:setTextureRect"); if (!ok) { break; } - cocos2d::Size arg2; - ok &= luaval_to_size(tolua_S, 4, &arg2, "cc.Sprite:setTextureRect"); + cocos2d::Vec2 arg2; + ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.Sprite:setTextureRect"); if (!ok) { break; } cobj->setTextureRect(arg0, arg1, arg2); @@ -75636,9 +75826,9 @@ int lua_cocos2dx_Sprite_initWithSpriteFrameName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite:initWithSpriteFrameName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite:initWithSpriteFrameName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Sprite_initWithSpriteFrameName'", nullptr); @@ -76179,8 +76369,8 @@ int lua_cocos2dx_Sprite_getResourceName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Sprite_getResourceName'", nullptr); return 0; } - const std::string& ret = cobj->getResourceName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getResourceName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Sprite:getResourceName",argc, 0); @@ -76583,8 +76773,8 @@ int lua_cocos2dx_Sprite_initWithFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite:initWithFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite:initWithFile"); if (!ok) { break; } cocos2d::Rect arg1; @@ -76599,8 +76789,8 @@ int lua_cocos2dx_Sprite_initWithFile(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite:initWithFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite:initWithFile"); if (!ok) { break; } bool ret = cobj->initWithFile(arg0); @@ -76997,8 +77187,8 @@ int lua_cocos2dx_Sprite_createWithSpriteFrameName(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Sprite:createWithSpriteFrameName"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Sprite:createWithSpriteFrameName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Sprite_createWithSpriteFrameName'", nullptr); @@ -77568,8 +77758,8 @@ int lua_cocos2dx_RenderTexture_saveToFileAsNonPMA(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 4) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFileAsNonPMA"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFileAsNonPMA"); if (!ok) { break; } cocos2d::Image::Format arg1; @@ -77580,7 +77770,7 @@ int lua_cocos2dx_RenderTexture_saveToFileAsNonPMA(lua_State* tolua_S) ok &= luaval_to_boolean(tolua_S, 4,&arg2, "cc.RenderTexture:saveToFileAsNonPMA"); if (!ok) { break; } - std::function arg3; + std::function arg3; do { // Lambda binding for lua is not supported. assert(false); @@ -77596,8 +77786,8 @@ int lua_cocos2dx_RenderTexture_saveToFileAsNonPMA(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFileAsNonPMA"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFileAsNonPMA"); if (!ok) { break; } bool ret = cobj->saveToFileAsNonPMA(arg0); @@ -77608,8 +77798,8 @@ int lua_cocos2dx_RenderTexture_saveToFileAsNonPMA(lua_State* tolua_S) ok = true; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFileAsNonPMA"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFileAsNonPMA"); if (!ok) { break; } bool arg1; @@ -77624,15 +77814,15 @@ int lua_cocos2dx_RenderTexture_saveToFileAsNonPMA(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFileAsNonPMA"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFileAsNonPMA"); if (!ok) { break; } bool arg1; ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.RenderTexture:saveToFileAsNonPMA"); if (!ok) { break; } - std::function arg2; + std::function arg2; do { // Lambda binding for lua is not supported. assert(false); @@ -77826,8 +78016,8 @@ int lua_cocos2dx_RenderTexture_saveToFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); if (!ok) { break; } cocos2d::Image::Format arg1; @@ -77842,8 +78032,8 @@ int lua_cocos2dx_RenderTexture_saveToFile(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); if (!ok) { break; } cocos2d::Image::Format arg1; @@ -77862,8 +78052,8 @@ int lua_cocos2dx_RenderTexture_saveToFile(lua_State* tolua_S) ok = true; do{ if (argc == 4) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); if (!ok) { break; } cocos2d::Image::Format arg1; @@ -77874,7 +78064,7 @@ int lua_cocos2dx_RenderTexture_saveToFile(lua_State* tolua_S) ok &= luaval_to_boolean(tolua_S, 4,&arg2, "cc.RenderTexture:saveToFile"); if (!ok) { break; } - std::function arg3; + std::function arg3; do { // Lambda binding for lua is not supported. assert(false); @@ -77890,8 +78080,8 @@ int lua_cocos2dx_RenderTexture_saveToFile(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); if (!ok) { break; } bool ret = cobj->saveToFile(arg0); @@ -77902,8 +78092,8 @@ int lua_cocos2dx_RenderTexture_saveToFile(lua_State* tolua_S) ok = true; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); if (!ok) { break; } bool arg1; @@ -77918,15 +78108,15 @@ int lua_cocos2dx_RenderTexture_saveToFile(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.RenderTexture:saveToFile"); if (!ok) { break; } bool arg1; ok &= luaval_to_boolean(tolua_S, 3,&arg1, "cc.RenderTexture:saveToFile"); if (!ok) { break; } - std::function arg2; + std::function arg2; do { // Lambda binding for lua is not supported. assert(false); @@ -82057,9 +82247,9 @@ int lua_cocos2dx_TransitionFadeTR_actionWithSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.TransitionFadeTR:actionWithSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.TransitionFadeTR:actionWithSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TransitionFadeTR_actionWithSize'", nullptr); @@ -82493,9 +82683,9 @@ int lua_cocos2dx_TransitionPageTurn_actionWithSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.TransitionPageTurn:actionWithSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.TransitionPageTurn:actionWithSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TransitionPageTurn_actionWithSize'", nullptr); @@ -85287,18 +85477,18 @@ int lua_cocos2dx_CameraBackgroundBrush_createSkyboxBrush(lua_State* tolua_S) if (argc == 6) { - std::string arg0; - std::string arg1; - std::string arg2; - std::string arg3; - std::string arg4; - std::string arg5; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CameraBackgroundBrush:createSkyboxBrush"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.CameraBackgroundBrush:createSkyboxBrush"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "cc.CameraBackgroundBrush:createSkyboxBrush"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "cc.CameraBackgroundBrush:createSkyboxBrush"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "cc.CameraBackgroundBrush:createSkyboxBrush"); - ok &= luaval_to_std_string(tolua_S, 7,&arg5, "cc.CameraBackgroundBrush:createSkyboxBrush"); + std::string_view arg0; + std::string_view arg1; + std::string_view arg2; + std::string_view arg3; + std::string_view arg4; + std::string_view arg5; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.CameraBackgroundBrush:createSkyboxBrush"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.CameraBackgroundBrush:createSkyboxBrush"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "cc.CameraBackgroundBrush:createSkyboxBrush"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "cc.CameraBackgroundBrush:createSkyboxBrush"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "cc.CameraBackgroundBrush:createSkyboxBrush"); + ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "cc.CameraBackgroundBrush:createSkyboxBrush"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_CameraBackgroundBrush_createSkyboxBrush'", nullptr); @@ -86064,23 +86254,23 @@ int lua_cocos2dx_CameraBackgroundSkyBoxBrush_create(lua_State* tolua_S) { if (argc == 6) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CameraBackgroundSkyBoxBrush:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.CameraBackgroundSkyBoxBrush:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.CameraBackgroundSkyBoxBrush:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.CameraBackgroundSkyBoxBrush:create"); if (!ok) { break; } - std::string arg2; - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "cc.CameraBackgroundSkyBoxBrush:create"); + std::string_view arg2; + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "cc.CameraBackgroundSkyBoxBrush:create"); if (!ok) { break; } - std::string arg3; - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "cc.CameraBackgroundSkyBoxBrush:create"); + std::string_view arg3; + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "cc.CameraBackgroundSkyBoxBrush:create"); if (!ok) { break; } - std::string arg4; - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "cc.CameraBackgroundSkyBoxBrush:create"); + std::string_view arg4; + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "cc.CameraBackgroundSkyBoxBrush:create"); if (!ok) { break; } - std::string arg5; - ok &= luaval_to_std_string(tolua_S, 7,&arg5, "cc.CameraBackgroundSkyBoxBrush:create"); + std::string_view arg5; + ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "cc.CameraBackgroundSkyBoxBrush:create"); if (!ok) { break; } cocos2d::CameraBackgroundSkyBoxBrush* ret = cocos2d::CameraBackgroundSkyBoxBrush::create(arg0, arg1, arg2, arg3, arg4, arg5); object_to_luaval(tolua_S, "cc.CameraBackgroundSkyBoxBrush",(cocos2d::CameraBackgroundSkyBoxBrush*)ret); @@ -86187,9 +86377,9 @@ int lua_cocos2dx_GridBase_setGridSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.GridBase:setGridSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.GridBase:setGridSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_GridBase_setGridSize'", nullptr); @@ -86527,8 +86717,8 @@ int lua_cocos2dx_GridBase_getGridSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_GridBase_getGridSize'", nullptr); return 0; } - const cocos2d::Size& ret = cobj->getGridSize(); - size_to_luaval(tolua_S, ret); + const cocos2d::Vec2& ret = cobj->getGridSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.GridBase:getGridSize",argc, 0); @@ -86949,8 +87139,8 @@ int lua_cocos2dx_GridBase_initWithSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.GridBase:initWithSize"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.GridBase:initWithSize"); if (!ok) { break; } cocos2d::Rect arg1; @@ -86965,8 +87155,8 @@ int lua_cocos2dx_GridBase_initWithSize(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.GridBase:initWithSize"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.GridBase:initWithSize"); if (!ok) { break; } bool ret = cobj->initWithSize(arg0); @@ -86977,8 +87167,8 @@ int lua_cocos2dx_GridBase_initWithSize(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.GridBase:initWithSize"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.GridBase:initWithSize"); if (!ok) { break; } cocos2d::Texture2D* arg1; @@ -86997,8 +87187,8 @@ int lua_cocos2dx_GridBase_initWithSize(lua_State* tolua_S) ok = true; do{ if (argc == 4) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.GridBase:initWithSize"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.GridBase:initWithSize"); if (!ok) { break; } cocos2d::Texture2D* arg1; @@ -87378,8 +87568,8 @@ int lua_cocos2dx_Grid3D_create(lua_State* tolua_S) { if (argc == 2) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.Grid3D:create"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.Grid3D:create"); if (!ok) { break; } cocos2d::Rect arg1; ok &= luaval_to_rect(tolua_S, 3, &arg1, "cc.Grid3D:create"); @@ -87394,8 +87584,8 @@ int lua_cocos2dx_Grid3D_create(lua_State* tolua_S) { if (argc == 1) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.Grid3D:create"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.Grid3D:create"); if (!ok) { break; } cocos2d::Grid3D* ret = cocos2d::Grid3D::create(arg0); object_to_luaval(tolua_S, "cc.Grid3D",(cocos2d::Grid3D*)ret); @@ -87407,8 +87597,8 @@ int lua_cocos2dx_Grid3D_create(lua_State* tolua_S) { if (argc == 3) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.Grid3D:create"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.Grid3D:create"); if (!ok) { break; } cocos2d::Texture2D* arg1; ok &= luaval_to_object(tolua_S, 3, "cc.Texture2D",&arg1, "cc.Grid3D:create"); @@ -87426,8 +87616,8 @@ int lua_cocos2dx_Grid3D_create(lua_State* tolua_S) { if (argc == 4) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.Grid3D:create"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.Grid3D:create"); if (!ok) { break; } cocos2d::Texture2D* arg1; ok &= luaval_to_object(tolua_S, 3, "cc.Texture2D",&arg1, "cc.Grid3D:create"); @@ -87530,8 +87720,8 @@ int lua_cocos2dx_TiledGrid3D_create(lua_State* tolua_S) { if (argc == 2) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.TiledGrid3D:create"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.TiledGrid3D:create"); if (!ok) { break; } cocos2d::Rect arg1; ok &= luaval_to_rect(tolua_S, 3, &arg1, "cc.TiledGrid3D:create"); @@ -87546,8 +87736,8 @@ int lua_cocos2dx_TiledGrid3D_create(lua_State* tolua_S) { if (argc == 1) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.TiledGrid3D:create"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.TiledGrid3D:create"); if (!ok) { break; } cocos2d::TiledGrid3D* ret = cocos2d::TiledGrid3D::create(arg0); object_to_luaval(tolua_S, "cc.TiledGrid3D",(cocos2d::TiledGrid3D*)ret); @@ -87559,8 +87749,8 @@ int lua_cocos2dx_TiledGrid3D_create(lua_State* tolua_S) { if (argc == 3) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.TiledGrid3D:create"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.TiledGrid3D:create"); if (!ok) { break; } cocos2d::Texture2D* arg1; ok &= luaval_to_object(tolua_S, 3, "cc.Texture2D",&arg1, "cc.TiledGrid3D:create"); @@ -87578,8 +87768,8 @@ int lua_cocos2dx_TiledGrid3D_create(lua_State* tolua_S) { if (argc == 4) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.TiledGrid3D:create"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.TiledGrid3D:create"); if (!ok) { break; } cocos2d::Texture2D* arg1; ok &= luaval_to_object(tolua_S, 3, "cc.Texture2D",&arg1, "cc.TiledGrid3D:create"); @@ -89920,9 +90110,9 @@ int lua_cocos2dx_Material_setName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Material:setName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Material:setName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Material_setName'", nullptr); @@ -90161,9 +90351,9 @@ int lua_cocos2dx_Material_setTechnique(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Material:setTechnique"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Material:setTechnique"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Material_setTechnique'", nullptr); @@ -90211,9 +90401,9 @@ int lua_cocos2dx_Material_getTechniqueByName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Material:getTechniqueByName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Material:getTechniqueByName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Material_getTechniqueByName'", nullptr); @@ -90347,8 +90537,8 @@ int lua_cocos2dx_Material_createWithFilename(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Material:createWithFilename"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Material:createWithFilename"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Material_createWithFilename'", nullptr); @@ -90867,9 +91057,9 @@ int lua_cocos2dx_Pass_setName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Pass:setName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Pass:setName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Pass_setName'", nullptr); @@ -90922,8 +91112,8 @@ int lua_cocos2dx_Pass_getName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Pass_getName'", nullptr); return 0; } - const std::string& ret = cobj->getName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Pass:getName",argc, 0); @@ -93610,11 +93800,11 @@ int lua_cocos2dx_Renderer_checkVisibility(lua_State* tolua_S) if (argc == 2) { cocos2d::Mat4 arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; ok &= luaval_to_mat4(tolua_S, 2, &arg0, "cc.Renderer:checkVisibility"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "cc.Renderer:checkVisibility"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "cc.Renderer:checkVisibility"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Renderer_checkVisibility'", nullptr); @@ -94761,9 +94951,9 @@ int lua_cocos2dx_TextureCache_reloadTexture(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TextureCache:reloadTexture"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TextureCache:reloadTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TextureCache_reloadTexture'", nullptr); @@ -94858,9 +95048,9 @@ int lua_cocos2dx_TextureCache_removeTextureForKey(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TextureCache:removeTextureForKey"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TextureCache:removeTextureForKey"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TextureCache_removeTextureForKey'", nullptr); @@ -95048,8 +95238,8 @@ int lua_cocos2dx_TextureCache_addImage(lua_State* tolua_S) ok &= luaval_to_object(tolua_S, 2, "cc.Image",&arg0, "cc.TextureCache:addImage"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.TextureCache:addImage"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.TextureCache:addImage"); if (!ok) { break; } cocos2d::Texture2D* ret = cobj->addImage(arg0, arg1); @@ -95060,8 +95250,8 @@ int lua_cocos2dx_TextureCache_addImage(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TextureCache:addImage"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TextureCache:addImage"); if (!ok) { break; } cocos2d::Texture2D* ret = cobj->addImage(arg0); @@ -95108,9 +95298,9 @@ int lua_cocos2dx_TextureCache_unbindImageAsync(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TextureCache:unbindImageAsync"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TextureCache:unbindImageAsync"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TextureCache_unbindImageAsync'", nullptr); @@ -95158,9 +95348,9 @@ int lua_cocos2dx_TextureCache_getTextureForKey(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TextureCache:getTextureForKey"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TextureCache:getTextureForKey"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TextureCache_getTextureForKey'", nullptr); @@ -95258,12 +95448,12 @@ int lua_cocos2dx_TextureCache_renameTextureWithKey(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TextureCache:renameTextureWithKey"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TextureCache:renameTextureWithKey"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.TextureCache:renameTextureWithKey"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.TextureCache:renameTextureWithKey"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TextureCache_renameTextureWithKey'", nullptr); @@ -95444,8 +95634,8 @@ int lua_cocos2dx_TextureCache_setETC1AlphaFileSuffix(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TextureCache:setETC1AlphaFileSuffix"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TextureCache:setETC1AlphaFileSuffix"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TextureCache_setETC1AlphaFileSuffix'", nullptr); @@ -95941,9 +96131,9 @@ int lua_cocos2dx_Application_openURL(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.Application:openURL"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.Application:openURL"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Application_openURL'", nullptr); @@ -96137,9 +96327,9 @@ int lua_cocos2dx_GLViewImpl_createWithRect(lua_State* tolua_S) if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::Rect arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.GLViewImpl:createWithRect"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.GLViewImpl:createWithRect"); ok &= luaval_to_rect(tolua_S, 3, &arg1, "cc.GLViewImpl:createWithRect"); if(!ok) { @@ -96152,10 +96342,10 @@ int lua_cocos2dx_GLViewImpl_createWithRect(lua_State* tolua_S) } if (argc == 3) { - std::string arg0; + std::string_view arg0; cocos2d::Rect arg1; double arg2; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.GLViewImpl:createWithRect"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.GLViewImpl:createWithRect"); ok &= luaval_to_rect(tolua_S, 3, &arg1, "cc.GLViewImpl:createWithRect"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.GLViewImpl:createWithRect"); if(!ok) @@ -96192,8 +96382,8 @@ int lua_cocos2dx_GLViewImpl_create(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.GLViewImpl:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.GLViewImpl:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_GLViewImpl_create'", nullptr); @@ -96228,8 +96418,8 @@ int lua_cocos2dx_GLViewImpl_createWithFullScreen(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.GLViewImpl:createWithFullScreen"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.GLViewImpl:createWithFullScreen"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_GLViewImpl_createWithFullScreen'", nullptr); @@ -96297,9 +96487,9 @@ int lua_cocos2dx_AnimationCache_getAnimation(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AnimationCache:getAnimation"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AnimationCache:getAnimation"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_AnimationCache_getAnimation'", nullptr); @@ -96348,11 +96538,11 @@ int lua_cocos2dx_AnimationCache_addAnimation(lua_State* tolua_S) if (argc == 2) { cocos2d::Animation* arg0; - std::string arg1; + std::string_view arg1; ok &= luaval_to_object(tolua_S, 2, "cc.Animation",&arg0, "cc.AnimationCache:addAnimation"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.AnimationCache:addAnimation"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.AnimationCache:addAnimation"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_AnimationCache_addAnimation'", nullptr); @@ -96448,11 +96638,11 @@ int lua_cocos2dx_AnimationCache_addAnimationsWithDictionary(lua_State* tolua_S) if (argc == 2) { cocos2d::ValueMap arg0; - std::string arg1; + std::string_view arg1; ok &= luaval_to_ccvaluemap(tolua_S, 2, &arg0, "cc.AnimationCache:addAnimationsWithDictionary"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.AnimationCache:addAnimationsWithDictionary"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.AnimationCache:addAnimationsWithDictionary"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_AnimationCache_addAnimationsWithDictionary'", nullptr); @@ -96500,9 +96690,9 @@ int lua_cocos2dx_AnimationCache_removeAnimation(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AnimationCache:removeAnimation"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AnimationCache:removeAnimation"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_AnimationCache_removeAnimation'", nullptr); @@ -96550,9 +96740,9 @@ int lua_cocos2dx_AnimationCache_addAnimationsWithFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AnimationCache:addAnimationsWithFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AnimationCache:addAnimationsWithFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_AnimationCache_addAnimationsWithFile'", nullptr); @@ -97556,9 +97746,9 @@ int lua_cocos2dx_SpriteBatchNode_initWithFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteBatchNode:initWithFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteBatchNode:initWithFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteBatchNode_initWithFile'", nullptr); @@ -97570,10 +97760,10 @@ int lua_cocos2dx_SpriteBatchNode_initWithFile(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; ssize_t arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteBatchNode:initWithFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteBatchNode:initWithFile"); ok &= luaval_to_ssize_t(tolua_S, 3, &arg1, "cc.SpriteBatchNode:initWithFile"); if(!ok) @@ -97812,8 +98002,8 @@ int lua_cocos2dx_SpriteBatchNode_create(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteBatchNode:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteBatchNode:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteBatchNode_create'", nullptr); @@ -97825,9 +98015,9 @@ int lua_cocos2dx_SpriteBatchNode_create(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; ssize_t arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteBatchNode:create"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteBatchNode:create"); ok &= luaval_to_ssize_t(tolua_S, 3, &arg1, "cc.SpriteBatchNode:create"); if(!ok) { @@ -98024,9 +98214,9 @@ int lua_cocos2dx_SpriteFrameCache_reloadTexture(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:reloadTexture"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:reloadTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrameCache_reloadTexture'", nullptr); @@ -98125,11 +98315,11 @@ int lua_cocos2dx_SpriteFrameCache_addSpriteFrame(lua_State* tolua_S) if (argc == 2) { cocos2d::SpriteFrame* arg0; - std::string arg1; + std::string_view arg1; ok &= luaval_to_object(tolua_S, 2, "cc.SpriteFrame",&arg0, "cc.SpriteFrameCache:addSpriteFrame"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.SpriteFrameCache:addSpriteFrame"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.SpriteFrameCache:addSpriteFrame"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrameCache_addSpriteFrame'", nullptr); @@ -98177,9 +98367,9 @@ int lua_cocos2dx_SpriteFrameCache_findFrame(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:findFrame"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:findFrame"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrameCache_findFrame'", nullptr); @@ -98222,12 +98412,12 @@ int lua_cocos2dx_SpriteFrameCache_addSpriteFramesWithFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.SpriteFrameCache:addSpriteFramesWithFile"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.SpriteFrameCache:addSpriteFramesWithFile"); if (!ok) { break; } cobj->addSpriteFramesWithFile(arg0, arg1); @@ -98238,12 +98428,12 @@ int lua_cocos2dx_SpriteFrameCache_addSpriteFramesWithFile(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.SpriteFrameCache:addSpriteFramesWithFile"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.SpriteFrameCache:addSpriteFramesWithFile"); if (!ok) { break; } unsigned int arg2; @@ -98258,8 +98448,8 @@ int lua_cocos2dx_SpriteFrameCache_addSpriteFramesWithFile(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); if (!ok) { break; } cobj->addSpriteFramesWithFile(arg0); @@ -98270,8 +98460,8 @@ int lua_cocos2dx_SpriteFrameCache_addSpriteFramesWithFile(lua_State* tolua_S) ok = true; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); if (!ok) { break; } unsigned int arg1; @@ -98286,8 +98476,8 @@ int lua_cocos2dx_SpriteFrameCache_addSpriteFramesWithFile(lua_State* tolua_S) ok = true; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); if (!ok) { break; } cocos2d::Texture2D* arg1; @@ -98302,8 +98492,8 @@ int lua_cocos2dx_SpriteFrameCache_addSpriteFramesWithFile(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:addSpriteFramesWithFile"); if (!ok) { break; } cocos2d::Texture2D* arg1; @@ -98358,9 +98548,9 @@ int lua_cocos2dx_SpriteFrameCache_getSpriteFrameByName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:getSpriteFrameByName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:getSpriteFrameByName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrameCache_getSpriteFrameByName'", nullptr); @@ -98464,9 +98654,9 @@ int lua_cocos2dx_SpriteFrameCache_removeSpriteFramesFromFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:removeSpriteFramesFromFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:removeSpriteFramesFromFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrameCache_removeSpriteFramesFromFile'", nullptr); @@ -98705,9 +98895,9 @@ int lua_cocos2dx_SpriteFrameCache_removeSpriteFramesFromFileContent(lua_State* t argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:removeSpriteFramesFromFileContent"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:removeSpriteFramesFromFileContent"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrameCache_removeSpriteFramesFromFileContent'", nullptr); @@ -98755,9 +98945,9 @@ int lua_cocos2dx_SpriteFrameCache_removeSpriteFrameByName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:removeSpriteFrameByName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:removeSpriteFrameByName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrameCache_removeSpriteFrameByName'", nullptr); @@ -98805,9 +98995,9 @@ int lua_cocos2dx_SpriteFrameCache_eraseFrame(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:eraseFrame"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:eraseFrame"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrameCache_eraseFrame'", nullptr); @@ -98855,9 +99045,9 @@ int lua_cocos2dx_SpriteFrameCache_isSpriteFramesWithFileLoaded(lua_State* tolua_ argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.SpriteFrameCache:isSpriteFramesWithFileLoaded"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.SpriteFrameCache:isSpriteFramesWithFileLoaded"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_SpriteFrameCache_isSpriteFramesWithFileLoaded'", nullptr); @@ -99314,9 +99504,9 @@ int lua_cocos2dx_TMXObjectGroup_getProperty(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXObjectGroup:getProperty"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXObjectGroup:getProperty"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXObjectGroup_getProperty'", nullptr); @@ -99411,9 +99601,9 @@ int lua_cocos2dx_TMXObjectGroup_getObject(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXObjectGroup:getObject"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXObjectGroup:getObject"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXObjectGroup_getObject'", nullptr); @@ -99508,9 +99698,9 @@ int lua_cocos2dx_TMXObjectGroup_setGroupName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXObjectGroup:setGroupName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXObjectGroup:setGroupName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXObjectGroup_setGroupName'", nullptr); @@ -99610,8 +99800,8 @@ int lua_cocos2dx_TMXObjectGroup_getGroupName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXObjectGroup_getGroupName'", nullptr); return 0; } - const std::string& ret = cobj->getGroupName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getGroupName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.TMXObjectGroup:getGroupName",argc, 0); @@ -100083,9 +100273,9 @@ int lua_cocos2dx_TMXMapInfo_setCurrentString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXMapInfo:setCurrentString"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXMapInfo:setCurrentString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_setCurrentString'", nullptr); @@ -100180,9 +100370,9 @@ int lua_cocos2dx_TMXMapInfo_setTileSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.TMXMapInfo:setTileSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.TMXMapInfo:setTileSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_setTileSize'", nullptr); @@ -100377,9 +100567,9 @@ int lua_cocos2dx_TMXMapInfo_parseXMLFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXMapInfo:parseXMLFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXMapInfo:parseXMLFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_parseXMLFile'", nullptr); @@ -100474,9 +100664,9 @@ int lua_cocos2dx_TMXMapInfo_setTMXFileName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXMapInfo:setTMXFileName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXMapInfo:setTMXFileName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_setTMXFileName'", nullptr); @@ -100524,9 +100714,9 @@ int lua_cocos2dx_TMXMapInfo_parseXMLString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXMapInfo:parseXMLString"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXMapInfo:parseXMLString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_parseXMLString'", nullptr); @@ -100718,9 +100908,9 @@ int lua_cocos2dx_TMXMapInfo_initWithTMXFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXMapInfo:initWithTMXFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXMapInfo:initWithTMXFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_initWithTMXFile'", nullptr); @@ -100912,12 +101102,12 @@ int lua_cocos2dx_TMXMapInfo_initWithXML(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXMapInfo:initWithXML"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXMapInfo:initWithXML"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.TMXMapInfo:initWithXML"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.TMXMapInfo:initWithXML"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_initWithXML'", nullptr); @@ -101067,8 +101257,8 @@ int lua_cocos2dx_TMXMapInfo_getTileSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_getTileSize'", nullptr); return 0; } - const cocos2d::Size& ret = cobj->getTileSize(); - size_to_luaval(tolua_S, ret); + const cocos2d::Vec2& ret = cobj->getTileSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.TMXMapInfo:getTileSize",argc, 0); @@ -101208,8 +101398,8 @@ int lua_cocos2dx_TMXMapInfo_getExternalTilesetFileName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_getExternalTilesetFileName'", nullptr); return 0; } - const std::string& ret = cobj->getExternalTilesetFileName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getExternalTilesetFileName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.TMXMapInfo:getExternalTilesetFileName",argc, 0); @@ -101302,8 +101492,8 @@ int lua_cocos2dx_TMXMapInfo_getTMXFileName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_getTMXFileName'", nullptr); return 0; } - const std::string& ret = cobj->getTMXFileName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getTMXFileName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.TMXMapInfo:getTMXFileName",argc, 0); @@ -101544,9 +101734,9 @@ int lua_cocos2dx_TMXMapInfo_setMapSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.TMXMapInfo:setMapSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.TMXMapInfo:setMapSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_setMapSize'", nullptr); @@ -101599,8 +101789,8 @@ int lua_cocos2dx_TMXMapInfo_getCurrentString(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_getCurrentString'", nullptr); return 0; } - const std::string& ret = cobj->getCurrentString(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getCurrentString(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.TMXMapInfo:getCurrentString",argc, 0); @@ -101746,8 +101936,8 @@ int lua_cocos2dx_TMXMapInfo_getMapSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_getMapSize'", nullptr); return 0; } - const cocos2d::Size& ret = cobj->getMapSize(); - size_to_luaval(tolua_S, ret); + const cocos2d::Vec2& ret = cobj->getMapSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.TMXMapInfo:getMapSize",argc, 0); @@ -101971,8 +102161,8 @@ int lua_cocos2dx_TMXMapInfo_create(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXMapInfo:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXMapInfo:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_create'", nullptr); @@ -102007,10 +102197,10 @@ int lua_cocos2dx_TMXMapInfo_createWithXML(lua_State* tolua_S) if (argc == 2) { - std::string arg0; - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TMXMapInfo:createWithXML"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.TMXMapInfo:createWithXML"); + std::string_view arg0; + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TMXMapInfo:createWithXML"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.TMXMapInfo:createWithXML"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_TMXMapInfo_createWithXML'", nullptr); @@ -102154,14 +102344,14 @@ int lua_cocos2dx_TileMapAtlas_initWithTileFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 4) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; int arg2; int arg3; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TileMapAtlas:initWithTileFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TileMapAtlas:initWithTileFile"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.TileMapAtlas:initWithTileFile"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.TileMapAtlas:initWithTileFile"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.TileMapAtlas:initWithTileFile"); @@ -102352,12 +102542,12 @@ int lua_cocos2dx_TileMapAtlas_create(lua_State* tolua_S) if (argc == 4) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; int arg2; int arg3; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.TileMapAtlas:create"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.TileMapAtlas:create"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.TileMapAtlas:create"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.TileMapAtlas:create"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "cc.TileMapAtlas:create"); ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "cc.TileMapAtlas:create"); if(!ok) @@ -102722,8 +102912,8 @@ int lua_cocos2dx_FastTMXLayer_getLayerSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXLayer_getLayerSize'", nullptr); return 0; } - const cocos2d::Size& ret = cobj->getLayerSize(); - size_to_luaval(tolua_S, ret); + const cocos2d::Vec2& ret = cobj->getLayerSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.FastTMXLayer:getLayerSize",argc, 0); @@ -102764,9 +102954,9 @@ int lua_cocos2dx_FastTMXLayer_setMapTileSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.FastTMXLayer:setMapTileSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.FastTMXLayer:setMapTileSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXLayer_setMapTileSize'", nullptr); @@ -102911,9 +103101,9 @@ int lua_cocos2dx_FastTMXLayer_setLayerName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FastTMXLayer:setLayerName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FastTMXLayer:setLayerName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXLayer_setLayerName'", nullptr); @@ -103233,8 +103423,8 @@ int lua_cocos2dx_FastTMXLayer_getMapTileSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXLayer_getMapTileSize'", nullptr); return 0; } - const cocos2d::Size& ret = cobj->getMapTileSize(); - size_to_luaval(tolua_S, ret); + const cocos2d::Vec2& ret = cobj->getMapTileSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.FastTMXLayer:getMapTileSize",argc, 0); @@ -103275,9 +103465,9 @@ int lua_cocos2dx_FastTMXLayer_getProperty(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FastTMXLayer:getProperty"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FastTMXLayer:getProperty"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXLayer_getProperty'", nullptr); @@ -103325,9 +103515,9 @@ int lua_cocos2dx_FastTMXLayer_setLayerSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.FastTMXLayer:setLayerSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.FastTMXLayer:setLayerSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXLayer_setLayerSize'", nullptr); @@ -103380,8 +103570,8 @@ int lua_cocos2dx_FastTMXLayer_getLayerName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXLayer_getLayerName'", nullptr); return 0; } - const std::string& ret = cobj->getLayerName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getLayerName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.FastTMXLayer:getLayerName",argc, 0); @@ -104281,9 +104471,9 @@ int lua_cocos2dx_FastTMXTiledMap_getProperty(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:getProperty"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:getProperty"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_getProperty'", nullptr); @@ -104331,9 +104521,9 @@ int lua_cocos2dx_FastTMXTiledMap_setMapSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.FastTMXTiledMap:setMapSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.FastTMXTiledMap:setMapSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_setMapSize'", nullptr); @@ -104381,9 +104571,9 @@ int lua_cocos2dx_FastTMXTiledMap_getObjectGroup(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:getObjectGroup"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:getObjectGroup"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_getObjectGroup'", nullptr); @@ -104436,8 +104626,8 @@ int lua_cocos2dx_FastTMXTiledMap_getResourceFile(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_getResourceFile'", nullptr); return 0; } - const std::string& ret = cobj->getResourceFile(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getResourceFile(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.FastTMXTiledMap:getResourceFile",argc, 0); @@ -104572,9 +104762,9 @@ int lua_cocos2dx_FastTMXTiledMap_initWithTMXFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:initWithTMXFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:initWithTMXFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_initWithTMXFile'", nullptr); @@ -104627,8 +104817,8 @@ int lua_cocos2dx_FastTMXTiledMap_getTileSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_getTileSize'", nullptr); return 0; } - const cocos2d::Size& ret = cobj->getTileSize(); - size_to_luaval(tolua_S, ret); + const cocos2d::Vec2& ret = cobj->getTileSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.FastTMXTiledMap:getTileSize",argc, 0); @@ -104674,8 +104864,8 @@ int lua_cocos2dx_FastTMXTiledMap_getMapSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_getMapSize'", nullptr); return 0; } - const cocos2d::Size& ret = cobj->getMapSize(); - size_to_luaval(tolua_S, ret); + const cocos2d::Vec2& ret = cobj->getMapSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.FastTMXTiledMap:getMapSize",argc, 0); @@ -104766,12 +104956,12 @@ int lua_cocos2dx_FastTMXTiledMap_initWithXML(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:initWithXML"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:initWithXML"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FastTMXTiledMap:initWithXML"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FastTMXTiledMap:initWithXML"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_initWithXML'", nullptr); @@ -104916,9 +105106,9 @@ int lua_cocos2dx_FastTMXTiledMap_setTileSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.FastTMXTiledMap:setTileSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.FastTMXTiledMap:setTileSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_setTileSize'", nullptr); @@ -105016,9 +105206,9 @@ int lua_cocos2dx_FastTMXTiledMap_getLayer(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:getLayer"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:getLayer"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_getLayer'", nullptr); @@ -105152,8 +105342,8 @@ int lua_cocos2dx_FastTMXTiledMap_create(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_create'", nullptr); @@ -105188,10 +105378,10 @@ int lua_cocos2dx_FastTMXTiledMap_createWithXML(lua_State* tolua_S) if (argc == 2) { - std::string arg0; - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:createWithXML"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.FastTMXTiledMap:createWithXML"); + std::string_view arg0; + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.FastTMXTiledMap:createWithXML"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.FastTMXTiledMap:createWithXML"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_FastTMXTiledMap_createWithXML'", nullptr); @@ -105836,8 +106026,8 @@ int lua_cocos2dx_MotionStreak3D_initWithFade(lua_State* tolua_S) ok &= luaval_to_color3b(tolua_S, 5, &arg3, "cc.MotionStreak3D:initWithFade"); if (!ok) { break; } - std::string arg4; - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "cc.MotionStreak3D:initWithFade"); + std::string_view arg4; + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "cc.MotionStreak3D:initWithFade"); if (!ok) { break; } bool ret = cobj->initWithFade(arg0, arg1, arg2, arg3, arg4); @@ -106011,8 +106201,8 @@ int lua_cocos2dx_MotionStreak3D_create(lua_State* tolua_S) cocos2d::Color3B arg3; ok &= luaval_to_color3b(tolua_S, 5, &arg3, "cc.MotionStreak3D:create"); if (!ok) { break; } - std::string arg4; - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "cc.MotionStreak3D:create"); + std::string_view arg4; + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "cc.MotionStreak3D:create"); if (!ok) { break; } cocos2d::MotionStreak3D* ret = cocos2d::MotionStreak3D::create(arg0, arg1, arg2, arg3, arg4); object_to_luaval(tolua_S, "cc.MotionStreak3D",(cocos2d::MotionStreak3D*)ret); @@ -106213,8 +106403,8 @@ int lua_cocos2dx_ComponentLua_create(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.ComponentLua:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.ComponentLua:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ComponentLua_create'", nullptr); @@ -106247,9 +106437,9 @@ int lua_cocos2dx_ComponentLua_constructor(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.ComponentLua:ComponentLua"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.ComponentLua:ComponentLua"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ComponentLua_constructor'", nullptr); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_auto.hpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_auto.hpp index 3e1cc6c6fe41..d7b8e611d950 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_auto.hpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_auto.hpp @@ -2328,6 +2328,10 @@ int register_all_cocos2dx(lua_State* tolua_S); + + + + diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_backend_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_backend_auto.cpp index 57a704777bc8..2523bad8605c 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_backend_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_backend_auto.cpp @@ -572,8 +572,8 @@ int lua_cocos2dx_backend_Program_getFragmentShader(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_backend_Program_getFragmentShader'", nullptr); return 0; } - const std::string& ret = cobj->getFragmentShader(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getFragmentShader(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccb.Program:getFragmentShader",argc, 0); @@ -671,8 +671,8 @@ int lua_cocos2dx_backend_Program_getUniformLocation(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccb.Program:getUniformLocation"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccb.Program:getUniformLocation"); if (!ok) { break; } cocos2d::backend::UniformLocation ret = cobj->getUniformLocation(arg0); @@ -771,7 +771,7 @@ int lua_cocos2dx_backend_Program_getActiveAttributes(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_backend_Program_getActiveAttributes'", nullptr); return 0; } - std::unordered_map ret = cobj->getActiveAttributes(); + tsl::robin_map ret = cobj->getActiveAttributes(); program_activeattrs_to_luaval(tolua_S, ret); return 1; } @@ -820,8 +820,8 @@ int lua_cocos2dx_backend_Program_getAttributeLocation(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccb.Program:getAttributeLocation"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccb.Program:getAttributeLocation"); if (!ok) { break; } int ret = cobj->getAttributeLocation(arg0); @@ -873,8 +873,8 @@ int lua_cocos2dx_backend_Program_getVertexShader(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_backend_Program_getVertexShader'", nullptr); return 0; } - const std::string& ret = cobj->getVertexShader(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getVertexShader(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccb.Program:getVertexShader",argc, 0); @@ -1125,13 +1125,13 @@ int lua_cocos2dx_backend_VertexLayout_setAttribute(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 5) { - std::string arg0; + std::string_view arg0; unsigned int arg1; cocos2d::backend::VertexFormat arg2; unsigned int arg3; bool arg4; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccb.VertexLayout:setAttribute"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccb.VertexLayout:setAttribute"); ok &= luaval_to_uint32(tolua_S, 3,&arg1, "ccb.VertexLayout:setAttribute"); @@ -1293,8 +1293,8 @@ int lua_cocos2dx_backend_ProgramState_setTexture(lua_State* tolua_S) ok &= luaval_to_uniformLocation(tolua_S, 2, arg0, "ccb.ProgramState:setTexture"); if (!ok) { break; } - unsigned short arg1; - ok &= luaval_to_ushort(tolua_S, 3, &arg1, "ccb.ProgramState:setTexture"); + int arg1; + ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccb.ProgramState:setTexture"); if (!ok) { break; } cocos2d::backend::TextureBackend* arg2; @@ -1325,12 +1325,12 @@ int lua_cocos2dx_backend_ProgramState_setTexture(lua_State* tolua_S) ok &= luaval_to_uniformLocation(tolua_S, 2, arg0, "ccb.ProgramState:setTexture"); if (!ok) { break; } - unsigned short arg1; - ok &= luaval_to_ushort(tolua_S, 3, &arg1, "ccb.ProgramState:setTexture"); + int arg1; + ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccb.ProgramState:setTexture"); if (!ok) { break; } - unsigned short arg2; - ok &= luaval_to_ushort(tolua_S, 4, &arg2, "ccb.ProgramState:setTexture"); + int arg2; + ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "ccb.ProgramState:setTexture"); if (!ok) { break; } cocos2d::backend::TextureBackend* arg3; @@ -1489,12 +1489,12 @@ int lua_cocos2dx_backend_ProgramState_setParameterAutoBinding(lua_State* tolua_S argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccb.ProgramState:setParameterAutoBinding"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccb.ProgramState:setParameterAutoBinding"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccb.ProgramState:setParameterAutoBinding"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccb.ProgramState:setParameterAutoBinding"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_backend_ProgramState_setParameterAutoBinding'", nullptr); @@ -1643,8 +1643,8 @@ int lua_cocos2dx_backend_ProgramState_getAttributeLocation(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccb.ProgramState:getAttributeLocation"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccb.ProgramState:getAttributeLocation"); if (!ok) { break; } int ret = cobj->getAttributeLocation(arg0); @@ -2992,12 +2992,12 @@ int lua_cocos2dx_backend_Device_newProgram(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccb.Device:newProgram"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccb.Device:newProgram"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccb.Device:newProgram"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccb.Device:newProgram"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_backend_Device_newProgram'", nullptr); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_controller_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_controller_auto.cpp index de4305f33eae..589c61ad7f61 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_controller_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_controller_auto.cpp @@ -90,8 +90,8 @@ int lua_cocos2dx_controller_Controller_getDeviceName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_controller_Controller_getDeviceName'", nullptr); return 0; } - const std::string& ret = cobj->getDeviceName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getDeviceName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Controller:getDeviceName",argc, 0); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_csloader_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_csloader_auto.cpp index fd903bb40492..30343b1ce5bf 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_csloader_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_csloader_auto.cpp @@ -31,9 +31,9 @@ int lua_cocos2dx_csloader_CSLoader_createNodeFromJson(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CSLoader:createNodeFromJson"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.CSLoader:createNodeFromJson"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_csloader_CSLoader_createNodeFromJson'", nullptr); @@ -81,9 +81,9 @@ int lua_cocos2dx_csloader_CSLoader_createNodeWithFlatBuffersFile(lua_State* tolu argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CSLoader:createNodeWithFlatBuffersFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.CSLoader:createNodeWithFlatBuffersFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_csloader_CSLoader_createNodeWithFlatBuffersFile'", nullptr); @@ -131,9 +131,9 @@ int lua_cocos2dx_csloader_CSLoader_loadNodeWithFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CSLoader:loadNodeWithFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.CSLoader:loadNodeWithFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_csloader_CSLoader_loadNodeWithFile'", nullptr); @@ -181,14 +181,14 @@ int lua_cocos2dx_csloader_CSLoader_bindCallback(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 4) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; cocos2d::ui::Widget* arg2; cocos2d::Node* arg3; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CSLoader:bindCallback"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.CSLoader:bindCallback"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.CSLoader:bindCallback"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.CSLoader:bindCallback"); ok &= luaval_to_object(tolua_S, 4, "ccui.Widget",&arg2, "cc.CSLoader:bindCallback"); @@ -337,9 +337,9 @@ int lua_cocos2dx_csloader_CSLoader_loadNodeWithContent(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CSLoader:loadNodeWithContent"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.CSLoader:loadNodeWithContent"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_csloader_CSLoader_loadNodeWithContent'", nullptr); @@ -531,9 +531,9 @@ int lua_cocos2dx_csloader_CSLoader_createNodeWithFlatBuffersForSimulator(lua_Sta argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CSLoader:createNodeWithFlatBuffersForSimulator"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.CSLoader:createNodeWithFlatBuffersForSimulator"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_csloader_CSLoader_createNodeWithFlatBuffersForSimulator'", nullptr); @@ -605,8 +605,8 @@ int lua_cocos2dx_csloader_CSLoader_createNodeWithVisibleSize(lua_State* tolua_S) { if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CSLoader:createNodeWithVisibleSize"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.CSLoader:createNodeWithVisibleSize"); if (!ok) { break; } std::function arg1; do { @@ -625,8 +625,8 @@ int lua_cocos2dx_csloader_CSLoader_createNodeWithVisibleSize(lua_State* tolua_S) { if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CSLoader:createNodeWithVisibleSize"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.CSLoader:createNodeWithVisibleSize"); if (!ok) { break; } cocos2d::Node* ret = cocos2d::CSLoader::createNodeWithVisibleSize(arg0); object_to_luaval(tolua_S, "cc.Node",(cocos2d::Node*)ret); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_extension_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_extension_auto.cpp index bd142213112e..0daaca8566d9 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_extension_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_extension_auto.cpp @@ -471,8 +471,8 @@ int lua_cocos2dx_extension_AssetsManager_getVersion(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_AssetsManager_getVersion'", nullptr); return 0; } - std::string ret = cobj->getVersion(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getVersion(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.AssetsManager:getVersion",argc, 0); @@ -1158,11 +1158,11 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 3) { - std::string arg0; + std::string_view arg0; cocos2d::extension::AssetsManagerEx* arg1; cocos2d::extension::EventAssetsManagerEx::EventCode arg2; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); ok &= luaval_to_object(tolua_S, 3, "cc.AssetsManagerEx",&arg1, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); @@ -1181,12 +1181,12 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) } if (argc == 4) { - std::string arg0; + std::string_view arg0; cocos2d::extension::AssetsManagerEx* arg1; cocos2d::extension::EventAssetsManagerEx::EventCode arg2; double arg3; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); ok &= luaval_to_object(tolua_S, 3, "cc.AssetsManagerEx",&arg1, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); @@ -1207,13 +1207,13 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) } if (argc == 5) { - std::string arg0; + std::string_view arg0; cocos2d::extension::AssetsManagerEx* arg1; cocos2d::extension::EventAssetsManagerEx::EventCode arg2; double arg3; double arg4; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); ok &= luaval_to_object(tolua_S, 3, "cc.AssetsManagerEx",&arg1, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); @@ -1236,14 +1236,14 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) } if (argc == 6) { - std::string arg0; + std::string_view arg0; cocos2d::extension::AssetsManagerEx* arg1; cocos2d::extension::EventAssetsManagerEx::EventCode arg2; double arg3; double arg4; - std::string arg5; + std::string_view arg5; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); ok &= luaval_to_object(tolua_S, 3, "cc.AssetsManagerEx",&arg1, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); @@ -1253,7 +1253,7 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) ok &= luaval_to_number(tolua_S, 6,&arg4, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); - ok &= luaval_to_std_string(tolua_S, 7,&arg5, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_EventAssetsManagerEx_constructor'", nullptr); @@ -1268,15 +1268,15 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) } if (argc == 7) { - std::string arg0; + std::string_view arg0; cocos2d::extension::AssetsManagerEx* arg1; cocos2d::extension::EventAssetsManagerEx::EventCode arg2; double arg3; double arg4; - std::string arg5; - std::string arg6; + std::string_view arg5; + std::string_view arg6; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); ok &= luaval_to_object(tolua_S, 3, "cc.AssetsManagerEx",&arg1, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); @@ -1286,9 +1286,9 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) ok &= luaval_to_number(tolua_S, 6,&arg4, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); - ok &= luaval_to_std_string(tolua_S, 7,&arg5, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); - ok &= luaval_to_std_string(tolua_S, 8,&arg6, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string_view(tolua_S, 8,&arg6, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_EventAssetsManagerEx_constructor'", nullptr); @@ -1303,16 +1303,16 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) } if (argc == 8) { - std::string arg0; + std::string_view arg0; cocos2d::extension::AssetsManagerEx* arg1; cocos2d::extension::EventAssetsManagerEx::EventCode arg2; double arg3; double arg4; - std::string arg5; - std::string arg6; + std::string_view arg5; + std::string_view arg6; int arg7; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); ok &= luaval_to_object(tolua_S, 3, "cc.AssetsManagerEx",&arg1, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); @@ -1322,9 +1322,9 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) ok &= luaval_to_number(tolua_S, 6,&arg4, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); - ok &= luaval_to_std_string(tolua_S, 7,&arg5, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); - ok &= luaval_to_std_string(tolua_S, 8,&arg6, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string_view(tolua_S, 8,&arg6, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); ok &= luaval_to_int32(tolua_S, 9,(int *)&arg7, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); if(!ok) @@ -1341,17 +1341,17 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) } if (argc == 9) { - std::string arg0; + std::string_view arg0; cocos2d::extension::AssetsManagerEx* arg1; cocos2d::extension::EventAssetsManagerEx::EventCode arg2; double arg3; double arg4; - std::string arg5; - std::string arg6; + std::string_view arg5; + std::string_view arg6; int arg7; int arg8; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); ok &= luaval_to_object(tolua_S, 3, "cc.AssetsManagerEx",&arg1, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); @@ -1361,9 +1361,9 @@ int lua_cocos2dx_extension_EventAssetsManagerEx_constructor(lua_State* tolua_S) ok &= luaval_to_number(tolua_S, 6,&arg4, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); - ok &= luaval_to_std_string(tolua_S, 7,&arg5, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); - ok &= luaval_to_std_string(tolua_S, 8,&arg6, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); + ok &= luaval_to_std_string_view(tolua_S, 8,&arg6, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); ok &= luaval_to_int32(tolua_S, 9,(int *)&arg7, "cc.EventAssetsManagerEx:EventAssetsManagerEx"); @@ -1451,8 +1451,8 @@ int lua_cocos2dx_extension_Manifest_getManifestFileUrl(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_Manifest_getManifestFileUrl'", nullptr); return 0; } - const std::string& ret = cobj->getManifestFileUrl(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getManifestFileUrl(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Manifest:getManifestFileUrl",argc, 0); @@ -1592,8 +1592,8 @@ int lua_cocos2dx_extension_Manifest_getPackageUrl(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_Manifest_getPackageUrl'", nullptr); return 0; } - const std::string& ret = cobj->getPackageUrl(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getPackageUrl(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Manifest:getPackageUrl",argc, 0); @@ -1639,8 +1639,8 @@ int lua_cocos2dx_extension_Manifest_getVersion(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_Manifest_getVersion'", nullptr); return 0; } - const std::string& ret = cobj->getVersion(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getVersion(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Manifest:getVersion",argc, 0); @@ -1686,8 +1686,8 @@ int lua_cocos2dx_extension_Manifest_getVersionFileUrl(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_Manifest_getVersionFileUrl'", nullptr); return 0; } - const std::string& ret = cobj->getVersionFileUrl(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getVersionFileUrl(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Manifest:getVersionFileUrl",argc, 0); @@ -1942,7 +1942,7 @@ int lua_cocos2dx_extension_AssetsManagerEx_setVerifyCallback(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::function arg0; + std::function arg0; do { // Lambda binding for lua is not supported. @@ -2001,8 +2001,8 @@ int lua_cocos2dx_extension_AssetsManagerEx_getStoragePath(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_AssetsManagerEx_getStoragePath'", nullptr); return 0; } - const std::string& ret = cobj->getStoragePath(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getStoragePath(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.AssetsManagerEx:getStoragePath",argc, 0); @@ -2090,7 +2090,7 @@ int lua_cocos2dx_extension_AssetsManagerEx_setVersionCompareHandle(lua_State* to argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::function arg0; + std::function arg0; do { // Lambda binding for lua is not supported. @@ -2324,10 +2324,10 @@ int lua_cocos2dx_extension_AssetsManagerEx_create(lua_State* tolua_S) if (argc == 2) { - std::string arg0; - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AssetsManagerEx:create"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.AssetsManagerEx:create"); + std::string_view arg0; + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AssetsManagerEx:create"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.AssetsManagerEx:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_AssetsManagerEx_create'", nullptr); @@ -2360,12 +2360,12 @@ int lua_cocos2dx_extension_AssetsManagerEx_constructor(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.AssetsManagerEx:AssetsManagerEx"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.AssetsManagerEx:AssetsManagerEx"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.AssetsManagerEx:AssetsManagerEx"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.AssetsManagerEx:AssetsManagerEx"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_AssetsManagerEx_constructor'", nullptr); @@ -3604,9 +3604,9 @@ int lua_cocos2dx_extension_PUParticleSystem3D_initWithFilePath(lua_State* tolua_ argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:initWithFilePath"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:initWithFilePath"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_PUParticleSystem3D_initWithFilePath'", nullptr); @@ -3845,12 +3845,12 @@ int lua_cocos2dx_extension_PUParticleSystem3D_initWithFilePathAndMaterialPath(lu argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:initWithFilePathAndMaterialPath"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:initWithFilePathAndMaterialPath"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.PUParticleSystem3D:initWithFilePathAndMaterialPath"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.PUParticleSystem3D:initWithFilePathAndMaterialPath"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_PUParticleSystem3D_initWithFilePathAndMaterialPath'", nullptr); @@ -3950,8 +3950,8 @@ int lua_cocos2dx_extension_PUParticleSystem3D_getMaterialName(lua_State* tolua_S tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_PUParticleSystem3D_getMaterialName'", nullptr); return 0; } - const std::string& ret = cobj->getMaterialName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getMaterialName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.PUParticleSystem3D:getMaterialName",argc, 0); @@ -4821,9 +4821,9 @@ int lua_cocos2dx_extension_PUParticleSystem3D_setMaterialName(lua_State* tolua_S argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:setMaterialName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:setMaterialName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_PUParticleSystem3D_setMaterialName'", nullptr); @@ -5403,9 +5403,9 @@ int lua_cocos2dx_extension_PUParticleSystem3D_initSystem(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:initSystem"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:initSystem"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_extension_PUParticleSystem3D_initSystem'", nullptr); @@ -5641,8 +5641,8 @@ int lua_cocos2dx_extension_PUParticleSystem3D_create(lua_State* tolua_S) { if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:create"); if (!ok) { break; } cocos2d::PUParticleSystem3D* ret = cocos2d::PUParticleSystem3D::create(arg0); object_to_luaval(tolua_S, "cc.PUParticleSystem3D",(cocos2d::PUParticleSystem3D*)ret); @@ -5664,11 +5664,11 @@ int lua_cocos2dx_extension_PUParticleSystem3D_create(lua_State* tolua_S) { if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.PUParticleSystem3D:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.PUParticleSystem3D:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.PUParticleSystem3D:create"); if (!ok) { break; } cocos2d::PUParticleSystem3D* ret = cocos2d::PUParticleSystem3D::create(arg0, arg1); object_to_luaval(tolua_S, "cc.PUParticleSystem3D",(cocos2d::PUParticleSystem3D*)ret); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_navmesh_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_navmesh_auto.cpp index 61117700c3dd..abb3bf630ad4 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_navmesh_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_navmesh_auto.cpp @@ -1424,8 +1424,8 @@ int lua_cocos2dx_navmesh_NavMeshAgent_getNavMeshAgentComponentName(lua_State* to tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_navmesh_NavMeshAgent_getNavMeshAgentComponentName'", nullptr); return 0; } - const std::string& ret = cocos2d::NavMeshAgent::getNavMeshAgentComponentName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cocos2d::NavMeshAgent::getNavMeshAgentComponentName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "cc.NavMeshAgent:getNavMeshAgentComponentName",argc, 0); @@ -1958,8 +1958,8 @@ int lua_cocos2dx_navmesh_NavMeshObstacle_getNavMeshObstacleComponentName(lua_Sta tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_navmesh_NavMeshObstacle_getNavMeshObstacleComponentName'", nullptr); return 0; } - const std::string& ret = cocos2d::NavMeshObstacle::getNavMeshObstacleComponentName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cocos2d::NavMeshObstacle::getNavMeshObstacleComponentName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "cc.NavMeshObstacle:getNavMeshObstacleComponentName",argc, 0); @@ -2450,10 +2450,10 @@ int lua_cocos2dx_navmesh_NavMesh_create(lua_State* tolua_S) if (argc == 2) { - std::string arg0; - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.NavMesh:create"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "cc.NavMesh:create"); + std::string_view arg0; + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "cc.NavMesh:create"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "cc.NavMesh:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_navmesh_NavMesh_create'", nullptr); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_physics_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_physics_auto.cpp index 5d72cd0e8e0f..79c3f641c716 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_physics_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_physics_auto.cpp @@ -1930,8 +1930,8 @@ int lua_cocos2dx_physics_PhysicsShapeBox_getSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_physics_PhysicsShapeBox_getSize'", nullptr); return 0; } - cocos2d::Size ret = cobj->getSize(); - size_to_luaval(tolua_S, ret); + cocos2d::Vec2 ret = cobj->getSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.PhysicsShapeBox:getSize",argc, 0); @@ -1961,8 +1961,8 @@ int lua_cocos2dx_physics_PhysicsShapeBox_create(lua_State* tolua_S) if (argc == 1) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsShapeBox:create"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsShapeBox:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_physics_PhysicsShapeBox_create'", nullptr); @@ -1974,9 +1974,9 @@ int lua_cocos2dx_physics_PhysicsShapeBox_create(lua_State* tolua_S) } if (argc == 2) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; cocos2d::PhysicsMaterial arg1; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsShapeBox:create"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsShapeBox:create"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsShapeBox:create"); if(!ok) { @@ -1989,10 +1989,10 @@ int lua_cocos2dx_physics_PhysicsShapeBox_create(lua_State* tolua_S) } if (argc == 3) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; cocos2d::PhysicsMaterial arg1; cocos2d::Vec2 arg2; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsShapeBox:create"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsShapeBox:create"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsShapeBox:create"); ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.PhysicsShapeBox:create"); if(!ok) @@ -2006,11 +2006,11 @@ int lua_cocos2dx_physics_PhysicsShapeBox_create(lua_State* tolua_S) } if (argc == 4) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; cocos2d::PhysicsMaterial arg1; cocos2d::Vec2 arg2; double arg3; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsShapeBox:create"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsShapeBox:create"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsShapeBox:create"); ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.PhysicsShapeBox:create"); ok &= luaval_to_number(tolua_S, 5,&arg3, "cc.PhysicsShapeBox:create"); @@ -2326,8 +2326,8 @@ int lua_cocos2dx_physics_PhysicsShapeEdgeBox_create(lua_State* tolua_S) if (argc == 1) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsShapeEdgeBox:create"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsShapeEdgeBox:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_physics_PhysicsShapeEdgeBox_create'", nullptr); @@ -2339,9 +2339,9 @@ int lua_cocos2dx_physics_PhysicsShapeEdgeBox_create(lua_State* tolua_S) } if (argc == 2) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; cocos2d::PhysicsMaterial arg1; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsShapeEdgeBox:create"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsShapeEdgeBox:create"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsShapeEdgeBox:create"); if(!ok) { @@ -2354,10 +2354,10 @@ int lua_cocos2dx_physics_PhysicsShapeEdgeBox_create(lua_State* tolua_S) } if (argc == 3) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; cocos2d::PhysicsMaterial arg1; double arg2; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsShapeEdgeBox:create"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsShapeEdgeBox:create"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsShapeEdgeBox:create"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.PhysicsShapeEdgeBox:create"); if(!ok) @@ -2371,11 +2371,11 @@ int lua_cocos2dx_physics_PhysicsShapeEdgeBox_create(lua_State* tolua_S) } if (argc == 4) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; cocos2d::PhysicsMaterial arg1; double arg2; cocos2d::Vec2 arg3; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsShapeEdgeBox:create"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsShapeEdgeBox:create"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsShapeEdgeBox:create"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.PhysicsShapeEdgeBox:create"); ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.PhysicsShapeEdgeBox:create"); @@ -5515,8 +5515,8 @@ int lua_cocos2dx_physics_PhysicsBody_createBox(lua_State* tolua_S) if (argc == 1) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsBody:createBox"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsBody:createBox"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_physics_PhysicsBody_createBox'", nullptr); @@ -5528,9 +5528,9 @@ int lua_cocos2dx_physics_PhysicsBody_createBox(lua_State* tolua_S) } if (argc == 2) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; cocos2d::PhysicsMaterial arg1; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsBody:createBox"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsBody:createBox"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsBody:createBox"); if(!ok) { @@ -5543,10 +5543,10 @@ int lua_cocos2dx_physics_PhysicsBody_createBox(lua_State* tolua_S) } if (argc == 3) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; cocos2d::PhysicsMaterial arg1; cocos2d::Vec2 arg2; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsBody:createBox"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsBody:createBox"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsBody:createBox"); ok &= luaval_to_vec2(tolua_S, 4, &arg2, "cc.PhysicsBody:createBox"); if(!ok) @@ -5718,8 +5718,8 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgeBox(lua_State* tolua_S) if (argc == 1) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsBody:createEdgeBox"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsBody:createEdgeBox"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_physics_PhysicsBody_createEdgeBox'", nullptr); @@ -5731,9 +5731,9 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgeBox(lua_State* tolua_S) } if (argc == 2) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; cocos2d::PhysicsMaterial arg1; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsBody:createEdgeBox"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsBody:createEdgeBox"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsBody:createEdgeBox"); if(!ok) { @@ -5746,10 +5746,10 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgeBox(lua_State* tolua_S) } if (argc == 3) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; cocos2d::PhysicsMaterial arg1; double arg2; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsBody:createEdgeBox"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsBody:createEdgeBox"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsBody:createEdgeBox"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.PhysicsBody:createEdgeBox"); if(!ok) @@ -5763,11 +5763,11 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgeBox(lua_State* tolua_S) } if (argc == 4) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; cocos2d::PhysicsMaterial arg1; double arg2; cocos2d::Vec2 arg3; - ok &= luaval_to_size(tolua_S, 2, &arg0, "cc.PhysicsBody:createEdgeBox"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "cc.PhysicsBody:createEdgeBox"); ok &= luaval_to_physics_material(tolua_S, 3, &arg1, "cc.PhysicsBody:createEdgeBox"); ok &= luaval_to_number(tolua_S, 4,&arg2, "cc.PhysicsBody:createEdgeBox"); ok &= luaval_to_vec2(tolua_S, 5, &arg3, "cc.PhysicsBody:createEdgeBox"); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp index 35b2be46df6e..1887d9bfb8c1 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp @@ -3232,8 +3232,8 @@ int lua_cocos2dx_studio_DisplayData_changeDisplayToTexture(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.DisplayData:changeDisplayToTexture"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.DisplayData:changeDisplayToTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_DisplayData_changeDisplayToTexture'", nullptr); @@ -4039,9 +4039,9 @@ int lua_cocos2dx_studio_ArmatureData_getBoneData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureData:getBoneData"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureData:getBoneData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureData_getBoneData'", nullptr); @@ -4569,9 +4569,9 @@ int lua_cocos2dx_studio_MovementData_getMovementBoneData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.MovementData:getMovementBoneData"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.MovementData:getMovementBoneData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_MovementData_getMovementBoneData'", nullptr); @@ -4763,9 +4763,9 @@ int lua_cocos2dx_studio_AnimationData_getMovement(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.AnimationData:getMovement"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.AnimationData:getMovement"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_AnimationData_getMovement'", nullptr); @@ -6407,10 +6407,10 @@ int lua_cocos2dx_studio_DisplayManager_changeDisplayWithName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; + std::string_view arg0; bool arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.DisplayManager:changeDisplayWithName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.DisplayManager:changeDisplayWithName"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "ccs.DisplayManager:changeDisplayWithName"); if(!ok) @@ -7577,9 +7577,9 @@ int lua_cocos2dx_studio_Bone_init(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.Bone:init"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.Bone:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_Bone_init'", nullptr); @@ -8031,10 +8031,10 @@ int lua_cocos2dx_studio_Bone_changeDisplayWithName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; + std::string_view arg0; bool arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.Bone:changeDisplayWithName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.Bone:changeDisplayWithName"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "ccs.Bone:changeDisplayWithName"); if(!ok) @@ -8465,8 +8465,8 @@ int lua_cocos2dx_studio_Bone_create(lua_State* tolua_S) { if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.Bone:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.Bone:create"); if (!ok) { break; } cocostudio::Bone* ret = cocostudio::Bone::create(arg0); object_to_luaval(tolua_S, "ccs.Bone",(cocostudio::Bone*)ret); @@ -8712,9 +8712,9 @@ int lua_cocos2dx_studio_ArmatureAnimation_play(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureAnimation:play"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureAnimation:play"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureAnimation_play'", nullptr); @@ -8726,10 +8726,10 @@ int lua_cocos2dx_studio_ArmatureAnimation_play(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; int arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureAnimation:play"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureAnimation:play"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccs.ArmatureAnimation:play"); if(!ok) @@ -8743,11 +8743,11 @@ int lua_cocos2dx_studio_ArmatureAnimation_play(lua_State* tolua_S) } if (argc == 3) { - std::string arg0; + std::string_view arg0; int arg1; int arg2; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureAnimation:play"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureAnimation:play"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccs.ArmatureAnimation:play"); @@ -9558,9 +9558,9 @@ int lua_cocos2dx_studio_ArmatureDataManager_removeAnimationData(lua_State* tolua argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:removeAnimationData"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:removeAnimationData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_removeAnimationData'", nullptr); @@ -9608,10 +9608,10 @@ int lua_cocos2dx_studio_ArmatureDataManager_addArmatureData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; + std::string_view arg0; cocostudio::ArmatureData* arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addArmatureData"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addArmatureData"); ok &= luaval_to_object(tolua_S, 3, "ccs.ArmatureData",&arg1, "ccs.ArmatureDataManager:addArmatureData"); if(!ok) @@ -9625,15 +9625,15 @@ int lua_cocos2dx_studio_ArmatureDataManager_addArmatureData(lua_State* tolua_S) } if (argc == 3) { - std::string arg0; + std::string_view arg0; cocostudio::ArmatureData* arg1; - std::string arg2; + std::string_view arg2; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addArmatureData"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addArmatureData"); ok &= luaval_to_object(tolua_S, 3, "ccs.ArmatureData",&arg1, "ccs.ArmatureDataManager:addArmatureData"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccs.ArmatureDataManager:addArmatureData"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccs.ArmatureDataManager:addArmatureData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_addArmatureData'", nullptr); @@ -9676,16 +9676,16 @@ int lua_cocos2dx_studio_ArmatureDataManager_addArmatureFileInfo(lua_State* tolua argc = lua_gettop(tolua_S)-1; do{ if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addArmatureFileInfo"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addArmatureFileInfo"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.ArmatureDataManager:addArmatureFileInfo"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.ArmatureDataManager:addArmatureFileInfo"); if (!ok) { break; } - std::string arg2; - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccs.ArmatureDataManager:addArmatureFileInfo"); + std::string_view arg2; + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccs.ArmatureDataManager:addArmatureFileInfo"); if (!ok) { break; } cobj->addArmatureFileInfo(arg0, arg1, arg2); @@ -9696,8 +9696,8 @@ int lua_cocos2dx_studio_ArmatureDataManager_addArmatureFileInfo(lua_State* tolua ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addArmatureFileInfo"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addArmatureFileInfo"); if (!ok) { break; } cobj->addArmatureFileInfo(arg0); @@ -9744,9 +9744,9 @@ int lua_cocos2dx_studio_ArmatureDataManager_removeArmatureFileInfo(lua_State* to argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:removeArmatureFileInfo"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:removeArmatureFileInfo"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_removeArmatureFileInfo'", nullptr); @@ -9799,7 +9799,7 @@ int lua_cocos2dx_studio_ArmatureDataManager_getTextureDatas(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_getTextureDatas'", nullptr); return 0; } - const cocos2d::Map& ret = cobj->getTextureDatas(); + const cocos2d::Map& ret = cobj->getTextureDatas(); ccmap_string_key_to_luaval(tolua_S, ret); return 1; } @@ -9841,9 +9841,9 @@ int lua_cocos2dx_studio_ArmatureDataManager_getTextureData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:getTextureData"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:getTextureData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_getTextureData'", nullptr); @@ -9891,9 +9891,9 @@ int lua_cocos2dx_studio_ArmatureDataManager_getArmatureData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:getArmatureData"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:getArmatureData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_getArmatureData'", nullptr); @@ -9941,9 +9941,9 @@ int lua_cocos2dx_studio_ArmatureDataManager_getAnimationData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:getAnimationData"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:getAnimationData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_getAnimationData'", nullptr); @@ -9991,10 +9991,10 @@ int lua_cocos2dx_studio_ArmatureDataManager_addAnimationData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; + std::string_view arg0; cocostudio::AnimationData* arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addAnimationData"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addAnimationData"); ok &= luaval_to_object(tolua_S, 3, "ccs.AnimationData",&arg1, "ccs.ArmatureDataManager:addAnimationData"); if(!ok) @@ -10008,15 +10008,15 @@ int lua_cocos2dx_studio_ArmatureDataManager_addAnimationData(lua_State* tolua_S) } if (argc == 3) { - std::string arg0; + std::string_view arg0; cocostudio::AnimationData* arg1; - std::string arg2; + std::string_view arg2; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addAnimationData"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addAnimationData"); ok &= luaval_to_object(tolua_S, 3, "ccs.AnimationData",&arg1, "ccs.ArmatureDataManager:addAnimationData"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccs.ArmatureDataManager:addAnimationData"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccs.ArmatureDataManager:addAnimationData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_addAnimationData'", nullptr); @@ -10111,9 +10111,9 @@ int lua_cocos2dx_studio_ArmatureDataManager_removeArmatureData(lua_State* tolua_ argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:removeArmatureData"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:removeArmatureData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_removeArmatureData'", nullptr); @@ -10166,7 +10166,7 @@ int lua_cocos2dx_studio_ArmatureDataManager_getArmatureDatas(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_getArmatureDatas'", nullptr); return 0; } - const cocos2d::Map& ret = cobj->getArmatureDatas(); + const cocos2d::Map& ret = cobj->getArmatureDatas(); ccmap_string_key_to_luaval(tolua_S, ret); return 1; } @@ -10208,9 +10208,9 @@ int lua_cocos2dx_studio_ArmatureDataManager_addRelativeData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addRelativeData"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addRelativeData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_addRelativeData'", nullptr); @@ -10258,9 +10258,9 @@ int lua_cocos2dx_studio_ArmatureDataManager_removeTextureData(lua_State* tolua_S argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:removeTextureData"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:removeTextureData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_removeTextureData'", nullptr); @@ -10308,9 +10308,9 @@ int lua_cocos2dx_studio_ArmatureDataManager_getRelativeData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:getRelativeData"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:getRelativeData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_getRelativeData'", nullptr); @@ -10358,10 +10358,10 @@ int lua_cocos2dx_studio_ArmatureDataManager_addTextureData(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; + std::string_view arg0; cocostudio::TextureData* arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addTextureData"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addTextureData"); ok &= luaval_to_object(tolua_S, 3, "ccs.TextureData",&arg1, "ccs.ArmatureDataManager:addTextureData"); if(!ok) @@ -10375,15 +10375,15 @@ int lua_cocos2dx_studio_ArmatureDataManager_addTextureData(lua_State* tolua_S) } if (argc == 3) { - std::string arg0; + std::string_view arg0; cocostudio::TextureData* arg1; - std::string arg2; + std::string_view arg2; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addTextureData"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addTextureData"); ok &= luaval_to_object(tolua_S, 3, "ccs.TextureData",&arg1, "ccs.ArmatureDataManager:addTextureData"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccs.ArmatureDataManager:addTextureData"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccs.ArmatureDataManager:addTextureData"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_addTextureData'", nullptr); @@ -10436,7 +10436,7 @@ int lua_cocos2dx_studio_ArmatureDataManager_getAnimationDatas(lua_State* tolua_S tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_getAnimationDatas'", nullptr); return 0; } - const cocos2d::Map& ret = cobj->getAnimationDatas(); + const cocos2d::Map& ret = cobj->getAnimationDatas(); ccmap_string_key_to_luaval(tolua_S, ret); return 1; } @@ -10525,12 +10525,12 @@ int lua_cocos2dx_studio_ArmatureDataManager_addSpriteFrameFromFile(lua_State* to argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addSpriteFrameFromFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addSpriteFrameFromFile"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.ArmatureDataManager:addSpriteFrameFromFile"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.ArmatureDataManager:addSpriteFrameFromFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_addSpriteFrameFromFile'", nullptr); @@ -10542,15 +10542,15 @@ int lua_cocos2dx_studio_ArmatureDataManager_addSpriteFrameFromFile(lua_State* to } if (argc == 3) { - std::string arg0; - std::string arg1; - std::string arg2; + std::string_view arg0; + std::string_view arg1; + std::string_view arg2; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addSpriteFrameFromFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ArmatureDataManager:addSpriteFrameFromFile"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.ArmatureDataManager:addSpriteFrameFromFile"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.ArmatureDataManager:addSpriteFrameFromFile"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccs.ArmatureDataManager:addSpriteFrameFromFile"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccs.ArmatureDataManager:addSpriteFrameFromFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ArmatureDataManager_addSpriteFrameFromFile'", nullptr); @@ -10706,9 +10706,9 @@ int lua_cocos2dx_studio_Armature_getBone(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.Armature:getBone"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.Armature:getBone"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_Armature_getBone'", nullptr); @@ -10757,11 +10757,11 @@ int lua_cocos2dx_studio_Armature_changeBoneParent(lua_State* tolua_S) if (argc == 2) { cocostudio::Bone* arg0; - std::string arg1; + std::string_view arg1; ok &= luaval_to_object(tolua_S, 2, "ccs.Bone",&arg0, "ccs.Armature:changeBoneParent"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.Armature:changeBoneParent"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.Armature:changeBoneParent"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_Armature_changeBoneParent'", nullptr); @@ -11198,8 +11198,8 @@ int lua_cocos2dx_studio_Armature_init(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.Armature:init"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.Armature:init"); if (!ok) { break; } cocostudio::Bone* arg1; @@ -11214,8 +11214,8 @@ int lua_cocos2dx_studio_Armature_init(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.Armature:init"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.Armature:init"); if (!ok) { break; } bool ret = cobj->init(arg0); @@ -11460,11 +11460,11 @@ int lua_cocos2dx_studio_Armature_addBone(lua_State* tolua_S) if (argc == 2) { cocostudio::Bone* arg0; - std::string arg1; + std::string_view arg1; ok &= luaval_to_object(tolua_S, 2, "ccs.Bone",&arg0, "ccs.Armature:addBone"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.Armature:addBone"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.Armature:addBone"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_Armature_addBone'", nullptr); @@ -11755,7 +11755,7 @@ int lua_cocos2dx_studio_Armature_getBoneDic(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_Armature_getBoneDic'", nullptr); return 0; } - const cocos2d::Map& ret = cobj->getBoneDic(); + const cocos2d::Map& ret = cobj->getBoneDic(); ccmap_string_key_to_luaval(tolua_S, ret); return 1; } @@ -11787,8 +11787,8 @@ int lua_cocos2dx_studio_Armature_create(lua_State* tolua_S) { if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.Armature:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.Armature:create"); if (!ok) { break; } cocostudio::Armature* ret = cocostudio::Armature::create(arg0); object_to_luaval(tolua_S, "ccs.Armature",(cocostudio::Armature*)ret); @@ -11810,8 +11810,8 @@ int lua_cocos2dx_studio_Armature_create(lua_State* tolua_S) { if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.Armature:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.Armature:create"); if (!ok) { break; } cocostudio::Bone* arg1; ok &= luaval_to_object(tolua_S, 3, "ccs.Bone",&arg1, "ccs.Armature:create"); @@ -12037,8 +12037,8 @@ int lua_cocos2dx_studio_Skin_getDisplayName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_Skin_getDisplayName'", nullptr); return 0; } - const std::string& ret = cobj->getDisplayName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getDisplayName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccs.Skin:getDisplayName",argc, 0); @@ -12166,8 +12166,8 @@ int lua_cocos2dx_studio_Skin_create(lua_State* tolua_S) { if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.Skin:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.Skin:create"); if (!ok) { break; } cocostudio::Skin* ret = cocostudio::Skin::create(arg0); object_to_luaval(tolua_S, "ccs.Skin",(cocostudio::Skin*)ret); @@ -12210,8 +12210,8 @@ int lua_cocos2dx_studio_Skin_createWithSpriteFrameName(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.Skin:createWithSpriteFrameName"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.Skin:createWithSpriteFrameName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_Skin_createWithSpriteFrameName'", nullptr); @@ -12321,9 +12321,9 @@ int lua_cocos2dx_studio_ComAttribute_getFloat(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:getFloat"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:getFloat"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ComAttribute_getFloat'", nullptr); @@ -12335,10 +12335,10 @@ int lua_cocos2dx_studio_ComAttribute_getFloat(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; double arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:getFloat"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:getFloat"); ok &= luaval_to_number(tolua_S, 3,&arg1, "ccs.ComAttribute:getFloat"); if(!ok) @@ -12388,9 +12388,9 @@ int lua_cocos2dx_studio_ComAttribute_getString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:getString"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:getString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ComAttribute_getString'", nullptr); @@ -12402,12 +12402,12 @@ int lua_cocos2dx_studio_ComAttribute_getString(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:getString"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:getString"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.ComAttribute:getString"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.ComAttribute:getString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ComAttribute_getString'", nullptr); @@ -12455,10 +12455,10 @@ int lua_cocos2dx_studio_ComAttribute_setFloat(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; + std::string_view arg0; double arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:setFloat"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:setFloat"); ok &= luaval_to_number(tolua_S, 3,&arg1, "ccs.ComAttribute:setFloat"); if(!ok) @@ -12508,12 +12508,12 @@ int lua_cocos2dx_studio_ComAttribute_setString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:setString"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:setString"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.ComAttribute:setString"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.ComAttribute:setString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ComAttribute_setString'", nullptr); @@ -12561,9 +12561,9 @@ int lua_cocos2dx_studio_ComAttribute_getBool(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:getBool"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:getBool"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ComAttribute_getBool'", nullptr); @@ -12575,10 +12575,10 @@ int lua_cocos2dx_studio_ComAttribute_getBool(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; bool arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:getBool"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:getBool"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "ccs.ComAttribute:getBool"); if(!ok) @@ -12628,10 +12628,10 @@ int lua_cocos2dx_studio_ComAttribute_setInt(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; + std::string_view arg0; int arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:setInt"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:setInt"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccs.ComAttribute:setInt"); if(!ok) @@ -12681,9 +12681,9 @@ int lua_cocos2dx_studio_ComAttribute_parse(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:parse"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:parse"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ComAttribute_parse'", nullptr); @@ -12731,9 +12731,9 @@ int lua_cocos2dx_studio_ComAttribute_getInt(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:getInt"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:getInt"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ComAttribute_getInt'", nullptr); @@ -12745,10 +12745,10 @@ int lua_cocos2dx_studio_ComAttribute_getInt(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; int arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:getInt"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:getInt"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccs.ComAttribute:getInt"); if(!ok) @@ -12798,10 +12798,10 @@ int lua_cocos2dx_studio_ComAttribute_setBool(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; + std::string_view arg0; bool arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComAttribute:setBool"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComAttribute:setBool"); ok &= luaval_to_boolean(tolua_S, 3,&arg1, "ccs.ComAttribute:setBool"); if(!ok) @@ -14785,9 +14785,9 @@ int lua_cocos2dx_studio_GUIReader_setFilePath(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.GUIReader:setFilePath"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.GUIReader:setFilePath"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_GUIReader_setFilePath'", nullptr); @@ -14890,8 +14890,8 @@ int lua_cocos2dx_studio_GUIReader_getFilePath(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_GUIReader_getFilePath'", nullptr); return 0; } - const std::string& ret = cobj->getFilePath(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getFilePath(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccs.GUIReader:getFilePath",argc, 0); @@ -15180,9 +15180,9 @@ int lua_cocos2dx_studio_SceneReader_createNodeWithSceneFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.SceneReader:createNodeWithSceneFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.SceneReader:createNodeWithSceneFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_SceneReader_createNodeWithSceneFile'", nullptr); @@ -15194,10 +15194,10 @@ int lua_cocos2dx_studio_SceneReader_createNodeWithSceneFile(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocostudio::SceneReader::AttachComponentType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.SceneReader:createNodeWithSceneFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.SceneReader:createNodeWithSceneFile"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccs.SceneReader:createNodeWithSceneFile"); if(!ok) @@ -15472,9 +15472,9 @@ int lua_cocos2dx_studio_ActionTimelineCache_createActionFromJson(lua_State* tolu argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createActionFromJson"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createActionFromJson"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimelineCache_createActionFromJson'", nullptr); @@ -15522,9 +15522,9 @@ int lua_cocos2dx_studio_ActionTimelineCache_createActionWithFlatBuffersFile(lua_ argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createActionWithFlatBuffersFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createActionWithFlatBuffersFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimelineCache_createActionWithFlatBuffersFile'", nullptr); @@ -15572,9 +15572,9 @@ int lua_cocos2dx_studio_ActionTimelineCache_loadAnimationActionWithFlatBuffersFi argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:loadAnimationActionWithFlatBuffersFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:loadAnimationActionWithFlatBuffersFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimelineCache_loadAnimationActionWithFlatBuffersFile'", nullptr); @@ -15622,12 +15622,12 @@ int lua_cocos2dx_studio_ActionTimelineCache_createActionFromContent(lua_State* t argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createActionFromContent"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createActionFromContent"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.ActionTimelineCache:createActionFromContent"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.ActionTimelineCache:createActionFromContent"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimelineCache_createActionFromContent'", nullptr); @@ -15769,12 +15769,12 @@ int lua_cocos2dx_studio_ActionTimelineCache_loadAnimationActionWithContent(lua_S argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:loadAnimationActionWithContent"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:loadAnimationActionWithContent"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.ActionTimelineCache:loadAnimationActionWithContent"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.ActionTimelineCache:loadAnimationActionWithContent"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimelineCache_loadAnimationActionWithContent'", nullptr); @@ -15822,9 +15822,9 @@ int lua_cocos2dx_studio_ActionTimelineCache_loadAnimationActionWithFile(lua_Stat argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:loadAnimationActionWithFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:loadAnimationActionWithFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimelineCache_loadAnimationActionWithFile'", nullptr); @@ -15872,9 +15872,9 @@ int lua_cocos2dx_studio_ActionTimelineCache_removeAction(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:removeAction"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:removeAction"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimelineCache_removeAction'", nullptr); @@ -15922,9 +15922,9 @@ int lua_cocos2dx_studio_ActionTimelineCache_createActionWithFlatBuffersForSimula argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createActionWithFlatBuffersForSimulator"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createActionWithFlatBuffersForSimulator"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimelineCache_createActionWithFlatBuffersForSimulator'", nullptr); @@ -15995,8 +15995,8 @@ int lua_cocos2dx_studio_ActionTimelineCache_createAction(lua_State* tolua_S) if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createAction"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createAction"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimelineCache_createAction'", nullptr); @@ -17029,8 +17029,8 @@ int lua_cocos2dx_studio_TextureFrame_getTextureName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_TextureFrame_getTextureName'", nullptr); return 0; } - std::string ret = cobj->getTextureName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getTextureName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccs.TextureFrame:getTextureName",argc, 0); @@ -19147,9 +19147,9 @@ int lua_cocos2dx_studio_InnerActionFrame_setAnimationName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.InnerActionFrame:setAnimationName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.InnerActionFrame:setAnimationName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_InnerActionFrame_setAnimationName'", nullptr); @@ -19783,8 +19783,8 @@ int lua_cocos2dx_studio_EventFrame_getEvent(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_EventFrame_getEvent'", nullptr); return 0; } - std::string ret = cobj->getEvent(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getEvent(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccs.EventFrame:getEvent",argc, 0); @@ -22120,9 +22120,9 @@ int lua_cocos2dx_studio_ActionTimeline_getAnimationInfo(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimeline:getAnimationInfo"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimeline:getAnimationInfo"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimeline_getAnimationInfo'", nullptr); @@ -22218,12 +22218,12 @@ int lua_cocos2dx_studio_ActionTimeline_addFrameEndCallFunc(lua_State* tolua_S) if (argc == 3) { int arg0; - std::string arg1; + std::string_view arg1; std::function arg2; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccs.ActionTimeline:addFrameEndCallFunc"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.ActionTimeline:addFrameEndCallFunc"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.ActionTimeline:addFrameEndCallFunc"); do { // Lambda binding for lua is not supported. @@ -22721,9 +22721,9 @@ int lua_cocos2dx_studio_ActionTimeline_IsAnimationInfoExists(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimeline:IsAnimationInfoExists"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ActionTimeline:IsAnimationInfoExists"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimeline_IsAnimationInfoExists'", nullptr); @@ -23016,11 +23016,11 @@ int lua_cocos2dx_studio_ActionTimeline_removeFrameEndCallFunc(lua_State* tolua_S if (argc == 2) { int arg0; - std::string arg1; + std::string_view arg1; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccs.ActionTimeline:removeFrameEndCallFunc"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccs.ActionTimeline:removeFrameEndCallFunc"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccs.ActionTimeline:removeFrameEndCallFunc"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimeline_removeFrameEndCallFunc'", nullptr); @@ -23916,8 +23916,8 @@ int lua_cocos2dx_studio_BoneNode_displaySkin(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.BoneNode:displaySkin"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.BoneNode:displaySkin"); if (!ok) { break; } bool arg1; @@ -24605,9 +24605,9 @@ int lua_cocos2dx_studio_SkeletonNode_getBoneNode(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.SkeletonNode:getBoneNode"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.SkeletonNode:getBoneNode"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_SkeletonNode_getBoneNode'", nullptr); @@ -24650,8 +24650,8 @@ int lua_cocos2dx_studio_SkeletonNode_changeSkins(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.SkeletonNode:changeSkins"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.SkeletonNode:changeSkins"); if (!ok) { break; } cobj->changeSkins(arg0); @@ -24662,7 +24662,7 @@ int lua_cocos2dx_studio_SkeletonNode_changeSkins(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::map arg0; + tsl::robin_map arg0; ok &= luaval_to_std_map_string_string(tolua_S, 2, &arg0, "ccs.SkeletonNode:changeSkins"); if (!ok) { break; } @@ -24711,7 +24711,7 @@ int lua_cocos2dx_studio_SkeletonNode_addSkinGroup(lua_State* tolua_S) if (argc == 2) { std::string arg0; - std::map arg1; + tsl::robin_map arg1; ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.SkeletonNode:addSkinGroup"); @@ -24768,7 +24768,7 @@ int lua_cocos2dx_studio_SkeletonNode_getAllSubBonesMap(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_SkeletonNode_getAllSubBonesMap'", nullptr); return 0; } - const cocos2d::Map& ret = cobj->getAllSubBonesMap(); + const cocos2d::Map& ret = cobj->getAllSubBonesMap(); ccmap_string_key_to_luaval(tolua_S, ret); return 1; } @@ -25050,9 +25050,9 @@ int lua_cocos2dx_studio_ComExtensionData_setCustomProperty(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ComExtensionData:setCustomProperty"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccs.ComExtensionData:setCustomProperty"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ComExtensionData_setCustomProperty'", nullptr); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp index 31cef92257d5..c6176f00c078 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp @@ -559,9 +559,9 @@ int lua_cocos2dx_ui_RelativeLayoutParameter_setRelativeToWidgetName(lua_State* t argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RelativeLayoutParameter:setRelativeToWidgetName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RelativeLayoutParameter:setRelativeToWidgetName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RelativeLayoutParameter_setRelativeToWidgetName'", nullptr); @@ -614,8 +614,8 @@ int lua_cocos2dx_ui_RelativeLayoutParameter_getRelativeName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RelativeLayoutParameter_getRelativeName'", nullptr); return 0; } - const std::string& ret = cobj->getRelativeName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getRelativeName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.RelativeLayoutParameter:getRelativeName",argc, 0); @@ -661,8 +661,8 @@ int lua_cocos2dx_ui_RelativeLayoutParameter_getRelativeToWidgetName(lua_State* t tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RelativeLayoutParameter_getRelativeToWidgetName'", nullptr); return 0; } - const std::string& ret = cobj->getRelativeToWidgetName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getRelativeToWidgetName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.RelativeLayoutParameter:getRelativeToWidgetName",argc, 0); @@ -703,9 +703,9 @@ int lua_cocos2dx_ui_RelativeLayoutParameter_setRelativeName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RelativeLayoutParameter:setRelativeName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RelativeLayoutParameter:setRelativeName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RelativeLayoutParameter_setRelativeName'", nullptr); @@ -1003,8 +1003,8 @@ int lua_cocos2dx_ui_Widget_getCustomSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Widget_getCustomSize'", nullptr); return 0; } - const cocos2d::Size& ret = cobj->getCustomSize(); - size_to_luaval(tolua_S, ret); + const cocos2d::Vec2& ret = cobj->getCustomSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Widget:getCustomSize",argc, 0); @@ -1142,9 +1142,9 @@ int lua_cocos2dx_ui_Widget_setCallbackName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Widget:setCallbackName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Widget:setCallbackName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Widget_setCallbackName'", nullptr); @@ -1488,8 +1488,8 @@ int lua_cocos2dx_ui_Widget_getLayoutSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Widget_getLayoutSize'", nullptr); return 0; } - const cocos2d::Size& ret = cobj->getLayoutSize(); - size_to_luaval(tolua_S, ret); + const cocos2d::Vec2& ret = cobj->getLayoutSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Widget:getLayoutSize",argc, 0); @@ -1682,8 +1682,8 @@ int lua_cocos2dx_ui_Widget_getVirtualRendererSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Widget_getVirtualRendererSize'", nullptr); return 0; } - cocos2d::Size ret = cobj->getVirtualRendererSize(); - size_to_luaval(tolua_S, ret); + cocos2d::Vec2 ret = cobj->getVirtualRendererSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Widget:getVirtualRendererSize",argc, 0); @@ -2208,8 +2208,8 @@ int lua_cocos2dx_ui_Widget_getCallbackName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Widget_getCallbackName'", nullptr); return 0; } - const std::string& ret = cobj->getCallbackName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getCallbackName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Widget:getCallbackName",argc, 0); @@ -3274,8 +3274,8 @@ int lua_cocos2dx_ui_Widget_updateSizeAndPosition(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 1) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.Widget:updateSizeAndPosition"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.Widget:updateSizeAndPosition"); if (!ok) { break; } cobj->updateSizeAndPosition(arg0); @@ -3482,8 +3482,8 @@ int lua_cocos2dx_ui_Widget_getCallbackType(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Widget_getCallbackType'", nullptr); return 0; } - const std::string& ret = cobj->getCallbackType(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getCallbackType(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Widget:getCallbackType",argc, 0); @@ -3974,9 +3974,9 @@ int lua_cocos2dx_ui_Widget_setCallbackType(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Widget:setCallbackType"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Widget:setCallbackType"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Widget_setCallbackType'", nullptr); @@ -4929,9 +4929,9 @@ int lua_cocos2dx_ui_Layout_setBackGroundImage(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Layout:setBackGroundImage"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Layout:setBackGroundImage"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Layout_setBackGroundImage'", nullptr); @@ -4943,10 +4943,10 @@ int lua_cocos2dx_ui_Layout_setBackGroundImage(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Layout:setBackGroundImage"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Layout:setBackGroundImage"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.Layout:setBackGroundImage"); if(!ok) @@ -5633,8 +5633,8 @@ int lua_cocos2dx_ui_Layout_getBackGroundImageTextureSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Layout_getBackGroundImageTextureSize'", nullptr); return 0; } - const cocos2d::Size& ret = cobj->getBackGroundImageTextureSize(); - size_to_luaval(tolua_S, ret); + const cocos2d::Vec2& ret = cobj->getBackGroundImageTextureSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Layout:getBackGroundImageTextureSize",argc, 0); @@ -6132,8 +6132,8 @@ int lua_cocos2dx_ui_Button_getNormalTextureSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_getNormalTextureSize'", nullptr); return 0; } - cocos2d::Size ret = cobj->getNormalTextureSize(); - size_to_luaval(tolua_S, ret); + cocos2d::Vec2 ret = cobj->getNormalTextureSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Button:getNormalTextureSize",argc, 0); @@ -6179,8 +6179,8 @@ int lua_cocos2dx_ui_Button_getTitleText(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_getTitleText'", nullptr); return 0; } - std::string ret = cobj->getTitleText(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getTitleText(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Button:getTitleText",argc, 0); @@ -6991,9 +6991,9 @@ int lua_cocos2dx_ui_Button_loadTextureDisabled(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:loadTextureDisabled"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:loadTextureDisabled"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_loadTextureDisabled'", nullptr); @@ -7005,10 +7005,10 @@ int lua_cocos2dx_ui_Button_loadTextureDisabled(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:loadTextureDisabled"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:loadTextureDisabled"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.Button:loadTextureDisabled"); if(!ok) @@ -7058,9 +7058,9 @@ int lua_cocos2dx_ui_Button_init(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:init"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_init'", nullptr); @@ -7072,12 +7072,12 @@ int lua_cocos2dx_ui_Button_init(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:init"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:init"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Button:init"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Button:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_init'", nullptr); @@ -7089,15 +7089,15 @@ int lua_cocos2dx_ui_Button_init(lua_State* tolua_S) } if (argc == 3) { - std::string arg0; - std::string arg1; - std::string arg2; + std::string_view arg0; + std::string_view arg1; + std::string_view arg2; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:init"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:init"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Button:init"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Button:init"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.Button:init"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.Button:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_init'", nullptr); @@ -7109,16 +7109,16 @@ int lua_cocos2dx_ui_Button_init(lua_State* tolua_S) } if (argc == 4) { - std::string arg0; - std::string arg1; - std::string arg2; + std::string_view arg0; + std::string_view arg1; + std::string_view arg2; cocos2d::ui::Widget::TextureResType arg3; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:init"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:init"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Button:init"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Button:init"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.Button:init"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.Button:init"); ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "ccui.Button:init"); if(!ok) @@ -7168,9 +7168,9 @@ int lua_cocos2dx_ui_Button_setTitleText(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:setTitleText"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:setTitleText"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_setTitleText'", nullptr); @@ -7268,9 +7268,9 @@ int lua_cocos2dx_ui_Button_loadTexturePressed(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:loadTexturePressed"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:loadTexturePressed"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_loadTexturePressed'", nullptr); @@ -7282,10 +7282,10 @@ int lua_cocos2dx_ui_Button_loadTexturePressed(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:loadTexturePressed"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:loadTexturePressed"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.Button:loadTexturePressed"); if(!ok) @@ -7335,9 +7335,9 @@ int lua_cocos2dx_ui_Button_setTitleFontName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:setTitleFontName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:setTitleFontName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_setTitleFontName'", nullptr); @@ -7538,12 +7538,12 @@ int lua_cocos2dx_ui_Button_loadTextures(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:loadTextures"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Button:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Button:loadTextures"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_loadTextures'", nullptr); @@ -7555,15 +7555,15 @@ int lua_cocos2dx_ui_Button_loadTextures(lua_State* tolua_S) } if (argc == 3) { - std::string arg0; - std::string arg1; - std::string arg2; + std::string_view arg0; + std::string_view arg1; + std::string_view arg2; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:loadTextures"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Button:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Button:loadTextures"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.Button:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.Button:loadTextures"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_loadTextures'", nullptr); @@ -7575,16 +7575,16 @@ int lua_cocos2dx_ui_Button_loadTextures(lua_State* tolua_S) } if (argc == 4) { - std::string arg0; - std::string arg1; - std::string arg2; + std::string_view arg0; + std::string_view arg1; + std::string_view arg2; cocos2d::ui::Widget::TextureResType arg3; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:loadTextures"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Button:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Button:loadTextures"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.Button:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.Button:loadTextures"); ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "ccui.Button:loadTextures"); if(!ok) @@ -7681,9 +7681,9 @@ int lua_cocos2dx_ui_Button_loadTextureNormal(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:loadTextureNormal"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:loadTextureNormal"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_loadTextureNormal'", nullptr); @@ -7695,10 +7695,10 @@ int lua_cocos2dx_ui_Button_loadTextureNormal(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:loadTextureNormal"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:loadTextureNormal"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.Button:loadTextureNormal"); if(!ok) @@ -7991,8 +7991,8 @@ int lua_cocos2dx_ui_Button_getTitleFontName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Button_getTitleFontName'", nullptr); return 0; } - std::string ret = cobj->getTitleFontName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getTitleFontName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Button:getTitleFontName",argc, 0); @@ -8170,8 +8170,8 @@ int lua_cocos2dx_ui_Button_create(lua_State* tolua_S) { if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:create"); if (!ok) { break; } cocos2d::ui::Button* ret = cocos2d::ui::Button::create(arg0); object_to_luaval(tolua_S, "ccui.Button",(cocos2d::ui::Button*)ret); @@ -8183,11 +8183,11 @@ int lua_cocos2dx_ui_Button_create(lua_State* tolua_S) { if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Button:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Button:create"); if (!ok) { break; } cocos2d::ui::Button* ret = cocos2d::ui::Button::create(arg0, arg1); object_to_luaval(tolua_S, "ccui.Button",(cocos2d::ui::Button*)ret); @@ -8199,14 +8199,14 @@ int lua_cocos2dx_ui_Button_create(lua_State* tolua_S) { if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Button:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Button:create"); if (!ok) { break; } - std::string arg2; - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.Button:create"); + std::string_view arg2; + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.Button:create"); if (!ok) { break; } cocos2d::ui::Button* ret = cocos2d::ui::Button::create(arg0, arg1, arg2); object_to_luaval(tolua_S, "ccui.Button",(cocos2d::ui::Button*)ret); @@ -8218,14 +8218,14 @@ int lua_cocos2dx_ui_Button_create(lua_State* tolua_S) { if (argc == 4) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Button:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Button:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Button:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Button:create"); if (!ok) { break; } - std::string arg2; - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.Button:create"); + std::string_view arg2; + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.Button:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg3; ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "ccui.Button:create"); @@ -8508,9 +8508,9 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextureBackGroundSelected(lua_State* argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGroundSelected"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGroundSelected"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_AbstractCheckButton_loadTextureBackGroundSelected'", nullptr); @@ -8522,10 +8522,10 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextureBackGroundSelected(lua_State* } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGroundSelected"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGroundSelected"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.AbstractCheckButton:loadTextureBackGroundSelected"); if(!ok) @@ -8575,9 +8575,9 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextureBackGroundDisabled(lua_State* argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGroundDisabled"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGroundDisabled"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_AbstractCheckButton_loadTextureBackGroundDisabled'", nullptr); @@ -8589,10 +8589,10 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextureBackGroundDisabled(lua_State* } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGroundDisabled"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGroundDisabled"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.AbstractCheckButton:loadTextureBackGroundDisabled"); if(!ok) @@ -8880,9 +8880,9 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextureFrontCross(lua_State* tolua_S argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureFrontCross"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureFrontCross"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_AbstractCheckButton_loadTextureFrontCross'", nullptr); @@ -8894,10 +8894,10 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextureFrontCross(lua_State* tolua_S } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureFrontCross"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureFrontCross"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.AbstractCheckButton:loadTextureFrontCross"); if(!ok) @@ -9041,21 +9041,21 @@ int lua_cocos2dx_ui_AbstractCheckButton_init(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 5) { - std::string arg0; - std::string arg1; - std::string arg2; - std::string arg3; - std::string arg4; + std::string_view arg0; + std::string_view arg1; + std::string_view arg2; + std::string_view arg3; + std::string_view arg4; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:init"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:init"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.AbstractCheckButton:init"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.AbstractCheckButton:init"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.AbstractCheckButton:init"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.AbstractCheckButton:init"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.AbstractCheckButton:init"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.AbstractCheckButton:init"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.AbstractCheckButton:init"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.AbstractCheckButton:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_AbstractCheckButton_init'", nullptr); @@ -9067,22 +9067,22 @@ int lua_cocos2dx_ui_AbstractCheckButton_init(lua_State* tolua_S) } if (argc == 6) { - std::string arg0; - std::string arg1; - std::string arg2; - std::string arg3; - std::string arg4; + std::string_view arg0; + std::string_view arg1; + std::string_view arg2; + std::string_view arg3; + std::string_view arg4; cocos2d::ui::Widget::TextureResType arg5; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:init"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:init"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.AbstractCheckButton:init"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.AbstractCheckButton:init"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.AbstractCheckButton:init"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.AbstractCheckButton:init"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.AbstractCheckButton:init"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.AbstractCheckButton:init"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.AbstractCheckButton:init"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.AbstractCheckButton:init"); ok &= luaval_to_int32(tolua_S, 7,(int *)&arg5, "ccui.AbstractCheckButton:init"); if(!ok) @@ -9179,21 +9179,21 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextures(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 5) { - std::string arg0; - std::string arg1; - std::string arg2; - std::string arg3; - std::string arg4; + std::string_view arg0; + std::string_view arg1; + std::string_view arg2; + std::string_view arg3; + std::string_view arg4; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextures"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.AbstractCheckButton:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.AbstractCheckButton:loadTextures"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.AbstractCheckButton:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.AbstractCheckButton:loadTextures"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.AbstractCheckButton:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.AbstractCheckButton:loadTextures"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.AbstractCheckButton:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.AbstractCheckButton:loadTextures"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_AbstractCheckButton_loadTextures'", nullptr); @@ -9205,22 +9205,22 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextures(lua_State* tolua_S) } if (argc == 6) { - std::string arg0; - std::string arg1; - std::string arg2; - std::string arg3; - std::string arg4; + std::string_view arg0; + std::string_view arg1; + std::string_view arg2; + std::string_view arg3; + std::string_view arg4; cocos2d::ui::Widget::TextureResType arg5; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextures"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.AbstractCheckButton:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.AbstractCheckButton:loadTextures"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.AbstractCheckButton:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.AbstractCheckButton:loadTextures"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.AbstractCheckButton:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.AbstractCheckButton:loadTextures"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.AbstractCheckButton:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.AbstractCheckButton:loadTextures"); ok &= luaval_to_int32(tolua_S, 7,(int *)&arg5, "ccui.AbstractCheckButton:loadTextures"); if(!ok) @@ -9411,9 +9411,9 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextureBackGround(lua_State* tolua_S argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGround"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGround"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_AbstractCheckButton_loadTextureBackGround'", nullptr); @@ -9425,10 +9425,10 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextureBackGround(lua_State* tolua_S } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGround"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureBackGround"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.AbstractCheckButton:loadTextureBackGround"); if(!ok) @@ -9528,9 +9528,9 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextureFrontCrossDisabled(lua_State* argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureFrontCrossDisabled"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureFrontCrossDisabled"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_AbstractCheckButton_loadTextureFrontCrossDisabled'", nullptr); @@ -9542,10 +9542,10 @@ int lua_cocos2dx_ui_AbstractCheckButton_loadTextureFrontCrossDisabled(lua_State* } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureFrontCrossDisabled"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.AbstractCheckButton:loadTextureFrontCrossDisabled"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.AbstractCheckButton:loadTextureFrontCrossDisabled"); if(!ok) @@ -9679,20 +9679,20 @@ int lua_cocos2dx_ui_CheckBox_create(lua_State* tolua_S) { if (argc == 5) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.CheckBox:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.CheckBox:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.CheckBox:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.CheckBox:create"); if (!ok) { break; } - std::string arg2; - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.CheckBox:create"); + std::string_view arg2; + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.CheckBox:create"); if (!ok) { break; } - std::string arg3; - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.CheckBox:create"); + std::string_view arg3; + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.CheckBox:create"); if (!ok) { break; } - std::string arg4; - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.CheckBox:create"); + std::string_view arg4; + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.CheckBox:create"); if (!ok) { break; } cocos2d::ui::CheckBox* ret = cocos2d::ui::CheckBox::create(arg0, arg1, arg2, arg3, arg4); object_to_luaval(tolua_S, "ccui.CheckBox",(cocos2d::ui::CheckBox*)ret); @@ -9704,20 +9704,20 @@ int lua_cocos2dx_ui_CheckBox_create(lua_State* tolua_S) { if (argc == 6) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.CheckBox:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.CheckBox:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.CheckBox:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.CheckBox:create"); if (!ok) { break; } - std::string arg2; - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.CheckBox:create"); + std::string_view arg2; + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.CheckBox:create"); if (!ok) { break; } - std::string arg3; - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.CheckBox:create"); + std::string_view arg3; + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.CheckBox:create"); if (!ok) { break; } - std::string arg4; - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.CheckBox:create"); + std::string_view arg4; + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.CheckBox:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg5; ok &= luaval_to_int32(tolua_S, 7,(int *)&arg5, "ccui.CheckBox:create"); @@ -9742,11 +9742,11 @@ int lua_cocos2dx_ui_CheckBox_create(lua_State* tolua_S) { if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.CheckBox:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.CheckBox:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.CheckBox:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.CheckBox:create"); if (!ok) { break; } cocos2d::ui::CheckBox* ret = cocos2d::ui::CheckBox::create(arg0, arg1); object_to_luaval(tolua_S, "ccui.CheckBox",(cocos2d::ui::CheckBox*)ret); @@ -9758,11 +9758,11 @@ int lua_cocos2dx_ui_CheckBox_create(lua_State* tolua_S) { if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.CheckBox:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.CheckBox:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.CheckBox:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.CheckBox:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "ccui.CheckBox:create"); @@ -9947,20 +9947,20 @@ int lua_cocos2dx_ui_RadioButton_create(lua_State* tolua_S) { if (argc == 5) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RadioButton:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RadioButton:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.RadioButton:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.RadioButton:create"); if (!ok) { break; } - std::string arg2; - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.RadioButton:create"); + std::string_view arg2; + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.RadioButton:create"); if (!ok) { break; } - std::string arg3; - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RadioButton:create"); + std::string_view arg3; + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RadioButton:create"); if (!ok) { break; } - std::string arg4; - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RadioButton:create"); + std::string_view arg4; + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RadioButton:create"); if (!ok) { break; } cocos2d::ui::RadioButton* ret = cocos2d::ui::RadioButton::create(arg0, arg1, arg2, arg3, arg4); object_to_luaval(tolua_S, "ccui.RadioButton",(cocos2d::ui::RadioButton*)ret); @@ -9972,20 +9972,20 @@ int lua_cocos2dx_ui_RadioButton_create(lua_State* tolua_S) { if (argc == 6) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RadioButton:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RadioButton:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.RadioButton:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.RadioButton:create"); if (!ok) { break; } - std::string arg2; - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.RadioButton:create"); + std::string_view arg2; + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.RadioButton:create"); if (!ok) { break; } - std::string arg3; - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RadioButton:create"); + std::string_view arg3; + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RadioButton:create"); if (!ok) { break; } - std::string arg4; - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RadioButton:create"); + std::string_view arg4; + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RadioButton:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg5; ok &= luaval_to_int32(tolua_S, 7,(int *)&arg5, "ccui.RadioButton:create"); @@ -10010,11 +10010,11 @@ int lua_cocos2dx_ui_RadioButton_create(lua_State* tolua_S) { if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RadioButton:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RadioButton:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.RadioButton:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.RadioButton:create"); if (!ok) { break; } cocos2d::ui::RadioButton* ret = cocos2d::ui::RadioButton::create(arg0, arg1); object_to_luaval(tolua_S, "ccui.RadioButton",(cocos2d::ui::RadioButton*)ret); @@ -10026,11 +10026,11 @@ int lua_cocos2dx_ui_RadioButton_create(lua_State* tolua_S) { if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RadioButton:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RadioButton:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.RadioButton:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.RadioButton:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "ccui.RadioButton:create"); @@ -10873,9 +10873,9 @@ int lua_cocos2dx_ui_ImageView_loadTexture(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.ImageView:loadTexture"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.ImageView:loadTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_ImageView_loadTexture'", nullptr); @@ -10887,10 +10887,10 @@ int lua_cocos2dx_ui_ImageView_loadTexture(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.ImageView:loadTexture"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.ImageView:loadTexture"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.ImageView:loadTexture"); if(!ok) @@ -10990,9 +10990,9 @@ int lua_cocos2dx_ui_ImageView_init(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.ImageView:init"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.ImageView:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_ImageView_init'", nullptr); @@ -11004,10 +11004,10 @@ int lua_cocos2dx_ui_ImageView_init(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.ImageView:init"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.ImageView:init"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.ImageView:init"); if(!ok) @@ -11338,8 +11338,8 @@ int lua_cocos2dx_ui_ImageView_create(lua_State* tolua_S) { if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.ImageView:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.ImageView:create"); if (!ok) { break; } cocos2d::ui::ImageView* ret = cocos2d::ui::ImageView::create(arg0); object_to_luaval(tolua_S, "ccui.ImageView",(cocos2d::ui::ImageView*)ret); @@ -11351,8 +11351,8 @@ int lua_cocos2dx_ui_ImageView_create(lua_State* tolua_S) { if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.ImageView:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.ImageView:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg1; ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.ImageView:create"); @@ -11538,11 +11538,11 @@ int lua_cocos2dx_ui_Text_enableShadow(lua_State* tolua_S) if (argc == 2) { cocos2d::Color4B arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; ok &=luaval_to_color4b(tolua_S, 2, &arg0, "ccui.Text:enableShadow"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "ccui.Text:enableShadow"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "ccui.Text:enableShadow"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Text_enableShadow'", nullptr); @@ -11555,12 +11555,12 @@ int lua_cocos2dx_ui_Text_enableShadow(lua_State* tolua_S) if (argc == 3) { cocos2d::Color4B arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; int arg2; ok &=luaval_to_color4b(tolua_S, 2, &arg0, "ccui.Text:enableShadow"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "ccui.Text:enableShadow"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "ccui.Text:enableShadow"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "ccui.Text:enableShadow"); if(!ok) @@ -11662,8 +11662,8 @@ int lua_cocos2dx_ui_Text_getString(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Text_getString'", nullptr); return 0; } - const std::string& ret = cobj->getString(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getString(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Text:getString",argc, 0); @@ -11946,9 +11946,9 @@ int lua_cocos2dx_ui_Text_setFontName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Text:setFontName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Text:setFontName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Text_setFontName'", nullptr); @@ -12051,8 +12051,8 @@ int lua_cocos2dx_ui_Text_getShadowOffset(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Text_getShadowOffset'", nullptr); return 0; } - cocos2d::Size ret = cobj->getShadowOffset(); - size_to_luaval(tolua_S, ret); + cocos2d::Vec2 ret = cobj->getShadowOffset(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Text:getShadowOffset",argc, 0); @@ -12093,9 +12093,9 @@ int lua_cocos2dx_ui_Text_setString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Text:setString"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Text:setString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Text_setString'", nullptr); @@ -12190,13 +12190,13 @@ int lua_cocos2dx_ui_Text_init(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 3) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; double arg2; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Text:init"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Text:init"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Text:init"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Text:init"); ok &= luaval_to_number(tolua_S, 4,&arg2, "ccui.Text:init"); if(!ok) @@ -12345,8 +12345,8 @@ int lua_cocos2dx_ui_Text_getFontName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Text_getFontName'", nullptr); return 0; } - const std::string& ret = cobj->getFontName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getFontName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Text:getFontName",argc, 0); @@ -12387,9 +12387,9 @@ int lua_cocos2dx_ui_Text_setTextAreaSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.Text:setTextAreaSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.Text:setTextAreaSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Text_setTextAreaSize'", nullptr); @@ -12489,8 +12489,8 @@ int lua_cocos2dx_ui_Text_getAutoRenderSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Text_getAutoRenderSize'", nullptr); return 0; } - cocos2d::Size ret = cobj->getAutoRenderSize(); - size_to_luaval(tolua_S, ret); + cocos2d::Vec2 ret = cobj->getAutoRenderSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Text:getAutoRenderSize",argc, 0); @@ -13135,8 +13135,8 @@ int lua_cocos2dx_ui_Text_getTextAreaSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Text_getTextAreaSize'", nullptr); return 0; } - const cocos2d::Size& ret = cobj->getTextAreaSize(); - size_to_luaval(tolua_S, ret); + const cocos2d::Vec2& ret = cobj->getTextAreaSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Text:getTextAreaSize",argc, 0); @@ -13217,11 +13217,11 @@ int lua_cocos2dx_ui_Text_create(lua_State* tolua_S) { if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Text:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Text:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Text:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Text:create"); if (!ok) { break; } double arg2; ok &= luaval_to_number(tolua_S, 4,&arg2, "ccui.Text:create"); @@ -13457,8 +13457,8 @@ int lua_cocos2dx_ui_TextAtlas_getString(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextAtlas_getString'", nullptr); return 0; } - const std::string& ret = cobj->getString(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getString(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.TextAtlas:getString",argc, 0); @@ -13499,9 +13499,9 @@ int lua_cocos2dx_ui_TextAtlas_setString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TextAtlas:setString"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TextAtlas:setString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextAtlas_setString'", nullptr); @@ -13596,21 +13596,21 @@ int lua_cocos2dx_ui_TextAtlas_setProperty(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 5) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; int arg2; int arg3; - std::string arg4; + std::string_view arg4; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TextAtlas:setProperty"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TextAtlas:setProperty"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.TextAtlas:setProperty"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.TextAtlas:setProperty"); ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "ccui.TextAtlas:setProperty"); ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "ccui.TextAtlas:setProperty"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.TextAtlas:setProperty"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.TextAtlas:setProperty"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextAtlas_setProperty'", nullptr); @@ -13695,11 +13695,11 @@ int lua_cocos2dx_ui_TextAtlas_create(lua_State* tolua_S) { if (argc == 5) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TextAtlas:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TextAtlas:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.TextAtlas:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.TextAtlas:create"); if (!ok) { break; } int arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "ccui.TextAtlas:create"); @@ -13707,8 +13707,8 @@ int lua_cocos2dx_ui_TextAtlas_create(lua_State* tolua_S) int arg3; ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "ccui.TextAtlas:create"); if (!ok) { break; } - std::string arg4; - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.TextAtlas:create"); + std::string_view arg4; + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.TextAtlas:create"); if (!ok) { break; } cocos2d::ui::TextAtlas* ret = cocos2d::ui::TextAtlas::create(arg0, arg1, arg2, arg3, arg4); object_to_luaval(tolua_S, "ccui.TextAtlas",(cocos2d::ui::TextAtlas*)ret); @@ -13911,9 +13911,9 @@ int lua_cocos2dx_ui_LoadingBar_loadTexture(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.LoadingBar:loadTexture"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.LoadingBar:loadTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_LoadingBar_loadTexture'", nullptr); @@ -13925,10 +13925,10 @@ int lua_cocos2dx_ui_LoadingBar_loadTexture(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.LoadingBar:loadTexture"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.LoadingBar:loadTexture"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.LoadingBar:loadTexture"); if(!ok) @@ -14353,8 +14353,8 @@ int lua_cocos2dx_ui_LoadingBar_create(lua_State* tolua_S) { if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.LoadingBar:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.LoadingBar:create"); if (!ok) { break; } cocos2d::ui::LoadingBar* ret = cocos2d::ui::LoadingBar::create(arg0); object_to_luaval(tolua_S, "ccui.LoadingBar",(cocos2d::ui::LoadingBar*)ret); @@ -14366,8 +14366,8 @@ int lua_cocos2dx_ui_LoadingBar_create(lua_State* tolua_S) { if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.LoadingBar:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.LoadingBar:create"); if (!ok) { break; } double arg1; ok &= luaval_to_number(tolua_S, 3,&arg1, "ccui.LoadingBar:create"); @@ -14392,8 +14392,8 @@ int lua_cocos2dx_ui_LoadingBar_create(lua_State* tolua_S) { if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.LoadingBar:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.LoadingBar:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg1; ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.LoadingBar:create"); @@ -14408,8 +14408,8 @@ int lua_cocos2dx_ui_LoadingBar_create(lua_State* tolua_S) { if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.LoadingBar:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.LoadingBar:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg1; ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.LoadingBar:create"); @@ -15418,9 +15418,9 @@ int lua_cocos2dx_ui_ScrollView_setInnerContainerSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.ScrollView:setInnerContainerSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.ScrollView:setInnerContainerSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_ScrollView_setInnerContainerSize'", nullptr); @@ -17473,8 +17473,8 @@ int lua_cocos2dx_ui_ScrollView_getInnerContainerSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_ScrollView_getInnerContainerSize'", nullptr); return 0; } - const cocos2d::Size& ret = cobj->getInnerContainerSize(); - size_to_luaval(tolua_S, ret); + const cocos2d::Vec2& ret = cobj->getInnerContainerSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.ScrollView:getInnerContainerSize",argc, 0); @@ -20115,9 +20115,9 @@ int lua_cocos2dx_ui_Slider_loadSlidBallTextureNormal(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextureNormal"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextureNormal"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Slider_loadSlidBallTextureNormal'", nullptr); @@ -20129,10 +20129,10 @@ int lua_cocos2dx_ui_Slider_loadSlidBallTextureNormal(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextureNormal"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextureNormal"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.Slider:loadSlidBallTextureNormal"); if(!ok) @@ -20182,9 +20182,9 @@ int lua_cocos2dx_ui_Slider_loadProgressBarTexture(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadProgressBarTexture"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadProgressBarTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Slider_loadProgressBarTexture'", nullptr); @@ -20196,10 +20196,10 @@ int lua_cocos2dx_ui_Slider_loadProgressBarTexture(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadProgressBarTexture"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadProgressBarTexture"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.Slider:loadProgressBarTexture"); if(!ok) @@ -20537,9 +20537,9 @@ int lua_cocos2dx_ui_Slider_loadSlidBallTextures(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextures"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextures"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Slider_loadSlidBallTextures'", nullptr); @@ -20551,12 +20551,12 @@ int lua_cocos2dx_ui_Slider_loadSlidBallTextures(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextures"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextures"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Slider:loadSlidBallTextures"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Slider:loadSlidBallTextures"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Slider_loadSlidBallTextures'", nullptr); @@ -20568,15 +20568,15 @@ int lua_cocos2dx_ui_Slider_loadSlidBallTextures(lua_State* tolua_S) } if (argc == 3) { - std::string arg0; - std::string arg1; - std::string arg2; + std::string_view arg0; + std::string_view arg1; + std::string_view arg2; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextures"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextures"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Slider:loadSlidBallTextures"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Slider:loadSlidBallTextures"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.Slider:loadSlidBallTextures"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.Slider:loadSlidBallTextures"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Slider_loadSlidBallTextures'", nullptr); @@ -20588,16 +20588,16 @@ int lua_cocos2dx_ui_Slider_loadSlidBallTextures(lua_State* tolua_S) } if (argc == 4) { - std::string arg0; - std::string arg1; - std::string arg2; + std::string_view arg0; + std::string_view arg1; + std::string_view arg2; cocos2d::ui::Widget::TextureResType arg3; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextures"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextures"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Slider:loadSlidBallTextures"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Slider:loadSlidBallTextures"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.Slider:loadSlidBallTextures"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.Slider:loadSlidBallTextures"); ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "ccui.Slider:loadSlidBallTextures"); if(!ok) @@ -20798,9 +20798,9 @@ int lua_cocos2dx_ui_Slider_loadBarTexture(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadBarTexture"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadBarTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Slider_loadBarTexture'", nullptr); @@ -20812,10 +20812,10 @@ int lua_cocos2dx_ui_Slider_loadBarTexture(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadBarTexture"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadBarTexture"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.Slider:loadBarTexture"); if(!ok) @@ -21100,9 +21100,9 @@ int lua_cocos2dx_ui_Slider_loadSlidBallTexturePressed(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTexturePressed"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTexturePressed"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Slider_loadSlidBallTexturePressed'", nullptr); @@ -21114,10 +21114,10 @@ int lua_cocos2dx_ui_Slider_loadSlidBallTexturePressed(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTexturePressed"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTexturePressed"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.Slider:loadSlidBallTexturePressed"); if(!ok) @@ -21455,9 +21455,9 @@ int lua_cocos2dx_ui_Slider_loadSlidBallTextureDisabled(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextureDisabled"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextureDisabled"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Slider_loadSlidBallTextureDisabled'", nullptr); @@ -21469,10 +21469,10 @@ int lua_cocos2dx_ui_Slider_loadSlidBallTextureDisabled(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextureDisabled"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:loadSlidBallTextureDisabled"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.Slider:loadSlidBallTextureDisabled"); if(!ok) @@ -21609,11 +21609,11 @@ int lua_cocos2dx_ui_Slider_create(lua_State* tolua_S) { if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Slider:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Slider:create"); if (!ok) { break; } cocos2d::ui::Slider* ret = cocos2d::ui::Slider::create(arg0, arg1); object_to_luaval(tolua_S, "ccui.Slider",(cocos2d::ui::Slider*)ret); @@ -21625,11 +21625,11 @@ int lua_cocos2dx_ui_Slider_create(lua_State* tolua_S) { if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Slider:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Slider:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Slider:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Slider:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "ccui.Slider:create"); @@ -21911,8 +21911,8 @@ int lua_cocos2dx_ui_TextField_getString(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextField_getString'", nullptr); return 0; } - const std::string& ret = cobj->getString(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getString(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.TextField:getString",argc, 0); @@ -22102,8 +22102,8 @@ int lua_cocos2dx_ui_TextField_getPlaceHolder(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextField_getPlaceHolder'", nullptr); return 0; } - const std::string& ret = cobj->getPlaceHolder(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getPlaceHolder(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.TextField:getPlaceHolder",argc, 0); @@ -22191,9 +22191,9 @@ int lua_cocos2dx_ui_TextField_setFontName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TextField:setFontName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TextField:setFontName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextField_setFontName'", nullptr); @@ -22338,9 +22338,9 @@ int lua_cocos2dx_ui_TextField_setString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TextField:setString"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TextField:setString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextField_setString'", nullptr); @@ -22591,8 +22591,8 @@ int lua_cocos2dx_ui_TextField_getFontName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextField_getFontName'", nullptr); return 0; } - const std::string& ret = cobj->getFontName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getFontName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.TextField:getFontName",argc, 0); @@ -22633,9 +22633,9 @@ int lua_cocos2dx_ui_TextField_setTextAreaSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.TextField:setTextAreaSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.TextField:setTextAreaSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextField_setTextAreaSize'", nullptr); @@ -22782,8 +22782,8 @@ int lua_cocos2dx_ui_TextField_getAutoRenderSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextField_getAutoRenderSize'", nullptr); return 0; } - cocos2d::Size ret = cobj->getAutoRenderSize(); - size_to_luaval(tolua_S, ret); + cocos2d::Vec2 ret = cobj->getAutoRenderSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.TextField:getAutoRenderSize",argc, 0); @@ -23262,9 +23262,9 @@ int lua_cocos2dx_ui_TextField_setPlaceHolder(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TextField:setPlaceHolder"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TextField:setPlaceHolder"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextField_setPlaceHolder'", nullptr); @@ -23911,9 +23911,9 @@ int lua_cocos2dx_ui_TextField_setTouchSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.TextField:setTouchSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.TextField:setTouchSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextField_setTouchSize'", nullptr); @@ -23966,8 +23966,8 @@ int lua_cocos2dx_ui_TextField_getTouchSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextField_getTouchSize'", nullptr); return 0; } - cocos2d::Size ret = cobj->getTouchSize(); - size_to_luaval(tolua_S, ret); + cocos2d::Vec2 ret = cobj->getTouchSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.TextField:getTouchSize",argc, 0); @@ -23998,11 +23998,11 @@ int lua_cocos2dx_ui_TextField_create(lua_State* tolua_S) { if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TextField:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TextField:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.TextField:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.TextField:create"); if (!ok) { break; } int arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "ccui.TextField:create"); @@ -24249,8 +24249,8 @@ int lua_cocos2dx_ui_TextBMFont_getString(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextBMFont_getString'", nullptr); return 0; } - const std::string& ret = cobj->getString(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getString(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.TextBMFont:getString",argc, 0); @@ -24291,9 +24291,9 @@ int lua_cocos2dx_ui_TextBMFont_setString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TextBMFont:setString"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TextBMFont:setString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextBMFont_setString'", nullptr); @@ -24388,9 +24388,9 @@ int lua_cocos2dx_ui_TextBMFont_setFntFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TextBMFont:setFntFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TextBMFont:setFntFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TextBMFont_setFntFile'", nullptr); @@ -24475,11 +24475,11 @@ int lua_cocos2dx_ui_TextBMFont_create(lua_State* tolua_S) { if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TextBMFont:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TextBMFont:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.TextBMFont:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.TextBMFont:create"); if (!ok) { break; } cocos2d::ui::TextBMFont* ret = cocos2d::ui::TextBMFont::create(arg0, arg1); object_to_luaval(tolua_S, "ccui.TextBMFont",(cocos2d::ui::TextBMFont*)ret); @@ -25880,9 +25880,9 @@ int lua_cocos2dx_ui_PageView_setIndicatorIndexNodesTexture(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.PageView:setIndicatorIndexNodesTexture"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.PageView:setIndicatorIndexNodesTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_PageView_setIndicatorIndexNodesTexture'", nullptr); @@ -25894,10 +25894,10 @@ int lua_cocos2dx_ui_PageView_setIndicatorIndexNodesTexture(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.PageView:setIndicatorIndexNodesTexture"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.PageView:setIndicatorIndexNodesTexture"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.PageView:setIndicatorIndexNodesTexture"); if(!ok) @@ -26287,10 +26287,10 @@ int lua_cocos2dx_ui_Helper_getSubStringOfUTF8String(lua_State* tolua_S) if (argc == 3) { - std::string arg0; + std::string_view arg0; unsigned int arg1; unsigned int arg2; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Helper:getSubStringOfUTF8String"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Helper:getSubStringOfUTF8String"); ok &= luaval_to_uint32(tolua_S, 3,&arg1, "ccui.Helper:getSubStringOfUTF8String"); ok &= luaval_to_uint32(tolua_S, 4,&arg2, "ccui.Helper:getSubStringOfUTF8String"); if(!ok) @@ -26438,9 +26438,9 @@ int lua_cocos2dx_ui_Helper_seekWidgetByName(lua_State* tolua_S) if (argc == 2) { cocos2d::ui::Widget* arg0; - std::string arg1; + std::string_view arg1; ok &= luaval_to_object(tolua_S, 2, "ccui.Widget",&arg0, "ccui.Helper:seekWidgetByName"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Helper:seekWidgetByName"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Helper:seekWidgetByName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Helper_seekWidgetByName'", nullptr); @@ -26514,9 +26514,9 @@ int lua_cocos2dx_ui_Helper_restrictCapInsetRect(lua_State* tolua_S) if (argc == 2) { cocos2d::Rect arg0; - cocos2d::Size arg1; + cocos2d::Vec2 arg1; ok &= luaval_to_rect(tolua_S, 2, &arg0, "ccui.Helper:restrictCapInsetRect"); - ok &= luaval_to_size(tolua_S, 3, &arg1, "ccui.Helper:restrictCapInsetRect"); + ok &= luaval_to_vec2(tolua_S, 3, &arg1, "ccui.Helper:restrictCapInsetRect"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Helper_restrictCapInsetRect'", nullptr); @@ -26844,11 +26844,11 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; - std::string arg4; + std::string_view arg3; + std::string_view arg4; double arg5; unsigned int arg6; - std::string arg7; + std::string_view arg7; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:init"); @@ -26856,15 +26856,15 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:init"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:init"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementText_init'", nullptr); @@ -26879,11 +26879,11 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; - std::string arg4; + std::string_view arg3; + std::string_view arg4; double arg5; unsigned int arg6; - std::string arg7; + std::string_view arg7; cocos2d::Color3B arg8; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:init"); @@ -26892,15 +26892,15 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:init"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:init"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:init"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:init"); if(!ok) @@ -26917,11 +26917,11 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; - std::string arg4; + std::string_view arg3; + std::string_view arg4; double arg5; unsigned int arg6; - std::string arg7; + std::string_view arg7; cocos2d::Color3B arg8; int arg9; @@ -26931,15 +26931,15 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:init"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:init"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:init"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:init"); @@ -26958,11 +26958,11 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; - std::string arg4; + std::string_view arg3; + std::string_view arg4; double arg5; unsigned int arg6; - std::string arg7; + std::string_view arg7; cocos2d::Color3B arg8; int arg9; cocos2d::Color3B arg10; @@ -26973,15 +26973,15 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:init"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:init"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:init"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:init"); @@ -27002,15 +27002,15 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; - std::string arg4; + std::string_view arg3; + std::string_view arg4; double arg5; unsigned int arg6; - std::string arg7; + std::string_view arg7; cocos2d::Color3B arg8; int arg9; cocos2d::Color3B arg10; - cocos2d::Size arg11; + cocos2d::Vec2 arg11; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:init"); @@ -27018,15 +27018,15 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:init"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:init"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:init"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:init"); @@ -27034,7 +27034,7 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) ok &= luaval_to_color3b(tolua_S, 12, &arg10, "ccui.RichElementText:init"); - ok &= luaval_to_size(tolua_S, 13, &arg11, "ccui.RichElementText:init"); + ok &= luaval_to_vec2(tolua_S, 13, &arg11, "ccui.RichElementText:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementText_init'", nullptr); @@ -27049,15 +27049,15 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; - std::string arg4; + std::string_view arg3; + std::string_view arg4; double arg5; unsigned int arg6; - std::string arg7; + std::string_view arg7; cocos2d::Color3B arg8; int arg9; cocos2d::Color3B arg10; - cocos2d::Size arg11; + cocos2d::Vec2 arg11; int arg12; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:init"); @@ -27066,15 +27066,15 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:init"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:init"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:init"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:init"); @@ -27082,7 +27082,7 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) ok &= luaval_to_color3b(tolua_S, 12, &arg10, "ccui.RichElementText:init"); - ok &= luaval_to_size(tolua_S, 13, &arg11, "ccui.RichElementText:init"); + ok &= luaval_to_vec2(tolua_S, 13, &arg11, "ccui.RichElementText:init"); ok &= luaval_to_int32(tolua_S, 14,(int *)&arg12, "ccui.RichElementText:init"); if(!ok) @@ -27099,15 +27099,15 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; - std::string arg4; + std::string_view arg3; + std::string_view arg4; double arg5; unsigned int arg6; - std::string arg7; + std::string_view arg7; cocos2d::Color3B arg8; int arg9; cocos2d::Color3B arg10; - cocos2d::Size arg11; + cocos2d::Vec2 arg11; int arg12; cocos2d::Color3B arg13; @@ -27117,15 +27117,15 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:init"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:init"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:init"); - ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:init"); + ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:init"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:init"); @@ -27133,7 +27133,7 @@ int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S) ok &= luaval_to_color3b(tolua_S, 12, &arg10, "ccui.RichElementText:init"); - ok &= luaval_to_size(tolua_S, 13, &arg11, "ccui.RichElementText:init"); + ok &= luaval_to_vec2(tolua_S, 13, &arg11, "ccui.RichElementText:init"); ok &= luaval_to_int32(tolua_S, 14,(int *)&arg12, "ccui.RichElementText:init"); @@ -27177,14 +27177,14 @@ int lua_cocos2dx_ui_RichElementText_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; - std::string arg4; + std::string_view arg3; + std::string_view arg4; double arg5; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:create"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create"); if(!ok) { @@ -27200,15 +27200,15 @@ int lua_cocos2dx_ui_RichElementText_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; - std::string arg4; + std::string_view arg3; + std::string_view arg4; double arg5; unsigned int arg6; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:create"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:create"); if(!ok) @@ -27225,19 +27225,19 @@ int lua_cocos2dx_ui_RichElementText_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; - std::string arg4; + std::string_view arg3; + std::string_view arg4; double arg5; unsigned int arg6; - std::string arg7; + std::string_view arg7; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:create"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementText_create'", nullptr); @@ -27252,20 +27252,20 @@ int lua_cocos2dx_ui_RichElementText_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; - std::string arg4; + std::string_view arg3; + std::string_view arg4; double arg5; unsigned int arg6; - std::string arg7; + std::string_view arg7; cocos2d::Color3B arg8; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:create"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:create"); if(!ok) { @@ -27281,21 +27281,21 @@ int lua_cocos2dx_ui_RichElementText_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; - std::string arg4; + std::string_view arg3; + std::string_view arg4; double arg5; unsigned int arg6; - std::string arg7; + std::string_view arg7; cocos2d::Color3B arg8; int arg9; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:create"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:create"); ok &= luaval_to_int32(tolua_S, 11,(int *)&arg9, "ccui.RichElementText:create"); if(!ok) @@ -27312,22 +27312,22 @@ int lua_cocos2dx_ui_RichElementText_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; - std::string arg4; + std::string_view arg3; + std::string_view arg4; double arg5; unsigned int arg6; - std::string arg7; + std::string_view arg7; cocos2d::Color3B arg8; int arg9; cocos2d::Color3B arg10; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:create"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:create"); ok &= luaval_to_int32(tolua_S, 11,(int *)&arg9, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 12, &arg10, "ccui.RichElementText:create"); @@ -27345,27 +27345,27 @@ int lua_cocos2dx_ui_RichElementText_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; - std::string arg4; + std::string_view arg3; + std::string_view arg4; double arg5; unsigned int arg6; - std::string arg7; + std::string_view arg7; cocos2d::Color3B arg8; int arg9; cocos2d::Color3B arg10; - cocos2d::Size arg11; + cocos2d::Vec2 arg11; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:create"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:create"); ok &= luaval_to_int32(tolua_S, 11,(int *)&arg9, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 12, &arg10, "ccui.RichElementText:create"); - ok &= luaval_to_size(tolua_S, 13, &arg11, "ccui.RichElementText:create"); + ok &= luaval_to_vec2(tolua_S, 13, &arg11, "ccui.RichElementText:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementText_create'", nullptr); @@ -27380,28 +27380,28 @@ int lua_cocos2dx_ui_RichElementText_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; - std::string arg4; + std::string_view arg3; + std::string_view arg4; double arg5; unsigned int arg6; - std::string arg7; + std::string_view arg7; cocos2d::Color3B arg8; int arg9; cocos2d::Color3B arg10; - cocos2d::Size arg11; + cocos2d::Vec2 arg11; int arg12; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:create"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:create"); ok &= luaval_to_int32(tolua_S, 11,(int *)&arg9, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 12, &arg10, "ccui.RichElementText:create"); - ok &= luaval_to_size(tolua_S, 13, &arg11, "ccui.RichElementText:create"); + ok &= luaval_to_vec2(tolua_S, 13, &arg11, "ccui.RichElementText:create"); ok &= luaval_to_int32(tolua_S, 14,(int *)&arg12, "ccui.RichElementText:create"); if(!ok) { @@ -27417,29 +27417,29 @@ int lua_cocos2dx_ui_RichElementText_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; - std::string arg4; + std::string_view arg3; + std::string_view arg4; double arg5; unsigned int arg6; - std::string arg7; + std::string_view arg7; cocos2d::Color3B arg8; int arg9; cocos2d::Color3B arg10; - cocos2d::Size arg11; + cocos2d::Vec2 arg11; int arg12; cocos2d::Color3B arg13; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementText:create"); ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create"); ok &= luaval_to_uint32(tolua_S, 8,&arg6, "ccui.RichElementText:create"); - ok &= luaval_to_std_string(tolua_S, 9,&arg7, "ccui.RichElementText:create"); + ok &= luaval_to_std_string_view(tolua_S, 9,&arg7, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 10, &arg8, "ccui.RichElementText:create"); ok &= luaval_to_int32(tolua_S, 11,(int *)&arg9, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 12, &arg10, "ccui.RichElementText:create"); - ok &= luaval_to_size(tolua_S, 13, &arg11, "ccui.RichElementText:create"); + ok &= luaval_to_vec2(tolua_S, 13, &arg11, "ccui.RichElementText:create"); ok &= luaval_to_int32(tolua_S, 14,(int *)&arg12, "ccui.RichElementText:create"); ok &= luaval_to_color3b(tolua_S, 15, &arg13, "ccui.RichElementText:create"); if(!ok) @@ -27599,7 +27599,7 @@ int lua_cocos2dx_ui_RichElementImage_init(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; + std::string_view arg3; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementImage:init"); @@ -27607,7 +27607,7 @@ int lua_cocos2dx_ui_RichElementImage_init(lua_State* tolua_S) ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementImage:init"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementImage:init"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementImage:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementImage_init'", nullptr); @@ -27622,8 +27622,8 @@ int lua_cocos2dx_ui_RichElementImage_init(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; - std::string arg4; + std::string_view arg3; + std::string_view arg4; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementImage:init"); @@ -27631,9 +27631,9 @@ int lua_cocos2dx_ui_RichElementImage_init(lua_State* tolua_S) ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementImage:init"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementImage:init"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementImage:init"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementImage:init"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementImage:init"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementImage_init'", nullptr); @@ -27648,8 +27648,8 @@ int lua_cocos2dx_ui_RichElementImage_init(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; - std::string arg4; + std::string_view arg3; + std::string_view arg4; cocos2d::ui::Widget::TextureResType arg5; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementImage:init"); @@ -27658,9 +27658,9 @@ int lua_cocos2dx_ui_RichElementImage_init(lua_State* tolua_S) ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementImage:init"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementImage:init"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementImage:init"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementImage:init"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementImage:init"); ok &= luaval_to_int32(tolua_S, 7,(int *)&arg5, "ccui.RichElementImage:init"); if(!ok) @@ -27760,9 +27760,9 @@ int lua_cocos2dx_ui_RichElementImage_setUrl(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RichElementImage:setUrl"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RichElementImage:setUrl"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementImage_setUrl'", nullptr); @@ -27802,11 +27802,11 @@ int lua_cocos2dx_ui_RichElementImage_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; + std::string_view arg3; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementImage:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementImage:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementImage:create"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementImage:create"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementImage:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementImage_create'", nullptr); @@ -27821,13 +27821,13 @@ int lua_cocos2dx_ui_RichElementImage_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; - std::string arg4; + std::string_view arg3; + std::string_view arg4; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementImage:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementImage:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementImage:create"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementImage:create"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementImage:create"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementImage:create"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementImage:create"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementImage_create'", nullptr); @@ -27842,14 +27842,14 @@ int lua_cocos2dx_ui_RichElementImage_create(lua_State* tolua_S) int arg0; cocos2d::Color3B arg1; uint16_t arg2; - std::string arg3; - std::string arg4; + std::string_view arg3; + std::string_view arg4; cocos2d::ui::Widget::TextureResType arg5; ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementImage:create"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementImage:create"); ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementImage:create"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementImage:create"); - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementImage:create"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.RichElementImage:create"); + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.RichElementImage:create"); ok &= luaval_to_int32(tolua_S, 7,(int *)&arg5, "ccui.RichElementImage:create"); if(!ok) { @@ -28630,13 +28630,13 @@ int lua_cocos2dx_ui_RichText_setAnchorTextShadow(lua_State* tolua_S) { bool arg0; cocos2d::Color3B arg1; - cocos2d::Size arg2; + cocos2d::Vec2 arg2; ok &= luaval_to_boolean(tolua_S, 2,&arg0, "ccui.RichText:setAnchorTextShadow"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichText:setAnchorTextShadow"); - ok &= luaval_to_size(tolua_S, 4, &arg2, "ccui.RichText:setAnchorTextShadow"); + ok &= luaval_to_vec2(tolua_S, 4, &arg2, "ccui.RichText:setAnchorTextShadow"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichText_setAnchorTextShadow'", nullptr); @@ -28650,14 +28650,14 @@ int lua_cocos2dx_ui_RichText_setAnchorTextShadow(lua_State* tolua_S) { bool arg0; cocos2d::Color3B arg1; - cocos2d::Size arg2; + cocos2d::Vec2 arg2; int arg3; ok &= luaval_to_boolean(tolua_S, 2,&arg0, "ccui.RichText:setAnchorTextShadow"); ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichText:setAnchorTextShadow"); - ok &= luaval_to_size(tolua_S, 4, &arg2, "ccui.RichText:setAnchorTextShadow"); + ok &= luaval_to_vec2(tolua_S, 4, &arg2, "ccui.RichText:setAnchorTextShadow"); ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "ccui.RichText:setAnchorTextShadow"); if(!ok) @@ -28754,9 +28754,9 @@ int lua_cocos2dx_ui_RichText_setAnchorFontColor(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RichText:setAnchorFontColor"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RichText:setAnchorFontColor"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichText_setAnchorFontColor'", nullptr); @@ -28804,9 +28804,9 @@ int lua_cocos2dx_ui_RichText_setFontFace(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RichText:setFontFace"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RichText:setFontFace"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichText_setFontFace'", nullptr); @@ -29165,10 +29165,10 @@ int lua_cocos2dx_ui_RichText_initWithXML(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ValueMap arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RichText:initWithXML"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RichText:initWithXML"); ok &= luaval_to_ccvaluemap(tolua_S, 3, &arg1, "ccui.RichText:initWithXML"); if(!ok) @@ -29182,11 +29182,11 @@ int lua_cocos2dx_ui_RichText_initWithXML(lua_State* tolua_S) } if (argc == 3) { - std::string arg0; + std::string_view arg0; cocos2d::ValueMap arg1; - std::function arg2; + std::function arg2; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RichText:initWithXML"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RichText:initWithXML"); ok &= luaval_to_ccvaluemap(tolua_S, 3, &arg1, "ccui.RichText:initWithXML"); @@ -29383,9 +29383,9 @@ int lua_cocos2dx_ui_RichText_openUrl(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RichText:openUrl"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RichText:openUrl"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichText_openUrl'", nullptr); @@ -29480,9 +29480,9 @@ int lua_cocos2dx_ui_RichText_setFontColor(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RichText:setFontColor"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RichText:setFontColor"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichText_setFontColor'", nullptr); @@ -30169,8 +30169,8 @@ int lua_cocos2dx_ui_RichText_getAnchorTextShadowOffset(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichText_getAnchorTextShadowOffset'", nullptr); return 0; } - cocos2d::Size ret = cobj->getAnchorTextShadowOffset(); - size_to_luaval(tolua_S, ret); + cocos2d::Vec2 ret = cobj->getAnchorTextShadowOffset(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.RichText:getAnchorTextShadowOffset",argc, 0); @@ -30546,9 +30546,9 @@ int lua_cocos2dx_ui_RichText_color3BWithString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RichText:color3BWithString"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RichText:color3BWithString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichText_color3BWithString'", nullptr); @@ -30619,9 +30619,9 @@ int lua_cocos2dx_ui_RichText_createWithXML(lua_State* tolua_S) if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ValueMap arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RichText:createWithXML"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RichText:createWithXML"); ok &= luaval_to_ccvaluemap(tolua_S, 3, &arg1, "ccui.RichText:createWithXML"); if(!ok) { @@ -30634,10 +30634,10 @@ int lua_cocos2dx_ui_RichText_createWithXML(lua_State* tolua_S) } if (argc == 3) { - std::string arg0; + std::string_view arg0; cocos2d::ValueMap arg1; - std::function arg2; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.RichText:createWithXML"); + std::function arg2; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.RichText:createWithXML"); ok &= luaval_to_ccvaluemap(tolua_S, 3, &arg1, "ccui.RichText:createWithXML"); do { // Lambda binding for lua is not supported. @@ -30794,9 +30794,9 @@ int lua_cocos2dx_ui_HBox_initWithSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.HBox:initWithSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.HBox:initWithSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_HBox_initWithSize'", nullptr); @@ -30834,8 +30834,8 @@ int lua_cocos2dx_ui_HBox_create(lua_State* tolua_S) { if (argc == 1) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.HBox:create"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.HBox:create"); if (!ok) { break; } cocos2d::ui::HBox* ret = cocos2d::ui::HBox::create(arg0); object_to_luaval(tolua_S, "ccui.HBox",(cocos2d::ui::HBox*)ret); @@ -30948,9 +30948,9 @@ int lua_cocos2dx_ui_VBox_initWithSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.VBox:initWithSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.VBox:initWithSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_VBox_initWithSize'", nullptr); @@ -30988,8 +30988,8 @@ int lua_cocos2dx_ui_VBox_create(lua_State* tolua_S) { if (argc == 1) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.VBox:create"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.VBox:create"); if (!ok) { break; } cocos2d::ui::VBox* ret = cocos2d::ui::VBox::create(arg0); object_to_luaval(tolua_S, "ccui.VBox",(cocos2d::ui::VBox*)ret); @@ -31102,9 +31102,9 @@ int lua_cocos2dx_ui_RelativeBox_initWithSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.RelativeBox:initWithSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.RelativeBox:initWithSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RelativeBox_initWithSize'", nullptr); @@ -31142,8 +31142,8 @@ int lua_cocos2dx_ui_RelativeBox_create(lua_State* tolua_S) { if (argc == 1) { - cocos2d::Size arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.RelativeBox:create"); + cocos2d::Vec2 arg0; + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.RelativeBox:create"); if (!ok) { break; } cocos2d::ui::RelativeBox* ret = cocos2d::ui::RelativeBox::create(arg0); object_to_luaval(tolua_S, "ccui.RelativeBox",(cocos2d::ui::RelativeBox*)ret); @@ -31267,8 +31267,8 @@ int lua_cocos2dx_ui_Scale9Sprite_updateWithSprite(lua_State* tolua_S) ok &= luaval_to_vec2(tolua_S, 5, &arg3, "ccui.Scale9Sprite:updateWithSprite"); if (!ok) { break; } - cocos2d::Size arg4; - ok &= luaval_to_size(tolua_S, 6, &arg4, "ccui.Scale9Sprite:updateWithSprite"); + cocos2d::Vec2 arg4; + ok &= luaval_to_vec2(tolua_S, 6, &arg4, "ccui.Scale9Sprite:updateWithSprite"); if (!ok) { break; } cocos2d::Rect arg5; @@ -31540,10 +31540,10 @@ int lua_cocos2dx_ui_Scale9Sprite_initWithSpriteFrameName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::Rect arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Scale9Sprite:initWithSpriteFrameName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Scale9Sprite:initWithSpriteFrameName"); ok &= luaval_to_rect(tolua_S, 3, &arg1, "ccui.Scale9Sprite:initWithSpriteFrameName"); if(!ok) @@ -31795,8 +31795,8 @@ int lua_cocos2dx_ui_Scale9Sprite_init(lua_State* tolua_S) ok &= luaval_to_vec2(tolua_S, 5, &arg3, "ccui.Scale9Sprite:init"); if (!ok) { break; } - cocos2d::Size arg4; - ok &= luaval_to_size(tolua_S, 6, &arg4, "ccui.Scale9Sprite:init"); + cocos2d::Vec2 arg4; + ok &= luaval_to_vec2(tolua_S, 6, &arg4, "ccui.Scale9Sprite:init"); if (!ok) { break; } cocos2d::Rect arg5; @@ -31847,9 +31847,9 @@ int lua_cocos2dx_ui_Scale9Sprite_setPreferredSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.Scale9Sprite:setPreferredSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.Scale9Sprite:setPreferredSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Scale9Sprite_setPreferredSize'", nullptr); @@ -32337,8 +32337,8 @@ int lua_cocos2dx_ui_Scale9Sprite_getOriginalSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Scale9Sprite_getOriginalSize'", nullptr); return 0; } - cocos2d::Size ret = cobj->getOriginalSize(); - size_to_luaval(tolua_S, ret); + cocos2d::Vec2 ret = cobj->getOriginalSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Scale9Sprite:getOriginalSize",argc, 0); @@ -32378,8 +32378,8 @@ int lua_cocos2dx_ui_Scale9Sprite_initWithFile(lua_State* tolua_S) ok &= luaval_to_rect(tolua_S, 2, &arg0, "ccui.Scale9Sprite:initWithFile"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Scale9Sprite:initWithFile"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Scale9Sprite:initWithFile"); if (!ok) { break; } bool ret = cobj->initWithFile(arg0, arg1); @@ -32390,8 +32390,8 @@ int lua_cocos2dx_ui_Scale9Sprite_initWithFile(lua_State* tolua_S) ok = true; do{ if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Scale9Sprite:initWithFile"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Scale9Sprite:initWithFile"); if (!ok) { break; } cocos2d::Rect arg1; @@ -32601,8 +32601,8 @@ int lua_cocos2dx_ui_Scale9Sprite_getPreferredSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_Scale9Sprite_getPreferredSize'", nullptr); return 0; } - cocos2d::Size ret = cobj->getPreferredSize(); - size_to_luaval(tolua_S, ret); + cocos2d::Vec2 ret = cobj->getPreferredSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.Scale9Sprite:getPreferredSize",argc, 0); @@ -32780,8 +32780,8 @@ int lua_cocos2dx_ui_Scale9Sprite_create(lua_State* tolua_S) { if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Scale9Sprite:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Scale9Sprite:create"); if (!ok) { break; } cocos2d::Rect arg1; ok &= luaval_to_rect(tolua_S, 3, &arg1, "ccui.Scale9Sprite:create"); @@ -32812,8 +32812,8 @@ int lua_cocos2dx_ui_Scale9Sprite_create(lua_State* tolua_S) cocos2d::Rect arg0; ok &= luaval_to_rect(tolua_S, 2, &arg0, "ccui.Scale9Sprite:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.Scale9Sprite:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.Scale9Sprite:create"); if (!ok) { break; } cocos2d::ui::Scale9Sprite* ret = cocos2d::ui::Scale9Sprite::create(arg0, arg1); object_to_luaval(tolua_S, "ccui.Scale9Sprite",(cocos2d::ui::Scale9Sprite*)ret); @@ -32825,8 +32825,8 @@ int lua_cocos2dx_ui_Scale9Sprite_create(lua_State* tolua_S) { if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Scale9Sprite:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Scale9Sprite:create"); if (!ok) { break; } cocos2d::Rect arg1; ok &= luaval_to_rect(tolua_S, 3, &arg1, "ccui.Scale9Sprite:create"); @@ -32841,8 +32841,8 @@ int lua_cocos2dx_ui_Scale9Sprite_create(lua_State* tolua_S) { if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Scale9Sprite:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Scale9Sprite:create"); if (!ok) { break; } cocos2d::ui::Scale9Sprite* ret = cocos2d::ui::Scale9Sprite::create(arg0); object_to_luaval(tolua_S, "ccui.Scale9Sprite",(cocos2d::ui::Scale9Sprite*)ret); @@ -32876,8 +32876,8 @@ int lua_cocos2dx_ui_Scale9Sprite_createWithSpriteFrameName(lua_State* tolua_S) { if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Scale9Sprite:createWithSpriteFrameName"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Scale9Sprite:createWithSpriteFrameName"); if (!ok) { break; } cocos2d::Rect arg1; ok &= luaval_to_rect(tolua_S, 3, &arg1, "ccui.Scale9Sprite:createWithSpriteFrameName"); @@ -32892,8 +32892,8 @@ int lua_cocos2dx_ui_Scale9Sprite_createWithSpriteFrameName(lua_State* tolua_S) { if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.Scale9Sprite:createWithSpriteFrameName"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.Scale9Sprite:createWithSpriteFrameName"); if (!ok) { break; } cocos2d::ui::Scale9Sprite* ret = cocos2d::ui::Scale9Sprite::createWithSpriteFrameName(arg0); object_to_luaval(tolua_S, "ccui.Scale9Sprite",(cocos2d::ui::Scale9Sprite*)ret); @@ -33431,8 +33431,8 @@ int lua_cocos2dx_ui_EditBox_initWithSizeAndBackgroundSprite(lua_State* tolua_S) ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:initWithSizeAndBackgroundSprite"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndBackgroundSprite"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndBackgroundSprite"); if (!ok) { break; } bool ret = cobj->initWithSizeAndBackgroundSprite(arg0, arg1); @@ -33447,8 +33447,8 @@ int lua_cocos2dx_ui_EditBox_initWithSizeAndBackgroundSprite(lua_State* tolua_S) ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:initWithSizeAndBackgroundSprite"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndBackgroundSprite"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndBackgroundSprite"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg2; @@ -34012,9 +34012,9 @@ int lua_cocos2dx_ui_EditBox_loadTextureDisabled(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.EditBox:loadTextureDisabled"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.EditBox:loadTextureDisabled"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_EditBox_loadTextureDisabled'", nullptr); @@ -34026,10 +34026,10 @@ int lua_cocos2dx_ui_EditBox_loadTextureDisabled(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.EditBox:loadTextureDisabled"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.EditBox:loadTextureDisabled"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.EditBox:loadTextureDisabled"); if(!ok) @@ -34532,9 +34532,9 @@ int lua_cocos2dx_ui_EditBox_loadTexturePressed(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.EditBox:loadTexturePressed"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.EditBox:loadTexturePressed"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_EditBox_loadTexturePressed'", nullptr); @@ -34546,10 +34546,10 @@ int lua_cocos2dx_ui_EditBox_loadTexturePressed(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.EditBox:loadTexturePressed"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.EditBox:loadTexturePressed"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.EditBox:loadTexturePressed"); if(!ok) @@ -34694,11 +34694,11 @@ int lua_cocos2dx_ui_EditBox_initWithSizeAndTexture(lua_State* tolua_S) if (argc == 2) { cocos2d::Size arg0; - std::string arg1; + std::string_view arg1; ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:initWithSizeAndTexture"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndTexture"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_EditBox_initWithSizeAndTexture'", nullptr); @@ -34711,14 +34711,14 @@ int lua_cocos2dx_ui_EditBox_initWithSizeAndTexture(lua_State* tolua_S) if (argc == 3) { cocos2d::Size arg0; - std::string arg1; - std::string arg2; + std::string_view arg1; + std::string_view arg2; ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:initWithSizeAndTexture"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndTexture"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndTexture"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.EditBox:initWithSizeAndTexture"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.EditBox:initWithSizeAndTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_EditBox_initWithSizeAndTexture'", nullptr); @@ -34731,17 +34731,17 @@ int lua_cocos2dx_ui_EditBox_initWithSizeAndTexture(lua_State* tolua_S) if (argc == 4) { cocos2d::Size arg0; - std::string arg1; - std::string arg2; - std::string arg3; + std::string_view arg1; + std::string_view arg2; + std::string_view arg3; ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:initWithSizeAndTexture"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndTexture"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndTexture"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.EditBox:initWithSizeAndTexture"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.EditBox:initWithSizeAndTexture"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.EditBox:initWithSizeAndTexture"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.EditBox:initWithSizeAndTexture"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_EditBox_initWithSizeAndTexture'", nullptr); @@ -34754,18 +34754,18 @@ int lua_cocos2dx_ui_EditBox_initWithSizeAndTexture(lua_State* tolua_S) if (argc == 5) { cocos2d::Size arg0; - std::string arg1; - std::string arg2; - std::string arg3; + std::string_view arg1; + std::string_view arg2; + std::string_view arg3; cocos2d::ui::Widget::TextureResType arg4; ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:initWithSizeAndTexture"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndTexture"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:initWithSizeAndTexture"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.EditBox:initWithSizeAndTexture"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.EditBox:initWithSizeAndTexture"); - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.EditBox:initWithSizeAndTexture"); + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.EditBox:initWithSizeAndTexture"); ok &= luaval_to_int32(tolua_S, 6,(int *)&arg4, "ccui.EditBox:initWithSizeAndTexture"); if(!ok) @@ -35003,12 +35003,12 @@ int lua_cocos2dx_ui_EditBox_loadTextures(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 2) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.EditBox:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.EditBox:loadTextures"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:loadTextures"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_EditBox_loadTextures'", nullptr); @@ -35020,15 +35020,15 @@ int lua_cocos2dx_ui_EditBox_loadTextures(lua_State* tolua_S) } if (argc == 3) { - std::string arg0; - std::string arg1; - std::string arg2; + std::string_view arg0; + std::string_view arg1; + std::string_view arg2; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.EditBox:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.EditBox:loadTextures"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:loadTextures"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.EditBox:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.EditBox:loadTextures"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_EditBox_loadTextures'", nullptr); @@ -35040,16 +35040,16 @@ int lua_cocos2dx_ui_EditBox_loadTextures(lua_State* tolua_S) } if (argc == 4) { - std::string arg0; - std::string arg1; - std::string arg2; + std::string_view arg0; + std::string_view arg1; + std::string_view arg2; cocos2d::ui::Widget::TextureResType arg3; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.EditBox:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.EditBox:loadTextures"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:loadTextures"); - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.EditBox:loadTextures"); + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.EditBox:loadTextures"); ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "ccui.EditBox:loadTextures"); if(!ok) @@ -35249,9 +35249,9 @@ int lua_cocos2dx_ui_EditBox_loadTextureNormal(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.EditBox:loadTextureNormal"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.EditBox:loadTextureNormal"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_EditBox_loadTextureNormal'", nullptr); @@ -35263,10 +35263,10 @@ int lua_cocos2dx_ui_EditBox_loadTextureNormal(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; + std::string_view arg0; cocos2d::ui::Widget::TextureResType arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.EditBox:loadTextureNormal"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.EditBox:loadTextureNormal"); ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.EditBox:loadTextureNormal"); if(!ok) @@ -35709,8 +35709,8 @@ int lua_cocos2dx_ui_EditBox_create(lua_State* tolua_S) cocos2d::Size arg0; ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg2; ok &= luaval_to_int32(tolua_S, 4,(int *)&arg2, "ccui.EditBox:create"); @@ -35785,8 +35785,8 @@ int lua_cocos2dx_ui_EditBox_create(lua_State* tolua_S) cocos2d::Size arg0; ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:create"); if (!ok) { break; } cocos2d::ui::EditBox* ret = cocos2d::ui::EditBox::create(arg0, arg1); object_to_luaval(tolua_S, "ccui.EditBox",(cocos2d::ui::EditBox*)ret); @@ -35801,11 +35801,11 @@ int lua_cocos2dx_ui_EditBox_create(lua_State* tolua_S) cocos2d::Size arg0; ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:create"); if (!ok) { break; } - std::string arg2; - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.EditBox:create"); + std::string_view arg2; + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.EditBox:create"); if (!ok) { break; } cocos2d::ui::EditBox* ret = cocos2d::ui::EditBox::create(arg0, arg1, arg2); object_to_luaval(tolua_S, "ccui.EditBox",(cocos2d::ui::EditBox*)ret); @@ -35820,14 +35820,14 @@ int lua_cocos2dx_ui_EditBox_create(lua_State* tolua_S) cocos2d::Size arg0; ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:create"); if (!ok) { break; } - std::string arg2; - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.EditBox:create"); + std::string_view arg2; + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.EditBox:create"); if (!ok) { break; } - std::string arg3; - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.EditBox:create"); + std::string_view arg3; + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.EditBox:create"); if (!ok) { break; } cocos2d::ui::EditBox* ret = cocos2d::ui::EditBox::create(arg0, arg1, arg2, arg3); object_to_luaval(tolua_S, "ccui.EditBox",(cocos2d::ui::EditBox*)ret); @@ -35842,14 +35842,14 @@ int lua_cocos2dx_ui_EditBox_create(lua_State* tolua_S) cocos2d::Size arg0; ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.EditBox:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.EditBox:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.EditBox:create"); if (!ok) { break; } - std::string arg2; - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.EditBox:create"); + std::string_view arg2; + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.EditBox:create"); if (!ok) { break; } - std::string arg3; - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.EditBox:create"); + std::string_view arg3; + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.EditBox:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg4; ok &= luaval_to_int32(tolua_S, 6,(int *)&arg4, "ccui.EditBox:create"); @@ -36352,8 +36352,8 @@ int lua_cocos2dx_ui_LayoutComponent_getSize(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_LayoutComponent_getSize'", nullptr); return 0; } - const cocos2d::Size& ret = cobj->getSize(); - size_to_luaval(tolua_S, ret); + const cocos2d::Vec2& ret = cobj->getSize(); + vec2_to_luaval(tolua_S, ret); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.LayoutComponent:getSize",argc, 0); @@ -38331,9 +38331,9 @@ int lua_cocos2dx_ui_LayoutComponent_setSize(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - cocos2d::Size arg0; + cocos2d::Vec2 arg0; - ok &= luaval_to_size(tolua_S, 2, &arg0, "ccui.LayoutComponent:setSize"); + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.LayoutComponent:setSize"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_LayoutComponent_setSize'", nullptr); @@ -38611,8 +38611,8 @@ int lua_cocos2dx_ui_TabHeader_getTitleText(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TabHeader_getTitleText'", nullptr); return 0; } - std::string ret = cobj->getTitleText(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getTitleText(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.TabHeader:getTitleText",argc, 0); @@ -38703,9 +38703,9 @@ int lua_cocos2dx_ui_TabHeader_setTitleFontName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TabHeader:setTitleFontName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TabHeader:setTitleFontName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TabHeader_setTitleFontName'", nullptr); @@ -38805,8 +38805,8 @@ int lua_cocos2dx_ui_TabHeader_getTitleFontName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TabHeader_getTitleFontName'", nullptr); return 0; } - std::string ret = cobj->getTitleFontName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getTitleFontName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.TabHeader:getTitleFontName",argc, 0); @@ -38941,9 +38941,9 @@ int lua_cocos2dx_ui_TabHeader_setTitleText(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TabHeader:setTitleText"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TabHeader:setTitleText"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_TabHeader_setTitleText'", nullptr); @@ -39031,14 +39031,14 @@ int lua_cocos2dx_ui_TabHeader_create(lua_State* tolua_S) { if (argc == 3) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TabHeader:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TabHeader:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.TabHeader:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.TabHeader:create"); if (!ok) { break; } - std::string arg2; - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.TabHeader:create"); + std::string_view arg2; + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.TabHeader:create"); if (!ok) { break; } cocos2d::ui::TabHeader* ret = cocos2d::ui::TabHeader::create(arg0, arg1, arg2); object_to_luaval(tolua_S, "ccui.TabHeader",(cocos2d::ui::TabHeader*)ret); @@ -39050,14 +39050,14 @@ int lua_cocos2dx_ui_TabHeader_create(lua_State* tolua_S) { if (argc == 4) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TabHeader:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TabHeader:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.TabHeader:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.TabHeader:create"); if (!ok) { break; } - std::string arg2; - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.TabHeader:create"); + std::string_view arg2; + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.TabHeader:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg3; ok &= luaval_to_int32(tolua_S, 5,(int *)&arg3, "ccui.TabHeader:create"); @@ -39082,23 +39082,23 @@ int lua_cocos2dx_ui_TabHeader_create(lua_State* tolua_S) { if (argc == 6) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TabHeader:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TabHeader:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.TabHeader:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.TabHeader:create"); if (!ok) { break; } - std::string arg2; - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.TabHeader:create"); + std::string_view arg2; + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.TabHeader:create"); if (!ok) { break; } - std::string arg3; - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.TabHeader:create"); + std::string_view arg3; + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.TabHeader:create"); if (!ok) { break; } - std::string arg4; - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.TabHeader:create"); + std::string_view arg4; + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.TabHeader:create"); if (!ok) { break; } - std::string arg5; - ok &= luaval_to_std_string(tolua_S, 7,&arg5, "ccui.TabHeader:create"); + std::string_view arg5; + ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "ccui.TabHeader:create"); if (!ok) { break; } cocos2d::ui::TabHeader* ret = cocos2d::ui::TabHeader::create(arg0, arg1, arg2, arg3, arg4, arg5); object_to_luaval(tolua_S, "ccui.TabHeader",(cocos2d::ui::TabHeader*)ret); @@ -39110,23 +39110,23 @@ int lua_cocos2dx_ui_TabHeader_create(lua_State* tolua_S) { if (argc == 7) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.TabHeader:create"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.TabHeader:create"); if (!ok) { break; } - std::string arg1; - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.TabHeader:create"); + std::string_view arg1; + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.TabHeader:create"); if (!ok) { break; } - std::string arg2; - ok &= luaval_to_std_string(tolua_S, 4,&arg2, "ccui.TabHeader:create"); + std::string_view arg2; + ok &= luaval_to_std_string_view(tolua_S, 4,&arg2, "ccui.TabHeader:create"); if (!ok) { break; } - std::string arg3; - ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.TabHeader:create"); + std::string_view arg3; + ok &= luaval_to_std_string_view(tolua_S, 5,&arg3, "ccui.TabHeader:create"); if (!ok) { break; } - std::string arg4; - ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.TabHeader:create"); + std::string_view arg4; + ok &= luaval_to_std_string_view(tolua_S, 6,&arg4, "ccui.TabHeader:create"); if (!ok) { break; } - std::string arg5; - ok &= luaval_to_std_string(tolua_S, 7,&arg5, "ccui.TabHeader:create"); + std::string_view arg5; + ok &= luaval_to_std_string_view(tolua_S, 7,&arg5, "ccui.TabHeader:create"); if (!ok) { break; } cocos2d::ui::Widget::TextureResType arg6; ok &= luaval_to_int32(tolua_S, 8,(int *)&arg6, "ccui.TabHeader:create"); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_video_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_video_auto.cpp index d01c83a464c7..eecb3ef9a9ec 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_video_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_video_auto.cpp @@ -36,8 +36,8 @@ int lua_cocos2dx_video_VideoPlayer_getFileName(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_video_VideoPlayer_getFileName'", nullptr); return 0; } - const std::string& ret = cobj->getFileName(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getFileName(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.VideoPlayer:getFileName",argc, 0); @@ -83,8 +83,8 @@ int lua_cocos2dx_video_VideoPlayer_getURL(lua_State* tolua_S) tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_video_VideoPlayer_getURL'", nullptr); return 0; } - const std::string& ret = cobj->getURL(); - lua_pushlstring(tolua_S,ret.c_str(),ret.length()); + std::string_view ret = cobj->getURL(); + lua_pushlstring(tolua_S,ret.data(),ret.length()); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.VideoPlayer:getURL",argc, 0); @@ -366,9 +366,9 @@ int lua_cocos2dx_video_VideoPlayer_setFileName(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.VideoPlayer:setFileName"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.VideoPlayer:setFileName"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_video_VideoPlayer_setFileName'", nullptr); @@ -416,9 +416,9 @@ int lua_cocos2dx_video_VideoPlayer_setURL(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.VideoPlayer:setURL"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.VideoPlayer:setURL"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_video_VideoPlayer_setURL'", nullptr); diff --git a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_webview_auto.cpp b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_webview_auto.cpp index 887d6cf0ac7c..378f246d8631 100644 --- a/extensions/scripting/lua-bindings/auto/lua_cocos2dx_webview_auto.cpp +++ b/extensions/scripting/lua-bindings/auto/lua_cocos2dx_webview_auto.cpp @@ -128,9 +128,9 @@ int lua_cocos2dx_webview_WebView_loadHTMLString(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.WebView:loadHTMLString"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.WebView:loadHTMLString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_webview_WebView_loadHTMLString'", nullptr); @@ -142,12 +142,12 @@ int lua_cocos2dx_webview_WebView_loadHTMLString(lua_State* tolua_S) } if (argc == 2) { - std::string arg0; - std::string arg1; + std::string_view arg0; + std::string_view arg1; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.WebView:loadHTMLString"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.WebView:loadHTMLString"); - ok &= luaval_to_std_string(tolua_S, 3,&arg1, "ccui.WebView:loadHTMLString"); + ok &= luaval_to_std_string_view(tolua_S, 3,&arg1, "ccui.WebView:loadHTMLString"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_webview_WebView_loadHTMLString'", nullptr); @@ -339,9 +339,9 @@ int lua_cocos2dx_webview_WebView_loadFile(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.WebView:loadFile"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.WebView:loadFile"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_webview_WebView_loadFile'", nullptr); @@ -384,8 +384,8 @@ int lua_cocos2dx_webview_WebView_loadURL(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; do{ if (argc == 2) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.WebView:loadURL"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.WebView:loadURL"); if (!ok) { break; } bool arg1; @@ -400,8 +400,8 @@ int lua_cocos2dx_webview_WebView_loadURL(lua_State* tolua_S) ok = true; do{ if (argc == 1) { - std::string arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.WebView:loadURL"); + std::string_view arg0; + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.WebView:loadURL"); if (!ok) { break; } cobj->loadURL(arg0); @@ -498,9 +498,9 @@ int lua_cocos2dx_webview_WebView_evaluateJS(lua_State* tolua_S) argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.WebView:evaluateJS"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.WebView:evaluateJS"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_webview_WebView_evaluateJS'", nullptr); @@ -830,9 +830,9 @@ int lua_cocos2dx_webview_WebView_setJavascriptInterfaceScheme(lua_State* tolua_S argc = lua_gettop(tolua_S)-1; if (argc == 1) { - std::string arg0; + std::string_view arg0; - ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.WebView:setJavascriptInterfaceScheme"); + ok &= luaval_to_std_string_view(tolua_S, 2,&arg0, "ccui.WebView:setJavascriptInterfaceScheme"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_webview_WebView_setJavascriptInterfaceScheme'", nullptr); diff --git a/extensions/scripting/lua-bindings/manual/CCComponentLua.cpp b/extensions/scripting/lua-bindings/manual/CCComponentLua.cpp index 1118e57d2d8c..31560146efa4 100644 --- a/extensions/scripting/lua-bindings/manual/CCComponentLua.cpp +++ b/extensions/scripting/lua-bindings/manual/CCComponentLua.cpp @@ -41,7 +41,7 @@ const std::string ComponentLua::UPDATE = "update"; namespace { -void adjustScriptFileName(std::string& scriptFileName) +void adjustScriptFileName(std::string_view& scriptFileName, std::string& holder) { assert(scriptFileName.size() > 4); @@ -54,22 +54,26 @@ void adjustScriptFileName(std::string& scriptFileName) // xxx.lua -> xxx.luac or // xxx.luac -> xxx.lua - if (scriptFileName.compare(scriptFileName.size() - luaSuffix.size(), luaSuffix.size(), luaSuffix) == 0) - scriptFileName.replace(scriptFileName.size() - luaSuffix.size(), luaSuffix.size(), luacSuffix); + holder = scriptFileName; + if (holder.compare(holder.size() - luaSuffix.size(), luaSuffix.size(), luaSuffix) == 0) + holder.replace(holder.size() - luaSuffix.size(), luaSuffix.size(), luacSuffix); else - scriptFileName.replace(scriptFileName.size() - luacSuffix.size(), luacSuffix.size(), luaSuffix); + holder.replace(holder.size() - luacSuffix.size(), luacSuffix.size(), luaSuffix); + + scriptFileName = holder; } } // namespace int ComponentLua::_index = 0; -ComponentLua* ComponentLua::create(const std::string& scriptFileName) +ComponentLua* ComponentLua::create(std::string_view scriptFileName) { CC_ASSERT(!scriptFileName.empty()); initClass(); - adjustScriptFileName(const_cast(scriptFileName)); + std::string holder; + adjustScriptFileName(scriptFileName, holder); auto componentLua = new ComponentLua(scriptFileName); if (componentLua) { @@ -79,7 +83,7 @@ ComponentLua* ComponentLua::create(const std::string& scriptFileName) return componentLua; } -ComponentLua::ComponentLua(const std::string& scriptFileName) +ComponentLua::ComponentLua(std::string_view scriptFileName) : _scriptFileName(scriptFileName), _table(nullptr), _strIndex("") { _succeedLoadingScript = loadAndExecuteScript(); @@ -134,18 +138,18 @@ void ComponentLua::onExit() } } -bool ComponentLua::getLuaFunction(const std::string& functionName) +bool ComponentLua::getLuaFunction(std::string_view functionName) { lua_State* l = LuaEngine::getInstance()->getLuaStack()->getLuaState(); - lua_pushstring(l, KEY_COMPONENT); // stack: "component" - lua_rawget(l, LUA_REGISTRYINDEX); // stack: table_of_component - lua_pushstring(l, _strIndex.c_str()); // stack: table_of_component strIndex - lua_rawget(l, -2); // stack: table_of_component table_of_this - lua_pushstring(l, functionName.c_str()); // stack: table_of_component table_of_this "update" - lua_rawget(l, -2); // stack: table_of_component table_of_this table_of_this["update"] - lua_remove(l, -2); // stack: table_of_component table_of_this["update"] - lua_remove(l, -2); // stack: table_of_this["update"] + lua_pushstring(l, KEY_COMPONENT); // stack: "component" + lua_rawget(l, LUA_REGISTRYINDEX); // stack: table_of_component + lua_pushstring(l, _strIndex.c_str()); // stack: table_of_component strIndex + lua_rawget(l, -2); // stack: table_of_component table_of_this + lua_pushlstring(l, functionName.data(), functionName.length()); // stack: table_of_component table_of_this "update" + lua_rawget(l, -2); // stack: table_of_component table_of_this table_of_this["update"] + lua_remove(l, -2); // stack: table_of_component table_of_this["update"] + lua_remove(l, -2); // stack: table_of_this["update"] int type = lua_type(l, -1); // if (type != LUA_TFUNCTION) diff --git a/extensions/scripting/lua-bindings/manual/CCComponentLua.h b/extensions/scripting/lua-bindings/manual/CCComponentLua.h index 4a2425987b7c..5f17a086d351 100644 --- a/extensions/scripting/lua-bindings/manual/CCComponentLua.h +++ b/extensions/scripting/lua-bindings/manual/CCComponentLua.h @@ -34,9 +34,9 @@ NS_CC_BEGIN class ComponentLua : public Component { public: - static ComponentLua* create(const std::string& scriptFileName); + static ComponentLua* create(std::string_view scriptFileName); - ComponentLua(const std::string& scriptFileName); + ComponentLua(std::string_view scriptFileName); /** * This function is used to be invoked from lua side to get the corresponding script object of this component. */ @@ -52,7 +52,7 @@ class ComponentLua : public Component bool loadAndExecuteScript(); void getUserData(); void storeLuaTable(); - bool getLuaFunction(const std::string& functionName); + bool getLuaFunction(std::string_view functionName); void removeLuaTable(); static void initClass(); diff --git a/extensions/scripting/lua-bindings/manual/CCLuaEngine.cpp b/extensions/scripting/lua-bindings/manual/CCLuaEngine.cpp index c474533f3c99..1e8453995300 100644 --- a/extensions/scripting/lua-bindings/manual/CCLuaEngine.cpp +++ b/extensions/scripting/lua-bindings/manual/CCLuaEngine.cpp @@ -174,7 +174,7 @@ int LuaEngine::reallocateScriptHandler(int nHandler) return nRet; } -bool LuaEngine::parseConfig(ConfigType type, const std::string& str) +bool LuaEngine::parseConfig(ConfigType type, std::string_view str) { lua_getglobal(_stack->getLuaState(), "__onParseConfig"); if (!lua_isfunction(_stack->getLuaState(), -1)) @@ -185,7 +185,7 @@ bool LuaEngine::parseConfig(ConfigType type, const std::string& str) } _stack->pushInt((int)type); - _stack->pushString(str.c_str()); + _stack->pushString(str.data(), str.length()); return _stack->executeFunction(2); } diff --git a/extensions/scripting/lua-bindings/manual/CCLuaEngine.h b/extensions/scripting/lua-bindings/manual/CCLuaEngine.h index dbaf44d04c30..233543b72f54 100644 --- a/extensions/scripting/lua-bindings/manual/CCLuaEngine.h +++ b/extensions/scripting/lua-bindings/manual/CCLuaEngine.h @@ -188,7 +188,7 @@ class CC_LUA_DLL LuaEngine : public ScriptEngineProtocol * @return if __onParseConfig function exist in the Lua, it return the value that _stack->executeFunction returns * otherwise return false. */ - virtual bool parseConfig(ConfigType type, const std::string& str) override; + virtual bool parseConfig(ConfigType type, std::string_view str) override; /** * When some events triggered in the c++ also needs to pass on to lua to handle, we could call this function to send diff --git a/extensions/scripting/lua-bindings/manual/CCLuaStack.cpp b/extensions/scripting/lua-bindings/manual/CCLuaStack.cpp index 1160d1ab9a0f..aef8cb70768b 100644 --- a/extensions/scripting/lua-bindings/manual/CCLuaStack.cpp +++ b/extensions/scripting/lua-bindings/manual/CCLuaStack.cpp @@ -294,9 +294,9 @@ void LuaStack::pushBoolean(bool boolValue) lua_pushboolean(_state, boolValue); } -void LuaStack::pushString(const char* stringValue) +void LuaStack::pushString(std::string_view stringValue) { - lua_pushstring(_state, stringValue); + lua_pushlstring(_state, stringValue.data(), stringValue.length()); } void LuaStack::pushString(const char* stringValue, int length) @@ -331,7 +331,7 @@ void LuaStack::pushLuaValue(const LuaValue& value) } else if (type == LuaValueTypeString) { - return pushString(value.stringValue().c_str()); + return pushString(value.stringValue()); } else if (type == LuaValueTypeDict) { @@ -343,7 +343,7 @@ void LuaStack::pushLuaValue(const LuaValue& value) } else if (type == LuaValueTypeObject) { - pushObject(value.ccobjectValue(), value.getObjectTypename().c_str()); + pushObject(value.ccobjectValue(), value.getObjectTypename().data()); } } @@ -352,9 +352,9 @@ void LuaStack::pushLuaValueDict(const LuaValueDict& dict) lua_newtable(_state); /* L: table */ for (LuaValueDictIterator it = dict.begin(); it != dict.end(); ++it) { - lua_pushstring(_state, it->first.c_str()); /* L: table key */ - pushLuaValue(it->second); /* L: table key value */ - lua_rawset(_state, -3); /* table.key = value, L: table */ + lua_pushlstring(_state, it->first.c_str(), it->first.length()); /* L: table key */ + pushLuaValue(it->second); /* L: table key value */ + lua_rawset(_state, -3); /* table.key = value, L: table */ } } diff --git a/extensions/scripting/lua-bindings/manual/CCLuaStack.h b/extensions/scripting/lua-bindings/manual/CCLuaStack.h index cd01e56d8f67..e55313b03fd5 100644 --- a/extensions/scripting/lua-bindings/manual/CCLuaStack.h +++ b/extensions/scripting/lua-bindings/manual/CCLuaStack.h @@ -184,7 +184,7 @@ class LuaStack : public Ref * * @param stringValue a pointer point to a zero-terminated string stringValue. */ - virtual void pushString(const char* stringValue); + virtual void pushString(std::string_view stringValue); /** * Pushes the string pointed to by stringValue with size length onto the stack. diff --git a/extensions/scripting/lua-bindings/manual/CCLuaValue.cpp b/extensions/scripting/lua-bindings/manual/CCLuaValue.cpp index 6bb23e16e167..6e2112c5e1d8 100644 --- a/extensions/scripting/lua-bindings/manual/CCLuaValue.cpp +++ b/extensions/scripting/lua-bindings/manual/CCLuaValue.cpp @@ -60,7 +60,7 @@ const LuaValue LuaValue::stringValue(const char* stringValue) return value; } -const LuaValue LuaValue::stringValue(const std::string& stringValue) +const LuaValue LuaValue::stringValue(std::string_view stringValue) { LuaValue value; value._type = LuaValueTypeString; @@ -94,9 +94,9 @@ const LuaValue LuaValue::ccobjectValue(Ref* ccobjectValue, const char* objectTyp return value; } -const LuaValue LuaValue::ccobjectValue(Ref* ccobjectValue, const std::string& objectTypename) +const LuaValue LuaValue::ccobjectValue(Ref* ccobjectValue, std::string_view objectTypename) { - return LuaValue::ccobjectValue(ccobjectValue, objectTypename.c_str()); + return LuaValue::ccobjectValue(ccobjectValue, objectTypename.data()); } LuaValue::LuaValue(const LuaValue& rhs) diff --git a/extensions/scripting/lua-bindings/manual/CCLuaValue.h b/extensions/scripting/lua-bindings/manual/CCLuaValue.h index 0997bdbf43d2..8b918263e136 100644 --- a/extensions/scripting/lua-bindings/manual/CCLuaValue.h +++ b/extensions/scripting/lua-bindings/manual/CCLuaValue.h @@ -135,7 +135,7 @@ class LuaValue * @param stringValue a std::string object. * @return a LuaValue object. */ - static const LuaValue stringValue(const std::string& stringValue); + static const LuaValue stringValue(std::string_view stringValue); /** * Construct a LuaValue object by a LuaValueDict value. @@ -169,7 +169,7 @@ class LuaValue * @param objectTypename a std::string object represent the typename of object. * @return a LuaValue object. */ - static const LuaValue ccobjectValue(Ref* ccobjectValue, const std::string& objectTypename); + static const LuaValue ccobjectValue(Ref* ccobjectValue, std::string_view objectTypename); /** * Default constructor of LuaValue. @@ -204,7 +204,7 @@ class LuaValue * * @return the reference of _ccobjectType. */ - const std::string& getObjectTypename() const { return *_ccobjectType; } + std::string_view getObjectTypename() const { return *_ccobjectType; } /** * Get the int value of LuaValue object. @@ -232,7 +232,7 @@ class LuaValue * * @return the reference about string value. */ - const std::string& stringValue() const { return *_field.stringValue; } + std::string_view stringValue() const { return *_field.stringValue; } /** * Get the LuaValueDict value of LuaValue object. diff --git a/extensions/scripting/lua-bindings/manual/LuaBasicConversions.cpp b/extensions/scripting/lua-bindings/manual/LuaBasicConversions.cpp index eba25e98e18a..a17f5ee6a7b3 100644 --- a/extensions/scripting/lua-bindings/manual/LuaBasicConversions.cpp +++ b/extensions/scripting/lua-bindings/manual/LuaBasicConversions.cpp @@ -1564,6 +1564,47 @@ bool luaval_to_std_vector_string(lua_State* L, int lo, std::vector* return ok; } +bool luaval_to_std_vector_string_view(lua_State* L, int lo, std::vector* ret, const char* funcName) +{ + if (nullptr == L || nullptr == ret || lua_gettop(L) < lo) + return false; + + tolua_Error tolua_err; + bool ok = true; + if (!tolua_istable(L, lo, 0, &tolua_err)) + { +#if COCOS2D_DEBUG >= 1 + luaval_to_native_err(L, "#ferror:", &tolua_err, funcName); +#endif + ok = false; + } + + if (ok) + { + size_t len = lua_objlen(L, lo); + std::string_view value = ""; + for (size_t i = 0; i < len; i++) + { + lua_pushnumber(L, i + 1); + lua_gettable(L, lo); + if (lua_isstring(L, -1)) + { + ok = luaval_to_std_string_view(L, -1, &value); + if (ok) + ret->push_back(value); + } + else + { + CCASSERT(false, "string type is needed"); + } + + lua_pop(L, 1); + } + } + + return ok; +} + bool luaval_to_std_vector_int(lua_State* L, int lo, std::vector* ret, const char* funcName) { if (nullptr == L || nullptr == ret || lua_gettop(L) < lo) @@ -2402,7 +2443,7 @@ void ccvalue_to_luaval(lua_State* L, const cocos2d::Value& inValue) lua_pushinteger(L, obj.asInt64()); break; case Value::Type::STRING: - lua_pushstring(L, obj.asStringRef().c_str()); + lua_pushstring(L, obj.asStringRef().data()); break; case Value::Type::VECTOR: ccvaluevector_to_luaval(L, obj.asValueVector()); @@ -2527,7 +2568,7 @@ void ccvaluemapintkey_to_luaval(lua_State* L, const cocos2d::ValueMapIntKey& inV case Value::Type::STRING: { lua_pushstring(L, key.c_str()); - lua_pushstring(L, obj.asStringRef().c_str()); + lua_pushstring(L, obj.asStringRef().data()); lua_rawset(L, -3); } break; @@ -2725,10 +2766,10 @@ void ccvector_std_string_to_luaval(lua_State* L, const std::vector& int index = 1; - for (const std::string& value : inValue) + for (std::string_view value : inValue) { lua_pushnumber(L, (lua_Number)index); - lua_pushstring(L, value.c_str()); + lua_pushlstring(L, value.data(), value.length()); lua_rawset(L, -3); ++index; } @@ -2858,10 +2899,7 @@ void std_map_string_string_to_luaval(lua_State* L, const std::map* ret, - const char* funcName) +bool luaval_to_std_map_string_string(lua_State* L, int lo, hlookup::string_map* ret, const char* funcName) { if (nullptr == L || nullptr == ret || lua_gettop(L) < lo) return false; @@ -2880,15 +2918,15 @@ bool luaval_to_std_map_string_string(lua_State* L, return ok; lua_pushnil(L); - std::string key; - std::string value; + std::string_view key; + std::string_view value; while (lua_next(L, lo) != 0) { if (lua_isstring(L, -2) && lua_isstring(L, -1)) { - if (luaval_to_std_string(L, -2, &key) && luaval_to_std_string(L, -1, &value)) + if (luaval_to_std_string_view(L, -2, &key) && luaval_to_std_string_view(L, -1, &value)) { - (*ret)[key] = value; + ret->emplace(key, value); // (*ret)[key] = value; } } else @@ -3022,8 +3060,7 @@ void uniformLocation_to_luaval(lua_State* L, const cocos2d::backend::UniformLoca lua_rawset(L, -3); } -void program_activeattrs_to_luaval(lua_State* L, - const std::unordered_map& attrs) +void program_activeattrs_to_luaval(lua_State* L, const hlookup::string_map& attrs) { if (L == nullptr) return; diff --git a/extensions/scripting/lua-bindings/manual/LuaBasicConversions.h b/extensions/scripting/lua-bindings/manual/LuaBasicConversions.h index a754959def03..d6665b5a7028 100644 --- a/extensions/scripting/lua-bindings/manual/LuaBasicConversions.h +++ b/extensions/scripting/lua-bindings/manual/LuaBasicConversions.h @@ -594,6 +594,11 @@ CC_LUA_DLL bool luaval_to_std_vector_string(lua_State* L, std::vector* ret, const char* funcName = ""); +CC_LUA_DLL bool luaval_to_std_vector_string_view(lua_State* L, + int lo, + std::vector* ret, + const char* funcName = ""); + /** * Get a pointer points to a std::vector from a Lua array table in the stack. * @@ -870,7 +875,7 @@ extern bool luaval_to_std_vector_vec3(lua_State* L, int lo, std::vector* ret, + hlookup::string_map* ret, const char* funcName); /**@}**/ @@ -1140,7 +1145,7 @@ void ccvector_to_luaval(lua_State* L, const cocos2d::Vector& inValue) * @param v a cocos2d::Map object. */ template -void ccmap_string_key_to_luaval(lua_State* L, const cocos2d::Map& v) +void ccmap_string_key_to_luaval(lua_State* L, const cocos2d::StringMap& v) { lua_newtable(L); @@ -1149,8 +1154,8 @@ void ccmap_string_key_to_luaval(lua_State* L, const cocos2d::Map for (auto iter = v.begin(); iter != v.end(); ++iter) { - std::string key = iter->first; - T obj = iter->second; + auto& key = iter->first; + T obj = iter->second; if (nullptr != dynamic_cast(obj)) { auto name = reinterpret_cast(typeid(*obj).name()); @@ -1360,9 +1365,8 @@ CC_LUA_DLL bool luaval_to_uniformLocation(lua_State* L, */ CC_LUA_DLL void uniformLocation_to_luaval(lua_State* L, const cocos2d::backend::UniformLocation& desc); -CC_LUA_DLL void program_activeattrs_to_luaval( - lua_State* L, - const std::unordered_map& map); +CC_LUA_DLL void program_activeattrs_to_luaval(lua_State* L, + const hlookup::string_map& map); // end group /// @} diff --git a/extensions/scripting/lua-bindings/manual/audioengine/lua_cocos2dx_audioengine_manual.cpp b/extensions/scripting/lua-bindings/manual/audioengine/lua_cocos2dx_audioengine_manual.cpp index 7274d4866458..a43793b275cf 100644 --- a/extensions/scripting/lua-bindings/manual/audioengine/lua_cocos2dx_audioengine_manual.cpp +++ b/extensions/scripting/lua-bindings/manual/audioengine/lua_cocos2dx_audioengine_manual.cpp @@ -269,11 +269,11 @@ int lua_cocos2dx_audioengine_AudioEngine_setFinishCallback(lua_State* tolua_S) LUA_FUNCTION handler = (toluafix_ref_function(tolua_S, 3, 0)); - cocos2d::AudioEngine::setFinishCallback(arg0, [=](int audioID, std::string filePath) { + cocos2d::AudioEngine::setFinishCallback(arg0, [=](int audioID, std::string_view filePath) { LuaStack* stack = LuaEngine::getInstance()->getLuaStack(); stack->pushInt(audioID); - stack->pushString(filePath.c_str()); + stack->pushString(filePath); stack->executeFunctionByHandler(handler, 2); diff --git a/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.cpp b/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.cpp index 963f1d2e159d..1b8eb8f218d7 100644 --- a/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.cpp +++ b/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.cpp @@ -4546,7 +4546,7 @@ EventListenerAcceleration* LuaEventListenerAcceleration::create() return eventAcceleration; } -EventListenerCustom* LuaEventListenerCustom::create(const std::string& eventName) +EventListenerCustom* LuaEventListenerCustom::create(std::string_view eventName) { EventListenerCustom* eventCustom = new EventListenerCustom(); if (eventCustom->init(eventName, [=](EventCustom* event) { @@ -6109,12 +6109,12 @@ static int lua_cocos2dx_Console_addCommand(lua_State* tolua_S) handler = (toluafix_ref_function(tolua_S, 3, 0)); ScriptHandlerMgr::getInstance()->addCustomHandler((void*)cobj, handler); - Console::Command outValue = {name, help, [=](int fd, const std::string& args) { + Console::Command outValue = {name, help, [=](int fd, std::string_view args) { auto stack = LuaEngine::getInstance()->getLuaStack(); auto Ls = stack->getLuaState(); // lua-callback, the third param; tolua_pushnumber(Ls, fd); - tolua_pushstring(Ls, args.c_str()); + tolua_pushstring(Ls, args.data()); stack->executeFunctionByHandler(handler, 2); }}; @@ -6928,7 +6928,7 @@ int lua_cocos2dx_get_PolygonInfo_filename(lua_State* tolua_S) return 0; } #endif - tolua_pushcppstring(tolua_S, cobj->getFilename()); + tolua_pushstring(tolua_S, cobj->getFilename().data()); return 1; #if COCOS2D_DEBUG >= 1 @@ -7430,11 +7430,11 @@ static int tolua_cocos2d_utils_captureScreen(lua_State* tolua_S) LUA_FUNCTION handler = toluafix_ref_function(tolua_S, 2, 0); std::string fileName = tolua_tocppstring(tolua_S, 3, ""); cocos2d::utils::captureScreen( - [=](bool succeed, const std::string& name) { + [=](bool succeed, std::string_view name) { auto stack = LuaEngine::getInstance()->getLuaStack(); auto Ls = stack->getLuaState(); tolua_pushboolean(Ls, succeed); - tolua_pushstring(Ls, name.c_str()); + tolua_pushstring(Ls, name.data()); stack->executeFunctionByHandler(handler, 2); toluafix_remove_function_by_refid(tolua_S, handler); }, diff --git a/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.hpp b/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.hpp index ffca5eacff6f..d8ab149f92ca 100644 --- a/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.hpp +++ b/extensions/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.hpp @@ -44,7 +44,7 @@ NS_CC_BEGIN class LuaEventListenerCustom { public: - static EventListenerCustom* create(const std::string& eventName); + static EventListenerCustom* create(std::string_view eventName); }; class LuaEventListenerAcceleration diff --git a/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.cpp b/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.cpp index be047e4b4b7e..3fa250fdb6c7 100644 --- a/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.cpp +++ b/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.cpp @@ -85,7 +85,7 @@ void CustomGUIReader::init(std::string& className, int createFunc, int setPropsF (*callbackMap)[className] = parseselector(CustomGUIReader::setCustomProps); } -void CustomGUIReader::setCustomProps(const std::string& classType, +void CustomGUIReader::setCustomProps(std::string_view classType, cocos2d::Ref* widget, const rapidjson::Value& customOptions) { @@ -96,7 +96,7 @@ void CustomGUIReader::setCustomProps(const std::string& classType, customOptions.Accept(writer); auto stack = LuaEngine::getInstance()->getLuaStack(); - stack->pushString(classType.c_str(), static_cast(classType.size())); + stack->pushString(classType); stack->pushObject(widget, "cc.Ref"); stack->pushString(buffer.GetString(), static_cast(buffer.GetSize())); stack->executeFunctionByHandler(_setPropsFunc, 3); diff --git a/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.h b/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.h index 79c4ab3ec743..9c331a16fd19 100644 --- a/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.h +++ b/extensions/scripting/lua-bindings/manual/cocostudio/CustomGUIReader.h @@ -43,7 +43,7 @@ class CustomGUIReader : public Ref Ref* createInstance(); - void setCustomProps(const std::string& classType, cocos2d::Ref* widget, const rapidjson::Value& customOptions); + void setCustomProps(std::string_view classType, cocos2d::Ref* widget, const rapidjson::Value& customOptions); private: std::string _className; diff --git a/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.cpp b/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.cpp index d063179bedc7..27e19dbf397a 100644 --- a/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.cpp +++ b/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.cpp @@ -112,11 +112,10 @@ static int lua_cocos2dx_ArmatureAnimation_setMovementEventCallFunc(lua_State* L) ScriptHandlerMgr::HandlerType::ARMATURE_EVENT); self->setMovementEventCallFunc( - [=](Armature* armature, MovementEventType movementType, const std::string& movementID) { + [=](Armature* armature, MovementEventType movementType, std::string_view movementID) { if (0 != handler) { - std::string strMovementID = movementID; - LuaArmatureMovementEventData movementData(armature, (int)movementType, strMovementID); + LuaArmatureMovementEventData movementData(armature, (int)movementType, movementID); LuaArmatureWrapperEventData wrapperData( LuaArmatureWrapperEventData::LuaArmatureWrapperEventType::MOVEMENT_EVENT, (void*)&movementData); @@ -188,22 +187,22 @@ static int lua_cocos2dx_ArmatureAnimation_setFrameEventCallFunc(lua_State* L) ScriptHandlerMgr::getInstance()->addObjectHandler((void*)wrapper, handler, ScriptHandlerMgr::HandlerType::ARMATURE_EVENT); - self->setFrameEventCallFunc([=](cocostudio::Bone* bone, const std::string& frameEventName, int originFrameIndex, - int currentFrameIndex) { - if (0 != handler) - { - std::string strFrameEventName(frameEventName); + self->setFrameEventCallFunc( + [=](cocostudio::Bone* bone, std::string_view frameEventName, int originFrameIndex, int currentFrameIndex) { + if (0 != handler) + { + std::string strFrameEventName(frameEventName); - LuaArmatureFrameEventData frameData(bone, frameEventName, originFrameIndex, currentFrameIndex); + LuaArmatureFrameEventData frameData(bone, frameEventName, originFrameIndex, currentFrameIndex); - LuaArmatureWrapperEventData wrapperData( - LuaArmatureWrapperEventData::LuaArmatureWrapperEventType::FRAME_EVENT, (void*)&frameData); + LuaArmatureWrapperEventData wrapperData( + LuaArmatureWrapperEventData::LuaArmatureWrapperEventType::FRAME_EVENT, (void*)&frameData); - BasicScriptData data((void*)vec.at(0), (void*)&wrapperData); + BasicScriptData data((void*)vec.at(0), (void*)&wrapperData); - LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::ARMATURE_EVENT, (void*)&data); - } - }); + LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::ARMATURE_EVENT, (void*)&data); + } + }); return 0; } diff --git a/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.hpp b/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.hpp index afd08dc0e5d9..422d717d843d 100644 --- a/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.hpp +++ b/extensions/scripting/lua-bindings/manual/cocostudio/lua_cocos2dx_coco_studio_manual.hpp @@ -78,7 +78,7 @@ struct LuaArmatureMovementEventData int movementType; std::string movementID; - LuaArmatureMovementEventData(cocos2d::Ref* _objTarget, int _movementType,const std::string& _movementID):objTarget(_objTarget),movementType(_movementType),movementID(_movementID) + LuaArmatureMovementEventData(cocos2d::Ref* _objTarget, int _movementType,std::string_view _movementID):objTarget(_objTarget),movementType(_movementType),movementID(_movementID) { } }; @@ -90,7 +90,7 @@ struct LuaArmatureFrameEventData int originFrameIndex; int currentFrameIndex; - LuaArmatureFrameEventData( cocos2d::Ref* _objTarget, const std::string& _frameEventName, int _originFrameIndex, int _currentFrameIndex):objTarget(_objTarget), frameEventName(_frameEventName),originFrameIndex(_originFrameIndex), currentFrameIndex(_currentFrameIndex) + LuaArmatureFrameEventData( cocos2d::Ref* _objTarget, std::string_view _frameEventName, int _originFrameIndex, int _currentFrameIndex):objTarget(_objTarget), frameEventName(_frameEventName),originFrameIndex(_originFrameIndex), currentFrameIndex(_currentFrameIndex) { } }; diff --git a/extensions/scripting/lua-bindings/manual/network/lua_downloader.cpp b/extensions/scripting/lua-bindings/manual/network/lua_downloader.cpp index 179eb45bf0ae..ba66c3442b40 100644 --- a/extensions/scripting/lua-bindings/manual/network/lua_downloader.cpp +++ b/extensions/scripting/lua-bindings/manual/network/lua_downloader.cpp @@ -270,27 +270,26 @@ static int lua_downloader_setOnTaskError(lua_State* L) luaL_argcheck(L, lua_isfunction(L, 2), 2, "should be a function"); saveCallback(L, d, "setOnTaskError"); - d->setOnTaskError( - [d, L](const DownloadTask& task, int errorCode, int errorCodeInternal, const std::string& errorSt) { - int ret = getCallback(L, d, "setOnTaskError"); // stack callbackfn - if (ret) - { - pushTaskTable(L, task); // stack callbackfn, task - lua_pushnumber(L, errorCode); - lua_pushnumber(L, errorCodeInternal); - lua_pushstring(L, errorSt.c_str()); - if (lua_pcall(L, 4, 0, 0) != 0) - { - lua_pop(L, 1); // remove callback or nil - luaL_error(L, "cc.Downloader.setOnTaskError invoke callback error!"); - return; - } - } - else + d->setOnTaskError([d, L](const DownloadTask& task, int errorCode, int errorCodeInternal, std::string_view errorSt) { + int ret = getCallback(L, d, "setOnTaskError"); // stack callbackfn + if (ret) + { + pushTaskTable(L, task); // stack callbackfn, task + lua_pushnumber(L, errorCode); + lua_pushnumber(L, errorCodeInternal); + lua_pushlstring(L, errorSt.data(), errorSt.length()); + if (lua_pcall(L, 4, 0, 0) != 0) { lua_pop(L, 1); // remove callback or nil + luaL_error(L, "cc.Downloader.setOnTaskError invoke callback error!"); + return; } - }); + } + else + { + lua_pop(L, 1); // remove callback or nil + } + }); return 0; } diff --git a/extensions/scripting/lua-bindings/manual/network/lua_xml_http_request.cpp b/extensions/scripting/lua-bindings/manual/network/lua_xml_http_request.cpp index b6b942c6e793..dce4f0d92ab5 100644 --- a/extensions/scripting/lua-bindings/manual/network/lua_xml_http_request.cpp +++ b/extensions/scripting/lua-bindings/manual/network/lua_xml_http_request.cpp @@ -76,16 +76,16 @@ class LuaMinXmlHttpRequest : public cocos2d::Ref inline int getReadyState() const { return _readyState; } inline cocos2d::network::HttpRequest* getHttpRequest() const { return _httpRequest; } - inline const std::string& getStatusText() const { return _statusText; } + inline std::string_view getStatusText() const { return _statusText; } inline void setStatus(int status) { _status = status; } inline int getStatus() { return _status; } - inline const std::string& getUrl() { return _url; } - inline void setUrl(const std::string& url) { _url = url; } + inline std::string_view getUrl() { return _url; } + inline void setUrl(std::string_view url) { _url = url; } - inline const std::string& getMethod() const { return _meth; } - inline void setMethod(const std::string& meth) { _meth = meth; } + inline std::string_view getMethod() const { return _meth; } + inline void setMethod(std::string_view meth) { _meth = meth; } inline void setAsync(bool isAsync) { _isAsync = isAsync; } inline void setIsNetWork(bool isNetWork) { _isNetwork = isNetWork; } @@ -621,7 +621,8 @@ static int lua_get_XMLHttpRequest_statusText(lua_State* L) } #endif - lua_pushstring(L, self->getStatusText().c_str()); + auto statusText = self->getStatusText(); + lua_pushlstring(L, statusText.data(), statusText.length()); return 1; diff --git a/extensions/scripting/lua-bindings/manual/platform/ios/CCLuaObjcBridge.mm b/extensions/scripting/lua-bindings/manual/platform/ios/CCLuaObjcBridge.mm index f28f8b47b280..b50ec4d916bf 100644 --- a/extensions/scripting/lua-bindings/manual/platform/ios/CCLuaObjcBridge.mm +++ b/extensions/scripting/lua-bindings/manual/platform/ios/CCLuaObjcBridge.mm @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -22,13 +22,12 @@ of this software and associated documentation files (the "Software"), to deal THE SOFTWARE. ****************************************************************************/ - #include "scripting/lua-bindings/manual/platform/ios/CCLuaObjcBridge.h" #include NS_CC_BEGIN -void LuaObjcBridge::luaopen_luaoc(lua_State *L) +void LuaObjcBridge::luaopen_luaoc(lua_State* L) { s_luaState = L; lua_newtable(L); @@ -38,39 +37,36 @@ of this software and associated documentation files (the "Software"), to deal lua_setglobal(L, "LuaObjcBridge"); } - -static void luaTableToObjcDictionary(lua_State *L, NSMutableDictionary *dict,NSString *key){ - NSMutableDictionary *dict2 = [[NSMutableDictionary alloc] init]; +static void luaTableToObjcDictionary(lua_State* L, NSMutableDictionary* dict, NSString* key) +{ + NSMutableDictionary* dict2 = [[NSMutableDictionary alloc] init]; lua_pushnil(L); - while(lua_next(L, -2)) + while (lua_next(L, -2)) { - NSString *key2 = [NSString stringWithCString:lua_tostring(L, -2) encoding:NSUTF8StringEncoding]; - + NSString* key2 = [NSString stringWithCString:lua_tostring(L, -2) encoding:NSUTF8StringEncoding]; + switch (lua_type(L, -1)) { - case LUA_TNUMBER: - [dict2 setObject:[NSNumber numberWithFloat:lua_tonumber(L, -1)] forKey:key2]; - break; - - case LUA_TBOOLEAN: - [dict2 setObject:[NSNumber numberWithBool:lua_toboolean(L, -1)] forKey:key2]; - break; - - case LUA_TSTRING: - [dict2 setObject:[NSString stringWithCString:lua_tostring(L, -1) encoding:NSUTF8StringEncoding] - forKey:key2]; - break; - case LUA_TTABLE: - luaTableToObjcDictionary(L, dict2, key2); - break; + case LUA_TNUMBER: + [dict2 setObject:[NSNumber numberWithFloat:lua_tonumber(L, -1)] forKey:key2]; + break; + + case LUA_TBOOLEAN: + [dict2 setObject:[NSNumber numberWithBool:lua_toboolean(L, -1)] forKey:key2]; + break; + + case LUA_TSTRING: + [dict2 setObject:[NSString stringWithCString:lua_tostring(L, -1) encoding:NSUTF8StringEncoding] + forKey:key2]; + break; + case LUA_TTABLE: + luaTableToObjcDictionary(L, dict2, key2); + break; } - lua_pop(L,1); + lua_pop(L, 1); } - - + [dict setObject:dict2 forKey:key]; - - } /** @@ -78,24 +74,24 @@ static void luaTableToObjcDictionary(lua_State *L, NSMutableDictionary *dict,NSS methodName args */ -int LuaObjcBridge::callObjcStaticMethod(lua_State *L) +int LuaObjcBridge::callObjcStaticMethod(lua_State* L) { if (lua_gettop(L) != 3 || !lua_isstring(L, -3) || !lua_isstring(L, -2)) { - lua_pushboolean(L, 0); - lua_pushinteger(L, kLuaBridgeErrorInvalidParameters); - return 2; + lua_pushboolean(L, 0); + lua_pushinteger(L, kLuaBridgeErrorInvalidParameters); + return 2; } - - const char *className = lua_tostring(L, -3); - const char *methodName = lua_tostring(L, -2); + + const char* className = lua_tostring(L, -3); + const char* methodName = lua_tostring(L, -2); if (!className || !methodName) { lua_pushboolean(L, 0); lua_pushinteger(L, kLuaBridgeErrorInvalidParameters); return 2; } - + Class targetClass = NSClassFromString([NSString stringWithCString:className encoding:NSUTF8StringEncoding]); if (!targetClass) { @@ -103,14 +99,14 @@ static void luaTableToObjcDictionary(lua_State *L, NSMutableDictionary *dict,NSS lua_pushinteger(L, kLuaBridgeErrorClassNotFound); return 2; } - + SEL methodSel; bool hasArguments = lua_istable(L, -1); if (hasArguments) { - NSString *methodName_ = [NSString stringWithCString:methodName encoding:NSUTF8StringEncoding]; - methodName_ = [NSString stringWithFormat:@"%@:", methodName_]; - methodSel = NSSelectorFromString(methodName_); + NSString* methodName_ = [NSString stringWithCString:methodName encoding:NSUTF8StringEncoding]; + methodName_ = [NSString stringWithFormat:@"%@:", methodName_]; + methodSel = NSSelectorFromString(methodName_); } else { @@ -122,58 +118,59 @@ static void luaTableToObjcDictionary(lua_State *L, NSMutableDictionary *dict,NSS lua_pushinteger(L, kLuaBridgeErrorMethodNotFound); return 2; } - - NSMethodSignature *methodSig = [targetClass methodSignatureForSelector:(SEL)methodSel]; + + NSMethodSignature* methodSig = [targetClass methodSignatureForSelector:(SEL)methodSel]; if (methodSig == nil) { lua_pushboolean(L, 0); lua_pushinteger(L, kLuaBridgeErrorMethodSignature); return 2; } - - @try { - NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig]; + + @try + { + NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:methodSig]; [invocation setTarget:targetClass]; [invocation setSelector:methodSel]; NSUInteger returnLength = [methodSig methodReturnLength]; - const char *returnType = [methodSig methodReturnType]; - + const char* returnType = [methodSig methodReturnType]; + if (hasArguments) { - NSMutableDictionary *dict = [NSMutableDictionary dictionary]; + NSMutableDictionary* dict = [NSMutableDictionary dictionary]; lua_pushnil(L); while (lua_next(L, -2)) { - NSString *key = [NSString stringWithCString:lua_tostring(L, -2) encoding:NSUTF8StringEncoding]; - + NSString* key = [NSString stringWithCString:lua_tostring(L, -2) encoding:NSUTF8StringEncoding]; + switch (lua_type(L, -1)) { - case LUA_TNUMBER: - [dict setObject:[NSNumber numberWithFloat:lua_tonumber(L, -1)] forKey:key]; - break; - - case LUA_TBOOLEAN: - [dict setObject:[NSNumber numberWithBool:lua_toboolean(L, -1)] forKey:key]; - break; - - case LUA_TSTRING: - [dict setObject:[NSString stringWithCString:lua_tostring(L, -1) encoding:NSUTF8StringEncoding] - forKey:key]; - break; - - case LUA_TTABLE: - luaTableToObjcDictionary(L, dict, key); - break; - - case LUA_TFUNCTION: - int functionId = retainLuaFunction(L, -1, NULL); - [dict setObject:[NSNumber numberWithInt:functionId] forKey:key]; - break; + case LUA_TNUMBER: + [dict setObject:[NSNumber numberWithFloat:lua_tonumber(L, -1)] forKey:key]; + break; + + case LUA_TBOOLEAN: + [dict setObject:[NSNumber numberWithBool:lua_toboolean(L, -1)] forKey:key]; + break; + + case LUA_TSTRING: + [dict setObject:[NSString stringWithCString:lua_tostring(L, -1) encoding:NSUTF8StringEncoding] + forKey:key]; + break; + + case LUA_TTABLE: + luaTableToObjcDictionary(L, dict, key); + break; + + case LUA_TFUNCTION: + int functionId = retainLuaFunction(L, -1, NULL); + [dict setObject:[NSNumber numberWithInt:functionId] forKey:key]; + break; } - + lua_pop(L, 1); } - + [invocation setArgument:&dict atIndex:2]; [invocation invoke]; } @@ -181,7 +178,7 @@ static void luaTableToObjcDictionary(lua_State *L, NSMutableDictionary *dict,NSS { [invocation invoke]; } - + lua_pushboolean(L, 1); if (returnLength > 0) { @@ -191,19 +188,19 @@ static void luaTableToObjcDictionary(lua_State *L, NSMutableDictionary *dict,NSS [invocation getReturnValue:&ret]; pushValue(L, ret); } - else if (strcmp(returnType, @encode(BOOL)) == 0) // BOOL + else if (strcmp(returnType, @encode(BOOL)) == 0) // BOOL { char ret; [invocation getReturnValue:&ret]; lua_pushboolean(L, ret); } - else if (strcmp(returnType, @encode(int)) == 0) // int + else if (strcmp(returnType, @encode(int)) == 0) // int { int ret; [invocation getReturnValue:&ret]; lua_pushinteger(L, ret); } - else if (strcmp(returnType, @encode(float)) == 0) // float + else if (strcmp(returnType, @encode(float)) == 0) // float { float ret; [invocation getReturnValue:&ret]; @@ -221,16 +218,16 @@ static void luaTableToObjcDictionary(lua_State *L, NSMutableDictionary *dict,NSS } return 2; } - @catch (NSException *exception) + @catch (NSException* exception) { NSLog(@"EXCEPTION THROW: %@", exception); lua_pushboolean(L, 0); lua_pushinteger(L, kLuaBridgeErrorExceptionOccurred); - return 2; + return 2; } } -void LuaObjcBridge::pushValue(lua_State *L, void *val) +void LuaObjcBridge::pushValue(lua_State* L, void* val) { id oval = (id)val; if (oval == nil) @@ -239,8 +236,8 @@ static void luaTableToObjcDictionary(lua_State *L, NSMutableDictionary *dict,NSS } else if ([oval isKindOfClass:[NSNumber class]]) { - NSNumber *number = (NSNumber *)oval; - const char *numberType = [number objCType]; + NSNumber* number = (NSNumber*)oval; + const char* numberType = [number objCType]; if (strcmp(numberType, @encode(BOOL)) == 0) { lua_pushboolean(L, [number boolValue]); @@ -261,15 +258,15 @@ static void luaTableToObjcDictionary(lua_State *L, NSMutableDictionary *dict,NSS else if ([oval isKindOfClass:[NSDictionary class]]) { lua_newtable(L); - + for (id key in oval) { - const char *key_ = [[NSString stringWithFormat:@"%@", key] cStringUsingEncoding:NSUTF8StringEncoding]; + const char* key_ = [[NSString stringWithFormat:@"%@", key] cStringUsingEncoding:NSUTF8StringEncoding]; lua_pushstring(L, key_); pushValue(L, [oval objectForKey:key]); lua_rawset(L, -3); } - + return; } else diff --git a/extensions/scripting/lua-bindings/manual/ui/lua_cocos2dx_webview_manual.cpp b/extensions/scripting/lua-bindings/manual/ui/lua_cocos2dx_webview_manual.cpp index a9d616e84245..88fc10209c42 100644 --- a/extensions/scripting/lua-bindings/manual/ui/lua_cocos2dx_webview_manual.cpp +++ b/extensions/scripting/lua-bindings/manual/ui/lua_cocos2dx_webview_manual.cpp @@ -63,8 +63,8 @@ static int lua_cocos2dx_WebView_setOnShouldStartLoading(lua_State* L) #endif LUA_FUNCTION handler = (toluafix_ref_function(L, 2, 0)); - std::function callback = - [L, handler](ui::WebView* sender, const std::string& url) -> bool { + std::function callback = + [L, handler](ui::WebView* sender, std::string_view url) -> bool { toluafix_pushusertype_ccobject(L, sender->_ID, &(sender->_luaID), (void*)sender, "ccui.WebView"); tolua_pushcppstring(L, url); return LuaEngine::getInstance()->getLuaStack()->executeFunctionByHandler(handler, 2); @@ -118,13 +118,13 @@ static int lua_cocos2dx_WebView_setOnDidFinishLoading(lua_State* L) } #endif - LUA_FUNCTION handler = (toluafix_ref_function(L, 2, 0)); - std::function callback = - [L, handler](ui::WebView* sender, const std::string& url) { - toluafix_pushusertype_ccobject(L, sender->_ID, &(sender->_luaID), (void*)sender, "ccui.WebView"); - tolua_pushcppstring(L, url); - LuaEngine::getInstance()->getLuaStack()->executeFunctionByHandler(handler, 2); - }; + LUA_FUNCTION handler = (toluafix_ref_function(L, 2, 0)); + std::function callback = [L, handler](ui::WebView* sender, + std::string_view url) { + toluafix_pushusertype_ccobject(L, sender->_ID, &(sender->_luaID), (void*)sender, "ccui.WebView"); + tolua_pushcppstring(L, url); + LuaEngine::getInstance()->getLuaStack()->executeFunctionByHandler(handler, 2); + }; ScriptHandlerMgr::getInstance()->addCustomHandler((void*)self, handler); self->setOnDidFinishLoading(callback); @@ -173,13 +173,13 @@ static int lua_cocos2dx_WebView_setOnDidFailLoading(lua_State* L) } #endif - LUA_FUNCTION handler = (toluafix_ref_function(L, 2, 0)); - std::function callback = - [L, handler](ui::WebView* sender, const std::string& url) { - toluafix_pushusertype_ccobject(L, sender->_ID, &(sender->_luaID), (void*)sender, "ccui.WebView"); - tolua_pushcppstring(L, url); - LuaEngine::getInstance()->getLuaStack()->executeFunctionByHandler(handler, 2); - }; + LUA_FUNCTION handler = (toluafix_ref_function(L, 2, 0)); + std::function callback = [L, handler](ui::WebView* sender, + std::string_view url) { + toluafix_pushusertype_ccobject(L, sender->_ID, &(sender->_luaID), (void*)sender, "ccui.WebView"); + tolua_pushcppstring(L, url); + LuaEngine::getInstance()->getLuaStack()->executeFunctionByHandler(handler, 2); + }; ScriptHandlerMgr::getInstance()->addCustomHandler((void*)self, handler); self->setOnDidFailLoading(callback); diff --git a/templates/cpp-template-default/CMakeLists.txt b/templates/cpp-template-default/CMakeLists.txt index 210f150edec0..04bebd1d1ca1 100644 --- a/templates/cpp-template-default/CMakeLists.txt +++ b/templates/cpp-template-default/CMakeLists.txt @@ -133,15 +133,14 @@ set(all_code_files ) if(NOT ANDROID) add_executable(${APP_NAME} ${all_code_files}) + target_link_libraries(${APP_NAME} ${ADXE_LUA_LIB}) else() add_library(${APP_NAME} SHARED ${all_code_files}) - add_subdirectory(${ADXE_ROOT_PATH}/cocos/platform/android ${ENGINE_BINARY_PATH}/cocos/platform) - target_link_libraries(${APP_NAME} -Wl,--whole-archive cpp_android_spec -Wl,--no-whole-archive) - + # whole archive ${ADXE_LUA_LIB} to make sure JNI_Onload can be invoke from java + target_link_libraries(${APP_NAME} -Wl,--whole-archive ${ADXE_LUA_LIB} -Wl,--no-whole-archive) config_android_shared_libs("org.cocos2dx.lib" "${CMAKE_CURRENT_SOURCE_DIR}/proj.android/app/src") endif() -target_link_libraries(${APP_NAME} ${ADXE_CORE_LIB}) target_include_directories(${APP_NAME} PRIVATE Classes PRIVATE ${ADXE_ROOT_PATH}/cocos/audio/include/ diff --git a/templates/cpp-template-default/Classes/AppDelegate.cpp b/templates/cpp-template-default/Classes/AppDelegate.cpp index 9e7d6a6d6823..0119494ae12e 100644 --- a/templates/cpp-template-default/Classes/AppDelegate.cpp +++ b/templates/cpp-template-default/Classes/AppDelegate.cpp @@ -3,17 +3,17 @@ Copyright (c) 2021 Bytedance Inc. https://adxe.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 @@ -29,23 +29,19 @@ #define USE_AUDIO_ENGINE 1 #if USE_AUDIO_ENGINE -#include "audio/include/AudioEngine.h" +# include "audio/include/AudioEngine.h" #endif USING_NS_CC; static cocos2d::Size designResolutionSize = cocos2d::Size(1280, 720); -static cocos2d::Size smallResolutionSize = cocos2d::Size(480, 320); +static cocos2d::Size smallResolutionSize = cocos2d::Size(480, 320); static cocos2d::Size mediumResolutionSize = cocos2d::Size(1024, 768); -static cocos2d::Size largeResolutionSize = cocos2d::Size(2048, 1536); +static cocos2d::Size largeResolutionSize = cocos2d::Size(2048, 1536); -AppDelegate::AppDelegate() -{ -} +AppDelegate::AppDelegate() {} -AppDelegate::~AppDelegate() -{ -} +AppDelegate::~AppDelegate() {} // if you want a different context, modify the value of glContextAttrs // it will affect all platforms @@ -57,20 +53,24 @@ void AppDelegate::initGLContextAttrs() GLView::setGLContextAttrs(glContextAttrs); } -// if you want to use the package manager to install more packages, +// if you want to use the package manager to install more packages, // don't modify or remove this function static int register_all_packages() { - return 0; //flag for packages manager + return 0; // flag for packages manager } -bool AppDelegate::applicationDidFinishLaunching() { +bool AppDelegate::applicationDidFinishLaunching() +{ // initialize director auto director = Director::getInstance(); - auto glview = director->getOpenGLView(); - if(!glview) { -#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) - glview = GLViewImpl::createWithRect("HelloCpp", cocos2d::Rect(0, 0, designResolutionSize.width, designResolutionSize.height)); + auto glview = director->getOpenGLView(); + if (!glview) + { +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || \ + (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) + glview = GLViewImpl::createWithRect( + "HelloCpp", cocos2d::Rect(0, 0, designResolutionSize.width, designResolutionSize.height)); #else glview = GLViewImpl::create("HelloCpp"); #endif @@ -84,22 +84,26 @@ bool AppDelegate::applicationDidFinishLaunching() { director->setAnimationInterval(1.0f / 60); // Set the design resolution - glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, ResolutionPolicy::NO_BORDER); + glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, + ResolutionPolicy::NO_BORDER); auto frameSize = glview->getFrameSize(); // if the frame's height is larger than the height of medium size. if (frameSize.height > mediumResolutionSize.height) - { - director->setContentScaleFactor(MIN(largeResolutionSize.height/designResolutionSize.height, largeResolutionSize.width/designResolutionSize.width)); + { + director->setContentScaleFactor(MIN(largeResolutionSize.height / designResolutionSize.height, + largeResolutionSize.width / designResolutionSize.width)); } // if the frame's height is larger than the height of small size. else if (frameSize.height > smallResolutionSize.height) - { - director->setContentScaleFactor(MIN(mediumResolutionSize.height/designResolutionSize.height, mediumResolutionSize.width/designResolutionSize.width)); + { + director->setContentScaleFactor(MIN(mediumResolutionSize.height / designResolutionSize.height, + mediumResolutionSize.width / designResolutionSize.width)); } // if the frame's height is smaller than the height of medium size. else - { - director->setContentScaleFactor(MIN(smallResolutionSize.height/designResolutionSize.height, smallResolutionSize.width/designResolutionSize.width)); + { + director->setContentScaleFactor(MIN(smallResolutionSize.height / designResolutionSize.height, + smallResolutionSize.width / designResolutionSize.width)); } register_all_packages(); @@ -114,7 +118,8 @@ bool AppDelegate::applicationDidFinishLaunching() { } // This function will be called when the app is inactive. Note, when receiving a phone call it is invoked. -void AppDelegate::applicationDidEnterBackground() { +void AppDelegate::applicationDidEnterBackground() +{ Director::getInstance()->stopAnimation(); #if USE_AUDIO_ENGINE @@ -123,7 +128,8 @@ void AppDelegate::applicationDidEnterBackground() { } // this function will be called when the app is active again -void AppDelegate::applicationWillEnterForeground() { +void AppDelegate::applicationWillEnterForeground() +{ Director::getInstance()->startAnimation(); #if USE_AUDIO_ENGINE diff --git a/templates/cpp-template-default/Classes/AppDelegate.h b/templates/cpp-template-default/Classes/AppDelegate.h index 41d860f5deef..0ce2aaaa5be1 100644 --- a/templates/cpp-template-default/Classes/AppDelegate.h +++ b/templates/cpp-template-default/Classes/AppDelegate.h @@ -3,17 +3,17 @@ Copyright (c) 2021 Bytedance Inc. https://adxe.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 @@ -23,8 +23,8 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef _APP_DELEGATE_H_ -#define _APP_DELEGATE_H_ +#ifndef _APP_DELEGATE_H_ +#define _APP_DELEGATE_H_ #include "cocos2d.h" @@ -33,7 +33,7 @@ Private inheritance here hides part of interface from Director. */ -class AppDelegate : private cocos2d::Application +class AppDelegate : private cocos2d::Application { public: AppDelegate(); @@ -61,5 +61,4 @@ class AppDelegate : private cocos2d::Application void applicationWillEnterForeground() override; }; -#endif // _APP_DELEGATE_H_ - +#endif // _APP_DELEGATE_H_ diff --git a/templates/cpp-template-default/Classes/HelloWorldScene.cpp b/templates/cpp-template-default/Classes/HelloWorldScene.cpp index 620e41e8664b..5ad976f9778e 100644 --- a/templates/cpp-template-default/Classes/HelloWorldScene.cpp +++ b/templates/cpp-template-default/Classes/HelloWorldScene.cpp @@ -48,8 +48,8 @@ bool HelloWorld::init() auto visibleSize = Director::getInstance()->getVisibleSize(); auto origin = Director::getInstance()->getVisibleOrigin(); - auto safeArea = Director::getInstance()->getSafeAreaRect(); - auto safeOrigin = safeArea.origin; + auto safeArea = Director::getInstance()->getSafeAreaRect(); + auto safeOrigin = safeArea.origin; ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program @@ -97,7 +97,7 @@ bool HelloWorld::init() } // add "HelloWorld" splash screen" - auto sprite = Sprite::create("HelloWorld.png"); + auto sprite = Sprite::create("HelloWorld.png"sv); if (sprite == nullptr) { problemLoading("'HelloWorld.png'"); diff --git a/templates/cpp-template-default/Classes/HelloWorldScene.h b/templates/cpp-template-default/Classes/HelloWorldScene.h index c77c79b593ab..894b4e0dd898 100644 --- a/templates/cpp-template-default/Classes/HelloWorldScene.h +++ b/templates/cpp-template-default/Classes/HelloWorldScene.h @@ -3,17 +3,17 @@ Copyright (c) 2021 Bytedance Inc. https://adxe.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 @@ -37,4 +37,4 @@ class HelloWorld : public cocos2d::Scene void menuCloseCallback(Ref* sender); }; -#endif // __HELLOWORLD_SCENE_H__ +#endif // __HELLOWORLD_SCENE_H__ diff --git a/templates/cpp-template-default/proj.android/app/jni/hellocpp/main.cpp b/templates/cpp-template-default/proj.android/app/jni/hellocpp/main.cpp index 6cab47cbb306..ccd4757e4c78 100644 --- a/templates/cpp-template-default/proj.android/app/jni/hellocpp/main.cpp +++ b/templates/cpp-template-default/proj.android/app/jni/hellocpp/main.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -29,14 +29,16 @@ #include "AppDelegate.h" -#define LOG_TAG "main" -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) +#define LOG_TAG "main" +#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) -namespace { +namespace +{ std::unique_ptr appDelegate; } -void cocos_android_app_init(JNIEnv* env) { +void cocos_android_app_init(JNIEnv* env) +{ LOGD("cocos_android_app_init"); appDelegate.reset(new AppDelegate()); } diff --git a/templates/cpp-template-default/proj.ios_mac/ios/AppController.h b/templates/cpp-template-default/proj.ios_mac/ios/AppController.h index f0e78b77634f..aeb65f50857b 100644 --- a/templates/cpp-template-default/proj.ios_mac/ios/AppController.h +++ b/templates/cpp-template-default/proj.ios_mac/ios/AppController.h @@ -2,19 +2,19 @@ Copyright (c) 2010-2013 cocos2d-x.org Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -29,10 +29,8 @@ @class RootViewController; @interface AppController : NSObject { - } @property(nonatomic, readonly) RootViewController* viewController; @end - diff --git a/templates/cpp-template-default/proj.ios_mac/ios/AppController.mm b/templates/cpp-template-default/proj.ios_mac/ios/AppController.mm index edcd92178a39..2dafa17d40e3 100644 --- a/templates/cpp-template-default/proj.ios_mac/ios/AppController.mm +++ b/templates/cpp-template-default/proj.ios_mac/ios/AppController.mm @@ -2,19 +2,19 @@ Copyright (c) 2010-2013 cocos2d-x.org Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -39,29 +39,29 @@ @implementation AppController // cocos2d application instance static AppDelegate s_sharedApplication; -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - - cocos2d::Application *app = cocos2d::Application::getInstance(); - +- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions +{ + + cocos2d::Application* app = cocos2d::Application::getInstance(); + // Initialize the GLView attributes app->initGLContextAttrs(); cocos2d::GLViewImpl::convertAttrs(); - + // Override point for customization after application launch. // Add the view controller's view to the window and display. - window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; + window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Use RootViewController to manage CCEAGLView - _viewController = [[RootViewController alloc]init]; + _viewController = [[RootViewController alloc] init]; _viewController.wantsFullScreenLayout = YES; - // Set RootViewController to window - if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) + if ([[UIDevice currentDevice].systemVersion floatValue] < 6.0) { // warning: addSubView doesn't work on iOS6 - [window addSubview: _viewController.view]; + [window addSubview:_viewController.view]; } else { @@ -72,82 +72,91 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( [window makeKeyAndVisible]; [[UIApplication sharedApplication] setStatusBarHidden:true]; - - //Launching the app with the arguments -NSAllowsDefaultLineBreakStrategy NO to force back to the old behavior. - if ( [[UIDevice currentDevice].systemVersion floatValue] >= 13.0f) + + // Launching the app with the arguments -NSAllowsDefaultLineBreakStrategy NO to force back to the old behavior. + if ([[UIDevice currentDevice].systemVersion floatValue] >= 13.0f) { [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"NSAllowsDefaultLineBreakStrategy"]; } - + // IMPORTANT: Setting the GLView should be done after creating the RootViewController - cocos2d::GLView *glview = cocos2d::GLViewImpl::createWithEAGLView((__bridge void *)_viewController.view); + cocos2d::GLView* glview = cocos2d::GLViewImpl::createWithEAGLView((__bridge void*)_viewController.view); cocos2d::Director::getInstance()->setOpenGLView(glview); - - //run the cocos2d-x game scene + + // run the cocos2d-x game scene app->run(); return YES; } - -- (void)applicationWillResignActive:(UIApplication *)application { +- (void)applicationWillResignActive:(UIApplication*)application +{ /* - Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. + Sent when the application is about to move from active to inactive state. This can occur for certain types of + temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and + it begins the transition to the background state. Use this method to pause ongoing tasks, disable timers, and + throttle down OpenGL ES frame rates. Games should use this method to pause the game. */ // We don't need to call this method any more. It will interrupt user defined game pause&resume logic /* cocos2d::Director::getInstance()->pause(); */ } -- (void)applicationDidBecomeActive:(UIApplication *)application { +- (void)applicationDidBecomeActive:(UIApplication*)application +{ /* - Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was + previously in the background, optionally refresh the user interface. */ // We don't need to call this method any more. It will interrupt user defined game pause&resume logic /* cocos2d::Director::getInstance()->resume(); */ } -- (void)applicationDidEnterBackground:(UIApplication *)application { +- (void)applicationDidEnterBackground:(UIApplication*)application +{ /* - Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. - If your application supports background execution, called instead of applicationWillTerminate: when the user quits. + Use this method to release shared resources, save user data, invalidate timers, and store enough application state + information to restore your application to its current state in case it is terminated later. If your application + supports background execution, called instead of applicationWillTerminate: when the user quits. */ cocos2d::Application::getInstance()->applicationDidEnterBackground(); } -- (void)applicationWillEnterForeground:(UIApplication *)application { +- (void)applicationWillEnterForeground:(UIApplication*)application +{ /* - Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background. + Called as part of transition from the background to the inactive state: here you can undo many of the changes made + on entering the background. */ cocos2d::Application::getInstance()->applicationWillEnterForeground(); } -- (void)applicationWillTerminate:(UIApplication *)application { +- (void)applicationWillTerminate:(UIApplication*)application +{ /* Called when the application is about to terminate. See also applicationDidEnterBackground:. */ } - #pragma mark - #pragma mark Memory management -- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { +- (void)applicationDidReceiveMemoryWarning:(UIApplication*)application +{ /* - Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. + Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) + later. */ } - #if __has_feature(objc_arc) #else -- (void)dealloc { +- (void)dealloc +{ [window release]; [_viewController release]; [super dealloc]; } #endif - @end diff --git a/templates/cpp-template-default/proj.ios_mac/ios/RootViewController.h b/templates/cpp-template-default/proj.ios_mac/ios/RootViewController.h index ed4046d6faaf..06c3b0556216 100644 --- a/templates/cpp-template-default/proj.ios_mac/ios/RootViewController.h +++ b/templates/cpp-template-default/proj.ios_mac/ios/RootViewController.h @@ -26,10 +26,8 @@ #import - @interface RootViewController : UIViewController { - } -- (BOOL) prefersStatusBarHidden; +- (BOOL)prefersStatusBarHidden; @end diff --git a/templates/cpp-template-default/proj.ios_mac/ios/RootViewController.mm b/templates/cpp-template-default/proj.ios_mac/ios/RootViewController.mm index a4c37af784ab..8eaf237db900 100644 --- a/templates/cpp-template-default/proj.ios_mac/ios/RootViewController.mm +++ b/templates/cpp-template-default/proj.ios_mac/ios/RootViewController.mm @@ -28,11 +28,11 @@ of this software and associated documentation files (the "Software"), to deal #import "cocos2d.h" #import "platform/ios/CCEAGLView-ios.h" - @implementation RootViewController /* - // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. + // The designated initializer. Override if you create the controller programmatically and want to perform +customization that is not appropriate for viewDidLoad. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { // Custom initialization @@ -42,81 +42,89 @@ - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil */ // Implement loadView to create a view hierarchy programmatically, without using a nib. -- (void)loadView { +- (void)loadView +{ // Initialize the CCEAGLView - CCEAGLView *eaglView = [CCEAGLView viewWithFrame: [UIScreen mainScreen].bounds - pixelFormat: (__bridge NSString *)cocos2d::GLViewImpl::_pixelFormat - depthFormat: cocos2d::GLViewImpl::_depthFormat - preserveBackbuffer: NO - sharegroup: nil - multiSampling: cocos2d::GLViewImpl::_multisamplingCount > 0 ? YES : NO - numberOfSamples: cocos2d::GLViewImpl::_multisamplingCount ]; - + CCEAGLView* eaglView = [CCEAGLView viewWithFrame:[UIScreen mainScreen].bounds + pixelFormat:(__bridge NSString*)cocos2d::GLViewImpl::_pixelFormat + depthFormat:cocos2d::GLViewImpl::_depthFormat + preserveBackbuffer:NO + sharegroup:nil + multiSampling:cocos2d::GLViewImpl::_multisamplingCount > 0 ? YES : NO + numberOfSamples:cocos2d::GLViewImpl::_multisamplingCount]; + // Enable or disable multiple touches [eaglView setMultipleTouchEnabled:NO]; - + // Set EAGLView as view of RootViewController self.view = eaglView; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. -- (void)viewDidLoad { +- (void)viewDidLoad +{ [super viewDidLoad]; } -- (void)viewWillAppear:(BOOL)animated { +- (void)viewWillAppear:(BOOL)animated +{ [super viewWillAppear:animated]; } -- (void)viewDidDisappear:(BOOL)animated { +- (void)viewDidDisappear:(BOOL)animated +{ [super viewDidDisappear:animated]; } - // For ios6, use supportedInterfaceOrientations & shouldAutorotate instead #ifdef __IPHONE_6_0 -- (NSUInteger) supportedInterfaceOrientations{ +- (NSUInteger)supportedInterfaceOrientations +{ return UIInterfaceOrientationMaskAllButUpsideDown; } #endif -- (BOOL) shouldAutorotate { +- (BOOL)shouldAutorotate +{ return YES; } -- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { +- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation +{ [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; auto glview = cocos2d::Director::getInstance()->getOpenGLView(); if (glview) { - CCEAGLView *eaglview = (__bridge CCEAGLView *)glview->getEAGLView(); + CCEAGLView* eaglview = (__bridge CCEAGLView*)glview->getEAGLView(); if (eaglview) { CGSize s = CGSizeMake([eaglview getWidth], [eaglview getHeight]); - cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height); + cocos2d::Application::getInstance()->applicationScreenSizeChanged((int)s.width, (int)s.height); } } } -//fix not hide status on ios7 -- (BOOL)prefersStatusBarHidden { +// fix not hide status on ios7 +- (BOOL)prefersStatusBarHidden +{ return YES; } // Controls the application's preferred home indicator auto-hiding when this view controller is shown. -- (BOOL)prefersHomeIndicatorAutoHidden { +- (BOOL)prefersHomeIndicatorAutoHidden +{ return YES; } -- (void)didReceiveMemoryWarning { +- (void)didReceiveMemoryWarning +{ // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } - @end diff --git a/templates/cpp-template-default/proj.ios_mac/mac/main.cpp b/templates/cpp-template-default/proj.ios_mac/mac/main.cpp index ed8ee7c15c33..44045f8feb1d 100644 --- a/templates/cpp-template-default/proj.ios_mac/mac/main.cpp +++ b/templates/cpp-template-default/proj.ios_mac/mac/main.cpp @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2010 cocos2d-x.org Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -28,7 +28,7 @@ USING_NS_CC; -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { AppDelegate app; return Application::getInstance()->run(); diff --git a/templates/cpp-template-default/proj.linux/main.cpp b/templates/cpp-template-default/proj.linux/main.cpp index 2bd3032f78c4..3cbdb2bc35a6 100644 --- a/templates/cpp-template-default/proj.linux/main.cpp +++ b/templates/cpp-template-default/proj.linux/main.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -31,7 +31,7 @@ USING_NS_CC; -int main(int argc, char **argv) +int main(int argc, char** argv) { // create the application instance AppDelegate app; diff --git a/templates/cpp-template-default/proj.win32/main.cpp b/templates/cpp-template-default/proj.win32/main.cpp index c3c5dc6fd49c..636fa57f07f2 100644 --- a/templates/cpp-template-default/proj.win32/main.cpp +++ b/templates/cpp-template-default/proj.win32/main.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -28,10 +28,7 @@ USING_NS_CC; -int WINAPI _tWinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) +int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); diff --git a/templates/cpp-template-default/proj.win32/main.h b/templates/cpp-template-default/proj.win32/main.h index 13b6f36fd230..64d684e652a4 100644 --- a/templates/cpp-template-default/proj.win32/main.h +++ b/templates/cpp-template-default/proj.win32/main.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -25,7 +25,7 @@ #ifndef __MAIN_H__ #define __MAIN_H__ -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include @@ -34,4 +34,4 @@ // C RunTime Header Files #include "platform/CCStdC.h" -#endif // __MAIN_H__ +#endif // __MAIN_H__ diff --git a/templates/cpp-template-default/proj.win32/resource.h b/templates/cpp-template-default/proj.win32/resource.h index 6f4e11f03d52..da3599c69cf8 100644 --- a/templates/cpp-template-default/proj.win32/resource.h +++ b/templates/cpp-template-default/proj.win32/resource.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,18 +27,18 @@ // Used by game.RC // -#define IDS_PROJNAME 100 -#define IDR_TESTJS 100 +#define IDS_PROJNAME 100 +#define IDR_TESTJS 100 -#define ID_FILE_NEW_WINDOW 32771 +#define ID_FILE_NEW_WINDOW 32771 // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 201 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 32775 -#endif +# ifndef APSTUDIO_READONLY_SYMBOLS +# define _APS_NEXT_RESOURCE_VALUE 201 +# define _APS_NEXT_CONTROL_VALUE 1000 +# define _APS_NEXT_SYMED_VALUE 101 +# define _APS_NEXT_COMMAND_VALUE 32775 +# endif #endif diff --git a/templates/lua-template-default/CMakeLists.txt b/templates/lua-template-default/CMakeLists.txt index c2f896ee0073..b5559c79d40c 100644 --- a/templates/lua-template-default/CMakeLists.txt +++ b/templates/lua-template-default/CMakeLists.txt @@ -132,17 +132,16 @@ set(APP_SRC ${GAME_HEADER} ${GAME_SOURCE}) # mark app complie info and libs info if(NOT ANDROID) add_executable(${APP_NAME} ${APP_SRC}) + target_link_libraries(${APP_NAME} ${ADXE_LUA_LIB}) else() add_library(${APP_NAME} SHARED ${APP_SRC}) - add_subdirectory(${ADXE_ROOT_PATH}/cocos/platform/android ${ENGINE_BINARY_PATH}/cocos/platform) - target_link_libraries(${APP_NAME} -Wl,--whole-archive cpp_android_spec -Wl,--no-whole-archive) add_subdirectory(${ADXE_ROOT_PATH}/extensions/scripting/lua-bindings/proj.android ${ENGINE_BINARY_PATH}/cocos/lua-android) target_link_libraries(${APP_NAME} -Wl,--whole-archive lua_android_spec -Wl,--no-whole-archive) - + # whole archive ${ADXE_LUA_LIB} to make sure JNI_Onload can be invoke from java + target_link_libraries(${APP_NAME} -Wl,--whole-archive ${ADXE_LUA_LIB} -Wl,--whole-archive) config_android_shared_libs("org.cocos2dx.lib" "${CMAKE_CURRENT_SOURCE_DIR}/frameworks/runtime-src/proj.android/app/src") endif() -target_link_libraries(${APP_NAME} ${ADXE_LUA_LIB}) target_include_directories(${APP_NAME} PRIVATE ${RUNTIME_SRC_ROOT}/Classes) # mark app resources, resource will be copy auto after mark diff --git a/templates/lua-template-default/frameworks/runtime-src/Classes/AppDelegate.cpp b/templates/lua-template-default/frameworks/runtime-src/Classes/AppDelegate.cpp index b0542eff320f..abbab833fd96 100644 --- a/templates/lua-template-default/frameworks/runtime-src/Classes/AppDelegate.cpp +++ b/templates/lua-template-default/frameworks/runtime-src/Classes/AppDelegate.cpp @@ -3,17 +3,17 @@ Copyright (c) 2021 Bytedance Inc. https://adxe.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 @@ -31,35 +31,31 @@ #define USE_AUDIO_ENGINE 1 #if USE_AUDIO_ENGINE -#include "audio/include/AudioEngine.h" +# include "audio/include/AudioEngine.h" #endif USING_NS_CC; using namespace std; -AppDelegate::AppDelegate() -{ -} +AppDelegate::AppDelegate() {} -AppDelegate::~AppDelegate() -{ -} +AppDelegate::~AppDelegate() {} // if you want a different context, modify the value of glContextAttrs // it will affect all platforms void AppDelegate::initGLContextAttrs() { // set OpenGL context attributes: red,green,blue,alpha,depth,stencil,multisamplesCount - GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8, 0 }; + GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8, 0}; GLView::setGLContextAttrs(glContextAttrs); } -// if you want to use the package manager to install more packages, +// if you want to use the package manager to install more packages, // don't modify or remove this function static int register_all_packages() { - return 0; //flag for packages manager + return 0; // flag for packages manager } bool AppDelegate::applicationDidFinishLaunching() @@ -76,12 +72,12 @@ bool AppDelegate::applicationDidFinishLaunching() register_all_packages(); LuaStack* stack = engine->getLuaStack(); - - //register custom function - //LuaStack* stack = engine->getLuaStack(); - //register_custom_function(stack->getLuaState()); - - stack->addSearchPath("src"); + + // register custom function + // LuaStack* stack = engine->getLuaStack(); + // register_custom_function(stack->getLuaState()); + + stack->addSearchPath("src"); FileUtils::getInstance()->addSearchPath("res"); if (engine->executeString("require 'main'")) { diff --git a/templates/lua-template-default/frameworks/runtime-src/Classes/AppDelegate.h b/templates/lua-template-default/frameworks/runtime-src/Classes/AppDelegate.h index c5a12ae3d6d1..53d04ceced8c 100644 --- a/templates/lua-template-default/frameworks/runtime-src/Classes/AppDelegate.h +++ b/templates/lua-template-default/frameworks/runtime-src/Classes/AppDelegate.h @@ -3,17 +3,17 @@ Copyright (c) 2021 Bytedance Inc. https://adxe.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 @@ -32,7 +32,7 @@ Private inheritance here hides part of interface from Director. */ -class AppDelegate : private cocos2d::Application +class AppDelegate : private cocos2d::Application { public: AppDelegate(); diff --git a/templates/lua-template-default/frameworks/runtime-src/proj.android/app/jni/hellolua/main.cpp b/templates/lua-template-default/frameworks/runtime-src/proj.android/app/jni/hellolua/main.cpp index 6cab47cbb306..ccd4757e4c78 100644 --- a/templates/lua-template-default/frameworks/runtime-src/proj.android/app/jni/hellolua/main.cpp +++ b/templates/lua-template-default/frameworks/runtime-src/proj.android/app/jni/hellolua/main.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -29,14 +29,16 @@ #include "AppDelegate.h" -#define LOG_TAG "main" -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) +#define LOG_TAG "main" +#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) -namespace { +namespace +{ std::unique_ptr appDelegate; } -void cocos_android_app_init(JNIEnv* env) { +void cocos_android_app_init(JNIEnv* env) +{ LOGD("cocos_android_app_init"); appDelegate.reset(new AppDelegate()); } diff --git a/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.h b/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.h index f0e78b77634f..aeb65f50857b 100644 --- a/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.h +++ b/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.h @@ -2,19 +2,19 @@ Copyright (c) 2010-2013 cocos2d-x.org Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -29,10 +29,8 @@ @class RootViewController; @interface AppController : NSObject { - } @property(nonatomic, readonly) RootViewController* viewController; @end - diff --git a/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm b/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm index 8116adeba98d..2dafa17d40e3 100644 --- a/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm +++ b/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm @@ -2,19 +2,19 @@ Copyright (c) 2010-2013 cocos2d-x.org Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -39,29 +39,29 @@ @implementation AppController // cocos2d application instance static AppDelegate s_sharedApplication; -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - - cocos2d::Application *app = cocos2d::Application::getInstance(); - +- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions +{ + + cocos2d::Application* app = cocos2d::Application::getInstance(); + // Initialize the GLView attributes app->initGLContextAttrs(); cocos2d::GLViewImpl::convertAttrs(); - + // Override point for customization after application launch. // Add the view controller's view to the window and display. - window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; + window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Use RootViewController to manage CCEAGLView - _viewController = [[RootViewController alloc]init]; + _viewController = [[RootViewController alloc] init]; _viewController.wantsFullScreenLayout = YES; - // Set RootViewController to window - if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) + if ([[UIDevice currentDevice].systemVersion floatValue] < 6.0) { // warning: addSubView doesn't work on iOS6 - [window addSubview: _viewController.view]; + [window addSubview:_viewController.view]; } else { @@ -73,81 +73,90 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( [[UIApplication sharedApplication] setStatusBarHidden:true]; - //Launching the app with the arguments -NSAllowsDefaultLineBreakStrategy NO to force back to the old behavior. - if ( [[UIDevice currentDevice].systemVersion floatValue] >= 13.0f) + // Launching the app with the arguments -NSAllowsDefaultLineBreakStrategy NO to force back to the old behavior. + if ([[UIDevice currentDevice].systemVersion floatValue] >= 13.0f) { [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"NSAllowsDefaultLineBreakStrategy"]; } - + // IMPORTANT: Setting the GLView should be done after creating the RootViewController - cocos2d::GLView *glview = cocos2d::GLViewImpl::createWithEAGLView((__bridge void *)_viewController.view); + cocos2d::GLView* glview = cocos2d::GLViewImpl::createWithEAGLView((__bridge void*)_viewController.view); cocos2d::Director::getInstance()->setOpenGLView(glview); - - //run the cocos2d-x game scene + + // run the cocos2d-x game scene app->run(); return YES; } - -- (void)applicationWillResignActive:(UIApplication *)application { +- (void)applicationWillResignActive:(UIApplication*)application +{ /* - Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. + Sent when the application is about to move from active to inactive state. This can occur for certain types of + temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and + it begins the transition to the background state. Use this method to pause ongoing tasks, disable timers, and + throttle down OpenGL ES frame rates. Games should use this method to pause the game. */ // We don't need to call this method any more. It will interrupt user defined game pause&resume logic /* cocos2d::Director::getInstance()->pause(); */ } -- (void)applicationDidBecomeActive:(UIApplication *)application { +- (void)applicationDidBecomeActive:(UIApplication*)application +{ /* - Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was + previously in the background, optionally refresh the user interface. */ // We don't need to call this method any more. It will interrupt user defined game pause&resume logic /* cocos2d::Director::getInstance()->resume(); */ } -- (void)applicationDidEnterBackground:(UIApplication *)application { +- (void)applicationDidEnterBackground:(UIApplication*)application +{ /* - Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. - If your application supports background execution, called instead of applicationWillTerminate: when the user quits. + Use this method to release shared resources, save user data, invalidate timers, and store enough application state + information to restore your application to its current state in case it is terminated later. If your application + supports background execution, called instead of applicationWillTerminate: when the user quits. */ cocos2d::Application::getInstance()->applicationDidEnterBackground(); } -- (void)applicationWillEnterForeground:(UIApplication *)application { +- (void)applicationWillEnterForeground:(UIApplication*)application +{ /* - Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background. + Called as part of transition from the background to the inactive state: here you can undo many of the changes made + on entering the background. */ cocos2d::Application::getInstance()->applicationWillEnterForeground(); } -- (void)applicationWillTerminate:(UIApplication *)application { +- (void)applicationWillTerminate:(UIApplication*)application +{ /* Called when the application is about to terminate. See also applicationDidEnterBackground:. */ } - #pragma mark - #pragma mark Memory management -- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { +- (void)applicationDidReceiveMemoryWarning:(UIApplication*)application +{ /* - Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. + Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) + later. */ } - #if __has_feature(objc_arc) #else -- (void)dealloc { +- (void)dealloc +{ [window release]; [_viewController release]; [super dealloc]; } #endif - @end diff --git a/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.h b/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.h index ed4046d6faaf..06c3b0556216 100644 --- a/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.h +++ b/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.h @@ -26,10 +26,8 @@ #import - @interface RootViewController : UIViewController { - } -- (BOOL) prefersStatusBarHidden; +- (BOOL)prefersStatusBarHidden; @end diff --git a/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.mm b/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.mm index 37144e420fce..1210e485ccdc 100644 --- a/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.mm +++ b/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.mm @@ -28,11 +28,11 @@ of this software and associated documentation files (the "Software"), to deal #import "cocos2d.h" #import "platform/ios/CCEAGLView-ios.h" - @implementation RootViewController /* - // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. + // The designated initializer. Override if you create the controller programmatically and want to perform +customization that is not appropriate for viewDidLoad. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { // Custom initialization @@ -42,81 +42,89 @@ - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil */ // Implement loadView to create a view hierarchy programmatically, without using a nib. -- (void)loadView { +- (void)loadView +{ // Initialize the CCEAGLView - CCEAGLView *eaglView = [CCEAGLView viewWithFrame: [UIScreen mainScreen].bounds - pixelFormat: (__bridge NSString *)cocos2d::GLViewImpl::_pixelFormat - depthFormat: cocos2d::GLViewImpl::_depthFormat - preserveBackbuffer: NO - sharegroup: nil - multiSampling: NO - numberOfSamples: 0 ]; - + CCEAGLView* eaglView = [CCEAGLView viewWithFrame:[UIScreen mainScreen].bounds + pixelFormat:(__bridge NSString*)cocos2d::GLViewImpl::_pixelFormat + depthFormat:cocos2d::GLViewImpl::_depthFormat + preserveBackbuffer:NO + sharegroup:nil + multiSampling:NO + numberOfSamples:0]; + // Enable or disable multiple touches [eaglView setMultipleTouchEnabled:NO]; - + // Set EAGLView as view of RootViewController self.view = eaglView; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. -- (void)viewDidLoad { +- (void)viewDidLoad +{ [super viewDidLoad]; } -- (void)viewWillAppear:(BOOL)animated { +- (void)viewWillAppear:(BOOL)animated +{ [super viewWillAppear:animated]; } -- (void)viewDidDisappear:(BOOL)animated { +- (void)viewDidDisappear:(BOOL)animated +{ [super viewDidDisappear:animated]; } - // For ios6, use supportedInterfaceOrientations & shouldAutorotate instead #ifdef __IPHONE_6_0 -- (NSUInteger) supportedInterfaceOrientations{ +- (NSUInteger)supportedInterfaceOrientations +{ return UIInterfaceOrientationMaskAllButUpsideDown; } #endif -- (BOOL) shouldAutorotate { +- (BOOL)shouldAutorotate +{ return YES; } -- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { +- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation +{ [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; auto glview = cocos2d::Director::getInstance()->getOpenGLView(); if (glview) { - CCEAGLView *eaglview = (__bridge CCEAGLView *)glview->getEAGLView(); + CCEAGLView* eaglview = (__bridge CCEAGLView*)glview->getEAGLView(); if (eaglview) { CGSize s = CGSizeMake([eaglview getWidth], [eaglview getHeight]); - cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height); + cocos2d::Application::getInstance()->applicationScreenSizeChanged((int)s.width, (int)s.height); } } } -//fix not hide status on ios7 -- (BOOL)prefersStatusBarHidden { +// fix not hide status on ios7 +- (BOOL)prefersStatusBarHidden +{ return YES; } // Controls the application's preferred home indicator auto-hiding when this view controller is shown. -- (BOOL)prefersHomeIndicatorAutoHidden { +- (BOOL)prefersHomeIndicatorAutoHidden +{ return YES; } -- (void)didReceiveMemoryWarning { +- (void)didReceiveMemoryWarning +{ // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } - @end diff --git a/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/mac/main.cpp b/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/mac/main.cpp index cd6c3e8cdc52..371a2b4fcc85 100644 --- a/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/mac/main.cpp +++ b/templates/lua-template-default/frameworks/runtime-src/proj.ios_mac/mac/main.cpp @@ -4,9 +4,8 @@ USING_NS_CC; -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { AppDelegate app; return Application::getInstance()->run(); } - diff --git a/templates/lua-template-default/frameworks/runtime-src/proj.linux/main.cpp b/templates/lua-template-default/frameworks/runtime-src/proj.linux/main.cpp index 042c94fef689..c03ce74184e9 100644 --- a/templates/lua-template-default/frameworks/runtime-src/proj.linux/main.cpp +++ b/templates/lua-template-default/frameworks/runtime-src/proj.linux/main.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -32,7 +32,7 @@ USING_NS_CC; -int main(int argc, char **argv) +int main(int argc, char** argv) { // create the application instance AppDelegate app; diff --git a/templates/lua-template-default/frameworks/runtime-src/proj.win32/main.cpp b/templates/lua-template-default/frameworks/runtime-src/proj.win32/main.cpp index 88ab9a2856fb..0aa2a83d78aa 100644 --- a/templates/lua-template-default/frameworks/runtime-src/proj.win32/main.cpp +++ b/templates/lua-template-default/frameworks/runtime-src/proj.win32/main.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -30,10 +30,7 @@ USING_NS_CC; // uncomment below line, open debug console #define USE_WIN32_CONSOLE -int WINAPI _tWinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) +int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); diff --git a/templates/lua-template-default/frameworks/runtime-src/proj.win32/main.h b/templates/lua-template-default/frameworks/runtime-src/proj.win32/main.h index 7943814d121b..d262f80bb84e 100644 --- a/templates/lua-template-default/frameworks/runtime-src/proj.win32/main.h +++ b/templates/lua-template-default/frameworks/runtime-src/proj.win32/main.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -24,7 +24,7 @@ #pragma once -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include @@ -32,4 +32,3 @@ // C RunTime Header Files #include "platform/CCStdC.h" - diff --git a/tests/cpp-tests/CMakeLists.txt b/tests/cpp-tests/CMakeLists.txt index 3e73a2fa571b..f8ed4d47810d 100644 --- a/tests/cpp-tests/CMakeLists.txt +++ b/tests/cpp-tests/CMakeLists.txt @@ -524,16 +524,14 @@ set(all_code_files if(NOT ANDROID) add_executable(${APP_NAME} ${all_code_files}) + target_link_libraries(${APP_NAME} ${ADXE_CORE_LIB}) else() add_library(${APP_NAME} SHARED ${all_code_files}) - add_subdirectory(${ADXE_ROOT_PATH}/cocos/platform/android ${ENGINE_BINARY_PATH}/cocos/platform) - target_link_libraries(${APP_NAME} -Wl,--whole-archive cpp_android_spec -Wl,--no-whole-archive) - + # whole archive ${ADXE_LUA_LIB} to make sure JNI_Onload can be invoke from java + target_link_libraries(${APP_NAME} -Wl,--whole-archive ${ADXE_CORE_LIB} -Wl,--no-whole-archive) config_android_shared_libs("org.cocos2dx.lib" "${CMAKE_CURRENT_SOURCE_DIR}/proj.android/app/src") endif() -target_link_libraries(${APP_NAME} ${ADXE_CORE_LIB}) - target_include_directories(${APP_NAME} PRIVATE Classes ) diff --git a/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.cpp b/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.cpp index e7a86cd63aa5..d4be38fbeec0 100644 --- a/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.cpp +++ b/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -28,12 +28,12 @@ USING_NS_CC; -enum +enum { kTagNode, kTagGrossini, kTagSequence, -}; +}; ActionManagerTests::ActionManagerTests() { @@ -53,13 +53,9 @@ ActionManagerTests::ActionManagerTests() // //------------------------------------------------------------------ -ActionManagerTest::ActionManagerTest() -{ -} +ActionManagerTest::ActionManagerTest() {} -ActionManagerTest::~ActionManagerTest() -{ -} +ActionManagerTest::~ActionManagerTest() {} std::string ActionManagerTest::title() const { @@ -81,30 +77,23 @@ void CrashTest::onEnter() ActionManagerTest::onEnter(); auto child = Sprite::create(s_pathGrossini); - child->setPosition( VisibleRect::center() ); + child->setPosition(VisibleRect::center()); addChild(child, 1, kTagGrossini); - //Sum of all action's duration is 1.5 second. + // Sum of all action's duration is 1.5 second. child->runAction(RotateBy::create(1.5f, 90)); - child->runAction(Sequence::create( - DelayTime::create(1.4f), - FadeOut::create(1.1f), - nullptr) - ); - - //After 1.5 second, self will be removed. - child->runAction(Sequence::create( - DelayTime::create(1.4f), - CallFunc::create( CC_CALLBACK_0(CrashTest::removeThis,this)), - nullptr) - ); + child->runAction(Sequence::create(DelayTime::create(1.4f), FadeOut::create(1.1f), nullptr)); + + // After 1.5 second, self will be removed. + child->runAction(Sequence::create(DelayTime::create(1.4f), + CallFunc::create(CC_CALLBACK_0(CrashTest::removeThis, this)), nullptr)); } void CrashTest::removeThis() { auto child = getChildByTag(kTagGrossini); child->removeChild(child, true); - + getTestSuite()->enterNextTest(); } @@ -126,22 +115,19 @@ void LogicTest::onEnter() addChild(grossini, 0, 2); grossini->setPosition(VisibleRect::center()); - grossini->runAction( Sequence::create( - MoveBy::create(1, Vec2(150.0f,0.0f)), - CallFuncN::create(CC_CALLBACK_1(LogicTest::bugMe,this)), - nullptr) - ); + grossini->runAction(Sequence::create(MoveBy::create(1, Vec2(150.0f, 0.0f)), + CallFuncN::create(CC_CALLBACK_1(LogicTest::bugMe, this)), nullptr)); } void LogicTest::bugMe(Node* node) { - node->stopAllActions(); //After this stop next action not working, if remove this stop everything is working + node->stopAllActions(); // After this stop next action not working, if remove this stop everything is working node->runAction(ScaleTo::create(2, 2)); } std::string LogicTest::subtitle() const { - return "Logic test"; + return "Logic test"; } //------------------------------------------------------------------ @@ -157,32 +143,30 @@ void PauseTest::onEnter() // otherwise the paused action will be resumed at 'onEnter' time // ActionManagerTest::onEnter(); - auto l = Label::createWithTTF("After 5 seconds grossini should move", "fonts/Thonburi.ttf", 16.0f); addChild(l); - l->setPosition(VisibleRect::center().x, VisibleRect::top().y-75); - - + l->setPosition(VisibleRect::center().x, VisibleRect::top().y - 75); + // // Also, this test MUST be done, after [super onEnter] // auto grossini = Sprite::create(s_pathGrossini); addChild(grossini, 0, kTagGrossini); - grossini->setPosition(VisibleRect::center() ); - - auto action = MoveBy::create(1, Vec2(150.0f,0.0f)); + grossini->setPosition(VisibleRect::center()); + + auto action = MoveBy::create(1, Vec2(150.0f, 0.0f)); auto director = Director::getInstance(); director->getActionManager()->addAction(action, grossini, true); - schedule( CC_SCHEDULE_SELECTOR(PauseTest::unpause), 3); + schedule(CC_SCHEDULE_SELECTOR(PauseTest::unpause), 3); } void PauseTest::unpause(float dt) { - unschedule( CC_SCHEDULE_SELECTOR(PauseTest::unpause) ); - auto node = getChildByTag( kTagGrossini ); + unschedule(CC_SCHEDULE_SELECTOR(PauseTest::unpause)); + auto node = getChildByTag(kTagGrossini); auto director = Director::getInstance(); director->getActionManager()->resumeTarget(node); } @@ -205,13 +189,13 @@ void StopActionTest::onEnter() addChild(l); l->setPosition(VisibleRect::center().x, VisibleRect::top().y - 75); - auto pMove = MoveBy::create(2, Vec2(200.0f, 0.0f)); - auto pCallback = CallFunc::create(CC_CALLBACK_0(StopActionTest::stopAction,this)); + auto pMove = MoveBy::create(2, Vec2(200.0f, 0.0f)); + auto pCallback = CallFunc::create(CC_CALLBACK_0(StopActionTest::stopAction, this)); auto pSequence = Sequence::create(pMove, pCallback, nullptr); pSequence->setTag(kTagSequence); auto pChild = Sprite::create(s_pathGrossini); - pChild->setPosition( VisibleRect::center() ); + pChild->setPosition(VisibleRect::center()); addChild(pChild, 1, kTagGrossini); pChild->runAction(pSequence); @@ -236,29 +220,30 @@ std::string StopActionTest::subtitle() const void StopAllActionsTest::onEnter() { ActionManagerTest::onEnter(); - - auto l = Label::createWithTTF("Should stop scale & move after 4 seconds but keep rotate", "fonts/Thonburi.ttf", 16.0f); + + auto l = + Label::createWithTTF("Should stop scale & move after 4 seconds but keep rotate", "fonts/Thonburi.ttf", 16.0f); addChild(l); - l->setPosition( Vec2(VisibleRect::center().x, VisibleRect::top().y - 75) ); - - auto pMove1 = MoveBy::create(2, Vec2(200.0f, 0.0f)); - auto pMove2 = MoveBy::create(2, Vec2(-200.0f, 0.0f)); + l->setPosition(Vec2(VisibleRect::center().x, VisibleRect::top().y - 75)); + + auto pMove1 = MoveBy::create(2, Vec2(200.0f, 0.0f)); + auto pMove2 = MoveBy::create(2, Vec2(-200.0f, 0.0f)); auto pSequenceMove = Sequence::createWithTwoActions(pMove1, pMove2); - auto pRepeatMove = RepeatForever::create(pSequenceMove); + auto pRepeatMove = RepeatForever::create(pSequenceMove); pRepeatMove->setTag(kTagSequence); - - auto pScale1 = ScaleBy::create(2, 1.5f); - auto pScale2 = ScaleBy::create(2, 1.0f/1.5f); + + auto pScale1 = ScaleBy::create(2, 1.5f); + auto pScale2 = ScaleBy::create(2, 1.0f / 1.5f); auto pSequenceScale = Sequence::createWithTwoActions(pScale1, pScale2); - auto pRepeatScale = RepeatForever::create(pSequenceScale); + auto pRepeatScale = RepeatForever::create(pSequenceScale); pRepeatScale->setTag(kTagSequence); - - auto pRotate = RotateBy::create(2, 360); + + auto pRotate = RotateBy::create(2, 360); auto pRepeatRotate = RepeatForever::create(pRotate); - + auto pChild = Sprite::create(s_pathGrossini); - pChild->setPosition( VisibleRect::center() ); - + pChild->setPosition(VisibleRect::center()); + addChild(pChild, 1, kTagGrossini); pChild->runAction(pRepeatMove); pChild->runAction(pRepeatScale); @@ -277,7 +262,6 @@ std::string StopAllActionsTest::subtitle() const return "Stop All Action Test"; } - //------------------------------------------------------------------ // // ResumeTest @@ -314,7 +298,7 @@ void ResumeTest::resumeGrossini(float time) this->unschedule(CC_SCHEDULE_SELECTOR(ResumeTest::resumeGrossini)); auto pGrossini = getChildByTag(kTagGrossini); - auto director = Director::getInstance(); + auto director = Director::getInstance(); director->getActionManager()->resumeTarget(pGrossini); } @@ -327,28 +311,29 @@ void StopActionsByFlagsTest::onEnter() { ActionManagerTest::onEnter(); - auto l = Label::createWithTTF("Should stop scale & move after 4 seconds but keep rotate", "fonts/Thonburi.ttf", 16.0f); + auto l = + Label::createWithTTF("Should stop scale & move after 4 seconds but keep rotate", "fonts/Thonburi.ttf", 16.0f); addChild(l); - l->setPosition( Vec2(VisibleRect::center().x, VisibleRect::top().y - 75) ); + l->setPosition(Vec2(VisibleRect::center().x, VisibleRect::top().y - 75)); - auto pMove1 = MoveBy::create(2, Vec2(200.0f, 0.0f)); - auto pMove2 = MoveBy::create(2, Vec2(-200.0f, 0.0f)); + auto pMove1 = MoveBy::create(2, Vec2(200.0f, 0.0f)); + auto pMove2 = MoveBy::create(2, Vec2(-200.0f, 0.0f)); auto pSequenceMove = Sequence::createWithTwoActions(pMove1, pMove2); - auto pRepeatMove = RepeatForever::create(pSequenceMove); + auto pRepeatMove = RepeatForever::create(pSequenceMove); pRepeatMove->setFlags(kMoveFlag | kRepeatForeverFlag); - auto pScale1 = ScaleBy::create(2, 1.5f); - auto pScale2 = ScaleBy::create(2, 1.0f/1.5f); + auto pScale1 = ScaleBy::create(2, 1.5f); + auto pScale2 = ScaleBy::create(2, 1.0f / 1.5f); auto pSequenceScale = Sequence::createWithTwoActions(pScale1, pScale2); - auto pRepeatScale = RepeatForever::create(pSequenceScale); + auto pRepeatScale = RepeatForever::create(pSequenceScale); pRepeatScale->setFlags(kScaleFlag | kRepeatForeverFlag); - auto pRotate = RotateBy::create(2, 360); + auto pRotate = RotateBy::create(2, 360); auto pRepeatRotate = RepeatForever::create(pRotate); pRepeatRotate->setFlags(kRotateFlag | kRepeatForeverFlag); auto pChild = Sprite::create(s_pathGrossini); - pChild->setPosition( VisibleRect::center() ); + pChild->setPosition(VisibleRect::center()); addChild(pChild, 1, kTagGrossini); pChild->runAction(pRepeatMove); @@ -373,17 +358,11 @@ std::string StopActionsByFlagsTest::subtitle() const // Issue14050Test // //------------------------------------------------------------------ -class SpriteIssue14050: public Sprite +class SpriteIssue14050 : public Sprite { public: - SpriteIssue14050() - { - log("SpriteIssue14050::constructor"); - } - virtual ~SpriteIssue14050() - { - log("SpriteIssue14050::destructor"); - } + SpriteIssue14050() { log("SpriteIssue14050::constructor"); } + virtual ~SpriteIssue14050() { log("SpriteIssue14050::destructor"); } }; void Issue14050Test::onEnter() diff --git a/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.h b/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.h index eb7f7528c19b..d4fd6b9a6f53 100644 --- a/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.h +++ b/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,7 +34,7 @@ class ActionManagerTest : public TestCase protected: cocos2d::TextureAtlas* _atlas; - std::string _title; + std::string _title; public: ActionManagerTest(); @@ -112,11 +112,13 @@ class StopActionsByFlagsTest : public ActionManagerTest virtual std::string subtitle() const override; virtual void onEnter() override; void stopAction(float time); + protected: - const unsigned int kMoveFlag = 0x01; - const unsigned int kScaleFlag = 0x02; - const unsigned int kRotateFlag = 0x04; - const unsigned int kRepeatForeverFlag = 0x08; // You don't need this for the test, but it's for demonstration how to activate several flags on an action. + const unsigned int kMoveFlag = 0x01; + const unsigned int kScaleFlag = 0x02; + const unsigned int kRotateFlag = 0x04; + const unsigned int kRepeatForeverFlag = 0x08; // You don't need this for the test, but it's for demonstration how + // to activate several flags on an action. }; class Issue14050Test : public ActionManagerTest @@ -126,6 +128,7 @@ class Issue14050Test : public ActionManagerTest virtual std::string subtitle() const override; virtual void onEnter() override; + protected: }; diff --git a/tests/cpp-tests/Classes/ActionsEaseTest/ActionsEaseTest.cpp b/tests/cpp-tests/Classes/ActionsEaseTest/ActionsEaseTest.cpp index 29c9bc3d99d8..c10e571f3ec1 100644 --- a/tests/cpp-tests/Classes/ActionsEaseTest/ActionsEaseTest.cpp +++ b/tests/cpp-tests/Classes/ActionsEaseTest/ActionsEaseTest.cpp @@ -29,13 +29,13 @@ USING_NS_CC; -enum { +enum +{ kTagAction1 = 1, kTagAction2 = 2, - kTagSlider = 1, + kTagSlider = 1, }; - //------------------------------------------------------------------ // // SpriteDemo @@ -44,34 +44,33 @@ enum { void EaseSpriteDemo::centerSprites(unsigned int numberOfSprites) { auto s = Director::getInstance()->getWinSize(); - - if( numberOfSprites == 0 ) + + if (numberOfSprites == 0) { _tamara->setVisible(false); _kathia->setVisible(false); _grossini->setVisible(false); } - else if ( numberOfSprites == 1 ) + else if (numberOfSprites == 1) { _tamara->setVisible(false); _kathia->setVisible(false); - _grossini->setPosition(s.width/2, s.height/2); + _grossini->setPosition(s.width / 2, s.height / 2); } - else if( numberOfSprites == 2 ) + else if (numberOfSprites == 2) { - _kathia->setPosition(s.width/3, s.height/2); - _tamara->setPosition(2*s.width/3, s.height/2); + _kathia->setPosition(s.width / 3, s.height / 2); + _tamara->setPosition(2 * s.width / 3, s.height / 2); _grossini->setVisible(false); } - else if( numberOfSprites == 3 ) + else if (numberOfSprites == 3) { - _grossini->setPosition(s.width/2, s.height/2); - _tamara->setPosition(s.width/4, s.height/2); - _kathia->setPosition(3 * s.width/4, s.height/2); + _grossini->setPosition(s.width / 2, s.height / 2); + _tamara->setPosition(s.width / 4, s.height / 2); + _kathia->setPosition(3 * s.width / 4, s.height / 2); } } - //------------------------------------------------------------------ // // SpriteEase @@ -81,23 +80,22 @@ void EaseSpriteDemo::centerSprites(unsigned int numberOfSprites) void SpriteEase::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130,0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseIn::create(move->clone(), 2.5f); + + auto move_ease_in = EaseIn::create(move->clone(), 2.5f); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseOut::create(move->clone(), 2.5f); + + auto move_ease_out = EaseOut::create(move->clone(), 2.5f); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); - - + auto a2 = _grossini->runAction(RepeatForever::create(seq1)); a2->setTag(1); @@ -110,7 +108,6 @@ void SpriteEase::onEnter() schedule(CC_SCHEDULE_SELECTOR(SpriteEase::testStopAction), 6.25f); } - void SpriteEase::testStopAction(float dt) { unschedule(CC_SCHEDULE_SELECTOR(SpriteEase::testStopAction)); @@ -124,7 +121,6 @@ std::string SpriteEase::subtitle() const return "EaseIn - EaseOut - Stop"; } - //------------------------------------------------------------------ // // SpriteEaseInOut @@ -135,30 +131,29 @@ void SpriteEaseInOut::onEnter() { EaseSpriteDemo::onEnter(); - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); -// id move_back = move->reverse(); - - auto move_ease_inout1 = EaseInOut::create(move->clone(), 0.65f); + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + // id move_back = move->reverse(); + + auto move_ease_inout1 = EaseInOut::create(move->clone(), 0.65f); auto move_ease_inout_back1 = move_ease_inout1->reverse(); - - auto move_ease_inout2 = EaseInOut::create(move->clone(), 1.35f); + + auto move_ease_inout2 = EaseInOut::create(move->clone(), 1.35f); auto move_ease_inout_back2 = move_ease_inout2->reverse(); - auto move_ease_inout3 = EaseInOut::create(move->clone(), 1.0f); + auto move_ease_inout3 = EaseInOut::create(move->clone(), 1.0f); auto move_ease_inout_back3 = move_ease_inout3->reverse(); - + auto delay = DelayTime::create(0.25f); - auto seq1 = Sequence::create( move_ease_inout1, delay, move_ease_inout_back1, delay->clone(), nullptr); - auto seq2 = Sequence::create( move_ease_inout2, delay->clone(), move_ease_inout_back2, delay->clone(), nullptr); - auto seq3 = Sequence::create( move_ease_inout3, delay->clone(), move_ease_inout_back3, delay->clone(), nullptr); - + auto seq1 = Sequence::create(move_ease_inout1, delay, move_ease_inout_back1, delay->clone(), nullptr); + auto seq2 = Sequence::create(move_ease_inout2, delay->clone(), move_ease_inout_back2, delay->clone(), nullptr); + auto seq3 = Sequence::create(move_ease_inout3, delay->clone(), move_ease_inout_back3, delay->clone(), nullptr); + _tamara->runAction(RepeatForever::create(seq1)); _kathia->runAction(RepeatForever::create(seq2)); _grossini->runAction(RepeatForever::create(seq3)); } - std::string SpriteEaseInOut::subtitle() const { return "EaseInOut and rates"; @@ -173,29 +168,27 @@ std::string SpriteEaseInOut::subtitle() const void SpriteEaseExponential::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseExponentialIn::create(move->clone()); + + auto move_ease_in = EaseExponentialIn::create(move->clone()); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseExponentialOut::create(move->clone()); + + auto move_ease_out = EaseExponentialOut::create(move->clone()); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); - - _grossini->runAction( RepeatForever::create(seq1)); - _tamara->runAction( RepeatForever::create(seq2)); - _kathia->runAction( RepeatForever::create(seq3)); + _grossini->runAction(RepeatForever::create(seq1)); + _tamara->runAction(RepeatForever::create(seq2)); + _kathia->runAction(RepeatForever::create(seq3)); } - std::string SpriteEaseExponential::subtitle() const { return "ExpIn - ExpOut actions"; @@ -210,25 +203,23 @@ void SpriteEaseExponentialInOut::onEnter() { EaseSpriteDemo::onEnter(); - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease = EaseExponentialInOut::create(move->clone() ); - auto move_ease_back = move_ease->reverse(); //--> reverse() - + + auto move_ease = EaseExponentialInOut::create(move->clone()); + auto move_ease_back = move_ease->reverse(); //--> reverse() + auto delay = DelayTime::create(0.25f); - - auto seq1 = Sequence::create( move, delay, move_back, delay->clone(), nullptr); - auto seq2 = Sequence::create( move_ease, delay, move_ease_back, delay->clone(), nullptr); - + + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); + auto seq2 = Sequence::create(move_ease, delay, move_ease_back, delay->clone(), nullptr); + this->positionForTwo(); - - _grossini->runAction( RepeatForever::create(seq1)); - _tamara->runAction( RepeatForever::create(seq2)); + _grossini->runAction(RepeatForever::create(seq1)); + _tamara->runAction(RepeatForever::create(seq2)); } - std::string SpriteEaseExponentialInOut::subtitle() const { return "EaseExponentialInOut action"; @@ -243,29 +234,26 @@ void SpriteEaseSine::onEnter() { EaseSpriteDemo::onEnter(); - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseSineIn::create(move->clone() ); + + auto move_ease_in = EaseSineIn::create(move->clone()); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseSineOut::create(move->clone() ); + + auto move_ease_out = EaseSineOut::create(move->clone()); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); - - - _grossini->runAction( RepeatForever::create(seq1)); - _tamara->runAction( RepeatForever::create(seq2)); - _kathia->runAction( RepeatForever::create(seq3)); + _grossini->runAction(RepeatForever::create(seq1)); + _tamara->runAction(RepeatForever::create(seq2)); + _kathia->runAction(RepeatForever::create(seq3)); } - std::string SpriteEaseSine::subtitle() const { return "EaseSineIn - EaseSineOut"; @@ -280,24 +268,23 @@ void SpriteEaseSineInOut::onEnter() { EaseSpriteDemo::onEnter(); - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease = EaseSineInOut::create(move->clone() ); + + auto move_ease = EaseSineInOut::create(move->clone()); auto move_ease_back = move_ease->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease, delay->clone(), move_ease_back, delay->clone(), nullptr); this->positionForTwo(); - _grossini->runAction( RepeatForever::create(seq1)); - _tamara->runAction( RepeatForever::create(seq2)); + _grossini->runAction(RepeatForever::create(seq1)); + _tamara->runAction(RepeatForever::create(seq2)); } - std::string SpriteEaseSineInOut::subtitle() const { return "EaseSineInOut action"; @@ -311,27 +298,26 @@ std::string SpriteEaseSineInOut::subtitle() const void SpriteEaseElastic::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseElasticIn::create(move->clone() ); + + auto move_ease_in = EaseElasticIn::create(move->clone()); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseElasticOut::create(move->clone() ); + + auto move_ease_out = EaseElasticOut::create(move->clone()); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); - - _grossini->runAction( RepeatForever::create(seq1)); - _tamara->runAction( RepeatForever::create(seq2)); - _kathia->runAction( RepeatForever::create(seq3)); -} + _grossini->runAction(RepeatForever::create(seq1)); + _tamara->runAction(RepeatForever::create(seq2)); + _kathia->runAction(RepeatForever::create(seq3)); +} std::string SpriteEaseElastic::subtitle() const { @@ -347,36 +333,34 @@ std::string SpriteEaseElastic::subtitle() const void SpriteEaseElasticInOut::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); - auto move_ease_inout1 = EaseElasticInOut::create(move->clone(), 0.3f); + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); + + auto move_ease_inout1 = EaseElasticInOut::create(move->clone(), 0.3f); auto move_ease_inout_back1 = move_ease_inout1->reverse(); - - auto move_ease_inout2 = EaseElasticInOut::create(move->clone(), 0.45f); + + auto move_ease_inout2 = EaseElasticInOut::create(move->clone(), 0.45f); auto move_ease_inout_back2 = move_ease_inout2->reverse(); - - auto move_ease_inout3 = EaseElasticInOut::create(move->clone(), 0.6f); + + auto move_ease_inout3 = EaseElasticInOut::create(move->clone(), 0.6f); auto move_ease_inout_back3 = move_ease_inout3->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move_ease_inout1, delay, move_ease_inout_back1, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_inout2, delay->clone(), move_ease_inout_back2, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_inout3, delay->clone(), move_ease_inout_back3, delay->clone(), nullptr); - - _tamara->runAction( RepeatForever::create(seq1)); - _kathia->runAction( RepeatForever::create(seq2)); - _grossini->runAction( RepeatForever::create(seq3)); -} + _tamara->runAction(RepeatForever::create(seq1)); + _kathia->runAction(RepeatForever::create(seq2)); + _grossini->runAction(RepeatForever::create(seq3)); +} std::string SpriteEaseElasticInOut::subtitle() const { return "EaseElasticInOut action"; } - //------------------------------------------------------------------ // // SpriteEaseBounce @@ -386,34 +370,32 @@ std::string SpriteEaseElasticInOut::subtitle() const void SpriteEaseBounce::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseBounceIn::create(move->clone() ); + + auto move_ease_in = EaseBounceIn::create(move->clone()); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseBounceOut::create(move->clone() ); + + auto move_ease_out = EaseBounceOut::create(move->clone()); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); - - _grossini->runAction( RepeatForever::create(seq1)); - _tamara->runAction( RepeatForever::create(seq2)); - _kathia->runAction( RepeatForever::create(seq3)); -} + _grossini->runAction(RepeatForever::create(seq1)); + _tamara->runAction(RepeatForever::create(seq2)); + _kathia->runAction(RepeatForever::create(seq3)); +} std::string SpriteEaseBounce::subtitle() const { return "Bounce In - Out actions"; } - //------------------------------------------------------------------ // // SpriteEaseBounceInOut @@ -424,23 +406,22 @@ void SpriteEaseBounceInOut::onEnter() { EaseSpriteDemo::onEnter(); - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease = EaseBounceInOut::create(move->clone() ); + + auto move_ease = EaseBounceInOut::create(move->clone()); auto move_ease_back = move_ease->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease, delay->clone(), move_ease_back, delay->clone(), nullptr); - + this->positionForTwo(); - - _grossini->runAction( RepeatForever::create(seq1)); - _tamara->runAction( RepeatForever::create(seq2)); -} + _grossini->runAction(RepeatForever::create(seq1)); + _tamara->runAction(RepeatForever::create(seq2)); +} std::string SpriteEaseBounceInOut::subtitle() const { @@ -456,28 +437,27 @@ std::string SpriteEaseBounceInOut::subtitle() const void SpriteEaseBack::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseBackIn::create(move->clone()); + + auto move_ease_in = EaseBackIn::create(move->clone()); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseBackOut::create( move->clone()); + + auto move_ease_out = EaseBackOut::create(move->clone()); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); - + _grossini->runAction(RepeatForever::create(seq1)); _tamara->runAction(RepeatForever::create(seq2)); - _kathia->runAction(RepeatForever::create(seq3)); + _kathia->runAction(RepeatForever::create(seq3)); } - std::string SpriteEaseBack::subtitle() const { return "Back In - Out actions"; @@ -492,24 +472,23 @@ std::string SpriteEaseBack::subtitle() const void SpriteEaseBackInOut::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease = EaseBackInOut::create(move->clone() ); + + auto move_ease = EaseBackInOut::create(move->clone()); auto move_ease_back = move_ease->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease, delay->clone(), move_ease_back, delay->clone(), nullptr); - + this->positionForTwo(); - - _grossini->runAction( RepeatForever::create(seq1)); - _tamara->runAction( RepeatForever::create(seq2)); -} + _grossini->runAction(RepeatForever::create(seq1)); + _tamara->runAction(RepeatForever::create(seq2)); +} std::string SpriteEaseBackInOut::subtitle() const { @@ -525,55 +504,52 @@ std::string SpriteEaseBackInOut::subtitle() const void SpriteEaseBezier::onEnter() { EaseSpriteDemo::onEnter(); - + auto s = Director::getInstance()->getWinSize(); - + // // startPosition can be any coordinate, but since the movement // is relative to the Bezier curve, make it (0,0) // - + centerSprites(3); - + // sprite 1 ccBezierConfig bezier; - bezier.controlPoint_1 = Vec2(0.0f, s.height/2); - bezier.controlPoint_2 = Vec2(300.0f, -s.height/2); - bezier.endPosition = Vec2(300.0f,100.0f); - - auto bezierForward = BezierBy::create(3, bezier); + bezier.controlPoint_1 = Vec2(0.0f, s.height / 2); + bezier.controlPoint_2 = Vec2(300.0f, -s.height / 2); + bezier.endPosition = Vec2(300.0f, 100.0f); + + auto bezierForward = BezierBy::create(3, bezier); auto bezierEaseForward = EaseBezierAction::create(bezierForward); bezierEaseForward->setBezierParamer(0.5f, 0.5f, 1.0f, 1.0f); - + auto bezierEaseBack = bezierEaseForward->reverse(); - auto rep = RepeatForever::create(Sequence::create( bezierEaseForward, bezierEaseBack, nullptr)); - - + auto rep = RepeatForever::create(Sequence::create(bezierEaseForward, bezierEaseBack, nullptr)); + // sprite 2 - _tamara->setPosition(80,160); - ccBezierConfig bezier2; - bezier2.controlPoint_1 = Vec2(100.0f, s.height/2); - bezier2.controlPoint_2 = Vec2(200.0f, -s.height/2); - bezier2.endPosition = Vec2(240.0f,160.0f); - - auto bezierTo1 = BezierTo::create(2, bezier2); + _tamara->setPosition(80, 160); + ccBezierConfig bezier2; + bezier2.controlPoint_1 = Vec2(100.0f, s.height / 2); + bezier2.controlPoint_2 = Vec2(200.0f, -s.height / 2); + bezier2.endPosition = Vec2(240.0f, 160.0f); + + auto bezierTo1 = BezierTo::create(2, bezier2); auto bezierEaseTo1 = EaseBezierAction::create(bezierTo1); bezierEaseTo1->setBezierParamer(0.5f, 0.5f, 1.0f, 1.0f); - + // sprite 3 - _kathia->setPosition(400.0f,160.0f); - auto bezierTo2 = BezierTo::create(2, bezier2); + _kathia->setPosition(400.0f, 160.0f); + auto bezierTo2 = BezierTo::create(2, bezier2); auto bezierEaseTo2 = EaseBezierAction::create(bezierTo2); bezierEaseTo2->setBezierParamer(0.0f, 0.5f, -5.0f, 1.0f); - - _grossini->runAction( rep); + _grossini->runAction(rep); _tamara->runAction(bezierEaseTo1); _kathia->runAction(bezierEaseTo2); - } -std::string SpriteEaseBezier::subtitle()const +std::string SpriteEaseBezier::subtitle() const { return "SpriteEaseBezier action"; } @@ -587,25 +563,25 @@ std::string SpriteEaseBezier::subtitle()const void SpriteEaseQuadratic::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseQuadraticActionIn::create(move->clone() ); + + auto move_ease_in = EaseQuadraticActionIn::create(move->clone()); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseQuadraticActionOut::create(move->clone() ); + + auto move_ease_out = EaseQuadraticActionOut::create(move->clone()); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); - - _grossini->runAction( RepeatForever::create(seq1)); - _tamara->runAction( RepeatForever::create(seq2)); - _kathia->runAction( RepeatForever::create(seq3)); + + _grossini->runAction(RepeatForever::create(seq1)); + _tamara->runAction(RepeatForever::create(seq2)); + _kathia->runAction(RepeatForever::create(seq3)); } std::string SpriteEaseQuadratic::subtitle() const @@ -622,30 +598,29 @@ std::string SpriteEaseQuadratic::subtitle() const void SpriteEaseQuadraticInOut::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease = EaseQuadraticActionInOut::create(move->clone() ); + + auto move_ease = EaseQuadraticActionInOut::create(move->clone()); auto move_ease_back = move_ease->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease, delay->clone(), move_ease_back, delay->clone(), nullptr); - + this->positionForTwo(); - - _grossini->runAction( RepeatForever::create(seq1)); - _tamara->runAction( RepeatForever::create(seq2)); + + _grossini->runAction(RepeatForever::create(seq1)); + _tamara->runAction(RepeatForever::create(seq2)); } -std::string SpriteEaseQuadraticInOut::subtitle()const +std::string SpriteEaseQuadraticInOut::subtitle() const { return "SpriteEaseQuadraticInOut action"; } - //------------------------------------------------------------------ // // SpriteEaseQuartic @@ -655,28 +630,28 @@ std::string SpriteEaseQuadraticInOut::subtitle()const void SpriteEaseQuartic::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseQuarticActionIn::create(move->clone() ); + + auto move_ease_in = EaseQuarticActionIn::create(move->clone()); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseQuarticActionOut::create(move->clone() ); + + auto move_ease_out = EaseQuarticActionOut::create(move->clone()); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); - - _grossini->runAction( RepeatForever::create(seq1)); - _tamara->runAction( RepeatForever::create(seq2)); - _kathia->runAction( RepeatForever::create(seq3)); + + _grossini->runAction(RepeatForever::create(seq1)); + _tamara->runAction(RepeatForever::create(seq2)); + _kathia->runAction(RepeatForever::create(seq3)); } -std::string SpriteEaseQuartic::subtitle()const +std::string SpriteEaseQuartic::subtitle() const { return "SpriteEaseQuartic action"; } @@ -690,25 +665,25 @@ std::string SpriteEaseQuartic::subtitle()const void SpriteEaseQuarticInOut::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease = EaseQuarticActionInOut::create(move->clone() ); + + auto move_ease = EaseQuarticActionInOut::create(move->clone()); auto move_ease_back = move_ease->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease, delay->clone(), move_ease_back, delay->clone(), nullptr); - + this->positionForTwo(); - - _grossini->runAction( RepeatForever::create(seq1)); - _tamara->runAction( RepeatForever::create(seq2)); + + _grossini->runAction(RepeatForever::create(seq1)); + _tamara->runAction(RepeatForever::create(seq2)); } -std::string SpriteEaseQuarticInOut::subtitle()const +std::string SpriteEaseQuarticInOut::subtitle() const { return "SpriteEaseQuarticInOut action"; } @@ -722,33 +697,32 @@ std::string SpriteEaseQuarticInOut::subtitle()const void SpriteEaseQuintic::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseQuinticActionIn::create(move->clone() ); + + auto move_ease_in = EaseQuinticActionIn::create(move->clone()); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseQuinticActionOut::create(move->clone() ); + + auto move_ease_out = EaseQuinticActionOut::create(move->clone()); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); - - _grossini->runAction( RepeatForever::create(seq1)); - _tamara->runAction( RepeatForever::create(seq2)); - _kathia->runAction( RepeatForever::create(seq3)); + + _grossini->runAction(RepeatForever::create(seq1)); + _tamara->runAction(RepeatForever::create(seq2)); + _kathia->runAction(RepeatForever::create(seq3)); } -std::string SpriteEaseQuintic::subtitle()const +std::string SpriteEaseQuintic::subtitle() const { return "SpriteEaseQuintic action"; } - //------------------------------------------------------------------ // // SpriteEaseQuinticInOut @@ -758,25 +732,25 @@ std::string SpriteEaseQuintic::subtitle()const void SpriteEaseQuinticInOut::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease = EaseQuinticActionInOut::create(move->clone() ); + + auto move_ease = EaseQuinticActionInOut::create(move->clone()); auto move_ease_back = move_ease->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease, delay->clone(), move_ease_back, delay->clone(), nullptr); - + this->positionForTwo(); - - _grossini->runAction( RepeatForever::create(seq1)); - _tamara->runAction( RepeatForever::create(seq2)); + + _grossini->runAction(RepeatForever::create(seq1)); + _tamara->runAction(RepeatForever::create(seq2)); } -std::string SpriteEaseQuinticInOut::subtitle()const +std::string SpriteEaseQuinticInOut::subtitle() const { return "SpriteEaseQuinticInOut action"; } @@ -790,33 +764,32 @@ std::string SpriteEaseQuinticInOut::subtitle()const void SpriteEaseCircle::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseCircleActionIn::create(move->clone() ); + + auto move_ease_in = EaseCircleActionIn::create(move->clone()); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseCircleActionOut::create(move->clone() ); + + auto move_ease_out = EaseCircleActionOut::create(move->clone()); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); - - _grossini->runAction( RepeatForever::create(seq1)); - _tamara->runAction( RepeatForever::create(seq2)); - _kathia->runAction( RepeatForever::create(seq3)); + + _grossini->runAction(RepeatForever::create(seq1)); + _tamara->runAction(RepeatForever::create(seq2)); + _kathia->runAction(RepeatForever::create(seq3)); } -std::string SpriteEaseCircle::subtitle()const +std::string SpriteEaseCircle::subtitle() const { return "SpriteEaseCircle action"; } - //------------------------------------------------------------------ // // SpriteEaseCircleInOut @@ -826,25 +799,25 @@ std::string SpriteEaseCircle::subtitle()const void SpriteEaseCircleInOut::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease = EaseCircleActionInOut::create(move->clone() ); + + auto move_ease = EaseCircleActionInOut::create(move->clone()); auto move_ease_back = move_ease->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease, delay->clone(), move_ease_back, delay->clone(), nullptr); - + this->positionForTwo(); - - _grossini->runAction( RepeatForever::create(seq1)); - _tamara->runAction( RepeatForever::create(seq2)); + + _grossini->runAction(RepeatForever::create(seq1)); + _tamara->runAction(RepeatForever::create(seq2)); } -std::string SpriteEaseCircleInOut::subtitle()const +std::string SpriteEaseCircleInOut::subtitle() const { return "SpriteEaseCircleInOut action"; } @@ -858,33 +831,32 @@ std::string SpriteEaseCircleInOut::subtitle()const void SpriteEaseCubic::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease_in = EaseCubicActionIn::create(move->clone() ); + + auto move_ease_in = EaseCubicActionIn::create(move->clone()); auto move_ease_in_back = move_ease_in->reverse(); - - auto move_ease_out = EaseCubicActionOut::create(move->clone() ); + + auto move_ease_out = EaseCubicActionOut::create(move->clone()); auto move_ease_out_back = move_ease_out->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease_in, delay->clone(), move_ease_in_back, delay->clone(), nullptr); auto seq3 = Sequence::create(move_ease_out, delay->clone(), move_ease_out_back, delay->clone(), nullptr); - - _grossini->runAction( RepeatForever::create(seq1)); - _tamara->runAction( RepeatForever::create(seq2)); - _kathia->runAction( RepeatForever::create(seq3)); + + _grossini->runAction(RepeatForever::create(seq1)); + _tamara->runAction(RepeatForever::create(seq2)); + _kathia->runAction(RepeatForever::create(seq3)); } -std::string SpriteEaseCubic::subtitle()const +std::string SpriteEaseCubic::subtitle() const { return "SpriteEaseCubic action"; } - //------------------------------------------------------------------ // // SpriteEaseCubicInOut @@ -894,25 +866,25 @@ std::string SpriteEaseCubic::subtitle()const void SpriteEaseCubicInOut::onEnter() { EaseSpriteDemo::onEnter(); - - auto move = MoveBy::create(3, Vec2(VisibleRect::right().x-130, 0.0f)); + + auto move = MoveBy::create(3, Vec2(VisibleRect::right().x - 130, 0.0f)); auto move_back = move->reverse(); - - auto move_ease = EaseCubicActionInOut::create(move->clone() ); + + auto move_ease = EaseCubicActionInOut::create(move->clone()); auto move_ease_back = move_ease->reverse(); - + auto delay = DelayTime::create(0.25f); - + auto seq1 = Sequence::create(move, delay, move_back, delay->clone(), nullptr); auto seq2 = Sequence::create(move_ease, delay->clone(), move_ease_back, delay->clone(), nullptr); - + this->positionForTwo(); - - _grossini->runAction( RepeatForever::create(seq1)); - _tamara->runAction( RepeatForever::create(seq2)); + + _grossini->runAction(RepeatForever::create(seq1)); + _tamara->runAction(RepeatForever::create(seq2)); } -std::string SpriteEaseCubicInOut::title()const +std::string SpriteEaseCubicInOut::title() const { return "SpriteEaseCubicInOut action"; } @@ -925,43 +897,43 @@ std::string SpriteEaseCubicInOut::title()const void SpeedTest::onEnter() { EaseSpriteDemo::onEnter(); - + auto s = Director::getInstance()->getWinSize(); // rotate and jump - auto jump1 = JumpBy::create(4.0f, Vec2(-s.width+80, 0.0f), 100.0f, 4); + auto jump1 = JumpBy::create(4.0f, Vec2(-s.width + 80, 0.0f), 100.0f, 4); auto jump2 = jump1->reverse(); - auto rot1 = RotateBy::create(4.0f, 360*2.0f); - auto rot2 = rot1->reverse(); - + auto rot1 = RotateBy::create(4.0f, 360 * 2.0f); + auto rot2 = rot1->reverse(); + auto seq3_1 = Sequence::create(jump2, jump1, nullptr); - auto seq3_2 = Sequence::create( rot1, rot2, nullptr); - auto spawn = Spawn::create(seq3_1, seq3_2, nullptr); + auto seq3_2 = Sequence::create(rot1, rot2, nullptr); + auto spawn = Spawn::create(seq3_1, seq3_2, nullptr); auto action = Speed::create(RepeatForever::create(spawn), 1.0f); action->setTag(kTagAction1); - + auto action2 = action->clone(); auto action3 = action->clone(); action2->setTag(kTagAction1); action3->setTag(kTagAction1); - + _grossini->runAction(action2); _tamara->runAction(action3); _kathia->runAction(action); - - this->schedule(CC_SCHEDULE_SELECTOR(SpeedTest::altertime), 1.0f);//:@selector(altertime:) interval:1.0f]; + + this->schedule(CC_SCHEDULE_SELECTOR(SpeedTest::altertime), 1.0f); //:@selector(altertime:) interval:1.0f]; } void SpeedTest::altertime(float dt) -{ +{ auto action1 = static_cast(_grossini->getActionByTag(kTagAction1)); auto action2 = static_cast(_tamara->getActionByTag(kTagAction1)); auto action3 = static_cast(_kathia->getActionByTag(kTagAction1)); - - action1->setSpeed( CCRANDOM_MINUS1_1() * 2 ); - action2->setSpeed( CCRANDOM_MINUS1_1() * 2 ); - action3->setSpeed( CCRANDOM_MINUS1_1() * 2 ); + + action1->setSpeed(CCRANDOM_MINUS1_1() * 2); + action2->setSpeed(CCRANDOM_MINUS1_1() * 2); + action3->setSpeed(CCRANDOM_MINUS1_1() * 2); } std::string SpeedTest::subtitle() const @@ -1003,9 +975,7 @@ ActionsEaseTests::ActionsEaseTests() ADD_TEST_CASE(SpeedTest); } -EaseSpriteDemo::EaseSpriteDemo() -{ -} +EaseSpriteDemo::EaseSpriteDemo() {} EaseSpriteDemo::~EaseSpriteDemo() { @@ -1015,13 +985,14 @@ EaseSpriteDemo::~EaseSpriteDemo() } void EaseSpriteDemo::positionForTwo() -{ - _grossini->setPosition(VisibleRect::left().x+60, VisibleRect::bottom().y + VisibleRect::getVisibleRect().size.height*1/5); - _tamara->setPosition(VisibleRect::left().x+60, VisibleRect::bottom().y + VisibleRect::getVisibleRect().size.height*4/5); +{ + _grossini->setPosition(VisibleRect::left().x + 60, + VisibleRect::bottom().y + VisibleRect::getVisibleRect().size.height * 1 / 5); + _tamara->setPosition(VisibleRect::left().x + 60, + VisibleRect::bottom().y + VisibleRect::getVisibleRect().size.height * 4 / 5); _kathia->setVisible(false); } - std::string EaseSpriteDemo::subtitle() const { return "No title"; @@ -1032,15 +1003,21 @@ void EaseSpriteDemo::onEnter() TestCase::onEnter(); // Or you can create an sprite using a filename. PNG and BMP files are supported. - _grossini = Sprite::create(s_pathGrossini); _grossini->retain(); - _tamara = Sprite::create(s_pathSister1); _tamara->retain(); - _kathia = Sprite::create(s_pathSister2); _kathia->retain(); - - addChild( _grossini, 3); - addChild( _kathia, 2); - addChild( _tamara, 1); - - _grossini->setPosition(VisibleRect::left().x + 60, VisibleRect::bottom().y+VisibleRect::getVisibleRect().size.height*1/5); - _kathia->setPosition(VisibleRect::left().x + 60, VisibleRect::bottom().y+VisibleRect::getVisibleRect().size.height*2.5f/5); - _tamara->setPosition(VisibleRect::left().x + 60, VisibleRect::bottom().y+VisibleRect::getVisibleRect().size.height*4/5); + _grossini = Sprite::create(s_pathGrossini); + _grossini->retain(); + _tamara = Sprite::create(s_pathSister1); + _tamara->retain(); + _kathia = Sprite::create(s_pathSister2); + _kathia->retain(); + + addChild(_grossini, 3); + addChild(_kathia, 2); + addChild(_tamara, 1); + + _grossini->setPosition(VisibleRect::left().x + 60, + VisibleRect::bottom().y + VisibleRect::getVisibleRect().size.height * 1 / 5); + _kathia->setPosition(VisibleRect::left().x + 60, + VisibleRect::bottom().y + VisibleRect::getVisibleRect().size.height * 2.5f / 5); + _tamara->setPosition(VisibleRect::left().x + 60, + VisibleRect::bottom().y + VisibleRect::getVisibleRect().size.height * 4 / 5); } diff --git a/tests/cpp-tests/Classes/ActionsEaseTest/ActionsEaseTest.h b/tests/cpp-tests/Classes/ActionsEaseTest/ActionsEaseTest.h index 1fe1f577f2c5..2676595bb027 100644 --- a/tests/cpp-tests/Classes/ActionsEaseTest/ActionsEaseTest.h +++ b/tests/cpp-tests/Classes/ActionsEaseTest/ActionsEaseTest.h @@ -34,11 +34,11 @@ DEFINE_TEST_SUITE(ActionsEaseTests); class EaseSpriteDemo : public TestCase { protected: - cocos2d::Sprite* _grossini; - cocos2d::Sprite* _tamara; - cocos2d::Sprite* _kathia; + cocos2d::Sprite* _grossini; + cocos2d::Sprite* _tamara; + cocos2d::Sprite* _kathia; - std::string _title; + std::string _title; public: EaseSpriteDemo(); @@ -46,7 +46,7 @@ class EaseSpriteDemo : public TestCase virtual std::string subtitle() const override; virtual void onEnter() override; - + void centerSprites(unsigned int numberOfSprites); void positionForTwo(); @@ -225,7 +225,6 @@ class SpriteEaseQuinticInOut : public EaseSpriteDemo virtual std::string subtitle() const override; }; - class SpriteEaseCircle : public EaseSpriteDemo { public: @@ -272,5 +271,4 @@ class SpeedTest : public EaseSpriteDemo void altertime(float dt); }; - #endif diff --git a/tests/cpp-tests/Classes/ActionsProgressTest/ActionsProgressTest.cpp b/tests/cpp-tests/Classes/ActionsProgressTest/ActionsProgressTest.cpp index f1f2f2cba037..6d570773260a 100644 --- a/tests/cpp-tests/Classes/ActionsProgressTest/ActionsProgressTest.cpp +++ b/tests/cpp-tests/Classes/ActionsProgressTest/ActionsProgressTest.cpp @@ -45,13 +45,9 @@ ActionsProgressTests::ActionsProgressTests() // SpriteDemo // //------------------------------------------------------------------ -SpriteDemo::SpriteDemo() -{ -} +SpriteDemo::SpriteDemo() {} -SpriteDemo::~SpriteDemo() -{ -} +SpriteDemo::~SpriteDemo() {} std::string SpriteDemo::title() const { @@ -62,7 +58,7 @@ void SpriteDemo::onEnter() { TestCase::onEnter(); - auto background = LayerColor::create(Color4B(255,0,0,255)); + auto background = LayerColor::create(Color4B(255, 0, 0, 255)); addChild(background, -10); } @@ -74,25 +70,25 @@ void SpriteDemo::onEnter() void SpriteProgressToRadial::onEnter() { SpriteDemo::onEnter(); - + auto s = Director::getInstance()->getWinSize(); auto to1 = Sequence::createWithTwoActions(ProgressTo::create(2, 100), ProgressTo::create(0, 0)); auto to2 = Sequence::createWithTwoActions(ProgressTo::create(2, 100), ProgressTo::create(0, 0)); auto left = ProgressTimer::create(Sprite::create(s_pathSister1)); - left->setType( ProgressTimer::Type::RADIAL ); + left->setType(ProgressTimer::Type::RADIAL); addChild(left); - left->setPosition(100, s.height/2); - left->runAction( RepeatForever::create(to1)); - + left->setPosition(100, s.height / 2); + left->runAction(RepeatForever::create(to1)); + auto right = ProgressTimer::create(Sprite::create(s_pathBlock)); right->setType(ProgressTimer::Type::RADIAL); // Makes the ridial CCW right->setReverseDirection(true); addChild(right); - right->setPosition(s.width-100, s.height/2); - right->runAction( RepeatForever::create(to2)); + right->setPosition(s.width - 100, s.height / 2); + right->runAction(RepeatForever::create(to2)); } std::string SpriteProgressToRadial::subtitle() const @@ -109,22 +105,22 @@ std::string SpriteProgressToRadial::subtitle() const void SpriteProgressToHorizontal::onEnter() { SpriteDemo::onEnter(); - + auto s = Director::getInstance()->getWinSize(); - + auto to1 = Sequence::createWithTwoActions(ProgressTo::create(2, 100), ProgressTo::create(0, 0)); auto to2 = Sequence::createWithTwoActions(ProgressTo::create(2, 100), ProgressTo::create(0, 0)); - + auto left = ProgressTimer::create(Sprite::create(s_pathSister1)); left->setType(ProgressTimer::Type::BAR); // Setup for a bar starting from the left since the midpoint is 0 for the x - left->setMidpoint(Vec2(0.0f,0.0f)); + left->setMidpoint(Vec2(0.0f, 0.0f)); // Setup for a horizontal bar since the bar change rate is 0 for y meaning no vertical change left->setBarChangeRate(Vec2(1.0f, 0.0f)); addChild(left); - left->setPosition(100, s.height/2); - left->runAction( RepeatForever::create(to1)); - + left->setPosition(100, s.height / 2); + left->runAction(RepeatForever::create(to1)); + auto right = ProgressTimer::create(Sprite::create(s_pathSister2)); right->setType(ProgressTimer::Type::BAR); // Setup for a bar starting from the left since the midpoint is 1 for the x @@ -132,8 +128,8 @@ void SpriteProgressToHorizontal::onEnter() // Setup for a horizontal bar since the bar change rate is 0 for y meaning no vertical change right->setBarChangeRate(Vec2(1.0f, 0.0f)); addChild(right); - right->setPosition(s.width-100, s.height/2); - right->runAction( RepeatForever::create(to2)); + right->setPosition(s.width - 100, s.height / 2); + right->runAction(RepeatForever::create(to2)); } std::string SpriteProgressToHorizontal::subtitle() const @@ -149,23 +145,23 @@ std::string SpriteProgressToHorizontal::subtitle() const void SpriteProgressToVertical::onEnter() { SpriteDemo::onEnter(); - + auto s = Director::getInstance()->getWinSize(); - + auto to1 = Sequence::createWithTwoActions(ProgressTo::create(2, 100), ProgressTo::create(0, 0)); auto to2 = Sequence::createWithTwoActions(ProgressTo::create(2, 100), ProgressTo::create(0, 0)); - + auto left = ProgressTimer::create(Sprite::create(s_pathSister1)); left->setType(ProgressTimer::Type::BAR); // Setup for a bar starting from the bottom since the midpoint is 0 for the y - left->setMidpoint(Vec2(0.0f,0.0f)); + left->setMidpoint(Vec2(0.0f, 0.0f)); // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change left->setBarChangeRate(Vec2(0.0f, 1.0f)); addChild(left); - left->setPosition(100, s.height/2); - left->runAction( RepeatForever::create(to1)); - + left->setPosition(100, s.height / 2); + left->runAction(RepeatForever::create(to1)); + auto right = ProgressTimer::create(Sprite::create(s_pathSister2)); right->setType(ProgressTimer::Type::BAR); // Setup for a bar starting from the bottom since the midpoint is 0 for the y @@ -173,8 +169,8 @@ void SpriteProgressToVertical::onEnter() // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change right->setBarChangeRate(Vec2(0, 1)); addChild(right); - right->setPosition(s.width-100, s.height/2); - right->runAction( RepeatForever::create(to2)); + right->setPosition(s.width - 100, s.height / 2); + right->runAction(RepeatForever::create(to2)); } std::string SpriteProgressToVertical::subtitle() const @@ -196,28 +192,28 @@ void SpriteProgressToRadialMidpointChanged::onEnter() auto action = Sequence::createWithTwoActions(ProgressTo::create(2, 100), ProgressTo::create(0, 0)); /** - * Our image on the left should be a radial progress indicator, clockwise - */ + * Our image on the left should be a radial progress indicator, clockwise + */ auto left = ProgressTimer::create(Sprite::create(s_pathBlock)); left->setType(ProgressTimer::Type::RADIAL); addChild(left); left->setMidpoint(Vec2(0.25f, 0.75f)); - left->setPosition(100, s.height/2); + left->setPosition(100, s.height / 2); left->runAction(RepeatForever::create(action->clone())); /** - * Our image on the left should be a radial progress indicator, counter clockwise - */ + * Our image on the left should be a radial progress indicator, counter clockwise + */ auto right = ProgressTimer::create(Sprite::create(s_pathBlock)); right->setType(ProgressTimer::Type::RADIAL); right->setMidpoint(Vec2(0.75f, 0.25f)); /** - * Note the reverse property (default=NO) is only added to the right image. That's how - * we get a counter clockwise progress. - */ + * Note the reverse property (default=NO) is only added to the right image. That's how + * we get a counter clockwise progress. + */ addChild(right); - right->setPosition(s.width-100, s.height/2); + right->setPosition(s.width - 100, s.height / 2); right->runAction(RepeatForever::create(action->clone())); } @@ -247,7 +243,7 @@ void SpriteProgressBarVarious::onEnter() // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change left->setBarChangeRate(Vec2(1.0f, 0.0f)); addChild(left); - left->setPosition(100, s.height/2); + left->setPosition(100, s.height / 2); left->runAction(RepeatForever::create(to->clone())); auto middle = ProgressTimer::create(Sprite::create(s_pathSister2)); @@ -255,9 +251,9 @@ void SpriteProgressBarVarious::onEnter() // Setup for a bar starting from the bottom since the midpoint is 0 for the y middle->setMidpoint(Vec2(0.5f, 0.5f)); // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change - middle->setBarChangeRate(Vec2(1,1)); + middle->setBarChangeRate(Vec2(1, 1)); addChild(middle); - middle->setPosition(s.width/2, s.height/2); + middle->setPosition(s.width / 2, s.height / 2); middle->runAction(RepeatForever::create(to->clone())); auto right = ProgressTimer::create(Sprite::create(s_pathSister2)); @@ -267,7 +263,7 @@ void SpriteProgressBarVarious::onEnter() // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change right->setBarChangeRate(Vec2(0, 1)); addChild(right); - right->setPosition(s.width-100, s.height/2); + right->setPosition(s.width - 100, s.height / 2); right->runAction(RepeatForever::create(to->clone())); } @@ -287,14 +283,10 @@ void SpriteProgressBarTintAndFade::onEnter() auto s = Director::getInstance()->getWinSize(); - auto to = Sequence::createWithTwoActions(ProgressTo::create(6, 100), ProgressTo::create(0, 0)); - auto tint = Sequence::create(TintTo::create(1, 255, 0, 0), - TintTo::create(1, 0, 255, 0), - TintTo::create(1, 0, 0, 255), - nullptr); - auto fade = Sequence::create(FadeTo::create(1.0f, 0), - FadeTo::create(1.0f, 255), - nullptr); + auto to = Sequence::createWithTwoActions(ProgressTo::create(6, 100), ProgressTo::create(0, 0)); + auto tint = Sequence::create(TintTo::create(1, 255, 0, 0), TintTo::create(1, 0, 255, 0), + TintTo::create(1, 0, 0, 255), nullptr); + auto fade = Sequence::create(FadeTo::create(1.0f, 0), FadeTo::create(1.0f, 255), nullptr); auto left = ProgressTimer::create(Sprite::create(s_pathSister1)); left->setType(ProgressTimer::Type::BAR); @@ -304,7 +296,7 @@ void SpriteProgressBarTintAndFade::onEnter() // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change left->setBarChangeRate(Vec2(1.0f, 0.0f)); addChild(left); - left->setPosition(100, s.height/2); + left->setPosition(100, s.height / 2); left->runAction(RepeatForever::create(to->clone())); left->runAction(RepeatForever::create(tint->clone())); @@ -317,7 +309,7 @@ void SpriteProgressBarTintAndFade::onEnter() // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change middle->setBarChangeRate(Vec2(1, 1)); addChild(middle); - middle->setPosition(s.width/2, s.height/2); + middle->setPosition(s.width / 2, s.height / 2); middle->runAction(RepeatForever::create(to->clone())); middle->runAction(RepeatForever::create(fade->clone())); @@ -330,9 +322,9 @@ void SpriteProgressBarTintAndFade::onEnter() // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change right->setBarChangeRate(Vec2(0, 1)); addChild(right); - right->setPosition(s.width-100, s.height/2); + right->setPosition(s.width - 100, s.height / 2); right->runAction(RepeatForever::create(to->clone())); - right->runAction(RepeatForever::create(tint->clone())); + right->runAction(RepeatForever::create(tint->clone())); right->runAction(RepeatForever::create(fade->clone())); right->addChild(Label::createWithTTF("Tint and Fade", "fonts/Marker Felt.ttf", 20.0f)); @@ -365,7 +357,7 @@ void SpriteProgressWithSpriteFrame::onEnter() // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change left->setBarChangeRate(Vec2(1.0f, 0.0f)); addChild(left); - left->setPosition(100, s.height/2); + left->setPosition(100, s.height / 2); left->runAction(RepeatForever::create(to->clone())); auto middle = ProgressTimer::create(Sprite::createWithSpriteFrameName("grossini_dance_02.png")); @@ -375,7 +367,7 @@ void SpriteProgressWithSpriteFrame::onEnter() // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change middle->setBarChangeRate(Vec2(1, 1)); addChild(middle); - middle->setPosition(s.width/2, s.height/2); + middle->setPosition(s.width / 2, s.height / 2); middle->runAction(RepeatForever::create(to->clone())); auto right = ProgressTimer::create(Sprite::createWithSpriteFrameName("grossini_dance_03.png")); @@ -385,7 +377,7 @@ void SpriteProgressWithSpriteFrame::onEnter() // Setup for a vertical bar since the bar change rate is 0 for x meaning no horizontal change right->setBarChangeRate(Vec2(0, 1)); addChild(right); - right->setPosition(s.width-100, s.height/2); + right->setPosition(s.width - 100, s.height / 2); right->runAction(RepeatForever::create(to->clone())); } diff --git a/tests/cpp-tests/Classes/ActionsProgressTest/ActionsProgressTest.h b/tests/cpp-tests/Classes/ActionsProgressTest/ActionsProgressTest.h index 336fabd2f3e2..5fffe2bb32a4 100644 --- a/tests/cpp-tests/Classes/ActionsProgressTest/ActionsProgressTest.h +++ b/tests/cpp-tests/Classes/ActionsProgressTest/ActionsProgressTest.h @@ -104,4 +104,4 @@ class SpriteProgressWithSpriteFrame : public SpriteDemo virtual std::string subtitle() const override; }; -#endif // _ACTIONS__PROGRESS_TEST_H_ +#endif // _ACTIONS__PROGRESS_TEST_H_ diff --git a/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp b/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp index 03a32b70bea0..23f6b817cd42 100644 --- a/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp +++ b/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp @@ -1,28 +1,28 @@ - /**************************************************************************** - Copyright (c) 2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - 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. - ****************************************************************************/ +/**************************************************************************** +Copyright (c) 2012 cocos2d-x.org +Copyright (c) 2013-2016 Chukong Technologies Inc. +Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +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 "ActionsTest.h" #include "../testResource.h" @@ -110,7 +110,7 @@ void ActionsDemo::onEnter() _grossini = Sprite::create(s_pathGrossini); _grossini->retain(); - _tamara = Sprite::create(s_pathSister1); + _tamara = Sprite::create(s_pathSister1); _tamara->retain(); _kathia = Sprite::create(s_pathSister2); @@ -120,9 +120,12 @@ void ActionsDemo::onEnter() addChild(_tamara, 2); addChild(_kathia, 3); - _grossini->setPosition(VisibleRect::center().x, VisibleRect::bottom().y+VisibleRect::getVisibleRect().size.height/3); - _tamara->setPosition(VisibleRect::center().x, VisibleRect::bottom().y+VisibleRect::getVisibleRect().size.height*2/3); - _kathia->setPosition(VisibleRect::center().x, VisibleRect::bottom().y+VisibleRect::getVisibleRect().size.height/2); + _grossini->setPosition(VisibleRect::center().x, + VisibleRect::bottom().y + VisibleRect::getVisibleRect().size.height / 3); + _tamara->setPosition(VisibleRect::center().x, + VisibleRect::bottom().y + VisibleRect::getVisibleRect().size.height * 2 / 3); + _kathia->setPosition(VisibleRect::center().x, + VisibleRect::bottom().y + VisibleRect::getVisibleRect().size.height / 2); } void ActionsDemo::onExit() @@ -138,29 +141,29 @@ void ActionsDemo::centerSprites(unsigned int numberOfSprites) { auto s = Director::getInstance()->getWinSize(); - if( numberOfSprites == 0 ) + if (numberOfSprites == 0) { _tamara->setVisible(false); _kathia->setVisible(false); _grossini->setVisible(false); - } - else if ( numberOfSprites == 1 ) + } + else if (numberOfSprites == 1) { _tamara->setVisible(false); _kathia->setVisible(false); - _grossini->setPosition(s.width/2, s.height/2); + _grossini->setPosition(s.width / 2, s.height / 2); } - else if( numberOfSprites == 2 ) - { - _kathia->setPosition(s.width/3, s.height/2); - _tamara->setPosition(2*s.width/3, s.height/2); + else if (numberOfSprites == 2) + { + _kathia->setPosition(s.width / 3, s.height / 2); + _tamara->setPosition(2 * s.width / 3, s.height / 2); _grossini->setVisible(false); - } - else if( numberOfSprites == 3 ) + } + else if (numberOfSprites == 3) { - _grossini->setPosition(s.width/2, s.height/2); - _tamara->setPosition(s.width/4, s.height/2); - _kathia->setPosition(3 * s.width/4, s.height/2); + _grossini->setPosition(s.width / 2, s.height / 2); + _tamara->setPosition(s.width / 4, s.height / 2); + _kathia->setPosition(3 * s.width / 4, s.height / 2); } } @@ -168,23 +171,23 @@ void ActionsDemo::alignSpritesLeft(unsigned int numberOfSprites) { auto s = Director::getInstance()->getWinSize(); - if( numberOfSprites == 1 ) + if (numberOfSprites == 1) { _tamara->setVisible(false); _kathia->setVisible(false); - _grossini->setPosition(60, s.height/2); - } - else if( numberOfSprites == 2 ) - { - _kathia->setPosition(60, s.height/3); - _tamara->setPosition(60, 2*s.height/3); - _grossini->setVisible( false ); - } - else if( numberOfSprites == 3 ) + _grossini->setPosition(60, s.height / 2); + } + else if (numberOfSprites == 2) { - _grossini->setPosition(60, s.height/2); - _tamara->setPosition(60, 2*s.height/3); - _kathia->setPosition(60, s.height/3); + _kathia->setPosition(60, s.height / 3); + _tamara->setPosition(60, 2 * s.height / 3); + _grossini->setVisible(false); + } + else if (numberOfSprites == 3) + { + _grossini->setPosition(60, s.height / 2); + _tamara->setPosition(60, 2 * s.height / 3); + _kathia->setPosition(60, s.height / 3); } } @@ -201,13 +204,13 @@ void ActionMove::onEnter() auto s = Director::getInstance()->getWinSize(); - auto actionTo = MoveTo::create(2, Vec2(s.width-40, s.height-40)); - auto actionBy = MoveBy::create(2, Vec2(80.0f,80.0f)); + auto actionTo = MoveTo::create(2, Vec2(s.width - 40, s.height - 40)); + auto actionBy = MoveBy::create(2, Vec2(80.0f, 80.0f)); auto actionByBack = actionBy->reverse(); - _tamara->runAction( actionTo); - _grossini->runAction( Sequence::create(actionBy, actionByBack, nullptr)); - _kathia->runAction(MoveTo::create(1, Vec2(40.0f,40.0f))); + _tamara->runAction(actionTo); + _grossini->runAction(Sequence::create(actionBy, actionByBack, nullptr)); + _kathia->runAction(MoveTo::create(1, Vec2(40.0f, 40.0f))); } std::string ActionMove::subtitle() const @@ -223,18 +226,18 @@ std::string ActionMove::subtitle() const void ActionMove3D::onEnter() { ActionsDemo::onEnter(); - + centerSprites(3); - + auto s = Director::getInstance()->getWinSize(); - - _tamara->setPosition3D(Vec3(s.width-40, s.height-40, 0.0f)); + + _tamara->setPosition3D(Vec3(s.width - 40, s.height - 40, 0.0f)); _kathia->setPosition3D(Vec3(40.0f, 40.0f, 0.0f)); - - auto actionTo = MoveTo::create(2, Vec3(s.width-40, s.height-40, -100.0f)); - auto actionBy = MoveBy::create(2, Vec3(80.0f, 80.0f, -100.0f)); + + auto actionTo = MoveTo::create(2, Vec3(s.width - 40, s.height - 40, -100.0f)); + auto actionBy = MoveBy::create(2, Vec3(80.0f, 80.0f, -100.0f)); auto actionByBack = actionBy->reverse(); - + _tamara->runAction(actionTo); _grossini->runAction(Sequence::create(actionBy, actionByBack, nullptr)); _kathia->runAction(MoveTo::create(1, Vec3(40.0f, 40.0f, -100.0f))); @@ -256,13 +259,13 @@ void ActionScale::onEnter() centerSprites(3); - auto actionTo = ScaleTo::create(2.0f, 0.5f); - auto actionBy = ScaleBy::create(2.0f, 1.0f, 10.0f); + auto actionTo = ScaleTo::create(2.0f, 0.5f); + auto actionBy = ScaleBy::create(2.0f, 1.0f, 10.0f); auto actionBy2 = ScaleBy::create(2.0f, 5.0f, 1.0f); - _grossini->runAction( actionTo); - _tamara->runAction( Sequence::create(actionBy, actionBy->reverse(), nullptr)); - _kathia->runAction( Sequence::create(actionBy2, actionBy2->reverse(), nullptr)); + _grossini->runAction(actionTo); + _tamara->runAction(Sequence::create(actionBy, actionBy->reverse(), nullptr)); + _kathia->runAction(Sequence::create(actionBy2, actionBy2->reverse(), nullptr)); } std::string ActionScale::subtitle() const @@ -281,10 +284,10 @@ void ActionSkew::onEnter() centerSprites(3); - auto actionTo = SkewTo::create(2, 37.2f, -37.2f); + auto actionTo = SkewTo::create(2, 37.2f, -37.2f); auto actionToBack = SkewTo::create(2, 0, 0); - auto actionBy = SkewBy::create(2, 0.0f, -90.0f); - auto actionBy2 = SkewBy::create(2, 45.0f, 45.0f); + auto actionBy = SkewBy::create(2, 0.0f, -90.0f); + auto actionBy2 = SkewBy::create(2, 45.0f, 45.0f); auto actionByBack = actionBy->reverse(); _tamara->runAction(Sequence::create(actionTo, actionToBack, nullptr)); @@ -305,17 +308,17 @@ void ActionRotationalSkew::onEnter() this->centerSprites(3); - auto actionTo = RotateTo::create(2, 180, 180); + auto actionTo = RotateTo::create(2, 180, 180); auto actionToBack = RotateTo::create(2, 0, 0); - auto actionBy = RotateBy::create(2, 0.0f, 360); + auto actionBy = RotateBy::create(2, 0.0f, 360); auto actionByBack = actionBy->reverse(); - auto actionBy2 = RotateBy::create(2, 360, 0); + auto actionBy2 = RotateBy::create(2, 360, 0); auto actionBy2Back = actionBy2->reverse(); - _tamara->runAction( Sequence::create(actionBy, actionByBack, nullptr) ); - _grossini->runAction( Sequence::create(actionTo, actionToBack, nullptr) ); - _kathia->runAction( Sequence::create(actionBy2, actionBy2Back, nullptr) ); + _tamara->runAction(Sequence::create(actionBy, actionByBack, nullptr)); + _grossini->runAction(Sequence::create(actionTo, actionToBack, nullptr)); + _kathia->runAction(Sequence::create(actionBy2, actionBy2Back, nullptr)); } std::string ActionRotationalSkew::subtitle() const @@ -323,9 +326,7 @@ std::string ActionRotationalSkew::subtitle() const return "RotationalSkewTo / RotationalSkewBy"; } - - -//ActionRotationalSkewVSStandardSkew +// ActionRotationalSkewVSStandardSkew void ActionRotationalSkewVSStandardSkew::onEnter() { ActionsDemo::onEnter(); @@ -338,33 +339,33 @@ void ActionRotationalSkewVSStandardSkew::onEnter() Size boxSize(100.0f, 100.0f); - auto box = LayerColor::create(Color4B(255,255,0,255)); - box->setAnchorPoint(Vec2(0.5f,0.5f)); - box->setContentSize( boxSize ); + auto box = LayerColor::create(Color4B(255, 255, 0, 255)); + box->setAnchorPoint(Vec2(0.5f, 0.5f)); + box->setContentSize(boxSize); box->setIgnoreAnchorPointForPosition(false); - box->setPosition(s.width/2, s.height - 100 - box->getContentSize().height/2); + box->setPosition(s.width / 2, s.height - 100 - box->getContentSize().height / 2); this->addChild(box); auto label = Label::createWithTTF("Standard cocos2d Skew", "fonts/Marker Felt.ttf", 16.0f); - label->setPosition(s.width/2, s.height - 100 + label->getContentSize().height); + label->setPosition(s.width / 2, s.height - 100 + label->getContentSize().height); this->addChild(label); - auto actionTo = SkewBy::create(2, 360, 0); + auto actionTo = SkewBy::create(2, 360, 0); auto actionToBack = SkewBy::create(2, -360, 0); box->runAction(Sequence::create(actionTo, actionToBack, nullptr)); - box = LayerColor::create(Color4B(255,255,0,255)); - box->setAnchorPoint(Vec2(0.5f,0.5f)); + box = LayerColor::create(Color4B(255, 255, 0, 255)); + box->setAnchorPoint(Vec2(0.5f, 0.5f)); box->setContentSize(boxSize); box->setIgnoreAnchorPointForPosition(false); - box->setPosition(s.width/2, s.height - 250 - box->getContentSize().height/2); + box->setPosition(s.width / 2, s.height - 250 - box->getContentSize().height / 2); this->addChild(box); label = Label::createWithTTF("Rotational Skew", "fonts/Marker Felt.ttf", 16.0f); - label->setPosition(s.width/2, s.height - 250 + label->getContentSize().height/2); + label->setPosition(s.width / 2, s.height - 250 + label->getContentSize().height / 2); this->addChild(label); - auto actionTo2 = RotateBy::create(2, 360, 0); + auto actionTo2 = RotateBy::create(2, 360, 0); auto actionToBack2 = RotateBy::create(2, -360, 0); box->runAction(Sequence::create(actionTo2, actionToBack2, nullptr)); } @@ -390,7 +391,7 @@ void ActionSkewRotateScale::onEnter() box->setContentSize(boxSize); static float markrside = 10.0f; - auto uL = LayerColor::create(Color4B(255, 0, 0, 255)); + auto uL = LayerColor::create(Color4B(255, 0, 0, 255)); box->addChild(uL); uL->setContentSize(Size(markrside, markrside)); uL->setPosition(0.f, boxSize.height - markrside); @@ -403,13 +404,13 @@ void ActionSkewRotateScale::onEnter() uR->setAnchorPoint(Vec2(0.0f, 0.0f)); addChild(box); - auto actionTo = SkewTo::create(2, 0.f, 2.f); - auto rotateTo = RotateTo::create(2, 61.0f); + auto actionTo = SkewTo::create(2, 0.f, 2.f); + auto rotateTo = RotateTo::create(2, 61.0f); auto actionScaleTo = ScaleTo::create(2, -0.44f, 0.47f); auto actionScaleToBack = ScaleTo::create(2, 1.0f, 1.0f); - auto rotateToBack = RotateTo::create(2, 0); - auto actionToBack = SkewTo::create(2, 0, 0); + auto rotateToBack = RotateTo::create(2, 0); + auto actionToBack = SkewTo::create(2, 0, 0); box->runAction(Sequence::create(actionTo, actionToBack, nullptr)); box->runAction(Sequence::create(rotateTo, rotateToBack, nullptr)); @@ -432,16 +433,16 @@ void ActionRotate::onEnter() centerSprites(3); - auto actionTo = RotateTo::create( 2, 45); - auto actionTo2 = RotateTo::create( 2, -45); - auto actionTo0 = RotateTo::create(2 , 0); - _tamara->runAction( Sequence::create(actionTo, actionTo0, nullptr)); + auto actionTo = RotateTo::create(2, 45); + auto actionTo2 = RotateTo::create(2, -45); + auto actionTo0 = RotateTo::create(2, 0); + _tamara->runAction(Sequence::create(actionTo, actionTo0, nullptr)); - auto actionBy = RotateBy::create(2 , 360); + auto actionBy = RotateBy::create(2, 360); auto actionByBack = actionBy->reverse(); - _grossini->runAction( Sequence::create(actionBy, actionByBack, nullptr)); + _grossini->runAction(Sequence::create(actionBy, actionByBack, nullptr)); - _kathia->runAction( Sequence::create(actionTo2, actionTo0->clone(), nullptr)); + _kathia->runAction(Sequence::create(actionTo2, actionTo0->clone(), nullptr)); } std::string ActionRotate::subtitle() const @@ -462,11 +463,11 @@ void ActionRotateBy3D::onEnter() auto actionBy1 = RotateBy::create(4, Vec3(360.0f, 0.0f, 0.0f)); auto actionBy2 = RotateBy::create(4, Vec3(0.0f, 360.0f, 0.0f)); - auto actionBy3 = RotateBy::create(4 ,Vec3(0.0f, 0.0f, 360.0f)); + auto actionBy3 = RotateBy::create(4, Vec3(0.0f, 0.0f, 360.0f)); - _tamara->runAction( Sequence::create(actionBy1, actionBy1->reverse(), nullptr)); - _grossini->runAction( Sequence::create(actionBy2, actionBy2->reverse(), nullptr)); - _kathia->runAction( Sequence::create(actionBy3, actionBy3->reverse(), nullptr)); + _tamara->runAction(Sequence::create(actionBy1, actionBy1->reverse(), nullptr)); + _grossini->runAction(Sequence::create(actionBy2, actionBy2->reverse(), nullptr)); + _kathia->runAction(Sequence::create(actionBy3, actionBy3->reverse(), nullptr)); } std::string ActionRotateBy3D::subtitle() const @@ -485,14 +486,14 @@ void ActionJump::onEnter() centerSprites(3); - auto actionTo = JumpTo::create(2, Vec2(300,300), 50, 4); - auto actionBy = JumpBy::create(2, Vec2(300,0), 50, 4); - auto actionUp = JumpBy::create(2, Vec2(0,0), 80, 4); + auto actionTo = JumpTo::create(2, Vec2(300, 300), 50, 4); + auto actionBy = JumpBy::create(2, Vec2(300, 0), 50, 4); + auto actionUp = JumpBy::create(2, Vec2(0, 0), 80, 4); auto actionByBack = actionBy->reverse(); - _tamara->runAction( actionTo); - _grossini->runAction( Sequence::create(actionBy, actionByBack, nullptr)); - _kathia->runAction( RepeatForever::create(actionUp)); + _tamara->runAction(actionTo); + _grossini->runAction(Sequence::create(actionBy, actionByBack, nullptr)); + _kathia->runAction(RepeatForever::create(actionUp)); } std::string ActionJump::subtitle() const { @@ -519,32 +520,30 @@ void ActionBezier::onEnter() // sprite 1 ccBezierConfig bezier; - bezier.controlPoint_1 = Vec2(0.0f, s.height/2); - bezier.controlPoint_2 = Vec2(300.0f, -s.height/2); - bezier.endPosition = Vec2(300.0f,100.0f); + bezier.controlPoint_1 = Vec2(0.0f, s.height / 2); + bezier.controlPoint_2 = Vec2(300.0f, -s.height / 2); + bezier.endPosition = Vec2(300.0f, 100.0f); auto bezierForward = BezierBy::create(3, bezier); - auto bezierBack = bezierForward->reverse(); - auto rep = RepeatForever::create(Sequence::create( bezierForward, bezierBack, nullptr)); - + auto bezierBack = bezierForward->reverse(); + auto rep = RepeatForever::create(Sequence::create(bezierForward, bezierBack, nullptr)); // sprite 2 - _tamara->setPosition(80,160); - ccBezierConfig bezier2; - bezier2.controlPoint_1 = Vec2(100.0f, s.height/2); - bezier2.controlPoint_2 = Vec2(200.0f, -s.height/2); - bezier2.endPosition = Vec2(240.0f,160.0f); + _tamara->setPosition(80, 160); + ccBezierConfig bezier2; + bezier2.controlPoint_1 = Vec2(100.0f, s.height / 2); + bezier2.controlPoint_2 = Vec2(200.0f, -s.height / 2); + bezier2.endPosition = Vec2(240.0f, 160.0f); - auto bezierTo1 = BezierTo::create(2, bezier2); + auto bezierTo1 = BezierTo::create(2, bezier2); // sprite 3 - _kathia->setPosition(400,160); + _kathia->setPosition(400, 160); auto bezierTo2 = BezierTo::create(2, bezier2); - _grossini->runAction( rep); + _grossini->runAction(rep); _tamara->runAction(bezierTo1); _kathia->runAction(bezierTo2); - } std::string ActionBezier::subtitle() const @@ -566,11 +565,11 @@ void ActionBlink::onEnter() auto action1 = Blink::create(2, 10); auto action2 = Blink::create(2, 5); - _tamara->runAction( action1); + _tamara->runAction(action1); _kathia->runAction(action2); } -std::string ActionBlink::subtitle() const +std::string ActionBlink::subtitle() const { return "Blink"; } @@ -586,22 +585,22 @@ void ActionFade::onEnter() centerSprites(2); - _tamara->setOpacity( 0 ); - auto action1 = FadeIn::create(1.0f); + _tamara->setOpacity(0); + auto action1 = FadeIn::create(1.0f); auto action1Back = action1->reverse(); - auto action2 = FadeOut::create(1.0f); - auto action2Back = action2->reverse(); - auto action2BackReverse = action2Back->reverse(); + auto action2 = FadeOut::create(1.0f); + auto action2Back = action2->reverse(); + auto action2BackReverse = action2Back->reverse(); auto action2BackReverseReverse = action2BackReverse->reverse(); _tamara->setOpacity(122); - _tamara->runAction( Sequence::create( action1, action1Back, nullptr)); + _tamara->runAction(Sequence::create(action1, action1Back, nullptr)); _kathia->setOpacity(122); - _kathia->runAction( Sequence::create( action2, action2Back,action2BackReverse,action2BackReverseReverse, nullptr)); + _kathia->runAction(Sequence::create(action2, action2Back, action2BackReverse, action2BackReverseReverse, nullptr)); } -std::string ActionFade::subtitle() const +std::string ActionFade::subtitle() const { return "FadeIn / FadeOut"; } @@ -618,15 +617,15 @@ void ActionTint::onEnter() centerSprites(2); - auto action1 = TintTo::create(2, 255, 0, 255); - auto action2 = TintBy::create(2, -127, -255, -127); + auto action1 = TintTo::create(2, 255, 0, 255); + auto action2 = TintBy::create(2, -127, -255, -127); auto action2Back = action2->reverse(); - _tamara->runAction( action1); - _kathia->runAction( Sequence::create( action2, action2Back, nullptr)); + _tamara->runAction(action1); + _kathia->runAction(Sequence::create(action2, action2Back, nullptr)); } -std::string ActionTint::subtitle() const +std::string ActionTint::subtitle() const { return "TintTo / TintBy"; } @@ -646,7 +645,7 @@ void ActionAnimate::onEnter() // Manual animation // auto animation = Animation::create(); - for( int i=1;i<15;i++) + for (int i = 1; i < 15; i++) { char szName[100] = {0}; sprintf(szName, "Images/grossini_dance_%02d.png", i); @@ -658,7 +657,7 @@ void ActionAnimate::onEnter() auto action = Animate::create(animation); _grossini->runAction(Sequence::create(action, action->reverse(), nullptr)); - + // // File animation // @@ -670,10 +669,10 @@ void ActionAnimate::onEnter() auto action2 = Animate::create(animation2); _tamara->runAction(Sequence::create(action2, action2->reverse(), nullptr)); - _frameDisplayedListener = EventListenerCustom::create(AnimationFrameDisplayedNotification, [](EventCustom * event){ + _frameDisplayedListener = EventListenerCustom::create(AnimationFrameDisplayedNotification, [](EventCustom* event) { auto userData = static_cast(event->getUserData()); - - log("target %p with data %s", userData->target, Value(userData->userInfo).getDescription().c_str()); + + log("target %p with data %s", userData->target, Value(userData->userInfo).getDescription().c_str()); }); _eventDispatcher->addEventListenerWithFixedPriority(_frameDisplayedListener, -1); @@ -685,7 +684,6 @@ void ActionAnimate::onEnter() auto animation3 = animation2->clone(); animation3->setLoops(4); - auto action3 = Animate::create(animation3); _kathia->runAction(action3); } @@ -717,10 +715,7 @@ void ActionSequence::onEnter() alignSpritesLeft(1); - auto action = Sequence::create( - MoveBy::create( 2, Vec2(240.0f,0.0f)), - RotateBy::create( 2, 540), - nullptr); + auto action = Sequence::create(MoveBy::create(2, Vec2(240.0f, 0.0f)), RotateBy::create(2, 540), nullptr); _grossini->runAction(action); } @@ -744,40 +739,37 @@ void ActionSequence2::onEnter() _grossini->setVisible(false); auto action = Sequence::create( - Place::create(Vec2(200.0f,200.0f)), - Show::create(), - MoveBy::create(1, Vec2(100.0f,0.0f)), - CallFunc::create( CC_CALLBACK_0(ActionSequence2::callback1,this)), - CallFunc::create( CC_CALLBACK_0(ActionSequence2::callback2,this,_grossini)), - CallFunc::create( CC_CALLBACK_0(ActionSequence2::callback3,this,_grossini,0xbebabeba)), - nullptr); + Place::create(Vec2(200.0f, 200.0f)), Show::create(), MoveBy::create(1, Vec2(100.0f, 0.0f)), + CallFunc::create(CC_CALLBACK_0(ActionSequence2::callback1, this)), + CallFunc::create(CC_CALLBACK_0(ActionSequence2::callback2, this, _grossini)), + CallFunc::create(CC_CALLBACK_0(ActionSequence2::callback3, this, _grossini, 0xbebabeba)), nullptr); _grossini->runAction(action); } void ActionSequence2::callback1() { - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto label = Label::createWithTTF("callback 1 called", "fonts/Marker Felt.ttf", 16.0f); - label->setPosition(s.width/4*1,s.height/2); + label->setPosition(s.width / 4 * 1, s.height / 2); addChild(label); } void ActionSequence2::callback2(Node* sender) { - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto label = Label::createWithTTF("callback 2 called", "fonts/Marker Felt.ttf", 16.0f); - label->setPosition(s.width/4*2,s.height/2); + label->setPosition(s.width / 4 * 2, s.height / 2); addChild(label); } void ActionSequence2::callback3(Node* sender, int32_t data) { - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto label = Label::createWithTTF("callback 3 called", "fonts/Marker Felt.ttf", 16.0f); - label->setPosition(s.width/4*3,s.height/2); + label->setPosition(s.width / 4 * 3, s.height / 2); addChild(label); } @@ -799,7 +791,7 @@ void ActionSequence3::onEnter() alignSpritesLeft(1); // Uses Array API - auto action1 = MoveBy::create(2, Vec2(240.0f,0.0f)); + auto action1 = MoveBy::create(2, Vec2(240.0f, 0.0f)); auto action2 = RotateBy::create(2, 540); auto action3 = action1->reverse(); auto action4 = action2->reverse(); @@ -829,10 +821,8 @@ void ActionCallFuncN::onEnter() centerSprites(1); - auto action = Sequence::create( - MoveBy::create(2.0f, Vec2(150.0f,0.0f)), - CallFuncN::create( CC_CALLBACK_1(ActionCallFuncN::callback, this)), - nullptr); + auto action = Sequence::create(MoveBy::create(2.0f, Vec2(150.0f, 0.0f)), + CallFuncN::create(CC_CALLBACK_1(ActionCallFuncN::callback, this)), nullptr); _grossini->runAction(action); } @@ -847,9 +837,9 @@ std::string ActionCallFuncN::subtitle() const return "Grossini should jump after moving"; } -void ActionCallFuncN::callback(Node* sender ) +void ActionCallFuncN::callback(Node* sender) { - auto a = JumpBy::create(5, Vec2(0,0), 100, 5); + auto a = JumpBy::create(5, Vec2(0, 0), 100, 5); sender->runAction(a); } //------------------------------------------------------------------ @@ -865,9 +855,8 @@ void ActionCallFuncND::onEnter() centerSprites(1); auto action = Sequence::create( - MoveBy::create(2.0f, Vec2(200.0f,0.0f)), - CallFuncN::create( CC_CALLBACK_1(ActionCallFuncND::doRemoveFromParentAndCleanup, this, true)), - nullptr); + MoveBy::create(2.0f, Vec2(200.0f, 0.0f)), + CallFuncN::create(CC_CALLBACK_1(ActionCallFuncND::doRemoveFromParentAndCleanup, this, true)), nullptr); _grossini->runAction(action); } @@ -898,66 +887,59 @@ void ActionCallFunction::onEnter() centerSprites(3); + auto action1 = Sequence::create( + MoveBy::create(2, Vec2(200.0f, 0.0f)), CallFunc::create(std::bind(&ActionCallFunction::callback1, this)), + CallFunc::create( + // lambda + [&]() { + auto s = Director::getInstance()->getWinSize(); + auto label = Label::createWithTTF("called:lambda callback", "fonts/Marker Felt.ttf", 16.0f); + label->setPosition(s.width / 4 * 1, s.height / 2 - 40); + this->addChild(label); + }), + nullptr); + + auto action2 = + Sequence::create(ScaleBy::create(2, 2), FadeOut::create(2), + CallFunc::create(std::bind(&ActionCallFunction::callback2, this, _tamara)), nullptr); - auto action1 = Sequence::create( - MoveBy::create(2, Vec2(200.0f,0.0f)), - CallFunc::create( std::bind(&ActionCallFunction::callback1, this) ), - CallFunc::create( - // lambda - [&](){ - auto s = Director::getInstance()->getWinSize(); - auto label = Label::createWithTTF("called:lambda callback", "fonts/Marker Felt.ttf", 16.0f); - label->setPosition(s.width/4*1,s.height/2-40); - this->addChild(label); - } ), - nullptr); - - auto action2 = Sequence::create( - ScaleBy::create(2 , 2), - FadeOut::create(2), - CallFunc::create( std::bind(&ActionCallFunction::callback2, this, _tamara) ), - nullptr); - - auto action3 = Sequence::create( - RotateBy::create(3 , 360), - FadeOut::create(2), - CallFunc::create( std::bind(&ActionCallFunction::callback3, this, _kathia, 42) ), - nullptr); + auto action3 = + Sequence::create(RotateBy::create(3, 360), FadeOut::create(2), + CallFunc::create(std::bind(&ActionCallFunction::callback3, this, _kathia, 42)), nullptr); _grossini->runAction(action1); _tamara->runAction(action2); _kathia->runAction(action3); } - void ActionCallFunction::callback1() { - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto label = Label::createWithTTF("callback 1 called", "fonts/Marker Felt.ttf", 16.0f); - label->setPosition(s.width/4*1,s.height/2); + label->setPosition(s.width / 4 * 1, s.height / 2); addChild(label); } void ActionCallFunction::callback2(Node* sender) { - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto label = Label::createWithTTF("callback 2 called", "fonts/Marker Felt.ttf", 16.0f); - label->setPosition(s.width/4*2,s.height/2); + label->setPosition(s.width / 4 * 2, s.height / 2); addChild(label); - CCLOG("sender is: %p", sender); + CCLOG("sender is: %p", sender); } void ActionCallFunction::callback3(Node* sender, int32_t data) { - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto label = Label::createWithTTF("callback 3 called", "fonts/Marker Felt.ttf", 16.0f); - label->setPosition(s.width/4*3,s.height/2); + label->setPosition(s.width / 4 * 3, s.height / 2); addChild(label); - CCLOG("target is: %p, data is: %d", sender, data); + CCLOG("target is: %p, data is: %d", sender, data); } std::string ActionCallFunction::subtitle() const @@ -976,10 +958,7 @@ void ActionSpawn::onEnter() alignSpritesLeft(1); - auto action = Spawn::create( - JumpBy::create(2, Vec2(300,0), 50, 4), - RotateBy::create( 2, 720), - nullptr); + auto action = Spawn::create(JumpBy::create(2, Vec2(300, 0), 50, 4), RotateBy::create(2, 720), nullptr); _grossini->runAction(action); } @@ -1001,8 +980,8 @@ void ActionSpawn2::onEnter() alignSpritesLeft(1); - auto action1 = JumpBy::create(2, Vec2(300,0), 50, 4); - auto action2 = RotateBy::create( 2, 720); + auto action1 = JumpBy::create(2, Vec2(300, 0), 50, 4); + auto action2 = RotateBy::create(2, 720); Vector array; array.pushBack(action1); @@ -1028,17 +1007,16 @@ void ActionRepeatForever::onEnter() centerSprites(1); - auto action = Sequence::create( - DelayTime::create(1), - CallFunc::create( std::bind( &ActionRepeatForever::repeatForever, this, _grossini) ), - nullptr); + auto action = + Sequence::create(DelayTime::create(1), + CallFunc::create(std::bind(&ActionRepeatForever::repeatForever, this, _grossini)), nullptr); _grossini->runAction(action); } void ActionRepeatForever::repeatForever(Node* sender) { - auto repeat = RepeatForever::create( RotateBy::create(1.0f, 360) ); + auto repeat = RepeatForever::create(RotateBy::create(1.0f, 360)); sender->runAction(repeat); } @@ -1048,7 +1026,6 @@ std::string ActionRepeatForever::subtitle() const return "CallFuncN + RepeatForever"; } - //------------------------------------------------------------------ // // ActionRotateToRepeat @@ -1060,11 +1037,11 @@ void ActionRotateToRepeat::onEnter() centerSprites(2); - auto act1 = RotateTo::create(1, 90); - auto act2 = RotateTo::create(1, 0); - auto seq = Sequence::create(act1, act2, nullptr); - auto rep1 = RepeatForever::create(seq); - auto rep2 = Repeat::create( seq->clone(), 10); + auto act1 = RotateTo::create(1, 90); + auto act2 = RotateTo::create(1, 0); + auto seq = Sequence::create(act1, act2, nullptr); + auto rep1 = RepeatForever::create(seq); + auto rep2 = Repeat::create(seq->clone(), 10); _tamara->runAction(rep1); _kathia->runAction(rep2); @@ -1086,8 +1063,8 @@ void ActionReverse::onEnter() alignSpritesLeft(1); - auto jump = JumpBy::create(2, Vec2(300,0), 50, 4); - auto action = Sequence::create( jump, jump->reverse(), nullptr); + auto jump = JumpBy::create(2, Vec2(300, 0), 50, 4); + auto action = Sequence::create(jump, jump->reverse(), nullptr); _grossini->runAction(action); } @@ -1097,7 +1074,6 @@ std::string ActionReverse::subtitle() const return "Reverse an action"; } - //------------------------------------------------------------------ // // ActionDelayTime @@ -1109,8 +1085,8 @@ void ActionDelayTime::onEnter() alignSpritesLeft(1); - auto move = MoveBy::create(1, Vec2(150.0f,0.0f)); - auto action = Sequence::create( move, DelayTime::create(2), move, nullptr); + auto move = MoveBy::create(1, Vec2(150.0f, 0.0f)); + auto action = Sequence::create(move, DelayTime::create(2), move, nullptr); _grossini->runAction(action); } @@ -1120,7 +1096,6 @@ std::string ActionDelayTime::subtitle() const return "DelayTime: m + delay + m"; } - //------------------------------------------------------------------ // // ActionReverseSequence @@ -1132,10 +1107,10 @@ void ActionReverseSequence::onEnter() alignSpritesLeft(1); - auto move1 = MoveBy::create(1, Vec2(250.0f,0.0f)); - auto move2 = MoveBy::create(1, Vec2(0.0f,50.0f)); - auto seq = Sequence::create( move1, move2, move1->reverse(), nullptr); - auto action = Sequence::create( seq, seq->reverse(), nullptr); + auto move1 = MoveBy::create(1, Vec2(250.0f, 0.0f)); + auto move2 = MoveBy::create(1, Vec2(0.0f, 50.0f)); + auto seq = Sequence::create(move1, move2, move1->reverse(), nullptr); + auto action = Sequence::create(seq, seq->reverse(), nullptr); _grossini->runAction(action); } @@ -1145,7 +1120,6 @@ std::string ActionReverseSequence::subtitle() const return "Reverse a sequence"; } - //------------------------------------------------------------------ // // ActionReverseSequence2 @@ -1157,27 +1131,25 @@ void ActionReverseSequence2::onEnter() alignSpritesLeft(2); - // Test: // Sequence should work both with IntervalAction and InstantActions - auto move1 = MoveBy::create(1, Vec2(250.0f,0.0f)); - auto move2 = MoveBy::create(1, Vec2(0.0f,50.0f)); - auto tog1 = ToggleVisibility::create(); - auto tog2 = ToggleVisibility::create(); - auto seq = Sequence::create( move1, tog1, move2, tog2, move1->reverse(), nullptr); - auto action = Repeat::create(Sequence::create( seq, seq->reverse(), nullptr), 3); - + auto move1 = MoveBy::create(1, Vec2(250.0f, 0.0f)); + auto move2 = MoveBy::create(1, Vec2(0.0f, 50.0f)); + auto tog1 = ToggleVisibility::create(); + auto tog2 = ToggleVisibility::create(); + auto seq = Sequence::create(move1, tog1, move2, tog2, move1->reverse(), nullptr); + auto action = Repeat::create(Sequence::create(seq, seq->reverse(), nullptr), 3); // Test: // Also test that the reverse of Hide is Show, and vice-versa _kathia->runAction(action); - auto move_tamara = MoveBy::create(1, Vec2(100.0f,0.0f)); - auto move_tamara2 = MoveBy::create(1, Vec2(50.0f,0.0f)); - auto hide = Hide::create(); - auto seq_tamara = Sequence::create( move_tamara, hide, move_tamara2, nullptr); - auto seq_back = seq_tamara->reverse(); - _tamara->runAction( Sequence::create( seq_tamara, seq_back, nullptr)); + auto move_tamara = MoveBy::create(1, Vec2(100.0f, 0.0f)); + auto move_tamara2 = MoveBy::create(1, Vec2(50.0f, 0.0f)); + auto hide = Hide::create(); + auto seq_tamara = Sequence::create(move_tamara, hide, move_tamara2, nullptr); + auto seq_back = seq_tamara->reverse(); + _tamara->runAction(Sequence::create(seq_tamara, seq_back, nullptr)); } std::string ActionReverseSequence2::subtitle() const { @@ -1195,14 +1167,9 @@ void ActionRepeat::onEnter() alignSpritesLeft(2); - - auto a1 = MoveBy::create(1, Vec2(150.0f,0.0f)); - auto action1 = Repeat::create( - Sequence::create( Place::create(Vec2(60.0f,60.0f)), a1, nullptr) , - 3); - auto action2 = RepeatForever::create( - Sequence::create(a1->clone(), a1->reverse(), nullptr) - ); + auto a1 = MoveBy::create(1, Vec2(150.0f, 0.0f)); + auto action1 = Repeat::create(Sequence::create(Place::create(Vec2(60.0f, 60.0f)), a1, nullptr), 3); + auto action2 = RepeatForever::create(Sequence::create(a1->clone(), a1->reverse(), nullptr)); _kathia->runAction(action1); _tamara->runAction(action2); @@ -1225,41 +1192,32 @@ void ActionOrbit::onEnter() Director::getInstance()->setProjection(Director::Projection::_2D); centerSprites(3); - auto orbit1 = OrbitCamera::create(2,1, 0, 0, 180, 0, 0); - auto action1 = Sequence::create( - orbit1, - orbit1->reverse(), - nullptr); + auto orbit1 = OrbitCamera::create(2, 1, 0, 0, 180, 0, 0); + auto action1 = Sequence::create(orbit1, orbit1->reverse(), nullptr); - auto orbit2 = OrbitCamera::create(2,1, 0, 0, 180, -45, 0); - auto action2 = Sequence::create( - orbit2, - orbit2->reverse(), - nullptr); + auto orbit2 = OrbitCamera::create(2, 1, 0, 0, 180, -45, 0); + auto action2 = Sequence::create(orbit2, orbit2->reverse(), nullptr); - auto orbit3 = OrbitCamera::create(2,1, 0, 0, 180, 90, 0); - auto action3 = Sequence::create( - orbit3, - orbit3->reverse(), - nullptr); + auto orbit3 = OrbitCamera::create(2, 1, 0, 0, 180, 90, 0); + auto action3 = Sequence::create(orbit3, orbit3->reverse(), nullptr); _kathia->runAction(RepeatForever::create(action1)); _tamara->runAction(RepeatForever::create(action2)); _grossini->runAction(RepeatForever::create(action3)); - auto move = MoveBy::create(3, Vec2(100.0f,-100.0f)); + auto move = MoveBy::create(3, Vec2(100.0f, -100.0f)); auto move_back = move->reverse(); - auto seq = Sequence::create(move, move_back, nullptr); - auto rfe = RepeatForever::create(seq); + auto seq = Sequence::create(move, move_back, nullptr); + auto rfe = RepeatForever::create(seq); _kathia->runAction(rfe); - _tamara->runAction(rfe->clone() ); - _grossini->runAction( rfe->clone() ); + _tamara->runAction(rfe->clone()); + _grossini->runAction(rfe->clone()); } void ActionOrbit::onExit() { ActionsDemo::onExit(); - + Director::getInstance()->setProjection(Director::Projection::DEFAULT); } @@ -1281,19 +1239,19 @@ void ActionFollow::onEnter() auto s = Director::getInstance()->getWinSize(); DrawNode* drawNode = DrawNode::create(); - float x = s.width*2 - 100; - float y = s.height; - - Vec2 vertices[] = { Vec2(5.0f,5.0f), Vec2(x-5,5.0f), Vec2(x-5,y-5), Vec2(5.0f,y-5) }; - drawNode->drawPoly(vertices, 4, true, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); - + float x = s.width * 2 - 100; + float y = s.height; + + Vec2 vertices[] = {Vec2(5.0f, 5.0f), Vec2(x - 5, 5.0f), Vec2(x - 5, y - 5), Vec2(5.0f, y - 5)}; + drawNode->drawPoly(vertices, 4, true, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); + this->addChild(drawNode); _grossini->setPosition(-200.0f, s.height / 2); - auto move = MoveBy::create(2, Vec2(s.width * 3, 0.0f)); + auto move = MoveBy::create(2, Vec2(s.width * 3, 0.0f)); auto move_back = move->reverse(); - auto seq = Sequence::create(move, move_back, nullptr); - auto rep = RepeatForever::create(seq); + auto seq = Sequence::create(move, move_back, nullptr); + auto rep = RepeatForever::create(seq); _grossini->runAction(rep); @@ -1313,31 +1271,32 @@ std::string ActionFollow::subtitle() const void ActionFollowWithOffset::onEnter() { ActionsDemo::onEnter(); - + centerSprites(1); auto s = Director::getInstance()->getWinSize(); - + DrawNode* drawNode = DrawNode::create(); - float x = s.width*2 - 100; - float y = s.height; - - Vec2 vertices[] = { Vec2(5.0f,5.0f), Vec2(x-5,5.0f), Vec2(x-5,y-5), Vec2(5.0f,y-5) }; - drawNode->drawPoly(vertices, 4, true, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); - + float x = s.width * 2 - 100; + float y = s.height; + + Vec2 vertices[] = {Vec2(5.0f, 5.0f), Vec2(x - 5, 5.0f), Vec2(x - 5, y - 5), Vec2(5.0f, y - 5)}; + drawNode->drawPoly(vertices, 4, true, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); + this->addChild(drawNode); - + _grossini->setPosition(-200, s.height / 2); - auto move = MoveBy::create(2, Vec2(s.width * 3, 1.0f)); + auto move = MoveBy::create(2, Vec2(s.width * 3, 1.0f)); auto move_back = move->reverse(); - auto seq = Sequence::create(move, move_back, nullptr); - auto rep = RepeatForever::create(seq); - + auto seq = Sequence::create(move, move_back, nullptr); + auto rep = RepeatForever::create(seq); + _grossini->runAction(rep); - - //sample offset values set - float verticalOffset = -900; + + // sample offset values set + float verticalOffset = -900; float horizontalOffset = 200; - this->runAction(Follow::createWithOffset(_grossini, horizontalOffset,verticalOffset,Rect(0.0f, 0.0f, s.width * 2 - 100, s.height))); + this->runAction(Follow::createWithOffset(_grossini, horizontalOffset, verticalOffset, + Rect(0.0f, 0.0f, s.width * 2 - 100, s.height))); } std::string ActionFollowWithOffset::subtitle() const @@ -1345,22 +1304,20 @@ std::string ActionFollowWithOffset::subtitle() const return "Follow action with horizontal and vertical offset"; } - void ActionTargeted::onEnter() { ActionsDemo::onEnter(); centerSprites(2); - - auto jump1 = JumpBy::create(2,Vec2::ZERO,100,3); + auto jump1 = JumpBy::create(2, Vec2::ZERO, 100, 3); auto jump2 = jump1->clone(); - auto rot1 = RotateBy::create(1, 360); - auto rot2 = rot1->clone(); + auto rot1 = RotateBy::create(1, 360); + auto rot2 = rot1->clone(); auto t1 = TargetedAction::create(_kathia, jump2); auto t2 = TargetedAction::create(_kathia, rot2); - auto seq = Sequence::create(jump1, t1, rot1, t2, nullptr); + auto seq = Sequence::create(jump1, t1, rot1, t2, nullptr); auto always = RepeatForever::create(seq); _tamara->runAction(always); @@ -1376,24 +1333,22 @@ std::string ActionTargeted::subtitle() const return "Action that runs on another target. Useful for sequences"; } - void ActionTargetedReverse::onEnter() { ActionsDemo::onEnter(); centerSprites(2); - - - auto jump1 = JumpBy::create(2,Vec2::ZERO,100,3); + + auto jump1 = JumpBy::create(2, Vec2::ZERO, 100, 3); auto jump2 = jump1->clone(); - auto rot1 = RotateBy::create(1, 360); - auto rot2 = rot1->clone(); - + auto rot1 = RotateBy::create(1, 360); + auto rot2 = rot1->clone(); + auto t1 = TargetedAction::create(_kathia, jump2); auto t2 = TargetedAction::create(_kathia, rot2); - - auto seq = Sequence::create(jump1, t1->reverse(), rot1, t2->reverse(), nullptr); + + auto seq = Sequence::create(jump1, t1->reverse(), rot1, t2->reverse(), nullptr); auto always = RepeatForever::create(seq); - + _tamara->runAction(always); } @@ -1412,15 +1367,15 @@ std::string ActionTargetedReverse::subtitle() const void ActionStacked::onEnter() { ActionsDemo::onEnter(); - + this->centerSprites(0); - - auto listener = EventListenerTouchAllAtOnce::create(); + + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesEnded = CC_CALLBACK_2(ActionStacked::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - + auto s = Director::getInstance()->getWinSize(); - this->addNewSpriteWithCoords(Vec2(s.width/2, s.height/2)); + this->addNewSpriteWithCoords(Vec2(s.width / 2, s.height / 2)); } void ActionStacked::addNewSpriteWithCoords(Vec2 p) @@ -1428,27 +1383,28 @@ void ActionStacked::addNewSpriteWithCoords(Vec2 p) int idx = static_cast(CCRANDOM_0_1() * 1400 / 100); float w = 85.0f; float h = 121.0f; - float x = (idx%5) * w; - float y = (idx/5) * h; - - auto sprite = Sprite::create("Images/grossini_dance_atlas.png", Rect(x,y,w,h)); - + float x = (idx % 5) * w; + float y = (idx / 5) * h; + + auto sprite = Sprite::create("Images/grossini_dance_atlas.png", Rect(x, y, w, h)); + sprite->setPosition(p); this->addChild(sprite); - + this->runActionsInSprite(sprite); } -void ActionStacked::runActionsInSprite(Sprite *sprite) +void ActionStacked::runActionsInSprite(Sprite* sprite) { // override me } void ActionStacked::onTouchesEnded(const std::vector& touches, Event* event) { - for ( auto &touch: touches ) { + for (auto& touch : touches) + { auto location = touch->getLocation(); - addNewSpriteWithCoords( location ); + addNewSpriteWithCoords(location); } } @@ -1464,25 +1420,16 @@ std::string ActionStacked::subtitle() const // ActionMoveStacked - -void ActionMoveStacked::runActionsInSprite(Sprite *sprite) +void ActionMoveStacked::runActionsInSprite(Sprite* sprite) { - sprite->runAction( - RepeatForever::create( - Sequence::create( - MoveBy::create(0.05f, Vec2(10.0f,10.0f)), - MoveBy::create(0.05f, Vec2(-10.0f,-10.0f)), - nullptr))); - - auto action = MoveBy::create(2.0f, Vec2(400.0f,0.0f)); + sprite->runAction(RepeatForever::create(Sequence::create(MoveBy::create(0.05f, Vec2(10.0f, 10.0f)), + MoveBy::create(0.05f, Vec2(-10.0f, -10.0f)), nullptr))); + + auto action = MoveBy::create(2.0f, Vec2(400.0f, 0.0f)); auto action_back = action->reverse(); - - sprite->runAction( - RepeatForever::create( - Sequence::create(action, action_back, nullptr) - )); -} + sprite->runAction(RepeatForever::create(Sequence::create(action, action_back, nullptr))); +} std::string ActionMoveStacked::title() const { @@ -1491,22 +1438,15 @@ std::string ActionMoveStacked::title() const // ActionMoveJumpStacked -void ActionMoveJumpStacked::runActionsInSprite(Sprite *sprite) +void ActionMoveJumpStacked::runActionsInSprite(Sprite* sprite) { - sprite->runAction( - RepeatForever::create( - Sequence::create( - MoveBy::create(0.05f, Vec2(10,2)), - MoveBy::create(0.05f, Vec2(-10,-2)), - nullptr))); - - auto jump = JumpBy::create(2.0f, Vec2(400,0), 100, 5); + sprite->runAction(RepeatForever::create( + Sequence::create(MoveBy::create(0.05f, Vec2(10, 2)), MoveBy::create(0.05f, Vec2(-10, -2)), nullptr))); + + auto jump = JumpBy::create(2.0f, Vec2(400, 0), 100, 5); auto jump_back = jump->reverse(); - - sprite->runAction( - RepeatForever::create( - Sequence::create(jump, jump_back, nullptr) - )); + + sprite->runAction(RepeatForever::create(Sequence::create(jump, jump_back, nullptr))); } std::string ActionMoveJumpStacked::title() const @@ -1516,28 +1456,24 @@ std::string ActionMoveJumpStacked::title() const // ActionMoveBezierStacked -void ActionMoveBezierStacked::runActionsInSprite(Sprite *sprite) +void ActionMoveBezierStacked::runActionsInSprite(Sprite* sprite) { auto s = Director::getInstance()->getWinSize(); - + // sprite 1 ccBezierConfig bezier; - bezier.controlPoint_1 = Vec2(0.0f, s.height/2); - bezier.controlPoint_2 = Vec2(300.0f, -s.height/2); - bezier.endPosition = Vec2(300.0f,100.0f); - + bezier.controlPoint_1 = Vec2(0.0f, s.height / 2); + bezier.controlPoint_2 = Vec2(300.0f, -s.height / 2); + bezier.endPosition = Vec2(300.0f, 100.0f); + auto bezierForward = BezierBy::create(3, bezier); - auto bezierBack = bezierForward->reverse(); - auto seq = Sequence::create(bezierForward, bezierBack, nullptr); - auto rep = RepeatForever::create(seq); + auto bezierBack = bezierForward->reverse(); + auto seq = Sequence::create(bezierForward, bezierBack, nullptr); + auto rep = RepeatForever::create(seq); sprite->runAction(rep); - - sprite->runAction( - RepeatForever::create( - Sequence::create( - MoveBy::create(0.05f, Vec2(10.0f,0.0f)), - MoveBy::create(0.05f, Vec2(-10.0f,0.0f)), - nullptr))); + + sprite->runAction(RepeatForever::create(Sequence::create(MoveBy::create(0.05f, Vec2(10.0f, 0.0f)), + MoveBy::create(0.05f, Vec2(-10.0f, 0.0f)), nullptr))); } std::string ActionMoveBezierStacked::title() const @@ -1545,92 +1481,81 @@ std::string ActionMoveBezierStacked::title() const return "Stacked Move + Bezier actions"; } - // ActionCatmullRomStacked void ActionCatmullRomStacked::onEnter() { ActionsDemo::onEnter(); - + this->centerSprites(2); - + auto s = Director::getInstance()->getWinSize(); - + // // sprite 1 (By) // // startPosition can be any coordinate, but since the movement // is relative to the Catmull Rom curve, it is better to start with (0,0). // - - _tamara->setPosition(50,50); - + + _tamara->setPosition(50, 50); + auto array = PointArray::create(20); - - array->addControlPoint(Vec2(0.0f,0.0f)); - array->addControlPoint(Vec2(80.0f,80.0f)); - array->addControlPoint(Vec2(s.width-80,80.0f)); - array->addControlPoint(Vec2(s.width-80,s.height-80.0f)); - array->addControlPoint(Vec2(80.0f,s.height-80.0f)); - array->addControlPoint(Vec2(80.0f,80.0f)); - array->addControlPoint(Vec2(s.width/2, s.height/2)); - - auto action = CatmullRomBy::create(3, array); + + array->addControlPoint(Vec2(0.0f, 0.0f)); + array->addControlPoint(Vec2(80.0f, 80.0f)); + array->addControlPoint(Vec2(s.width - 80, 80.0f)); + array->addControlPoint(Vec2(s.width - 80, s.height - 80.0f)); + array->addControlPoint(Vec2(80.0f, s.height - 80.0f)); + array->addControlPoint(Vec2(80.0f, 80.0f)); + array->addControlPoint(Vec2(s.width / 2, s.height / 2)); + + auto action = CatmullRomBy::create(3, array); auto reverse = action->reverse(); - + auto seq = Sequence::create(action, reverse, nullptr); - + _tamara->runAction(seq); - - _tamara->runAction( - RepeatForever::create( - Sequence::create( - MoveBy::create(0.05f, Vec2(10.0f,0.0f)), - MoveBy::create(0.05f, Vec2(-10.0f,0.0f)), - nullptr))); - + + _tamara->runAction(RepeatForever::create(Sequence::create(MoveBy::create(0.05f, Vec2(10.0f, 0.0f)), + MoveBy::create(0.05f, Vec2(-10.0f, 0.0f)), nullptr))); + auto drawNode1 = DrawNode::create(); - drawNode1->setPosition(Vec2(50.0f,50.0f)); + drawNode1->setPosition(Vec2(50.0f, 50.0f)); drawNode1->drawCatmullRom(array, 50, Color4F(1.0f, 1.0f, 0.0f, 0.5f)); this->addChild(drawNode1); - + // // sprite 2 (To) // // The startPosition is not important here, because it uses a "To" action. // The initial position will be the 1st point of the Catmull Rom path // - + auto array2 = PointArray::create(20); - - array2->addControlPoint(Vec2(s.width/2, 30.0f)); - array2->addControlPoint(Vec2(s.width-80,30.0f)); - array2->addControlPoint(Vec2(s.width-80.0f,s.height-80.0f)); - array2->addControlPoint(Vec2(s.width/2,s.height-80.0f)); - array2->addControlPoint(Vec2(s.width/2, 30.0f)); - - auto action2 = CatmullRomTo::create(3, array2); + + array2->addControlPoint(Vec2(s.width / 2, 30.0f)); + array2->addControlPoint(Vec2(s.width - 80, 30.0f)); + array2->addControlPoint(Vec2(s.width - 80.0f, s.height - 80.0f)); + array2->addControlPoint(Vec2(s.width / 2, s.height - 80.0f)); + array2->addControlPoint(Vec2(s.width / 2, 30.0f)); + + auto action2 = CatmullRomTo::create(3, array2); auto reverse2 = action2->reverse(); - + auto seq2 = Sequence::create(action2, reverse2, nullptr); - + _kathia->runAction(seq2); - - _kathia->runAction( - RepeatForever::create( - Sequence::create( - MoveBy::create(0.05f, Vec2(10.0f,0.0f)), - MoveBy::create(0.05f, Vec2(-10.0f,0.0f)), - nullptr))); - + + _kathia->runAction(RepeatForever::create(Sequence::create(MoveBy::create(0.05f, Vec2(10.0f, 0.0f)), + MoveBy::create(0.05f, Vec2(-10.0f, 0.0f)), nullptr))); + auto drawNode2 = DrawNode::create(); drawNode2->drawCatmullRom(array2, 50, Color4F(1.0, 0.0, 0.0, 0.5)); this->addChild(drawNode2); } -ActionCatmullRomStacked::~ActionCatmullRomStacked() -{ -} +ActionCatmullRomStacked::~ActionCatmullRomStacked() {} std::string ActionCatmullRomStacked::title() const { @@ -1642,83 +1567,71 @@ std::string ActionCatmullRomStacked::subtitle() const return "MoveBy + CatmullRom at the same time in the same sprite"; } - // ActionCardinalSplineStacked void ActionCardinalSplineStacked::onEnter() { ActionsDemo::onEnter(); - + this->centerSprites(2); - + auto s = Director::getInstance()->getWinSize(); - + auto array = PointArray::create(20); - + array->addControlPoint(Vec2(0.0f, 0.0f)); - array->addControlPoint(Vec2(s.width/2-30,0.0f)); - array->addControlPoint(Vec2(s.width/2-30,s.height-80.0f)); - array->addControlPoint(Vec2(0.0f, s.height-80.0f)); + array->addControlPoint(Vec2(s.width / 2 - 30, 0.0f)); + array->addControlPoint(Vec2(s.width / 2 - 30, s.height - 80.0f)); + array->addControlPoint(Vec2(0.0f, s.height - 80.0f)); array->addControlPoint(Vec2(0.0f, 0.0f)); - - + // // sprite 1 (By) // // Spline with no tension (tension==0) // - auto action = CardinalSplineBy::create(3, array, 0); + auto action = CardinalSplineBy::create(3, array, 0); auto reverse = action->reverse(); - + auto seq = Sequence::create(action, reverse, nullptr); - - _tamara->setPosition(50,50); + + _tamara->setPosition(50, 50); _tamara->runAction(seq); - - _tamara->runAction( - RepeatForever::create( - Sequence::create( - MoveBy::create(0.05f, Vec2(10.0f,0.0f)), - MoveBy::create(0.05f, Vec2(-10.0f,0.0f)), - nullptr))); - + + _tamara->runAction(RepeatForever::create(Sequence::create(MoveBy::create(0.05f, Vec2(10.0f, 0.0f)), + MoveBy::create(0.05f, Vec2(-10.0f, 0.0f)), nullptr))); + auto drawNode1 = DrawNode::create(); - drawNode1->setPosition(Vec2(50.0f,50.0f)); + drawNode1->setPosition(Vec2(50.0f, 50.0f)); drawNode1->drawCardinalSpline(array, 0, 100, Color4F(1.0f, 0.0f, 1.0f, 1.0f)); this->addChild(drawNode1); - + // // sprite 2 (By) // // Spline with high tension (tension==1) // - - auto *action2 = CardinalSplineBy::create(3, array, 1); + + auto* action2 = CardinalSplineBy::create(3, array, 1); auto reverse2 = action2->reverse(); - + auto seq2 = Sequence::create(action2, reverse2, nullptr); - - _kathia->setPosition(s.width/2,50); - + + _kathia->setPosition(s.width / 2, 50); + _kathia->runAction(seq2); - - _kathia->runAction( - RepeatForever::create( - Sequence::create( - MoveBy::create(0.05f, Vec2(10.0f,0.0f)), - MoveBy::create(0.05f, Vec2(-10.0f,0.0f)), - nullptr))); - + + _kathia->runAction(RepeatForever::create(Sequence::create(MoveBy::create(0.05f, Vec2(10.0f, 0.0f)), + MoveBy::create(0.05f, Vec2(-10.0f, 0.0f)), nullptr))); + auto drawNode2 = DrawNode::create(); - drawNode2->setPosition(Vec2(s.width/2,50.0f)); + drawNode2->setPosition(Vec2(s.width / 2, 50.0f)); drawNode2->drawCardinalSpline(array, 1, 100, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); this->addChild(drawNode2); } -ActionCardinalSplineStacked::~ActionCardinalSplineStacked() -{ -} +ActionCardinalSplineStacked::~ActionCardinalSplineStacked() {} std::string ActionCardinalSplineStacked::title() const { @@ -1740,11 +1653,12 @@ void Issue1305::onEnter() _spriteTmp->runAction(CallFunc::create(std::bind(&Issue1305::log, this, _spriteTmp))); _spriteTmp->retain(); - scheduleOnce([&](float dt) { - _spriteTmp->setPosition(250,250); - addChild(_spriteTmp); - },2 ,"update_key"); - + scheduleOnce( + [&](float dt) { + _spriteTmp->setPosition(250, 250); + addChild(_spriteTmp); + }, + 2, "update_key"); } void Issue1305::log(Node* sender) @@ -1775,10 +1689,10 @@ void Issue1305_2::onEnter() centerSprites(0); auto spr = Sprite::create("Images/grossini.png"); - spr->setPosition(200,200); + spr->setPosition(200, 200); addChild(spr); - auto act1 = MoveBy::create(2 ,Vec2(0.0f, 100.0f)); + auto act1 = MoveBy::create(2, Vec2(0.0f, 100.0f)); /* c++ can't support block, so we use CallFuncN instead. id act2 = [CallBlock actionWithBlock:^{ NSLog(@"1st block"); @@ -1797,19 +1711,18 @@ void Issue1305_2::onEnter() }); */ - auto act2 = CallFunc::create( std::bind( &Issue1305_2::printLog1, this)); + auto act2 = CallFunc::create(std::bind(&Issue1305_2::printLog1, this)); auto act3 = MoveBy::create(2, Vec2(0.0f, -100.0f)); - auto act4 = CallFunc::create( std::bind( &Issue1305_2::printLog2, this)); + auto act4 = CallFunc::create(std::bind(&Issue1305_2::printLog2, this)); auto act5 = MoveBy::create(2, Vec2(100.0f, -100.0f)); - auto act6 = CallFunc::create( std::bind( &Issue1305_2::printLog3, this)); + auto act6 = CallFunc::create(std::bind(&Issue1305_2::printLog3, this)); auto act7 = MoveBy::create(2, Vec2(-100.0f, 0.0f)); - auto act8 = CallFunc::create( std::bind( &Issue1305_2::printLog4, this)); + auto act8 = CallFunc::create(std::bind(&Issue1305_2::printLog4, this)); auto actF = Sequence::create(act1, act2, act3, act4, act5, act6, act7, act8, nullptr); // [spr runAction:actF); - Director::getInstance()->getActionManager()->addAction(actF ,spr, false); - + Director::getInstance()->getActionManager()->addAction(actF, spr, false); } void Issue1305_2::printLog1() @@ -1892,7 +1805,6 @@ std::string Issue1288_2::subtitle() const return "Sprite should move 100 pixels, and stay there"; } - void Issue1327::onEnter() { ActionsDemo::onEnter(); @@ -1902,15 +1814,15 @@ void Issue1327::onEnter() spr->setPosition(100, 100); addChild(spr); - auto act1 = CallFunc::create( std::bind(&Issue1327::logSprRotation, this, spr)); + auto act1 = CallFunc::create(std::bind(&Issue1327::logSprRotation, this, spr)); auto act2 = RotateBy::create(0.25, 45); - auto act3 = CallFunc::create( std::bind(&Issue1327::logSprRotation, this, spr)); + auto act3 = CallFunc::create(std::bind(&Issue1327::logSprRotation, this, spr)); auto act4 = RotateBy::create(0.25, 45); - auto act5 = CallFunc::create( std::bind(&Issue1327::logSprRotation, this, spr)); + auto act5 = CallFunc::create(std::bind(&Issue1327::logSprRotation, this, spr)); auto act6 = RotateBy::create(0.25, 45); - auto act7 = CallFunc::create( std::bind(&Issue1327::logSprRotation, this, spr)); + auto act7 = CallFunc::create(std::bind(&Issue1327::logSprRotation, this, spr)); auto act8 = RotateBy::create(0.25, 45); - auto act9 = CallFunc::create( std::bind(&Issue1327::logSprRotation, this, spr)); + auto act9 = CallFunc::create(std::bind(&Issue1327::logSprRotation, this, spr)); auto actF = Sequence::create(act1, act2, act3, act4, act5, act6, act7, act8, act9, nullptr); spr->runAction(actF); @@ -1931,7 +1843,7 @@ void Issue1327::logSprRotation(Sprite* sender) log("%f", sender->getRotation()); } -//Issue1398 +// Issue1398 void Issue1398::incrementInteger() { _testInteger++; @@ -1947,16 +1859,14 @@ void Issue1398::onEnter() log("testInt = %d", _testInteger); this->runAction( - Sequence::create( - CallFunc::create( std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"1")), - CallFunc::create( std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"2")), - CallFunc::create( std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"3")), - CallFunc::create( std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"4")), - CallFunc::create( std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"5")), - CallFunc::create( std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"6")), - CallFunc::create( std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"7")), - CallFunc::create( std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"8")), - nullptr)); + Sequence::create(CallFunc::create(std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"1")), + CallFunc::create(std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"2")), + CallFunc::create(std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"3")), + CallFunc::create(std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"4")), + CallFunc::create(std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"5")), + CallFunc::create(std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"6")), + CallFunc::create(std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"7")), + CallFunc::create(std::bind(&Issue1398::incrementIntegerCallback, this, (void*)"8")), nullptr)); } void Issue1398::incrementIntegerCallback(void* data) @@ -1979,22 +1889,16 @@ void Issue2599::onEnter() { ActionsDemo::onEnter(); this->centerSprites(0); - + _count = 0; log("before: count = %d", _count); - + log("start count up 50 times using Repeat action"); - auto delay = 1.0f / 50; + auto delay = 1.0f / 50; auto repeatAction = Repeat::create( - Sequence::createWithTwoActions( - CallFunc::create([&](){ this->_count++; }), - DelayTime::create(delay)), - 50); - this->runAction( - Sequence::createWithTwoActions( - repeatAction, - CallFunc::create([&]() { log("after: count = %d", this->_count); }) - )); + Sequence::createWithTwoActions(CallFunc::create([&]() { this->_count++; }), DelayTime::create(delay)), 50); + this->runAction(Sequence::createWithTwoActions( + repeatAction, CallFunc::create([&]() { log("after: count = %d", this->_count); }))); } std::string Issue2599::subtitle() const @@ -2012,22 +1916,22 @@ std::string Issue2599::title() const void ActionCatmullRom::onEnter() { ActionsDemo::onEnter(); - + this->centerSprites(2); - + auto s = Director::getInstance()->getWinSize(); - + // // sprite 1 (By) // // startPosition can be any coordinate, but since the movement // is relative to the Catmull Rom curve, it is better to start with (0,0). // - + _tamara->setPosition(50, 50); - + auto array = PointArray::create(20); - + array->addControlPoint(Vec2(0.0f, 0.0f)); array->addControlPoint(Vec2(80.0f, 80.0f)); array->addControlPoint(Vec2(s.width - 80, 80.0f)); @@ -2035,49 +1939,47 @@ void ActionCatmullRom::onEnter() array->addControlPoint(Vec2(80.0f, s.height - 80.0f)); array->addControlPoint(Vec2(80.0f, 80.0f)); array->addControlPoint(Vec2(s.width / 2, s.height / 2)); - - auto action = CatmullRomBy::create(3, array); + + auto action = CatmullRomBy::create(3, array); auto reverse = action->reverse(); - + auto seq = Sequence::create(action, reverse, nullptr); - + _tamara->runAction(seq); - + auto drawNode1 = DrawNode::create(); - drawNode1->setPosition(Vec2(50.0f,50.0f)); + drawNode1->setPosition(Vec2(50.0f, 50.0f)); drawNode1->drawCatmullRom(array, 50, Color4F(1.0f, 0.0f, 1.0f, 1.0f)); this->addChild(drawNode1); - + // // sprite 2 (To) // // The startPosition is not important here, because it uses a "To" action. // The initial position will be the 1st point of the Catmull Rom path - // - + // + auto array2 = PointArray::create(20); - + array2->addControlPoint(Vec2(s.width / 2, 30.0f)); - array2->addControlPoint(Vec2(s.width -80, 30.0f)); + array2->addControlPoint(Vec2(s.width - 80, 30.0f)); array2->addControlPoint(Vec2(s.width - 80, s.height - 80)); array2->addControlPoint(Vec2(s.width / 2, s.height - 80)); array2->addControlPoint(Vec2(s.width / 2, 30.0f)); - - auto action2 = CatmullRomTo::create(3, array2); + + auto action2 = CatmullRomTo::create(3, array2); auto reverse2 = action2->reverse(); - + auto seq2 = Sequence::create(action2, reverse2, nullptr); - + _kathia->runAction(seq2); - + auto drawNode2 = DrawNode::create(); drawNode2->drawCatmullRom(array2, 50, Color4F(0.0f, 1.0f, 1.0f, 1.0f)); this->addChild(drawNode2); } -ActionCatmullRom::~ActionCatmullRom() -{ -} +ActionCatmullRom::~ActionCatmullRom() {} std::string ActionCatmullRom::title() const { @@ -2094,61 +1996,59 @@ std::string ActionCatmullRom::subtitle() const void ActionCardinalSpline::onEnter() { ActionsDemo::onEnter(); - + this->centerSprites(2); - + auto s = Director::getInstance()->getWinSize(); - + auto array = PointArray::create(20); - + array->addControlPoint(Vec2(0.0f, 0.0f)); - array->addControlPoint(Vec2(s.width/2-30, 0.0f)); - array->addControlPoint(Vec2(s.width/2-30, s.height-80)); - array->addControlPoint(Vec2(0.0f, s.height-80)); + array->addControlPoint(Vec2(s.width / 2 - 30, 0.0f)); + array->addControlPoint(Vec2(s.width / 2 - 30, s.height - 80)); + array->addControlPoint(Vec2(0.0f, s.height - 80)); array->addControlPoint(Vec2(0.0f, 0.0f)); - + // // sprite 1 (By) // // Spline with no tension (tension==0) // - - auto action = CardinalSplineBy::create(3, array, 0); + + auto action = CardinalSplineBy::create(3, array, 0); auto reverse = action->reverse(); - + auto seq = Sequence::create(action, reverse, nullptr); - + _tamara->setPosition(50, 50); _tamara->runAction(seq); - + auto drawNode1 = DrawNode::create(); - drawNode1->setPosition(Vec2(50.0f,50.0f)); + drawNode1->setPosition(Vec2(50.0f, 50.0f)); drawNode1->drawCardinalSpline(array, 0, 100, Color4F(1.0f, 0.0f, 1.0f, 1.0f)); this->addChild(drawNode1); - + // // sprite 2 (By) // // Spline with high tension (tension==1) // - - auto action2 = CardinalSplineBy::create(3, array, 1); + + auto action2 = CardinalSplineBy::create(3, array, 1); auto reverse2 = action2->reverse(); - + auto seq2 = Sequence::create(action2, reverse2, nullptr); - - _kathia->setPosition(s.width/2, 50); + + _kathia->setPosition(s.width / 2, 50); _kathia->runAction(seq2); - + auto drawNode2 = DrawNode::create(); - drawNode2->setPosition(Vec2(s.width/2, 50.0f)); + drawNode2->setPosition(Vec2(s.width / 2, 50.0f)); drawNode2->drawCardinalSpline(array, 1, 100, Color4F(1.0f, 0.0f, 1.0f, 1.0f)); this->addChild(drawNode2); } -ActionCardinalSpline::~ActionCardinalSpline() -{ -} +ActionCardinalSpline::~ActionCardinalSpline() {} std::string ActionCardinalSpline::title() const { @@ -2163,41 +2063,37 @@ std::string ActionCardinalSpline::subtitle() const /** PauseResumeActions */ -PauseResumeActions::PauseResumeActions() -{ +PauseResumeActions::PauseResumeActions() {} -} - -PauseResumeActions::~PauseResumeActions() -{ - -} +PauseResumeActions::~PauseResumeActions() {} void PauseResumeActions::onEnter() { ActionsDemo::onEnter(); - + this->centerSprites(3); - + _tamara->runAction(RepeatForever::create(RotateBy::create(3.0f, 360.0f))); _grossini->runAction(RepeatForever::create(RotateBy::create(3.0f, -360.0f))); _kathia->runAction(RepeatForever::create(RotateBy::create(3.0f, 360.0f))); - - this->schedule([&](float dt){ - log("Pausing"); - auto director = Director::getInstance(); - _pausedTargets = director->getActionManager()->pauseAllRunningActions(); - } - ,3 ,false ,0 ,"pause_key"); + this->schedule( + [&](float dt) { + log("Pausing"); + auto director = Director::getInstance(); - this->schedule([&](float dt) { - log("Resuming"); - auto director = Director::getInstance(); - director->getActionManager()->resumeTargets(_pausedTargets); - _pausedTargets.clear(); - } - ,5 ,false ,0, "resume_key"); + _pausedTargets = director->getActionManager()->pauseAllRunningActions(); + }, + 3, false, 0, "pause_key"); + + this->schedule( + [&](float dt) { + log("Resuming"); + auto director = Director::getInstance(); + director->getActionManager()->resumeTargets(_pausedTargets); + _pausedTargets.clear(); + }, + 5, false, 0, "resume_key"); } std::string PauseResumeActions::title() const @@ -2213,11 +2109,11 @@ std::string PauseResumeActions::subtitle() const //------------------------------------------------------------------ // // ActionResize -// Works on all nodes where setContentSize is effective. +// Works on all nodes where setContentSize is effective. // But it's mostly useful for nodes where 9-slice is enabled // //------------------------------------------------------------------ -void ActionResize::onEnter() +void ActionResize::onEnter() { ActionsDemo::onEnter(); @@ -2227,10 +2123,13 @@ void ActionResize::onEnter() Size widgetSize = getContentSize(); - Text* alert = Text::create("ImageView Content ResizeTo ResizeBy action. \nTop: ResizeTo/ResizeBy on a 9-slice ImageView \nBottom: ScaleTo/ScaleBy on a 9-slice ImageView (for comparison)", "fonts/Marker Felt.ttf", 14); + Text* alert = Text::create( + "ImageView Content ResizeTo ResizeBy action. \nTop: ResizeTo/ResizeBy on a 9-slice ImageView \nBottom: " + "ScaleTo/ScaleBy on a 9-slice ImageView (for comparison)", + "fonts/Marker Felt.ttf", 14); alert->setColor(Color3B(159, 168, 176)); - alert->setPosition(Vec2(widgetSize.width / 2.0f, - widgetSize.height / 2.0f - alert->getContentSize().height * 1.125f)); + alert->setPosition( + Vec2(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getContentSize().height * 1.125f)); addChild(alert); @@ -2239,14 +2138,13 @@ void ActionResize::onEnter() ImageView* imageViewResize = ImageView::create("cocosui/buttonHighlighted.png"); imageViewResize->setScale9Enabled(true); imageViewResize->setContentSize(Size(50.0f, 40.0f)); - imageViewResize->setPosition(Vec2((widgetSize.width / 2.0f) + offset.x, - (widgetSize.height / 2.0f) + offset.y)); + imageViewResize->setPosition(Vec2((widgetSize.width / 2.0f) + offset.x, (widgetSize.height / 2.0f) + offset.y)); auto resizeDown = cocos2d::ResizeTo::create(2.8f, Size(50.0f, 40.0f)); - auto resizeUp = cocos2d::ResizeTo::create(2.8f, Size(300.0f, 40.0f)); + auto resizeUp = cocos2d::ResizeTo::create(2.8f, Size(300.0f, 40.0f)); auto resizeByDown = cocos2d::ResizeBy::create(1.8f, Size(0.0f, -30.0f)); - auto resizeByUp = cocos2d::ResizeBy::create(1.8f, Size(0.0f, 30.0f)); + auto resizeByUp = cocos2d::ResizeBy::create(1.8f, Size(0.0f, 30.0f)); addChild(imageViewResize); auto rep = RepeatForever::create(Sequence::create(resizeUp, resizeDown, resizeByDown, resizeByUp, nullptr)); imageViewResize->runAction(rep); @@ -2255,20 +2153,20 @@ void ActionResize::onEnter() ImageView* imageViewScale = ImageView::create("cocosui/buttonHighlighted.png"); imageViewScale->setScale9Enabled(true); imageViewScale->setContentSize(Size(50.0f, 40.0f)); - imageViewScale->setPosition(Vec2(widgetSize.width / 2.0f, - widgetSize.height / 2.0f)); + imageViewScale->setPosition(Vec2(widgetSize.width / 2.0f, widgetSize.height / 2.0f)); auto scaleDownScale = cocos2d::ScaleTo::create(2.8f, 1.0f); - auto scaleUpScale = cocos2d::ScaleTo::create(2.8f, 6.0f, 1.0f); + auto scaleUpScale = cocos2d::ScaleTo::create(2.8f, 6.0f, 1.0f); auto scaleByDownScale = cocos2d::ScaleBy::create(1.8f, 1.0f, 0.25f); - auto scaleByUpScale = cocos2d::ScaleBy::create(1.8f, 1.0f, 4.0f); + auto scaleByUpScale = cocos2d::ScaleBy::create(1.8f, 1.0f, 4.0f); addChild(imageViewScale); - auto rep2 = RepeatForever::create(Sequence::create(scaleUpScale, scaleDownScale, scaleByDownScale, scaleByUpScale, nullptr)); + auto rep2 = RepeatForever::create( + Sequence::create(scaleUpScale, scaleDownScale, scaleByDownScale, scaleByUpScale, nullptr)); imageViewScale->runAction(rep2); } -std::string ActionResize::subtitle() const +std::string ActionResize::subtitle() const { return "ResizeTo / ResizeBy"; } @@ -2280,23 +2178,19 @@ std::string ActionResize::subtitle() const //------------------------------------------------------------------ void ActionRemoveSelf::onEnter() { - ActionsDemo::onEnter(); + ActionsDemo::onEnter(); - alignSpritesLeft(1); + alignSpritesLeft(1); - auto action = Sequence::create( - MoveBy::create( 2, Vec2(240.0f,0.0f)), - RotateBy::create( 2, 540), - ScaleTo::create(1,0.1f), - RemoveSelf::create(), - nullptr); + auto action = Sequence::create(MoveBy::create(2, Vec2(240.0f, 0.0f)), RotateBy::create(2, 540), + ScaleTo::create(1, 0.1f), RemoveSelf::create(), nullptr); - _grossini->runAction(action); + _grossini->runAction(action); } std::string ActionRemoveSelf::subtitle() const { - return "Sequence: Move + Rotate + Scale + RemoveSelf"; + return "Sequence: Move + Rotate + Scale + RemoveSelf"; } //------------------------------------------------------------------ @@ -2312,31 +2206,28 @@ void ActionFloatTest::onEnter() auto s = Director::getInstance()->getWinSize(); - // create float action with duration and from to value, using lambda function we can easily animate any property of the Node. - auto actionFloat = ActionFloat::create(2.f, 0, 3, [this](float value) { - _tamara->setScale(value); - }); + // create float action with duration and from to value, using lambda function we can easily animate any property of + // the Node. + auto actionFloat = ActionFloat::create(2.f, 0, 3, [this](float value) { _tamara->setScale(value); }); float grossiniY = _grossini->getPositionY(); - auto actionFloat1 = ActionFloat::create(3.f, grossiniY, grossiniY + 50, [this](float value) { - _grossini->setPositionY(value); - }); + auto actionFloat1 = + ActionFloat::create(3.f, grossiniY, grossiniY + 50, [this](float value) { _grossini->setPositionY(value); }); - auto actionFloat2 = ActionFloat::create(3.f, 3, 1, [this] (float value) { - _kathia->setScale(value); - }); + auto actionFloat2 = ActionFloat::create(3.f, 3, 1, [this](float value) { _kathia->setScale(value); }); _tamara->runAction(actionFloat); _grossini->runAction(actionFloat1); _kathia->runAction(actionFloat2); } -void Issue14936_1::onEnter() { +void Issue14936_1::onEnter() +{ ActionsDemo::onEnter(); centerSprites(0); - auto origin = cocos2d::Director::getInstance()->getVisibleOrigin(); + auto origin = cocos2d::Director::getInstance()->getVisibleOrigin(); auto visibleSize = cocos2d::Director::getInstance()->getVisibleSize(); _count = 0; @@ -2345,7 +2236,7 @@ void Issue14936_1::onEnter() { counterLabel->setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2); addChild(counterLabel); - auto func = CallFunc::create([this, counterLabel]{ + auto func = CallFunc::create([this, counterLabel] { _count++; std::ostringstream os; os << _count; @@ -2355,18 +2246,20 @@ void Issue14936_1::onEnter() { runAction(Spawn::create(func, func, nullptr)); } -std::string Issue14936_1::subtitle() const { +std::string Issue14936_1::subtitle() const +{ return "Counter should be equal 2"; } -void Issue14936_2::onEnter() { +void Issue14936_2::onEnter() +{ ActionsDemo::onEnter(); centerSprites(0); - auto origin = cocos2d::Director::getInstance()->getVisibleOrigin(); + auto origin = cocos2d::Director::getInstance()->getVisibleOrigin(); auto visibleSize = cocos2d::Director::getInstance()->getVisibleSize(); - _count = 0; + _count = 0; auto counterLabel = Label::createWithTTF("0", "fonts/Marker Felt.ttf", 16.0f); counterLabel->setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2); addChild(counterLabel); @@ -2381,15 +2274,18 @@ void Issue14936_2::onEnter() { runAction(Sequence::create(TargetedAction::create(this, func), DelayTime::create(0.2f), nullptr)); } -std::string Issue14936_2::subtitle() const { +std::string Issue14936_2::subtitle() const +{ return "Counter should be equal 1"; } -std::string Issue14936_2::title() const { +std::string Issue14936_2::title() const +{ return "Issue 14936 - Sequence"; } -std::string Issue14936_1::title() const { +std::string Issue14936_1::title() const +{ return "Issue 14936 - Action Interval"; } @@ -2398,8 +2294,6 @@ std::string ActionFloatTest::subtitle() const return "ActionFloat"; } - - //------------------------------------------------------------------ // // SequenceWithFinalInstant @@ -2410,36 +2304,31 @@ void SequenceWithFinalInstant::onEnter() TestCase::onEnter(); _manager = new cocos2d::ActionManager(); - + _target = cocos2d::Node::create(); - _target->setActionManager( _manager ); + _target->setActionManager(_manager); _target->retain(); _target->onEnter(); - bool called( false ); - const auto f - ( [ &called ]() -> void - { - cocos2d::log("Callback called."); - called = true; - } ); - + bool called(false); + const auto f([&called]() -> void { + cocos2d::log("Callback called."); + called = true; + }); + const auto action = - cocos2d::Sequence::create - (cocos2d::DelayTime::create(0.05f), - cocos2d::CallFunc::create(f), - nullptr); + cocos2d::Sequence::create(cocos2d::DelayTime::create(0.05f), cocos2d::CallFunc::create(f), nullptr); _target->runAction(action); _manager->update(0); _manager->update(0.05f - FLT_EPSILON); - if ( action->isDone() && !called ) + if (action->isDone() && !called) assert(false); - + _manager->update(FLT_EPSILON); - if ( action->isDone() && !called ) + if (action->isDone() && !called) assert(false); } @@ -2465,54 +2354,46 @@ std::string SequenceWithFinalInstant::subtitle() const void Issue18003::onEnter() { TestCase::onEnter(); - + _manager = new ActionManager(); - + _target = Node::create(); _target->setActionManager(_manager); _target->retain(); _target->onEnter(); - + // instant action + interval action - - const auto f - ( []() -> void - { - // do nothing - }); - - auto action = Sequence::create(CallFunc::create(f), - DelayTime::create(1), - nullptr); - + + const auto f([]() -> void { + // do nothing + }); + + auto action = Sequence::create(CallFunc::create(f), DelayTime::create(1), nullptr); + _target->runAction(action); _manager->update(0); _manager->update(2); - + assert(action->isDone()); - + _target->stopAction(action); - + // instant action + instant action - action = Sequence::create(CallFunc::create(f), - CallFunc::create(f), - nullptr); + action = Sequence::create(CallFunc::create(f), CallFunc::create(f), nullptr); _target->runAction(action); _manager->update(0); _manager->update(1); assert(action->isDone()); _target->stopAction(action); - + // interval action + instant action - action = Sequence::create(DelayTime::create(1), - CallFunc::create(f), - nullptr); + action = Sequence::create(DelayTime::create(1), CallFunc::create(f), nullptr); _target->runAction(action); _manager->update(0); _manager->update(2); assert(action->isDone()); _target->stopAction(action); - + // interval action + interval action action = Sequence::create(DelayTime::create(1), DelayTime::create(1), nullptr); _target->runAction(action); diff --git a/tests/cpp-tests/Classes/ActionsTest/ActionsTest.h b/tests/cpp-tests/Classes/ActionsTest/ActionsTest.h index 12b16ed6a160..1252de4f9d47 100644 --- a/tests/cpp-tests/Classes/ActionsTest/ActionsTest.h +++ b/tests/cpp-tests/Classes/ActionsTest/ActionsTest.h @@ -34,9 +34,10 @@ DEFINE_TEST_SUITE(ActionsTests); class ActionsDemo : public TestCase { protected: - cocos2d::Sprite* _grossini; - cocos2d::Sprite* _tamara; - cocos2d::Sprite* _kathia; + cocos2d::Sprite* _grossini; + cocos2d::Sprite* _tamara; + cocos2d::Sprite* _kathia; + public: virtual void onEnter() override; virtual void onExit() override; @@ -59,7 +60,7 @@ class ActionMove3D : public ActionsDemo { public: CREATE_FUNC(ActionMove3D); - + virtual void onEnter() override; virtual std::string subtitle() const override; }; @@ -181,7 +182,7 @@ class ActionAnimate : public ActionsDemo virtual void onExit() override; virtual std::string title() const override; virtual std::string subtitle() const override; - + private: cocos2d::EventListenerCustom* _frameDisplayedListener; }; @@ -295,8 +296,8 @@ class ActionRemoveSelf : public ActionsDemo public: CREATE_FUNC(ActionRemoveSelf); - virtual void onEnter() override; - virtual std::string subtitle() const override; + virtual void onEnter() override; + virtual std::string subtitle() const override; }; class ActionRepeatForever : public ActionsDemo @@ -354,7 +355,6 @@ class ActionCallFunction : public ActionsDemo void callback3(Node* pTarget, int32_t data); }; - class ActionFollow : public ActionsDemo { public: @@ -366,10 +366,10 @@ class ActionFollow : public ActionsDemo class ActionFollowWithOffset : public ActionsDemo { - + public: CREATE_FUNC(ActionFollowWithOffset); - + virtual void onEnter() override; virtual std::string subtitle() const override; }; @@ -466,6 +466,7 @@ class Issue1305 : public ActionsDemo void log(Node* sender); virtual std::string title() const override; virtual std::string subtitle() const override; + private: cocos2d::Sprite* _spriteTmp; }; @@ -525,6 +526,7 @@ class Issue1398 : public ActionsDemo virtual void onEnter() override; virtual std::string subtitle() const override; virtual std::string title() const override; + private: int _testInteger; }; @@ -533,10 +535,11 @@ class Issue2599 : public ActionsDemo { public: CREATE_FUNC(Issue2599); - + virtual void onEnter() override; virtual std::string subtitle() const override; virtual std::string title() const override; + private: int _count; }; @@ -547,7 +550,7 @@ class ActionCatmullRom : public ActionsDemo CREATE_FUNC(ActionCatmullRom); ~ActionCatmullRom(); - + virtual void onEnter() override; virtual std::string subtitle() const override; virtual std::string title() const override; @@ -559,7 +562,7 @@ class ActionCardinalSpline : public ActionsDemo CREATE_FUNC(ActionCardinalSpline); ~ActionCardinalSpline(); - + virtual void onEnter() override; virtual std::string subtitle() const override; virtual std::string title() const override; @@ -574,12 +577,13 @@ class PauseResumeActions : public ActionsDemo virtual ~PauseResumeActions(); virtual void onEnter() override; virtual std::string subtitle() const override; - virtual std::string title() const override; + virtual std::string title() const override; + private: cocos2d::Vector _pausedTargets; }; -class ActionResize : public ActionsDemo +class ActionResize : public ActionsDemo { public: CREATE_FUNC(ActionResize); @@ -605,6 +609,7 @@ class Issue14936_1 : public ActionsDemo virtual void onEnter() override; virtual std::string subtitle() const override; virtual std::string title() const override; + private: int _count; }; @@ -617,6 +622,7 @@ class Issue14936_2 : public ActionsDemo virtual void onEnter() override; virtual std::string subtitle() const override; virtual std::string title() const override; + private: int _count; }; @@ -625,30 +631,28 @@ class SequenceWithFinalInstant : public ActionsDemo { public: CREATE_FUNC(SequenceWithFinalInstant); - + virtual std::string subtitle() const override; virtual void onEnter() override; virtual void onExit() override; - + private: cocos2d::ActionManager* _manager; cocos2d::Node* _target; - }; class Issue18003 : public ActionsDemo { public: CREATE_FUNC(Issue18003); - + virtual std::string subtitle() const override; virtual void onEnter() override; virtual void onExit() override; - + private: cocos2d::ActionManager* _manager; cocos2d::Node* _target; - }; #endif diff --git a/tests/cpp-tests/Classes/AppDelegate.cpp b/tests/cpp-tests/Classes/AppDelegate.cpp index 6dda03072606..e606394e20aa 100644 --- a/tests/cpp-tests/Classes/AppDelegate.cpp +++ b/tests/cpp-tests/Classes/AppDelegate.cpp @@ -36,21 +36,18 @@ USING_NS_CC; // Enable log on Debug version #ifndef NDEBUG -#define COCOS2D_DEBUG 1 +# define COCOS2D_DEBUG 1 #else -#define COCOS2D_DEBUG 0 +# define COCOS2D_DEBUG 0 #endif -AppDelegate::AppDelegate() -: _testController(nullptr) -{ -} +AppDelegate::AppDelegate() : _testController(nullptr) {} AppDelegate::~AppDelegate() { - //SimpleAudioEngine::end(); - //TODO: minggo - // cocostudio::ArmatureDataManager::destroyInstance(); + // SimpleAudioEngine::end(); + // TODO: minggo + // cocostudio::ArmatureDataManager::destroyInstance(); } // if you want a different context, modify the value of glContextAttrs @@ -75,42 +72,42 @@ bool AppDelegate::applicationDidFinishLaunching() // initialize director auto director = Director::getInstance(); - auto glview = director->getOpenGLView(); - if (!glview) { + auto glview = director->getOpenGLView(); + if (!glview) + { std::string title = "Cpp Tests"; #ifndef NDEBUG title += " *Debug*", #endif - glview = GLViewImpl::createWithRect(title, Rect(0, 0, resourceSize.width, resourceSize.height)); + glview = GLViewImpl::createWithRect(title, Rect(0, 0, resourceSize.width, resourceSize.height)); director->setOpenGLView(glview); } - + director->setDisplayStats(true); director->setAnimationInterval(1.0f / 60); auto screenSize = glview->getFrameSize(); - auto fileUtils = FileUtils::getInstance(); std::vector searchPaths; - + if (screenSize.height > 320) { searchPaths.push_back("hd"); searchPaths.push_back("ccs-res/hd"); searchPaths.push_back("ccs-res"); searchPaths.push_back("Manifests"); - director->setContentScaleFactor(resourceSize.height/designSize.height); + director->setContentScaleFactor(resourceSize.height / designSize.height); searchPaths.push_back("hd/ActionTimeline"); } else { searchPaths.push_back("ccs-res"); - + searchPaths.push_back("ActionTimeline"); } - + fileUtils->setSearchPaths(searchPaths); glview->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::NO_BORDER); @@ -129,9 +126,9 @@ void AppDelegate::applicationDidEnterBackground() { if (_testController) { -// _testController->onEnterBackground(); + // _testController->onEnterBackground(); } - + Director::getInstance()->stopAnimation(); } @@ -140,8 +137,8 @@ void AppDelegate::applicationWillEnterForeground() { if (_testController) { -// _testController->onEnterForeground(); + // _testController->onEnterForeground(); } - + Director::getInstance()->startAnimation(); } diff --git a/tests/cpp-tests/Classes/AppDelegate.h b/tests/cpp-tests/Classes/AppDelegate.h index 6a7ff311ecca..ee34105f56ff 100644 --- a/tests/cpp-tests/Classes/AppDelegate.h +++ b/tests/cpp-tests/Classes/AppDelegate.h @@ -24,8 +24,8 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef _APP_DELEGATE_H_ -#define _APP_DELEGATE_H_ +#ifndef _APP_DELEGATE_H_ +#define _APP_DELEGATE_H_ #include "cocos2d.h" @@ -35,7 +35,7 @@ class TestController; Private inheritance here hides part of interface from Director. */ -class AppDelegate : private cocos2d::Application +class AppDelegate : private cocos2d::Application { public: AppDelegate(); @@ -66,5 +66,4 @@ class AppDelegate : private cocos2d::Application TestController* _testController; }; -#endif // _APP_DELEGATE_H_ - +#endif // _APP_DELEGATE_H_ diff --git a/tests/cpp-tests/Classes/BaseTest.cpp b/tests/cpp-tests/Classes/BaseTest.cpp index 30fbd9671fa3..04856b009b4b 100644 --- a/tests/cpp-tests/Classes/BaseTest.cpp +++ b/tests/cpp-tests/Classes/BaseTest.cpp @@ -32,17 +32,9 @@ USING_NS_CC_EXT; #define TABEL_LABEL_TAG 1024 -TestBase::TestBase() -: _parentTest(nullptr) -, _isTestList(false) -{ - -} - -TestBase::~TestBase() -{ +TestBase::TestBase() : _parentTest(nullptr), _isTestList(false) {} -} +TestBase::~TestBase() {} void TestBase::backsUpOneLevel() { @@ -53,7 +45,7 @@ void TestBase::backsUpOneLevel() } } -//TestList +// TestList class TestCustomTableView : public TableView { public: @@ -68,8 +60,8 @@ class TestCustomTableView : public TableView return table; } - - virtual void onTouchEnded(Touch *touch, Event *event) override + + virtual void onTouchEnded(Touch* touch, Event* event) override { if (!this->isVisible()) { @@ -80,7 +72,7 @@ class TestCustomTableView : public TableView { auto label = (Label*)_touchedCell->getChildByTag(TABEL_LABEL_TAG); - Rect bbox = label->getBoundingBox(); + Rect bbox = label->getBoundingBox(); bbox.origin = _touchedCell->convertToWorldSpace(bbox.origin); if (bbox.containsPoint(touch->getLocation()) && _tableViewDelegate != nullptr) @@ -95,10 +87,10 @@ class TestCustomTableView : public TableView ScrollView::onTouchEnded(touch, event); } - void onMouseScroll(Event *event) + void onMouseScroll(Event* event) { auto mouseEvent = static_cast(event); - float moveY = mouseEvent->getScrollY() * 20; + float moveY = mouseEvent->getScrollY() * 20; auto minOffset = this->minContainerOffset(); auto maxOffset = this->maxContainerOffset(); @@ -120,7 +112,7 @@ class TestCustomTableView : public TableView protected: TestCustomTableView() { - auto mouseListener = EventListenerMouse::create(); + auto mouseListener = EventListenerMouse::create(); mouseListener->onMouseScroll = CC_CALLBACK_1(TestCustomTableView::onMouseScroll, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(mouseListener, this); } @@ -128,25 +120,28 @@ class TestCustomTableView : public TableView TestList::TestList() { - _isTestList = true; + _isTestList = true; _shouldRestoreTableOffset = false; } -TestList::~TestList() { +TestList::~TestList() +{ deatchTableView(); } -void TestList::deatchTableView() { +void TestList::deatchTableView() +{ if (_tableView) _tableView->setDataSource(nullptr); CC_SAFE_RELEASE_NULL(_tableView); } -void TestList::addTest(const std::string& testName, std::function callback) +void TestList::addTest(std::string_view testName, std::function callback) { if (!testName.empty()) { - _childTestNames.emplace_back(StringUtils::format("%d", static_cast(_childTestNames.size() + 1)) + ":" + testName); + _childTestNames.emplace_back( + StringUtils::format("%d:%s", static_cast(_childTestNames.size() + 1), testName.data())); _testCallbacks.emplace_back(callback); } } @@ -156,24 +151,24 @@ void TestList::runThisTest() _cellTouchEnabled = true; /* Restore default window and design size - * Note: We should change frame and design size before your new scene create - * otherwise, the layout will incorrect - */ - - GLViewImpl* glview = (GLViewImpl*) Director::getInstance()->getOpenGLView(); - #if defined(CC_PLATFORM_PC) + * Note: We should change frame and design size before your new scene create + * otherwise, the layout will incorrect + */ + + GLViewImpl* glview = (GLViewImpl*)Director::getInstance()->getOpenGLView(); +#if defined(CC_PLATFORM_PC) Size resourceSize(960, 640); glview->setWindowed(resourceSize.width, resourceSize.height); - #endif - +#endif + Size designSize(480, 320); glview->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::NO_BORDER); auto director = Director::getInstance(); - auto scene = Scene::create(); + auto scene = Scene::create(); auto visibleSize = director->getVisibleSize(); - auto origin = director->getVisibleOrigin(); + auto origin = director->getVisibleOrigin(); deatchTableView(); _tableView = TestCustomTableView::create(this, Size(400, visibleSize.height)); _tableView->retain(); @@ -191,12 +186,12 @@ void TestList::runThisTest() if (_parentTest) { - //Add back button. + // Add back button. TTFConfig ttfConfig("fonts/arial.ttf", 20); auto label = Label::createWithTTF(ttfConfig, "Back"); auto menuItem = MenuItemLabel::create(label, std::bind(&TestBase::backsUpOneLevel, this)); - auto menu = Menu::create(menuItem, nullptr); + auto menu = Menu::create(menuItem, nullptr); menu->setPosition(Vec2::ZERO); menuItem->setPosition(Vec2(VisibleRect::right().x - 50, VisibleRect::bottom().y + 25)); @@ -205,18 +200,17 @@ void TestList::runThisTest() } else { - //Add close and "Start AutoTest" button. - auto closeItem = MenuItemImage::create(s_pathClose, s_pathClose, [](Ref* sender){ + // Add close and "Start AutoTest" button. + auto closeItem = MenuItemImage::create(s_pathClose, s_pathClose, [](Ref* sender) { TestController::getInstance()->stopAutoTest(); TestController::destroyInstance(); Director::getInstance()->end(); }); closeItem->setPosition(VisibleRect::right().x - 30, VisibleRect::top().y - 30); - auto autoTestLabel = Label::createWithTTF("Start AutoTest","fonts/arial.ttf",16); - auto autoTestItem = MenuItemLabel::create(autoTestLabel, [&](Ref* sender){ - TestController::getInstance()->startAutoTest(); - }); + auto autoTestLabel = Label::createWithTTF("Start AutoTest", "fonts/arial.ttf", 16); + auto autoTestItem = + MenuItemLabel::create(autoTestLabel, [&](Ref* sender) { TestController::getInstance()->startAutoTest(); }); autoTestItem->setPosition(Vec2(VisibleRect::left().x + 60, VisibleRect::bottom().y + 50)); auto menu = Menu::create(closeItem, autoTestItem, nullptr); @@ -237,9 +231,9 @@ void TestList::tableCellTouched(TableView* table, TableViewCell* cell) auto test = _testCallbacks[index](); if (test->getChildTestCount() > 0) { - _tableOffset = table->getContentOffset(); + _tableOffset = table->getContentOffset(); _shouldRestoreTableOffset = true; - _cellTouchEnabled = false; + _cellTouchEnabled = false; test->setTestParent(this); test->runThisTest(); } @@ -251,12 +245,12 @@ void TestList::tableCellTouched(TableView* table, TableViewCell* cell) } } -TableViewCell* TestList::tableCellAtIndex(TableView *table, ssize_t idx) +TableViewCell* TestList::tableCellAtIndex(TableView* table, ssize_t idx) { auto cell = table->dequeueCell(); if (!cell) { - cell = TableViewCell::create(); + cell = TableViewCell::create(); auto label = Label::createWithTTF(_childTestNames[idx], "fonts/arial.ttf", 20.0f); label->setTag(TABEL_LABEL_TAG); label->setPosition(200, 15); @@ -271,18 +265,18 @@ TableViewCell* TestList::tableCellAtIndex(TableView *table, ssize_t idx) return cell; } -Size TestList::tableCellSizeForIndex(TableView *table, ssize_t idx) +Size TestList::tableCellSizeForIndex(TableView* table, ssize_t idx) { return Size(400, 30); } -ssize_t TestList::numberOfCellsInTableView(TableView *table) +ssize_t TestList::numberOfCellsInTableView(TableView* table) { return _childTestNames.size(); } -//TestSuite -void TestSuite::addTestCase(const std::string& testName, std::function callback) +// TestSuite +void TestSuite::addTestCase(std::string_view testName, std::function callback) { if (!testName.empty() && callback) { @@ -294,7 +288,7 @@ void TestSuite::addTestCase(const std::string& testName, std::function static TestCase* getTestCase(Scene* scene) { auto transitionScene = dynamic_cast(scene); - TestCase* testCase = nullptr; + TestCase* testCase = nullptr; if (transitionScene) { testCase = dynamic_cast(transitionScene->getInScene()); @@ -314,8 +308,8 @@ void TestSuite::runThisTest() TestController::getInstance()->setCurrTestSuite(this); _currTestIndex = 0; - auto scene = _testCallbacks[0](); - auto testCase = getTestCase(scene); + auto scene = _testCallbacks[0](); + auto testCase = getTestCase(scene); testCase->setTestSuite(this); testCase->setTestCaseName(_childTestNames[_currTestIndex]); Director::getInstance()->replaceScene(scene); @@ -324,7 +318,7 @@ void TestSuite::runThisTest() void TestSuite::restartCurrTest() { - auto scene = _testCallbacks[_currTestIndex](); + auto scene = _testCallbacks[_currTestIndex](); auto testCase = getTestCase(scene); testCase->setTestSuite(this); testCase->setTestCaseName(_childTestNames[_currTestIndex]); @@ -336,7 +330,7 @@ void TestSuite::enterNextTest() { _currTestIndex = (_currTestIndex + 1) % _childTestNames.size(); - auto scene = _testCallbacks[_currTestIndex](); + auto scene = _testCallbacks[_currTestIndex](); auto testCase = getTestCase(scene); testCase->setTestSuite(this); testCase->setTestCaseName(_childTestNames[_currTestIndex]); @@ -355,7 +349,7 @@ void TestSuite::enterPreviousTest() _currTestIndex = (int)_childTestNames.size() - 1; } - auto scene = _testCallbacks[_currTestIndex](); + auto scene = _testCallbacks[_currTestIndex](); auto testCase = getTestCase(scene); testCase->setTestSuite(this); testCase->setTestCaseName(_childTestNames[_currTestIndex]); @@ -363,22 +357,20 @@ void TestSuite::enterPreviousTest() Director::getInstance()->replaceScene(scene); } -//TestCase +// TestCase TestCase::TestCase() -: _priorTestItem(nullptr) -, _restartTestItem(nullptr) -, _nextTestItem(nullptr) -, _titleLabel(nullptr) -, _subtitleLabel(nullptr) -, _testSuite(nullptr) -, _runTime(0.0f) + : _priorTestItem(nullptr) + , _restartTestItem(nullptr) + , _nextTestItem(nullptr) + , _titleLabel(nullptr) + , _subtitleLabel(nullptr) + , _testSuite(nullptr) + , _runTime(0.0f) { SpriteFrameCache::getInstance()->removeUnusedSpriteFrames(); Director::getInstance()->getTextureCache()->removeUnusedTextures(); - this->schedule([&](float dt){ - _runTime += dt; - }, "AccumulatedTimeUse"); + this->schedule([&](float dt) { _runTime += dt; }, "AccumulatedTimeUse"); } TestCase::~TestCase() @@ -422,27 +414,31 @@ bool TestCase::init() _titleLabel = Label::createWithTTF(ttfConfig, title()); addChild(_titleLabel, 9999); _titleLabel->setPosition(VisibleRect::center().x, VisibleRect::top().y - 30); - + ttfConfig.fontSize = 16; - _subtitleLabel = Label::createWithTTF(ttfConfig, subtitle()); + _subtitleLabel = Label::createWithTTF(ttfConfig, subtitle()); _subtitleLabel->setMaxLineWidth(VisibleRect::getVisibleRect().size.width); addChild(_subtitleLabel, 9999); _subtitleLabel->setPosition(VisibleRect::center().x, VisibleRect::top().y - 60); - + _priorTestItem = MenuItemImage::create(s_pathB1, s_pathB2, CC_CALLBACK_1(TestCase::priorTestCallback, this)); - _restartTestItem = MenuItemImage::create(s_pathR1, s_pathR2, CC_CALLBACK_1(TestCase::restartTestCallback, this)); + _restartTestItem = + MenuItemImage::create(s_pathR1, s_pathR2, CC_CALLBACK_1(TestCase::restartTestCallback, this)); _nextTestItem = MenuItemImage::create(s_pathF1, s_pathF2, CC_CALLBACK_1(TestCase::nextTestCallback, this)); - + ttfConfig.fontSize = 20; - auto backLabel = Label::createWithTTF(ttfConfig, "Back"); - auto backItem = MenuItemLabel::create(backLabel, CC_CALLBACK_1(TestCase::onBackCallback, this)); + auto backLabel = Label::createWithTTF(ttfConfig, "Back"); + auto backItem = MenuItemLabel::create(backLabel, CC_CALLBACK_1(TestCase::onBackCallback, this)); auto menu = Menu::create(_priorTestItem, _restartTestItem, _nextTestItem, backItem, nullptr); menu->setPosition(Vec2::ZERO); - _priorTestItem->setPosition(VisibleRect::center().x - _restartTestItem->getContentSize().width * 2, VisibleRect::bottom().y + _restartTestItem->getContentSize().height / 2); - _restartTestItem->setPosition(VisibleRect::center().x, VisibleRect::bottom().y + _restartTestItem->getContentSize().height / 2); - _nextTestItem->setPosition(VisibleRect::center().x + _restartTestItem->getContentSize().width * 2, VisibleRect::bottom().y + _restartTestItem->getContentSize().height / 2); + _priorTestItem->setPosition(VisibleRect::center().x - _restartTestItem->getContentSize().width * 2, + VisibleRect::bottom().y + _restartTestItem->getContentSize().height / 2); + _restartTestItem->setPosition(VisibleRect::center().x, + VisibleRect::bottom().y + _restartTestItem->getContentSize().height / 2); + _nextTestItem->setPosition(VisibleRect::center().x + _restartTestItem->getContentSize().width * 2, + VisibleRect::bottom().y + _restartTestItem->getContentSize().height / 2); backItem->setPosition(Vec2(VisibleRect::right().x - 50, VisibleRect::bottom().y + 25)); addChild(menu, 9999); @@ -464,7 +460,8 @@ void TestCase::onEnter() if (_testSuite) { - _titleLabel->setString(StringUtils::format("%d", static_cast(_testSuite->getCurrTestIndex() + 1)) + ":" + title()); + _titleLabel->setString(StringUtils::format("%d", static_cast(_testSuite->getCurrTestIndex() + 1)) + ":" + + title()); } else { diff --git a/tests/cpp-tests/Classes/BaseTest.h b/tests/cpp-tests/Classes/BaseTest.h index b7824a917ccd..526b4d16d552 100644 --- a/tests/cpp-tests/Classes/BaseTest.h +++ b/tests/cpp-tests/Classes/BaseTest.h @@ -47,7 +47,7 @@ class TestCase : public cocos2d::Scene /** For testing whether test case not crash.*/ ROBUSTNESS, /** - * For check the correctness of regular test cases. + * For check the correctness of regular test cases. * A test case passes only if the actual output equal to the expected output. */ UNIT, @@ -67,7 +67,6 @@ class TestCase : public cocos2d::Scene /** Returns the time the test case needs.*/ virtual float getDuration() const; - /** Returns the expected output.*/ virtual std::string getExpectedOutput() const { return ""; } /** Returns the actual output.*/ @@ -91,15 +90,14 @@ class TestCase : public cocos2d::Scene /** * You should NEVER call this method, unless you know what you are doing. */ - void setTestCaseName(const std::string& name) { _testCaseName = name; } + void setTestCaseName(std::string_view name) { _testCaseName = name; } std::string getTestCaseName() const { return _testCaseName; } const cocos2d::Label* getSubtitleLable() const { return _subtitleLabel; } const cocos2d::MenuItemImage* getRestartTestItem() const { return _restartTestItem; } virtual void onEnter() override; -CC_CONSTRUCTOR_ACCESS: - virtual bool init() override; + CC_CONSTRUCTOR_ACCESS : virtual bool init() override; protected: cocos2d::MenuItemImage* _priorTestItem; @@ -138,13 +136,14 @@ class TestBase : public cocos2d::Ref ssize_t getChildTestCount() { return _childTestNames.size(); } /** - * You should NEVER call this method. - */ + * You should NEVER call this method. + */ void setTestParent(TestBase* parent) { _parentTest = parent; } TestBase* getTestParent() { return _parentTest; } - void setTestName(const std::string& testName) { _testName = testName; } + void setTestName(std::string_view testName) { _testName = testName; } std::string getTestName() const { return _testName; } + protected: TestBase(); @@ -157,13 +156,13 @@ class TestBase : public cocos2d::Ref class TestController; /** -* TestSuite correspond to a group of test cases. -* @note Each test case should add to a TestSuite object. -*/ + * TestSuite correspond to a group of test cases. + * @note Each test case should add to a TestSuite object. + */ class TestSuite : public TestBase { public: - void addTestCase(const std::string& testName, std::function callback); + void addTestCase(std::string_view testName, std::function callback); virtual void restartCurrTest(); virtual void enterNextTest(); @@ -184,26 +183,30 @@ class TestCustomTableView; /** * An instance of TestList is a means for displaying hierarchical lists of TestSuite. */ -class TestList : public TestBase, public cocos2d::extension::TableViewDataSource, public cocos2d::extension::TableViewDelegate +class TestList : public TestBase, + public cocos2d::extension::TableViewDataSource, + public cocos2d::extension::TableViewDelegate { public: TestList(); ~TestList(); - void addTest(const std::string& testName, std::function callback); + void addTest(std::string_view testName, std::function callback); virtual void runThisTest() override; + virtual void tableCellTouched(cocos2d::extension::TableView* table, + cocos2d::extension::TableViewCell* cell) override; + virtual cocos2d::extension::TableViewCell* tableCellAtIndex(cocos2d::extension::TableView* table, + ssize_t idx) override; + virtual cocos2d::Size tableCellSizeForIndex(cocos2d::extension::TableView* table, ssize_t idx) override; + virtual ssize_t numberOfCellsInTableView(cocos2d::extension::TableView* table) override; - virtual void tableCellTouched(cocos2d::extension::TableView* table, cocos2d::extension::TableViewCell* cell) override; - virtual cocos2d::extension::TableViewCell* tableCellAtIndex(cocos2d::extension::TableView *table, ssize_t idx) override; - virtual cocos2d::Size tableCellSizeForIndex(cocos2d::extension::TableView *table, ssize_t idx) override; - virtual ssize_t numberOfCellsInTableView(cocos2d::extension::TableView *table) override; - - virtual void scrollViewDidScroll(cocos2d::extension::ScrollView* view) override{} - virtual void scrollViewDidZoom(cocos2d::extension::ScrollView* view) override{} + virtual void scrollViewDidScroll(cocos2d::extension::ScrollView* view) override {} + virtual void scrollViewDidZoom(cocos2d::extension::ScrollView* view) override {} void deatchTableView(); + private: std::vector> _testCallbacks; bool _cellTouchEnabled; @@ -213,32 +216,40 @@ class TestList : public TestBase, public cocos2d::extension::TableViewDataSource TestCustomTableView* _tableView{}; }; +#define ADD_TEST(__className__) addTest(#__className__, []() { return new __className__; }); -#define ADD_TEST(__className__) addTest( #__className__, [](){ return new __className__;} ); - -#define ADD_TEST_CASE(__className__) addTestCase( #__className__, [](){ return __className__::create();} ); +#define ADD_TEST_CASE(__className__) addTestCase(#__className__, []() { return __className__::create(); }); -#define DEFINE_TEST_LIST(__className__) class __className__ : public TestList { public: __className__();} - -#define DEFINE_TEST_SUITE(__className__) class __className__ : public TestSuite { public: __className__();} +#define DEFINE_TEST_LIST(__className__) \ + class __className__ : public TestList \ + { \ + public: \ + __className__(); \ + } +#define DEFINE_TEST_SUITE(__className__) \ + class __className__ : public TestSuite \ + { \ + public: \ + __className__(); \ + } /** * BaseTest is retained for compatibility with older versions. - * @warning It should soon be removed. + * @warning It should soon be removed. */ class BaseTest : public cocos2d::Layer { public: virtual std::string title() const { return ""; } - virtual std::string subtitle() const{ return ""; } + virtual std::string subtitle() const { return ""; } virtual void restartCallback(cocos2d::Ref* sender) {} - virtual void nextCallback(cocos2d::Ref* sender){} - virtual void backCallback(cocos2d::Ref* sender){} + virtual void nextCallback(cocos2d::Ref* sender) {} + virtual void backCallback(cocos2d::Ref* sender) {} - virtual void onEnter() override{} - virtual void onExit() override{} + virtual void onEnter() override {} + virtual void onExit() override {} }; #endif /* defined(_CPPTESTS_BASETEST_H__) */ diff --git a/tests/cpp-tests/Classes/BillBoardTest/BillBoardTest.cpp b/tests/cpp-tests/Classes/BillBoardTest/BillBoardTest.cpp index 49b908ab2242..0e7953a73541 100644 --- a/tests/cpp-tests/Classes/BillBoardTest/BillBoardTest.cpp +++ b/tests/cpp-tests/Classes/BillBoardTest/BillBoardTest.cpp @@ -2,19 +2,19 @@ Copyright (c) 2012 cocos2d-x.org Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,7 +34,6 @@ USING_NS_CC; USING_NS_CC_EXT; using namespace cocos2d::ui; - BillBoardTests::BillBoardTests() { ADD_TEST_CASE(BillBoardRotationTest); @@ -49,51 +48,48 @@ BillBoardTests::BillBoardTests() BillBoardRotationTest::BillBoardRotationTest() { auto root = Sprite3D::create(); - root->setPositionNormalized(Vec2(0.5f,0.25f)); + root->setPositionNormalized(Vec2(0.5f, 0.25f)); addChild(root); - + auto model = Sprite3D::create("Sprite3DTest/orc.c3b"); model->setScale(5); - model->setRotation3D(Vec3(0.0f,180.0f,0.0f)); + model->setRotation3D(Vec3(0.0f, 180.0f, 0.0f)); root->addChild(model); - + auto bill = BillBoard::create(); bill->setPosition(0, 120); root->addChild(bill); - + auto sp = Sprite::create("Images/SpookyPeas.png"); sp->setScale(2); bill->addChild(sp); - + auto lbl = Label::create(); lbl->setPosition(0.0f, 30.0f); lbl->setString("+100"); bill->addChild(lbl); - - auto r = RotateBy::create(10, Vec3(0.0f,360.0f,0.0f)); + + auto r = RotateBy::create(10, Vec3(0.0f, 360.0f, 0.0f)); auto rp = RepeatForever::create(r); root->runAction(rp); - - auto jump = JumpBy::create(1, Vec2(0.0f, 0.0f), 30, 1); + + auto jump = JumpBy::create(1, Vec2(0.0f, 0.0f), 30, 1); auto scale = ScaleBy::create(2.f, 2.f, 2.f, 0.1f); - auto seq = Sequence::create(jump,scale, NULL); - + auto seq = Sequence::create(jump, scale, NULL); + auto rot = RotateBy::create(2, Vec3(-90.0f, 0.0f, 0.0f)); - auto act = Spawn::create(seq, rot,NULL); - + auto act = Spawn::create(seq, rot, NULL); + auto scale2 = scale->reverse(); - auto rot2 = rot->reverse(); - auto act2 = Spawn::create(scale2, rot2, NULL); - - auto seq2 = Sequence::create(act, act2, NULL); + auto rot2 = rot->reverse(); + auto act2 = Spawn::create(scale2, rot2, NULL); + + auto seq2 = Sequence::create(act, act2, NULL); auto repeat = RepeatForever::create(seq2); model->runAction(repeat); } -BillBoardRotationTest::~BillBoardRotationTest() -{ - -} +BillBoardRotationTest::~BillBoardRotationTest() {} std::string BillBoardRotationTest::title() const { @@ -110,38 +106,37 @@ std::string BillBoardRotationTest::subtitle() const // Billboard Rendering Test // //------------------------------------------------------------------ -BillBoardTest::BillBoardTest() -: _camera(nullptr) +BillBoardTest::BillBoardTest() : _camera(nullptr) { - //Create touch listener - auto listener = EventListenerTouchAllAtOnce::create(); + // Create touch listener + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesMoved = CC_CALLBACK_2(BillBoardTest::onTouchesMoved, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - - auto layer3D=Layer::create(); - addChild(layer3D,0); + + auto layer3D = Layer::create(); + addChild(layer3D, 0); _layerBillBoard = layer3D; - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); if (_camera == nullptr) { - _camera=Camera::createPerspective(60, (float)s.width/s.height, 1, 500); + _camera = Camera::createPerspective(60, (float)s.width / s.height, 1, 500); _camera->setCameraFlag(CameraFlag::USER1); _layerBillBoard->addChild(_camera); } - //Create rotating billboards + // Create rotating billboards std::string imgs[3] = {"Images/Icon.png", "Images/r2.png"}; for (unsigned int i = 0; i < 4; ++i) { - Layer *layer = Layer::create(); + Layer* layer = Layer::create(); auto billboard = BillBoard::create(imgs[(unsigned int)(CCRANDOM_0_1() * 1 + 0.5f)]); billboard->setScale(0.5f); - billboard->setPosition3D(Vec3(0.0f, 0.0f, CCRANDOM_MINUS1_1() * 150.0f)); + billboard->setPosition3D(Vec3(0.0f, 0.0f, CCRANDOM_MINUS1_1() * 150.0f)); billboard->setOpacity(static_cast(CCRANDOM_0_1() * 128 + 128)); _billboards.push_back(billboard); layer->addChild(billboard); _layerBillBoard->addChild(layer); - layer->runAction( RepeatForever::create( RotateBy::create( CCRANDOM_0_1() * 10, Vec3(0.0f, 45.0f, 0.0f) ) ) ); + layer->runAction(RepeatForever::create(RotateBy::create(CCRANDOM_0_1() * 10, Vec3(0.0f, 45.0f, 0.0f)))); } { @@ -158,62 +153,64 @@ BillBoardTest::BillBoardTest() auto sprite3d = Sprite3D::create("Sprite3DTest/orc.c3t"); sprite3d->setScale(2.0f); sprite3d->addChild(billboard); - sprite3d->runAction( RepeatForever::create( RotateBy::create( 10.0f, Vec3(0.0f, 360.0f, 0.0f) ) ) ); + sprite3d->runAction(RepeatForever::create(RotateBy::create(10.0f, Vec3(0.0f, 360.0f, 0.0f)))); _layerBillBoard->addChild(sprite3d); } - addNewBillBoardWithCoords(Vec3(20.0f,5.0f,0.0f)); - addNewBillBoardWithCoords(Vec3(60.0f,5.0f,0.0f)); - addNewBillBoardWithCoords(Vec3(100.0f,5.0f,0.0f)); - addNewBillBoardWithCoords(Vec3(140.0f,5.0f,0.0f)); - addNewBillBoardWithCoords(Vec3(180.0f,5.0f,0.0f)); - - addNewAniBillBoardWithCoords(Vec3(-20.0f,0.0f,0.0f)); - addNewAniBillBoardWithCoords(Vec3(-60.0f,0.0f,0.0f)); - addNewAniBillBoardWithCoords(Vec3(-100.0f,0.0f,0.0f)); - addNewAniBillBoardWithCoords(Vec3(-140.0f,0.0f,0.0f)); - addNewAniBillBoardWithCoords(Vec3(-180.0f,0.0f,0.0f)); - + addNewBillBoardWithCoords(Vec3(20.0f, 5.0f, 0.0f)); + addNewBillBoardWithCoords(Vec3(60.0f, 5.0f, 0.0f)); + addNewBillBoardWithCoords(Vec3(100.0f, 5.0f, 0.0f)); + addNewBillBoardWithCoords(Vec3(140.0f, 5.0f, 0.0f)); + addNewBillBoardWithCoords(Vec3(180.0f, 5.0f, 0.0f)); + + addNewAniBillBoardWithCoords(Vec3(-20.0f, 0.0f, 0.0f)); + addNewAniBillBoardWithCoords(Vec3(-60.0f, 0.0f, 0.0f)); + addNewAniBillBoardWithCoords(Vec3(-100.0f, 0.0f, 0.0f)); + addNewAniBillBoardWithCoords(Vec3(-140.0f, 0.0f, 0.0f)); + addNewAniBillBoardWithCoords(Vec3(-180.0f, 0.0f, 0.0f)); + _camera->setPosition3D(Vec3(0.0f, 100.0f, 230.0f)); - _camera->lookAt(Vec3(0,0,0), Vec3(0.0f,1.0f,0.0f)); + _camera->lookAt(Vec3(0, 0, 0), Vec3(0.0f, 1.0f, 0.0f)); TTFConfig ttfConfig("fonts/arial.ttf", 16); - auto label1 = Label::createWithTTF(ttfConfig,"rotate+"); - auto menuItem1 = MenuItemLabel::create(label1, CC_CALLBACK_1(BillBoardTest::rotateCameraCallback,this,10)); - auto label2 = Label::createWithTTF(ttfConfig,"rotate-"); - auto menuItem2 = MenuItemLabel::create(label2, CC_CALLBACK_1(BillBoardTest::rotateCameraCallback,this,-10)); - auto menu = Menu::create(menuItem1, menuItem2, nullptr); + auto label1 = Label::createWithTTF(ttfConfig, "rotate+"); + auto menuItem1 = MenuItemLabel::create(label1, CC_CALLBACK_1(BillBoardTest::rotateCameraCallback, this, 10)); + auto label2 = Label::createWithTTF(ttfConfig, "rotate-"); + auto menuItem2 = MenuItemLabel::create(label2, CC_CALLBACK_1(BillBoardTest::rotateCameraCallback, this, -10)); + auto menu = Menu::create(menuItem1, menuItem2, nullptr); menu->setPosition(Vec2::ZERO); - menuItem1->setPosition( Vec2( s.width-80, VisibleRect::top().y-160) ); - menuItem2->setPosition( Vec2( s.width-80, VisibleRect::top().y-190) ); + menuItem1->setPosition(Vec2(s.width - 80, VisibleRect::top().y - 160)); + menuItem2->setPosition(Vec2(s.width - 80, VisibleRect::top().y - 190)); addChild(menu, 0); _layerBillBoard->setCameraMask(2); - - label1 = Label::createWithTTF(ttfConfig,"Point Oriented"); - menuItem1 = MenuItemLabel::create(label1,CC_CALLBACK_1(BillBoardTest::menuCallback_orientedPoint,this) ); - label2 = Label::createWithTTF(ttfConfig,"Plane Oriented"); - menuItem2 = MenuItemLabel::create(label2,CC_CALLBACK_1(BillBoardTest::menuCallback_orientedPlane,this) ); - menuItem1->setPosition( Vec2( s.width-80, VisibleRect::top().y-100) ); - menuItem2->setPosition( Vec2( s.width-80, VisibleRect::top().y-130) ); - + + label1 = Label::createWithTTF(ttfConfig, "Point Oriented"); + menuItem1 = MenuItemLabel::create(label1, CC_CALLBACK_1(BillBoardTest::menuCallback_orientedPoint, this)); + label2 = Label::createWithTTF(ttfConfig, "Plane Oriented"); + menuItem2 = MenuItemLabel::create(label2, CC_CALLBACK_1(BillBoardTest::menuCallback_orientedPlane, this)); + menuItem1->setPosition(Vec2(s.width - 80, VisibleRect::top().y - 100)); + menuItem2->setPosition(Vec2(s.width - 80, VisibleRect::top().y - 130)); + menu = Menu::create(menuItem1, menuItem2, nullptr); - menu->setPosition(Vec2(0,0)); + menu->setPosition(Vec2(0, 0)); this->addChild(menu, 10); menuCallback_orientedPoint(nullptr); - + schedule(CC_SCHEDULE_SELECTOR(BillBoardTest::update)); } void BillBoardTest::menuCallback_orientedPoint(Ref* sender) { - for (auto& billboard : _billboards) { + for (auto& billboard : _billboards) + { billboard->setMode(BillBoard::Mode::VIEW_POINT_ORIENTED); } } void BillBoardTest::menuCallback_orientedPlane(Ref* sender) { - for (auto& billboard : _billboards) { + for (auto& billboard : _billboards) + { billboard->setMode(BillBoard::Mode::VIEW_PLANE_ORIENTED); } } @@ -242,7 +239,7 @@ void BillBoardTest::addNewBillBoardWithCoords(Vec3 p) billboard->setScale(0.5f); billboard->setPosition3D(Vec3(p.x, p.y, -150.0f + 30 * i)); billboard->setOpacity(static_cast(CCRANDOM_0_1() * 128 + 128)); - + _layerBillBoard->addChild(billboard); _billboards.push_back(billboard); } @@ -253,11 +250,11 @@ void BillBoardTest::addNewAniBillBoardWithCoords(Vec3 p) { auto billboardAni = BillBoard::create("Images/grossini.png"); billboardAni->setScale(0.5f); - billboardAni->setPosition3D(Vec3(p.x, p.y, -150.0f + 30 * i)); + billboardAni->setPosition3D(Vec3(p.x, p.y, -150.0f + 30 * i)); _layerBillBoard->addChild(billboardAni); auto animation = Animation::create(); - for( int i=1;i<15;i++) + for (int i = 1; i < 15; i++) { char szName1[100] = {0}; sprintf(szName1, "Images/grossini_dance_%02d.png", i); @@ -273,37 +270,35 @@ void BillBoardTest::addNewAniBillBoardWithCoords(Vec3 p) _billboards.push_back(billboardAni); } } -void BillBoardTest::update(float dt) -{ -} +void BillBoardTest::update(float dt) {} void BillBoardTest::onTouchesMoved(const std::vector& touches, Event* event) { - if(touches.size()==1) + if (touches.size() == 1) { - auto touch = touches[0]; - auto location = touch->getLocation(); + auto touch = touches[0]; + auto location = touch->getLocation(); auto PreviousLocation = touch->getPreviousLocation(); - Point newPos = PreviousLocation - location; + Point newPos = PreviousLocation - location; Vec3 cameraDir; Vec3 cameraRightDir; _camera->getNodeToWorldTransform().getForwardVector(&cameraDir); cameraDir.normalize(); - cameraDir.y=0; + cameraDir.y = 0; _camera->getNodeToWorldTransform().getRightVector(&cameraRightDir); cameraRightDir.normalize(); - cameraRightDir.y=0; - Vec3 cameraPos= _camera->getPosition3D(); - cameraPos+=cameraDir*newPos.y*0.5; - cameraPos+=cameraRightDir*newPos.x*0.5; - _camera->setPosition3D(cameraPos); + cameraRightDir.y = 0; + Vec3 cameraPos = _camera->getPosition3D(); + cameraPos += cameraDir * newPos.y * 0.5; + cameraPos += cameraRightDir * newPos.x * 0.5; + _camera->setPosition3D(cameraPos); } } -void BillBoardTest::rotateCameraCallback(Ref* sender,float value) +void BillBoardTest::rotateCameraCallback(Ref* sender, float value) { - Vec3 rotation3D= _camera->getRotation3D(); - rotation3D.y+= value; + Vec3 rotation3D = _camera->getRotation3D(); + rotation3D.y += value; _camera->setRotation3D(rotation3D); } diff --git a/tests/cpp-tests/Classes/BillBoardTest/BillBoardTest.h b/tests/cpp-tests/Classes/BillBoardTest/BillBoardTest.h index d53779089749..729091065107 100644 --- a/tests/cpp-tests/Classes/BillBoardTest/BillBoardTest.h +++ b/tests/cpp-tests/Classes/BillBoardTest/BillBoardTest.h @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2013 cocos2d-x.org Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -29,10 +29,11 @@ #include "../BaseTest.h" #include -namespace cocos2d { - class BillBoard; - class Camera; -} +namespace cocos2d +{ +class BillBoard; +class Camera; +} // namespace cocos2d class BillBoardRotationTest : public TestCase { @@ -42,7 +43,7 @@ class BillBoardRotationTest : public TestCase virtual ~BillBoardRotationTest(); virtual std::string title() const override; virtual std::string subtitle() const override; - + protected: }; @@ -57,15 +58,15 @@ class BillBoardTest : public TestCase virtual void update(float dt) override; void addNewBillBoardWithCoords(cocos2d::Vec3 p); void addNewAniBillBoardWithCoords(cocos2d::Vec3 p); - void rotateCameraCallback(cocos2d::Ref* sender,float value); + void rotateCameraCallback(cocos2d::Ref* sender, float value); void onTouchesMoved(const std::vector& touches, cocos2d::Event* event); - + void menuCallback_orientedPoint(cocos2d::Ref* sender); void menuCallback_orientedPlane(cocos2d::Ref* sender); - + protected: - cocos2d::Camera* _camera; - cocos2d::Layer* _layerBillBoard; + cocos2d::Camera* _camera; + cocos2d::Layer* _layerBillBoard; std::vector _billboards; }; diff --git a/tests/cpp-tests/Classes/Box2DTest/Box2dTest.cpp b/tests/cpp-tests/Classes/Box2DTest/Box2dTest.cpp index 52f3a16bd400..1461f8505883 100644 --- a/tests/cpp-tests/Classes/Box2DTest/Box2dTest.cpp +++ b/tests/cpp-tests/Classes/Box2DTest/Box2dTest.cpp @@ -29,18 +29,16 @@ #include "renderer/CCRenderer.h" #include "renderer/CCCustomCommand.h" - - USING_NS_CC; USING_NS_CC_EXT; #define PTM_RATIO 32 -enum { +enum +{ kTagParentNode = 1, }; - Box2DTests::Box2DTests() { ADD_TEST_CASE(Box2DTest); @@ -51,7 +49,6 @@ std::string Box2DTest::title() const return "Box2D - Basic"; } - bool Box2DTest::init() { if (!TestCase::init()) @@ -60,35 +57,34 @@ bool Box2DTest::init() } auto dispatcher = Director::getInstance()->getEventDispatcher(); - auto touchListener = EventListenerTouchAllAtOnce::create(); + auto touchListener = EventListenerTouchAllAtOnce::create(); touchListener->onTouchesEnded = CC_CALLBACK_2(Box2DTest::onTouchesEnded, this); dispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); - // init physics this->initPhysics(); // create reset button this->createResetButton(); - //Set up sprite + // Set up sprite #if 1 // Use batch node. Faster - auto parent = SpriteBatchNode::create("Images/blocks.png", 100); + auto parent = SpriteBatchNode::create("Images/blocks.png", 100); _spriteTexture = parent->getTexture(); #else // doesn't use batch node. Slower _spriteTexture = Director::getInstance()->getTextureCache()->addImage("Images/blocks.png"); - auto parent = Node::create(); + auto parent = Node::create(); #endif addChild(parent, 0, kTagParentNode); - addNewSpriteAtPosition(VisibleRect::center()); - auto label = Label::createWithTTF("Tap screen add boxes.\nSome objects be only visible with debug on.", "fonts/Marker Felt.ttf", 12.0f); + auto label = Label::createWithTTF("Tap screen add boxes.\nSome objects be only visible with debug on.", + "fonts/Marker Felt.ttf", 12.0f); addChild(label, 0); label->setColor(Color3B(0, 0, 255)); - label->setPosition(VisibleRect::center().x-50, VisibleRect::top().y - 60); + label->setPosition(VisibleRect::center().x - 50, VisibleRect::top().y - 60); // menu for debug layer MenuItemFont::setFontSize(18); @@ -107,26 +103,19 @@ bool Box2DTest::init() return true; } -Box2DTest::Box2DTest() - : _spriteTexture(nullptr) - , world(nullptr) -{ - -} +Box2DTest::Box2DTest() : _spriteTexture(nullptr), world(nullptr) {} Box2DTest::~Box2DTest() { CC_SAFE_DELETE(world); } - void Box2DTest::toggleDebugCallback(Ref* sender) { showDebugDraw = !showDebugDraw; - drawBox2D->clear(); + drawBox2D->clear(); } - void Box2DTest::initPhysics() { b2Vec2 gravity; @@ -140,7 +129,7 @@ void Box2DTest::initPhysics() // Define the ground body. b2BodyDef groundBodyDef; - groundBodyDef.position.Set(0, 0); // bottom-left corner + groundBodyDef.position.Set(0, 0); // bottom-left corner // Call the body factory which allocates memory for the ground body // from a pool and creates the ground box shape (also from a pool). @@ -151,22 +140,25 @@ void Box2DTest::initPhysics() b2EdgeShape groundBox; // bottom - groundBox.SetTwoSided(b2Vec2(VisibleRect::leftBottom().x / PTM_RATIO, VisibleRect::leftBottom().y / PTM_RATIO), b2Vec2(VisibleRect::rightBottom().x / PTM_RATIO, VisibleRect::rightBottom().y / PTM_RATIO)); + groundBox.SetTwoSided(b2Vec2(VisibleRect::leftBottom().x / PTM_RATIO, VisibleRect::leftBottom().y / PTM_RATIO), + b2Vec2(VisibleRect::rightBottom().x / PTM_RATIO, VisibleRect::rightBottom().y / PTM_RATIO)); groundBody->CreateFixture(&groundBox, 0); // top - groundBox.SetTwoSided(b2Vec2(VisibleRect::leftTop().x / PTM_RATIO, VisibleRect::leftTop().y / PTM_RATIO), b2Vec2(VisibleRect::rightTop().x / PTM_RATIO, VisibleRect::rightTop().y / PTM_RATIO)); + groundBox.SetTwoSided(b2Vec2(VisibleRect::leftTop().x / PTM_RATIO, VisibleRect::leftTop().y / PTM_RATIO), + b2Vec2(VisibleRect::rightTop().x / PTM_RATIO, VisibleRect::rightTop().y / PTM_RATIO)); groundBody->CreateFixture(&groundBox, 0); // left - groundBox.SetTwoSided(b2Vec2(VisibleRect::leftTop().x / PTM_RATIO, VisibleRect::leftTop().y / PTM_RATIO), b2Vec2(VisibleRect::leftBottom().x / PTM_RATIO, VisibleRect::leftBottom().y / PTM_RATIO)); + groundBox.SetTwoSided(b2Vec2(VisibleRect::leftTop().x / PTM_RATIO, VisibleRect::leftTop().y / PTM_RATIO), + b2Vec2(VisibleRect::leftBottom().x / PTM_RATIO, VisibleRect::leftBottom().y / PTM_RATIO)); groundBody->CreateFixture(&groundBox, 0); // right - groundBox.SetTwoSided(b2Vec2(VisibleRect::rightBottom().x / PTM_RATIO, VisibleRect::rightBottom().y / PTM_RATIO), b2Vec2(VisibleRect::rightTop().x / PTM_RATIO, VisibleRect::rightTop().y / PTM_RATIO)); + groundBox.SetTwoSided(b2Vec2(VisibleRect::rightBottom().x / PTM_RATIO, VisibleRect::rightBottom().y / PTM_RATIO), + b2Vec2(VisibleRect::rightTop().x / PTM_RATIO, VisibleRect::rightTop().y / PTM_RATIO)); groundBody->CreateFixture(&groundBox, 0); - // Small triangle b2Vec2 vertices[3]; vertices[0].Set(-1.0f, 0.0f); @@ -177,7 +169,7 @@ void Box2DTest::initPhysics() polygon.Set(vertices, 3); b2FixtureDef triangleShapeDef; - triangleShapeDef.shape = &polygon; + triangleShapeDef.shape = &polygon; triangleShapeDef.density = 1.0f; b2BodyDef triangleBodyDef; @@ -202,7 +194,7 @@ void Box2DTest::initPhysics() polygon.SetAsBox(1.0f, 0.5f); b2FixtureDef boxShapeDef; - boxShapeDef.shape = &polygon; + boxShapeDef.shape = &polygon; boxShapeDef.density = 1.0f; b2BodyDef boxBodyDef; @@ -224,7 +216,7 @@ void Box2DTest::initPhysics() circle.m_radius = 1.0f; b2FixtureDef circleShapeDef; - circleShapeDef.shape = &circle; + circleShapeDef.shape = &circle; circleShapeDef.density = 1.0f; b2BodyDef circleBodyDef; @@ -247,16 +239,15 @@ void Box2DTest::initPhysics() flags += 0 * b2Draw::e_aabbBit; flags += 0 * b2Draw::e_centerOfMassBit; g_debugDraw.SetFlags(flags); - g_debugDraw.mRatio = PTM_RATIO; - g_debugDraw.debugNodeOffset = { 0, 0 }; + g_debugDraw.mRatio = PTM_RATIO; + g_debugDraw.debugNodeOffset = {0, 0}; world->SetDebugDraw(&g_debugDraw); } void Box2DTest::createResetButton() { - auto reset = MenuItemImage::create("Images/r1.png", "Images/r2.png", [&](Ref* sender) { - getTestSuite()->restartCurrTest(); - }); + auto reset = MenuItemImage::create("Images/r1.png", "Images/r2.png", + [&](Ref* sender) { getTestSuite()->restartCurrTest(); }); auto menu = Menu::create(reset, nullptr); @@ -269,7 +260,7 @@ void Box2DTest::addNewSpriteAtPosition(Vec2 p) CCLOG("Add sprite %0.2f x %02.f", p.x, p.y); // Define the dynamic body. - //Set up a 1m squared box in the physics world + // Set up a 1m squared box in the physics world b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; bodyDef.position.Set(p.x / PTM_RATIO, p.y / PTM_RATIO); @@ -280,21 +271,21 @@ void Box2DTest::addNewSpriteAtPosition(Vec2 p) // Define another box shape for our dynamic body. b2PolygonShape dynamicBox; - dynamicBox.SetAsBox(.5f, .5f);//These are mid points for our 1m box + dynamicBox.SetAsBox(.5f, .5f); // These are mid points for our 1m box // Define the dynamic body fixture. b2FixtureDef fixtureDef; - fixtureDef.shape = &dynamicBox; - fixtureDef.density = 1.0f; + fixtureDef.shape = &dynamicBox; + fixtureDef.density = 1.0f; fixtureDef.friction = 0.3f; body->CreateFixture(&fixtureDef); auto parent = this->getChildByTag(kTagParentNode); - //We have a 64x64 sprite sheet with 4 different 32x32 images. The following code is - //just randomly picking one of the images - int idx = (CCRANDOM_0_1() > .5 ? 0 : 1); - int idy = (CCRANDOM_0_1() > .5 ? 0 : 1); + // We have a 64x64 sprite sheet with 4 different 32x32 images. The following code is + // just randomly picking one of the images + int idx = (CCRANDOM_0_1() > .5 ? 0 : 1); + int idy = (CCRANDOM_0_1() > .5 ? 0 : 1); auto sprite = PhysicsSpriteBox2D::createWithTexture(_spriteTexture, Rect(32 * idx, 32 * idy, 32, 32)); parent->addChild(sprite); sprite->setB2Body(body); @@ -304,10 +295,10 @@ void Box2DTest::addNewSpriteAtPosition(Vec2 p) void Box2DTest::update(float dt) { - //It is recommended that a fixed time step is used with Box2D for stability - //of the simulation, however, we are using a variable time step here. - //You need to make an informed choice, the following URL is useful - //http://gafferongames.com/game-physics/fix-your-timestep/ + // It is recommended that a fixed time step is used with Box2D for stability + // of the simulation, however, we are using a variable time step here. + // You need to make an informed choice, the following URL is useful + // http://gafferongames.com/game-physics/fix-your-timestep/ int velocityIterations = 8; int positionIterations = 1; @@ -316,19 +307,17 @@ void Box2DTest::update(float dt) // generally best to keep the time step and iterations fixed. world->Step(dt, velocityIterations, positionIterations); - // Debug draw if (showDebugDraw) { drawBox2D->clear(); world->DebugDraw(); } - } void Box2DTest::onTouchesEnded(const std::vector& touches, Event* event) { - //Add a new body/atlas sprite at the touched location + // Add a new body/atlas sprite at the touched location for (auto& touch : touches) { diff --git a/tests/cpp-tests/Classes/Box2DTest/Box2dTest.h b/tests/cpp-tests/Classes/Box2DTest/Box2dTest.h index d98406d746a9..f11f92fe08fc 100644 --- a/tests/cpp-tests/Classes/Box2DTest/Box2dTest.h +++ b/tests/cpp-tests/Classes/Box2DTest/Box2dTest.h @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. Copyright (c) 2021 @aismann; Peter Eismann, Germany; dreifrankensoft - + 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 @@ -33,7 +33,6 @@ DEFINE_TEST_SUITE(Box2DTests); - class Box2DTest : public TestCase { public: @@ -61,6 +60,6 @@ class Box2DTest : public TestCase cocos2d::DrawNode* drawBox2D; cocos2d::extension::PhysicsDebugNodeBox2D g_debugDraw; bool showDebugDraw = true; -} ; +}; #endif \ No newline at end of file diff --git a/tests/cpp-tests/Classes/Box2DTestBed/Box2DTestBed.cpp b/tests/cpp-tests/Classes/Box2DTestBed/Box2DTestBed.cpp index 1b95100a080d..76c03de9ff3e 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/Box2DTestBed.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/Box2DTestBed.cpp @@ -34,8 +34,9 @@ USING_NS_CC; USING_NS_CC_EXT; -enum { - kTagParentNode = 1, +enum +{ + kTagParentNode = 1, }; Settings settings; @@ -43,34 +44,31 @@ cocos2d::Label* labelDebugDraw; enum { - kTagBox2DNode, + kTagBox2DNode, }; - -TestEntry g_testEntries[MAX_TESTS] = { {nullptr} }; -int g_testCount = 0; +TestEntry g_testEntries[MAX_TESTS] = {{nullptr}}; +int g_testCount = 0; int RegisterTest(const char* category, const char* name, TestCreateFcn* fcn) { - int index = g_testCount; - if (index < MAX_TESTS) - { - g_testEntries[index] = { category, name, fcn }; - ++g_testCount; - return index; - } - - return -1; + int index = g_testCount; + if (index < MAX_TESTS) + { + g_testEntries[index] = {category, name, fcn}; + ++g_testCount; + return index; + } + + return -1; } Box2DTestBedTests::Box2DTestBedTests() { - for (int entryId = 0; entryId < g_testCount; ++entryId) - { - addTestCase(g_testEntries[entryId].name, [entryId]() { - return Box2DTestBed::createWithEntryID(entryId); - }); - } + for (int entryId = 0; entryId < g_testCount; ++entryId) + { + addTestCase(g_testEntries[entryId].name, [entryId]() { return Box2DTestBed::createWithEntryID(entryId); }); + } } //------------------------------------------------------------------ @@ -79,205 +77,202 @@ Box2DTestBedTests::Box2DTestBedTests() // //------------------------------------------------------------------ -Box2DTestBed::Box2DTestBed() -{ -} +Box2DTestBed::Box2DTestBed() {} Box2DTestBed::~Box2DTestBed() { - Layer::_eventDispatcher->removeEventListener(_touchListener); + Layer::_eventDispatcher->removeEventListener(_touchListener); } Box2DTestBed* Box2DTestBed::createWithEntryID(int entryId) { - auto layer = new Box2DTestBed(); - layer->initWithEntryID(entryId); -// layer->autorelease(); + auto layer = new Box2DTestBed(); + layer->initWithEntryID(entryId); + // layer->autorelease(); - return layer; + return layer; } bool Box2DTestBed::initWithEntryID(int entryId) { - if (!TestCase::init()) - { - return false; - } - auto director = Director::getInstance(); - Vec2 visibleOrigin = director->getVisibleOrigin(); - Size visibleSize = director->getVisibleSize(); - - m_entryID = entryId; - - m_entry = g_testEntries + entryId; - m_test = m_entry->createFcn(); - - debugDrawNode = g_debugDraw.GetDrawNode(); - m_test->debugDrawNode = debugDrawNode; - m_test->g_debugDraw = g_debugDraw; - - TestCase::addChild(debugDrawNode, 100); - - // init physics - this->initPhysics(); - - auto label = Label::createWithTTF(m_entry->name, "fonts/arial.ttf", 28); - TestCase::addChild(label, 1); - label->setPosition(visibleOrigin.x + visibleSize.width / 2, visibleOrigin.y + visibleSize.height - 50); - - // Adds touch event listener - _touchListener = EventListenerTouchOneByOne::create(); - _touchListener->setSwallowTouches(true); - _touchListener->onTouchBegan = CC_CALLBACK_2(Box2DTestBed::onTouchBegan, this); - _touchListener->onTouchMoved = CC_CALLBACK_2(Box2DTestBed::onTouchMoved, this); - _touchListener->onTouchEnded = CC_CALLBACK_2(Box2DTestBed::onTouchEnded, this); - TestCase::_eventDispatcher->addEventListenerWithFixedPriority(_touchListener,10); - - // Adds Keyboard event listener - _keyboardListener = EventListenerKeyboard::create(); - _keyboardListener->onKeyPressed = CC_CALLBACK_2(Box2DTestBed::onKeyPressed, this); - _keyboardListener->onKeyReleased = CC_CALLBACK_2(Box2DTestBed::onKeyReleased, this); - TestCase::_eventDispatcher->addEventListenerWithFixedPriority(_keyboardListener,11); - - auto _mouseListener = EventListenerMouse::create(); - _mouseListener->onMouseMove = CC_CALLBACK_1(Box2DTestBed::onMouseMove, this); - _mouseListener->onMouseUp = CC_CALLBACK_1(Box2DTestBed::onMouseUp, this); - _mouseListener->onMouseDown = CC_CALLBACK_1(Box2DTestBed::onMouseDown, this); - _mouseListener->onMouseScroll = CC_CALLBACK_1(Box2DTestBed::onMouseScroll, this); - TestCase::_eventDispatcher->addEventListenerWithFixedPriority(_mouseListener, 12); - - // Demo messageString - labelDebugDraw = Label::createWithTTF("TEST", "fonts/arial.ttf", 8.0f); - labelDebugDraw->setAnchorPoint(Vec2(0, 1)); - labelDebugDraw->setPosition(VisibleRect::left().x, VisibleRect::top().y - 10); - labelDebugDraw->setColor(Color3B::WHITE); - TestCase::addChild(labelDebugDraw, 100); - - TestCase::scheduleUpdate(); - - return true; + if (!TestCase::init()) + { + return false; + } + auto director = Director::getInstance(); + Vec2 visibleOrigin = director->getVisibleOrigin(); + Size visibleSize = director->getVisibleSize(); + + m_entryID = entryId; + + m_entry = g_testEntries + entryId; + m_test = m_entry->createFcn(); + + debugDrawNode = g_debugDraw.GetDrawNode(); + m_test->debugDrawNode = debugDrawNode; + m_test->g_debugDraw = g_debugDraw; + + TestCase::addChild(debugDrawNode, 100); + + // init physics + this->initPhysics(); + + auto label = Label::createWithTTF(m_entry->name, "fonts/arial.ttf", 28); + TestCase::addChild(label, 1); + label->setPosition(visibleOrigin.x + visibleSize.width / 2, visibleOrigin.y + visibleSize.height - 50); + + // Adds touch event listener + _touchListener = EventListenerTouchOneByOne::create(); + _touchListener->setSwallowTouches(true); + _touchListener->onTouchBegan = CC_CALLBACK_2(Box2DTestBed::onTouchBegan, this); + _touchListener->onTouchMoved = CC_CALLBACK_2(Box2DTestBed::onTouchMoved, this); + _touchListener->onTouchEnded = CC_CALLBACK_2(Box2DTestBed::onTouchEnded, this); + TestCase::_eventDispatcher->addEventListenerWithFixedPriority(_touchListener, 10); + + // Adds Keyboard event listener + _keyboardListener = EventListenerKeyboard::create(); + _keyboardListener->onKeyPressed = CC_CALLBACK_2(Box2DTestBed::onKeyPressed, this); + _keyboardListener->onKeyReleased = CC_CALLBACK_2(Box2DTestBed::onKeyReleased, this); + TestCase::_eventDispatcher->addEventListenerWithFixedPriority(_keyboardListener, 11); + + auto _mouseListener = EventListenerMouse::create(); + _mouseListener->onMouseMove = CC_CALLBACK_1(Box2DTestBed::onMouseMove, this); + _mouseListener->onMouseUp = CC_CALLBACK_1(Box2DTestBed::onMouseUp, this); + _mouseListener->onMouseDown = CC_CALLBACK_1(Box2DTestBed::onMouseDown, this); + _mouseListener->onMouseScroll = CC_CALLBACK_1(Box2DTestBed::onMouseScroll, this); + TestCase::_eventDispatcher->addEventListenerWithFixedPriority(_mouseListener, 12); + + // Demo messageString + labelDebugDraw = Label::createWithTTF("TEST", "fonts/arial.ttf", 8.0f); + labelDebugDraw->setAnchorPoint(Vec2(0, 1)); + labelDebugDraw->setPosition(VisibleRect::left().x, VisibleRect::top().y - 10); + labelDebugDraw->setColor(Color3B::WHITE); + TestCase::addChild(labelDebugDraw, 100); + + TestCase::scheduleUpdate(); + + return true; } bool Box2DTestBed::onTouchBegan(Touch* touch, Event* event) { - auto location = touch->getLocation() - g_debugDraw.debugNodeOffset; - b2Vec2 pos = { location.x / g_debugDraw.mRatio, location.y / g_debugDraw.mRatio }; - return m_test->MouseDown(pos); + auto location = touch->getLocation() - g_debugDraw.debugNodeOffset; + b2Vec2 pos = {location.x / g_debugDraw.mRatio, location.y / g_debugDraw.mRatio}; + return m_test->MouseDown(pos); } void Box2DTestBed::onTouchMoved(Touch* touch, Event* event) { - auto location = touch->getLocation() - g_debugDraw.debugNodeOffset; - b2Vec2 pos = { location.x / g_debugDraw.mRatio, location.y / g_debugDraw.mRatio }; - m_test->MouseMove(pos); + auto location = touch->getLocation() - g_debugDraw.debugNodeOffset; + b2Vec2 pos = {location.x / g_debugDraw.mRatio, location.y / g_debugDraw.mRatio}; + m_test->MouseMove(pos); } void Box2DTestBed::onTouchEnded(Touch* touch, Event* event) { - auto location = touch->getLocation() - g_debugDraw.debugNodeOffset; - b2Vec2 pos = { location.x / g_debugDraw.mRatio, location.y / g_debugDraw.mRatio }; - m_test->MouseUp(pos); + auto location = touch->getLocation() - g_debugDraw.debugNodeOffset; + b2Vec2 pos = {location.x / g_debugDraw.mRatio, location.y / g_debugDraw.mRatio}; + m_test->MouseUp(pos); } void Box2DTestBed::onKeyPressed(EventKeyboard::KeyCode code, Event* event) { - CCLOG("onKeyPressed, keycode: %d", static_cast(code)); - m_test->Keyboard((static_cast(code) - 59)); // its a bad hack! + CCLOG("onKeyPressed, keycode: %d", static_cast(code)); + m_test->Keyboard((static_cast(code) - 59)); // its a bad hack! } void Box2DTestBed::onKeyReleased(EventKeyboard::KeyCode code, Event* event) { - CCLOG("onKeyPressed, keycode: %d", static_cast(code)); - m_test->KeyboardUp((static_cast(code) - 59)); // its a bad hack! - + CCLOG("onKeyPressed, keycode: %d", static_cast(code)); + m_test->KeyboardUp((static_cast(code) - 59)); // its a bad hack! } void Box2DTestBed::onMouseDown(Event* event) { - EventMouse* e = (EventMouse*)event; - switch (e->getMouseButton()) - { - button[(int)EventMouse::MouseButton::BUTTON_LEFT] = false; - button[(int)EventMouse::MouseButton::BUTTON_RIGHT] = false; - button[(int)EventMouse::MouseButton::BUTTON_MIDDLE] = false; - case EventMouse::MouseButton::BUTTON_LEFT: - button[(int)EventMouse::MouseButton::BUTTON_LEFT] = true; - break; - case EventMouse::MouseButton::BUTTON_RIGHT: - button[(int)EventMouse::MouseButton::BUTTON_RIGHT] = true; - break; - case EventMouse::MouseButton::BUTTON_MIDDLE: - button[(int)EventMouse::MouseButton::BUTTON_MIDDLE] = true; - break; - } + EventMouse* e = (EventMouse*)event; + switch (e->getMouseButton()) + { + button[(int)EventMouse::MouseButton::BUTTON_LEFT] = false; + button[(int)EventMouse::MouseButton::BUTTON_RIGHT] = false; + button[(int)EventMouse::MouseButton::BUTTON_MIDDLE] = false; + case EventMouse::MouseButton::BUTTON_LEFT: + button[(int)EventMouse::MouseButton::BUTTON_LEFT] = true; + break; + case EventMouse::MouseButton::BUTTON_RIGHT: + button[(int)EventMouse::MouseButton::BUTTON_RIGHT] = true; + break; + case EventMouse::MouseButton::BUTTON_MIDDLE: + button[(int)EventMouse::MouseButton::BUTTON_MIDDLE] = true; + break; + } } void Box2DTestBed::onMouseUp(Event* event) { - button[(int)EventMouse::MouseButton::BUTTON_LEFT] = false; - button[(int)EventMouse::MouseButton::BUTTON_RIGHT] = false; - button[(int)EventMouse::MouseButton::BUTTON_MIDDLE] = false; + button[(int)EventMouse::MouseButton::BUTTON_LEFT] = false; + button[(int)EventMouse::MouseButton::BUTTON_RIGHT] = false; + button[(int)EventMouse::MouseButton::BUTTON_MIDDLE] = false; } void Box2DTestBed::onMouseMove(Event* event) { - EventMouse* e = (EventMouse*)event; - pos = { e->getCursorX() / g_debugDraw.mRatio , e->getCursorY() / g_debugDraw.mRatio }; - - if (button[(int)EventMouse::MouseButton::BUTTON_RIGHT]) - { - (pos.x > oldPos.x) ? g_debugDraw.debugNodeOffset.x += 4 : g_debugDraw.debugNodeOffset.x -= 4; - (pos.y < oldPos.y) ? g_debugDraw.debugNodeOffset.y -= 2 : g_debugDraw.debugNodeOffset.y += 2; - } - oldPos = pos; + EventMouse* e = (EventMouse*)event; + pos = {e->getCursorX() / g_debugDraw.mRatio, e->getCursorY() / g_debugDraw.mRatio}; + + if (button[(int)EventMouse::MouseButton::BUTTON_RIGHT]) + { + (pos.x > oldPos.x) ? g_debugDraw.debugNodeOffset.x += 4 : g_debugDraw.debugNodeOffset.x -= 4; + (pos.y < oldPos.y) ? g_debugDraw.debugNodeOffset.y -= 2 : g_debugDraw.debugNodeOffset.y += 2; + } + oldPos = pos; } void Box2DTestBed::onMouseScroll(Event* event) { - EventMouse* e = (EventMouse*)event; - g_debugDraw.mRatio += e->getScrollY(); + EventMouse* e = (EventMouse*)event; + g_debugDraw.mRatio += e->getScrollY(); } void Box2DTestBed::onEnter() { - Scene::onEnter(); - ImGuiEXT::getInstance()->addFont(FileUtils::getInstance()->fullPathForFilename("fonts/arial.ttf")); - ImGuiEXT::getInstance()->addRenderLoop("#im01", CC_CALLBACK_0(Box2DTestBed::onDrawImGui, this), this); + Scene::onEnter(); + ImGuiEXT::getInstance()->addFont(FileUtils::getInstance()->fullPathForFilename("fonts/arial.ttf")); + ImGuiEXT::getInstance()->addRenderLoop("#im01", CC_CALLBACK_0(Box2DTestBed::onDrawImGui, this), this); } void Box2DTestBed::onExit() { - Scene::onExit(); - ImGuiEXT::getInstance()->removeRenderLoop("#im01"); + Scene::onExit(); + ImGuiEXT::getInstance()->removeRenderLoop("#im01"); } void Box2DTestBed::update(float dt) { - // Debug draw - m_test->debugString = ""; - labelDebugDraw->setString(""); - debugDrawNode->clear(); - m_test->Step(settings); - m_test->m_world->DebugDraw(); + // Debug draw + m_test->debugString = ""; + labelDebugDraw->setString(""); + debugDrawNode->clear(); + m_test->Step(settings); + m_test->m_world->DebugDraw(); } void Box2DTestBed::initPhysics() { - uint32 flags = 0; - flags += 1 * b2Draw::e_shapeBit; - flags += 1 * b2Draw::e_jointBit; - flags += 0 * b2Draw::e_aabbBit; - flags += 0 * b2Draw::e_centerOfMassBit; - g_debugDraw.SetFlags(flags); - g_debugDraw.mRatio = 8; - m_test->m_world->SetDebugDraw(&g_debugDraw); - m_test->g_debugDraw = g_debugDraw; - g_debugDraw.debugNodeOffset = { 250, 70 }; - m_test->g_debugDraw.debugNodeOffset = g_debugDraw.debugNodeOffset; - - settings.m_hertz = 60; + uint32 flags = 0; + flags += 1 * b2Draw::e_shapeBit; + flags += 1 * b2Draw::e_jointBit; + flags += 0 * b2Draw::e_aabbBit; + flags += 0 * b2Draw::e_centerOfMassBit; + g_debugDraw.SetFlags(flags); + g_debugDraw.mRatio = 8; + m_test->m_world->SetDebugDraw(&g_debugDraw); + m_test->g_debugDraw = g_debugDraw; + g_debugDraw.debugNodeOffset = {250, 70}; + m_test->g_debugDraw.debugNodeOffset = g_debugDraw.debugNodeOffset; + + settings.m_hertz = 60; } void Box2DTestBed::onDrawImGui() { - m_test->UpdateUI(); + m_test->UpdateUI(); } \ No newline at end of file diff --git a/tests/cpp-tests/Classes/Box2DTestBed/Box2DTestBed.h b/tests/cpp-tests/Classes/Box2DTestBed/Box2DTestBed.h index ef82f8bdf86f..40fd87846750 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/Box2DTestBed.h +++ b/tests/cpp-tests/Classes/Box2DTestBed/Box2DTestBed.h @@ -31,15 +31,14 @@ DEFINE_TEST_SUITE(Box2DTestBedTests); - class Test; typedef Test* TestCreateFcn(); struct TestEntry { - const char* category; - const char* name; - TestCreateFcn* createFcn; + const char* category; + const char* name; + TestCreateFcn* createFcn; }; #define MAX_TESTS 256 @@ -50,55 +49,53 @@ int RegisterTest(const char* category, const char* name, TestCreateFcn* fcn); class Box2DTestBed : public TestCase, cocos2d::Layer { public: - static Box2DTestBed* createWithEntryID(int entryId); + static Box2DTestBed* createWithEntryID(int entryId); - Box2DTestBed(); - virtual ~Box2DTestBed(); + Box2DTestBed(); + virtual ~Box2DTestBed(); - void onEnter() override; - void onExit() override; + void onEnter() override; + void onExit() override; - void onDrawImGui(); + void onDrawImGui(); - void initPhysics(); - void update(float dt) override; + void initPhysics(); + void update(float dt) override; - void createResetButton(); + void createResetButton(); - bool initWithEntryID(int entryId); + bool initWithEntryID(int entryId); - bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event); - void onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event); - void onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event); + bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event); + void onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event); + void onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event); - void onKeyPressed(cocos2d::EventKeyboard::KeyCode code, cocos2d::Event* event); - void onKeyReleased(cocos2d::EventKeyboard::KeyCode code, cocos2d::Event* event); + void onKeyPressed(cocos2d::EventKeyboard::KeyCode code, cocos2d::Event* event); + void onKeyReleased(cocos2d::EventKeyboard::KeyCode code, cocos2d::Event* event); - void onMouseDown(cocos2d::Event* event); - void onMouseUp(cocos2d::Event* event); - void onMouseMove(cocos2d::Event* event); - void onMouseScroll(cocos2d::Event* event); + void onMouseDown(cocos2d::Event* event); + void onMouseUp(cocos2d::Event* event); + void onMouseMove(cocos2d::Event* event); + void onMouseScroll(cocos2d::Event* event); - cocos2d::EventListenerTouchOneByOne* _touchListener; - cocos2d::EventListenerKeyboard* _keyboardListener; + cocos2d::EventListenerTouchOneByOne* _touchListener; + cocos2d::EventListenerKeyboard* _keyboardListener; - TestEntry* m_entry; - Test* m_test; - int m_entryID; + TestEntry* m_entry; + Test* m_test; + int m_entryID; private: + b2World* world; + cocos2d::Texture2D* _spriteTexture; - b2World* world; - cocos2d::Texture2D* _spriteTexture; - - b2Vec2 pos; - b2Vec2 oldPos; - bool button[2]; - - // Debug stuff - cocos2d::DrawNode* debugDrawNode; - cocos2d::extension::PhysicsDebugNodeBox2D g_debugDraw; + b2Vec2 pos; + b2Vec2 oldPos; + bool button[2]; + // Debug stuff + cocos2d::DrawNode* debugDrawNode; + cocos2d::extension::PhysicsDebugNodeBox2D g_debugDraw; }; #endif diff --git a/tests/cpp-tests/Classes/Box2DTestBed/test.cpp b/tests/cpp-tests/Classes/Box2DTestBed/test.cpp index 5d88954b276e..1c60abf38593 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/test.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/test.cpp @@ -1,20 +1,20 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ + * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + */ #include "tests/test.h" #include "tests/settings.h" @@ -31,471 +31,476 @@ USING_NS_CC_EXT; extern cocos2d::Label* labelDebugDraw; #endif -void DestructionListener::SayGoodbye(b2Joint * joint) +void DestructionListener::SayGoodbye(b2Joint* joint) { - if (test->m_mouseJoint == joint) - { - test->m_mouseJoint = NULL; - } - else - { - test->JointDestroyed(joint); - } + if (test->m_mouseJoint == joint) + { + test->m_mouseJoint = NULL; + } + else + { + test->JointDestroyed(joint); + } } Test::Test() { - b2Vec2 gravity; - gravity.Set(0.0f, -10.0f); - m_world = new b2World(gravity); - m_bomb = NULL; - m_textLine = 30; - m_textIncrement = 13; - m_mouseJoint = NULL; - m_pointCount = 0; + b2Vec2 gravity; + gravity.Set(0.0f, -10.0f); + m_world = new b2World(gravity); + m_bomb = NULL; + m_textLine = 30; + m_textIncrement = 13; + m_mouseJoint = NULL; + m_pointCount = 0; - m_destructionListener.test = this; - m_world->SetDestructionListener(&m_destructionListener); - m_world->SetContactListener(this); - m_world->SetDebugDraw(&g_debugDraw); + m_destructionListener.test = this; + m_world->SetDestructionListener(&m_destructionListener); + m_world->SetContactListener(this); + m_world->SetDebugDraw(&g_debugDraw); - m_bombSpawning = false; + m_bombSpawning = false; - m_stepCount = 0; + m_stepCount = 0; - b2BodyDef bodyDef; - m_groundBody = m_world->CreateBody(&bodyDef); + b2BodyDef bodyDef; + m_groundBody = m_world->CreateBody(&bodyDef); - memset(&m_maxProfile, 0, sizeof(b2Profile)); - memset(&m_totalProfile, 0, sizeof(b2Profile)); + memset(&m_maxProfile, 0, sizeof(b2Profile)); + memset(&m_totalProfile, 0, sizeof(b2Profile)); } Test::~Test() { - // By deleting the world, we delete the bomb, mouse joint, etc. - delete m_world; - m_world = NULL; + // By deleting the world, we delete the bomb, mouse joint, etc. + delete m_world; + m_world = NULL; } -void Test::PreSolve(b2Contact * contact, const b2Manifold * oldManifold) +void Test::PreSolve(b2Contact* contact, const b2Manifold* oldManifold) { - const b2Manifold* manifold = contact->GetManifold(); - - if (manifold->pointCount == 0) - { - return; - } - - b2Fixture* fixtureA = contact->GetFixtureA(); - b2Fixture* fixtureB = contact->GetFixtureB(); - - b2PointState state1[b2_maxManifoldPoints], state2[b2_maxManifoldPoints]; - b2GetPointStates(state1, state2, oldManifold, manifold); - - b2WorldManifold worldManifold; - contact->GetWorldManifold(&worldManifold); - - for (int32 i = 0; i < manifold->pointCount && m_pointCount < k_maxContactPoints; ++i) - { - ContactPoint* cp = m_points + m_pointCount; - cp->fixtureA = fixtureA; - cp->fixtureB = fixtureB; - cp->position = worldManifold.points[i]; - cp->normal = worldManifold.normal; - cp->state = state2[i]; - cp->normalImpulse = manifold->points[i].normalImpulse; - cp->tangentImpulse = manifold->points[i].tangentImpulse; - cp->separation = worldManifold.separations[i]; - ++m_pointCount; - } + const b2Manifold* manifold = contact->GetManifold(); + + if (manifold->pointCount == 0) + { + return; + } + + b2Fixture* fixtureA = contact->GetFixtureA(); + b2Fixture* fixtureB = contact->GetFixtureB(); + + b2PointState state1[b2_maxManifoldPoints], state2[b2_maxManifoldPoints]; + b2GetPointStates(state1, state2, oldManifold, manifold); + + b2WorldManifold worldManifold; + contact->GetWorldManifold(&worldManifold); + + for (int32 i = 0; i < manifold->pointCount && m_pointCount < k_maxContactPoints; ++i) + { + ContactPoint* cp = m_points + m_pointCount; + cp->fixtureA = fixtureA; + cp->fixtureB = fixtureB; + cp->position = worldManifold.points[i]; + cp->normal = worldManifold.normal; + cp->state = state2[i]; + cp->normalImpulse = manifold->points[i].normalImpulse; + cp->tangentImpulse = manifold->points[i].tangentImpulse; + cp->separation = worldManifold.separations[i]; + ++m_pointCount; + } } void Test::DrawTitle(const char* string) { - DrawString(5, 5, string); - m_textLine = int32(26.0f); + DrawString(5, 5, string); + m_textLine = int32(26.0f); } class QueryCallback : public b2QueryCallback { public: - QueryCallback(const b2Vec2& point) - { - m_point = point; - m_fixture = NULL; - } - - bool ReportFixture(b2Fixture* fixture) override - { - b2Body* body = fixture->GetBody(); - if (body->GetType() == b2_dynamicBody) - { - bool inside = fixture->TestPoint(m_point); - if (inside) - { - m_fixture = fixture; - - // We are done, terminate the query. - return false; - } - } - - // Continue the query. - return true; - } - - b2Vec2 m_point; - b2Fixture* m_fixture; + QueryCallback(const b2Vec2& point) + { + m_point = point; + m_fixture = NULL; + } + + bool ReportFixture(b2Fixture* fixture) override + { + b2Body* body = fixture->GetBody(); + if (body->GetType() == b2_dynamicBody) + { + bool inside = fixture->TestPoint(m_point); + if (inside) + { + m_fixture = fixture; + + // We are done, terminate the query. + return false; + } + } + + // Continue the query. + return true; + } + + b2Vec2 m_point; + b2Fixture* m_fixture; }; -bool Test::MouseDown(const b2Vec2 & p) +bool Test::MouseDown(const b2Vec2& p) { - m_mouseWorld = p; - - if (m_mouseJoint != NULL) - { - return false; - } - - // Make a small box. - b2AABB aabb; - b2Vec2 d; - d.Set(0.001f, 0.001f); - aabb.lowerBound = p - d; - aabb.upperBound = p + d; - - // Query the world for overlapping shapes. - QueryCallback callback(p); - m_world->QueryAABB(&callback, aabb); - - if (callback.m_fixture) - { - float frequencyHz = 5.0f; - float dampingRatio = 0.7f; - - b2Body* body = callback.m_fixture->GetBody(); - b2MouseJointDef jd; - jd.bodyA = m_groundBody; - jd.bodyB = body; - jd.target = p; - jd.maxForce = 1000.0f * body->GetMass(); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - - m_mouseJoint = (b2MouseJoint*)m_world->CreateJoint(&jd); - body->SetAwake(true); - return true; - } - return false; + m_mouseWorld = p; + + if (m_mouseJoint != NULL) + { + return false; + } + + // Make a small box. + b2AABB aabb; + b2Vec2 d; + d.Set(0.001f, 0.001f); + aabb.lowerBound = p - d; + aabb.upperBound = p + d; + + // Query the world for overlapping shapes. + QueryCallback callback(p); + m_world->QueryAABB(&callback, aabb); + + if (callback.m_fixture) + { + float frequencyHz = 5.0f; + float dampingRatio = 0.7f; + + b2Body* body = callback.m_fixture->GetBody(); + b2MouseJointDef jd; + jd.bodyA = m_groundBody; + jd.bodyB = body; + jd.target = p; + jd.maxForce = 1000.0f * body->GetMass(); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + + m_mouseJoint = (b2MouseJoint*)m_world->CreateJoint(&jd); + body->SetAwake(true); + return true; + } + return false; } -void Test::SpawnBomb(const b2Vec2 & worldPt) +void Test::SpawnBomb(const b2Vec2& worldPt) { - m_bombSpawnPoint = worldPt; - m_bombSpawning = true; + m_bombSpawnPoint = worldPt; + m_bombSpawning = true; } -void Test::CompleteBombSpawn(const b2Vec2 & p) +void Test::CompleteBombSpawn(const b2Vec2& p) { - if (m_bombSpawning == false) - { - return; - } - - const float multiplier = 30.0f; - b2Vec2 vel = m_bombSpawnPoint - p; - vel *= multiplier; - LaunchBomb(m_bombSpawnPoint, vel); - m_bombSpawning = false; + if (m_bombSpawning == false) + { + return; + } + + const float multiplier = 30.0f; + b2Vec2 vel = m_bombSpawnPoint - p; + vel *= multiplier; + LaunchBomb(m_bombSpawnPoint, vel); + m_bombSpawning = false; } -void Test::ShiftMouseDown(const b2Vec2 & p) +void Test::ShiftMouseDown(const b2Vec2& p) { - m_mouseWorld = p; + m_mouseWorld = p; - if (m_mouseJoint != NULL) - { - return; - } + if (m_mouseJoint != NULL) + { + return; + } - SpawnBomb(p); + SpawnBomb(p); } -void Test::MouseUp(const b2Vec2 & p) +void Test::MouseUp(const b2Vec2& p) { - if (m_mouseJoint) - { - m_world->DestroyJoint(m_mouseJoint); - m_mouseJoint = NULL; - } - - if (m_bombSpawning) - { - CompleteBombSpawn(p); - } + if (m_mouseJoint) + { + m_world->DestroyJoint(m_mouseJoint); + m_mouseJoint = NULL; + } + + if (m_bombSpawning) + { + CompleteBombSpawn(p); + } } -void Test::MouseMove(const b2Vec2 & p) +void Test::MouseMove(const b2Vec2& p) { - m_mouseWorld = p; + m_mouseWorld = p; - if (m_mouseJoint) - { - m_mouseJoint->SetTarget(p); - } + if (m_mouseJoint) + { + m_mouseJoint->SetTarget(p); + } } void Test::LaunchBomb() { - b2Vec2 p(RandomFloat(-15.0f, 15.0f), 30.0f); - b2Vec2 v = -5.0f * p; - LaunchBomb(p, v); + b2Vec2 p(RandomFloat(-15.0f, 15.0f), 30.0f); + b2Vec2 v = -5.0f * p; + LaunchBomb(p, v); } -void Test::LaunchBomb(const b2Vec2 & position, const b2Vec2 & velocity) +void Test::LaunchBomb(const b2Vec2& position, const b2Vec2& velocity) { - if (m_bomb) - { - m_world->DestroyBody(m_bomb); - m_bomb = NULL; - } - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = position; - bd.bullet = true; - m_bomb = m_world->CreateBody(&bd); - m_bomb->SetLinearVelocity(velocity); - - b2CircleShape circle; - circle.m_radius = 0.3f; - - b2FixtureDef fd; - fd.shape = &circle; - fd.density = 20.0f; - fd.restitution = 0.0f; - - b2Vec2 minV = position - b2Vec2(0.3f, 0.3f); - b2Vec2 maxV = position + b2Vec2(0.3f, 0.3f); - - b2AABB aabb; - aabb.lowerBound = minV; - aabb.upperBound = maxV; - - m_bomb->CreateFixture(&fd); + if (m_bomb) + { + m_world->DestroyBody(m_bomb); + m_bomb = NULL; + } + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = position; + bd.bullet = true; + m_bomb = m_world->CreateBody(&bd); + m_bomb->SetLinearVelocity(velocity); + + b2CircleShape circle; + circle.m_radius = 0.3f; + + b2FixtureDef fd; + fd.shape = &circle; + fd.density = 20.0f; + fd.restitution = 0.0f; + + b2Vec2 minV = position - b2Vec2(0.3f, 0.3f); + b2Vec2 maxV = position + b2Vec2(0.3f, 0.3f); + + b2AABB aabb; + aabb.lowerBound = minV; + aabb.upperBound = maxV; + + m_bomb->CreateFixture(&fd); } void Test::Step(Settings& settings) { - float timeStep = settings.m_hertz > 0.0f ? 1.0f / settings.m_hertz : float(0.0f); - - if (settings.m_pause) - { - if (settings.m_singleStep) - { - settings.m_singleStep = 0; - } - else - { - timeStep = 0.0f; - } - - DrawString(5, m_textLine, "****PAUSED****"); - - } - - uint32 flags = 0; - flags += settings.m_drawShapes * b2Draw::e_shapeBit; - flags += settings.m_drawJoints * b2Draw::e_jointBit; - flags += settings.m_drawAABBs * b2Draw::e_aabbBit; - flags += settings.m_drawCOMs * b2Draw::e_centerOfMassBit; - g_debugDraw.SetFlags(flags); - - m_world->SetAllowSleeping(settings.m_enableSleep); - m_world->SetWarmStarting(settings.m_enableWarmStarting); - m_world->SetContinuousPhysics(settings.m_enableContinuous); - m_world->SetSubStepping(settings.m_enableSubStepping); - - m_pointCount = 0; - - m_world->Step(timeStep, settings.m_velocityIterations, settings.m_positionIterations); - - m_world->DebugDraw(); - - if (timeStep > 0.0f) - { - ++m_stepCount; - } - - if (settings.m_drawStats) - { - int32 bodyCount = m_world->GetBodyCount(); - int32 contactCount = m_world->GetContactCount(); - int32 jointCount = m_world->GetJointCount(); - DrawString(5, m_textLine, "bodies/contacts/joints = %d/%d/%d", bodyCount, contactCount, jointCount); - - - int32 proxyCount = m_world->GetProxyCount(); - int32 height = m_world->GetTreeHeight(); - int32 balance = m_world->GetTreeBalance(); - float quality = m_world->GetTreeQuality(); - DrawString(5, m_textLine, "proxies/height/balance/quality = %d/%d/%d/%g", proxyCount, height, balance, quality); - - } - - // Track maximum profile times - { - const b2Profile& p = m_world->GetProfile(); - m_maxProfile.step = b2Max(m_maxProfile.step, p.step); - m_maxProfile.collide = b2Max(m_maxProfile.collide, p.collide); - m_maxProfile.solve = b2Max(m_maxProfile.solve, p.solve); - m_maxProfile.solveInit = b2Max(m_maxProfile.solveInit, p.solveInit); - m_maxProfile.solveVelocity = b2Max(m_maxProfile.solveVelocity, p.solveVelocity); - m_maxProfile.solvePosition = b2Max(m_maxProfile.solvePosition, p.solvePosition); - m_maxProfile.solveTOI = b2Max(m_maxProfile.solveTOI, p.solveTOI); - m_maxProfile.broadphase = b2Max(m_maxProfile.broadphase, p.broadphase); - - m_totalProfile.step += p.step; - m_totalProfile.collide += p.collide; - m_totalProfile.solve += p.solve; - m_totalProfile.solveInit += p.solveInit; - m_totalProfile.solveVelocity += p.solveVelocity; - m_totalProfile.solvePosition += p.solvePosition; - m_totalProfile.solveTOI += p.solveTOI; - m_totalProfile.broadphase += p.broadphase; - } - - if (settings.m_drawProfile) - { - const b2Profile& p = m_world->GetProfile(); - - b2Profile aveProfile; - memset(&aveProfile, 0, sizeof(b2Profile)); - if (m_stepCount > 0) - { - float scale = 1.0f / m_stepCount; - aveProfile.step = scale * m_totalProfile.step; - aveProfile.collide = scale * m_totalProfile.collide; - aveProfile.solve = scale * m_totalProfile.solve; - aveProfile.solveInit = scale * m_totalProfile.solveInit; - aveProfile.solveVelocity = scale * m_totalProfile.solveVelocity; - aveProfile.solvePosition = scale * m_totalProfile.solvePosition; - aveProfile.solveTOI = scale * m_totalProfile.solveTOI; - aveProfile.broadphase = scale * m_totalProfile.broadphase; - } - - DrawString(5, m_textLine, "step [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.step, aveProfile.step, m_maxProfile.step); - DrawString(5, m_textLine, "collide [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.collide, aveProfile.collide, m_maxProfile.collide); - DrawString(5, m_textLine, "solve [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solve, aveProfile.solve, m_maxProfile.solve); - DrawString(5, m_textLine, "solve init [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveInit, aveProfile.solveInit, m_maxProfile.solveInit); - DrawString(5, m_textLine, "solve velocity [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveVelocity, aveProfile.solveVelocity, m_maxProfile.solveVelocity); - DrawString(5, m_textLine, "solve position [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solvePosition, aveProfile.solvePosition, m_maxProfile.solvePosition); - DrawString(5, m_textLine, "solveTOI [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveTOI, aveProfile.solveTOI, m_maxProfile.solveTOI); - DrawString(5, m_textLine, "broad-phase [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.broadphase, aveProfile.broadphase, m_maxProfile.broadphase); - } - - if (m_bombSpawning) - { - b2Color c; - c.Set(0.0f, 0.0f, 1.0f); - g_debugDraw.DrawPoint(m_bombSpawnPoint, 4.0f, c); - - c.Set(0.8f, 0.8f, 0.8f); - g_debugDraw.DrawSegment(m_mouseWorld, m_bombSpawnPoint, c); - } - - if (settings.m_drawContactPoints) - { - const float k_impulseScale = 0.1f; - const float k_axisScale = 0.3f; - - for (int32 i = 0; i < m_pointCount; ++i) - { - ContactPoint* point = m_points + i; - - if (point->state == b2_addState) - { - // Add - g_debugDraw.DrawPoint(point->position, 10.0f, b2Color(0.3f, 0.95f, 0.3f)); - } - else if (point->state == b2_persistState) - { - // Persist - g_debugDraw.DrawPoint(point->position, 5.0f, b2Color(0.3f, 0.3f, 0.95f)); - } - - if (settings.m_drawContactNormals == 1) - { - b2Vec2 p1 = point->position; - b2Vec2 p2 = p1 + k_axisScale * point->normal; - g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.9f)); - } - else if (settings.m_drawContactImpulse == 1) - { - b2Vec2 p1 = point->position; - b2Vec2 p2 = p1 + k_impulseScale * point->normalImpulse * point->normal; - g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f)); - } - - if (settings.m_drawFrictionImpulse == 1) - { - b2Vec2 tangent = b2Cross(point->normal, 1.0f); - b2Vec2 p1 = point->position; - b2Vec2 p2 = p1 + k_impulseScale * point->tangentImpulse * tangent; - g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f)); - } - } - } + float timeStep = settings.m_hertz > 0.0f ? 1.0f / settings.m_hertz : float(0.0f); + + if (settings.m_pause) + { + if (settings.m_singleStep) + { + settings.m_singleStep = 0; + } + else + { + timeStep = 0.0f; + } + + DrawString(5, m_textLine, "****PAUSED****"); + } + + uint32 flags = 0; + flags += settings.m_drawShapes * b2Draw::e_shapeBit; + flags += settings.m_drawJoints * b2Draw::e_jointBit; + flags += settings.m_drawAABBs * b2Draw::e_aabbBit; + flags += settings.m_drawCOMs * b2Draw::e_centerOfMassBit; + g_debugDraw.SetFlags(flags); + + m_world->SetAllowSleeping(settings.m_enableSleep); + m_world->SetWarmStarting(settings.m_enableWarmStarting); + m_world->SetContinuousPhysics(settings.m_enableContinuous); + m_world->SetSubStepping(settings.m_enableSubStepping); + + m_pointCount = 0; + + m_world->Step(timeStep, settings.m_velocityIterations, settings.m_positionIterations); + + m_world->DebugDraw(); + + if (timeStep > 0.0f) + { + ++m_stepCount; + } + + if (settings.m_drawStats) + { + int32 bodyCount = m_world->GetBodyCount(); + int32 contactCount = m_world->GetContactCount(); + int32 jointCount = m_world->GetJointCount(); + DrawString(5, m_textLine, "bodies/contacts/joints = %d/%d/%d", bodyCount, contactCount, jointCount); + + int32 proxyCount = m_world->GetProxyCount(); + int32 height = m_world->GetTreeHeight(); + int32 balance = m_world->GetTreeBalance(); + float quality = m_world->GetTreeQuality(); + DrawString(5, m_textLine, "proxies/height/balance/quality = %d/%d/%d/%g", proxyCount, height, balance, quality); + } + + // Track maximum profile times + { + const b2Profile& p = m_world->GetProfile(); + m_maxProfile.step = b2Max(m_maxProfile.step, p.step); + m_maxProfile.collide = b2Max(m_maxProfile.collide, p.collide); + m_maxProfile.solve = b2Max(m_maxProfile.solve, p.solve); + m_maxProfile.solveInit = b2Max(m_maxProfile.solveInit, p.solveInit); + m_maxProfile.solveVelocity = b2Max(m_maxProfile.solveVelocity, p.solveVelocity); + m_maxProfile.solvePosition = b2Max(m_maxProfile.solvePosition, p.solvePosition); + m_maxProfile.solveTOI = b2Max(m_maxProfile.solveTOI, p.solveTOI); + m_maxProfile.broadphase = b2Max(m_maxProfile.broadphase, p.broadphase); + + m_totalProfile.step += p.step; + m_totalProfile.collide += p.collide; + m_totalProfile.solve += p.solve; + m_totalProfile.solveInit += p.solveInit; + m_totalProfile.solveVelocity += p.solveVelocity; + m_totalProfile.solvePosition += p.solvePosition; + m_totalProfile.solveTOI += p.solveTOI; + m_totalProfile.broadphase += p.broadphase; + } + + if (settings.m_drawProfile) + { + const b2Profile& p = m_world->GetProfile(); + + b2Profile aveProfile; + memset(&aveProfile, 0, sizeof(b2Profile)); + if (m_stepCount > 0) + { + float scale = 1.0f / m_stepCount; + aveProfile.step = scale * m_totalProfile.step; + aveProfile.collide = scale * m_totalProfile.collide; + aveProfile.solve = scale * m_totalProfile.solve; + aveProfile.solveInit = scale * m_totalProfile.solveInit; + aveProfile.solveVelocity = scale * m_totalProfile.solveVelocity; + aveProfile.solvePosition = scale * m_totalProfile.solvePosition; + aveProfile.solveTOI = scale * m_totalProfile.solveTOI; + aveProfile.broadphase = scale * m_totalProfile.broadphase; + } + + DrawString(5, m_textLine, "step [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.step, aveProfile.step, + m_maxProfile.step); + DrawString(5, m_textLine, "collide [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.collide, aveProfile.collide, + m_maxProfile.collide); + DrawString(5, m_textLine, "solve [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solve, aveProfile.solve, + m_maxProfile.solve); + DrawString(5, m_textLine, "solve init [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveInit, aveProfile.solveInit, + m_maxProfile.solveInit); + DrawString(5, m_textLine, "solve velocity [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveVelocity, + aveProfile.solveVelocity, m_maxProfile.solveVelocity); + DrawString(5, m_textLine, "solve position [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solvePosition, + aveProfile.solvePosition, m_maxProfile.solvePosition); + DrawString(5, m_textLine, "solveTOI [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveTOI, aveProfile.solveTOI, + m_maxProfile.solveTOI); + DrawString(5, m_textLine, "broad-phase [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.broadphase, + aveProfile.broadphase, m_maxProfile.broadphase); + } + + if (m_bombSpawning) + { + b2Color c; + c.Set(0.0f, 0.0f, 1.0f); + g_debugDraw.DrawPoint(m_bombSpawnPoint, 4.0f, c); + + c.Set(0.8f, 0.8f, 0.8f); + g_debugDraw.DrawSegment(m_mouseWorld, m_bombSpawnPoint, c); + } + + if (settings.m_drawContactPoints) + { + const float k_impulseScale = 0.1f; + const float k_axisScale = 0.3f; + + for (int32 i = 0; i < m_pointCount; ++i) + { + ContactPoint* point = m_points + i; + + if (point->state == b2_addState) + { + // Add + g_debugDraw.DrawPoint(point->position, 10.0f, b2Color(0.3f, 0.95f, 0.3f)); + } + else if (point->state == b2_persistState) + { + // Persist + g_debugDraw.DrawPoint(point->position, 5.0f, b2Color(0.3f, 0.3f, 0.95f)); + } + + if (settings.m_drawContactNormals == 1) + { + b2Vec2 p1 = point->position; + b2Vec2 p2 = p1 + k_axisScale * point->normal; + g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.9f)); + } + else if (settings.m_drawContactImpulse == 1) + { + b2Vec2 p1 = point->position; + b2Vec2 p2 = p1 + k_impulseScale * point->normalImpulse * point->normal; + g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f)); + } + + if (settings.m_drawFrictionImpulse == 1) + { + b2Vec2 tangent = b2Cross(point->normal, 1.0f); + b2Vec2 p1 = point->position; + b2Vec2 p2 = p1 + k_impulseScale * point->tangentImpulse * tangent; + g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f)); + } + } + } } -void Test::ShiftOrigin(const b2Vec2 & newOrigin) +void Test::ShiftOrigin(const b2Vec2& newOrigin) { - m_world->ShiftOrigin(newOrigin); + m_world->ShiftOrigin(newOrigin); } void Test::initShader(void) { - // initShader is unsupported + // initShader is unsupported } void Test::DrawString(int x, int y, const char* fmt, ...) { #if defined(CC_PLATFORM_PC) - debugString.append(std::string(fmt)); - debugString.append("\n"); - labelDebugDraw->setString(debugString); - // labelDebugDraw->setPosition(x, y); + debugString.append(std::string(fmt)); + debugString.append("\n"); + labelDebugDraw->setString(debugString); + // labelDebugDraw->setPosition(x, y); #endif } void Test::DrawString(const b2Vec2& pw, const char* fmt, ...) { #if defined(CC_PLATFORM_PC) - debugString.append(std::string(fmt)); - debugString.append("\n"); - labelDebugDraw->setString(debugString); - // labelDebugDraw->setPosition(pw.x, pw.y); + debugString.append(std::string(fmt)); + debugString.append("\n"); + labelDebugDraw->setString(debugString); + // labelDebugDraw->setPosition(pw.x, pw.y); #endif } - - void Test::DrawAABB(b2AABB* aabb, const b2Color& color) { - b2Vec2 p1 = aabb->lowerBound; - b2Vec2 p2 = b2Vec2(aabb->upperBound.x, aabb->lowerBound.y); - b2Vec2 p3 = aabb->upperBound; - b2Vec2 p4 = b2Vec2(aabb->lowerBound.x, aabb->upperBound.y); - - Vec2 verts[] = { - Vec2(p1.x * g_debugDraw.mRatio, p1.y * g_debugDraw.mRatio) + g_debugDraw.debugNodeOffset , - Vec2(p2.x * g_debugDraw.mRatio, p2.y * g_debugDraw.mRatio) + g_debugDraw.debugNodeOffset , - Vec2(p3.x * g_debugDraw.mRatio, p3.y * g_debugDraw.mRatio) + g_debugDraw.debugNodeOffset , - Vec2(p4.x * g_debugDraw.mRatio, p4.y * g_debugDraw.mRatio) + g_debugDraw.debugNodeOffset , - }; - debugDrawNode->drawPolygon(verts, sizeof(verts) / sizeof(verts[0]), Color4F(color.r / 2, color.g / 2, color.b / 2, 0), 0.4f, Color4F(color.r, color.g, color.b, color.a)); + b2Vec2 p1 = aabb->lowerBound; + b2Vec2 p2 = b2Vec2(aabb->upperBound.x, aabb->lowerBound.y); + b2Vec2 p3 = aabb->upperBound; + b2Vec2 p4 = b2Vec2(aabb->lowerBound.x, aabb->upperBound.y); + + Vec2 verts[] = { + Vec2(p1.x * g_debugDraw.mRatio, p1.y * g_debugDraw.mRatio) + g_debugDraw.debugNodeOffset, + Vec2(p2.x * g_debugDraw.mRatio, p2.y * g_debugDraw.mRatio) + g_debugDraw.debugNodeOffset, + Vec2(p3.x * g_debugDraw.mRatio, p3.y * g_debugDraw.mRatio) + g_debugDraw.debugNodeOffset, + Vec2(p4.x * g_debugDraw.mRatio, p4.y * g_debugDraw.mRatio) + g_debugDraw.debugNodeOffset, + }; + debugDrawNode->drawPolygon(verts, sizeof(verts) / sizeof(verts[0]), + Color4F(color.r / 2, color.g / 2, color.b / 2, 0), 0.4f, + Color4F(color.r, color.g, color.b, color.a)); } void Test::Flush() { - // Flush is unsupported + // Flush is unsupported } \ No newline at end of file diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/add_pair.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/add_pair.cpp index ceccbf8ca2e7..4465d35f3e01 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/add_pair.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/add_pair.cpp @@ -25,47 +25,43 @@ class AddPair : public Test { public: + AddPair() + { + m_world->SetGravity(b2Vec2(0.0f, 0.0f)); + { + b2CircleShape shape; + shape.m_p.SetZero(); + shape.m_radius = 0.1f; - AddPair() - { - m_world->SetGravity(b2Vec2(0.0f,0.0f)); - { - b2CircleShape shape; - shape.m_p.SetZero(); - shape.m_radius = 0.1f; + float minX = -6.0f; + float maxX = 0.0f; + float minY = 4.0f; + float maxY = 6.0f; - float minX = -6.0f; - float maxX = 0.0f; - float minY = 4.0f; - float maxY = 6.0f; - - for (int32 i = 0; i < 400; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = b2Vec2(RandomFloat(minX,maxX),RandomFloat(minY,maxY)); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 0.01f); - } - } - - { - b2PolygonShape shape; - shape.SetAsBox(1.5f, 1.5f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-40.0f,5.0f); - bd.bullet = true; - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 1.0f); - body->SetLinearVelocity(b2Vec2(10.0f, 0.0f)); - } - } + for (int32 i = 0; i < 400; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = b2Vec2(RandomFloat(minX, maxX), RandomFloat(minY, maxY)); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 0.01f); + } + } - static Test* Create() - { - return new AddPair; - } + { + b2PolygonShape shape; + shape.SetAsBox(1.5f, 1.5f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-40.0f, 5.0f); + bd.bullet = true; + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 1.0f); + body->SetLinearVelocity(b2Vec2(10.0f, 0.0f)); + } + } + + static Test* Create() { return new AddPair; } }; static int testIndex = RegisterTest("Benchmark", "Add Pair", AddPair::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/apply_force.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/apply_force.cpp index 40fc7e1decf4..51239f60e2f3 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/apply_force.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/apply_force.cpp @@ -28,176 +28,172 @@ class ApplyForce : public Test { public: - ApplyForce() - { - m_world->SetGravity(b2Vec2(0.0f, 0.0f)); - - const float k_restitution = 0.4f; - - b2Body* ground; - { - b2BodyDef bd; - bd.position.Set(0.0f, 20.0f); - ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - - b2FixtureDef sd; - sd.shape = &shape; - sd.density = 0.0f; - sd.restitution = k_restitution; - - // Left vertical - shape.SetTwoSided(b2Vec2(-20.0f, -20.0f), b2Vec2(-20.0f, 20.0f)); - ground->CreateFixture(&sd); - - // Right vertical - shape.SetTwoSided(b2Vec2(20.0f, -20.0f), b2Vec2(20.0f, 20.0f)); - ground->CreateFixture(&sd); - - // Top horizontal - shape.SetTwoSided(b2Vec2(-20.0f, 20.0f), b2Vec2(20.0f, 20.0f)); - ground->CreateFixture(&sd); - - // Bottom horizontal - shape.SetTwoSided(b2Vec2(-20.0f, -20.0f), b2Vec2(20.0f, -20.0f)); - ground->CreateFixture(&sd); - } - - { - b2Transform xf1; - xf1.q.Set(0.3524f * b2_pi); - xf1.p = xf1.q.GetXAxis(); - - b2Vec2 vertices[3]; - vertices[0] = b2Mul(xf1, b2Vec2(-1.0f, 0.0f)); - vertices[1] = b2Mul(xf1, b2Vec2(1.0f, 0.0f)); - vertices[2] = b2Mul(xf1, b2Vec2(0.0f, 0.5f)); - - b2PolygonShape poly1; - poly1.Set(vertices, 3); - - b2FixtureDef sd1; - sd1.shape = &poly1; - sd1.density = 2.0f; - - b2Transform xf2; - xf2.q.Set(-0.3524f * b2_pi); - xf2.p = -xf2.q.GetXAxis(); - - vertices[0] = b2Mul(xf2, b2Vec2(-1.0f, 0.0f)); - vertices[1] = b2Mul(xf2, b2Vec2(1.0f, 0.0f)); - vertices[2] = b2Mul(xf2, b2Vec2(0.0f, 0.5f)); - - b2PolygonShape poly2; - poly2.Set(vertices, 3); - - b2FixtureDef sd2; - sd2.shape = &poly2; - sd2.density = 2.0f; - - b2BodyDef bd; - bd.type = b2_dynamicBody; - - bd.position.Set(0.0f, 3.0); - bd.angle = b2_pi; - bd.allowSleep = false; - m_body = m_world->CreateBody(&bd); - m_body->CreateFixture(&sd1); - m_body->CreateFixture(&sd2); - - float gravity = 10.0f; - float I = m_body->GetInertia(); - float mass = m_body->GetMass(); - - // Compute an effective radius that can be used to - // set the max torque for a friction joint - // For a circle: I = 0.5 * m * r * r ==> r = sqrt(2 * I / m) - float radius = b2Sqrt(2.0f * I / mass); - - b2FrictionJointDef jd; - jd.bodyA = ground; - jd.bodyB = m_body; - jd.localAnchorA.SetZero(); - jd.localAnchorB = m_body->GetLocalCenter(); - jd.collideConnected = true; - jd.maxForce = 0.5f * mass * gravity; - jd.maxTorque = 0.2f * mass * radius * gravity; - - m_world->CreateJoint(&jd); - } - - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.5f); - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - fd.friction = 0.3f; - - for (int i = 0; i < 10; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - - bd.position.Set(0.0f, 7.0f + 1.54f * i); - b2Body* body = m_world->CreateBody(&bd); - - body->CreateFixture(&fd); - - float gravity = 10.0f; - float I = body->GetInertia(); - float mass = body->GetMass(); - - // For a circle: I = 0.5 * m * r * r ==> r = sqrt(2 * I / m) - float radius = b2Sqrt(2.0f * I / mass); - - b2FrictionJointDef jd; - jd.localAnchorA.SetZero(); - jd.localAnchorB.SetZero(); - jd.bodyA = ground; - jd.bodyB = body; - jd.collideConnected = true; - jd.maxForce = mass * gravity; - jd.maxTorque = 0.1f * mass * radius * gravity; - - m_world->CreateJoint(&jd); - } - } - } - - void Step(Settings& settings) override - { - DrawString(5, m_textLine, "Forward (W), Turn (A) and (D)"); - - - //if (glfwGetKey(g_mainWindow, GLFW_KEY_W) == GLFW_PRESS) - //{ - // b2Vec2 f = m_body->GetWorldVector(b2Vec2(0.0f, -50.0f)); - // b2Vec2 p = m_body->GetWorldPoint(b2Vec2(0.0f, 3.0f)); - // m_body->ApplyForce(f, p, true); - //} - - //if (glfwGetKey(g_mainWindow, GLFW_KEY_A) == GLFW_PRESS) - //{ - // m_body->ApplyTorque(10.0f, true); - //} - - //if (glfwGetKey(g_mainWindow, GLFW_KEY_D) == GLFW_PRESS) - //{ - // m_body->ApplyTorque(-10.0f, true); - //} - - Test::Step(settings); - } - - static Test* Create() - { - return new ApplyForce; - } - - b2Body* m_body; + ApplyForce() + { + m_world->SetGravity(b2Vec2(0.0f, 0.0f)); + + const float k_restitution = 0.4f; + + b2Body* ground; + { + b2BodyDef bd; + bd.position.Set(0.0f, 20.0f); + ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + + b2FixtureDef sd; + sd.shape = &shape; + sd.density = 0.0f; + sd.restitution = k_restitution; + + // Left vertical + shape.SetTwoSided(b2Vec2(-20.0f, -20.0f), b2Vec2(-20.0f, 20.0f)); + ground->CreateFixture(&sd); + + // Right vertical + shape.SetTwoSided(b2Vec2(20.0f, -20.0f), b2Vec2(20.0f, 20.0f)); + ground->CreateFixture(&sd); + + // Top horizontal + shape.SetTwoSided(b2Vec2(-20.0f, 20.0f), b2Vec2(20.0f, 20.0f)); + ground->CreateFixture(&sd); + + // Bottom horizontal + shape.SetTwoSided(b2Vec2(-20.0f, -20.0f), b2Vec2(20.0f, -20.0f)); + ground->CreateFixture(&sd); + } + + { + b2Transform xf1; + xf1.q.Set(0.3524f * b2_pi); + xf1.p = xf1.q.GetXAxis(); + + b2Vec2 vertices[3]; + vertices[0] = b2Mul(xf1, b2Vec2(-1.0f, 0.0f)); + vertices[1] = b2Mul(xf1, b2Vec2(1.0f, 0.0f)); + vertices[2] = b2Mul(xf1, b2Vec2(0.0f, 0.5f)); + + b2PolygonShape poly1; + poly1.Set(vertices, 3); + + b2FixtureDef sd1; + sd1.shape = &poly1; + sd1.density = 2.0f; + + b2Transform xf2; + xf2.q.Set(-0.3524f * b2_pi); + xf2.p = -xf2.q.GetXAxis(); + + vertices[0] = b2Mul(xf2, b2Vec2(-1.0f, 0.0f)); + vertices[1] = b2Mul(xf2, b2Vec2(1.0f, 0.0f)); + vertices[2] = b2Mul(xf2, b2Vec2(0.0f, 0.5f)); + + b2PolygonShape poly2; + poly2.Set(vertices, 3); + + b2FixtureDef sd2; + sd2.shape = &poly2; + sd2.density = 2.0f; + + b2BodyDef bd; + bd.type = b2_dynamicBody; + + bd.position.Set(0.0f, 3.0); + bd.angle = b2_pi; + bd.allowSleep = false; + m_body = m_world->CreateBody(&bd); + m_body->CreateFixture(&sd1); + m_body->CreateFixture(&sd2); + + float gravity = 10.0f; + float I = m_body->GetInertia(); + float mass = m_body->GetMass(); + + // Compute an effective radius that can be used to + // set the max torque for a friction joint + // For a circle: I = 0.5 * m * r * r ==> r = sqrt(2 * I / m) + float radius = b2Sqrt(2.0f * I / mass); + + b2FrictionJointDef jd; + jd.bodyA = ground; + jd.bodyB = m_body; + jd.localAnchorA.SetZero(); + jd.localAnchorB = m_body->GetLocalCenter(); + jd.collideConnected = true; + jd.maxForce = 0.5f * mass * gravity; + jd.maxTorque = 0.2f * mass * radius * gravity; + + m_world->CreateJoint(&jd); + } + + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + fd.friction = 0.3f; + + for (int i = 0; i < 10; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + + bd.position.Set(0.0f, 7.0f + 1.54f * i); + b2Body* body = m_world->CreateBody(&bd); + + body->CreateFixture(&fd); + + float gravity = 10.0f; + float I = body->GetInertia(); + float mass = body->GetMass(); + + // For a circle: I = 0.5 * m * r * r ==> r = sqrt(2 * I / m) + float radius = b2Sqrt(2.0f * I / mass); + + b2FrictionJointDef jd; + jd.localAnchorA.SetZero(); + jd.localAnchorB.SetZero(); + jd.bodyA = ground; + jd.bodyB = body; + jd.collideConnected = true; + jd.maxForce = mass * gravity; + jd.maxTorque = 0.1f * mass * radius * gravity; + + m_world->CreateJoint(&jd); + } + } + } + + void Step(Settings& settings) override + { + DrawString(5, m_textLine, "Forward (W), Turn (A) and (D)"); + + // if (glfwGetKey(g_mainWindow, GLFW_KEY_W) == GLFW_PRESS) + //{ + // b2Vec2 f = m_body->GetWorldVector(b2Vec2(0.0f, -50.0f)); + // b2Vec2 p = m_body->GetWorldPoint(b2Vec2(0.0f, 3.0f)); + // m_body->ApplyForce(f, p, true); + // } + + // if (glfwGetKey(g_mainWindow, GLFW_KEY_A) == GLFW_PRESS) + //{ + // m_body->ApplyTorque(10.0f, true); + // } + + // if (glfwGetKey(g_mainWindow, GLFW_KEY_D) == GLFW_PRESS) + //{ + // m_body->ApplyTorque(-10.0f, true); + // } + + Test::Step(settings); + } + + static Test* Create() { return new ApplyForce; } + + b2Body* m_body; }; static int testIndex = RegisterTest("Forces", "Apply Force", ApplyForce::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/body_types.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/body_types.cpp index 055d27957833..0de1079826f0 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/body_types.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/body_types.cpp @@ -25,139 +25,134 @@ class BodyTypes : public Test { public: - BodyTypes() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); - - b2FixtureDef fd; - fd.shape = &shape; - - ground->CreateFixture(&fd); - } - - // Define attachment - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 3.0f); - m_attachment = m_world->CreateBody(&bd); - - b2PolygonShape shape; - shape.SetAsBox(0.5f, 2.0f); - m_attachment->CreateFixture(&shape, 2.0f); - } - - // Define platform - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-4.0f, 5.0f); - m_platform = m_world->CreateBody(&bd); - - b2PolygonShape shape; - shape.SetAsBox(0.5f, 4.0f, b2Vec2(4.0f, 0.0f), 0.5f * b2_pi); - - b2FixtureDef fd; - fd.shape = &shape; - fd.friction = 0.6f; - fd.density = 2.0f; - m_platform->CreateFixture(&fd); - - b2RevoluteJointDef rjd; - rjd.Initialize(m_attachment, m_platform, b2Vec2(0.0f, 5.0f)); - rjd.maxMotorTorque = 50.0f; - rjd.enableMotor = true; - m_world->CreateJoint(&rjd); - - b2PrismaticJointDef pjd; - pjd.Initialize(ground, m_platform, b2Vec2(0.0f, 5.0f), b2Vec2(1.0f, 0.0f)); - - pjd.maxMotorForce = 1000.0f; - pjd.enableMotor = true; - pjd.lowerTranslation = -10.0f; - pjd.upperTranslation = 10.0f; - pjd.enableLimit = true; - - m_world->CreateJoint(&pjd); - - m_speed = 3.0f; - } - - // Create a payload - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 8.0f); - b2Body* body = m_world->CreateBody(&bd); - - b2PolygonShape shape; - shape.SetAsBox(0.75f, 0.75f); - - b2FixtureDef fd; - fd.shape = &shape; - fd.friction = 0.6f; - fd.density = 2.0f; - - body->CreateFixture(&fd); - } - } - - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_D: - m_platform->SetType(b2_dynamicBody); - break; - - case GLFW_KEY_S: - m_platform->SetType(b2_staticBody); - break; - - case GLFW_KEY_K: - m_platform->SetType(b2_kinematicBody); - m_platform->SetLinearVelocity(b2Vec2(-m_speed, 0.0f)); - m_platform->SetAngularVelocity(0.0f); - break; - } - } - - void Step(Settings& settings) override - { - // Drive the kinematic body. - if (m_platform->GetType() == b2_kinematicBody) - { - b2Vec2 p = m_platform->GetTransform().p; - b2Vec2 v = m_platform->GetLinearVelocity(); - - if ((p.x < -10.0f && v.x < 0.0f) || - (p.x > 10.0f && v.x > 0.0f)) - { - v.x = -v.x; - m_platform->SetLinearVelocity(v); - } - } - - Test::Step(settings); - - DrawString(5, m_textLine, "Keys: (d) dynamic, (s) static, (k) kinematic"); - - } - - static Test* Create() - { - return new BodyTypes; - } - - b2Body* m_attachment; - b2Body* m_platform; - float m_speed; + BodyTypes() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); + + b2FixtureDef fd; + fd.shape = &shape; + + ground->CreateFixture(&fd); + } + + // Define attachment + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 3.0f); + m_attachment = m_world->CreateBody(&bd); + + b2PolygonShape shape; + shape.SetAsBox(0.5f, 2.0f); + m_attachment->CreateFixture(&shape, 2.0f); + } + + // Define platform + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-4.0f, 5.0f); + m_platform = m_world->CreateBody(&bd); + + b2PolygonShape shape; + shape.SetAsBox(0.5f, 4.0f, b2Vec2(4.0f, 0.0f), 0.5f * b2_pi); + + b2FixtureDef fd; + fd.shape = &shape; + fd.friction = 0.6f; + fd.density = 2.0f; + m_platform->CreateFixture(&fd); + + b2RevoluteJointDef rjd; + rjd.Initialize(m_attachment, m_platform, b2Vec2(0.0f, 5.0f)); + rjd.maxMotorTorque = 50.0f; + rjd.enableMotor = true; + m_world->CreateJoint(&rjd); + + b2PrismaticJointDef pjd; + pjd.Initialize(ground, m_platform, b2Vec2(0.0f, 5.0f), b2Vec2(1.0f, 0.0f)); + + pjd.maxMotorForce = 1000.0f; + pjd.enableMotor = true; + pjd.lowerTranslation = -10.0f; + pjd.upperTranslation = 10.0f; + pjd.enableLimit = true; + + m_world->CreateJoint(&pjd); + + m_speed = 3.0f; + } + + // Create a payload + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 8.0f); + b2Body* body = m_world->CreateBody(&bd); + + b2PolygonShape shape; + shape.SetAsBox(0.75f, 0.75f); + + b2FixtureDef fd; + fd.shape = &shape; + fd.friction = 0.6f; + fd.density = 2.0f; + + body->CreateFixture(&fd); + } + } + + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_D: + m_platform->SetType(b2_dynamicBody); + break; + + case GLFW_KEY_S: + m_platform->SetType(b2_staticBody); + break; + + case GLFW_KEY_K: + m_platform->SetType(b2_kinematicBody); + m_platform->SetLinearVelocity(b2Vec2(-m_speed, 0.0f)); + m_platform->SetAngularVelocity(0.0f); + break; + } + } + + void Step(Settings& settings) override + { + // Drive the kinematic body. + if (m_platform->GetType() == b2_kinematicBody) + { + b2Vec2 p = m_platform->GetTransform().p; + b2Vec2 v = m_platform->GetLinearVelocity(); + + if ((p.x < -10.0f && v.x < 0.0f) || (p.x > 10.0f && v.x > 0.0f)) + { + v.x = -v.x; + m_platform->SetLinearVelocity(v); + } + } + + Test::Step(settings); + + DrawString(5, m_textLine, "Keys: (d) dynamic, (s) static, (k) kinematic"); + } + + static Test* Create() { return new BodyTypes; } + + b2Body* m_attachment; + b2Body* m_platform; + float m_speed; }; static int testIndex = RegisterTest("Examples", "Body Types", BodyTypes::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/box_stack.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/box_stack.cpp index 10da577cbcac..463d399b7f8e 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/box_stack.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/box_stack.cpp @@ -27,148 +27,144 @@ extern B2_API bool g_blockSolve; class BoxStack : public Test { public: + enum + { + e_columnCount = 1, + e_rowCount = 15 + // e_columnCount = 1, + // e_rowCount = 1 + }; + + BoxStack() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + + shape.SetTwoSided(b2Vec2(20.0f, 0.0f), b2Vec2(20.0f, 20.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + float xs[5] = {0.0f, -10.0f, -5.0f, 5.0f, 10.0f}; + + for (int32 j = 0; j < e_columnCount; ++j) + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + fd.friction = 0.3f; + + for (int i = 0; i < e_rowCount; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + + int32 n = j * e_rowCount + i; + b2Assert(n < e_rowCount * e_columnCount); + m_indices[n] = n; + bd.userData.pointer = n; + + float x = 0.0f; + // float x = RandomFloat(-0.02f, 0.02f); + // float x = i % 2 == 0 ? -0.01f : 0.01f; + bd.position.Set(xs[j] + x, 0.55f + 1.1f * i); + b2Body* body = m_world->CreateBody(&bd); + + m_bodies[n] = body; + + body->CreateFixture(&fd); + } + } + + m_bullet = NULL; + } + + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_COMMA: + if (m_bullet != NULL) + { + m_world->DestroyBody(m_bullet); + m_bullet = NULL; + } + + { + b2CircleShape shape; + shape.m_radius = 0.25f; + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + fd.restitution = 0.05f; + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.bullet = true; + bd.position.Set(-31.0f, 5.0f); + + m_bullet = m_world->CreateBody(&bd); + m_bullet->CreateFixture(&fd); + + m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0.0f)); + } + break; - enum - { - e_columnCount = 1, - e_rowCount = 15 - //e_columnCount = 1, - //e_rowCount = 1 - }; - - BoxStack() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - - shape.SetTwoSided(b2Vec2(20.0f, 0.0f), b2Vec2(20.0f, 20.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - float xs[5] = {0.0f, -10.0f, -5.0f, 5.0f, 10.0f}; - - for (int32 j = 0; j < e_columnCount; ++j) - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.5f); - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - fd.friction = 0.3f; - - for (int i = 0; i < e_rowCount; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - - int32 n = j * e_rowCount + i; - b2Assert(n < e_rowCount * e_columnCount); - m_indices[n] = n; - bd.userData.pointer = n; - - float x = 0.0f; - //float x = RandomFloat(-0.02f, 0.02f); - //float x = i % 2 == 0 ? -0.01f : 0.01f; - bd.position.Set(xs[j] + x, 0.55f + 1.1f * i); - b2Body* body = m_world->CreateBody(&bd); - - m_bodies[n] = body; - - body->CreateFixture(&fd); - } - } - - m_bullet = NULL; - } - - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_COMMA: - if (m_bullet != NULL) - { - m_world->DestroyBody(m_bullet); - m_bullet = NULL; - } - - { - b2CircleShape shape; - shape.m_radius = 0.25f; - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - fd.restitution = 0.05f; - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.bullet = true; - bd.position.Set(-31.0f, 5.0f); - - m_bullet = m_world->CreateBody(&bd); - m_bullet->CreateFixture(&fd); - - m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0.0f)); - } - break; - case GLFW_KEY_B: g_blockSolve = !g_blockSolve; break; - } - } - - void Step(Settings& settings) override - { - Test::Step(settings); - DrawString(5, m_textLine, "Press: (,) to launch a bullet."); - - DrawString(5, m_textLine, "Blocksolve = %d", g_blockSolve); - if (m_stepCount == 300) - { - if (m_bullet != NULL) - { - m_world->DestroyBody(m_bullet); - m_bullet = NULL; - } - - { - b2CircleShape shape; - shape.m_radius = 0.25f; - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - fd.restitution = 0.05f; - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.bullet = true; - bd.position.Set(-31.0f, 5.0f); - - m_bullet = m_world->CreateBody(&bd); - m_bullet->CreateFixture(&fd); - - m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0.0f)); - } - } - } - - static Test* Create() - { - return new BoxStack; - } - - b2Body* m_bullet; - b2Body* m_bodies[e_rowCount * e_columnCount]; - int32 m_indices[e_rowCount * e_columnCount]; + } + } + + void Step(Settings& settings) override + { + Test::Step(settings); + DrawString(5, m_textLine, "Press: (,) to launch a bullet."); + + DrawString(5, m_textLine, "Blocksolve = %d", g_blockSolve); + if (m_stepCount == 300) + { + if (m_bullet != NULL) + { + m_world->DestroyBody(m_bullet); + m_bullet = NULL; + } + + { + b2CircleShape shape; + shape.m_radius = 0.25f; + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + fd.restitution = 0.05f; + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.bullet = true; + bd.position.Set(-31.0f, 5.0f); + + m_bullet = m_world->CreateBody(&bd); + m_bullet->CreateFixture(&fd); + + m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0.0f)); + } + } + } + + static Test* Create() { return new BoxStack; } + + b2Body* m_bullet; + b2Body* m_bodies[e_rowCount * e_columnCount]; + int32 m_indices[e_rowCount * e_columnCount]; }; static int testIndex = RegisterTest("Stacking", "Boxes", BoxStack::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/breakable.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/breakable.cpp index 136244a49d3b..1128a56ef498 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/breakable.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/breakable.cpp @@ -26,133 +26,129 @@ class Breakable : public Test { public: - - enum - { - e_count = 7 - }; - - Breakable() - { - // Ground body - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - // Breakable dynamic body - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 40.0f); - bd.angle = 0.25f * b2_pi; - m_body1 = m_world->CreateBody(&bd); - - m_shape1.SetAsBox(0.5f, 0.5f, b2Vec2(-0.5f, 0.0f), 0.0f); - m_piece1 = m_body1->CreateFixture(&m_shape1, 1.0f); - - m_shape2.SetAsBox(0.5f, 0.5f, b2Vec2(0.5f, 0.0f), 0.0f); - m_piece2 = m_body1->CreateFixture(&m_shape2, 1.0f); - } - - m_break = false; - m_broke = false; - } - - void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) override - { - if (m_broke) - { - // The body already broke. - return; - } - - // Should the body break? - int32 count = contact->GetManifold()->pointCount; - - float maxImpulse = 0.0f; - for (int32 i = 0; i < count; ++i) - { - maxImpulse = b2Max(maxImpulse, impulse->normalImpulses[i]); - } - - if (maxImpulse > 40.0f) - { - // Flag the body for breaking. - m_break = true; - } - } - - void Break() - { - // Create two bodies from one. - b2Body* body1 = m_piece1->GetBody(); - b2Vec2 center = body1->GetWorldCenter(); - - body1->DestroyFixture(m_piece2); - m_piece2 = NULL; - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = body1->GetPosition(); - bd.angle = body1->GetAngle(); - - b2Body* body2 = m_world->CreateBody(&bd); - m_piece2 = body2->CreateFixture(&m_shape2, 1.0f); - - // Compute consistent velocities for new bodies based on - // cached velocity. - b2Vec2 center1 = body1->GetWorldCenter(); - b2Vec2 center2 = body2->GetWorldCenter(); - - b2Vec2 velocity1 = m_velocity + b2Cross(m_angularVelocity, center1 - center); - b2Vec2 velocity2 = m_velocity + b2Cross(m_angularVelocity, center2 - center); - - body1->SetAngularVelocity(m_angularVelocity); - body1->SetLinearVelocity(velocity1); - - body2->SetAngularVelocity(m_angularVelocity); - body2->SetLinearVelocity(velocity2); - } - - void Step(Settings& settings) override - { - if (m_break) - { - Break(); - m_broke = true; - m_break = false; - } - - // Cache velocities to improve movement on breakage. - if (m_broke == false) - { - m_velocity = m_body1->GetLinearVelocity(); - m_angularVelocity = m_body1->GetAngularVelocity(); - } - - Test::Step(settings); - } - - static Test* Create() - { - return new Breakable; - } - - b2Body* m_body1; - b2Vec2 m_velocity; - float m_angularVelocity; - b2PolygonShape m_shape1; - b2PolygonShape m_shape2; - b2Fixture* m_piece1; - b2Fixture* m_piece2; - - bool m_broke; - bool m_break; + enum + { + e_count = 7 + }; + + Breakable() + { + // Ground body + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + // Breakable dynamic body + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 40.0f); + bd.angle = 0.25f * b2_pi; + m_body1 = m_world->CreateBody(&bd); + + m_shape1.SetAsBox(0.5f, 0.5f, b2Vec2(-0.5f, 0.0f), 0.0f); + m_piece1 = m_body1->CreateFixture(&m_shape1, 1.0f); + + m_shape2.SetAsBox(0.5f, 0.5f, b2Vec2(0.5f, 0.0f), 0.0f); + m_piece2 = m_body1->CreateFixture(&m_shape2, 1.0f); + } + + m_break = false; + m_broke = false; + } + + void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) override + { + if (m_broke) + { + // The body already broke. + return; + } + + // Should the body break? + int32 count = contact->GetManifold()->pointCount; + + float maxImpulse = 0.0f; + for (int32 i = 0; i < count; ++i) + { + maxImpulse = b2Max(maxImpulse, impulse->normalImpulses[i]); + } + + if (maxImpulse > 40.0f) + { + // Flag the body for breaking. + m_break = true; + } + } + + void Break() + { + // Create two bodies from one. + b2Body* body1 = m_piece1->GetBody(); + b2Vec2 center = body1->GetWorldCenter(); + + body1->DestroyFixture(m_piece2); + m_piece2 = NULL; + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = body1->GetPosition(); + bd.angle = body1->GetAngle(); + + b2Body* body2 = m_world->CreateBody(&bd); + m_piece2 = body2->CreateFixture(&m_shape2, 1.0f); + + // Compute consistent velocities for new bodies based on + // cached velocity. + b2Vec2 center1 = body1->GetWorldCenter(); + b2Vec2 center2 = body2->GetWorldCenter(); + + b2Vec2 velocity1 = m_velocity + b2Cross(m_angularVelocity, center1 - center); + b2Vec2 velocity2 = m_velocity + b2Cross(m_angularVelocity, center2 - center); + + body1->SetAngularVelocity(m_angularVelocity); + body1->SetLinearVelocity(velocity1); + + body2->SetAngularVelocity(m_angularVelocity); + body2->SetLinearVelocity(velocity2); + } + + void Step(Settings& settings) override + { + if (m_break) + { + Break(); + m_broke = true; + m_break = false; + } + + // Cache velocities to improve movement on breakage. + if (m_broke == false) + { + m_velocity = m_body1->GetLinearVelocity(); + m_angularVelocity = m_body1->GetAngularVelocity(); + } + + Test::Step(settings); + } + + static Test* Create() { return new Breakable; } + + b2Body* m_body1; + b2Vec2 m_velocity; + float m_angularVelocity; + b2PolygonShape m_shape1; + b2PolygonShape m_shape2; + b2Fixture* m_piece1; + b2Fixture* m_piece2; + + bool m_broke; + bool m_break; }; static int testIndex = RegisterTest("Examples", "Breakable", Breakable::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/bridge.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/bridge.cpp index d397a607daa9..69bfab2cf1ea 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/bridge.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/bridge.cpp @@ -25,104 +25,100 @@ class Bridge : public Test { public: - - enum - { - e_count = 30 - }; - - Bridge() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.125f); - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - fd.friction = 0.2f; - - b2RevoluteJointDef jd; - - b2Body* prevBody = ground; - for (int32 i = 0; i < e_count; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-14.5f + 1.0f * i, 5.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - - b2Vec2 anchor(-15.0f + 1.0f * i, 5.0f); - jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); - - if (i == (e_count >> 1)) - { - m_middle = body; - } - prevBody = body; - } - - b2Vec2 anchor(-15.0f + 1.0f * e_count, 5.0f); - jd.Initialize(prevBody, ground, anchor); - m_world->CreateJoint(&jd); - } - - for (int32 i = 0; i < 2; ++i) - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.5f, 0.0f); - vertices[1].Set(0.5f, 0.0f); - vertices[2].Set(0.0f, 1.5f); - - b2PolygonShape shape; - shape.Set(vertices, 3); - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-8.0f + 8.0f * i, 12.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - } - - for (int32 i = 0; i < 3; ++i) - { - b2CircleShape shape; - shape.m_radius = 0.5f; - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-6.0f + 6.0f * i, 10.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - } - } - - static Test* Create() - { - return new Bridge; - } - - b2Body* m_middle; + enum + { + e_count = 30 + }; + + Bridge() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.125f); + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + fd.friction = 0.2f; + + b2RevoluteJointDef jd; + + b2Body* prevBody = ground; + for (int32 i = 0; i < e_count; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-14.5f + 1.0f * i, 5.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + + b2Vec2 anchor(-15.0f + 1.0f * i, 5.0f); + jd.Initialize(prevBody, body, anchor); + m_world->CreateJoint(&jd); + + if (i == (e_count >> 1)) + { + m_middle = body; + } + prevBody = body; + } + + b2Vec2 anchor(-15.0f + 1.0f * e_count, 5.0f); + jd.Initialize(prevBody, ground, anchor); + m_world->CreateJoint(&jd); + } + + for (int32 i = 0; i < 2; ++i) + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.5f, 0.0f); + vertices[1].Set(0.5f, 0.0f); + vertices[2].Set(0.0f, 1.5f); + + b2PolygonShape shape; + shape.Set(vertices, 3); + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-8.0f + 8.0f * i, 12.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + } + + for (int32 i = 0; i < 3; ++i) + { + b2CircleShape shape; + shape.m_radius = 0.5f; + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-6.0f + 6.0f * i, 10.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + } + } + + static Test* Create() { return new Bridge; } + + b2Body* m_middle; }; static int testIndex = RegisterTest("Joints", "Bridge", Bridge::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/bullet_test.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/bullet_test.cpp index 0ff1800f2834..945887da6f9c 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/bullet_test.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/bullet_test.cpp @@ -25,115 +25,108 @@ class BulletTest : public Test { public: - - BulletTest() - { - { - b2BodyDef bd; - bd.position.Set(0.0f, 0.0f); - b2Body* body = m_world->CreateBody(&bd); - - b2EdgeShape edge; - - edge.SetTwoSided(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); - body->CreateFixture(&edge, 0.0f); - - b2PolygonShape shape; - shape.SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0.0f); - body->CreateFixture(&shape, 0.0f); - } - - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 4.0f); - - b2PolygonShape box; - box.SetAsBox(2.0f, 0.1f); - - m_body = m_world->CreateBody(&bd); - m_body->CreateFixture(&box, 1.0f); - - box.SetAsBox(0.25f, 0.25f); - - //m_x = RandomFloat(-1.0f, 1.0f); - m_x = 0.20352793f; - bd.position.Set(m_x, 10.0f); - bd.bullet = true; - - m_bullet = m_world->CreateBody(&bd); - m_bullet->CreateFixture(&box, 100.0f); - - m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); - } - } - - void Launch() - { - m_body->SetTransform(b2Vec2(0.0f, 4.0f), 0.0f); - m_body->SetLinearVelocity(b2Vec2_zero); - m_body->SetAngularVelocity(0.0f); - - m_x = RandomFloat(-1.0f, 1.0f); - m_bullet->SetTransform(b2Vec2(m_x, 10.0f), 0.0f); - m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); - m_bullet->SetAngularVelocity(0.0f); - - extern B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; - extern B2_API int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters; - extern B2_API int32 b2_toiRootIters, b2_toiMaxRootIters; - - b2_gjkCalls = 0; - b2_gjkIters = 0; - b2_gjkMaxIters = 0; - - b2_toiCalls = 0; - b2_toiIters = 0; - b2_toiMaxIters = 0; - b2_toiRootIters = 0; - b2_toiMaxRootIters = 0; - } - - void Step(Settings& settings) override - { - Test::Step(settings); - - extern B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; - extern B2_API int32 b2_toiCalls, b2_toiIters; - extern B2_API int32 b2_toiRootIters, b2_toiMaxRootIters; - - if (b2_gjkCalls > 0) - { - DrawString(5, m_textLine, "gjk calls = %d, ave gjk iters = %3.1f, max gjk iters = %d", - b2_gjkCalls, b2_gjkIters / float(b2_gjkCalls), b2_gjkMaxIters); - - } - - if (b2_toiCalls > 0) - { - DrawString(5, m_textLine, "toi calls = %d, ave toi iters = %3.1f, max toi iters = %d", - b2_toiCalls, b2_toiIters / float(b2_toiCalls), b2_toiMaxRootIters); - - - DrawString(5, m_textLine, "ave toi root iters = %3.1f, max toi root iters = %d", - b2_toiRootIters / float(b2_toiCalls), b2_toiMaxRootIters); - - } - - if (m_stepCount % 60 == 0) - { - Launch(); - } - } - - static Test* Create() - { - return new BulletTest; - } - - b2Body* m_body; - b2Body* m_bullet; - float m_x; + BulletTest() + { + { + b2BodyDef bd; + bd.position.Set(0.0f, 0.0f); + b2Body* body = m_world->CreateBody(&bd); + + b2EdgeShape edge; + + edge.SetTwoSided(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); + body->CreateFixture(&edge, 0.0f); + + b2PolygonShape shape; + shape.SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0.0f); + body->CreateFixture(&shape, 0.0f); + } + + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 4.0f); + + b2PolygonShape box; + box.SetAsBox(2.0f, 0.1f); + + m_body = m_world->CreateBody(&bd); + m_body->CreateFixture(&box, 1.0f); + + box.SetAsBox(0.25f, 0.25f); + + // m_x = RandomFloat(-1.0f, 1.0f); + m_x = 0.20352793f; + bd.position.Set(m_x, 10.0f); + bd.bullet = true; + + m_bullet = m_world->CreateBody(&bd); + m_bullet->CreateFixture(&box, 100.0f); + + m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); + } + } + + void Launch() + { + m_body->SetTransform(b2Vec2(0.0f, 4.0f), 0.0f); + m_body->SetLinearVelocity(b2Vec2_zero); + m_body->SetAngularVelocity(0.0f); + + m_x = RandomFloat(-1.0f, 1.0f); + m_bullet->SetTransform(b2Vec2(m_x, 10.0f), 0.0f); + m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); + m_bullet->SetAngularVelocity(0.0f); + + extern B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; + extern B2_API int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters; + extern B2_API int32 b2_toiRootIters, b2_toiMaxRootIters; + + b2_gjkCalls = 0; + b2_gjkIters = 0; + b2_gjkMaxIters = 0; + + b2_toiCalls = 0; + b2_toiIters = 0; + b2_toiMaxIters = 0; + b2_toiRootIters = 0; + b2_toiMaxRootIters = 0; + } + + void Step(Settings& settings) override + { + Test::Step(settings); + + extern B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; + extern B2_API int32 b2_toiCalls, b2_toiIters; + extern B2_API int32 b2_toiRootIters, b2_toiMaxRootIters; + + if (b2_gjkCalls > 0) + { + DrawString(5, m_textLine, "gjk calls = %d, ave gjk iters = %3.1f, max gjk iters = %d", b2_gjkCalls, + b2_gjkIters / float(b2_gjkCalls), b2_gjkMaxIters); + } + + if (b2_toiCalls > 0) + { + DrawString(5, m_textLine, "toi calls = %d, ave toi iters = %3.1f, max toi iters = %d", b2_toiCalls, + b2_toiIters / float(b2_toiCalls), b2_toiMaxRootIters); + + DrawString(5, m_textLine, "ave toi root iters = %3.1f, max toi root iters = %d", + b2_toiRootIters / float(b2_toiCalls), b2_toiMaxRootIters); + } + + if (m_stepCount % 60 == 0) + { + Launch(); + } + } + + static Test* Create() { return new BulletTest; } + + b2Body* m_body; + b2Body* m_bullet; + float m_x; }; static int testIndex = RegisterTest("Continuous", "Bullet Test", BulletTest::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/cantilever.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/cantilever.cpp index e54717b76b64..8a9ffce0b7cd 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/cantilever.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/cantilever.cpp @@ -29,190 +29,186 @@ class Cantilever : public Test { public: - - enum - { - e_count = 8 - }; - - Cantilever() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.125f); - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - - b2WeldJointDef jd; - - b2Body* prevBody = ground; - for (int32 i = 0; i < e_count; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-14.5f + 1.0f * i, 5.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - - b2Vec2 anchor(-15.0f + 1.0f * i, 5.0f); - jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); - - prevBody = body; - } - } - - { - b2PolygonShape shape; - shape.SetAsBox(1.0f, 0.125f); - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - - b2WeldJointDef jd; - float frequencyHz = 5.0f; - float dampingRatio = 0.7f; - - b2Body* prevBody = ground; - for (int32 i = 0; i < 3; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-14.0f + 2.0f * i, 15.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - - b2Vec2 anchor(-15.0f + 2.0f * i, 15.0f); - jd.Initialize(prevBody, body, anchor); - b2AngularStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_world->CreateJoint(&jd); - - prevBody = body; - } - } - - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.125f); - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - - b2WeldJointDef jd; - - b2Body* prevBody = ground; - for (int32 i = 0; i < e_count; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-4.5f + 1.0f * i, 5.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - - if (i > 0) - { - b2Vec2 anchor(-5.0f + 1.0f * i, 5.0f); - jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); - } - - prevBody = body; - } - } - - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.125f); - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - - b2WeldJointDef jd; - float frequencyHz = 8.0f; - float dampingRatio = 0.7f; - - b2Body* prevBody = ground; - for (int32 i = 0; i < e_count; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(5.5f + 1.0f * i, 10.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - - if (i > 0) - { - b2Vec2 anchor(5.0f + 1.0f * i, 10.0f); - jd.Initialize(prevBody, body, anchor); - - b2AngularStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, prevBody, body); - - m_world->CreateJoint(&jd); - } - - prevBody = body; - } - } - - for (int32 i = 0; i < 2; ++i) - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.5f, 0.0f); - vertices[1].Set(0.5f, 0.0f); - vertices[2].Set(0.0f, 1.5f); - - b2PolygonShape shape; - shape.Set(vertices, 3); - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-8.0f + 8.0f * i, 12.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - } - - for (int32 i = 0; i < 2; ++i) - { - b2CircleShape shape; - shape.m_radius = 0.5f; - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-6.0f + 6.0f * i, 10.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - } - } - - static Test* Create() - { - return new Cantilever; - } - - b2Body* m_middle; + enum + { + e_count = 8 + }; + + Cantilever() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.125f); + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + + b2WeldJointDef jd; + + b2Body* prevBody = ground; + for (int32 i = 0; i < e_count; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-14.5f + 1.0f * i, 5.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + + b2Vec2 anchor(-15.0f + 1.0f * i, 5.0f); + jd.Initialize(prevBody, body, anchor); + m_world->CreateJoint(&jd); + + prevBody = body; + } + } + + { + b2PolygonShape shape; + shape.SetAsBox(1.0f, 0.125f); + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + + b2WeldJointDef jd; + float frequencyHz = 5.0f; + float dampingRatio = 0.7f; + + b2Body* prevBody = ground; + for (int32 i = 0; i < 3; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-14.0f + 2.0f * i, 15.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + + b2Vec2 anchor(-15.0f + 2.0f * i, 15.0f); + jd.Initialize(prevBody, body, anchor); + b2AngularStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_world->CreateJoint(&jd); + + prevBody = body; + } + } + + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.125f); + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + + b2WeldJointDef jd; + + b2Body* prevBody = ground; + for (int32 i = 0; i < e_count; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-4.5f + 1.0f * i, 5.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + + if (i > 0) + { + b2Vec2 anchor(-5.0f + 1.0f * i, 5.0f); + jd.Initialize(prevBody, body, anchor); + m_world->CreateJoint(&jd); + } + + prevBody = body; + } + } + + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.125f); + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + + b2WeldJointDef jd; + float frequencyHz = 8.0f; + float dampingRatio = 0.7f; + + b2Body* prevBody = ground; + for (int32 i = 0; i < e_count; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(5.5f + 1.0f * i, 10.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + + if (i > 0) + { + b2Vec2 anchor(5.0f + 1.0f * i, 10.0f); + jd.Initialize(prevBody, body, anchor); + + b2AngularStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, prevBody, body); + + m_world->CreateJoint(&jd); + } + + prevBody = body; + } + } + + for (int32 i = 0; i < 2; ++i) + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.5f, 0.0f); + vertices[1].Set(0.5f, 0.0f); + vertices[2].Set(0.0f, 1.5f); + + b2PolygonShape shape; + shape.Set(vertices, 3); + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-8.0f + 8.0f * i, 12.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + } + + for (int32 i = 0; i < 2; ++i) + { + b2CircleShape shape; + shape.m_radius = 0.5f; + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-6.0f + 6.0f * i, 10.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + } + } + + static Test* Create() { return new Cantilever; } + + b2Body* m_middle; }; static int testIndex = RegisterTest("Joints", "Cantilever", Cantilever::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/car.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/car.cpp index 63179b052642..c8bd9f087569 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/car.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/car.cpp @@ -30,261 +30,257 @@ USING_NS_CC_EXT; class Car : public Test { public: - Car() - { - m_speed = 50.0f; - - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 0.0f; - fd.friction = 0.6f; - - shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); - ground->CreateFixture(&fd); - - float hs[10] = {0.25f, 1.0f, 4.0f, 0.0f, 0.0f, -1.0f, -2.0f, -2.0f, -1.25f, 0.0f}; - - float x = 20.0f, y1 = 0.0f, dx = 5.0f; - - for (int32 i = 0; i < 10; ++i) - { - float y2 = hs[i]; - shape.SetTwoSided(b2Vec2(x, y1), b2Vec2(x + dx, y2)); - ground->CreateFixture(&fd); - y1 = y2; - x += dx; - } - - for (int32 i = 0; i < 10; ++i) - { - float y2 = hs[i]; - shape.SetTwoSided(b2Vec2(x, y1), b2Vec2(x + dx, y2)); - ground->CreateFixture(&fd); - y1 = y2; - x += dx; - } - - shape.SetTwoSided(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); - ground->CreateFixture(&fd); - - x += 80.0f; - shape.SetTwoSided(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); - ground->CreateFixture(&fd); - - x += 40.0f; - shape.SetTwoSided(b2Vec2(x, 0.0f), b2Vec2(x + 10.0f, 5.0f)); - ground->CreateFixture(&fd); - - x += 20.0f; - shape.SetTwoSided(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); - ground->CreateFixture(&fd); - - x += 40.0f; - shape.SetTwoSided(b2Vec2(x, 0.0f), b2Vec2(x, 20.0f)); - ground->CreateFixture(&fd); - } - - // Teeter - { - b2BodyDef bd; - bd.position.Set(140.0f, 1.0f); - bd.type = b2_dynamicBody; - b2Body* body = m_world->CreateBody(&bd); - - b2PolygonShape box; - box.SetAsBox(10.0f, 0.25f); - body->CreateFixture(&box, 1.0f); - - b2RevoluteJointDef jd; - jd.Initialize(ground, body, body->GetPosition()); - jd.lowerAngle = -8.0f * b2_pi / 180.0f; - jd.upperAngle = 8.0f * b2_pi / 180.0f; - jd.enableLimit = true; - m_world->CreateJoint(&jd); - - body->ApplyAngularImpulse(100.0f, true); - } - - // Bridge - { - int32 N = 20; - b2PolygonShape shape; - shape.SetAsBox(1.0f, 0.125f); - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - fd.friction = 0.6f; - - b2RevoluteJointDef jd; - - b2Body* prevBody = ground; - for (int32 i = 0; i < N; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(161.0f + 2.0f * i, -0.125f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - - b2Vec2 anchor(160.0f + 2.0f * i, -0.125f); - jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); - - prevBody = body; - } - - b2Vec2 anchor(160.0f + 2.0f * N, -0.125f); - jd.Initialize(prevBody, ground, anchor); - m_world->CreateJoint(&jd); - } - - // Boxes - { - b2PolygonShape box; - box.SetAsBox(0.5f, 0.5f); - - b2Body* body = NULL; - b2BodyDef bd; - bd.type = b2_dynamicBody; - - bd.position.Set(230.0f, 0.5f); - body = m_world->CreateBody(&bd); - body->CreateFixture(&box, 0.5f); - - bd.position.Set(230.0f, 1.5f); - body = m_world->CreateBody(&bd); - body->CreateFixture(&box, 0.5f); - - bd.position.Set(230.0f, 2.5f); - body = m_world->CreateBody(&bd); - body->CreateFixture(&box, 0.5f); - - bd.position.Set(230.0f, 3.5f); - body = m_world->CreateBody(&bd); - body->CreateFixture(&box, 0.5f); - - bd.position.Set(230.0f, 4.5f); - body = m_world->CreateBody(&bd); - body->CreateFixture(&box, 0.5f); - } - - // Car - { - b2PolygonShape chassis; - b2Vec2 vertices[8]; - vertices[0].Set(-1.5f, -0.5f); - vertices[1].Set(1.5f, -0.5f); - vertices[2].Set(1.5f, 0.0f); - vertices[3].Set(0.0f, 0.9f); - vertices[4].Set(-1.15f, 0.9f); - vertices[5].Set(-1.5f, 0.2f); - chassis.Set(vertices, 6); - - b2CircleShape circle; - circle.m_radius = 0.4f; - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 1.0f); - m_car = m_world->CreateBody(&bd); - m_car->CreateFixture(&chassis, 1.0f); - - b2FixtureDef fd; - fd.shape = &circle; - fd.density = 1.0f; - fd.friction = 0.9f; - - bd.position.Set(-1.0f, 0.35f); - m_wheel1 = m_world->CreateBody(&bd); - m_wheel1->CreateFixture(&fd); - - bd.position.Set(1.0f, 0.4f); - m_wheel2 = m_world->CreateBody(&bd); - m_wheel2->CreateFixture(&fd); - - b2WheelJointDef jd; - b2Vec2 axis(0.0f, 1.0f); - - float mass1 = m_wheel1->GetMass(); - float mass2 = m_wheel2->GetMass(); - - float hertz = 4.0f; - float dampingRatio = 0.7f; - float omega = 2.0f * b2_pi * hertz; - - jd.Initialize(m_car, m_wheel1, m_wheel1->GetPosition(), axis); - jd.motorSpeed = 0.0f; - jd.maxMotorTorque = 20.0f; - jd.enableMotor = true; - jd.stiffness = mass1 * omega * omega; - jd.damping = 2.0f * mass1 * dampingRatio * omega; - jd.lowerTranslation = -0.25f; - jd.upperTranslation = 0.25f; - jd.enableLimit = true; - m_spring1 = (b2WheelJoint*)m_world->CreateJoint(&jd); - - jd.Initialize(m_car, m_wheel2, m_wheel2->GetPosition(), axis); - jd.motorSpeed = 0.0f; - jd.maxMotorTorque = 10.0f; - jd.enableMotor = false; - jd.stiffness = mass2 * omega * omega; - jd.damping = 2.0f * mass2 * dampingRatio * omega; - jd.lowerTranslation = -0.25f; - jd.upperTranslation = 0.25f; - jd.enableLimit = true; - m_spring2 = (b2WheelJoint*)m_world->CreateJoint(&jd); - } - } - - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_A: - m_spring1->SetMotorSpeed(m_speed); - break; - - case GLFW_KEY_S: - m_spring1->SetMotorSpeed(0.0f); - break; - - case GLFW_KEY_D: - m_spring1->SetMotorSpeed(-m_speed); - break; - } - } - - void Step(Settings& settings) override - { - DrawString(5, m_textLine, "Keys: left = a, brake = s, right = d, hz down = q, hz up = e"); - - - //g_camera.m_center.x = m_car->GetPosition().x; - g_debugDraw.debugNodeOffset.x += m_car->GetPosition().x; - - Test::Step(settings); - } - - static Test* Create() - { - return new Car; - } - - b2Body* m_car; - b2Body* m_wheel1; - b2Body* m_wheel2; - - float m_speed; - b2WheelJoint* m_spring1; - b2WheelJoint* m_spring2; + Car() + { + m_speed = 50.0f; + + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 0.0f; + fd.friction = 0.6f; + + shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); + ground->CreateFixture(&fd); + + float hs[10] = {0.25f, 1.0f, 4.0f, 0.0f, 0.0f, -1.0f, -2.0f, -2.0f, -1.25f, 0.0f}; + + float x = 20.0f, y1 = 0.0f, dx = 5.0f; + + for (int32 i = 0; i < 10; ++i) + { + float y2 = hs[i]; + shape.SetTwoSided(b2Vec2(x, y1), b2Vec2(x + dx, y2)); + ground->CreateFixture(&fd); + y1 = y2; + x += dx; + } + + for (int32 i = 0; i < 10; ++i) + { + float y2 = hs[i]; + shape.SetTwoSided(b2Vec2(x, y1), b2Vec2(x + dx, y2)); + ground->CreateFixture(&fd); + y1 = y2; + x += dx; + } + + shape.SetTwoSided(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); + ground->CreateFixture(&fd); + + x += 80.0f; + shape.SetTwoSided(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); + ground->CreateFixture(&fd); + + x += 40.0f; + shape.SetTwoSided(b2Vec2(x, 0.0f), b2Vec2(x + 10.0f, 5.0f)); + ground->CreateFixture(&fd); + + x += 20.0f; + shape.SetTwoSided(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); + ground->CreateFixture(&fd); + + x += 40.0f; + shape.SetTwoSided(b2Vec2(x, 0.0f), b2Vec2(x, 20.0f)); + ground->CreateFixture(&fd); + } + + // Teeter + { + b2BodyDef bd; + bd.position.Set(140.0f, 1.0f); + bd.type = b2_dynamicBody; + b2Body* body = m_world->CreateBody(&bd); + + b2PolygonShape box; + box.SetAsBox(10.0f, 0.25f); + body->CreateFixture(&box, 1.0f); + + b2RevoluteJointDef jd; + jd.Initialize(ground, body, body->GetPosition()); + jd.lowerAngle = -8.0f * b2_pi / 180.0f; + jd.upperAngle = 8.0f * b2_pi / 180.0f; + jd.enableLimit = true; + m_world->CreateJoint(&jd); + + body->ApplyAngularImpulse(100.0f, true); + } + + // Bridge + { + int32 N = 20; + b2PolygonShape shape; + shape.SetAsBox(1.0f, 0.125f); + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + fd.friction = 0.6f; + + b2RevoluteJointDef jd; + + b2Body* prevBody = ground; + for (int32 i = 0; i < N; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(161.0f + 2.0f * i, -0.125f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + + b2Vec2 anchor(160.0f + 2.0f * i, -0.125f); + jd.Initialize(prevBody, body, anchor); + m_world->CreateJoint(&jd); + + prevBody = body; + } + + b2Vec2 anchor(160.0f + 2.0f * N, -0.125f); + jd.Initialize(prevBody, ground, anchor); + m_world->CreateJoint(&jd); + } + + // Boxes + { + b2PolygonShape box; + box.SetAsBox(0.5f, 0.5f); + + b2Body* body = NULL; + b2BodyDef bd; + bd.type = b2_dynamicBody; + + bd.position.Set(230.0f, 0.5f); + body = m_world->CreateBody(&bd); + body->CreateFixture(&box, 0.5f); + + bd.position.Set(230.0f, 1.5f); + body = m_world->CreateBody(&bd); + body->CreateFixture(&box, 0.5f); + + bd.position.Set(230.0f, 2.5f); + body = m_world->CreateBody(&bd); + body->CreateFixture(&box, 0.5f); + + bd.position.Set(230.0f, 3.5f); + body = m_world->CreateBody(&bd); + body->CreateFixture(&box, 0.5f); + + bd.position.Set(230.0f, 4.5f); + body = m_world->CreateBody(&bd); + body->CreateFixture(&box, 0.5f); + } + + // Car + { + b2PolygonShape chassis; + b2Vec2 vertices[8]; + vertices[0].Set(-1.5f, -0.5f); + vertices[1].Set(1.5f, -0.5f); + vertices[2].Set(1.5f, 0.0f); + vertices[3].Set(0.0f, 0.9f); + vertices[4].Set(-1.15f, 0.9f); + vertices[5].Set(-1.5f, 0.2f); + chassis.Set(vertices, 6); + + b2CircleShape circle; + circle.m_radius = 0.4f; + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 1.0f); + m_car = m_world->CreateBody(&bd); + m_car->CreateFixture(&chassis, 1.0f); + + b2FixtureDef fd; + fd.shape = &circle; + fd.density = 1.0f; + fd.friction = 0.9f; + + bd.position.Set(-1.0f, 0.35f); + m_wheel1 = m_world->CreateBody(&bd); + m_wheel1->CreateFixture(&fd); + + bd.position.Set(1.0f, 0.4f); + m_wheel2 = m_world->CreateBody(&bd); + m_wheel2->CreateFixture(&fd); + + b2WheelJointDef jd; + b2Vec2 axis(0.0f, 1.0f); + + float mass1 = m_wheel1->GetMass(); + float mass2 = m_wheel2->GetMass(); + + float hertz = 4.0f; + float dampingRatio = 0.7f; + float omega = 2.0f * b2_pi * hertz; + + jd.Initialize(m_car, m_wheel1, m_wheel1->GetPosition(), axis); + jd.motorSpeed = 0.0f; + jd.maxMotorTorque = 20.0f; + jd.enableMotor = true; + jd.stiffness = mass1 * omega * omega; + jd.damping = 2.0f * mass1 * dampingRatio * omega; + jd.lowerTranslation = -0.25f; + jd.upperTranslation = 0.25f; + jd.enableLimit = true; + m_spring1 = (b2WheelJoint*)m_world->CreateJoint(&jd); + + jd.Initialize(m_car, m_wheel2, m_wheel2->GetPosition(), axis); + jd.motorSpeed = 0.0f; + jd.maxMotorTorque = 10.0f; + jd.enableMotor = false; + jd.stiffness = mass2 * omega * omega; + jd.damping = 2.0f * mass2 * dampingRatio * omega; + jd.lowerTranslation = -0.25f; + jd.upperTranslation = 0.25f; + jd.enableLimit = true; + m_spring2 = (b2WheelJoint*)m_world->CreateJoint(&jd); + } + } + + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_A: + m_spring1->SetMotorSpeed(m_speed); + break; + + case GLFW_KEY_S: + m_spring1->SetMotorSpeed(0.0f); + break; + + case GLFW_KEY_D: + m_spring1->SetMotorSpeed(-m_speed); + break; + } + } + + void Step(Settings& settings) override + { + DrawString(5, m_textLine, "Keys: left = a, brake = s, right = d, hz down = q, hz up = e"); + + // g_camera.m_center.x = m_car->GetPosition().x; + g_debugDraw.debugNodeOffset.x += m_car->GetPosition().x; + + Test::Step(settings); + } + + static Test* Create() { return new Car; } + + b2Body* m_car; + b2Body* m_wheel1; + b2Body* m_wheel2; + + float m_speed; + b2WheelJoint* m_spring1; + b2WheelJoint* m_spring2; }; static int testIndex = RegisterTest("Examples", "Car", Car::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/chain.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/chain.cpp index e1580355e307..3520b89330ca 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/chain.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/chain.cpp @@ -27,66 +27,63 @@ class Chain : public Test { public: - Chain() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - { - b2PolygonShape shape; - shape.SetAsBox(0.6f, 0.125f); - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - fd.friction = 0.2f; - - b2RevoluteJointDef jd; - jd.collideConnected = false; - - const float y = 25.0f; - b2Body* prevBody = ground; - for (int32 i = 0; i < 30; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.5f + i, y); - b2Body* body = m_world->CreateBody(&bd); + Chain() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + { + b2PolygonShape shape; + shape.SetAsBox(0.6f, 0.125f); + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + fd.friction = 0.2f; + + b2RevoluteJointDef jd; + jd.collideConnected = false; + + const float y = 25.0f; + b2Body* prevBody = ground; + for (int32 i = 0; i < 30; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.5f + i, y); + b2Body* body = m_world->CreateBody(&bd); #if TEST_BAD_BODY == 1 - if (i == 10) - { - // Test zero density dynamic body - fd.density = 0.0f; - } - else - { - fd.density = 20.0f; - } + if (i == 10) + { + // Test zero density dynamic body + fd.density = 0.0f; + } + else + { + fd.density = 20.0f; + } #endif - body->CreateFixture(&fd); + body->CreateFixture(&fd); - b2Vec2 anchor(float(i), y); - jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); + b2Vec2 anchor(float(i), y); + jd.Initialize(prevBody, body, anchor); + m_world->CreateJoint(&jd); - prevBody = body; - } - } - } + prevBody = body; + } + } + } - static Test* Create() - { - return new Chain; - } + static Test* Create() { return new Chain; } }; static int testIndex = RegisterTest("Joints", "Chain", Chain::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/chain_problem.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/chain_problem.cpp index 4b2ab3828db4..a9a48a87301d 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/chain_problem.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/chain_problem.cpp @@ -25,17 +25,16 @@ class ChainProblem : public Test { public: - ChainProblem() { { b2Vec2 g(0.0f, -10.0f); m_world->SetGravity(g); - b2Body** bodies = (b2Body**)b2Alloc(2 * sizeof(b2Body*)); + b2Body** bodies = (b2Body**)b2Alloc(2 * sizeof(b2Body*)); b2Joint** joints = (b2Joint**)b2Alloc(0 * sizeof(b2Joint*)); { b2BodyDef bd; - bd.type = b2BodyType(0); + bd.type = b2BodyType(0); bodies[0] = m_world->CreateBody(&bd); { @@ -56,14 +55,14 @@ class ChainProblem : public Test { b2BodyDef bd; bd.type = b2BodyType(2); - //bd.position.Set(6.033980250358582e-01f, 3.028350114822388e+00f); + // bd.position.Set(6.033980250358582e-01f, 3.028350114822388e+00f); bd.position.Set(1.0f, 3.0f); bodies[1] = m_world->CreateBody(&bd); { b2FixtureDef fd; fd.friction = 0.2f; - fd.density = 10.0f; + fd.density = 10.0f; b2PolygonShape shape; b2Vec2 vs[8]; vs[0].Set(0.5f, -3.0f); @@ -84,11 +83,7 @@ class ChainProblem : public Test } } - static Test* Create() - { - return new ChainProblem; - } - + static Test* Create() { return new ChainProblem; } }; static int testIndex = RegisterTest("Bugs", "Chain Problem", ChainProblem::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/character_collision.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/character_collision.cpp index 42af87aec71f..42f9f81d6f98 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/character_collision.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/character_collision.cpp @@ -28,229 +28,225 @@ class CharacterCollision : public Test { public: - CharacterCollision() - { - // Ground body - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - // Collinear edges with no adjacency information. - // This shows the problematic case where a box shape can hit - // an internal vertex. - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-8.0f, 1.0f), b2Vec2(-6.0f, 1.0f)); - ground->CreateFixture(&shape, 0.0f); - shape.SetTwoSided(b2Vec2(-6.0f, 1.0f), b2Vec2(-4.0f, 1.0f)); - ground->CreateFixture(&shape, 0.0f); - shape.SetTwoSided(b2Vec2(-4.0f, 1.0f), b2Vec2(-2.0f, 1.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - // Chain shape - { - b2BodyDef bd; - bd.angle = 0.25f * b2_pi; - b2Body* ground = m_world->CreateBody(&bd); - - b2Vec2 vs[4]; - vs[0].Set(5.0f, 7.0f); - vs[1].Set(6.0f, 8.0f); - vs[2].Set(7.0f, 8.0f); - vs[3].Set(8.0f, 7.0f); - b2ChainShape shape; - shape.CreateLoop(vs, 4); - ground->CreateFixture(&shape, 0.0f); - } - - // Square tiles. This shows that adjacency shapes may - // have non-smooth collision. There is no solution - // to this problem. - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2PolygonShape shape; - shape.SetAsBox(1.0f, 1.0f, b2Vec2(4.0f, 3.0f), 0.0f); - ground->CreateFixture(&shape, 0.0f); - shape.SetAsBox(1.0f, 1.0f, b2Vec2(6.0f, 3.0f), 0.0f); - ground->CreateFixture(&shape, 0.0f); - shape.SetAsBox(1.0f, 1.0f, b2Vec2(8.0f, 3.0f), 0.0f); - ground->CreateFixture(&shape, 0.0f); - } - - // Square made from an edge loop. Collision should be smooth. - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2Vec2 vs[4]; - vs[0].Set(-1.0f, 3.0f); - vs[1].Set(1.0f, 3.0f); - vs[2].Set(1.0f, 5.0f); - vs[3].Set(-1.0f, 5.0f); - b2ChainShape shape; - shape.CreateLoop(vs, 4); - ground->CreateFixture(&shape, 0.0f); - } - - // Edge loop. Collision should be smooth. - { - b2BodyDef bd; - bd.position.Set(-10.0f, 4.0f); - b2Body* ground = m_world->CreateBody(&bd); - - b2Vec2 vs[10]; - vs[0].Set(0.0f, 0.0f); - vs[1].Set(6.0f, 0.0f); - vs[2].Set(6.0f, 2.0f); - vs[3].Set(4.0f, 1.0f); - vs[4].Set(2.0f, 2.0f); - vs[5].Set(0.0f, 2.0f); - vs[6].Set(-2.0f, 2.0f); - vs[7].Set(-4.0f, 3.0f); - vs[8].Set(-6.0f, 2.0f); - vs[9].Set(-6.0f, 0.0f); - b2ChainShape shape; - shape.CreateLoop(vs, 10); - ground->CreateFixture(&shape, 0.0f); - } - - // Square character 1 - { - b2BodyDef bd; - bd.position.Set(-3.0f, 8.0f); - bd.type = b2_dynamicBody; - bd.fixedRotation = true; - bd.allowSleep = false; - - b2Body* body = m_world->CreateBody(&bd); - - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.5f); - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - body->CreateFixture(&fd); - } - - // Square character 2 - { - b2BodyDef bd; - bd.position.Set(-5.0f, 5.0f); - bd.type = b2_dynamicBody; - bd.fixedRotation = true; - bd.allowSleep = false; - - b2Body* body = m_world->CreateBody(&bd); - - b2PolygonShape shape; - shape.SetAsBox(0.25f, 0.25f); - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - body->CreateFixture(&fd); - } - - // Hexagon character - { - b2BodyDef bd; - bd.position.Set(-5.0f, 8.0f); - bd.type = b2_dynamicBody; - bd.fixedRotation = true; - bd.allowSleep = false; - - b2Body* body = m_world->CreateBody(&bd); - - float angle = 0.0f; - float delta = b2_pi / 3.0f; - b2Vec2 vertices[6]; - for (int32 i = 0; i < 6; ++i) - { - vertices[i].Set(0.5f * cosf(angle), 0.5f * sinf(angle)); - angle += delta; - } - - b2PolygonShape shape; - shape.Set(vertices, 6); - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - body->CreateFixture(&fd); - } - - // Circle character - { - b2BodyDef bd; - bd.position.Set(3.0f, 5.0f); - bd.type = b2_dynamicBody; - bd.fixedRotation = true; - bd.allowSleep = false; - - b2Body* body = m_world->CreateBody(&bd); - - b2CircleShape shape; - shape.m_radius = 0.5f; - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - body->CreateFixture(&fd); - } - - // Circle character - { - b2BodyDef bd; - bd.position.Set(-7.0f, 6.0f); - bd.type = b2_dynamicBody; - bd.allowSleep = false; - - m_character = m_world->CreateBody(&bd); - - b2CircleShape shape; - shape.m_radius = 0.25f; - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - fd.friction = 1.0f; - m_character->CreateFixture(&fd); - } - } - - void Step(Settings& settings) override - { - b2Vec2 v = m_character->GetLinearVelocity(); - v.x = -5.0f; - m_character->SetLinearVelocity(v); - - Test::Step(settings); - DrawString(5, m_textLine, "This tests various character collision shapes."); - - DrawString(5, m_textLine, "Limitation: square and hexagon can snag on aligned boxes."); - - DrawString(5, m_textLine, "Feature: edge chains have smooth collision inside and out."); - - } - - static Test* Create() - { - return new CharacterCollision; - } - - b2Body* m_character; + CharacterCollision() + { + // Ground body + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + // Collinear edges with no adjacency information. + // This shows the problematic case where a box shape can hit + // an internal vertex. + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-8.0f, 1.0f), b2Vec2(-6.0f, 1.0f)); + ground->CreateFixture(&shape, 0.0f); + shape.SetTwoSided(b2Vec2(-6.0f, 1.0f), b2Vec2(-4.0f, 1.0f)); + ground->CreateFixture(&shape, 0.0f); + shape.SetTwoSided(b2Vec2(-4.0f, 1.0f), b2Vec2(-2.0f, 1.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + // Chain shape + { + b2BodyDef bd; + bd.angle = 0.25f * b2_pi; + b2Body* ground = m_world->CreateBody(&bd); + + b2Vec2 vs[4]; + vs[0].Set(5.0f, 7.0f); + vs[1].Set(6.0f, 8.0f); + vs[2].Set(7.0f, 8.0f); + vs[3].Set(8.0f, 7.0f); + b2ChainShape shape; + shape.CreateLoop(vs, 4); + ground->CreateFixture(&shape, 0.0f); + } + + // Square tiles. This shows that adjacency shapes may + // have non-smooth collision. There is no solution + // to this problem. + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2PolygonShape shape; + shape.SetAsBox(1.0f, 1.0f, b2Vec2(4.0f, 3.0f), 0.0f); + ground->CreateFixture(&shape, 0.0f); + shape.SetAsBox(1.0f, 1.0f, b2Vec2(6.0f, 3.0f), 0.0f); + ground->CreateFixture(&shape, 0.0f); + shape.SetAsBox(1.0f, 1.0f, b2Vec2(8.0f, 3.0f), 0.0f); + ground->CreateFixture(&shape, 0.0f); + } + + // Square made from an edge loop. Collision should be smooth. + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2Vec2 vs[4]; + vs[0].Set(-1.0f, 3.0f); + vs[1].Set(1.0f, 3.0f); + vs[2].Set(1.0f, 5.0f); + vs[3].Set(-1.0f, 5.0f); + b2ChainShape shape; + shape.CreateLoop(vs, 4); + ground->CreateFixture(&shape, 0.0f); + } + + // Edge loop. Collision should be smooth. + { + b2BodyDef bd; + bd.position.Set(-10.0f, 4.0f); + b2Body* ground = m_world->CreateBody(&bd); + + b2Vec2 vs[10]; + vs[0].Set(0.0f, 0.0f); + vs[1].Set(6.0f, 0.0f); + vs[2].Set(6.0f, 2.0f); + vs[3].Set(4.0f, 1.0f); + vs[4].Set(2.0f, 2.0f); + vs[5].Set(0.0f, 2.0f); + vs[6].Set(-2.0f, 2.0f); + vs[7].Set(-4.0f, 3.0f); + vs[8].Set(-6.0f, 2.0f); + vs[9].Set(-6.0f, 0.0f); + b2ChainShape shape; + shape.CreateLoop(vs, 10); + ground->CreateFixture(&shape, 0.0f); + } + + // Square character 1 + { + b2BodyDef bd; + bd.position.Set(-3.0f, 8.0f); + bd.type = b2_dynamicBody; + bd.fixedRotation = true; + bd.allowSleep = false; + + b2Body* body = m_world->CreateBody(&bd); + + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + body->CreateFixture(&fd); + } + + // Square character 2 + { + b2BodyDef bd; + bd.position.Set(-5.0f, 5.0f); + bd.type = b2_dynamicBody; + bd.fixedRotation = true; + bd.allowSleep = false; + + b2Body* body = m_world->CreateBody(&bd); + + b2PolygonShape shape; + shape.SetAsBox(0.25f, 0.25f); + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + body->CreateFixture(&fd); + } + + // Hexagon character + { + b2BodyDef bd; + bd.position.Set(-5.0f, 8.0f); + bd.type = b2_dynamicBody; + bd.fixedRotation = true; + bd.allowSleep = false; + + b2Body* body = m_world->CreateBody(&bd); + + float angle = 0.0f; + float delta = b2_pi / 3.0f; + b2Vec2 vertices[6]; + for (int32 i = 0; i < 6; ++i) + { + vertices[i].Set(0.5f * cosf(angle), 0.5f * sinf(angle)); + angle += delta; + } + + b2PolygonShape shape; + shape.Set(vertices, 6); + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + body->CreateFixture(&fd); + } + + // Circle character + { + b2BodyDef bd; + bd.position.Set(3.0f, 5.0f); + bd.type = b2_dynamicBody; + bd.fixedRotation = true; + bd.allowSleep = false; + + b2Body* body = m_world->CreateBody(&bd); + + b2CircleShape shape; + shape.m_radius = 0.5f; + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + body->CreateFixture(&fd); + } + + // Circle character + { + b2BodyDef bd; + bd.position.Set(-7.0f, 6.0f); + bd.type = b2_dynamicBody; + bd.allowSleep = false; + + m_character = m_world->CreateBody(&bd); + + b2CircleShape shape; + shape.m_radius = 0.25f; + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + fd.friction = 1.0f; + m_character->CreateFixture(&fd); + } + } + + void Step(Settings& settings) override + { + b2Vec2 v = m_character->GetLinearVelocity(); + v.x = -5.0f; + m_character->SetLinearVelocity(v); + + Test::Step(settings); + DrawString(5, m_textLine, "This tests various character collision shapes."); + + DrawString(5, m_textLine, "Limitation: square and hexagon can snag on aligned boxes."); + + DrawString(5, m_textLine, "Feature: edge chains have smooth collision inside and out."); + } + + static Test* Create() { return new CharacterCollision; } + + b2Body* m_character; }; static int testIndex = RegisterTest("Examples", "Character Collision", CharacterCollision::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/circle_stack.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/circle_stack.cpp index 62d19ea3feda..d642a12d33e2 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/circle_stack.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/circle_stack.cpp @@ -25,65 +25,61 @@ class CircleStack : public Test { public: + enum + { + e_count = 10 + }; - enum - { - e_count = 10 - }; + CircleStack() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - CircleStack() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + { + b2CircleShape shape; + shape.m_radius = 1.0f; - { - b2CircleShape shape; - shape.m_radius = 1.0f; + for (int32 i = 0; i < e_count; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0, 4.0f + 3.0f * i); - for (int32 i = 0; i < e_count; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0, 4.0f + 3.0f * i); + m_bodies[i] = m_world->CreateBody(&bd); - m_bodies[i] = m_world->CreateBody(&bd); + m_bodies[i]->CreateFixture(&shape, 1.0f); - m_bodies[i]->CreateFixture(&shape, 1.0f); + m_bodies[i]->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); + } + } + } - m_bodies[i]->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); - } - } - } + void Step(Settings& settings) override + { + Test::Step(settings); - void Step(Settings& settings) override - { - Test::Step(settings); + // for (int32 i = 0; i < e_count; ++i) + //{ + // printf("%g ", m_bodies[i]->GetWorldCenter().y); + // } - //for (int32 i = 0; i < e_count; ++i) - //{ - // printf("%g ", m_bodies[i]->GetWorldCenter().y); - //} + // for (int32 i = 0; i < e_count; ++i) + //{ + // printf("%g ", m_bodies[i]->GetLinearVelocity().y); + // } - //for (int32 i = 0; i < e_count; ++i) - //{ - // printf("%g ", m_bodies[i]->GetLinearVelocity().y); - //} + // printf("\n"); + } - //printf("\n"); - } + static Test* Create() { return new CircleStack; } - static Test* Create() - { - return new CircleStack; - } - - b2Body* m_bodies[e_count]; + b2Body* m_bodies[e_count]; }; static int testIndex = RegisterTest("Stacking", "Circles", CircleStack::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/collision_filtering.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/collision_filtering.cpp index 4903da5f5c64..65acb3866862 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/collision_filtering.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/collision_filtering.cpp @@ -28,152 +28,149 @@ // The 3 small ones always collide. // The 3 large ones never collide. // The boxes don't collide with triangles (except if both are small). -const int16 k_smallGroup = 1; +const int16 k_smallGroup = 1; const int16 k_largeGroup = -1; const uint16 k_triangleCategory = 0x0002; -const uint16 k_boxCategory = 0x0004; -const uint16 k_circleCategory = 0x0008; +const uint16 k_boxCategory = 0x0004; +const uint16 k_circleCategory = 0x0008; const uint16 k_triangleMask = 0xFFFF; -const uint16 k_boxMask = 0xFFFF ^ k_triangleCategory; -const uint16 k_circleMask = 0xFFFF; +const uint16 k_boxMask = 0xFFFF ^ k_triangleCategory; +const uint16 k_circleMask = 0xFFFF; class CollisionFiltering : public Test { public: - CollisionFiltering() - { - // Ground body - { - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - - b2FixtureDef sd; - sd.shape = &shape; - sd.friction = 0.3f; - - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&sd); - } - - // Small triangle - b2Vec2 vertices[3]; - vertices[0].Set(-1.0f, 0.0f); - vertices[1].Set(1.0f, 0.0f); - vertices[2].Set(0.0f, 2.0f); - b2PolygonShape polygon; - polygon.Set(vertices, 3); - - b2FixtureDef triangleShapeDef; - triangleShapeDef.shape = &polygon; - triangleShapeDef.density = 1.0f; - - triangleShapeDef.filter.groupIndex = k_smallGroup; - triangleShapeDef.filter.categoryBits = k_triangleCategory; - triangleShapeDef.filter.maskBits = k_triangleMask; - - b2BodyDef triangleBodyDef; - triangleBodyDef.type = b2_dynamicBody; - triangleBodyDef.position.Set(-5.0f, 2.0f); - - b2Body* body1 = m_world->CreateBody(&triangleBodyDef); - body1->CreateFixture(&triangleShapeDef); - - // Large triangle (recycle definitions) - vertices[0] *= 2.0f; - vertices[1] *= 2.0f; - vertices[2] *= 2.0f; - polygon.Set(vertices, 3); - triangleShapeDef.filter.groupIndex = k_largeGroup; - triangleBodyDef.position.Set(-5.0f, 6.0f); - triangleBodyDef.fixedRotation = true; // look at me! - - b2Body* body2 = m_world->CreateBody(&triangleBodyDef); - body2->CreateFixture(&triangleShapeDef); - - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-5.0f, 10.0f); - b2Body* body = m_world->CreateBody(&bd); - - b2PolygonShape p; - p.SetAsBox(0.5f, 1.0f); - body->CreateFixture(&p, 1.0f); - - b2PrismaticJointDef jd; - jd.bodyA = body2; - jd.bodyB = body; - jd.enableLimit = true; - jd.localAnchorA.Set(0.0f, 4.0f); - jd.localAnchorB.SetZero(); - jd.localAxisA.Set(0.0f, 1.0f); - jd.lowerTranslation = -1.0f; - jd.upperTranslation = 1.0f; - - m_world->CreateJoint(&jd); - } - - // Small box - polygon.SetAsBox(1.0f, 0.5f); - b2FixtureDef boxShapeDef; - boxShapeDef.shape = &polygon; - boxShapeDef.density = 1.0f; - boxShapeDef.restitution = 0.1f; - - boxShapeDef.filter.groupIndex = k_smallGroup; - boxShapeDef.filter.categoryBits = k_boxCategory; - boxShapeDef.filter.maskBits = k_boxMask; - - b2BodyDef boxBodyDef; - boxBodyDef.type = b2_dynamicBody; - boxBodyDef.position.Set(0.0f, 2.0f); - - b2Body* body3 = m_world->CreateBody(&boxBodyDef); - body3->CreateFixture(&boxShapeDef); - - // Large box (recycle definitions) - polygon.SetAsBox(2.0f, 1.0f); - boxShapeDef.filter.groupIndex = k_largeGroup; - boxBodyDef.position.Set(0.0f, 6.0f); - - b2Body* body4 = m_world->CreateBody(&boxBodyDef); - body4->CreateFixture(&boxShapeDef); - - // Small circle - b2CircleShape circle; - circle.m_radius = 1.0f; - - b2FixtureDef circleShapeDef; - circleShapeDef.shape = &circle; - circleShapeDef.density = 1.0f; - - circleShapeDef.filter.groupIndex = k_smallGroup; - circleShapeDef.filter.categoryBits = k_circleCategory; - circleShapeDef.filter.maskBits = k_circleMask; - - b2BodyDef circleBodyDef; - circleBodyDef.type = b2_dynamicBody; - circleBodyDef.position.Set(5.0f, 2.0f); - - b2Body* body5 = m_world->CreateBody(&circleBodyDef); - body5->CreateFixture(&circleShapeDef); - - // Large circle - circle.m_radius *= 2.0f; - circleShapeDef.filter.groupIndex = k_largeGroup; - circleBodyDef.position.Set(5.0f, 6.0f); - - b2Body* body6 = m_world->CreateBody(&circleBodyDef); - body6->CreateFixture(&circleShapeDef); - } - - static Test* Create() - { - return new CollisionFiltering; - } + CollisionFiltering() + { + // Ground body + { + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + + b2FixtureDef sd; + sd.shape = &shape; + sd.friction = 0.3f; + + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&sd); + } + + // Small triangle + b2Vec2 vertices[3]; + vertices[0].Set(-1.0f, 0.0f); + vertices[1].Set(1.0f, 0.0f); + vertices[2].Set(0.0f, 2.0f); + b2PolygonShape polygon; + polygon.Set(vertices, 3); + + b2FixtureDef triangleShapeDef; + triangleShapeDef.shape = &polygon; + triangleShapeDef.density = 1.0f; + + triangleShapeDef.filter.groupIndex = k_smallGroup; + triangleShapeDef.filter.categoryBits = k_triangleCategory; + triangleShapeDef.filter.maskBits = k_triangleMask; + + b2BodyDef triangleBodyDef; + triangleBodyDef.type = b2_dynamicBody; + triangleBodyDef.position.Set(-5.0f, 2.0f); + + b2Body* body1 = m_world->CreateBody(&triangleBodyDef); + body1->CreateFixture(&triangleShapeDef); + + // Large triangle (recycle definitions) + vertices[0] *= 2.0f; + vertices[1] *= 2.0f; + vertices[2] *= 2.0f; + polygon.Set(vertices, 3); + triangleShapeDef.filter.groupIndex = k_largeGroup; + triangleBodyDef.position.Set(-5.0f, 6.0f); + triangleBodyDef.fixedRotation = true; // look at me! + + b2Body* body2 = m_world->CreateBody(&triangleBodyDef); + body2->CreateFixture(&triangleShapeDef); + + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-5.0f, 10.0f); + b2Body* body = m_world->CreateBody(&bd); + + b2PolygonShape p; + p.SetAsBox(0.5f, 1.0f); + body->CreateFixture(&p, 1.0f); + + b2PrismaticJointDef jd; + jd.bodyA = body2; + jd.bodyB = body; + jd.enableLimit = true; + jd.localAnchorA.Set(0.0f, 4.0f); + jd.localAnchorB.SetZero(); + jd.localAxisA.Set(0.0f, 1.0f); + jd.lowerTranslation = -1.0f; + jd.upperTranslation = 1.0f; + + m_world->CreateJoint(&jd); + } + + // Small box + polygon.SetAsBox(1.0f, 0.5f); + b2FixtureDef boxShapeDef; + boxShapeDef.shape = &polygon; + boxShapeDef.density = 1.0f; + boxShapeDef.restitution = 0.1f; + + boxShapeDef.filter.groupIndex = k_smallGroup; + boxShapeDef.filter.categoryBits = k_boxCategory; + boxShapeDef.filter.maskBits = k_boxMask; + + b2BodyDef boxBodyDef; + boxBodyDef.type = b2_dynamicBody; + boxBodyDef.position.Set(0.0f, 2.0f); + + b2Body* body3 = m_world->CreateBody(&boxBodyDef); + body3->CreateFixture(&boxShapeDef); + + // Large box (recycle definitions) + polygon.SetAsBox(2.0f, 1.0f); + boxShapeDef.filter.groupIndex = k_largeGroup; + boxBodyDef.position.Set(0.0f, 6.0f); + + b2Body* body4 = m_world->CreateBody(&boxBodyDef); + body4->CreateFixture(&boxShapeDef); + + // Small circle + b2CircleShape circle; + circle.m_radius = 1.0f; + + b2FixtureDef circleShapeDef; + circleShapeDef.shape = &circle; + circleShapeDef.density = 1.0f; + + circleShapeDef.filter.groupIndex = k_smallGroup; + circleShapeDef.filter.categoryBits = k_circleCategory; + circleShapeDef.filter.maskBits = k_circleMask; + + b2BodyDef circleBodyDef; + circleBodyDef.type = b2_dynamicBody; + circleBodyDef.position.Set(5.0f, 2.0f); + + b2Body* body5 = m_world->CreateBody(&circleBodyDef); + body5->CreateFixture(&circleShapeDef); + + // Large circle + circle.m_radius *= 2.0f; + circleShapeDef.filter.groupIndex = k_largeGroup; + circleBodyDef.position.Set(5.0f, 6.0f); + + b2Body* body6 = m_world->CreateBody(&circleBodyDef); + body6->CreateFixture(&circleShapeDef); + } + + static Test* Create() { return new CollisionFiltering; } }; static int testIndex = RegisterTest("Examples", "Collision Filtering", CollisionFiltering::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/collision_processing.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/collision_processing.cpp index 1c684bdaecc1..f31db91a3b7d 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/collision_processing.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/collision_processing.cpp @@ -29,163 +29,161 @@ class CollisionProcessing : public Test { public: - CollisionProcessing() - { - // Ground body - { - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-50.0f, 0.0f), b2Vec2(50.0f, 0.0f)); - - b2FixtureDef sd; - sd.shape = &shape;; - - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&sd); - } - - float xLo = -5.0f, xHi = 5.0f; - float yLo = 2.0f, yHi = 35.0f; - - // Small triangle - b2Vec2 vertices[3]; - vertices[0].Set(-1.0f, 0.0f); - vertices[1].Set(1.0f, 0.0f); - vertices[2].Set(0.0f, 2.0f); - - b2PolygonShape polygon; - polygon.Set(vertices, 3); - - b2FixtureDef triangleShapeDef; - triangleShapeDef.shape = &polygon; - triangleShapeDef.density = 1.0f; - - b2BodyDef triangleBodyDef; - triangleBodyDef.type = b2_dynamicBody; - triangleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); - - b2Body* body1 = m_world->CreateBody(&triangleBodyDef); - body1->CreateFixture(&triangleShapeDef); - - // Large triangle (recycle definitions) - vertices[0] *= 2.0f; - vertices[1] *= 2.0f; - vertices[2] *= 2.0f; - polygon.Set(vertices, 3); - - triangleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); - - b2Body* body2 = m_world->CreateBody(&triangleBodyDef); - body2->CreateFixture(&triangleShapeDef); - - // Small box - polygon.SetAsBox(1.0f, 0.5f); - - b2FixtureDef boxShapeDef; - boxShapeDef.shape = &polygon; - boxShapeDef.density = 1.0f; - - b2BodyDef boxBodyDef; - boxBodyDef.type = b2_dynamicBody; - boxBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); - - b2Body* body3 = m_world->CreateBody(&boxBodyDef); - body3->CreateFixture(&boxShapeDef); - - // Large box (recycle definitions) - polygon.SetAsBox(2.0f, 1.0f); - boxBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); - - b2Body* body4 = m_world->CreateBody(&boxBodyDef); - body4->CreateFixture(&boxShapeDef); - - // Small circle - b2CircleShape circle; - circle.m_radius = 1.0f; - - b2FixtureDef circleShapeDef; - circleShapeDef.shape = &circle; - circleShapeDef.density = 1.0f; - - b2BodyDef circleBodyDef; - circleBodyDef.type = b2_dynamicBody; - circleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); - - b2Body* body5 = m_world->CreateBody(&circleBodyDef); - body5->CreateFixture(&circleShapeDef); - - // Large circle - circle.m_radius *= 2.0f; - circleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); - - b2Body* body6 = m_world->CreateBody(&circleBodyDef); - body6->CreateFixture(&circleShapeDef); - } - - void Step(Settings& settings) override - { - Test::Step(settings); - - // We are going to destroy some bodies according to contact - // points. We must buffer the bodies that should be destroyed - // because they may belong to multiple contact points. - const int32 k_maxNuke = 6; - b2Body* nuke[k_maxNuke]; - int32 nukeCount = 0; - - // Traverse the contact results. Destroy bodies that - // are touching heavier bodies. - for (int32 i = 0; i < m_pointCount; ++i) - { - ContactPoint* point = m_points + i; - - b2Body* body1 = point->fixtureA->GetBody(); - b2Body* body2 = point->fixtureB->GetBody(); - float mass1 = body1->GetMass(); - float mass2 = body2->GetMass(); - - if (mass1 > 0.0f && mass2 > 0.0f) - { - if (mass2 > mass1) - { - nuke[nukeCount++] = body1; - } - else - { - nuke[nukeCount++] = body2; - } - - if (nukeCount == k_maxNuke) - { - break; - } - } - } - - // Sort the nuke array to group duplicates. - std::sort(nuke, nuke + nukeCount); - - // Destroy the bodies, skipping duplicates. - int32 i = 0; - while (i < nukeCount) - { - b2Body* b = nuke[i++]; - while (i < nukeCount && nuke[i] == b) - { - ++i; - } - - if (b != m_bomb) - { - m_world->DestroyBody(b); - } - } - } - - static Test* Create() - { - return new CollisionProcessing; - } + CollisionProcessing() + { + // Ground body + { + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-50.0f, 0.0f), b2Vec2(50.0f, 0.0f)); + + b2FixtureDef sd; + sd.shape = &shape; + ; + + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&sd); + } + + float xLo = -5.0f, xHi = 5.0f; + float yLo = 2.0f, yHi = 35.0f; + + // Small triangle + b2Vec2 vertices[3]; + vertices[0].Set(-1.0f, 0.0f); + vertices[1].Set(1.0f, 0.0f); + vertices[2].Set(0.0f, 2.0f); + + b2PolygonShape polygon; + polygon.Set(vertices, 3); + + b2FixtureDef triangleShapeDef; + triangleShapeDef.shape = &polygon; + triangleShapeDef.density = 1.0f; + + b2BodyDef triangleBodyDef; + triangleBodyDef.type = b2_dynamicBody; + triangleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); + + b2Body* body1 = m_world->CreateBody(&triangleBodyDef); + body1->CreateFixture(&triangleShapeDef); + + // Large triangle (recycle definitions) + vertices[0] *= 2.0f; + vertices[1] *= 2.0f; + vertices[2] *= 2.0f; + polygon.Set(vertices, 3); + + triangleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); + + b2Body* body2 = m_world->CreateBody(&triangleBodyDef); + body2->CreateFixture(&triangleShapeDef); + + // Small box + polygon.SetAsBox(1.0f, 0.5f); + + b2FixtureDef boxShapeDef; + boxShapeDef.shape = &polygon; + boxShapeDef.density = 1.0f; + + b2BodyDef boxBodyDef; + boxBodyDef.type = b2_dynamicBody; + boxBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); + + b2Body* body3 = m_world->CreateBody(&boxBodyDef); + body3->CreateFixture(&boxShapeDef); + + // Large box (recycle definitions) + polygon.SetAsBox(2.0f, 1.0f); + boxBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); + + b2Body* body4 = m_world->CreateBody(&boxBodyDef); + body4->CreateFixture(&boxShapeDef); + + // Small circle + b2CircleShape circle; + circle.m_radius = 1.0f; + + b2FixtureDef circleShapeDef; + circleShapeDef.shape = &circle; + circleShapeDef.density = 1.0f; + + b2BodyDef circleBodyDef; + circleBodyDef.type = b2_dynamicBody; + circleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); + + b2Body* body5 = m_world->CreateBody(&circleBodyDef); + body5->CreateFixture(&circleShapeDef); + + // Large circle + circle.m_radius *= 2.0f; + circleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); + + b2Body* body6 = m_world->CreateBody(&circleBodyDef); + body6->CreateFixture(&circleShapeDef); + } + + void Step(Settings& settings) override + { + Test::Step(settings); + + // We are going to destroy some bodies according to contact + // points. We must buffer the bodies that should be destroyed + // because they may belong to multiple contact points. + const int32 k_maxNuke = 6; + b2Body* nuke[k_maxNuke]; + int32 nukeCount = 0; + + // Traverse the contact results. Destroy bodies that + // are touching heavier bodies. + for (int32 i = 0; i < m_pointCount; ++i) + { + ContactPoint* point = m_points + i; + + b2Body* body1 = point->fixtureA->GetBody(); + b2Body* body2 = point->fixtureB->GetBody(); + float mass1 = body1->GetMass(); + float mass2 = body2->GetMass(); + + if (mass1 > 0.0f && mass2 > 0.0f) + { + if (mass2 > mass1) + { + nuke[nukeCount++] = body1; + } + else + { + nuke[nukeCount++] = body2; + } + + if (nukeCount == k_maxNuke) + { + break; + } + } + } + + // Sort the nuke array to group duplicates. + std::sort(nuke, nuke + nukeCount); + + // Destroy the bodies, skipping duplicates. + int32 i = 0; + while (i < nukeCount) + { + b2Body* b = nuke[i++]; + while (i < nukeCount && nuke[i] == b) + { + ++i; + } + + if (b != m_bomb) + { + m_world->DestroyBody(b); + } + } + } + + static Test* Create() { return new CollisionProcessing; } }; static int testIndex = RegisterTest("Examples", "Collision Processing", CollisionProcessing::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/compound_shapes.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/compound_shapes.cpp index 657d8b27b9b5..34d29535110d 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/compound_shapes.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/compound_shapes.cpp @@ -26,202 +26,199 @@ class CompoundShapes : public Test { public: - CompoundShapes() - { - { - b2BodyDef bd; - bd.position.Set(0.0f, 0.0f); - b2Body* body = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(50.0f, 0.0f), b2Vec2(-50.0f, 0.0f)); - - body->CreateFixture(&shape, 0.0f); - } - - // Table 1 - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-15.0f, 1.0f); - m_table1 = m_world->CreateBody(&bd); - - b2PolygonShape top; - top.SetAsBox(3.0f, 0.5f, b2Vec2(0.0f, 3.5f), 0.0f); - - b2PolygonShape leftLeg; - leftLeg.SetAsBox(0.5f, 1.5f, b2Vec2(-2.5f, 1.5f), 0.0f); - - b2PolygonShape rightLeg; - rightLeg.SetAsBox(0.5f, 1.5f, b2Vec2(2.5f, 1.5f), 0.0f); - - m_table1->CreateFixture(&top, 2.0f); - m_table1->CreateFixture(&leftLeg, 2.0f); - m_table1->CreateFixture(&rightLeg, 2.0f); - } - - // Table 2 - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-5.0f, 1.0f); - m_table2 = m_world->CreateBody(&bd); - - b2PolygonShape top; - top.SetAsBox(3.0f, 0.5f, b2Vec2(0.0f, 3.5f), 0.0f); - - b2PolygonShape leftLeg; - leftLeg.SetAsBox(0.5f, 2.0f, b2Vec2(-2.5f, 2.0f), 0.0f); - - b2PolygonShape rightLeg; - rightLeg.SetAsBox(0.5f, 2.0f, b2Vec2(2.5f, 2.0f), 0.0f); - - m_table2->CreateFixture(&top, 2.0f); - m_table2->CreateFixture(&leftLeg, 2.0f); - m_table2->CreateFixture(&rightLeg, 2.0f); - } - - // Spaceship 1 - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(5.0f, 1.0f); - m_ship1 = m_world->CreateBody(&bd); - - b2Vec2 vertices[3]; - - b2PolygonShape left; - vertices[0].Set(-2.0f, 0.0f); - vertices[1].Set(0.0f, 4.0f / 3.0f); - vertices[2].Set(0.0f, 4.0f); - left.Set(vertices, 3); - - b2PolygonShape right; - vertices[0].Set(2.0f, 0.0f); - vertices[1].Set(0.0f, 4.0f / 3.0f); - vertices[2].Set(0.0f, 4.0f); - right.Set(vertices, 3); - - m_ship1->CreateFixture(&left, 2.0f); - m_ship1->CreateFixture(&right, 2.0f); - } - - // Spaceship 2 - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(15.0f, 1.0f); - m_ship2 = m_world->CreateBody(&bd); - - b2Vec2 vertices[3]; - - b2PolygonShape left; - vertices[0].Set(-2.0f, 0.0f); - vertices[1].Set(1.0f, 2.0f); - vertices[2].Set(0.0f, 4.0f); - left.Set(vertices, 3); - - b2PolygonShape right; - vertices[0].Set(2.0f, 0.0f); - vertices[1].Set(-1.0f, 2.0f); - vertices[2].Set(0.0f, 4.0f); - right.Set(vertices, 3); - - m_ship2->CreateFixture(&left, 2.0f); - m_ship2->CreateFixture(&right, 2.0f); - } - } - - void Spawn() - { - // Table 1 obstruction - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = m_table1->GetPosition(); - bd.angle = m_table1->GetAngle(); - - b2Body* body = m_world->CreateBody(&bd); - - b2PolygonShape box; - box.SetAsBox(4.0f, 0.1f, b2Vec2(0.0f, 3.0f), 0.0f); - - body->CreateFixture(&box, 2.0f); - } - - // Table 2 obstruction - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = m_table2->GetPosition(); - bd.angle = m_table2->GetAngle(); - - b2Body* body = m_world->CreateBody(&bd); - - b2PolygonShape box; - box.SetAsBox(4.0f, 0.1f, b2Vec2(0.0f, 3.0f), 0.0f); - - body->CreateFixture(&box, 2.0f); - } - - // Ship 1 obstruction - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = m_ship1->GetPosition(); - bd.angle = m_ship1->GetAngle(); - bd.gravityScale = 0.0f; - - b2Body* body = m_world->CreateBody(&bd); - - b2CircleShape circle; - circle.m_radius = 0.5f; - circle.m_p.Set(0.0f, 2.0f); - - body->CreateFixture(&circle, 2.0f); - } - - // Ship 2 obstruction - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = m_ship2->GetPosition(); - bd.angle = m_ship2->GetAngle(); - bd.gravityScale = 0.0f; - - b2Body* body = m_world->CreateBody(&bd); - - b2CircleShape circle; - circle.m_radius = 0.5f; - circle.m_p.Set(0.0f, 2.0f); - - body->CreateFixture(&circle, 2.0f); - } - } - - void UpdateUI() override - { - //ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); - ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); - ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_NoResize); - - if (ImGui::Button("Spawn")) - { - Spawn(); - } - - ImGui::End(); - } - - static Test* Create() - { - return new CompoundShapes; - } - - b2Body* m_table1; - b2Body* m_table2; - b2Body* m_ship1; - b2Body* m_ship2; + CompoundShapes() + { + { + b2BodyDef bd; + bd.position.Set(0.0f, 0.0f); + b2Body* body = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(50.0f, 0.0f), b2Vec2(-50.0f, 0.0f)); + + body->CreateFixture(&shape, 0.0f); + } + + // Table 1 + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-15.0f, 1.0f); + m_table1 = m_world->CreateBody(&bd); + + b2PolygonShape top; + top.SetAsBox(3.0f, 0.5f, b2Vec2(0.0f, 3.5f), 0.0f); + + b2PolygonShape leftLeg; + leftLeg.SetAsBox(0.5f, 1.5f, b2Vec2(-2.5f, 1.5f), 0.0f); + + b2PolygonShape rightLeg; + rightLeg.SetAsBox(0.5f, 1.5f, b2Vec2(2.5f, 1.5f), 0.0f); + + m_table1->CreateFixture(&top, 2.0f); + m_table1->CreateFixture(&leftLeg, 2.0f); + m_table1->CreateFixture(&rightLeg, 2.0f); + } + + // Table 2 + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-5.0f, 1.0f); + m_table2 = m_world->CreateBody(&bd); + + b2PolygonShape top; + top.SetAsBox(3.0f, 0.5f, b2Vec2(0.0f, 3.5f), 0.0f); + + b2PolygonShape leftLeg; + leftLeg.SetAsBox(0.5f, 2.0f, b2Vec2(-2.5f, 2.0f), 0.0f); + + b2PolygonShape rightLeg; + rightLeg.SetAsBox(0.5f, 2.0f, b2Vec2(2.5f, 2.0f), 0.0f); + + m_table2->CreateFixture(&top, 2.0f); + m_table2->CreateFixture(&leftLeg, 2.0f); + m_table2->CreateFixture(&rightLeg, 2.0f); + } + + // Spaceship 1 + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(5.0f, 1.0f); + m_ship1 = m_world->CreateBody(&bd); + + b2Vec2 vertices[3]; + + b2PolygonShape left; + vertices[0].Set(-2.0f, 0.0f); + vertices[1].Set(0.0f, 4.0f / 3.0f); + vertices[2].Set(0.0f, 4.0f); + left.Set(vertices, 3); + + b2PolygonShape right; + vertices[0].Set(2.0f, 0.0f); + vertices[1].Set(0.0f, 4.0f / 3.0f); + vertices[2].Set(0.0f, 4.0f); + right.Set(vertices, 3); + + m_ship1->CreateFixture(&left, 2.0f); + m_ship1->CreateFixture(&right, 2.0f); + } + + // Spaceship 2 + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(15.0f, 1.0f); + m_ship2 = m_world->CreateBody(&bd); + + b2Vec2 vertices[3]; + + b2PolygonShape left; + vertices[0].Set(-2.0f, 0.0f); + vertices[1].Set(1.0f, 2.0f); + vertices[2].Set(0.0f, 4.0f); + left.Set(vertices, 3); + + b2PolygonShape right; + vertices[0].Set(2.0f, 0.0f); + vertices[1].Set(-1.0f, 2.0f); + vertices[2].Set(0.0f, 4.0f); + right.Set(vertices, 3); + + m_ship2->CreateFixture(&left, 2.0f); + m_ship2->CreateFixture(&right, 2.0f); + } + } + + void Spawn() + { + // Table 1 obstruction + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = m_table1->GetPosition(); + bd.angle = m_table1->GetAngle(); + + b2Body* body = m_world->CreateBody(&bd); + + b2PolygonShape box; + box.SetAsBox(4.0f, 0.1f, b2Vec2(0.0f, 3.0f), 0.0f); + + body->CreateFixture(&box, 2.0f); + } + + // Table 2 obstruction + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = m_table2->GetPosition(); + bd.angle = m_table2->GetAngle(); + + b2Body* body = m_world->CreateBody(&bd); + + b2PolygonShape box; + box.SetAsBox(4.0f, 0.1f, b2Vec2(0.0f, 3.0f), 0.0f); + + body->CreateFixture(&box, 2.0f); + } + + // Ship 1 obstruction + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = m_ship1->GetPosition(); + bd.angle = m_ship1->GetAngle(); + bd.gravityScale = 0.0f; + + b2Body* body = m_world->CreateBody(&bd); + + b2CircleShape circle; + circle.m_radius = 0.5f; + circle.m_p.Set(0.0f, 2.0f); + + body->CreateFixture(&circle, 2.0f); + } + + // Ship 2 obstruction + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = m_ship2->GetPosition(); + bd.angle = m_ship2->GetAngle(); + bd.gravityScale = 0.0f; + + b2Body* body = m_world->CreateBody(&bd); + + b2CircleShape circle; + circle.m_radius = 0.5f; + circle.m_p.Set(0.0f, 2.0f); + + body->CreateFixture(&circle, 2.0f); + } + } + + void UpdateUI() override + { + // ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); + ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); + ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_NoResize); + + if (ImGui::Button("Spawn")) + { + Spawn(); + } + + ImGui::End(); + } + + static Test* Create() { return new CompoundShapes; } + + b2Body* m_table1; + b2Body* m_table2; + b2Body* m_ship1; + b2Body* m_ship2; }; static int testIndex = RegisterTest("Examples", "Compound Shapes", CompoundShapes::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/confined.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/confined.cpp index dc0e7cf12208..44e2f6201036 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/confined.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/confined.cpp @@ -25,146 +25,141 @@ class Confined : public Test { public: - - enum - { - e_columnCount = 0, - e_rowCount = 0 - }; - - Confined() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - - // Floor - shape.SetTwoSided(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - - // Left wall - shape.SetTwoSided(b2Vec2(-10.0f, 0.0f), b2Vec2(-10.0f, 20.0f)); - ground->CreateFixture(&shape, 0.0f); - - // Right wall - shape.SetTwoSided(b2Vec2(10.0f, 0.0f), b2Vec2(10.0f, 20.0f)); - ground->CreateFixture(&shape, 0.0f); - - // Roof - shape.SetTwoSided(b2Vec2(-10.0f, 20.0f), b2Vec2(10.0f, 20.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - float radius = 0.5f; - b2CircleShape shape; - shape.m_p.SetZero(); - shape.m_radius = radius; - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - fd.friction = 0.1f; - - for (int32 j = 0; j < e_columnCount; ++j) - { - for (int i = 0; i < e_rowCount; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-10.0f + (2.1f * j + 1.0f + 0.01f * i) * radius, (2.0f * i + 1.0f) * radius); - b2Body* body = m_world->CreateBody(&bd); - - body->CreateFixture(&fd); - } - } - - m_world->SetGravity(b2Vec2(0.0f, 0.0f)); - } - - void CreateCircle() - { - float radius = 2.0f; - b2CircleShape shape; - shape.m_p.SetZero(); - shape.m_radius = radius; - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - fd.friction = 0.0f; - - b2Vec2 p(RandomFloat(), 3.0f + RandomFloat()); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = p; - //bd.allowSleep = false; - b2Body* body = m_world->CreateBody(&bd); - - body->CreateFixture(&fd); - } - - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_C: - CreateCircle(); - break; - } - } - - void Step(Settings& settings) override - { - bool sleeping = true; - for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext()) - { - if (b->GetType() != b2_dynamicBody) - { - continue; - } - - if (b->IsAwake()) - { - sleeping = false; - } - } - - if (m_stepCount == 180) - { - m_stepCount += 0; - } - - //if (sleeping) - //{ - // CreateCircle(); - //} - - Test::Step(settings); - - for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext()) - { - if (b->GetType() != b2_dynamicBody) - { - continue; - } - - b2Vec2 p = b->GetPosition(); - if (p.x <= -10.0f || 10.0f <= p.x || p.y <= 0.0f || 20.0f <= p.y) - { - p.x += 0.0f; - } - } - - DrawString(5, m_textLine, "Press 'c' to create a circle."); - - } - - static Test* Create() - { - return new Confined; - } + enum + { + e_columnCount = 0, + e_rowCount = 0 + }; + + Confined() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + + // Floor + shape.SetTwoSided(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + + // Left wall + shape.SetTwoSided(b2Vec2(-10.0f, 0.0f), b2Vec2(-10.0f, 20.0f)); + ground->CreateFixture(&shape, 0.0f); + + // Right wall + shape.SetTwoSided(b2Vec2(10.0f, 0.0f), b2Vec2(10.0f, 20.0f)); + ground->CreateFixture(&shape, 0.0f); + + // Roof + shape.SetTwoSided(b2Vec2(-10.0f, 20.0f), b2Vec2(10.0f, 20.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + float radius = 0.5f; + b2CircleShape shape; + shape.m_p.SetZero(); + shape.m_radius = radius; + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + fd.friction = 0.1f; + + for (int32 j = 0; j < e_columnCount; ++j) + { + for (int i = 0; i < e_rowCount; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-10.0f + (2.1f * j + 1.0f + 0.01f * i) * radius, (2.0f * i + 1.0f) * radius); + b2Body* body = m_world->CreateBody(&bd); + + body->CreateFixture(&fd); + } + } + + m_world->SetGravity(b2Vec2(0.0f, 0.0f)); + } + + void CreateCircle() + { + float radius = 2.0f; + b2CircleShape shape; + shape.m_p.SetZero(); + shape.m_radius = radius; + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + fd.friction = 0.0f; + + b2Vec2 p(RandomFloat(), 3.0f + RandomFloat()); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = p; + // bd.allowSleep = false; + b2Body* body = m_world->CreateBody(&bd); + + body->CreateFixture(&fd); + } + + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_C: + CreateCircle(); + break; + } + } + + void Step(Settings& settings) override + { + bool sleeping = true; + for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext()) + { + if (b->GetType() != b2_dynamicBody) + { + continue; + } + + if (b->IsAwake()) + { + sleeping = false; + } + } + + if (m_stepCount == 180) + { + m_stepCount += 0; + } + + // if (sleeping) + //{ + // CreateCircle(); + // } + + Test::Step(settings); + + for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext()) + { + if (b->GetType() != b2_dynamicBody) + { + continue; + } + + b2Vec2 p = b->GetPosition(); + if (p.x <= -10.0f || 10.0f <= p.x || p.y <= 0.0f || 20.0f <= p.y) + { + p.x += 0.0f; + } + } + + DrawString(5, m_textLine, "Press 'c' to create a circle."); + } + + static Test* Create() { return new Confined; } }; static int testIndex = RegisterTest("Solver", "Confined", Confined::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/continuous_test.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/continuous_test.cpp index d8da4e99c1fb..80187d9daaad 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/continuous_test.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/continuous_test.cpp @@ -25,136 +25,138 @@ class ContinuousTest : public Test { public: + ContinuousTest() + { + { + b2BodyDef bd; + bd.position.Set(0.0f, 0.0f); + b2Body* body = m_world->CreateBody(&bd); - ContinuousTest() - { - { - b2BodyDef bd; - bd.position.Set(0.0f, 0.0f); - b2Body* body = m_world->CreateBody(&bd); + b2EdgeShape edge; - b2EdgeShape edge; + edge.SetTwoSided(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); + body->CreateFixture(&edge, 0.0f); - edge.SetTwoSided(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); - body->CreateFixture(&edge, 0.0f); - - b2PolygonShape shape; - shape.SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0.0f); - body->CreateFixture(&shape, 0.0f); - } + b2PolygonShape shape; + shape.SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0.0f); + body->CreateFixture(&shape, 0.0f); + } #if 1 - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 20.0f); - //bd.angle = 0.1f; - - b2PolygonShape shape; - shape.SetAsBox(2.0f, 0.1f); - - m_body = m_world->CreateBody(&bd); - m_body->CreateFixture(&shape, 1.0f); - - m_angularVelocity = RandomFloat(-50.0f, 50.0f); - //m_angularVelocity = 46.661274f; - m_body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); - m_body->SetAngularVelocity(m_angularVelocity); - } + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 20.0f); + // bd.angle = 0.1f; + + b2PolygonShape shape; + shape.SetAsBox(2.0f, 0.1f); + + m_body = m_world->CreateBody(&bd); + m_body->CreateFixture(&shape, 1.0f); + + m_angularVelocity = RandomFloat(-50.0f, 50.0f); + // m_angularVelocity = 46.661274f; + m_body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); + m_body->SetAngularVelocity(m_angularVelocity); + } #else - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 2.0f); - b2Body* body = m_world->CreateBody(&bd); - - b2CircleShape shape; - shape.m_p.SetZero(); - shape.m_radius = 0.5f; - body->CreateFixture(&shape, 1.0f); - - bd.bullet = true; - bd.position.Set(0.0f, 10.0f); - body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 1.0f); - body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); - } + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 2.0f); + b2Body* body = m_world->CreateBody(&bd); + + b2CircleShape shape; + shape.m_p.SetZero(); + shape.m_radius = 0.5f; + body->CreateFixture(&shape, 1.0f); + + bd.bullet = true; + bd.position.Set(0.0f, 10.0f); + body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 1.0f); + body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); + } #endif - extern B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; - extern B2_API int32 b2_toiCalls, b2_toiIters; - extern B2_API int32 b2_toiRootIters, b2_toiMaxRootIters; - extern B2_API float b2_toiTime, b2_toiMaxTime; - - b2_gjkCalls = 0; b2_gjkIters = 0; b2_gjkMaxIters = 0; - b2_toiCalls = 0; b2_toiIters = 0; - b2_toiRootIters = 0; b2_toiMaxRootIters = 0; - b2_toiTime = 0.0f; b2_toiMaxTime = 0.0f; - } - - void Launch() - { - extern B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; - extern B2_API int32 b2_toiCalls, b2_toiIters; - extern B2_API int32 b2_toiRootIters, b2_toiMaxRootIters; - extern B2_API float b2_toiTime, b2_toiMaxTime; - - b2_gjkCalls = 0; b2_gjkIters = 0; b2_gjkMaxIters = 0; - b2_toiCalls = 0; b2_toiIters = 0; - b2_toiRootIters = 0; b2_toiMaxRootIters = 0; - b2_toiTime = 0.0f; b2_toiMaxTime = 0.0f; - - m_body->SetTransform(b2Vec2(0.0f, 20.0f), 0.0f); - m_angularVelocity = RandomFloat(-50.0f, 50.0f); - m_body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); - m_body->SetAngularVelocity(m_angularVelocity); - } - - void Step(Settings& settings) override - { - Test::Step(settings); - - extern B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; - - if (b2_gjkCalls > 0) - { - DrawString(5, m_textLine, "gjk calls = %d, ave gjk iters = %3.1f, max gjk iters = %d", - b2_gjkCalls, b2_gjkIters / float(b2_gjkCalls), b2_gjkMaxIters); - - } - - extern B2_API int32 b2_toiCalls, b2_toiIters; - extern B2_API int32 b2_toiRootIters, b2_toiMaxRootIters; - extern B2_API float b2_toiTime, b2_toiMaxTime; - - if (b2_toiCalls > 0) - { - DrawString(5, m_textLine, "toi calls = %d, ave [max] toi iters = %3.1f [%d]", - b2_toiCalls, b2_toiIters / float(b2_toiCalls), b2_toiMaxRootIters); - - - DrawString(5, m_textLine, "ave [max] toi root iters = %3.1f [%d]", - b2_toiRootIters / float(b2_toiCalls), b2_toiMaxRootIters); - - - DrawString(5, m_textLine, "ave [max] toi time = %.1f [%.1f] (microseconds)", - 1000.0f * b2_toiTime / float(b2_toiCalls), 1000.0f * b2_toiMaxTime); - - } - - if (m_stepCount % 60 == 0) - { - Launch(); - } - } - - static Test* Create() - { - return new ContinuousTest; - } - - b2Body* m_body; - float m_angularVelocity; + extern B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; + extern B2_API int32 b2_toiCalls, b2_toiIters; + extern B2_API int32 b2_toiRootIters, b2_toiMaxRootIters; + extern B2_API float b2_toiTime, b2_toiMaxTime; + + b2_gjkCalls = 0; + b2_gjkIters = 0; + b2_gjkMaxIters = 0; + b2_toiCalls = 0; + b2_toiIters = 0; + b2_toiRootIters = 0; + b2_toiMaxRootIters = 0; + b2_toiTime = 0.0f; + b2_toiMaxTime = 0.0f; + } + + void Launch() + { + extern B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; + extern B2_API int32 b2_toiCalls, b2_toiIters; + extern B2_API int32 b2_toiRootIters, b2_toiMaxRootIters; + extern B2_API float b2_toiTime, b2_toiMaxTime; + + b2_gjkCalls = 0; + b2_gjkIters = 0; + b2_gjkMaxIters = 0; + b2_toiCalls = 0; + b2_toiIters = 0; + b2_toiRootIters = 0; + b2_toiMaxRootIters = 0; + b2_toiTime = 0.0f; + b2_toiMaxTime = 0.0f; + + m_body->SetTransform(b2Vec2(0.0f, 20.0f), 0.0f); + m_angularVelocity = RandomFloat(-50.0f, 50.0f); + m_body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); + m_body->SetAngularVelocity(m_angularVelocity); + } + + void Step(Settings& settings) override + { + Test::Step(settings); + + extern B2_API int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; + + if (b2_gjkCalls > 0) + { + DrawString(5, m_textLine, "gjk calls = %d, ave gjk iters = %3.1f, max gjk iters = %d", b2_gjkCalls, + b2_gjkIters / float(b2_gjkCalls), b2_gjkMaxIters); + } + + extern B2_API int32 b2_toiCalls, b2_toiIters; + extern B2_API int32 b2_toiRootIters, b2_toiMaxRootIters; + extern B2_API float b2_toiTime, b2_toiMaxTime; + + if (b2_toiCalls > 0) + { + DrawString(5, m_textLine, "toi calls = %d, ave [max] toi iters = %3.1f [%d]", b2_toiCalls, + b2_toiIters / float(b2_toiCalls), b2_toiMaxRootIters); + + DrawString(5, m_textLine, "ave [max] toi root iters = %3.1f [%d]", b2_toiRootIters / float(b2_toiCalls), + b2_toiMaxRootIters); + + DrawString(5, m_textLine, "ave [max] toi time = %.1f [%.1f] (microseconds)", + 1000.0f * b2_toiTime / float(b2_toiCalls), 1000.0f * b2_toiMaxTime); + } + + if (m_stepCount % 60 == 0) + { + Launch(); + } + } + + static Test* Create() { return new ContinuousTest; } + + b2Body* m_body; + float m_angularVelocity; }; static int testIndex = RegisterTest("Continuous", "Continuous Test", ContinuousTest::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/convex_hull.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/convex_hull.cpp index ac047b235eea..44f4da8906e5 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/convex_hull.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/convex_hull.cpp @@ -25,88 +25,84 @@ class ConvexHull : public Test { public: - enum - { - e_count = b2_maxPolygonVertices - }; - - ConvexHull() - { - Generate(); - m_auto = false; - } - - void Generate() - { - b2Vec2 lowerBound(-8.0f, -8.0f); - b2Vec2 upperBound(8.0f, 8.0f); - - for (int32 i = 0; i < e_count; ++i) - { - float x = 10.0f * RandomFloat(); - float y = 10.0f * RandomFloat(); - - // Clamp onto a square to help create collinearities. - // This will stress the convex hull algorithm. - b2Vec2 v(x, y); - v = b2Clamp(v, lowerBound, upperBound); - m_points[i] = v; - } - - m_count = e_count; - } - - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_A: - m_auto = !m_auto; - break; - - case GLFW_KEY_G: - Generate(); - break; - } - } - - void Step(Settings& settings) override - { - Test::Step(settings); - - b2PolygonShape shape; - shape.Set(m_points, m_count); - - DrawString(5, m_textLine, "Press g to generate a new random convex hull"); - - - g_debugDraw.DrawPolygon(shape.m_vertices, shape.m_count, b2Color(0.9f, 0.9f, 0.9f)); - - for (int32 i = 0; i < m_count; ++i) - { - g_debugDraw.DrawPoint(m_points[i], 3.0f, b2Color(0.3f, 0.9f, 0.3f)); - DrawString(m_points[i] + b2Vec2(0.05f, 0.05f), "%d", i); - } - - if (shape.Validate() == false) - { - m_textLine += 0; - } - - if (m_auto) - { - Generate(); - } - } - - static Test* Create() - { - return new ConvexHull; - } - - b2Vec2 m_points[b2_maxPolygonVertices]; - int32 m_count; - bool m_auto; + enum + { + e_count = b2_maxPolygonVertices + }; + + ConvexHull() + { + Generate(); + m_auto = false; + } + + void Generate() + { + b2Vec2 lowerBound(-8.0f, -8.0f); + b2Vec2 upperBound(8.0f, 8.0f); + + for (int32 i = 0; i < e_count; ++i) + { + float x = 10.0f * RandomFloat(); + float y = 10.0f * RandomFloat(); + + // Clamp onto a square to help create collinearities. + // This will stress the convex hull algorithm. + b2Vec2 v(x, y); + v = b2Clamp(v, lowerBound, upperBound); + m_points[i] = v; + } + + m_count = e_count; + } + + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_A: + m_auto = !m_auto; + break; + + case GLFW_KEY_G: + Generate(); + break; + } + } + + void Step(Settings& settings) override + { + Test::Step(settings); + + b2PolygonShape shape; + shape.Set(m_points, m_count); + + DrawString(5, m_textLine, "Press g to generate a new random convex hull"); + + g_debugDraw.DrawPolygon(shape.m_vertices, shape.m_count, b2Color(0.9f, 0.9f, 0.9f)); + + for (int32 i = 0; i < m_count; ++i) + { + g_debugDraw.DrawPoint(m_points[i], 3.0f, b2Color(0.3f, 0.9f, 0.3f)); + DrawString(m_points[i] + b2Vec2(0.05f, 0.05f), "%d", i); + } + + if (shape.Validate() == false) + { + m_textLine += 0; + } + + if (m_auto) + { + Generate(); + } + } + + static Test* Create() { return new ConvexHull; } + + b2Vec2 m_points[b2_maxPolygonVertices]; + int32 m_count; + bool m_auto; }; static int testIndex = RegisterTest("Geometry", "Convex Hull", ConvexHull::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/conveyor_belt.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/conveyor_belt.cpp index 41d4f2c61c5a..967ff5826369 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/conveyor_belt.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/conveyor_belt.cpp @@ -25,77 +25,70 @@ class ConveyorBelt : public Test { public: - - ConveyorBelt() - { - // Ground - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - // Platform - { - b2BodyDef bd; - bd.position.Set(-5.0f, 5.0f); - b2Body* body = m_world->CreateBody(&bd); - - b2PolygonShape shape; - shape.SetAsBox(10.0f, 0.5f); - - b2FixtureDef fd; - fd.shape = &shape; - fd.friction = 0.8f; - m_platform = body->CreateFixture(&fd); - } - - // Boxes - for (int32 i = 0; i < 5; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-10.0f + 2.0f * i, 7.0f); - b2Body* body = m_world->CreateBody(&bd); - - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.5f); - body->CreateFixture(&shape, 20.0f); - } - } - - void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override - { - Test::PreSolve(contact, oldManifold); - - b2Fixture* fixtureA = contact->GetFixtureA(); - b2Fixture* fixtureB = contact->GetFixtureB(); - - if (fixtureA == m_platform) - { - contact->SetTangentSpeed(5.0f); - } - - if (fixtureB == m_platform) - { - contact->SetTangentSpeed(-5.0f); - } - } - - void Step(Settings& settings) override - { - Test::Step(settings); - } - - static Test* Create() - { - return new ConveyorBelt; - } - - b2Fixture* m_platform; + ConveyorBelt() + { + // Ground + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + // Platform + { + b2BodyDef bd; + bd.position.Set(-5.0f, 5.0f); + b2Body* body = m_world->CreateBody(&bd); + + b2PolygonShape shape; + shape.SetAsBox(10.0f, 0.5f); + + b2FixtureDef fd; + fd.shape = &shape; + fd.friction = 0.8f; + m_platform = body->CreateFixture(&fd); + } + + // Boxes + for (int32 i = 0; i < 5; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-10.0f + 2.0f * i, 7.0f); + b2Body* body = m_world->CreateBody(&bd); + + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); + body->CreateFixture(&shape, 20.0f); + } + } + + void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override + { + Test::PreSolve(contact, oldManifold); + + b2Fixture* fixtureA = contact->GetFixtureA(); + b2Fixture* fixtureB = contact->GetFixtureB(); + + if (fixtureA == m_platform) + { + contact->SetTangentSpeed(5.0f); + } + + if (fixtureB == m_platform) + { + contact->SetTangentSpeed(-5.0f); + } + } + + void Step(Settings& settings) override { Test::Step(settings); } + + static Test* Create() { return new ConveyorBelt; } + + b2Fixture* m_platform; }; static int testIndex = RegisterTest("Examples", "Conveyor Belt", ConveyorBelt::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/distance_joint.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/distance_joint.cpp index 455a600bf216..087b6fcad1d7 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/distance_joint.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/distance_joint.cpp @@ -27,97 +27,94 @@ class DistanceJoint : public Test { public: - DistanceJoint() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.angularDamping = 0.1f; - - bd.position.Set(0.0f, 5.0f); - b2Body* body = m_world->CreateBody(&bd); - - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.5f); - body->CreateFixture(&shape, 5.0f); - - m_hertz = 1.0f; - m_dampingRatio = 0.7f; - - b2DistanceJointDef jd; - jd.Initialize(ground, body, b2Vec2(0.0f, 15.0f), bd.position); - jd.collideConnected = true; - m_length = jd.length; - m_minLength = m_length; - m_maxLength = m_length; - b2LinearStiffness(jd.stiffness, jd.damping, m_hertz, m_dampingRatio, jd.bodyA, jd.bodyB); - m_joint = (b2DistanceJoint*)m_world->CreateJoint(&jd); - } - } - - void UpdateUI() override - { - //ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); - ImGui::SetNextWindowSize(ImVec2(260.0f, 150.0f)); - ImGui::Begin("Joint Controls", nullptr, ImGuiWindowFlags_NoResize); - - if (ImGui::SliderFloat("Length", &m_length, 0.0f, 20.0f, "%.0f")) - { - m_length = m_joint->SetLength(m_length); - } - - if (ImGui::SliderFloat("Min Length", &m_minLength, 0.0f, 20.0f, "%.0f")) - { - m_minLength = m_joint->SetMinLength(m_minLength); - } - - if (ImGui::SliderFloat("Max Length", &m_maxLength, 0.0f, 20.0f, "%.0f")) - { - m_maxLength = m_joint->SetMaxLength(m_maxLength); - } - - if (ImGui::SliderFloat("Hertz", &m_hertz, 0.0f, 10.0f, "%.1f")) - { - float stiffness; - float damping; - b2LinearStiffness(stiffness, damping, m_hertz, m_dampingRatio, m_joint->GetBodyA(), m_joint->GetBodyB()); - m_joint->SetStiffness(stiffness); - m_joint->SetDamping(damping); - } - - if (ImGui::SliderFloat("Damping Ratio", &m_dampingRatio, 0.0f, 2.0f, "%.1f")) - { - float stiffness; - float damping; - b2LinearStiffness(stiffness, damping, m_hertz, m_dampingRatio, m_joint->GetBodyA(), m_joint->GetBodyB()); - m_joint->SetStiffness(stiffness); - m_joint->SetDamping(damping); - } - - ImGui::End(); - } - - static Test* Create() - { - return new DistanceJoint; - } - - b2DistanceJoint* m_joint; - float m_length; - float m_minLength; - float m_maxLength; - float m_hertz; - float m_dampingRatio; + DistanceJoint() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.angularDamping = 0.1f; + + bd.position.Set(0.0f, 5.0f); + b2Body* body = m_world->CreateBody(&bd); + + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); + body->CreateFixture(&shape, 5.0f); + + m_hertz = 1.0f; + m_dampingRatio = 0.7f; + + b2DistanceJointDef jd; + jd.Initialize(ground, body, b2Vec2(0.0f, 15.0f), bd.position); + jd.collideConnected = true; + m_length = jd.length; + m_minLength = m_length; + m_maxLength = m_length; + b2LinearStiffness(jd.stiffness, jd.damping, m_hertz, m_dampingRatio, jd.bodyA, jd.bodyB); + m_joint = (b2DistanceJoint*)m_world->CreateJoint(&jd); + } + } + + void UpdateUI() override + { + // ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); + ImGui::SetNextWindowSize(ImVec2(260.0f, 150.0f)); + ImGui::Begin("Joint Controls", nullptr, ImGuiWindowFlags_NoResize); + + if (ImGui::SliderFloat("Length", &m_length, 0.0f, 20.0f, "%.0f")) + { + m_length = m_joint->SetLength(m_length); + } + + if (ImGui::SliderFloat("Min Length", &m_minLength, 0.0f, 20.0f, "%.0f")) + { + m_minLength = m_joint->SetMinLength(m_minLength); + } + + if (ImGui::SliderFloat("Max Length", &m_maxLength, 0.0f, 20.0f, "%.0f")) + { + m_maxLength = m_joint->SetMaxLength(m_maxLength); + } + + if (ImGui::SliderFloat("Hertz", &m_hertz, 0.0f, 10.0f, "%.1f")) + { + float stiffness; + float damping; + b2LinearStiffness(stiffness, damping, m_hertz, m_dampingRatio, m_joint->GetBodyA(), m_joint->GetBodyB()); + m_joint->SetStiffness(stiffness); + m_joint->SetDamping(damping); + } + + if (ImGui::SliderFloat("Damping Ratio", &m_dampingRatio, 0.0f, 2.0f, "%.1f")) + { + float stiffness; + float damping; + b2LinearStiffness(stiffness, damping, m_hertz, m_dampingRatio, m_joint->GetBodyA(), m_joint->GetBodyB()); + m_joint->SetStiffness(stiffness); + m_joint->SetDamping(damping); + } + + ImGui::End(); + } + + static Test* Create() { return new DistanceJoint; } + + b2DistanceJoint* m_joint; + float m_length; + float m_minLength; + float m_maxLength; + float m_hertz; + float m_dampingRatio; }; static int testIndex = RegisterTest("Joints", "Distance Joint", DistanceJoint::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/distance_test.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/distance_test.cpp index 0f970de658af..6372330426b0 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/distance_test.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/distance_test.cpp @@ -26,114 +26,109 @@ class DistanceTest : public Test { public: - DistanceTest() - { - { - m_transformA.SetIdentity(); - m_transformA.p.Set(0.0f, -0.2f); - m_polygonA.SetAsBox(10.0f, 0.2f); - } - - { - m_positionB.Set(12.017401f, 0.13678508f); - m_angleB = -0.0109265f; - m_transformB.Set(m_positionB, m_angleB); - - m_polygonB.SetAsBox(2.0f, 0.1f); - } - } - - static Test* Create() - { - return new DistanceTest; - } - - void Step(Settings& settings) override - { - Test::Step(settings); - - b2DistanceInput input; - input.proxyA.Set(&m_polygonA, 0); - input.proxyB.Set(&m_polygonB, 0); - input.transformA = m_transformA; - input.transformB = m_transformB; - input.useRadii = true; - b2SimplexCache cache; - cache.count = 0; - b2DistanceOutput output; - b2Distance(&output, &cache, &input); - - DrawString(5, m_textLine, "distance = %g", output.distance); - - - DrawString(5, m_textLine, "iterations = %d", output.iterations); - - - { - b2Color color(0.9f, 0.9f, 0.9f); - b2Vec2 v[b2_maxPolygonVertices]; - for (int32 i = 0; i < m_polygonA.m_count; ++i) - { - v[i] = b2Mul(m_transformA, m_polygonA.m_vertices[i]); - } - g_debugDraw.DrawPolygon(v, m_polygonA.m_count, color); - - for (int32 i = 0; i < m_polygonB.m_count; ++i) - { - v[i] = b2Mul(m_transformB, m_polygonB.m_vertices[i]); - } - g_debugDraw.DrawPolygon(v, m_polygonB.m_count, color); - } - - b2Vec2 x1 = output.pointA; - b2Vec2 x2 = output.pointB; - - b2Color c1(1.0f, 0.0f, 0.0f); - g_debugDraw.DrawPoint(x1, 4.0f, c1); - - b2Color c2(1.0f, 1.0f, 0.0f); - g_debugDraw.DrawPoint(x2, 4.0f, c2); - } - - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_A: - m_positionB.x -= 0.1f; - break; - - case GLFW_KEY_D: - m_positionB.x += 0.1f; - break; - - case GLFW_KEY_S: - m_positionB.y -= 0.1f; - break; - - case GLFW_KEY_W: - m_positionB.y += 0.1f; - break; - - case GLFW_KEY_Q: - m_angleB += 0.1f * b2_pi; - break; - - case GLFW_KEY_E: - m_angleB -= 0.1f * b2_pi; - break; - } - - m_transformB.Set(m_positionB, m_angleB); - } - - b2Vec2 m_positionB; - float m_angleB; - - b2Transform m_transformA; - b2Transform m_transformB; - b2PolygonShape m_polygonA; - b2PolygonShape m_polygonB; + DistanceTest() + { + { + m_transformA.SetIdentity(); + m_transformA.p.Set(0.0f, -0.2f); + m_polygonA.SetAsBox(10.0f, 0.2f); + } + + { + m_positionB.Set(12.017401f, 0.13678508f); + m_angleB = -0.0109265f; + m_transformB.Set(m_positionB, m_angleB); + + m_polygonB.SetAsBox(2.0f, 0.1f); + } + } + + static Test* Create() { return new DistanceTest; } + + void Step(Settings& settings) override + { + Test::Step(settings); + + b2DistanceInput input; + input.proxyA.Set(&m_polygonA, 0); + input.proxyB.Set(&m_polygonB, 0); + input.transformA = m_transformA; + input.transformB = m_transformB; + input.useRadii = true; + b2SimplexCache cache; + cache.count = 0; + b2DistanceOutput output; + b2Distance(&output, &cache, &input); + + DrawString(5, m_textLine, "distance = %g", output.distance); + + DrawString(5, m_textLine, "iterations = %d", output.iterations); + + { + b2Color color(0.9f, 0.9f, 0.9f); + b2Vec2 v[b2_maxPolygonVertices]; + for (int32 i = 0; i < m_polygonA.m_count; ++i) + { + v[i] = b2Mul(m_transformA, m_polygonA.m_vertices[i]); + } + g_debugDraw.DrawPolygon(v, m_polygonA.m_count, color); + + for (int32 i = 0; i < m_polygonB.m_count; ++i) + { + v[i] = b2Mul(m_transformB, m_polygonB.m_vertices[i]); + } + g_debugDraw.DrawPolygon(v, m_polygonB.m_count, color); + } + + b2Vec2 x1 = output.pointA; + b2Vec2 x2 = output.pointB; + + b2Color c1(1.0f, 0.0f, 0.0f); + g_debugDraw.DrawPoint(x1, 4.0f, c1); + + b2Color c2(1.0f, 1.0f, 0.0f); + g_debugDraw.DrawPoint(x2, 4.0f, c2); + } + + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_A: + m_positionB.x -= 0.1f; + break; + + case GLFW_KEY_D: + m_positionB.x += 0.1f; + break; + + case GLFW_KEY_S: + m_positionB.y -= 0.1f; + break; + + case GLFW_KEY_W: + m_positionB.y += 0.1f; + break; + + case GLFW_KEY_Q: + m_angleB += 0.1f * b2_pi; + break; + + case GLFW_KEY_E: + m_angleB -= 0.1f * b2_pi; + break; + } + + m_transformB.Set(m_positionB, m_angleB); + } + + b2Vec2 m_positionB; + float m_angleB; + + b2Transform m_transformA; + b2Transform m_transformB; + b2PolygonShape m_polygonA; + b2PolygonShape m_polygonB; }; static int testIndex = RegisterTest("Geometry", "Distance Test", DistanceTest::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/dominos.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/dominos.cpp index 739876bf55fd..f64a141bd407 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/dominos.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/dominos.cpp @@ -25,196 +25,192 @@ class Dominos : public Test { public: - - Dominos() - { - b2Body* b1; - { - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - - b2BodyDef bd; - b1 = m_world->CreateBody(&bd); - b1->CreateFixture(&shape, 0.0f); - } - - { - b2PolygonShape shape; - shape.SetAsBox(6.0f, 0.25f); - - b2BodyDef bd; - bd.position.Set(-1.5f, 10.0f); - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } - - { - b2PolygonShape shape; - shape.SetAsBox(0.1f, 1.0f); - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - fd.friction = 0.1f; - - for (int i = 0; i < 10; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-6.0f + 1.0f * i, 11.25f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - } - } - - { - b2PolygonShape shape; - shape.SetAsBox(7.0f, 0.25f, b2Vec2_zero, 0.3f); - - b2BodyDef bd; - bd.position.Set(1.0f, 6.0f); - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } - - b2Body* b2; - { - b2PolygonShape shape; - shape.SetAsBox(0.25f, 1.5f); - - b2BodyDef bd; - bd.position.Set(-7.0f, 4.0f); - b2 = m_world->CreateBody(&bd); - b2->CreateFixture(&shape, 0.0f); - } - - b2Body* b3; - { - b2PolygonShape shape; - shape.SetAsBox(6.0f, 0.125f); - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-0.9f, 1.0f); - bd.angle = -0.15f; - - b3 = m_world->CreateBody(&bd); - b3->CreateFixture(&shape, 10.0f); - } - - b2RevoluteJointDef jd; - b2Vec2 anchor; - - anchor.Set(-2.0f, 1.0f); - jd.Initialize(b1, b3, anchor); - jd.collideConnected = true; - m_world->CreateJoint(&jd); - - b2Body* b4; - { - b2PolygonShape shape; - shape.SetAsBox(0.25f, 0.25f); - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-10.0f, 15.0f); - b4 = m_world->CreateBody(&bd); - b4->CreateFixture(&shape, 10.0f); - } - - anchor.Set(-7.0f, 15.0f); - jd.Initialize(b2, b4, anchor); - m_world->CreateJoint(&jd); - - b2Body* b5; - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(6.5f, 3.0f); - b5 = m_world->CreateBody(&bd); - - b2PolygonShape shape; - b2FixtureDef fd; - - fd.shape = &shape; - fd.density = 10.0f; - fd.friction = 0.1f; - - shape.SetAsBox(1.0f, 0.1f, b2Vec2(0.0f, -0.9f), 0.0f); - b5->CreateFixture(&fd); - - shape.SetAsBox(0.1f, 1.0f, b2Vec2(-0.9f, 0.0f), 0.0f); - b5->CreateFixture(&fd); - - shape.SetAsBox(0.1f, 1.0f, b2Vec2(0.9f, 0.0f), 0.0f); - b5->CreateFixture(&fd); - } - - anchor.Set(6.0f, 2.0f); - jd.Initialize(b1, b5, anchor); - m_world->CreateJoint(&jd); - - b2Body* b6; - { - b2PolygonShape shape; - shape.SetAsBox(1.0f, 0.1f); - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(6.5f, 4.1f); - b6 = m_world->CreateBody(&bd); - b6->CreateFixture(&shape, 30.0f); - } - - anchor.Set(7.5f, 4.0f); - jd.Initialize(b5, b6, anchor); - m_world->CreateJoint(&jd); - - b2Body* b7; - { - b2PolygonShape shape; - shape.SetAsBox(0.1f, 1.0f); - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(7.4f, 1.0f); - - b7 = m_world->CreateBody(&bd); - b7->CreateFixture(&shape, 10.0f); - } - - b2DistanceJointDef djd; - djd.bodyA = b3; - djd.bodyB = b7; - djd.localAnchorA.Set(6.0f, 0.0f); - djd.localAnchorB.Set(0.0f, -1.0f); - b2Vec2 d = djd.bodyB->GetWorldPoint(djd.localAnchorB) - djd.bodyA->GetWorldPoint(djd.localAnchorA); - djd.length = d.Length(); - - b2LinearStiffness(djd.stiffness, djd.damping, 1.0f, 1.0f, djd.bodyA, djd.bodyB); - m_world->CreateJoint(&djd); - - { - float radius = 0.2f; - - b2CircleShape shape; - shape.m_radius = radius; - - for (int32 i = 0; i < 4; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(5.9f + 2.0f * radius * i, 2.4f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 10.0f); - } - } - } - - static Test* Create() - { - return new Dominos; - } + Dominos() + { + b2Body* b1; + { + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + + b2BodyDef bd; + b1 = m_world->CreateBody(&bd); + b1->CreateFixture(&shape, 0.0f); + } + + { + b2PolygonShape shape; + shape.SetAsBox(6.0f, 0.25f); + + b2BodyDef bd; + bd.position.Set(-1.5f, 10.0f); + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } + + { + b2PolygonShape shape; + shape.SetAsBox(0.1f, 1.0f); + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + fd.friction = 0.1f; + + for (int i = 0; i < 10; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-6.0f + 1.0f * i, 11.25f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + } + } + + { + b2PolygonShape shape; + shape.SetAsBox(7.0f, 0.25f, b2Vec2_zero, 0.3f); + + b2BodyDef bd; + bd.position.Set(1.0f, 6.0f); + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } + + b2Body* b2; + { + b2PolygonShape shape; + shape.SetAsBox(0.25f, 1.5f); + + b2BodyDef bd; + bd.position.Set(-7.0f, 4.0f); + b2 = m_world->CreateBody(&bd); + b2->CreateFixture(&shape, 0.0f); + } + + b2Body* b3; + { + b2PolygonShape shape; + shape.SetAsBox(6.0f, 0.125f); + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-0.9f, 1.0f); + bd.angle = -0.15f; + + b3 = m_world->CreateBody(&bd); + b3->CreateFixture(&shape, 10.0f); + } + + b2RevoluteJointDef jd; + b2Vec2 anchor; + + anchor.Set(-2.0f, 1.0f); + jd.Initialize(b1, b3, anchor); + jd.collideConnected = true; + m_world->CreateJoint(&jd); + + b2Body* b4; + { + b2PolygonShape shape; + shape.SetAsBox(0.25f, 0.25f); + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-10.0f, 15.0f); + b4 = m_world->CreateBody(&bd); + b4->CreateFixture(&shape, 10.0f); + } + + anchor.Set(-7.0f, 15.0f); + jd.Initialize(b2, b4, anchor); + m_world->CreateJoint(&jd); + + b2Body* b5; + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(6.5f, 3.0f); + b5 = m_world->CreateBody(&bd); + + b2PolygonShape shape; + b2FixtureDef fd; + + fd.shape = &shape; + fd.density = 10.0f; + fd.friction = 0.1f; + + shape.SetAsBox(1.0f, 0.1f, b2Vec2(0.0f, -0.9f), 0.0f); + b5->CreateFixture(&fd); + + shape.SetAsBox(0.1f, 1.0f, b2Vec2(-0.9f, 0.0f), 0.0f); + b5->CreateFixture(&fd); + + shape.SetAsBox(0.1f, 1.0f, b2Vec2(0.9f, 0.0f), 0.0f); + b5->CreateFixture(&fd); + } + + anchor.Set(6.0f, 2.0f); + jd.Initialize(b1, b5, anchor); + m_world->CreateJoint(&jd); + + b2Body* b6; + { + b2PolygonShape shape; + shape.SetAsBox(1.0f, 0.1f); + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(6.5f, 4.1f); + b6 = m_world->CreateBody(&bd); + b6->CreateFixture(&shape, 30.0f); + } + + anchor.Set(7.5f, 4.0f); + jd.Initialize(b5, b6, anchor); + m_world->CreateJoint(&jd); + + b2Body* b7; + { + b2PolygonShape shape; + shape.SetAsBox(0.1f, 1.0f); + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(7.4f, 1.0f); + + b7 = m_world->CreateBody(&bd); + b7->CreateFixture(&shape, 10.0f); + } + + b2DistanceJointDef djd; + djd.bodyA = b3; + djd.bodyB = b7; + djd.localAnchorA.Set(6.0f, 0.0f); + djd.localAnchorB.Set(0.0f, -1.0f); + b2Vec2 d = djd.bodyB->GetWorldPoint(djd.localAnchorB) - djd.bodyA->GetWorldPoint(djd.localAnchorA); + djd.length = d.Length(); + + b2LinearStiffness(djd.stiffness, djd.damping, 1.0f, 1.0f, djd.bodyA, djd.bodyB); + m_world->CreateJoint(&djd); + + { + float radius = 0.2f; + + b2CircleShape shape; + shape.m_radius = radius; + + for (int32 i = 0; i < 4; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(5.9f + 2.0f * radius * i, 2.4f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 10.0f); + } + } + } + + static Test* Create() { return new Dominos; } }; static int testIndex = RegisterTest("Examples", "Dominos", Dominos::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/dump_loader.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/dump_loader.cpp index 3225113b517d..74e0984b076f 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/dump_loader.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/dump_loader.cpp @@ -26,63 +26,58 @@ class DumpLoader : public Test { public: + DumpLoader() + { + b2ChainShape chainShape; + b2Vec2 vertices[] = {b2Vec2(-5, 0), b2Vec2(5, 0), b2Vec2(5, 5), b2Vec2(4, 1), b2Vec2(-4, 1), b2Vec2(-5, 5)}; + chainShape.CreateLoop(vertices, 6); - DumpLoader() - { - b2ChainShape chainShape; - b2Vec2 vertices[] = {b2Vec2(-5,0), b2Vec2(5,0), b2Vec2(5,5), b2Vec2(4,1), b2Vec2(-4,1), b2Vec2(-5,5)}; - chainShape.CreateLoop(vertices, 6); + b2FixtureDef groundFixtureDef; + groundFixtureDef.density = 0; + groundFixtureDef.shape = &chainShape; - b2FixtureDef groundFixtureDef; - groundFixtureDef.density = 0; - groundFixtureDef.shape = &chainShape; + b2BodyDef groundBodyDef; + groundBodyDef.type = b2_staticBody; - b2BodyDef groundBodyDef; - groundBodyDef.type = b2_staticBody; + b2Body* groundBody = m_world->CreateBody(&groundBodyDef); + b2Fixture* groundBodyFixture = groundBody->CreateFixture(&groundFixtureDef); - b2Body *groundBody = m_world->CreateBody(&groundBodyDef); - b2Fixture *groundBodyFixture = groundBody->CreateFixture(&groundFixtureDef); + b2CircleShape ballShape; + ballShape.m_radius = 1; - b2CircleShape ballShape; - ballShape.m_radius = 1; + b2FixtureDef ballFixtureDef; + ballFixtureDef.restitution = 0.75f; + ballFixtureDef.density = 1; + ballFixtureDef.shape = &ballShape; - b2FixtureDef ballFixtureDef; - ballFixtureDef.restitution = 0.75f; - ballFixtureDef.density = 1; - ballFixtureDef.shape = &ballShape; + b2BodyDef ballBodyDef; + ballBodyDef.type = b2BodyType::b2_dynamicBody; + ballBodyDef.position = b2Vec2(0, 10); + // ballBodyDef.angularDamping = 0.2f; - b2BodyDef ballBodyDef; - ballBodyDef.type = b2BodyType::b2_dynamicBody; - ballBodyDef.position = b2Vec2(0, 10); - // ballBodyDef.angularDamping = 0.2f; + m_ball = m_world->CreateBody(&ballBodyDef); + b2Fixture* ballFixture = m_ball->CreateFixture(&ballFixtureDef); + m_ball->ApplyForceToCenter(b2Vec2(-1000, -400), true); + } - m_ball = m_world->CreateBody(&ballBodyDef); - b2Fixture *ballFixture = m_ball->CreateFixture(&ballFixtureDef); - m_ball->ApplyForceToCenter(b2Vec2(-1000, -400), true); - } + void Step(Settings& settings) override + { + b2Vec2 v = m_ball->GetLinearVelocity(); + float omega = m_ball->GetAngularVelocity(); - void Step(Settings& settings) override - { - b2Vec2 v = m_ball->GetLinearVelocity(); - float omega = m_ball->GetAngularVelocity(); + b2MassData massData; + m_ball->GetMassData(&massData); - b2MassData massData; - m_ball->GetMassData(&massData); + float ke = 0.5f * massData.mass * b2Dot(v, v) + 0.5f * massData.I * omega * omega; - float ke = 0.5f * massData.mass * b2Dot(v, v) + 0.5f * massData.I * omega * omega; + DrawString(5, m_textLine, "kinetic energy = %.6f", ke); - DrawString(5, m_textLine, "kinetic energy = %.6f", ke); - + Test::Step(settings); + } - Test::Step(settings); - } + static Test* Create() { return new DumpLoader; } - static Test* Create() - { - return new DumpLoader; - } - - b2Body* m_ball; + b2Body* m_ball; }; static int testIndex = RegisterTest("Bugs", "Dump Loader", DumpLoader::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/dynamic_tree.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/dynamic_tree.cpp index 4efcf56903bb..bd2de4d80a0f 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/dynamic_tree.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/dynamic_tree.cpp @@ -25,336 +25,333 @@ class DynamicTree : public Test { public: - - enum - { - e_actorCount = 128 - }; - - DynamicTree() - { - m_worldExtent = 15.0f; - m_proxyExtent = 0.5f; - - srand(888); - - for (int32 i = 0; i < e_actorCount; ++i) - { - Actor* actor = m_actors + i; - GetRandomAABB(&actor->aabb); - actor->proxyId = m_tree.CreateProxy(actor->aabb, actor); - } - - m_stepCount = 0; - - float h = m_worldExtent; - m_queryAABB.lowerBound.Set(-3.0f, -4.0f + h); - m_queryAABB.upperBound.Set(5.0f, 6.0f + h); - - m_rayCastInput.p1.Set(-5.0, 5.0f + h); - m_rayCastInput.p2.Set(7.0f, -4.0f + h); - //m_rayCastInput.p1.Set(0.0f, 2.0f + h); - //m_rayCastInput.p2.Set(0.0f, -2.0f + h); - m_rayCastInput.maxFraction = 1.0f; - - m_automated = false; - } - - static Test* Create() - { - return new DynamicTree; - } - - void Step(Settings& settings) override - { - B2_NOT_USED(settings); - - m_rayActor = NULL; - for (int32 i = 0; i < e_actorCount; ++i) - { - m_actors[i].fraction = 1.0f; - m_actors[i].overlap = false; - } - - if (m_automated == true) - { - int32 actionCount = b2Max(1, e_actorCount >> 2); - - for (int32 i = 0; i < actionCount; ++i) - { - Action(); - } - } - - Query(); - RayCast(); - - for (int32 i = 0; i < e_actorCount; ++i) - { - Actor* actor = m_actors + i; - if (actor->proxyId == b2_nullNode) - continue; - - b2Color c(0.9f, 0.9f, 0.9f); - if (actor == m_rayActor && actor->overlap) - { - c.Set(0.9f, 0.6f, 0.6f); - } - else if (actor == m_rayActor) - { - c.Set(0.6f, 0.9f, 0.6f); - } - else if (actor->overlap) - { - c.Set(0.6f, 0.6f, 0.9f); - } - - DrawAABB(&actor->aabb, c); - } - - b2Color c(0.7f, 0.7f, 0.7f); - DrawAABB(&m_queryAABB, c); - - g_debugDraw.DrawSegment(m_rayCastInput.p1, m_rayCastInput.p2, c); - - b2Color c1(0.2f, 0.9f, 0.2f); - b2Color c2(0.9f, 0.2f, 0.2f); - g_debugDraw.DrawPoint(m_rayCastInput.p1, 6.0f, c1); - g_debugDraw.DrawPoint(m_rayCastInput.p2, 6.0f, c2); - - if (m_rayActor) - { - b2Color cr(0.2f, 0.2f, 0.9f); - b2Vec2 p = m_rayCastInput.p1 + m_rayActor->fraction * (m_rayCastInput.p2 - m_rayCastInput.p1); - g_debugDraw.DrawPoint(p, 6.0f, cr); - } - - { - int32 height = m_tree.GetHeight(); - DrawString(5, m_textLine, "dynamic tree height = %d", height); - - } - - ++m_stepCount; - } - - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_A: - m_automated = !m_automated; - break; - - case GLFW_KEY_C: - CreateProxy(); - break; - - case GLFW_KEY_D: - DestroyProxy(); - break; - - case GLFW_KEY_M: - MoveProxy(); - break; - } - } - - bool QueryCallback(int32 proxyId) - { - Actor* actor = (Actor*)m_tree.GetUserData(proxyId); - actor->overlap = b2TestOverlap(m_queryAABB, actor->aabb); - return true; - } - - float RayCastCallback(const b2RayCastInput& input, int32 proxyId) - { - Actor* actor = (Actor*)m_tree.GetUserData(proxyId); - - b2RayCastOutput output; - bool hit = actor->aabb.RayCast(&output, input); - - if (hit) - { - m_rayCastOutput = output; - m_rayActor = actor; - m_rayActor->fraction = output.fraction; - return output.fraction; - } - - return input.maxFraction; - } + enum + { + e_actorCount = 128 + }; + + DynamicTree() + { + m_worldExtent = 15.0f; + m_proxyExtent = 0.5f; + + srand(888); + + for (int32 i = 0; i < e_actorCount; ++i) + { + Actor* actor = m_actors + i; + GetRandomAABB(&actor->aabb); + actor->proxyId = m_tree.CreateProxy(actor->aabb, actor); + } + + m_stepCount = 0; + + float h = m_worldExtent; + m_queryAABB.lowerBound.Set(-3.0f, -4.0f + h); + m_queryAABB.upperBound.Set(5.0f, 6.0f + h); + + m_rayCastInput.p1.Set(-5.0, 5.0f + h); + m_rayCastInput.p2.Set(7.0f, -4.0f + h); + // m_rayCastInput.p1.Set(0.0f, 2.0f + h); + // m_rayCastInput.p2.Set(0.0f, -2.0f + h); + m_rayCastInput.maxFraction = 1.0f; + + m_automated = false; + } + + static Test* Create() { return new DynamicTree; } + + void Step(Settings& settings) override + { + B2_NOT_USED(settings); + + m_rayActor = NULL; + for (int32 i = 0; i < e_actorCount; ++i) + { + m_actors[i].fraction = 1.0f; + m_actors[i].overlap = false; + } + + if (m_automated == true) + { + int32 actionCount = b2Max(1, e_actorCount >> 2); + + for (int32 i = 0; i < actionCount; ++i) + { + Action(); + } + } + + Query(); + RayCast(); + + for (int32 i = 0; i < e_actorCount; ++i) + { + Actor* actor = m_actors + i; + if (actor->proxyId == b2_nullNode) + continue; + + b2Color c(0.9f, 0.9f, 0.9f); + if (actor == m_rayActor && actor->overlap) + { + c.Set(0.9f, 0.6f, 0.6f); + } + else if (actor == m_rayActor) + { + c.Set(0.6f, 0.9f, 0.6f); + } + else if (actor->overlap) + { + c.Set(0.6f, 0.6f, 0.9f); + } + + DrawAABB(&actor->aabb, c); + } + + b2Color c(0.7f, 0.7f, 0.7f); + DrawAABB(&m_queryAABB, c); + + g_debugDraw.DrawSegment(m_rayCastInput.p1, m_rayCastInput.p2, c); + + b2Color c1(0.2f, 0.9f, 0.2f); + b2Color c2(0.9f, 0.2f, 0.2f); + g_debugDraw.DrawPoint(m_rayCastInput.p1, 6.0f, c1); + g_debugDraw.DrawPoint(m_rayCastInput.p2, 6.0f, c2); + + if (m_rayActor) + { + b2Color cr(0.2f, 0.2f, 0.9f); + b2Vec2 p = m_rayCastInput.p1 + m_rayActor->fraction * (m_rayCastInput.p2 - m_rayCastInput.p1); + g_debugDraw.DrawPoint(p, 6.0f, cr); + } + + { + int32 height = m_tree.GetHeight(); + DrawString(5, m_textLine, "dynamic tree height = %d", height); + } + + ++m_stepCount; + } + + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_A: + m_automated = !m_automated; + break; + + case GLFW_KEY_C: + CreateProxy(); + break; + + case GLFW_KEY_D: + DestroyProxy(); + break; + + case GLFW_KEY_M: + MoveProxy(); + break; + } + } + + bool QueryCallback(int32 proxyId) + { + Actor* actor = (Actor*)m_tree.GetUserData(proxyId); + actor->overlap = b2TestOverlap(m_queryAABB, actor->aabb); + return true; + } + + float RayCastCallback(const b2RayCastInput& input, int32 proxyId) + { + Actor* actor = (Actor*)m_tree.GetUserData(proxyId); + + b2RayCastOutput output; + bool hit = actor->aabb.RayCast(&output, input); + + if (hit) + { + m_rayCastOutput = output; + m_rayActor = actor; + m_rayActor->fraction = output.fraction; + return output.fraction; + } + + return input.maxFraction; + } private: - - struct Actor - { - b2AABB aabb; - float fraction; - bool overlap; - int32 proxyId; - }; - - void GetRandomAABB(b2AABB* aabb) - { - b2Vec2 w; w.Set(2.0f * m_proxyExtent, 2.0f * m_proxyExtent); - //aabb->lowerBound.x = -m_proxyExtent; - //aabb->lowerBound.y = -m_proxyExtent + m_worldExtent; - aabb->lowerBound.x = RandomFloat(-m_worldExtent, m_worldExtent); - aabb->lowerBound.y = RandomFloat(0.0f, 2.0f * m_worldExtent); - aabb->upperBound = aabb->lowerBound + w; - } - - void MoveAABB(b2AABB* aabb) - { - b2Vec2 d; - d.x = RandomFloat(-0.5f, 0.5f); - d.y = RandomFloat(-0.5f, 0.5f); - //d.x = 2.0f; - //d.y = 0.0f; - aabb->lowerBound += d; - aabb->upperBound += d; - - b2Vec2 c0 = 0.5f * (aabb->lowerBound + aabb->upperBound); - b2Vec2 min; min.Set(-m_worldExtent, 0.0f); - b2Vec2 max; max.Set(m_worldExtent, 2.0f * m_worldExtent); - b2Vec2 c = b2Clamp(c0, min, max); - - aabb->lowerBound += c - c0; - aabb->upperBound += c - c0; - } - - void CreateProxy() - { - for (int32 i = 0; i < e_actorCount; ++i) - { - int32 j = rand() % e_actorCount; - Actor* actor = m_actors + j; - if (actor->proxyId == b2_nullNode) - { - GetRandomAABB(&actor->aabb); - actor->proxyId = m_tree.CreateProxy(actor->aabb, actor); - return; - } - } - } - - void DestroyProxy() - { - for (int32 i = 0; i < e_actorCount; ++i) - { - int32 j = rand() % e_actorCount; - Actor* actor = m_actors + j; - if (actor->proxyId != b2_nullNode) - { - m_tree.DestroyProxy(actor->proxyId); - actor->proxyId = b2_nullNode; - return; - } - } - } - - void MoveProxy() - { - for (int32 i = 0; i < e_actorCount; ++i) - { - int32 j = rand() % e_actorCount; - Actor* actor = m_actors + j; - if (actor->proxyId == b2_nullNode) - { - continue; - } - - b2AABB aabb0 = actor->aabb; - MoveAABB(&actor->aabb); - b2Vec2 displacement = actor->aabb.GetCenter() - aabb0.GetCenter(); - m_tree.MoveProxy(actor->proxyId, actor->aabb, displacement); - return; - } - } - - void Action() - { - int32 choice = rand() % 20; - - switch (choice) - { - case 0: - CreateProxy(); - break; - - case 1: - DestroyProxy(); - break; - - default: - MoveProxy(); - } - } - - void Query() - { - m_tree.Query(this, m_queryAABB); - - for (int32 i = 0; i < e_actorCount; ++i) - { - if (m_actors[i].proxyId == b2_nullNode) - { - continue; - } - - bool overlap = b2TestOverlap(m_queryAABB, m_actors[i].aabb); - B2_NOT_USED(overlap); - b2Assert(overlap == m_actors[i].overlap); - } - } - - void RayCast() - { - m_rayActor = NULL; - - b2RayCastInput input = m_rayCastInput; - - // Ray cast against the dynamic tree. - m_tree.RayCast(this, input); - - // Brute force ray cast. - Actor* bruteActor = NULL; - b2RayCastOutput bruteOutput; - for (int32 i = 0; i < e_actorCount; ++i) - { - if (m_actors[i].proxyId == b2_nullNode) - { - continue; - } - - b2RayCastOutput output; - bool hit = m_actors[i].aabb.RayCast(&output, input); - if (hit) - { - bruteActor = m_actors + i; - bruteOutput = output; - input.maxFraction = output.fraction; - } - } - - if (bruteActor != NULL) - { - b2Assert(bruteOutput.fraction == m_rayCastOutput.fraction); - } - } - - float m_worldExtent; - float m_proxyExtent; - - b2DynamicTree m_tree; - b2AABB m_queryAABB; - b2RayCastInput m_rayCastInput; - b2RayCastOutput m_rayCastOutput; - Actor* m_rayActor; - Actor m_actors[e_actorCount]; - int32 m_stepCount; - bool m_automated; + struct Actor + { + b2AABB aabb; + float fraction; + bool overlap; + int32 proxyId; + }; + + void GetRandomAABB(b2AABB* aabb) + { + b2Vec2 w; + w.Set(2.0f * m_proxyExtent, 2.0f * m_proxyExtent); + // aabb->lowerBound.x = -m_proxyExtent; + // aabb->lowerBound.y = -m_proxyExtent + m_worldExtent; + aabb->lowerBound.x = RandomFloat(-m_worldExtent, m_worldExtent); + aabb->lowerBound.y = RandomFloat(0.0f, 2.0f * m_worldExtent); + aabb->upperBound = aabb->lowerBound + w; + } + + void MoveAABB(b2AABB* aabb) + { + b2Vec2 d; + d.x = RandomFloat(-0.5f, 0.5f); + d.y = RandomFloat(-0.5f, 0.5f); + // d.x = 2.0f; + // d.y = 0.0f; + aabb->lowerBound += d; + aabb->upperBound += d; + + b2Vec2 c0 = 0.5f * (aabb->lowerBound + aabb->upperBound); + b2Vec2 min; + min.Set(-m_worldExtent, 0.0f); + b2Vec2 max; + max.Set(m_worldExtent, 2.0f * m_worldExtent); + b2Vec2 c = b2Clamp(c0, min, max); + + aabb->lowerBound += c - c0; + aabb->upperBound += c - c0; + } + + void CreateProxy() + { + for (int32 i = 0; i < e_actorCount; ++i) + { + int32 j = rand() % e_actorCount; + Actor* actor = m_actors + j; + if (actor->proxyId == b2_nullNode) + { + GetRandomAABB(&actor->aabb); + actor->proxyId = m_tree.CreateProxy(actor->aabb, actor); + return; + } + } + } + + void DestroyProxy() + { + for (int32 i = 0; i < e_actorCount; ++i) + { + int32 j = rand() % e_actorCount; + Actor* actor = m_actors + j; + if (actor->proxyId != b2_nullNode) + { + m_tree.DestroyProxy(actor->proxyId); + actor->proxyId = b2_nullNode; + return; + } + } + } + + void MoveProxy() + { + for (int32 i = 0; i < e_actorCount; ++i) + { + int32 j = rand() % e_actorCount; + Actor* actor = m_actors + j; + if (actor->proxyId == b2_nullNode) + { + continue; + } + + b2AABB aabb0 = actor->aabb; + MoveAABB(&actor->aabb); + b2Vec2 displacement = actor->aabb.GetCenter() - aabb0.GetCenter(); + m_tree.MoveProxy(actor->proxyId, actor->aabb, displacement); + return; + } + } + + void Action() + { + int32 choice = rand() % 20; + + switch (choice) + { + case 0: + CreateProxy(); + break; + + case 1: + DestroyProxy(); + break; + + default: + MoveProxy(); + } + } + + void Query() + { + m_tree.Query(this, m_queryAABB); + + for (int32 i = 0; i < e_actorCount; ++i) + { + if (m_actors[i].proxyId == b2_nullNode) + { + continue; + } + + bool overlap = b2TestOverlap(m_queryAABB, m_actors[i].aabb); + B2_NOT_USED(overlap); + b2Assert(overlap == m_actors[i].overlap); + } + } + + void RayCast() + { + m_rayActor = NULL; + + b2RayCastInput input = m_rayCastInput; + + // Ray cast against the dynamic tree. + m_tree.RayCast(this, input); + + // Brute force ray cast. + Actor* bruteActor = NULL; + b2RayCastOutput bruteOutput; + for (int32 i = 0; i < e_actorCount; ++i) + { + if (m_actors[i].proxyId == b2_nullNode) + { + continue; + } + + b2RayCastOutput output; + bool hit = m_actors[i].aabb.RayCast(&output, input); + if (hit) + { + bruteActor = m_actors + i; + bruteOutput = output; + input.maxFraction = output.fraction; + } + } + + if (bruteActor != NULL) + { + b2Assert(bruteOutput.fraction == m_rayCastOutput.fraction); + } + } + + float m_worldExtent; + float m_proxyExtent; + + b2DynamicTree m_tree; + b2AABB m_queryAABB; + b2RayCastInput m_rayCastInput; + b2RayCastOutput m_rayCastOutput; + Actor* m_rayActor; + Actor m_actors[e_actorCount]; + int32 m_stepCount; + bool m_automated; }; static int testIndex = RegisterTest("Collision", "Dynamic Tree", DynamicTree::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/edge_shapes.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/edge_shapes.cpp index 37923549694a..f7416dc4373d 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/edge_shapes.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/edge_shapes.cpp @@ -26,228 +26,219 @@ class EdgeShapesCallback : public b2RayCastCallback { public: - EdgeShapesCallback() - { - m_fixture = NULL; - } - - float ReportFixture(b2Fixture* fixture, const b2Vec2& point, - const b2Vec2& normal, float fraction) override - { - m_fixture = fixture; - m_point = point; - m_normal = normal; - - return fraction; - } - - b2Fixture* m_fixture; - b2Vec2 m_point; - b2Vec2 m_normal; + EdgeShapesCallback() { m_fixture = NULL; } + + float ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float fraction) override + { + m_fixture = fixture; + m_point = point; + m_normal = normal; + + return fraction; + } + + b2Fixture* m_fixture; + b2Vec2 m_point; + b2Vec2 m_normal; }; class EdgeShapes : public Test { public: - - enum - { - e_maxBodies = 256 - }; - - EdgeShapes() - { - // Ground body - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - float x1 = -20.0f; - float y1 = 2.0f * cosf(x1 / 10.0f * b2_pi); - for (int32 i = 0; i < 80; ++i) - { - float x2 = x1 + 0.5f; - float y2 = 2.0f * cosf(x2 / 10.0f * b2_pi); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(x1, y1), b2Vec2(x2, y2)); - ground->CreateFixture(&shape, 0.0f); - - x1 = x2; - y1 = y2; - } - } - - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.5f, 0.0f); - vertices[1].Set(0.5f, 0.0f); - vertices[2].Set(0.0f, 1.5f); - m_polygons[0].Set(vertices, 3); - } - - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.1f, 0.0f); - vertices[1].Set(0.1f, 0.0f); - vertices[2].Set(0.0f, 1.5f); - m_polygons[1].Set(vertices, 3); - } - - { - float w = 1.0f; - float b = w / (2.0f + b2Sqrt(2.0f)); - float s = b2Sqrt(2.0f) * b; - - b2Vec2 vertices[8]; - vertices[0].Set(0.5f * s, 0.0f); - vertices[1].Set(0.5f * w, b); - vertices[2].Set(0.5f * w, b + s); - vertices[3].Set(0.5f * s, w); - vertices[4].Set(-0.5f * s, w); - vertices[5].Set(-0.5f * w, b + s); - vertices[6].Set(-0.5f * w, b); - vertices[7].Set(-0.5f * s, 0.0f); - - m_polygons[2].Set(vertices, 8); - } - - { - m_polygons[3].SetAsBox(0.5f, 0.5f); - } - - { - m_circle.m_radius = 0.5f; - } - - m_bodyIndex = 0; - memset(m_bodies, 0, sizeof(m_bodies)); - - m_angle = 0.0f; - } - - void Create(int32 index) - { - if (m_bodies[m_bodyIndex] != NULL) - { - m_world->DestroyBody(m_bodies[m_bodyIndex]); - m_bodies[m_bodyIndex] = NULL; - } - - b2BodyDef bd; - - float x = RandomFloat(-10.0f, 10.0f); - float y = RandomFloat(10.0f, 20.0f); - bd.position.Set(x, y); - bd.angle = RandomFloat(-b2_pi, b2_pi); - bd.type = b2_dynamicBody; - - if (index == 4) - { - bd.angularDamping = 0.02f; - } - - m_bodies[m_bodyIndex] = m_world->CreateBody(&bd); - - if (index < 4) - { - b2FixtureDef fd; - fd.shape = m_polygons + index; - fd.friction = 0.3f; - fd.density = 20.0f; - m_bodies[m_bodyIndex]->CreateFixture(&fd); - } - else - { - b2FixtureDef fd; - fd.shape = &m_circle; - fd.friction = 0.3f; - fd.density = 20.0f; - m_bodies[m_bodyIndex]->CreateFixture(&fd); - } - - m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; - } - - void DestroyBody() - { - for (int32 i = 0; i < e_maxBodies; ++i) - { - if (m_bodies[i] != NULL) - { - m_world->DestroyBody(m_bodies[i]); - m_bodies[i] = NULL; - return; - } - } - } - - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_1: - case GLFW_KEY_2: - case GLFW_KEY_3: - case GLFW_KEY_4: - case GLFW_KEY_5: - Create(key - GLFW_KEY_1); - break; - - case GLFW_KEY_D: - DestroyBody(); - break; - } - } - - void Step(Settings& settings) override - { - bool advanceRay = settings.m_pause == 0 || settings.m_singleStep; - - Test::Step(settings); - DrawString(5, m_textLine, "Press 1-5 to drop stuff"); - - - float L = 25.0f; - b2Vec2 point1(0.0f, 10.0f); - b2Vec2 d(L * cosf(m_angle), -L * b2Abs(sinf(m_angle))); - b2Vec2 point2 = point1 + d; - - EdgeShapesCallback callback; - - m_world->RayCast(&callback, point1, point2); - - if (callback.m_fixture) - { - g_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); - - g_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f)); - - b2Vec2 head = callback.m_point + 0.5f * callback.m_normal; - g_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f)); - } - else - { - g_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); - } - - if (advanceRay) - { - m_angle += 0.25f * b2_pi / 180.0f; - } - } - - static Test* Create() - { - return new EdgeShapes; - } - - int32 m_bodyIndex; - b2Body* m_bodies[e_maxBodies]; - b2PolygonShape m_polygons[4]; - b2CircleShape m_circle; - - float m_angle; + enum + { + e_maxBodies = 256 + }; + + EdgeShapes() + { + // Ground body + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + float x1 = -20.0f; + float y1 = 2.0f * cosf(x1 / 10.0f * b2_pi); + for (int32 i = 0; i < 80; ++i) + { + float x2 = x1 + 0.5f; + float y2 = 2.0f * cosf(x2 / 10.0f * b2_pi); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(x1, y1), b2Vec2(x2, y2)); + ground->CreateFixture(&shape, 0.0f); + + x1 = x2; + y1 = y2; + } + } + + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.5f, 0.0f); + vertices[1].Set(0.5f, 0.0f); + vertices[2].Set(0.0f, 1.5f); + m_polygons[0].Set(vertices, 3); + } + + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.1f, 0.0f); + vertices[1].Set(0.1f, 0.0f); + vertices[2].Set(0.0f, 1.5f); + m_polygons[1].Set(vertices, 3); + } + + { + float w = 1.0f; + float b = w / (2.0f + b2Sqrt(2.0f)); + float s = b2Sqrt(2.0f) * b; + + b2Vec2 vertices[8]; + vertices[0].Set(0.5f * s, 0.0f); + vertices[1].Set(0.5f * w, b); + vertices[2].Set(0.5f * w, b + s); + vertices[3].Set(0.5f * s, w); + vertices[4].Set(-0.5f * s, w); + vertices[5].Set(-0.5f * w, b + s); + vertices[6].Set(-0.5f * w, b); + vertices[7].Set(-0.5f * s, 0.0f); + + m_polygons[2].Set(vertices, 8); + } + + { + m_polygons[3].SetAsBox(0.5f, 0.5f); + } + + { + m_circle.m_radius = 0.5f; + } + + m_bodyIndex = 0; + memset(m_bodies, 0, sizeof(m_bodies)); + + m_angle = 0.0f; + } + + void Create(int32 index) + { + if (m_bodies[m_bodyIndex] != NULL) + { + m_world->DestroyBody(m_bodies[m_bodyIndex]); + m_bodies[m_bodyIndex] = NULL; + } + + b2BodyDef bd; + + float x = RandomFloat(-10.0f, 10.0f); + float y = RandomFloat(10.0f, 20.0f); + bd.position.Set(x, y); + bd.angle = RandomFloat(-b2_pi, b2_pi); + bd.type = b2_dynamicBody; + + if (index == 4) + { + bd.angularDamping = 0.02f; + } + + m_bodies[m_bodyIndex] = m_world->CreateBody(&bd); + + if (index < 4) + { + b2FixtureDef fd; + fd.shape = m_polygons + index; + fd.friction = 0.3f; + fd.density = 20.0f; + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } + else + { + b2FixtureDef fd; + fd.shape = &m_circle; + fd.friction = 0.3f; + fd.density = 20.0f; + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } + + m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; + } + + void DestroyBody() + { + for (int32 i = 0; i < e_maxBodies; ++i) + { + if (m_bodies[i] != NULL) + { + m_world->DestroyBody(m_bodies[i]); + m_bodies[i] = NULL; + return; + } + } + } + + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_1: + case GLFW_KEY_2: + case GLFW_KEY_3: + case GLFW_KEY_4: + case GLFW_KEY_5: + Create(key - GLFW_KEY_1); + break; + + case GLFW_KEY_D: + DestroyBody(); + break; + } + } + + void Step(Settings& settings) override + { + bool advanceRay = settings.m_pause == 0 || settings.m_singleStep; + + Test::Step(settings); + DrawString(5, m_textLine, "Press 1-5 to drop stuff"); + + float L = 25.0f; + b2Vec2 point1(0.0f, 10.0f); + b2Vec2 d(L * cosf(m_angle), -L * b2Abs(sinf(m_angle))); + b2Vec2 point2 = point1 + d; + + EdgeShapesCallback callback; + + m_world->RayCast(&callback, point1, point2); + + if (callback.m_fixture) + { + g_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); + + g_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f)); + + b2Vec2 head = callback.m_point + 0.5f * callback.m_normal; + g_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f)); + } + else + { + g_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); + } + + if (advanceRay) + { + m_angle += 0.25f * b2_pi / 180.0f; + } + } + + static Test* Create() { return new EdgeShapes; } + + int32 m_bodyIndex; + b2Body* m_bodies[e_maxBodies]; + b2PolygonShape m_polygons[4]; + b2CircleShape m_circle; + + float m_angle; }; static int testIndex = RegisterTest("Geometry", "Edge Shapes", EdgeShapes::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/edge_test.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/edge_test.cpp index 7f53a86f1cb8..e9c4bf4dc55c 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/edge_test.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/edge_test.cpp @@ -26,257 +26,242 @@ class EdgeTest : public Test { public: + EdgeTest() + { + b2Vec2 vertices[10] = {{10.0f, -4.0f}, {10.0f, 0.0f}, {6.0f, 0.0f}, {4.0f, 2.0f}, {2.0f, 0.0f}, + {-2.0f, 0.0f}, {-6.0f, 0.0f}, {-8.0f, -3.0f}, {-10.0f, 0.0f}, {-10.0f, -4.0f}}; - EdgeTest() - { - b2Vec2 vertices[10] = - { - {10.0f, -4.0f}, - {10.0f, 0.0f}, - {6.0f, 0.0f}, - {4.0f, 2.0f}, - {2.0f, 0.0f}, - {-2.0f, 0.0f}, - {-6.0f, 0.0f}, - {-8.0f, -3.0f}, - {-10.0f, 0.0f}, - {-10.0f, -4.0f} - }; + m_offset1.Set(0.0f, 8.0f); + m_offset2.Set(0.0f, 16.0f); - m_offset1.Set(0.0f, 8.0f); - m_offset2.Set(0.0f, 16.0f); - - { - b2Vec2 v1 = vertices[0] + m_offset1; - b2Vec2 v2 = vertices[1] + m_offset1; - b2Vec2 v3 = vertices[2] + m_offset1; - b2Vec2 v4 = vertices[3] + m_offset1; - b2Vec2 v5 = vertices[4] + m_offset1; - b2Vec2 v6 = vertices[5] + m_offset1; - b2Vec2 v7 = vertices[6] + m_offset1; - b2Vec2 v8 = vertices[7] + m_offset1; - b2Vec2 v9 = vertices[8] + m_offset1; - b2Vec2 v10 = vertices[9] + m_offset1; - - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - - shape.SetOneSided(v10, v1, v2, v3); - ground->CreateFixture(&shape, 0.0f); - - shape.SetOneSided(v1, v2, v3, v4); - ground->CreateFixture(&shape, 0.0f); - - shape.SetOneSided(v2, v3, v4, v5); - ground->CreateFixture(&shape, 0.0f); - - shape.SetOneSided(v3, v4, v5, v6); - ground->CreateFixture(&shape, 0.0f); - - shape.SetOneSided(v4, v5, v6, v7); - ground->CreateFixture(&shape, 0.0f); - - shape.SetOneSided(v5, v6, v7, v8); - ground->CreateFixture(&shape, 0.0f); - - shape.SetOneSided(v6, v7, v8, v9); - ground->CreateFixture(&shape, 0.0f); - - shape.SetOneSided(v7, v8, v9, v10); - ground->CreateFixture(&shape, 0.0f); - - shape.SetOneSided(v8, v9, v10, v1); - ground->CreateFixture(&shape, 0.0f); - - shape.SetOneSided(v9, v10, v1, v2); - ground->CreateFixture(&shape, 0.0f); - } - - { - b2Vec2 v1 = vertices[0] + m_offset2; - b2Vec2 v2 = vertices[1] + m_offset2; - b2Vec2 v3 = vertices[2] + m_offset2; - b2Vec2 v4 = vertices[3] + m_offset2; - b2Vec2 v5 = vertices[4] + m_offset2; - b2Vec2 v6 = vertices[5] + m_offset2; - b2Vec2 v7 = vertices[6] + m_offset2; - b2Vec2 v8 = vertices[7] + m_offset2; - b2Vec2 v9 = vertices[8] + m_offset2; - b2Vec2 v10 = vertices[9] + m_offset2; - - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - - shape.SetTwoSided(v1, v2); - ground->CreateFixture(&shape, 0.0f); - - shape.SetTwoSided(v2, v3); - ground->CreateFixture(&shape, 0.0f); - - shape.SetTwoSided(v3, v4); - ground->CreateFixture(&shape, 0.0f); - - shape.SetTwoSided(v4, v5); - ground->CreateFixture(&shape, 0.0f); - - shape.SetTwoSided(v5, v6); - ground->CreateFixture(&shape, 0.0f); - - shape.SetTwoSided(v6, v7); - ground->CreateFixture(&shape, 0.0f); - - shape.SetTwoSided(v7, v8); - ground->CreateFixture(&shape, 0.0f); - - shape.SetTwoSided(v8, v9); - ground->CreateFixture(&shape, 0.0f); - - shape.SetTwoSided(v9, v10); - ground->CreateFixture(&shape, 0.0f); - - shape.SetTwoSided(v10, v1); - ground->CreateFixture(&shape, 0.0f); - } - - m_body1 = nullptr; - m_body2 = nullptr; - CreateBoxes(); - m_boxes = true; - } - - void CreateBoxes() - { - if (m_body1) - { - m_world->DestroyBody(m_body1); - m_body1 = nullptr; - } - - if (m_body2) - { - m_world->DestroyBody(m_body2); - m_body2 = nullptr; - } - - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = b2Vec2(8.0f, 2.6f) + m_offset1; - bd.allowSleep = false; - m_body1 = m_world->CreateBody(&bd); - - b2PolygonShape shape; - shape.SetAsBox(0.5f, 1.0f); - - m_body1->CreateFixture(&shape, 1.0f); - } - - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = b2Vec2(8.0f, 2.6f) + m_offset2; - bd.allowSleep = false; - m_body2 = m_world->CreateBody(&bd); - - b2PolygonShape shape; - shape.SetAsBox(0.5f, 1.0f); - - m_body2->CreateFixture(&shape, 1.0f); - } - } - - void CreateCircles() - { - if (m_body1) - { - m_world->DestroyBody(m_body1); - m_body1 = nullptr; - } - - if (m_body2) - { - m_world->DestroyBody(m_body2); - m_body2 = nullptr; - } - - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = b2Vec2(-0.5f, 0.6f) + m_offset1; - bd.allowSleep = false; - m_body1 = m_world->CreateBody(&bd); - - b2CircleShape shape; - shape.m_radius = 0.5f; - - m_body1->CreateFixture(&shape, 1.0f); - } - - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = b2Vec2(-0.5f, 0.6f) + m_offset2; - bd.allowSleep = false; - m_body2 = m_world->CreateBody(&bd); - - b2CircleShape shape; - shape.m_radius = 0.5f; - - m_body2->CreateFixture(&shape, 1.0f); - } - } - - void UpdateUI() override - { - //ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); - ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); - ImGui::Begin("Custom Controls", nullptr, ImGuiWindowFlags_NoResize); - - if (ImGui::RadioButton("Boxes", m_boxes == true)) - { - CreateBoxes(); - m_boxes = true; - } - - if (ImGui::RadioButton("Circles", m_boxes == false)) - { - CreateCircles(); - m_boxes = false; - } - - ImGui::End(); - } - - void Step(Settings& settings) override - { - //if (glfwGetKey(g_mainWindow, GLFW_KEY_A) == GLFW_PRESS) - //{ - // m_body1->ApplyForceToCenter(b2Vec2(-10.0f, 0.0f), true); - // m_body2->ApplyForceToCenter(b2Vec2(-10.0f, 0.0f), true); - //} - - //if (glfwGetKey(g_mainWindow, GLFW_KEY_D) == GLFW_PRESS) - //{ - // m_body1->ApplyForceToCenter(b2Vec2(10.0f, 0.0f), true); - // m_body2->ApplyForceToCenter(b2Vec2(10.0f, 0.0f), true); - //} - - Test::Step(settings); - } - - static Test* Create() - { - return new EdgeTest; - } - - b2Vec2 m_offset1, m_offset2; - b2Body* m_body1; - b2Body* m_body2; - bool m_boxes; + { + b2Vec2 v1 = vertices[0] + m_offset1; + b2Vec2 v2 = vertices[1] + m_offset1; + b2Vec2 v3 = vertices[2] + m_offset1; + b2Vec2 v4 = vertices[3] + m_offset1; + b2Vec2 v5 = vertices[4] + m_offset1; + b2Vec2 v6 = vertices[5] + m_offset1; + b2Vec2 v7 = vertices[6] + m_offset1; + b2Vec2 v8 = vertices[7] + m_offset1; + b2Vec2 v9 = vertices[8] + m_offset1; + b2Vec2 v10 = vertices[9] + m_offset1; + + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + + shape.SetOneSided(v10, v1, v2, v3); + ground->CreateFixture(&shape, 0.0f); + + shape.SetOneSided(v1, v2, v3, v4); + ground->CreateFixture(&shape, 0.0f); + + shape.SetOneSided(v2, v3, v4, v5); + ground->CreateFixture(&shape, 0.0f); + + shape.SetOneSided(v3, v4, v5, v6); + ground->CreateFixture(&shape, 0.0f); + + shape.SetOneSided(v4, v5, v6, v7); + ground->CreateFixture(&shape, 0.0f); + + shape.SetOneSided(v5, v6, v7, v8); + ground->CreateFixture(&shape, 0.0f); + + shape.SetOneSided(v6, v7, v8, v9); + ground->CreateFixture(&shape, 0.0f); + + shape.SetOneSided(v7, v8, v9, v10); + ground->CreateFixture(&shape, 0.0f); + + shape.SetOneSided(v8, v9, v10, v1); + ground->CreateFixture(&shape, 0.0f); + + shape.SetOneSided(v9, v10, v1, v2); + ground->CreateFixture(&shape, 0.0f); + } + + { + b2Vec2 v1 = vertices[0] + m_offset2; + b2Vec2 v2 = vertices[1] + m_offset2; + b2Vec2 v3 = vertices[2] + m_offset2; + b2Vec2 v4 = vertices[3] + m_offset2; + b2Vec2 v5 = vertices[4] + m_offset2; + b2Vec2 v6 = vertices[5] + m_offset2; + b2Vec2 v7 = vertices[6] + m_offset2; + b2Vec2 v8 = vertices[7] + m_offset2; + b2Vec2 v9 = vertices[8] + m_offset2; + b2Vec2 v10 = vertices[9] + m_offset2; + + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + + shape.SetTwoSided(v1, v2); + ground->CreateFixture(&shape, 0.0f); + + shape.SetTwoSided(v2, v3); + ground->CreateFixture(&shape, 0.0f); + + shape.SetTwoSided(v3, v4); + ground->CreateFixture(&shape, 0.0f); + + shape.SetTwoSided(v4, v5); + ground->CreateFixture(&shape, 0.0f); + + shape.SetTwoSided(v5, v6); + ground->CreateFixture(&shape, 0.0f); + + shape.SetTwoSided(v6, v7); + ground->CreateFixture(&shape, 0.0f); + + shape.SetTwoSided(v7, v8); + ground->CreateFixture(&shape, 0.0f); + + shape.SetTwoSided(v8, v9); + ground->CreateFixture(&shape, 0.0f); + + shape.SetTwoSided(v9, v10); + ground->CreateFixture(&shape, 0.0f); + + shape.SetTwoSided(v10, v1); + ground->CreateFixture(&shape, 0.0f); + } + + m_body1 = nullptr; + m_body2 = nullptr; + CreateBoxes(); + m_boxes = true; + } + + void CreateBoxes() + { + if (m_body1) + { + m_world->DestroyBody(m_body1); + m_body1 = nullptr; + } + + if (m_body2) + { + m_world->DestroyBody(m_body2); + m_body2 = nullptr; + } + + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = b2Vec2(8.0f, 2.6f) + m_offset1; + bd.allowSleep = false; + m_body1 = m_world->CreateBody(&bd); + + b2PolygonShape shape; + shape.SetAsBox(0.5f, 1.0f); + + m_body1->CreateFixture(&shape, 1.0f); + } + + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = b2Vec2(8.0f, 2.6f) + m_offset2; + bd.allowSleep = false; + m_body2 = m_world->CreateBody(&bd); + + b2PolygonShape shape; + shape.SetAsBox(0.5f, 1.0f); + + m_body2->CreateFixture(&shape, 1.0f); + } + } + + void CreateCircles() + { + if (m_body1) + { + m_world->DestroyBody(m_body1); + m_body1 = nullptr; + } + + if (m_body2) + { + m_world->DestroyBody(m_body2); + m_body2 = nullptr; + } + + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = b2Vec2(-0.5f, 0.6f) + m_offset1; + bd.allowSleep = false; + m_body1 = m_world->CreateBody(&bd); + + b2CircleShape shape; + shape.m_radius = 0.5f; + + m_body1->CreateFixture(&shape, 1.0f); + } + + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = b2Vec2(-0.5f, 0.6f) + m_offset2; + bd.allowSleep = false; + m_body2 = m_world->CreateBody(&bd); + + b2CircleShape shape; + shape.m_radius = 0.5f; + + m_body2->CreateFixture(&shape, 1.0f); + } + } + + void UpdateUI() override + { + // ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); + ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); + ImGui::Begin("Custom Controls", nullptr, ImGuiWindowFlags_NoResize); + + if (ImGui::RadioButton("Boxes", m_boxes == true)) + { + CreateBoxes(); + m_boxes = true; + } + + if (ImGui::RadioButton("Circles", m_boxes == false)) + { + CreateCircles(); + m_boxes = false; + } + + ImGui::End(); + } + + void Step(Settings& settings) override + { + // if (glfwGetKey(g_mainWindow, GLFW_KEY_A) == GLFW_PRESS) + //{ + // m_body1->ApplyForceToCenter(b2Vec2(-10.0f, 0.0f), true); + // m_body2->ApplyForceToCenter(b2Vec2(-10.0f, 0.0f), true); + // } + + // if (glfwGetKey(g_mainWindow, GLFW_KEY_D) == GLFW_PRESS) + //{ + // m_body1->ApplyForceToCenter(b2Vec2(10.0f, 0.0f), true); + // m_body2->ApplyForceToCenter(b2Vec2(10.0f, 0.0f), true); + // } + + Test::Step(settings); + } + + static Test* Create() { return new EdgeTest; } + + b2Vec2 m_offset1, m_offset2; + b2Body* m_body1; + b2Body* m_body2; + bool m_boxes; }; static int testIndex = RegisterTest("Geometry", "Edge Test", EdgeTest::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/friction.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/friction.cpp index 9f1c06e93206..b935e0459c64 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/friction.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/friction.cpp @@ -25,103 +25,99 @@ class Friction : public Test { public: - - Friction() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - { - b2PolygonShape shape; - shape.SetAsBox(13.0f, 0.25f); - - b2BodyDef bd; - bd.position.Set(-4.0f, 22.0f); - bd.angle = -0.25f; - - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } - - { - b2PolygonShape shape; - shape.SetAsBox(0.25f, 1.0f); - - b2BodyDef bd; - bd.position.Set(10.5f, 19.0f); - - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } - - { - b2PolygonShape shape; - shape.SetAsBox(13.0f, 0.25f); - - b2BodyDef bd; - bd.position.Set(4.0f, 14.0f); - bd.angle = 0.25f; - - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } - - { - b2PolygonShape shape; - shape.SetAsBox(0.25f, 1.0f); - - b2BodyDef bd; - bd.position.Set(-10.5f, 11.0f); - - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } - - { - b2PolygonShape shape; - shape.SetAsBox(13.0f, 0.25f); - - b2BodyDef bd; - bd.position.Set(-4.0f, 6.0f); - bd.angle = -0.25f; - - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } - - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.5f); - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 25.0f; - - float friction[5] = {0.75f, 0.5f, 0.35f, 0.1f, 0.0f}; - - for (int i = 0; i < 5; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-15.0f + 4.0f * i, 28.0f); - b2Body* body = m_world->CreateBody(&bd); - - fd.friction = friction[i]; - body->CreateFixture(&fd); - } - } - } - - static Test* Create() - { - return new Friction; - } + Friction() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + { + b2PolygonShape shape; + shape.SetAsBox(13.0f, 0.25f); + + b2BodyDef bd; + bd.position.Set(-4.0f, 22.0f); + bd.angle = -0.25f; + + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } + + { + b2PolygonShape shape; + shape.SetAsBox(0.25f, 1.0f); + + b2BodyDef bd; + bd.position.Set(10.5f, 19.0f); + + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } + + { + b2PolygonShape shape; + shape.SetAsBox(13.0f, 0.25f); + + b2BodyDef bd; + bd.position.Set(4.0f, 14.0f); + bd.angle = 0.25f; + + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } + + { + b2PolygonShape shape; + shape.SetAsBox(0.25f, 1.0f); + + b2BodyDef bd; + bd.position.Set(-10.5f, 11.0f); + + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } + + { + b2PolygonShape shape; + shape.SetAsBox(13.0f, 0.25f); + + b2BodyDef bd; + bd.position.Set(-4.0f, 6.0f); + bd.angle = -0.25f; + + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } + + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 25.0f; + + float friction[5] = {0.75f, 0.5f, 0.35f, 0.1f, 0.0f}; + + for (int i = 0; i < 5; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-15.0f + 4.0f * i, 28.0f); + b2Body* body = m_world->CreateBody(&bd); + + fd.friction = friction[i]; + body->CreateFixture(&fd); + } + } + } + + static Test* Create() { return new Friction; } }; static int testIndex = RegisterTest("Forces", "Friction", Friction::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/gear_joint.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/gear_joint.cpp index ddde2cfb8d7e..d7e1b15771e2 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/gear_joint.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/gear_joint.cpp @@ -25,156 +25,151 @@ class GearJoint : public Test { public: - GearJoint() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(50.0f, 0.0f), b2Vec2(-50.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - { - b2CircleShape circle1; - circle1.m_radius = 1.0f; - - b2PolygonShape box; - box.SetAsBox(0.5f, 5.0f); - - b2CircleShape circle2; - circle2.m_radius = 2.0f; - - b2BodyDef bd1; - bd1.type = b2_staticBody; - bd1.position.Set(10.0f, 9.0f); - b2Body* body1 = m_world->CreateBody(&bd1); - body1->CreateFixture(&circle1, 5.0f); - - b2BodyDef bd2; - bd2.type = b2_dynamicBody; - bd2.position.Set(10.0f, 8.0f); - b2Body* body2 = m_world->CreateBody(&bd2); - body2->CreateFixture(&box, 5.0f); - - b2BodyDef bd3; - bd3.type = b2_dynamicBody; - bd3.position.Set(10.0f, 6.0f); - b2Body* body3 = m_world->CreateBody(&bd3); - body3->CreateFixture(&circle2, 5.0f); - - b2RevoluteJointDef jd1; - jd1.Initialize(body1, body2, bd1.position); - b2Joint* joint1 = m_world->CreateJoint(&jd1); - - b2RevoluteJointDef jd2; - jd2.Initialize(body2, body3, bd3.position); - b2Joint* joint2 = m_world->CreateJoint(&jd2); - - b2GearJointDef jd4; - jd4.bodyA = body1; - jd4.bodyB = body3; - jd4.joint1 = joint1; - jd4.joint2 = joint2; - jd4.ratio = circle2.m_radius / circle1.m_radius; - m_world->CreateJoint(&jd4); - } - - { - b2CircleShape circle1; - circle1.m_radius = 1.0f; - - b2CircleShape circle2; - circle2.m_radius = 2.0f; - - b2PolygonShape box; - box.SetAsBox(0.5f, 5.0f); - - b2BodyDef bd1; - bd1.type = b2_dynamicBody; - bd1.position.Set(-3.0f, 12.0f); - b2Body* body1 = m_world->CreateBody(&bd1); - body1->CreateFixture(&circle1, 5.0f); - - b2RevoluteJointDef jd1; - jd1.bodyA = ground; - jd1.bodyB = body1; - jd1.localAnchorA = ground->GetLocalPoint(bd1.position); - jd1.localAnchorB = body1->GetLocalPoint(bd1.position); - jd1.referenceAngle = body1->GetAngle() - ground->GetAngle(); - m_joint1 = (b2RevoluteJoint*)m_world->CreateJoint(&jd1); - - b2BodyDef bd2; - bd2.type = b2_dynamicBody; - bd2.position.Set(0.0f, 12.0f); - b2Body* body2 = m_world->CreateBody(&bd2); - body2->CreateFixture(&circle2, 5.0f); - - b2RevoluteJointDef jd2; - jd2.Initialize(ground, body2, bd2.position); - m_joint2 = (b2RevoluteJoint*)m_world->CreateJoint(&jd2); - - b2BodyDef bd3; - bd3.type = b2_dynamicBody; - bd3.position.Set(2.5f, 12.0f); - b2Body* body3 = m_world->CreateBody(&bd3); - body3->CreateFixture(&box, 5.0f); - - b2PrismaticJointDef jd3; - jd3.Initialize(ground, body3, bd3.position, b2Vec2(0.0f, 1.0f)); - jd3.lowerTranslation = -5.0f; - jd3.upperTranslation = 5.0f; - jd3.enableLimit = true; - - m_joint3 = (b2PrismaticJoint*)m_world->CreateJoint(&jd3); - - b2GearJointDef jd4; - jd4.bodyA = body1; - jd4.bodyB = body2; - jd4.joint1 = m_joint1; - jd4.joint2 = m_joint2; - jd4.ratio = circle2.m_radius / circle1.m_radius; - m_joint4 = (b2GearJoint*)m_world->CreateJoint(&jd4); - - b2GearJointDef jd5; - jd5.bodyA = body2; - jd5.bodyB = body3; - jd5.joint1 = m_joint2; - jd5.joint2 = m_joint3; - jd5.ratio = -1.0f / circle2.m_radius; - m_joint5 = (b2GearJoint*)m_world->CreateJoint(&jd5); - } - } - - void Step(Settings& settings) override - { - Test::Step(settings); - - float ratio, value; - - ratio = m_joint4->GetRatio(); - value = m_joint1->GetJointAngle() + ratio * m_joint2->GetJointAngle(); - DrawString(5, m_textLine, "theta1 + %4.2f * theta2 = %4.2f", (float) ratio, (float) value); - - - ratio = m_joint5->GetRatio(); - value = m_joint2->GetJointAngle() + ratio * m_joint3->GetJointTranslation(); - DrawString(5, m_textLine, "theta2 + %4.2f * delta = %4.2f", (float) ratio, (float) value); - - } - - static Test* Create() - { - return new GearJoint; - } - - b2RevoluteJoint* m_joint1; - b2RevoluteJoint* m_joint2; - b2PrismaticJoint* m_joint3; - b2GearJoint* m_joint4; - b2GearJoint* m_joint5; + GearJoint() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(50.0f, 0.0f), b2Vec2(-50.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + { + b2CircleShape circle1; + circle1.m_radius = 1.0f; + + b2PolygonShape box; + box.SetAsBox(0.5f, 5.0f); + + b2CircleShape circle2; + circle2.m_radius = 2.0f; + + b2BodyDef bd1; + bd1.type = b2_staticBody; + bd1.position.Set(10.0f, 9.0f); + b2Body* body1 = m_world->CreateBody(&bd1); + body1->CreateFixture(&circle1, 5.0f); + + b2BodyDef bd2; + bd2.type = b2_dynamicBody; + bd2.position.Set(10.0f, 8.0f); + b2Body* body2 = m_world->CreateBody(&bd2); + body2->CreateFixture(&box, 5.0f); + + b2BodyDef bd3; + bd3.type = b2_dynamicBody; + bd3.position.Set(10.0f, 6.0f); + b2Body* body3 = m_world->CreateBody(&bd3); + body3->CreateFixture(&circle2, 5.0f); + + b2RevoluteJointDef jd1; + jd1.Initialize(body1, body2, bd1.position); + b2Joint* joint1 = m_world->CreateJoint(&jd1); + + b2RevoluteJointDef jd2; + jd2.Initialize(body2, body3, bd3.position); + b2Joint* joint2 = m_world->CreateJoint(&jd2); + + b2GearJointDef jd4; + jd4.bodyA = body1; + jd4.bodyB = body3; + jd4.joint1 = joint1; + jd4.joint2 = joint2; + jd4.ratio = circle2.m_radius / circle1.m_radius; + m_world->CreateJoint(&jd4); + } + + { + b2CircleShape circle1; + circle1.m_radius = 1.0f; + + b2CircleShape circle2; + circle2.m_radius = 2.0f; + + b2PolygonShape box; + box.SetAsBox(0.5f, 5.0f); + + b2BodyDef bd1; + bd1.type = b2_dynamicBody; + bd1.position.Set(-3.0f, 12.0f); + b2Body* body1 = m_world->CreateBody(&bd1); + body1->CreateFixture(&circle1, 5.0f); + + b2RevoluteJointDef jd1; + jd1.bodyA = ground; + jd1.bodyB = body1; + jd1.localAnchorA = ground->GetLocalPoint(bd1.position); + jd1.localAnchorB = body1->GetLocalPoint(bd1.position); + jd1.referenceAngle = body1->GetAngle() - ground->GetAngle(); + m_joint1 = (b2RevoluteJoint*)m_world->CreateJoint(&jd1); + + b2BodyDef bd2; + bd2.type = b2_dynamicBody; + bd2.position.Set(0.0f, 12.0f); + b2Body* body2 = m_world->CreateBody(&bd2); + body2->CreateFixture(&circle2, 5.0f); + + b2RevoluteJointDef jd2; + jd2.Initialize(ground, body2, bd2.position); + m_joint2 = (b2RevoluteJoint*)m_world->CreateJoint(&jd2); + + b2BodyDef bd3; + bd3.type = b2_dynamicBody; + bd3.position.Set(2.5f, 12.0f); + b2Body* body3 = m_world->CreateBody(&bd3); + body3->CreateFixture(&box, 5.0f); + + b2PrismaticJointDef jd3; + jd3.Initialize(ground, body3, bd3.position, b2Vec2(0.0f, 1.0f)); + jd3.lowerTranslation = -5.0f; + jd3.upperTranslation = 5.0f; + jd3.enableLimit = true; + + m_joint3 = (b2PrismaticJoint*)m_world->CreateJoint(&jd3); + + b2GearJointDef jd4; + jd4.bodyA = body1; + jd4.bodyB = body2; + jd4.joint1 = m_joint1; + jd4.joint2 = m_joint2; + jd4.ratio = circle2.m_radius / circle1.m_radius; + m_joint4 = (b2GearJoint*)m_world->CreateJoint(&jd4); + + b2GearJointDef jd5; + jd5.bodyA = body2; + jd5.bodyB = body3; + jd5.joint1 = m_joint2; + jd5.joint2 = m_joint3; + jd5.ratio = -1.0f / circle2.m_radius; + m_joint5 = (b2GearJoint*)m_world->CreateJoint(&jd5); + } + } + + void Step(Settings& settings) override + { + Test::Step(settings); + + float ratio, value; + + ratio = m_joint4->GetRatio(); + value = m_joint1->GetJointAngle() + ratio * m_joint2->GetJointAngle(); + DrawString(5, m_textLine, "theta1 + %4.2f * theta2 = %4.2f", (float)ratio, (float)value); + + ratio = m_joint5->GetRatio(); + value = m_joint2->GetJointAngle() + ratio * m_joint3->GetJointTranslation(); + DrawString(5, m_textLine, "theta2 + %4.2f * delta = %4.2f", (float)ratio, (float)value); + } + + static Test* Create() { return new GearJoint; } + + b2RevoluteJoint* m_joint1; + b2RevoluteJoint* m_joint2; + b2PrismaticJoint* m_joint3; + b2GearJoint* m_joint4; + b2GearJoint* m_joint5; }; static int testIndex = RegisterTest("Joints", "Gear", GearJoint::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/heavy1.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/heavy1.cpp index d302808aad4d..17ba6d183f23 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/heavy1.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/heavy1.cpp @@ -25,37 +25,33 @@ class Heavy1 : public Test { public: - Heavy1() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 0.5f); - b2Body* body = m_world->CreateBody(&bd); - - b2CircleShape shape; - shape.m_radius = 0.5f; + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 0.5f); + b2Body* body = m_world->CreateBody(&bd); + + b2CircleShape shape; + shape.m_radius = 0.5f; body->CreateFixture(&shape, 10.0f); - + bd.position.Set(0.0f, 6.0f); - body = m_world->CreateBody(&bd); + body = m_world->CreateBody(&bd); shape.m_radius = 5.0f; body->CreateFixture(&shape, 10.0f); - } - - static Test* Create() - { - return new Heavy1; - } + } + + static Test* Create() { return new Heavy1; } }; static int testIndex = RegisterTest("Solver", "Heavy 1", Heavy1::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/heavy2.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/heavy2.cpp index 271c089b3d7c..c34a36995eb8 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/heavy2.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/heavy2.cpp @@ -25,34 +25,33 @@ class Heavy2 : public Test { public: - Heavy2() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 2.5f); - b2Body* body = m_world->CreateBody(&bd); - - b2CircleShape shape; - shape.m_radius = 0.5f; + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 2.5f); + b2Body* body = m_world->CreateBody(&bd); + + b2CircleShape shape; + shape.m_radius = 0.5f; body->CreateFixture(&shape, 10.0f); - + bd.position.Set(0.0f, 3.5f); body = m_world->CreateBody(&bd); body->CreateFixture(&shape, 10.0f); - + m_heavy = NULL; - } - + } + void ToggleHeavy() { if (m_heavy) @@ -66,29 +65,26 @@ class Heavy2 : public Test bd.type = b2_dynamicBody; bd.position.Set(0.0f, 9.0f); m_heavy = m_world->CreateBody(&bd); - + b2CircleShape shape; shape.m_radius = 5.0f; m_heavy->CreateFixture(&shape, 10.0f); } } - - void Keyboard(int key) override - { - switch (key) - { + + void Keyboard(int key) override + { + switch (key) + { case GLFW_KEY_H: ToggleHeavy(); break; - } - } - - static Test* Create() - { - return new Heavy2; - } - - b2Body* m_heavy; + } + } + + static Test* Create() { return new Heavy2; } + + b2Body* m_heavy; }; static int testIndex = RegisterTest("Solver", "Heavy 2", Heavy2::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/mobile_balanced.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/mobile_balanced.cpp index ee5af37831d5..8b68edd0b7c7 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/mobile_balanced.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/mobile_balanced.cpp @@ -25,84 +25,80 @@ class MobileBalanced : public Test { public: - - enum - { - e_depth = 4 - }; - - MobileBalanced() - { - b2Body* ground; - - // Create ground body. - { - b2BodyDef bodyDef; - bodyDef.position.Set(0.0f, 20.0f); - ground = m_world->CreateBody(&bodyDef); - } - - float a = 0.5f; - b2Vec2 h(0.0f, a); - - b2Body* root = AddNode(ground, b2Vec2_zero, 0, 3.0f, a); - - b2RevoluteJointDef jointDef; - jointDef.bodyA = ground; - jointDef.bodyB = root; - jointDef.localAnchorA.SetZero(); - jointDef.localAnchorB = h; - m_world->CreateJoint(&jointDef); - } - - b2Body* AddNode(b2Body* parent, const b2Vec2& localAnchor, int32 depth, float offset, float a) - { - float density = 20.0f; - b2Vec2 h(0.0f, a); - - b2Vec2 p = parent->GetPosition() + localAnchor - h; - - b2BodyDef bodyDef; - bodyDef.type = b2_dynamicBody; - bodyDef.position = p; - b2Body* body = m_world->CreateBody(&bodyDef); - - b2PolygonShape shape; - shape.SetAsBox(0.25f * a, a); - body->CreateFixture(&shape, density); - - if (depth == e_depth) - { - return body; - } - - shape.SetAsBox(offset, 0.25f * a, b2Vec2(0, -a), 0.0f); - body->CreateFixture(&shape, density); - - b2Vec2 a1 = b2Vec2(offset, -a); - b2Vec2 a2 = b2Vec2(-offset, -a); - b2Body* body1 = AddNode(body, a1, depth + 1, 0.5f * offset, a); - b2Body* body2 = AddNode(body, a2, depth + 1, 0.5f * offset, a); - - b2RevoluteJointDef jointDef; - jointDef.bodyA = body; - jointDef.localAnchorB = h; - - jointDef.localAnchorA = a1; - jointDef.bodyB = body1; - m_world->CreateJoint(&jointDef); - - jointDef.localAnchorA = a2; - jointDef.bodyB = body2; - m_world->CreateJoint(&jointDef); - - return body; - } - - static Test* Create() - { - return new MobileBalanced; - } + enum + { + e_depth = 4 + }; + + MobileBalanced() + { + b2Body* ground; + + // Create ground body. + { + b2BodyDef bodyDef; + bodyDef.position.Set(0.0f, 20.0f); + ground = m_world->CreateBody(&bodyDef); + } + + float a = 0.5f; + b2Vec2 h(0.0f, a); + + b2Body* root = AddNode(ground, b2Vec2_zero, 0, 3.0f, a); + + b2RevoluteJointDef jointDef; + jointDef.bodyA = ground; + jointDef.bodyB = root; + jointDef.localAnchorA.SetZero(); + jointDef.localAnchorB = h; + m_world->CreateJoint(&jointDef); + } + + b2Body* AddNode(b2Body* parent, const b2Vec2& localAnchor, int32 depth, float offset, float a) + { + float density = 20.0f; + b2Vec2 h(0.0f, a); + + b2Vec2 p = parent->GetPosition() + localAnchor - h; + + b2BodyDef bodyDef; + bodyDef.type = b2_dynamicBody; + bodyDef.position = p; + b2Body* body = m_world->CreateBody(&bodyDef); + + b2PolygonShape shape; + shape.SetAsBox(0.25f * a, a); + body->CreateFixture(&shape, density); + + if (depth == e_depth) + { + return body; + } + + shape.SetAsBox(offset, 0.25f * a, b2Vec2(0, -a), 0.0f); + body->CreateFixture(&shape, density); + + b2Vec2 a1 = b2Vec2(offset, -a); + b2Vec2 a2 = b2Vec2(-offset, -a); + b2Body* body1 = AddNode(body, a1, depth + 1, 0.5f * offset, a); + b2Body* body2 = AddNode(body, a2, depth + 1, 0.5f * offset, a); + + b2RevoluteJointDef jointDef; + jointDef.bodyA = body; + jointDef.localAnchorB = h; + + jointDef.localAnchorA = a1; + jointDef.bodyB = body1; + m_world->CreateJoint(&jointDef); + + jointDef.localAnchorA = a2; + jointDef.bodyB = body2; + m_world->CreateJoint(&jointDef); + + return body; + } + + static Test* Create() { return new MobileBalanced; } }; static int testIndex = RegisterTest("Solver", "Mobile Balanced", MobileBalanced::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/mobile_unbalanced.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/mobile_unbalanced.cpp index 5f62fb6ebf6f..6d95738e5443 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/mobile_unbalanced.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/mobile_unbalanced.cpp @@ -25,81 +25,77 @@ class MobileUnbalanced : public Test { public: - - enum - { - e_depth = 4 - }; - - MobileUnbalanced() - { - b2Body* ground; - - // Create ground body. - { - b2BodyDef bodyDef; - bodyDef.position.Set(0.0f, 20.0f); - ground = m_world->CreateBody(&bodyDef); - } - - float a = 0.5f; - b2Vec2 h(0.0f, a); - - b2Body* root = AddNode(ground, b2Vec2_zero, 0, 3.0f, a); - - b2RevoluteJointDef jointDef; - jointDef.bodyA = ground; - jointDef.bodyB = root; - jointDef.localAnchorA.SetZero(); - jointDef.localAnchorB = h; - m_world->CreateJoint(&jointDef); - } - - b2Body* AddNode(b2Body* parent, const b2Vec2& localAnchor, int32 depth, float offset, float a) - { - float density = 20.0f; - b2Vec2 h(0.0f, a); - - b2Vec2 p = parent->GetPosition() + localAnchor - h; - - b2BodyDef bodyDef; - bodyDef.type = b2_dynamicBody; - bodyDef.position = p; - b2Body* body = m_world->CreateBody(&bodyDef); - - b2PolygonShape shape; - shape.SetAsBox(0.25f * a, a); - body->CreateFixture(&shape, density); - - if (depth == e_depth) - { - return body; - } - - b2Vec2 a1 = b2Vec2(offset, -a); - b2Vec2 a2 = b2Vec2(-offset, -a); - b2Body* body1 = AddNode(body, a1, depth + 1, 0.5f * offset, a); - b2Body* body2 = AddNode(body, a2, depth + 1, 0.5f * offset, a); - - b2RevoluteJointDef jointDef; - jointDef.bodyA = body; - jointDef.localAnchorB = h; - - jointDef.localAnchorA = a1; - jointDef.bodyB = body1; - m_world->CreateJoint(&jointDef); - - jointDef.localAnchorA = a2; - jointDef.bodyB = body2; - m_world->CreateJoint(&jointDef); - - return body; - } - - static Test* Create() - { - return new MobileUnbalanced; - } + enum + { + e_depth = 4 + }; + + MobileUnbalanced() + { + b2Body* ground; + + // Create ground body. + { + b2BodyDef bodyDef; + bodyDef.position.Set(0.0f, 20.0f); + ground = m_world->CreateBody(&bodyDef); + } + + float a = 0.5f; + b2Vec2 h(0.0f, a); + + b2Body* root = AddNode(ground, b2Vec2_zero, 0, 3.0f, a); + + b2RevoluteJointDef jointDef; + jointDef.bodyA = ground; + jointDef.bodyB = root; + jointDef.localAnchorA.SetZero(); + jointDef.localAnchorB = h; + m_world->CreateJoint(&jointDef); + } + + b2Body* AddNode(b2Body* parent, const b2Vec2& localAnchor, int32 depth, float offset, float a) + { + float density = 20.0f; + b2Vec2 h(0.0f, a); + + b2Vec2 p = parent->GetPosition() + localAnchor - h; + + b2BodyDef bodyDef; + bodyDef.type = b2_dynamicBody; + bodyDef.position = p; + b2Body* body = m_world->CreateBody(&bodyDef); + + b2PolygonShape shape; + shape.SetAsBox(0.25f * a, a); + body->CreateFixture(&shape, density); + + if (depth == e_depth) + { + return body; + } + + b2Vec2 a1 = b2Vec2(offset, -a); + b2Vec2 a2 = b2Vec2(-offset, -a); + b2Body* body1 = AddNode(body, a1, depth + 1, 0.5f * offset, a); + b2Body* body2 = AddNode(body, a2, depth + 1, 0.5f * offset, a); + + b2RevoluteJointDef jointDef; + jointDef.bodyA = body; + jointDef.localAnchorB = h; + + jointDef.localAnchorA = a1; + jointDef.bodyB = body1; + m_world->CreateJoint(&jointDef); + + jointDef.localAnchorA = a2; + jointDef.bodyB = body2; + m_world->CreateJoint(&jointDef); + + return body; + } + + static Test* Create() { return new MobileUnbalanced; } }; static int testIndex = RegisterTest("Solver", "Mobile Unbalanced", MobileUnbalanced::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/motor_joint.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/motor_joint.cpp index a7b0156e9bc8..1b4873ad0eda 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/motor_joint.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/motor_joint.cpp @@ -29,90 +29,87 @@ class MotorJoint : public Test { public: - MotorJoint() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); - - b2FixtureDef fd; - fd.shape = &shape; - - ground->CreateFixture(&fd); - } - - // Define motorized body - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 8.0f); - b2Body* body = m_world->CreateBody(&bd); - - b2PolygonShape shape; - shape.SetAsBox(2.0f, 0.5f); - - b2FixtureDef fd; - fd.shape = &shape; - fd.friction = 0.6f; - fd.density = 2.0f; - body->CreateFixture(&fd); - - b2MotorJointDef mjd; - mjd.Initialize(ground, body); - mjd.maxForce = 1000.0f; - mjd.maxTorque = 1000.0f; - m_joint = (b2MotorJoint*)m_world->CreateJoint(&mjd); - } - - m_go = false; - m_time = 0.0f; - } - - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_S: - m_go = !m_go; - break; - } - } - - void Step(Settings& settings) override - { - if (m_go && settings.m_hertz > 0.0f) - { - m_time += 1.0f / settings.m_hertz; - } - - b2Vec2 linearOffset; - linearOffset.x = 6.0f * sinf(2.0f * m_time); - linearOffset.y = 8.0f + 4.0f * sinf(1.0f * m_time); - - float angularOffset = 4.0f * m_time; - - m_joint->SetLinearOffset(linearOffset); - m_joint->SetAngularOffset(angularOffset); - - g_debugDraw.DrawPoint(linearOffset, 4.0f, b2Color(0.9f, 0.9f, 0.9f)); - - Test::Step(settings); - DrawString(5, m_textLine, "Keys: (s) pause"); - m_textLine += 15; - } - - static Test* Create() - { - return new MotorJoint; - } - - b2MotorJoint* m_joint; - float m_time; - bool m_go; + MotorJoint() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); + + b2FixtureDef fd; + fd.shape = &shape; + + ground->CreateFixture(&fd); + } + + // Define motorized body + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 8.0f); + b2Body* body = m_world->CreateBody(&bd); + + b2PolygonShape shape; + shape.SetAsBox(2.0f, 0.5f); + + b2FixtureDef fd; + fd.shape = &shape; + fd.friction = 0.6f; + fd.density = 2.0f; + body->CreateFixture(&fd); + + b2MotorJointDef mjd; + mjd.Initialize(ground, body); + mjd.maxForce = 1000.0f; + mjd.maxTorque = 1000.0f; + m_joint = (b2MotorJoint*)m_world->CreateJoint(&mjd); + } + + m_go = false; + m_time = 0.0f; + } + + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_S: + m_go = !m_go; + break; + } + } + + void Step(Settings& settings) override + { + if (m_go && settings.m_hertz > 0.0f) + { + m_time += 1.0f / settings.m_hertz; + } + + b2Vec2 linearOffset; + linearOffset.x = 6.0f * sinf(2.0f * m_time); + linearOffset.y = 8.0f + 4.0f * sinf(1.0f * m_time); + + float angularOffset = 4.0f * m_time; + + m_joint->SetLinearOffset(linearOffset); + m_joint->SetAngularOffset(angularOffset); + + g_debugDraw.DrawPoint(linearOffset, 4.0f, b2Color(0.9f, 0.9f, 0.9f)); + + Test::Step(settings); + DrawString(5, m_textLine, "Keys: (s) pause"); + m_textLine += 15; + } + + static Test* Create() { return new MotorJoint; } + + b2MotorJoint* m_joint; + float m_time; + bool m_go; }; static int testIndex = RegisterTest("Joints", "Motor Joint", MotorJoint::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/pinball.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/pinball.cpp index c7dca48db498..1c117de53c0e 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/pinball.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/pinball.cpp @@ -27,144 +27,139 @@ class Pinball : public Test { public: - Pinball() - { - // Ground body - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); - - b2Vec2 vs[5]; - vs[0].Set(-8.0f, 6.0f); - vs[1].Set(-8.0f, 20.0f); - vs[2].Set(8.0f, 20.0f); - vs[3].Set(8.0f, 6.0f); - vs[4].Set(0.0f, -2.0f); - - b2ChainShape loop; - loop.CreateLoop(vs, 5); - b2FixtureDef fd; - fd.shape = &loop; - fd.density = 0.0f; - ground->CreateFixture(&fd); - } - - // Flippers - { - b2Vec2 p1(-2.0f, 0.0f), p2(2.0f, 0.0f); - - b2BodyDef bd; - bd.type = b2_dynamicBody; - - bd.position = p1; - b2Body* leftFlipper = m_world->CreateBody(&bd); - - bd.position = p2; - b2Body* rightFlipper = m_world->CreateBody(&bd); - - b2PolygonShape box; - box.SetAsBox(1.75f, 0.1f); - - b2FixtureDef fd; - fd.shape = &box; - fd.density = 1.0f; - - leftFlipper->CreateFixture(&fd); - rightFlipper->CreateFixture(&fd); - - b2RevoluteJointDef jd; - jd.bodyA = ground; - jd.localAnchorB.SetZero(); - jd.enableMotor = true; - jd.maxMotorTorque = 1000.0f; - jd.enableLimit = true; - - jd.motorSpeed = 0.0f; - jd.localAnchorA = p1; - jd.bodyB = leftFlipper; - jd.lowerAngle = -30.0f * b2_pi / 180.0f; - jd.upperAngle = 5.0f * b2_pi / 180.0f; - m_leftJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); - - jd.motorSpeed = 0.0f; - jd.localAnchorA = p2; - jd.bodyB = rightFlipper; - jd.lowerAngle = -5.0f * b2_pi / 180.0f; - jd.upperAngle = 30.0f * b2_pi / 180.0f; - m_rightJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); - } - - // Circle character - { - b2BodyDef bd; - bd.position.Set(1.0f, 15.0f); - bd.type = b2_dynamicBody; - bd.bullet = true; - - m_ball = m_world->CreateBody(&bd); - - b2CircleShape shape; - shape.m_radius = 0.2f; - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - m_ball->CreateFixture(&fd); - } - - m_button = false; - } - - void Step(Settings& settings) override - { - if (m_button) - { - m_leftJoint->SetMotorSpeed(20.0f); - m_rightJoint->SetMotorSpeed(-20.0f); - } - else - { - m_leftJoint->SetMotorSpeed(-10.0f); - m_rightJoint->SetMotorSpeed(10.0f); - } - - Test::Step(settings); - - DrawString(5, m_textLine, "Press 'a' to control the flippers"); - - - } - - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_A: - m_button = true; - break; - } - } - - void KeyboardUp(int key) override - { - switch (key) - { - case GLFW_KEY_A: - m_button = false; - break; - } - } - - static Test* Create() - { - return new Pinball; - } - - b2RevoluteJoint* m_leftJoint; - b2RevoluteJoint* m_rightJoint; - b2Body* m_ball; - bool m_button; + Pinball() + { + // Ground body + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + + b2Vec2 vs[5]; + vs[0].Set(-8.0f, 6.0f); + vs[1].Set(-8.0f, 20.0f); + vs[2].Set(8.0f, 20.0f); + vs[3].Set(8.0f, 6.0f); + vs[4].Set(0.0f, -2.0f); + + b2ChainShape loop; + loop.CreateLoop(vs, 5); + b2FixtureDef fd; + fd.shape = &loop; + fd.density = 0.0f; + ground->CreateFixture(&fd); + } + + // Flippers + { + b2Vec2 p1(-2.0f, 0.0f), p2(2.0f, 0.0f); + + b2BodyDef bd; + bd.type = b2_dynamicBody; + + bd.position = p1; + b2Body* leftFlipper = m_world->CreateBody(&bd); + + bd.position = p2; + b2Body* rightFlipper = m_world->CreateBody(&bd); + + b2PolygonShape box; + box.SetAsBox(1.75f, 0.1f); + + b2FixtureDef fd; + fd.shape = &box; + fd.density = 1.0f; + + leftFlipper->CreateFixture(&fd); + rightFlipper->CreateFixture(&fd); + + b2RevoluteJointDef jd; + jd.bodyA = ground; + jd.localAnchorB.SetZero(); + jd.enableMotor = true; + jd.maxMotorTorque = 1000.0f; + jd.enableLimit = true; + + jd.motorSpeed = 0.0f; + jd.localAnchorA = p1; + jd.bodyB = leftFlipper; + jd.lowerAngle = -30.0f * b2_pi / 180.0f; + jd.upperAngle = 5.0f * b2_pi / 180.0f; + m_leftJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); + + jd.motorSpeed = 0.0f; + jd.localAnchorA = p2; + jd.bodyB = rightFlipper; + jd.lowerAngle = -5.0f * b2_pi / 180.0f; + jd.upperAngle = 30.0f * b2_pi / 180.0f; + m_rightJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); + } + + // Circle character + { + b2BodyDef bd; + bd.position.Set(1.0f, 15.0f); + bd.type = b2_dynamicBody; + bd.bullet = true; + + m_ball = m_world->CreateBody(&bd); + + b2CircleShape shape; + shape.m_radius = 0.2f; + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + m_ball->CreateFixture(&fd); + } + + m_button = false; + } + + void Step(Settings& settings) override + { + if (m_button) + { + m_leftJoint->SetMotorSpeed(20.0f); + m_rightJoint->SetMotorSpeed(-20.0f); + } + else + { + m_leftJoint->SetMotorSpeed(-10.0f); + m_rightJoint->SetMotorSpeed(10.0f); + } + + Test::Step(settings); + + DrawString(5, m_textLine, "Press 'a' to control the flippers"); + } + + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_A: + m_button = true; + break; + } + } + + void KeyboardUp(int key) override + { + switch (key) + { + case GLFW_KEY_A: + m_button = false; + break; + } + } + + static Test* Create() { return new Pinball; } + + b2RevoluteJoint* m_leftJoint; + b2RevoluteJoint* m_rightJoint; + b2Body* m_ball; + bool m_button; }; static int testIndex = RegisterTest("Examples", "Pinball", Pinball::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/platformer.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/platformer.cpp index 18b39b8a7ef7..c308f4922bac 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/platformer.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/platformer.cpp @@ -25,109 +25,104 @@ class Platformer : public Test { public: + enum State + { + e_unknown, + e_above, + e_below + }; + + Platformer() + { + // Ground + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + // Platform + { + b2BodyDef bd; + bd.position.Set(0.0f, 10.0f); + b2Body* body = m_world->CreateBody(&bd); + + b2PolygonShape shape; + shape.SetAsBox(3.0f, 0.5f); + m_platform = body->CreateFixture(&shape, 0.0f); + + m_bottom = 10.0f - 0.5f; + m_top = 10.0f + 0.5f; + } + + // Actor + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 12.0f); + b2Body* body = m_world->CreateBody(&bd); + + m_radius = 0.5f; + b2CircleShape shape; + shape.m_radius = m_radius; + m_character = body->CreateFixture(&shape, 20.0f); + + body->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); + + m_state = e_unknown; + } + } - enum State - { - e_unknown, - e_above, - e_below - }; - - Platformer() - { - // Ground - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - // Platform - { - b2BodyDef bd; - bd.position.Set(0.0f, 10.0f); - b2Body* body = m_world->CreateBody(&bd); - - b2PolygonShape shape; - shape.SetAsBox(3.0f, 0.5f); - m_platform = body->CreateFixture(&shape, 0.0f); - - m_bottom = 10.0f - 0.5f; - m_top = 10.0f + 0.5f; - } - - // Actor - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 12.0f); - b2Body* body = m_world->CreateBody(&bd); - - m_radius = 0.5f; - b2CircleShape shape; - shape.m_radius = m_radius; - m_character = body->CreateFixture(&shape, 20.0f); - - body->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); - - m_state = e_unknown; - } - } - - void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override - { - Test::PreSolve(contact, oldManifold); - - b2Fixture* fixtureA = contact->GetFixtureA(); - b2Fixture* fixtureB = contact->GetFixtureB(); - - if (fixtureA != m_platform && fixtureA != m_character) - { - return; - } - - if (fixtureB != m_platform && fixtureB != m_character) - { - return; - } + void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override + { + Test::PreSolve(contact, oldManifold); + + b2Fixture* fixtureA = contact->GetFixtureA(); + b2Fixture* fixtureB = contact->GetFixtureB(); + + if (fixtureA != m_platform && fixtureA != m_character) + { + return; + } + + if (fixtureB != m_platform && fixtureB != m_character) + { + return; + } #if 1 - b2Vec2 position = m_character->GetBody()->GetPosition(); + b2Vec2 position = m_character->GetBody()->GetPosition(); - if (position.y < m_top + m_radius - 3.0f * b2_linearSlop) - { - contact->SetEnabled(false); - } + if (position.y < m_top + m_radius - 3.0f * b2_linearSlop) + { + contact->SetEnabled(false); + } #else b2Vec2 v = m_character->GetBody()->GetLinearVelocity(); if (v.y > 0.0f) - { + { contact->SetEnabled(false); } #endif - } + } - void Step(Settings& settings) override - { - Test::Step(settings); + void Step(Settings& settings) override + { + Test::Step(settings); - b2Vec2 v = m_character->GetBody()->GetLinearVelocity(); + b2Vec2 v = m_character->GetBody()->GetLinearVelocity(); DrawString(5, m_textLine, "Character Linear Velocity: %f", v.y); - - } - - static Test* Create() - { - return new Platformer; - } - - float m_radius, m_top, m_bottom; - State m_state; - b2Fixture* m_platform; - b2Fixture* m_character; + } + + static Test* Create() { return new Platformer; } + + float m_radius, m_top, m_bottom; + State m_state; + b2Fixture* m_platform; + b2Fixture* m_character; }; static int testIndex = RegisterTest("Examples", "Platformer", Platformer::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/polygon_collision.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/polygon_collision.cpp index 558ad59c2751..dbc924694c2d 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/polygon_collision.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/polygon_collision.cpp @@ -25,103 +25,99 @@ class PolygonCollision : public Test { public: - PolygonCollision() - { - { - m_polygonA.SetAsBox(0.2f, 0.4f); - m_transformA.Set(b2Vec2(0.0f, 0.0f), 0.0f); - } - - { - m_polygonB.SetAsBox(0.5f, 0.5f); - m_positionB.Set(19.345284f, 1.5632932f); - m_angleB = 1.9160721f; - m_transformB.Set(m_positionB, m_angleB); - } - } - - static Test* Create() - { - return new PolygonCollision; - } - - void Step(Settings& settings) override - { - B2_NOT_USED(settings); - - b2Manifold manifold; - b2CollidePolygons(&manifold, &m_polygonA, m_transformA, &m_polygonB, m_transformB); - - b2WorldManifold worldManifold; - worldManifold.Initialize(&manifold, m_transformA, m_polygonA.m_radius, m_transformB, m_polygonB.m_radius); - - DrawString(5, m_textLine, "point count = %d", manifold.pointCount); - - - { - b2Color color(0.9f, 0.9f, 0.9f); - b2Vec2 v[b2_maxPolygonVertices]; - for (int32 i = 0; i < m_polygonA.m_count; ++i) - { - v[i] = b2Mul(m_transformA, m_polygonA.m_vertices[i]); - } - g_debugDraw.DrawPolygon(v, m_polygonA.m_count, color); - - for (int32 i = 0; i < m_polygonB.m_count; ++i) - { - v[i] = b2Mul(m_transformB, m_polygonB.m_vertices[i]); - } - g_debugDraw.DrawPolygon(v, m_polygonB.m_count, color); - } - - for (int32 i = 0; i < manifold.pointCount; ++i) - { - g_debugDraw.DrawPoint(worldManifold.points[i], 4.0f, b2Color(0.9f, 0.3f, 0.3f)); - } - - Test::Step(settings); - } - - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_A: - m_positionB.x -= 0.1f; - break; - - case GLFW_KEY_D: - m_positionB.x += 0.1f; - break; - - case GLFW_KEY_S: - m_positionB.y -= 0.1f; - break; - - case GLFW_KEY_W: - m_positionB.y += 0.1f; - break; - - case GLFW_KEY_Q: - m_angleB += 0.1f * b2_pi; - break; - - case GLFW_KEY_E: - m_angleB -= 0.1f * b2_pi; - break; - } - - m_transformB.Set(m_positionB, m_angleB); - } - - b2PolygonShape m_polygonA; - b2PolygonShape m_polygonB; - - b2Transform m_transformA; - b2Transform m_transformB; - - b2Vec2 m_positionB; - float m_angleB; + PolygonCollision() + { + { + m_polygonA.SetAsBox(0.2f, 0.4f); + m_transformA.Set(b2Vec2(0.0f, 0.0f), 0.0f); + } + + { + m_polygonB.SetAsBox(0.5f, 0.5f); + m_positionB.Set(19.345284f, 1.5632932f); + m_angleB = 1.9160721f; + m_transformB.Set(m_positionB, m_angleB); + } + } + + static Test* Create() { return new PolygonCollision; } + + void Step(Settings& settings) override + { + B2_NOT_USED(settings); + + b2Manifold manifold; + b2CollidePolygons(&manifold, &m_polygonA, m_transformA, &m_polygonB, m_transformB); + + b2WorldManifold worldManifold; + worldManifold.Initialize(&manifold, m_transformA, m_polygonA.m_radius, m_transformB, m_polygonB.m_radius); + + DrawString(5, m_textLine, "point count = %d", manifold.pointCount); + + { + b2Color color(0.9f, 0.9f, 0.9f); + b2Vec2 v[b2_maxPolygonVertices]; + for (int32 i = 0; i < m_polygonA.m_count; ++i) + { + v[i] = b2Mul(m_transformA, m_polygonA.m_vertices[i]); + } + g_debugDraw.DrawPolygon(v, m_polygonA.m_count, color); + + for (int32 i = 0; i < m_polygonB.m_count; ++i) + { + v[i] = b2Mul(m_transformB, m_polygonB.m_vertices[i]); + } + g_debugDraw.DrawPolygon(v, m_polygonB.m_count, color); + } + + for (int32 i = 0; i < manifold.pointCount; ++i) + { + g_debugDraw.DrawPoint(worldManifold.points[i], 4.0f, b2Color(0.9f, 0.3f, 0.3f)); + } + + Test::Step(settings); + } + + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_A: + m_positionB.x -= 0.1f; + break; + + case GLFW_KEY_D: + m_positionB.x += 0.1f; + break; + + case GLFW_KEY_S: + m_positionB.y -= 0.1f; + break; + + case GLFW_KEY_W: + m_positionB.y += 0.1f; + break; + + case GLFW_KEY_Q: + m_angleB += 0.1f * b2_pi; + break; + + case GLFW_KEY_E: + m_angleB -= 0.1f * b2_pi; + break; + } + + m_transformB.Set(m_positionB, m_angleB); + } + + b2PolygonShape m_polygonA; + b2PolygonShape m_polygonB; + + b2Transform m_transformA; + b2Transform m_transformB; + + b2Vec2 m_positionB; + float m_angleB; }; static int testIndex = RegisterTest("Geometry", "Polygon Collision", PolygonCollision::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/polygon_shapes.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/polygon_shapes.cpp index 2fa4c1cbc699..369f777ee85c 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/polygon_shapes.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/polygon_shapes.cpp @@ -31,235 +31,227 @@ class PolygonShapesCallback : public b2QueryCallback { public: - - enum - { - e_maxCount = 4 - }; - - PolygonShapesCallback() - { - m_count = 0; - } - - /// Called for each fixture found in the query AABB. - /// @return false to terminate the query. - bool ReportFixture(b2Fixture* fixture) override - { - if (m_count == e_maxCount) - { - return false; - } - - b2Body* body = fixture->GetBody(); - b2Shape* shape = fixture->GetShape(); - - bool overlap = b2TestOverlap(shape, 0, &m_circle, 0, body->GetTransform(), m_transform); - - if (overlap) - { - b2Color color(0.95f, 0.95f, 0.6f); - b2Vec2 center = body->GetWorldCenter(); - g_debugDraw->DrawPoint(center, 5.0f, color); - ++m_count; - } - - return true; - } - - b2CircleShape m_circle; - b2Transform m_transform; - b2Draw* g_debugDraw; - int32 m_count; + enum + { + e_maxCount = 4 + }; + + PolygonShapesCallback() { m_count = 0; } + + /// Called for each fixture found in the query AABB. + /// @return false to terminate the query. + bool ReportFixture(b2Fixture* fixture) override + { + if (m_count == e_maxCount) + { + return false; + } + + b2Body* body = fixture->GetBody(); + b2Shape* shape = fixture->GetShape(); + + bool overlap = b2TestOverlap(shape, 0, &m_circle, 0, body->GetTransform(), m_transform); + + if (overlap) + { + b2Color color(0.95f, 0.95f, 0.6f); + b2Vec2 center = body->GetWorldCenter(); + g_debugDraw->DrawPoint(center, 5.0f, color); + ++m_count; + } + + return true; + } + + b2CircleShape m_circle; + b2Transform m_transform; + b2Draw* g_debugDraw; + int32 m_count; }; class PolygonShapes : public Test { public: - - enum - { - e_maxBodies = 256 - }; - - PolygonShapes() - { - // Ground body - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.5f, 0.0f); - vertices[1].Set(0.5f, 0.0f); - vertices[2].Set(0.0f, 1.5f); - m_polygons[0].Set(vertices, 3); - } - - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.1f, 0.0f); - vertices[1].Set(0.1f, 0.0f); - vertices[2].Set(0.0f, 1.5f); - m_polygons[1].Set(vertices, 3); - } - - { - float w = 1.0f; - float b = w / (2.0f + b2Sqrt(2.0f)); - float s = b2Sqrt(2.0f) * b; - - b2Vec2 vertices[8]; - vertices[0].Set(0.5f * s, 0.0f); - vertices[1].Set(0.5f * w, b); - vertices[2].Set(0.5f * w, b + s); - vertices[3].Set(0.5f * s, w); - vertices[4].Set(-0.5f * s, w); - vertices[5].Set(-0.5f * w, b + s); - vertices[6].Set(-0.5f * w, b); - vertices[7].Set(-0.5f * s, 0.0f); - - m_polygons[2].Set(vertices, 8); - } - - { - m_polygons[3].SetAsBox(0.5f, 0.5f); - } - - { - m_circle.m_radius = 0.5f; - } - - m_bodyIndex = 0; - memset(m_bodies, 0, sizeof(m_bodies)); - } - - void Create(int32 index) - { - if (m_bodies[m_bodyIndex] != NULL) - { - m_world->DestroyBody(m_bodies[m_bodyIndex]); - m_bodies[m_bodyIndex] = NULL; - } - - b2BodyDef bd; - bd.type = b2_dynamicBody; - - float x = RandomFloat(-2.0f, 2.0f); - bd.position.Set(x, 10.0f); - bd.angle = RandomFloat(-b2_pi, b2_pi); - - if (index == 4) - { - bd.angularDamping = 0.02f; - } - - m_bodies[m_bodyIndex] = m_world->CreateBody(&bd); - - if (index < 4) - { - b2FixtureDef fd; - fd.shape = m_polygons + index; - fd.density = 1.0f; - fd.friction = 0.3f; - m_bodies[m_bodyIndex]->CreateFixture(&fd); - } - else - { - b2FixtureDef fd; - fd.shape = &m_circle; - fd.density = 1.0f; - fd.friction = 0.3f; - - m_bodies[m_bodyIndex]->CreateFixture(&fd); - } - - m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; - } - - void DestroyBody() - { - for (int32 i = 0; i < e_maxBodies; ++i) - { - if (m_bodies[i] != NULL) - { - m_world->DestroyBody(m_bodies[i]); - m_bodies[i] = NULL; - return; - } - } - } - - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_1: - case GLFW_KEY_2: - case GLFW_KEY_3: - case GLFW_KEY_4: - case GLFW_KEY_5: - Create(key - GLFW_KEY_1); - break; - - case GLFW_KEY_A: - for (int32 i = 0; i < e_maxBodies; i += 2) - { - if (m_bodies[i]) - { - bool enabled = m_bodies[i]->IsEnabled(); - m_bodies[i]->SetEnabled(!enabled); - } - } - break; - - case GLFW_KEY_D: - DestroyBody(); - break; - } - } - - void Step(Settings& settings) override - { - Test::Step(settings); - - PolygonShapesCallback callback; - callback.m_circle.m_radius = 2.0f; - callback.m_circle.m_p.Set(0.0f, 1.1f); - callback.m_transform.SetIdentity(); - callback.g_debugDraw = &g_debugDraw; - - b2AABB aabb; - callback.m_circle.ComputeAABB(&aabb, callback.m_transform, 0); - - m_world->QueryAABB(&callback, aabb); - - b2Color color(0.4f, 0.7f, 0.8f); - g_debugDraw.DrawCircle(callback.m_circle.m_p, callback.m_circle.m_radius, color); - - DrawString(5, m_textLine, "Press 1-5 to drop stuff, maximum of %d overlaps detected", PolygonShapesCallback::e_maxCount); - - DrawString(5, m_textLine, "Press 'a' to enable/disable some bodies"); - - DrawString(5, m_textLine, "Press 'd' to destroy a body"); - - } - - static Test* Create() - { - return new PolygonShapes; - } - - int32 m_bodyIndex; - b2Body* m_bodies[e_maxBodies]; - b2PolygonShape m_polygons[4]; - b2CircleShape m_circle; + enum + { + e_maxBodies = 256 + }; + + PolygonShapes() + { + // Ground body + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.5f, 0.0f); + vertices[1].Set(0.5f, 0.0f); + vertices[2].Set(0.0f, 1.5f); + m_polygons[0].Set(vertices, 3); + } + + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.1f, 0.0f); + vertices[1].Set(0.1f, 0.0f); + vertices[2].Set(0.0f, 1.5f); + m_polygons[1].Set(vertices, 3); + } + + { + float w = 1.0f; + float b = w / (2.0f + b2Sqrt(2.0f)); + float s = b2Sqrt(2.0f) * b; + + b2Vec2 vertices[8]; + vertices[0].Set(0.5f * s, 0.0f); + vertices[1].Set(0.5f * w, b); + vertices[2].Set(0.5f * w, b + s); + vertices[3].Set(0.5f * s, w); + vertices[4].Set(-0.5f * s, w); + vertices[5].Set(-0.5f * w, b + s); + vertices[6].Set(-0.5f * w, b); + vertices[7].Set(-0.5f * s, 0.0f); + + m_polygons[2].Set(vertices, 8); + } + + { + m_polygons[3].SetAsBox(0.5f, 0.5f); + } + + { + m_circle.m_radius = 0.5f; + } + + m_bodyIndex = 0; + memset(m_bodies, 0, sizeof(m_bodies)); + } + + void Create(int32 index) + { + if (m_bodies[m_bodyIndex] != NULL) + { + m_world->DestroyBody(m_bodies[m_bodyIndex]); + m_bodies[m_bodyIndex] = NULL; + } + + b2BodyDef bd; + bd.type = b2_dynamicBody; + + float x = RandomFloat(-2.0f, 2.0f); + bd.position.Set(x, 10.0f); + bd.angle = RandomFloat(-b2_pi, b2_pi); + + if (index == 4) + { + bd.angularDamping = 0.02f; + } + + m_bodies[m_bodyIndex] = m_world->CreateBody(&bd); + + if (index < 4) + { + b2FixtureDef fd; + fd.shape = m_polygons + index; + fd.density = 1.0f; + fd.friction = 0.3f; + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } + else + { + b2FixtureDef fd; + fd.shape = &m_circle; + fd.density = 1.0f; + fd.friction = 0.3f; + + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } + + m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; + } + + void DestroyBody() + { + for (int32 i = 0; i < e_maxBodies; ++i) + { + if (m_bodies[i] != NULL) + { + m_world->DestroyBody(m_bodies[i]); + m_bodies[i] = NULL; + return; + } + } + } + + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_1: + case GLFW_KEY_2: + case GLFW_KEY_3: + case GLFW_KEY_4: + case GLFW_KEY_5: + Create(key - GLFW_KEY_1); + break; + + case GLFW_KEY_A: + for (int32 i = 0; i < e_maxBodies; i += 2) + { + if (m_bodies[i]) + { + bool enabled = m_bodies[i]->IsEnabled(); + m_bodies[i]->SetEnabled(!enabled); + } + } + break; + + case GLFW_KEY_D: + DestroyBody(); + break; + } + } + + void Step(Settings& settings) override + { + Test::Step(settings); + + PolygonShapesCallback callback; + callback.m_circle.m_radius = 2.0f; + callback.m_circle.m_p.Set(0.0f, 1.1f); + callback.m_transform.SetIdentity(); + callback.g_debugDraw = &g_debugDraw; + + b2AABB aabb; + callback.m_circle.ComputeAABB(&aabb, callback.m_transform, 0); + + m_world->QueryAABB(&callback, aabb); + + b2Color color(0.4f, 0.7f, 0.8f); + g_debugDraw.DrawCircle(callback.m_circle.m_p, callback.m_circle.m_radius, color); + + DrawString(5, m_textLine, "Press 1-5 to drop stuff, maximum of %d overlaps detected", + PolygonShapesCallback::e_maxCount); + + DrawString(5, m_textLine, "Press 'a' to enable/disable some bodies"); + + DrawString(5, m_textLine, "Press 'd' to destroy a body"); + } + + static Test* Create() { return new PolygonShapes; } + + int32 m_bodyIndex; + b2Body* m_bodies[e_maxBodies]; + b2PolygonShape m_polygons[4]; + b2CircleShape m_circle; }; static int testIndex = RegisterTest("Geometry", "Polygon Shapes", PolygonShapes::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/prismatic_joint.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/prismatic_joint.cpp index b63d6c5f9260..d078c31b8ee1 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/prismatic_joint.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/prismatic_joint.cpp @@ -28,91 +28,87 @@ class PrismaticJoint : public Test { public: - PrismaticJoint() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - m_enableLimit = true; - m_enableMotor = false; - m_motorSpeed = 10.0f; - - { - b2PolygonShape shape; - shape.SetAsBox(1.0f, 1.0f); - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 10.0f); - bd.angle = 0.5f * b2_pi; - bd.allowSleep = false; - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 5.0f); - - b2PrismaticJointDef pjd; - - // Horizontal - pjd.Initialize(ground, body, bd.position, b2Vec2(1.0f, 0.0f)); - - pjd.motorSpeed = m_motorSpeed; - pjd.maxMotorForce = 10000.0f; - pjd.enableMotor = m_enableMotor; - pjd.lowerTranslation = -10.0f; - pjd.upperTranslation = 10.0f; - pjd.enableLimit = m_enableLimit; - - m_joint = (b2PrismaticJoint*)m_world->CreateJoint(&pjd); - } - } - - void UpdateUI() override - { - //ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); - ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); - ImGui::Begin("Joint Controls", nullptr, ImGuiWindowFlags_NoResize); - - if (ImGui::Checkbox("Limit", &m_enableLimit)) - { - m_joint->EnableLimit(m_enableLimit); - } - - if (ImGui::Checkbox("Motor", &m_enableMotor)) - { - m_joint->EnableMotor(m_enableMotor); - } - - if (ImGui::SliderFloat("Speed", &m_motorSpeed, -100.0f, 100.0f, "%.0f")) - { - m_joint->SetMotorSpeed(m_motorSpeed); - } - - ImGui::End(); - } - - void Step(Settings& settings) override - { - Test::Step(settings); - float force = m_joint->GetMotorForce(settings.m_hertz); - DrawString(5, m_textLine, "Motor Force = %4.0f", force); - - } - - static Test* Create() - { - return new PrismaticJoint; - } - - b2PrismaticJoint* m_joint; - float m_motorSpeed; - bool m_enableMotor; - bool m_enableLimit; + PrismaticJoint() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + m_enableLimit = true; + m_enableMotor = false; + m_motorSpeed = 10.0f; + + { + b2PolygonShape shape; + shape.SetAsBox(1.0f, 1.0f); + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 10.0f); + bd.angle = 0.5f * b2_pi; + bd.allowSleep = false; + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 5.0f); + + b2PrismaticJointDef pjd; + + // Horizontal + pjd.Initialize(ground, body, bd.position, b2Vec2(1.0f, 0.0f)); + + pjd.motorSpeed = m_motorSpeed; + pjd.maxMotorForce = 10000.0f; + pjd.enableMotor = m_enableMotor; + pjd.lowerTranslation = -10.0f; + pjd.upperTranslation = 10.0f; + pjd.enableLimit = m_enableLimit; + + m_joint = (b2PrismaticJoint*)m_world->CreateJoint(&pjd); + } + } + + void UpdateUI() override + { + // ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); + ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); + ImGui::Begin("Joint Controls", nullptr, ImGuiWindowFlags_NoResize); + + if (ImGui::Checkbox("Limit", &m_enableLimit)) + { + m_joint->EnableLimit(m_enableLimit); + } + + if (ImGui::Checkbox("Motor", &m_enableMotor)) + { + m_joint->EnableMotor(m_enableMotor); + } + + if (ImGui::SliderFloat("Speed", &m_motorSpeed, -100.0f, 100.0f, "%.0f")) + { + m_joint->SetMotorSpeed(m_motorSpeed); + } + + ImGui::End(); + } + + void Step(Settings& settings) override + { + Test::Step(settings); + float force = m_joint->GetMotorForce(settings.m_hertz); + DrawString(5, m_textLine, "Motor Force = %4.0f", force); + } + + static Test* Create() { return new PrismaticJoint; } + + b2PrismaticJoint* m_joint; + float m_motorSpeed; + bool m_enableMotor; + bool m_enableLimit; }; static int testIndex = RegisterTest("Joints", "Prismatic", PrismaticJoint::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/pulley_joint.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/pulley_joint.cpp index 83dcd6e28347..b724673d148a 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/pulley_joint.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/pulley_joint.cpp @@ -25,72 +25,68 @@ class PulleyJoint : public Test { public: - PulleyJoint() - { - float y = 16.0f; - float L = 12.0f; - float a = 1.0f; - float b = 2.0f; - - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); - - b2CircleShape circle; - circle.m_radius = 2.0f; - - circle.m_p.Set(-10.0f, y + b + L); - ground->CreateFixture(&circle, 0.0f); - - circle.m_p.Set(10.0f, y + b + L); - ground->CreateFixture(&circle, 0.0f); - } - - { - - b2PolygonShape shape; - shape.SetAsBox(a, b); - - b2BodyDef bd; - bd.type = b2_dynamicBody; - - //bd.fixedRotation = true; - bd.position.Set(-10.0f, y); - b2Body* body1 = m_world->CreateBody(&bd); - body1->CreateFixture(&shape, 5.0f); - - bd.position.Set(10.0f, y); - b2Body* body2 = m_world->CreateBody(&bd); - body2->CreateFixture(&shape, 5.0f); - - b2PulleyJointDef pulleyDef; - b2Vec2 anchor1(-10.0f, y + b); - b2Vec2 anchor2(10.0f, y + b); - b2Vec2 groundAnchor1(-10.0f, y + b + L); - b2Vec2 groundAnchor2(10.0f, y + b + L); - pulleyDef.Initialize(body1, body2, groundAnchor1, groundAnchor2, anchor1, anchor2, 1.5f); - - m_joint1 = (b2PulleyJoint*)m_world->CreateJoint(&pulleyDef); - } - } - - void Step(Settings& settings) override - { - Test::Step(settings); - - float ratio = m_joint1->GetRatio(); - float L = m_joint1->GetCurrentLengthA() + ratio * m_joint1->GetCurrentLengthB(); - DrawString(5, m_textLine, "L1 + %4.2f * L2 = %4.2f", (float) ratio, (float) L); - - } - - static Test* Create() - { - return new PulleyJoint; - } - - b2PulleyJoint* m_joint1; + PulleyJoint() + { + float y = 16.0f; + float L = 12.0f; + float a = 1.0f; + float b = 2.0f; + + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + + b2CircleShape circle; + circle.m_radius = 2.0f; + + circle.m_p.Set(-10.0f, y + b + L); + ground->CreateFixture(&circle, 0.0f); + + circle.m_p.Set(10.0f, y + b + L); + ground->CreateFixture(&circle, 0.0f); + } + + { + + b2PolygonShape shape; + shape.SetAsBox(a, b); + + b2BodyDef bd; + bd.type = b2_dynamicBody; + + // bd.fixedRotation = true; + bd.position.Set(-10.0f, y); + b2Body* body1 = m_world->CreateBody(&bd); + body1->CreateFixture(&shape, 5.0f); + + bd.position.Set(10.0f, y); + b2Body* body2 = m_world->CreateBody(&bd); + body2->CreateFixture(&shape, 5.0f); + + b2PulleyJointDef pulleyDef; + b2Vec2 anchor1(-10.0f, y + b); + b2Vec2 anchor2(10.0f, y + b); + b2Vec2 groundAnchor1(-10.0f, y + b + L); + b2Vec2 groundAnchor2(10.0f, y + b + L); + pulleyDef.Initialize(body1, body2, groundAnchor1, groundAnchor2, anchor1, anchor2, 1.5f); + + m_joint1 = (b2PulleyJoint*)m_world->CreateJoint(&pulleyDef); + } + } + + void Step(Settings& settings) override + { + Test::Step(settings); + + float ratio = m_joint1->GetRatio(); + float L = m_joint1->GetCurrentLengthA() + ratio * m_joint1->GetCurrentLengthB(); + DrawString(5, m_textLine, "L1 + %4.2f * L2 = %4.2f", (float)ratio, (float)L); + } + + static Test* Create() { return new PulleyJoint; } + + b2PulleyJoint* m_joint1; }; static int testIndex = RegisterTest("Joints", "Pulley", PulleyJoint::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/pyramid.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/pyramid.cpp index ee90d5d01b45..5f527451601a 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/pyramid.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/pyramid.cpp @@ -25,68 +25,65 @@ class Pyramid : public Test { public: - enum - { - e_count = 20 - }; - - Pyramid() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - { - float a = 0.5f; - b2PolygonShape shape; - shape.SetAsBox(a, a); - - b2Vec2 x(-7.0f, 0.75f); - b2Vec2 y; - b2Vec2 deltaX(0.5625f, 1.25f); - b2Vec2 deltaY(1.125f, 0.0f); - - for (int32 i = 0; i < e_count; ++i) - { - y = x; - - for (int32 j = i; j < e_count; ++j) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = y; - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 5.0f); - - y += deltaY; - } - - x += deltaX; - } - } - } - - void Step(Settings& settings) override - { - Test::Step(settings); - - //b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_tree; - - //if (m_stepCount == 400) - //{ - // tree->RebuildBottomUp(); - //} - } - - static Test* Create() - { - return new Pyramid; - } + enum + { + e_count = 20 + }; + + Pyramid() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + { + float a = 0.5f; + b2PolygonShape shape; + shape.SetAsBox(a, a); + + b2Vec2 x(-7.0f, 0.75f); + b2Vec2 y; + b2Vec2 deltaX(0.5625f, 1.25f); + b2Vec2 deltaY(1.125f, 0.0f); + + for (int32 i = 0; i < e_count; ++i) + { + y = x; + + for (int32 j = i; j < e_count; ++j) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = y; + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 5.0f); + + y += deltaY; + } + + x += deltaX; + } + } + } + + void Step(Settings& settings) override + { + Test::Step(settings); + + // b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_tree; + + // if (m_stepCount == 400) + //{ + // tree->RebuildBottomUp(); + // } + } + + static Test* Create() { return new Pyramid; } }; static int testIndex = RegisterTest("Stacking", "Pyramid", Pyramid::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/ray_cast.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/ray_cast.cpp index 4dba339838ee..0f31b5d4c908 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/ray_cast.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/ray_cast.cpp @@ -26,7 +26,7 @@ enum { - e_maxBodies = 256 + e_maxBodies = 256 }; // This test demonstrates how to use the world ray-cast feature. @@ -37,68 +37,62 @@ enum class RayCastClosestCallback : public b2RayCastCallback { public: - RayCastClosestCallback() - { - m_hit = false; - } - - float ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float fraction) override - { - uintptr_t index = fixture->GetUserData().pointer; - if (index == 1) - { - // By returning -1, we instruct the calling code to ignore this fixture and - // continue the ray-cast to the next fixture. - return -1.0f; - } - - m_hit = true; - m_point = point; - m_normal = normal; - - // By returning the current fraction, we instruct the calling code to clip the ray and - // continue the ray-cast to the next fixture. WARNING: do not assume that fixtures - // are reported in order. However, by clipping, we can always get the closest fixture. - return fraction; - } - - bool m_hit; - b2Vec2 m_point; - b2Vec2 m_normal; + RayCastClosestCallback() { m_hit = false; } + + float ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float fraction) override + { + uintptr_t index = fixture->GetUserData().pointer; + if (index == 1) + { + // By returning -1, we instruct the calling code to ignore this fixture and + // continue the ray-cast to the next fixture. + return -1.0f; + } + + m_hit = true; + m_point = point; + m_normal = normal; + + // By returning the current fraction, we instruct the calling code to clip the ray and + // continue the ray-cast to the next fixture. WARNING: do not assume that fixtures + // are reported in order. However, by clipping, we can always get the closest fixture. + return fraction; + } + + bool m_hit; + b2Vec2 m_point; + b2Vec2 m_normal; }; // This callback finds any hit. Polygon 0 is filtered. For this type of query we are usually -// just checking for obstruction, so the actual fixture and hit point are irrelevant. +// just checking for obstruction, so the actual fixture and hit point are irrelevant. class RayCastAnyCallback : public b2RayCastCallback { public: - RayCastAnyCallback() - { - m_hit = false; - } - - float ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float) override - { - uintptr_t index = fixture->GetUserData().pointer; - if (index == 1) - { - // By returning -1, we instruct the calling code to ignore this fixture and - // continue the ray-cast to the next fixture. - return -1.0f; - } - - m_hit = true; - m_point = point; - m_normal = normal; - - // At this point we have a hit, so we know the ray is obstructed. - // By returning 0, we instruct the calling code to terminate the ray-cast. - return 0.0f; - } - - bool m_hit; - b2Vec2 m_point; - b2Vec2 m_normal; + RayCastAnyCallback() { m_hit = false; } + + float ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float) override + { + uintptr_t index = fixture->GetUserData().pointer; + if (index == 1) + { + // By returning -1, we instruct the calling code to ignore this fixture and + // continue the ray-cast to the next fixture. + return -1.0f; + } + + m_hit = true; + m_point = point; + m_normal = normal; + + // At this point we have a hit, so we know the ray is obstructed. + // By returning 0, we instruct the calling code to terminate the ray-cast. + return 0.0f; + } + + bool m_hit; + b2Vec2 m_point; + b2Vec2 m_normal; }; // This ray cast collects multiple hits along the ray. Polygon 0 is filtered. @@ -107,319 +101,312 @@ class RayCastAnyCallback : public b2RayCastCallback class RayCastMultipleCallback : public b2RayCastCallback { public: - enum - { - e_maxCount = 3 - }; - - RayCastMultipleCallback() - { - m_count = 0; - } - - float ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float) override - { - uintptr_t index = fixture->GetUserData().pointer; - if (index == 1) - { - // By returning -1, we instruct the calling code to ignore this fixture and - // continue the ray-cast to the next fixture. - return -1.0f; - } - - b2Assert(m_count < e_maxCount); - - m_points[m_count] = point; - m_normals[m_count] = normal; - ++m_count; - - if (m_count == e_maxCount) - { - // At this point the buffer is full. - // By returning 0, we instruct the calling code to terminate the ray-cast. - return 0.0f; - } - - // By returning 1, we instruct the caller to continue without clipping the ray. - return 1.0f; - } - - b2Vec2 m_points[e_maxCount]; - b2Vec2 m_normals[e_maxCount]; - int32 m_count; + enum + { + e_maxCount = 3 + }; + + RayCastMultipleCallback() { m_count = 0; } + + float ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float) override + { + uintptr_t index = fixture->GetUserData().pointer; + if (index == 1) + { + // By returning -1, we instruct the calling code to ignore this fixture and + // continue the ray-cast to the next fixture. + return -1.0f; + } + + b2Assert(m_count < e_maxCount); + + m_points[m_count] = point; + m_normals[m_count] = normal; + ++m_count; + + if (m_count == e_maxCount) + { + // At this point the buffer is full. + // By returning 0, we instruct the calling code to terminate the ray-cast. + return 0.0f; + } + + // By returning 1, we instruct the caller to continue without clipping the ray. + return 1.0f; + } + + b2Vec2 m_points[e_maxCount]; + b2Vec2 m_normals[e_maxCount]; + int32 m_count; }; - class RayCast : public Test { public: - - enum Mode - { - e_any = 0, - e_closest = 1, - e_multiple = 2 - }; - - RayCast() - { - // Ground body - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.5f, 0.0f); - vertices[1].Set(0.5f, 0.0f); - vertices[2].Set(0.0f, 1.5f); - m_polygons[0].Set(vertices, 3); - } - - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.1f, 0.0f); - vertices[1].Set(0.1f, 0.0f); - vertices[2].Set(0.0f, 1.5f); - m_polygons[1].Set(vertices, 3); - } - - { - float w = 1.0f; - float b = w / (2.0f + b2Sqrt(2.0f)); - float s = b2Sqrt(2.0f) * b; - - b2Vec2 vertices[8]; - vertices[0].Set(0.5f * s, 0.0f); - vertices[1].Set(0.5f * w, b); - vertices[2].Set(0.5f * w, b + s); - vertices[3].Set(0.5f * s, w); - vertices[4].Set(-0.5f * s, w); - vertices[5].Set(-0.5f * w, b + s); - vertices[6].Set(-0.5f * w, b); - vertices[7].Set(-0.5f * s, 0.0f); - - m_polygons[2].Set(vertices, 8); - } - - { - m_polygons[3].SetAsBox(0.5f, 0.5f); - } - - { - m_circle.m_radius = 0.5f; - } - - { - m_edge.SetTwoSided(b2Vec2(-1.0f, 0.0f), b2Vec2(1.0f, 0.0f)); - } - - m_bodyIndex = 0; - memset(m_bodies, 0, sizeof(m_bodies)); - - m_degrees = 0.0f; - - m_mode = e_closest; - } - - void Create(int32 index) - { - if (m_bodies[m_bodyIndex] != NULL) - { - m_world->DestroyBody(m_bodies[m_bodyIndex]); - m_bodies[m_bodyIndex] = NULL; - } - - b2BodyDef bd; - - float x = RandomFloat(-10.0f, 10.0f); - float y = RandomFloat(0.0f, 20.0f); - bd.position.Set(x, y); - bd.angle = RandomFloat(-b2_pi, b2_pi); - - if (index == 4) - { - bd.angularDamping = 0.02f; - } - - m_bodies[m_bodyIndex] = m_world->CreateBody(&bd); - - if (index < 4) - { - b2FixtureDef fd; - fd.shape = m_polygons + index; - fd.friction = 0.3f; - fd.userData.pointer = index + 1; - m_bodies[m_bodyIndex]->CreateFixture(&fd); - } - else if (index < 5) - { - b2FixtureDef fd; - fd.shape = &m_circle; - fd.friction = 0.3f; - fd.userData.pointer = index + 1; - m_bodies[m_bodyIndex]->CreateFixture(&fd); - } - else - { - b2FixtureDef fd; - fd.shape = &m_edge; - fd.friction = 0.3f; - fd.userData.pointer = index + 1; - - m_bodies[m_bodyIndex]->CreateFixture(&fd); - } - - m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; - } - - void DestroyBody() - { - for (int32 i = 0; i < e_maxBodies; ++i) - { - if (m_bodies[i] != NULL) - { - m_world->DestroyBody(m_bodies[i]); - m_bodies[i] = NULL; - return; - } - } - } - - void UpdateUI() override - { - //ImGui::SetNextWindowPos(ImVec2(g_debugDrawTestBed.debugNodeOffset.x, g_debugDrawTestBed.debugNodeOffset.y)); - ImGui::SetNextWindowSize(ImVec2(210.0f, 285.0f)); - ImGui::Begin("Ray-cast Controls", nullptr, ImGuiWindowFlags_NoResize); - - if (ImGui::Button("Shape 1")) - { - Create(0); - } - - if (ImGui::Button("Shape 2")) - { - Create(1); - } - - if (ImGui::Button("Shape 3")) - { - Create(2); - } - - if (ImGui::Button("Shape 4")) - { - Create(3); - } - - if (ImGui::Button("Shape 5")) - { - Create(4); - } - - if (ImGui::Button("Shape 6")) - { - Create(5); - } - - if (ImGui::Button("Destroy Shape")) - { - DestroyBody(); - } - - ImGui::RadioButton("Any", &m_mode, e_any); - ImGui::RadioButton("Closest", &m_mode, e_closest); - ImGui::RadioButton("Multiple", &m_mode, e_multiple); - - ImGui::SliderFloat("Angle", &m_degrees, 0.0f, 360.0f, "%.0f"); - - ImGui::End(); - } - - void Step(Settings& settings) override - { - Test::Step(settings); - - DrawString(5, m_textLine, "Shape 1 is intentionally ignored by the ray"); - - switch (m_mode) - { - case e_closest: - DrawString(5, m_textLine, "Ray-cast mode: closest - find closest fixture along the ray"); - break; - - case e_any: - DrawString(5, m_textLine, "Ray-cast mode: any - check for obstruction"); - break; - - case e_multiple: - DrawString(5, m_textLine, "Ray-cast mode: multiple - gather multiple fixtures"); - break; - } - - - - float angle = b2_pi * m_degrees / 180.0f; - float L = 11.0f; - b2Vec2 point1(0.0f, 10.0f); - b2Vec2 d(L * cosf(angle), L * sinf(angle)); - b2Vec2 point2 = point1 + d; - - if (m_mode == e_closest) - { - RayCastClosestCallback callback; - m_world->RayCast(&callback, point1, point2); - - if (callback.m_hit) - { - g_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); - g_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f)); - b2Vec2 head = callback.m_point + 0.5f * callback.m_normal; - g_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f)); - } - else - { - g_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); - } - } - else if (m_mode == e_any) - { - RayCastAnyCallback callback; - m_world->RayCast(&callback, point1, point2); - - if (callback.m_hit) - { - g_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); - g_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f)); - b2Vec2 head = callback.m_point + 0.5f * callback.m_normal; - g_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f)); - } - else - { - g_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); - } - } - else if (m_mode == e_multiple) - { - RayCastMultipleCallback callback; - m_world->RayCast(&callback, point1, point2); - g_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); - - for (int32 i = 0; i < callback.m_count; ++i) - { - b2Vec2 p = callback.m_points[i]; - b2Vec2 n = callback.m_normals[i]; - g_debugDraw.DrawPoint(p, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); - g_debugDraw.DrawSegment(point1, p, b2Color(0.8f, 0.8f, 0.8f)); - b2Vec2 head = p + 0.5f * n; - g_debugDraw.DrawSegment(p, head, b2Color(0.9f, 0.9f, 0.4f)); - } - } + enum Mode + { + e_any = 0, + e_closest = 1, + e_multiple = 2 + }; + + RayCast() + { + // Ground body + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.5f, 0.0f); + vertices[1].Set(0.5f, 0.0f); + vertices[2].Set(0.0f, 1.5f); + m_polygons[0].Set(vertices, 3); + } + + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.1f, 0.0f); + vertices[1].Set(0.1f, 0.0f); + vertices[2].Set(0.0f, 1.5f); + m_polygons[1].Set(vertices, 3); + } + + { + float w = 1.0f; + float b = w / (2.0f + b2Sqrt(2.0f)); + float s = b2Sqrt(2.0f) * b; + + b2Vec2 vertices[8]; + vertices[0].Set(0.5f * s, 0.0f); + vertices[1].Set(0.5f * w, b); + vertices[2].Set(0.5f * w, b + s); + vertices[3].Set(0.5f * s, w); + vertices[4].Set(-0.5f * s, w); + vertices[5].Set(-0.5f * w, b + s); + vertices[6].Set(-0.5f * w, b); + vertices[7].Set(-0.5f * s, 0.0f); + + m_polygons[2].Set(vertices, 8); + } + + { + m_polygons[3].SetAsBox(0.5f, 0.5f); + } + + { + m_circle.m_radius = 0.5f; + } + + { + m_edge.SetTwoSided(b2Vec2(-1.0f, 0.0f), b2Vec2(1.0f, 0.0f)); + } + + m_bodyIndex = 0; + memset(m_bodies, 0, sizeof(m_bodies)); + + m_degrees = 0.0f; + + m_mode = e_closest; + } + + void Create(int32 index) + { + if (m_bodies[m_bodyIndex] != NULL) + { + m_world->DestroyBody(m_bodies[m_bodyIndex]); + m_bodies[m_bodyIndex] = NULL; + } + + b2BodyDef bd; + + float x = RandomFloat(-10.0f, 10.0f); + float y = RandomFloat(0.0f, 20.0f); + bd.position.Set(x, y); + bd.angle = RandomFloat(-b2_pi, b2_pi); + + if (index == 4) + { + bd.angularDamping = 0.02f; + } + + m_bodies[m_bodyIndex] = m_world->CreateBody(&bd); + + if (index < 4) + { + b2FixtureDef fd; + fd.shape = m_polygons + index; + fd.friction = 0.3f; + fd.userData.pointer = index + 1; + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } + else if (index < 5) + { + b2FixtureDef fd; + fd.shape = &m_circle; + fd.friction = 0.3f; + fd.userData.pointer = index + 1; + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } + else + { + b2FixtureDef fd; + fd.shape = &m_edge; + fd.friction = 0.3f; + fd.userData.pointer = index + 1; + + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } + + m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; + } + + void DestroyBody() + { + for (int32 i = 0; i < e_maxBodies; ++i) + { + if (m_bodies[i] != NULL) + { + m_world->DestroyBody(m_bodies[i]); + m_bodies[i] = NULL; + return; + } + } + } + + void UpdateUI() override + { + // ImGui::SetNextWindowPos(ImVec2(g_debugDrawTestBed.debugNodeOffset.x, g_debugDrawTestBed.debugNodeOffset.y)); + ImGui::SetNextWindowSize(ImVec2(210.0f, 285.0f)); + ImGui::Begin("Ray-cast Controls", nullptr, ImGuiWindowFlags_NoResize); + + if (ImGui::Button("Shape 1")) + { + Create(0); + } + + if (ImGui::Button("Shape 2")) + { + Create(1); + } + + if (ImGui::Button("Shape 3")) + { + Create(2); + } + + if (ImGui::Button("Shape 4")) + { + Create(3); + } + + if (ImGui::Button("Shape 5")) + { + Create(4); + } + + if (ImGui::Button("Shape 6")) + { + Create(5); + } + + if (ImGui::Button("Destroy Shape")) + { + DestroyBody(); + } + + ImGui::RadioButton("Any", &m_mode, e_any); + ImGui::RadioButton("Closest", &m_mode, e_closest); + ImGui::RadioButton("Multiple", &m_mode, e_multiple); + + ImGui::SliderFloat("Angle", &m_degrees, 0.0f, 360.0f, "%.0f"); + + ImGui::End(); + } + + void Step(Settings& settings) override + { + Test::Step(settings); + + DrawString(5, m_textLine, "Shape 1 is intentionally ignored by the ray"); + + switch (m_mode) + { + case e_closest: + DrawString(5, m_textLine, "Ray-cast mode: closest - find closest fixture along the ray"); + break; + + case e_any: + DrawString(5, m_textLine, "Ray-cast mode: any - check for obstruction"); + break; + + case e_multiple: + DrawString(5, m_textLine, "Ray-cast mode: multiple - gather multiple fixtures"); + break; + } + + float angle = b2_pi * m_degrees / 180.0f; + float L = 11.0f; + b2Vec2 point1(0.0f, 10.0f); + b2Vec2 d(L * cosf(angle), L * sinf(angle)); + b2Vec2 point2 = point1 + d; + + if (m_mode == e_closest) + { + RayCastClosestCallback callback; + m_world->RayCast(&callback, point1, point2); + + if (callback.m_hit) + { + g_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); + g_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f)); + b2Vec2 head = callback.m_point + 0.5f * callback.m_normal; + g_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f)); + } + else + { + g_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); + } + } + else if (m_mode == e_any) + { + RayCastAnyCallback callback; + m_world->RayCast(&callback, point1, point2); + + if (callback.m_hit) + { + g_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); + g_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f)); + b2Vec2 head = callback.m_point + 0.5f * callback.m_normal; + g_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f)); + } + else + { + g_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); + } + } + else if (m_mode == e_multiple) + { + RayCastMultipleCallback callback; + m_world->RayCast(&callback, point1, point2); + g_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); + + for (int32 i = 0; i < callback.m_count; ++i) + { + b2Vec2 p = callback.m_points[i]; + b2Vec2 n = callback.m_normals[i]; + g_debugDraw.DrawPoint(p, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); + g_debugDraw.DrawSegment(point1, p, b2Color(0.8f, 0.8f, 0.8f)); + b2Vec2 head = p + 0.5f * n; + g_debugDraw.DrawSegment(p, head, b2Color(0.9f, 0.9f, 0.4f)); + } + } #if 0 // This case was failing. @@ -460,20 +447,17 @@ class RayCast : public Test g_debugDraw.DrawSegment(input.p1, input.p2, color); } #endif - } - - static Test* Create() - { - return new RayCast; - } - - int32 m_bodyIndex; - b2Body* m_bodies[e_maxBodies]; - b2PolygonShape m_polygons[4]; - b2CircleShape m_circle; - b2EdgeShape m_edge; - float m_degrees; - int32 m_mode; + } + + static Test* Create() { return new RayCast; } + + int32 m_bodyIndex; + b2Body* m_bodies[e_maxBodies]; + b2PolygonShape m_polygons[4]; + b2CircleShape m_circle; + b2EdgeShape m_edge; + float m_degrees; + int32 m_mode; }; static int testIndex = RegisterTest("Collision", "Ray Cast", RayCast::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/restitution.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/restitution.cpp index 7772c623638c..10dd861e57f5 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/restitution.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/restitution.cpp @@ -27,53 +27,49 @@ class Restitution : public Test { public: + Restitution() + { + const float threshold = 10.0f; - Restitution() - { - const float threshold = 10.0f; - - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - - b2FixtureDef fd; - fd.shape = &shape; - fd.restitutionThreshold = threshold; - ground->CreateFixture(&fd); - } - - { - b2CircleShape shape; - shape.m_radius = 1.0f; - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - - float restitution[7] = { 0.0f, 0.1f, 0.3f, 0.5f, 0.75f, 0.9f, 1.0f }; - - for (int32 i = 0; i < 7; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-10.0f + 3.0f * i, 20.0f); - - b2Body* body = m_world->CreateBody(&bd); - - fd.restitution = restitution[i]; - fd.restitutionThreshold = threshold; - body->CreateFixture(&fd); - } - } - } - - static Test* Create() - { - return new Restitution; - } + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + + b2FixtureDef fd; + fd.shape = &shape; + fd.restitutionThreshold = threshold; + ground->CreateFixture(&fd); + } + + { + b2CircleShape shape; + shape.m_radius = 1.0f; + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + + float restitution[7] = {0.0f, 0.1f, 0.3f, 0.5f, 0.75f, 0.9f, 1.0f}; + + for (int32 i = 0; i < 7; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-10.0f + 3.0f * i, 20.0f); + + b2Body* body = m_world->CreateBody(&bd); + + fd.restitution = restitution[i]; + fd.restitutionThreshold = threshold; + body->CreateFixture(&fd); + } + } + } + + static Test* Create() { return new Restitution; } }; static int testIndex = RegisterTest("Forces", "Restitution", Restitution::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/revolute_joint.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/revolute_joint.cpp index e793d86bf283..9422ce3473bf 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/revolute_joint.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/revolute_joint.cpp @@ -27,136 +27,131 @@ class RevoluteJoint : public Test { public: - RevoluteJoint() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - - b2FixtureDef fd; - fd.shape = &shape; - //fd.filter.categoryBits = 2; - - ground->CreateFixture(&fd); - } - - m_enableLimit = true; - m_enableMotor = false; - m_motorSpeed = 1.0f; - - { - b2PolygonShape shape; - shape.SetAsBox(0.25f, 3.0f, b2Vec2(0.0f, 3.0f), 0.0f); - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-10.0f, 20.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 5.0f); - - b2RevoluteJointDef jd; - jd.Initialize(ground, body, b2Vec2(-10.0f, 20.5f)); - jd.motorSpeed = m_motorSpeed; - jd.maxMotorTorque = 10000.0f; - jd.enableMotor = m_enableMotor; - jd.lowerAngle = -0.25f * b2_pi; - jd.upperAngle = 0.5f * b2_pi; - jd.enableLimit = m_enableLimit; - - m_joint1 = (b2RevoluteJoint*)m_world->CreateJoint(&jd); - } - - { - b2CircleShape circle_shape; - circle_shape.m_radius = 2.0f; - - b2BodyDef circle_bd; - circle_bd.type = b2_dynamicBody; - circle_bd.position.Set(5.0f, 30.0f); - - b2FixtureDef fd; - fd.density = 5.0f; - fd.filter.maskBits = 1; - fd.shape = &circle_shape; - - m_ball = m_world->CreateBody(&circle_bd); - m_ball->CreateFixture(&fd); - - b2PolygonShape polygon_shape; - polygon_shape.SetAsBox(10.0f, 0.5f, b2Vec2 (-10.0f, 0.0f), 0.0f); - - b2BodyDef polygon_bd; - polygon_bd.position.Set(20.0f, 10.0f); - polygon_bd.type = b2_dynamicBody; - polygon_bd.bullet = true; - b2Body* polygon_body = m_world->CreateBody(&polygon_bd); - polygon_body->CreateFixture(&polygon_shape, 2.0f); - - b2RevoluteJointDef jd; - jd.Initialize(ground, polygon_body, b2Vec2(19.0f, 10.0f)); - jd.lowerAngle = -0.25f * b2_pi; - jd.upperAngle = 0.0f * b2_pi; - jd.enableLimit = true; - jd.enableMotor = true; - jd.motorSpeed = 0.0f; - jd.maxMotorTorque = 10000.0f; - - m_joint2 = (b2RevoluteJoint*)m_world->CreateJoint(&jd); - } - } - - void UpdateUI() override - { - //ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); - ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); - ImGui::Begin("Joint Controls", nullptr, ImGuiWindowFlags_NoResize); - - if (ImGui::Checkbox("Limit", &m_enableLimit)) - { - m_joint1->EnableLimit(m_enableLimit); - } - - if (ImGui::Checkbox("Motor", &m_enableMotor)) - { - m_joint1->EnableMotor(m_enableMotor); - } - - if (ImGui::SliderFloat("Speed", &m_motorSpeed, -20.0f, 20.0f, "%.0f")) - { - m_joint1->SetMotorSpeed(m_motorSpeed); - } - - ImGui::End(); - } - - void Step(Settings& settings) override - { - Test::Step(settings); - - float torque1 = m_joint1->GetMotorTorque(settings.m_hertz); - DrawString(5, m_textLine, "Motor Torque 1= %4.0f", torque1); - - - float torque2 = m_joint2->GetMotorTorque(settings.m_hertz); - DrawString(5, m_textLine, "Motor Torque 2= %4.0f", torque2); - - } - - static Test* Create() - { - return new RevoluteJoint; - } - - b2Body* m_ball; - b2RevoluteJoint* m_joint1; - b2RevoluteJoint* m_joint2; - float m_motorSpeed; - bool m_enableMotor; - bool m_enableLimit; + RevoluteJoint() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + + b2FixtureDef fd; + fd.shape = &shape; + // fd.filter.categoryBits = 2; + + ground->CreateFixture(&fd); + } + + m_enableLimit = true; + m_enableMotor = false; + m_motorSpeed = 1.0f; + + { + b2PolygonShape shape; + shape.SetAsBox(0.25f, 3.0f, b2Vec2(0.0f, 3.0f), 0.0f); + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-10.0f, 20.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 5.0f); + + b2RevoluteJointDef jd; + jd.Initialize(ground, body, b2Vec2(-10.0f, 20.5f)); + jd.motorSpeed = m_motorSpeed; + jd.maxMotorTorque = 10000.0f; + jd.enableMotor = m_enableMotor; + jd.lowerAngle = -0.25f * b2_pi; + jd.upperAngle = 0.5f * b2_pi; + jd.enableLimit = m_enableLimit; + + m_joint1 = (b2RevoluteJoint*)m_world->CreateJoint(&jd); + } + + { + b2CircleShape circle_shape; + circle_shape.m_radius = 2.0f; + + b2BodyDef circle_bd; + circle_bd.type = b2_dynamicBody; + circle_bd.position.Set(5.0f, 30.0f); + + b2FixtureDef fd; + fd.density = 5.0f; + fd.filter.maskBits = 1; + fd.shape = &circle_shape; + + m_ball = m_world->CreateBody(&circle_bd); + m_ball->CreateFixture(&fd); + + b2PolygonShape polygon_shape; + polygon_shape.SetAsBox(10.0f, 0.5f, b2Vec2(-10.0f, 0.0f), 0.0f); + + b2BodyDef polygon_bd; + polygon_bd.position.Set(20.0f, 10.0f); + polygon_bd.type = b2_dynamicBody; + polygon_bd.bullet = true; + b2Body* polygon_body = m_world->CreateBody(&polygon_bd); + polygon_body->CreateFixture(&polygon_shape, 2.0f); + + b2RevoluteJointDef jd; + jd.Initialize(ground, polygon_body, b2Vec2(19.0f, 10.0f)); + jd.lowerAngle = -0.25f * b2_pi; + jd.upperAngle = 0.0f * b2_pi; + jd.enableLimit = true; + jd.enableMotor = true; + jd.motorSpeed = 0.0f; + jd.maxMotorTorque = 10000.0f; + + m_joint2 = (b2RevoluteJoint*)m_world->CreateJoint(&jd); + } + } + + void UpdateUI() override + { + // ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); + ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); + ImGui::Begin("Joint Controls", nullptr, ImGuiWindowFlags_NoResize); + + if (ImGui::Checkbox("Limit", &m_enableLimit)) + { + m_joint1->EnableLimit(m_enableLimit); + } + + if (ImGui::Checkbox("Motor", &m_enableMotor)) + { + m_joint1->EnableMotor(m_enableMotor); + } + + if (ImGui::SliderFloat("Speed", &m_motorSpeed, -20.0f, 20.0f, "%.0f")) + { + m_joint1->SetMotorSpeed(m_motorSpeed); + } + + ImGui::End(); + } + + void Step(Settings& settings) override + { + Test::Step(settings); + + float torque1 = m_joint1->GetMotorTorque(settings.m_hertz); + DrawString(5, m_textLine, "Motor Torque 1= %4.0f", torque1); + + float torque2 = m_joint2->GetMotorTorque(settings.m_hertz); + DrawString(5, m_textLine, "Motor Torque 2= %4.0f", torque2); + } + + static Test* Create() { return new RevoluteJoint; } + + b2Body* m_ball; + b2RevoluteJoint* m_joint1; + b2RevoluteJoint* m_joint2; + float m_motorSpeed; + bool m_enableMotor; + bool m_enableLimit; }; static int testIndex = RegisterTest("Joints", "Revolute", RevoluteJoint::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/rope.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/rope.cpp index 846cfaaee654..65b41763f23b 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/rope.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/rope.cpp @@ -29,258 +29,254 @@ class Rope : public Test { public: - Rope() - { - const int32 N = 20; - const float L = 0.5f; - b2Vec2 vertices[N]; - float masses[N]; - - for (int32 i = 0; i < N; ++i) - { - vertices[i].Set(0.0f, L * (N - i)); - masses[i] = 1.0f; - } - masses[0] = 0.0f; - masses[1] = 0.0f; - - m_tuning1.bendHertz = 30.0f; - m_tuning1.bendDamping = 4.0f; - m_tuning1.bendStiffness = 1.0f; - m_tuning1.bendingModel = b2_pbdTriangleBendingModel; - m_tuning1.isometric = true; - - m_tuning1.stretchHertz = 30.0f; - m_tuning1.stretchDamping = 4.0f; - m_tuning1.stretchStiffness = 1.0f; - m_tuning1.stretchingModel = b2_pbdStretchingModel; - - m_tuning2.bendHertz = 30.0f; - m_tuning2.bendDamping = 0.7f; - m_tuning2.bendStiffness = 1.0f; - m_tuning2.bendingModel = b2_pbdHeightBendingModel; - m_tuning2.isometric = true; - - m_tuning2.stretchHertz = 30.0f; - m_tuning2.stretchDamping = 1.0f; - m_tuning2.stretchStiffness = 1.0f; - m_tuning2.stretchingModel = b2_pbdStretchingModel; - - m_position1.Set(-5.0f, 15.0f); - m_position2.Set(5.0f, 15.0f); - - b2RopeDef def; - def.vertices = vertices; - def.count = N; - def.gravity.Set(0.0f, -10.0f); - def.masses = masses; - - def.position = m_position1; - def.tuning = m_tuning1; - m_rope1.Create(def); - - def.position = m_position2; - def.tuning = m_tuning2; - m_rope2.Create(def); - - m_iterations1 = 8; - m_iterations2 = 8; - - m_speed = 10.0f; - } - - void UpdateUI() override - { - //ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); - ImGui::SetNextWindowSize(ImVec2(200.0f, 700.0f)); - ImGui::Begin("Tuning", nullptr, ImGuiWindowFlags_NoResize); - - ImGui::Separator(); + Rope() + { + const int32 N = 20; + const float L = 0.5f; + b2Vec2 vertices[N]; + float masses[N]; + + for (int32 i = 0; i < N; ++i) + { + vertices[i].Set(0.0f, L * (N - i)); + masses[i] = 1.0f; + } + masses[0] = 0.0f; + masses[1] = 0.0f; + + m_tuning1.bendHertz = 30.0f; + m_tuning1.bendDamping = 4.0f; + m_tuning1.bendStiffness = 1.0f; + m_tuning1.bendingModel = b2_pbdTriangleBendingModel; + m_tuning1.isometric = true; + + m_tuning1.stretchHertz = 30.0f; + m_tuning1.stretchDamping = 4.0f; + m_tuning1.stretchStiffness = 1.0f; + m_tuning1.stretchingModel = b2_pbdStretchingModel; + + m_tuning2.bendHertz = 30.0f; + m_tuning2.bendDamping = 0.7f; + m_tuning2.bendStiffness = 1.0f; + m_tuning2.bendingModel = b2_pbdHeightBendingModel; + m_tuning2.isometric = true; + + m_tuning2.stretchHertz = 30.0f; + m_tuning2.stretchDamping = 1.0f; + m_tuning2.stretchStiffness = 1.0f; + m_tuning2.stretchingModel = b2_pbdStretchingModel; + + m_position1.Set(-5.0f, 15.0f); + m_position2.Set(5.0f, 15.0f); + + b2RopeDef def; + def.vertices = vertices; + def.count = N; + def.gravity.Set(0.0f, -10.0f); + def.masses = masses; + + def.position = m_position1; + def.tuning = m_tuning1; + m_rope1.Create(def); + + def.position = m_position2; + def.tuning = m_tuning2; + m_rope2.Create(def); + + m_iterations1 = 8; + m_iterations2 = 8; + + m_speed = 10.0f; + } + + void UpdateUI() override + { + // ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); + ImGui::SetNextWindowSize(ImVec2(200.0f, 700.0f)); + ImGui::Begin("Tuning", nullptr, ImGuiWindowFlags_NoResize); + + ImGui::Separator(); ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f); - - const ImGuiComboFlags comboFlags = 0; - const char* bendModels[] = { "Spring", "PBD Ang", "XPBD Ang", "PBD Dist", "PBD Height", "PBD Triangle" }; - const char* stretchModels[] = { "PBD", "XPBD" }; - - ImGui::Text("Rope 1"); - static int bendModel1 = m_tuning1.bendingModel; - if (ImGui::BeginCombo("Bend Model##1", bendModels[bendModel1], comboFlags)) - { - for (int i = 0; i < IM_ARRAYSIZE(bendModels); ++i) - { - bool isSelected = (bendModel1 == i); - if (ImGui::Selectable(bendModels[i], isSelected)) - { - bendModel1 = i; - m_tuning1.bendingModel = b2BendingModel(i); - } - - if (isSelected) - { - ImGui::SetItemDefaultFocus(); - } - } - ImGui::EndCombo(); - } - - ImGui::SliderFloat("Damping##B1", &m_tuning1.bendDamping, 0.0f, 4.0f, "%.1f"); - ImGui::SliderFloat("Hertz##B1", &m_tuning1.bendHertz, 0.0f, 60.0f, "%.0f"); - ImGui::SliderFloat("Stiffness##B1", &m_tuning1.bendStiffness, 0.0f, 1.0f, "%.1f"); - - ImGui::Checkbox("Isometric##1", &m_tuning1.isometric); - ImGui::Checkbox("Fixed Mass##1", &m_tuning1.fixedEffectiveMass); - ImGui::Checkbox("Warm Start##1", &m_tuning1.warmStart); - - static int stretchModel1 = m_tuning1.stretchingModel; - if (ImGui::BeginCombo("Stretch Model##1", stretchModels[stretchModel1], comboFlags)) - { - for (int i = 0; i < IM_ARRAYSIZE(stretchModels); ++i) - { - bool isSelected = (stretchModel1 == i); - if (ImGui::Selectable(stretchModels[i], isSelected)) - { - stretchModel1 = i; - m_tuning1.stretchingModel = b2StretchingModel(i); - } - - if (isSelected) - { - ImGui::SetItemDefaultFocus(); - } - } - ImGui::EndCombo(); - } - - ImGui::SliderFloat("Damping##S1", &m_tuning1.stretchDamping, 0.0f, 4.0f, "%.1f"); - ImGui::SliderFloat("Hertz##S1", &m_tuning1.stretchHertz, 0.0f, 60.0f, "%.0f"); - ImGui::SliderFloat("Stiffness##S1", &m_tuning1.stretchStiffness, 0.0f, 1.0f, "%.1f"); - - ImGui::SliderInt("Iterations##1", &m_iterations1, 1, 100, "%d"); - - ImGui::Separator(); - - ImGui::Text("Rope 2"); - static int bendModel2 = m_tuning2.bendingModel; - if (ImGui::BeginCombo("Bend Model##2", bendModels[bendModel2], comboFlags)) - { - for (int i = 0; i < IM_ARRAYSIZE(bendModels); ++i) - { - bool isSelected = (bendModel2 == i); - if (ImGui::Selectable(bendModels[i], isSelected)) - { - bendModel2 = i; - m_tuning2.bendingModel = b2BendingModel(i); - } - - if (isSelected) - { - ImGui::SetItemDefaultFocus(); - } - } - ImGui::EndCombo(); - } - - ImGui::SliderFloat("Damping##B2", &m_tuning2.bendDamping, 0.0f, 4.0f, "%.1f"); - ImGui::SliderFloat("Hertz##B2", &m_tuning2.bendHertz, 0.0f, 60.0f, "%.0f"); - ImGui::SliderFloat("Stiffness##B2", &m_tuning2.bendStiffness, 0.0f, 1.0f, "%.1f"); - - ImGui::Checkbox("Isometric##2", &m_tuning2.isometric); - ImGui::Checkbox("Fixed Mass##2", &m_tuning2.fixedEffectiveMass); - ImGui::Checkbox("Warm Start##2", &m_tuning2.warmStart); - - static int stretchModel2 = m_tuning2.stretchingModel; - if (ImGui::BeginCombo("Stretch Model##2", stretchModels[stretchModel2], comboFlags)) - { - for (int i = 0; i < IM_ARRAYSIZE(stretchModels); ++i) - { - bool isSelected = (stretchModel2 == i); - if (ImGui::Selectable(stretchModels[i], isSelected)) - { - stretchModel2 = i; - m_tuning2.stretchingModel = b2StretchingModel(i); - } - - if (isSelected) - { - ImGui::SetItemDefaultFocus(); - } - } - ImGui::EndCombo(); - } - - ImGui::SliderFloat("Damping##S2", &m_tuning2.stretchDamping, 0.0f, 4.0f, "%.1f"); - ImGui::SliderFloat("Hertz##S2", &m_tuning2.stretchHertz, 0.0f, 60.0f, "%.0f"); - ImGui::SliderFloat("Stiffness##S2", &m_tuning2.stretchStiffness, 0.0f, 1.0f, "%.1f"); - - ImGui::SliderInt("Iterations##2", &m_iterations2, 1, 100, "%d"); - - ImGui::Separator(); - - ImGui::SliderFloat("Speed", &m_speed, 10.0f, 100.0f, "%.0f"); - - if (ImGui::Button("Reset")) - { - m_position1.Set(-5.0f, 15.0f); - m_position2.Set(5.0f, 15.0f); - m_rope1.Reset(m_position1); - m_rope2.Reset(m_position2); - } + + const ImGuiComboFlags comboFlags = 0; + const char* bendModels[] = {"Spring", "PBD Ang", "XPBD Ang", "PBD Dist", "PBD Height", "PBD Triangle"}; + const char* stretchModels[] = {"PBD", "XPBD"}; + + ImGui::Text("Rope 1"); + static int bendModel1 = m_tuning1.bendingModel; + if (ImGui::BeginCombo("Bend Model##1", bendModels[bendModel1], comboFlags)) + { + for (int i = 0; i < IM_ARRAYSIZE(bendModels); ++i) + { + bool isSelected = (bendModel1 == i); + if (ImGui::Selectable(bendModels[i], isSelected)) + { + bendModel1 = i; + m_tuning1.bendingModel = b2BendingModel(i); + } + + if (isSelected) + { + ImGui::SetItemDefaultFocus(); + } + } + ImGui::EndCombo(); + } + + ImGui::SliderFloat("Damping##B1", &m_tuning1.bendDamping, 0.0f, 4.0f, "%.1f"); + ImGui::SliderFloat("Hertz##B1", &m_tuning1.bendHertz, 0.0f, 60.0f, "%.0f"); + ImGui::SliderFloat("Stiffness##B1", &m_tuning1.bendStiffness, 0.0f, 1.0f, "%.1f"); + + ImGui::Checkbox("Isometric##1", &m_tuning1.isometric); + ImGui::Checkbox("Fixed Mass##1", &m_tuning1.fixedEffectiveMass); + ImGui::Checkbox("Warm Start##1", &m_tuning1.warmStart); + + static int stretchModel1 = m_tuning1.stretchingModel; + if (ImGui::BeginCombo("Stretch Model##1", stretchModels[stretchModel1], comboFlags)) + { + for (int i = 0; i < IM_ARRAYSIZE(stretchModels); ++i) + { + bool isSelected = (stretchModel1 == i); + if (ImGui::Selectable(stretchModels[i], isSelected)) + { + stretchModel1 = i; + m_tuning1.stretchingModel = b2StretchingModel(i); + } + + if (isSelected) + { + ImGui::SetItemDefaultFocus(); + } + } + ImGui::EndCombo(); + } + + ImGui::SliderFloat("Damping##S1", &m_tuning1.stretchDamping, 0.0f, 4.0f, "%.1f"); + ImGui::SliderFloat("Hertz##S1", &m_tuning1.stretchHertz, 0.0f, 60.0f, "%.0f"); + ImGui::SliderFloat("Stiffness##S1", &m_tuning1.stretchStiffness, 0.0f, 1.0f, "%.1f"); + + ImGui::SliderInt("Iterations##1", &m_iterations1, 1, 100, "%d"); + + ImGui::Separator(); + + ImGui::Text("Rope 2"); + static int bendModel2 = m_tuning2.bendingModel; + if (ImGui::BeginCombo("Bend Model##2", bendModels[bendModel2], comboFlags)) + { + for (int i = 0; i < IM_ARRAYSIZE(bendModels); ++i) + { + bool isSelected = (bendModel2 == i); + if (ImGui::Selectable(bendModels[i], isSelected)) + { + bendModel2 = i; + m_tuning2.bendingModel = b2BendingModel(i); + } + + if (isSelected) + { + ImGui::SetItemDefaultFocus(); + } + } + ImGui::EndCombo(); + } + + ImGui::SliderFloat("Damping##B2", &m_tuning2.bendDamping, 0.0f, 4.0f, "%.1f"); + ImGui::SliderFloat("Hertz##B2", &m_tuning2.bendHertz, 0.0f, 60.0f, "%.0f"); + ImGui::SliderFloat("Stiffness##B2", &m_tuning2.bendStiffness, 0.0f, 1.0f, "%.1f"); + + ImGui::Checkbox("Isometric##2", &m_tuning2.isometric); + ImGui::Checkbox("Fixed Mass##2", &m_tuning2.fixedEffectiveMass); + ImGui::Checkbox("Warm Start##2", &m_tuning2.warmStart); + + static int stretchModel2 = m_tuning2.stretchingModel; + if (ImGui::BeginCombo("Stretch Model##2", stretchModels[stretchModel2], comboFlags)) + { + for (int i = 0; i < IM_ARRAYSIZE(stretchModels); ++i) + { + bool isSelected = (stretchModel2 == i); + if (ImGui::Selectable(stretchModels[i], isSelected)) + { + stretchModel2 = i; + m_tuning2.stretchingModel = b2StretchingModel(i); + } + + if (isSelected) + { + ImGui::SetItemDefaultFocus(); + } + } + ImGui::EndCombo(); + } + + ImGui::SliderFloat("Damping##S2", &m_tuning2.stretchDamping, 0.0f, 4.0f, "%.1f"); + ImGui::SliderFloat("Hertz##S2", &m_tuning2.stretchHertz, 0.0f, 60.0f, "%.0f"); + ImGui::SliderFloat("Stiffness##S2", &m_tuning2.stretchStiffness, 0.0f, 1.0f, "%.1f"); + + ImGui::SliderInt("Iterations##2", &m_iterations2, 1, 100, "%d"); + + ImGui::Separator(); + + ImGui::SliderFloat("Speed", &m_speed, 10.0f, 100.0f, "%.0f"); + + if (ImGui::Button("Reset")) + { + m_position1.Set(-5.0f, 15.0f); + m_position2.Set(5.0f, 15.0f); + m_rope1.Reset(m_position1); + m_rope2.Reset(m_position2); + } ImGui::PopItemWidth(); - ImGui::End(); - } - - void Step(Settings& settings) override - { - float dt = settings.m_hertz > 0.0f ? 1.0f / settings.m_hertz : 0.0f; - - if (settings.m_pause == 1 && settings.m_singleStep == 0) - { - dt = 0.0f; - } - - //if (glfwGetKey(g_mainWindow, GLFW_KEY_COMMA) == GLFW_PRESS) - //{ - // m_position1.x -= m_speed * dt; - // m_position2.x -= m_speed * dt; - //} - - //if (glfwGetKey(g_mainWindow, GLFW_KEY_PERIOD) == GLFW_PRESS) - //{ - // m_position1.x += m_speed * dt; - // m_position2.x += m_speed * dt; - //} - - m_rope1.SetTuning(m_tuning1); - m_rope2.SetTuning(m_tuning2); - m_rope1.Step(dt, m_iterations1, m_position1); - m_rope2.Step(dt, m_iterations2, m_position2); - - Test::Step(settings); - - m_rope1.Draw(&g_debugDraw); - m_rope2.Draw(&g_debugDraw); - - DrawString(5, m_textLine, "Press comma and period to move left and right"); - - } - - static Test* Create() - { - return new Rope; - } - - b2Rope m_rope1; - b2Rope m_rope2; - b2RopeTuning m_tuning1; - b2RopeTuning m_tuning2; - int32 m_iterations1; - int32 m_iterations2; - b2Vec2 m_position1; - b2Vec2 m_position2; - float m_speed; + ImGui::End(); + } + + void Step(Settings& settings) override + { + float dt = settings.m_hertz > 0.0f ? 1.0f / settings.m_hertz : 0.0f; + + if (settings.m_pause == 1 && settings.m_singleStep == 0) + { + dt = 0.0f; + } + + // if (glfwGetKey(g_mainWindow, GLFW_KEY_COMMA) == GLFW_PRESS) + //{ + // m_position1.x -= m_speed * dt; + // m_position2.x -= m_speed * dt; + // } + + // if (glfwGetKey(g_mainWindow, GLFW_KEY_PERIOD) == GLFW_PRESS) + //{ + // m_position1.x += m_speed * dt; + // m_position2.x += m_speed * dt; + // } + + m_rope1.SetTuning(m_tuning1); + m_rope2.SetTuning(m_tuning2); + m_rope1.Step(dt, m_iterations1, m_position1); + m_rope2.Step(dt, m_iterations2, m_position2); + + Test::Step(settings); + + m_rope1.Draw(&g_debugDraw); + m_rope2.Draw(&g_debugDraw); + + DrawString(5, m_textLine, "Press comma and period to move left and right"); + } + + static Test* Create() { return new Rope; } + + b2Rope m_rope1; + b2Rope m_rope2; + b2RopeTuning m_tuning1; + b2RopeTuning m_tuning2; + int32 m_iterations1; + int32 m_iterations2; + b2Vec2 m_position1; + b2Vec2 m_position2; + float m_speed; }; static int testIndex = RegisterTest("Rope", "Bending", Rope::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/sensor.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/sensor.cpp index af9e88c1e13e..b7b4b9bdb04c 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/sensor.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/sensor.cpp @@ -27,23 +27,22 @@ class Sensors : public Test { public: - - enum - { - e_count = 7 - }; - - Sensors() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - { - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + enum + { + e_count = 7 + }; + + Sensors() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + { + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } #if 0 { @@ -53,143 +52,140 @@ class Sensors : public Test m_sensor = ground->CreateFixture(&sd); } #else - { - b2CircleShape shape; - shape.m_radius = 5.0f; - shape.m_p.Set(0.0f, 10.0f); - - b2FixtureDef fd; - fd.shape = &shape; - fd.isSensor = true; - m_sensor = ground->CreateFixture(&fd); - } + { + b2CircleShape shape; + shape.m_radius = 5.0f; + shape.m_p.Set(0.0f, 10.0f); + + b2FixtureDef fd; + fd.shape = &shape; + fd.isSensor = true; + m_sensor = ground->CreateFixture(&fd); + } #endif - } - - { - b2CircleShape shape; - shape.m_radius = 1.0f; - - for (int32 i = 0; i < e_count; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-10.0f + 3.0f * i, 20.0f); - bd.userData.pointer = i; - - m_touching[i] = false; - m_bodies[i] = m_world->CreateBody(&bd); - - m_bodies[i]->CreateFixture(&shape, 1.0f); - } - } - - m_force = 100.0f; - } - - // Implement contact listener. - void BeginContact(b2Contact* contact) override - { - b2Fixture* fixtureA = contact->GetFixtureA(); - b2Fixture* fixtureB = contact->GetFixtureB(); - - if (fixtureA == m_sensor) - { - uintptr_t index = fixtureB->GetBody()->GetUserData().pointer; - if (index < e_count) - { - m_touching[index] = true; - } - } - - if (fixtureB == m_sensor) - { - uintptr_t index = fixtureA->GetBody()->GetUserData().pointer; - if (index < e_count) - { - m_touching[index] = true; - } - } - } - - // Implement contact listener. - void EndContact(b2Contact* contact) override - { - b2Fixture* fixtureA = contact->GetFixtureA(); - b2Fixture* fixtureB = contact->GetFixtureB(); - - if (fixtureA == m_sensor) - { - uintptr_t index = fixtureB->GetBody()->GetUserData().pointer; - if (index < e_count) - { - m_touching[index] = false; - } - } - - if (fixtureB == m_sensor) - { - uintptr_t index = fixtureA->GetBody()->GetUserData().pointer; - if (index < e_count) - { - m_touching[index] = false; - } - } - } - - void UpdateUI() override - { - //ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); - ImGui::SetNextWindowSize(ImVec2(200.0f, 60.0f)); - ImGui::Begin("Sensor Controls", nullptr, ImGuiWindowFlags_NoResize); - - ImGui::SliderFloat("Force", &m_force, 0.0f, 2000.0f, "%.0f"); - - ImGui::End(); - } - - void Step(Settings& settings) override - { - Test::Step(settings); - - // Traverse the contact results. Apply a force on shapes - // that overlap the sensor. - for (int32 i = 0; i < e_count; ++i) - { - if (m_touching[i] == false) - { - continue; - } - - b2Body* body = m_bodies[i]; - b2Body* ground = m_sensor->GetBody(); - - b2CircleShape* circle = (b2CircleShape*)m_sensor->GetShape(); - b2Vec2 center = ground->GetWorldPoint(circle->m_p); - - b2Vec2 position = body->GetPosition(); - - b2Vec2 d = center - position; - if (d.LengthSquared() < FLT_EPSILON * FLT_EPSILON) - { - continue; - } - - d.Normalize(); - b2Vec2 F = m_force * d; - body->ApplyForce(F, position, false); - } - } - - static Test* Create() - { - return new Sensors; - } - - b2Fixture* m_sensor; - b2Body* m_bodies[e_count]; - float m_force; - bool m_touching[e_count]; + } + + { + b2CircleShape shape; + shape.m_radius = 1.0f; + + for (int32 i = 0; i < e_count; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-10.0f + 3.0f * i, 20.0f); + bd.userData.pointer = i; + + m_touching[i] = false; + m_bodies[i] = m_world->CreateBody(&bd); + + m_bodies[i]->CreateFixture(&shape, 1.0f); + } + } + + m_force = 100.0f; + } + + // Implement contact listener. + void BeginContact(b2Contact* contact) override + { + b2Fixture* fixtureA = contact->GetFixtureA(); + b2Fixture* fixtureB = contact->GetFixtureB(); + + if (fixtureA == m_sensor) + { + uintptr_t index = fixtureB->GetBody()->GetUserData().pointer; + if (index < e_count) + { + m_touching[index] = true; + } + } + + if (fixtureB == m_sensor) + { + uintptr_t index = fixtureA->GetBody()->GetUserData().pointer; + if (index < e_count) + { + m_touching[index] = true; + } + } + } + + // Implement contact listener. + void EndContact(b2Contact* contact) override + { + b2Fixture* fixtureA = contact->GetFixtureA(); + b2Fixture* fixtureB = contact->GetFixtureB(); + + if (fixtureA == m_sensor) + { + uintptr_t index = fixtureB->GetBody()->GetUserData().pointer; + if (index < e_count) + { + m_touching[index] = false; + } + } + + if (fixtureB == m_sensor) + { + uintptr_t index = fixtureA->GetBody()->GetUserData().pointer; + if (index < e_count) + { + m_touching[index] = false; + } + } + } + + void UpdateUI() override + { + // ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); + ImGui::SetNextWindowSize(ImVec2(200.0f, 60.0f)); + ImGui::Begin("Sensor Controls", nullptr, ImGuiWindowFlags_NoResize); + + ImGui::SliderFloat("Force", &m_force, 0.0f, 2000.0f, "%.0f"); + + ImGui::End(); + } + + void Step(Settings& settings) override + { + Test::Step(settings); + + // Traverse the contact results. Apply a force on shapes + // that overlap the sensor. + for (int32 i = 0; i < e_count; ++i) + { + if (m_touching[i] == false) + { + continue; + } + + b2Body* body = m_bodies[i]; + b2Body* ground = m_sensor->GetBody(); + + b2CircleShape* circle = (b2CircleShape*)m_sensor->GetShape(); + b2Vec2 center = ground->GetWorldPoint(circle->m_p); + + b2Vec2 position = body->GetPosition(); + + b2Vec2 d = center - position; + if (d.LengthSquared() < FLT_EPSILON * FLT_EPSILON) + { + continue; + } + + d.Normalize(); + b2Vec2 F = m_force * d; + body->ApplyForce(F, position, false); + } + } + + static Test* Create() { return new Sensors; } + + b2Fixture* m_sensor; + b2Body* m_bodies[e_count]; + float m_force; + bool m_touching[e_count]; }; static int testIndex = RegisterTest("Collision", "Sensors", Sensors::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/settings.h b/tests/cpp-tests/Classes/Box2DTestBed/tests/settings.h index a34f6fda0c54..7ba71423e898 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/settings.h +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/settings.h @@ -25,62 +25,59 @@ struct Settings { - Settings() - { - Reset(); - } + Settings() { Reset(); } - void Reset() - { - m_testIndex = 0; - m_windowWidth = 1600; - m_windowHeight = 900; - m_hertz = 60.0f; - m_velocityIterations = 8; - m_positionIterations = 3; - m_drawShapes = true; - m_drawJoints = true; - m_drawAABBs = false; - m_drawContactPoints = false; - m_drawContactNormals = false; - m_drawContactImpulse = false; - m_drawFrictionImpulse = false; - m_drawCOMs = false; - m_drawStats = false; - m_drawProfile = false; - m_enableWarmStarting = true; - m_enableContinuous = true; - m_enableSubStepping = false; - m_enableSleep = true; - m_pause = false; - m_singleStep = false; - } + void Reset() + { + m_testIndex = 0; + m_windowWidth = 1600; + m_windowHeight = 900; + m_hertz = 60.0f; + m_velocityIterations = 8; + m_positionIterations = 3; + m_drawShapes = true; + m_drawJoints = true; + m_drawAABBs = false; + m_drawContactPoints = false; + m_drawContactNormals = false; + m_drawContactImpulse = false; + m_drawFrictionImpulse = false; + m_drawCOMs = false; + m_drawStats = false; + m_drawProfile = false; + m_enableWarmStarting = true; + m_enableContinuous = true; + m_enableSubStepping = false; + m_enableSleep = true; + m_pause = false; + m_singleStep = false; + } - void Save(); - void Load(); + void Save(); + void Load(); - int m_testIndex; - int m_windowWidth; - int m_windowHeight; - float m_hertz; - int m_velocityIterations; - int m_positionIterations; - bool m_drawShapes; - bool m_drawJoints; - bool m_drawAABBs; - bool m_drawContactPoints; - bool m_drawContactNormals; - bool m_drawContactImpulse; - bool m_drawFrictionImpulse; - bool m_drawCOMs; - bool m_drawStats; - bool m_drawProfile; - bool m_enableWarmStarting; - bool m_enableContinuous; - bool m_enableSubStepping; - bool m_enableSleep; - bool m_pause; - bool m_singleStep; + int m_testIndex; + int m_windowWidth; + int m_windowHeight; + float m_hertz; + int m_velocityIterations; + int m_positionIterations; + bool m_drawShapes; + bool m_drawJoints; + bool m_drawAABBs; + bool m_drawContactPoints; + bool m_drawContactNormals; + bool m_drawContactImpulse; + bool m_drawFrictionImpulse; + bool m_drawCOMs; + bool m_drawStats; + bool m_drawProfile; + bool m_enableWarmStarting; + bool m_enableContinuous; + bool m_enableSubStepping; + bool m_enableSleep; + bool m_pause; + bool m_singleStep; }; #endif \ No newline at end of file diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/shape_cast.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/shape_cast.cpp index 2c942add2890..60771b589681 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/shape_cast.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/shape_cast.cpp @@ -26,168 +26,164 @@ class ShapeCast : public Test { public: - enum - { - e_vertexCount = 8 - }; + enum + { + e_vertexCount = 8 + }; - ShapeCast() - { + ShapeCast() + { #if 1 - m_vAs[0].Set(-0.5f, 1.0f); - m_vAs[1].Set(0.5f, 1.0f); - m_vAs[2].Set(0.0f, 0.0f); - m_countA = 3; - m_radiusA = b2_polygonRadius; - - m_vBs[0].Set(-0.5f, -0.5f); - m_vBs[1].Set(0.5f, -0.5f); - m_vBs[2].Set(0.5f, 0.5f); - m_vBs[3].Set(-0.5f, 0.5f); - m_countB = 4; - m_radiusB = b2_polygonRadius; - - m_transformA.p.Set(0.0f, 0.25f); - m_transformA.q.SetIdentity(); - m_transformB.p.Set(-4.0f, 0.0f); - m_transformB.q.SetIdentity(); - m_translationB.Set(8.0f, 0.0f); + m_vAs[0].Set(-0.5f, 1.0f); + m_vAs[1].Set(0.5f, 1.0f); + m_vAs[2].Set(0.0f, 0.0f); + m_countA = 3; + m_radiusA = b2_polygonRadius; + + m_vBs[0].Set(-0.5f, -0.5f); + m_vBs[1].Set(0.5f, -0.5f); + m_vBs[2].Set(0.5f, 0.5f); + m_vBs[3].Set(-0.5f, 0.5f); + m_countB = 4; + m_radiusB = b2_polygonRadius; + + m_transformA.p.Set(0.0f, 0.25f); + m_transformA.q.SetIdentity(); + m_transformB.p.Set(-4.0f, 0.0f); + m_transformB.q.SetIdentity(); + m_translationB.Set(8.0f, 0.0f); #elif 0 - m_vAs[0].Set(0.0f, 0.0f); - m_countA = 1; - m_radiusA = 0.5f; - - m_vBs[0].Set(0.0f, 0.0f); - m_countB = 1; - m_radiusB = 0.5f; - - m_transformA.p.Set(0.0f, 0.25f); - m_transformA.q.SetIdentity(); - m_transformB.p.Set(-4.0f, 0.0f); - m_transformB.q.SetIdentity(); - m_translationB.Set(8.0f, 0.0f); + m_vAs[0].Set(0.0f, 0.0f); + m_countA = 1; + m_radiusA = 0.5f; + + m_vBs[0].Set(0.0f, 0.0f); + m_countB = 1; + m_radiusB = 0.5f; + + m_transformA.p.Set(0.0f, 0.25f); + m_transformA.q.SetIdentity(); + m_transformB.p.Set(-4.0f, 0.0f); + m_transformB.q.SetIdentity(); + m_translationB.Set(8.0f, 0.0f); #else - m_vAs[0].Set(0.0f, 0.0f); - m_vAs[1].Set(2.0f, 0.0f); - m_countA = 2; - m_radiusA = b2_polygonRadius; - - m_vBs[0].Set(0.0f, 0.0f); - m_countB = 1; - m_radiusB = 0.25f; - - // Initial overlap - m_transformA.p.Set(0.0f, 0.0f); - m_transformA.q.SetIdentity(); - m_transformB.p.Set(-0.244360745f, 0.05999358f); - m_transformB.q.SetIdentity(); - m_translationB.Set(0.0f, 0.0399999991f); + m_vAs[0].Set(0.0f, 0.0f); + m_vAs[1].Set(2.0f, 0.0f); + m_countA = 2; + m_radiusA = b2_polygonRadius; + + m_vBs[0].Set(0.0f, 0.0f); + m_countB = 1; + m_radiusB = 0.25f; + + // Initial overlap + m_transformA.p.Set(0.0f, 0.0f); + m_transformA.q.SetIdentity(); + m_transformB.p.Set(-0.244360745f, 0.05999358f); + m_transformB.q.SetIdentity(); + m_translationB.Set(0.0f, 0.0399999991f); #endif - } - - static Test* Create() - { - return new ShapeCast; - } - - void Step(Settings& settings) override - { - Test::Step(settings); - - b2ShapeCastInput input; - input.proxyA.Set(m_vAs, m_countA, m_radiusA); - input.proxyB.Set(m_vBs, m_countB, m_radiusB); - input.transformA = m_transformA; - input.transformB = m_transformB; - input.translationB = m_translationB; - - b2ShapeCastOutput output; - bool hit = b2ShapeCast(&output, &input); - - b2Transform transformB2; - transformB2.q = m_transformB.q; - transformB2.p = m_transformB.p + output.lambda * input.translationB; - - b2DistanceInput distanceInput; - distanceInput.proxyA.Set(m_vAs, m_countA, m_radiusA); - distanceInput.proxyB.Set(m_vBs, m_countB, m_radiusB); - distanceInput.transformA = m_transformA; - distanceInput.transformB = transformB2; - distanceInput.useRadii = false; - b2SimplexCache simplexCache; - simplexCache.count = 0; - b2DistanceOutput distanceOutput; - - b2Distance(&distanceOutput, &simplexCache, &distanceInput); - - DrawString(5, m_textLine, "hit = %s, iters = %d, lambda = %g, distance = %g", - hit ? "true" : "false", output.iterations, output.lambda, distanceOutput.distance); - - - b2Vec2 vertices[b2_maxPolygonVertices]; - - for (int32 i = 0; i < m_countA; ++i) - { - vertices[i] = b2Mul(m_transformA, m_vAs[i]); - } - - if (m_countA == 1) - { - g_debugDraw.DrawCircle(vertices[0], m_radiusA, b2Color(0.9f, 0.9f, 0.9f)); - } - else - { - g_debugDraw.DrawPolygon(vertices, m_countA, b2Color(0.9f, 0.9f, 0.9f)); - } - - for (int32 i = 0; i < m_countB; ++i) - { - vertices[i] = b2Mul(m_transformB, m_vBs[i]); - } - - if (m_countB == 1) - { - g_debugDraw.DrawCircle(vertices[0], m_radiusB, b2Color(0.5f, 0.9f, 0.5f)); - } - else - { - g_debugDraw.DrawPolygon(vertices, m_countB, b2Color(0.5f, 0.9f, 0.5f)); - } - - for (int32 i = 0; i < m_countB; ++i) - { - vertices[i] = b2Mul(transformB2, m_vBs[i]); - } - - if (m_countB == 1) - { - g_debugDraw.DrawCircle(vertices[0], m_radiusB, b2Color(0.5f, 0.7f, 0.9f)); - } - else - { - g_debugDraw.DrawPolygon(vertices, m_countB, b2Color(0.5f, 0.7f, 0.9f)); - } - - if (hit) - { - b2Vec2 p1 = output.point; - g_debugDraw.DrawPoint(p1, 10.0f, b2Color(0.9f, 0.3f, 0.3f)); - b2Vec2 p2 = p1 + output.normal; - g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.3f, 0.3f)); - } - } - - b2Vec2 m_vAs[b2_maxPolygonVertices]; - int32 m_countA; - float m_radiusA; - - b2Vec2 m_vBs[b2_maxPolygonVertices]; - int32 m_countB; - float m_radiusB; - - b2Transform m_transformA; - b2Transform m_transformB; - b2Vec2 m_translationB; + } + + static Test* Create() { return new ShapeCast; } + + void Step(Settings& settings) override + { + Test::Step(settings); + + b2ShapeCastInput input; + input.proxyA.Set(m_vAs, m_countA, m_radiusA); + input.proxyB.Set(m_vBs, m_countB, m_radiusB); + input.transformA = m_transformA; + input.transformB = m_transformB; + input.translationB = m_translationB; + + b2ShapeCastOutput output; + bool hit = b2ShapeCast(&output, &input); + + b2Transform transformB2; + transformB2.q = m_transformB.q; + transformB2.p = m_transformB.p + output.lambda * input.translationB; + + b2DistanceInput distanceInput; + distanceInput.proxyA.Set(m_vAs, m_countA, m_radiusA); + distanceInput.proxyB.Set(m_vBs, m_countB, m_radiusB); + distanceInput.transformA = m_transformA; + distanceInput.transformB = transformB2; + distanceInput.useRadii = false; + b2SimplexCache simplexCache; + simplexCache.count = 0; + b2DistanceOutput distanceOutput; + + b2Distance(&distanceOutput, &simplexCache, &distanceInput); + + DrawString(5, m_textLine, "hit = %s, iters = %d, lambda = %g, distance = %g", hit ? "true" : "false", + output.iterations, output.lambda, distanceOutput.distance); + + b2Vec2 vertices[b2_maxPolygonVertices]; + + for (int32 i = 0; i < m_countA; ++i) + { + vertices[i] = b2Mul(m_transformA, m_vAs[i]); + } + + if (m_countA == 1) + { + g_debugDraw.DrawCircle(vertices[0], m_radiusA, b2Color(0.9f, 0.9f, 0.9f)); + } + else + { + g_debugDraw.DrawPolygon(vertices, m_countA, b2Color(0.9f, 0.9f, 0.9f)); + } + + for (int32 i = 0; i < m_countB; ++i) + { + vertices[i] = b2Mul(m_transformB, m_vBs[i]); + } + + if (m_countB == 1) + { + g_debugDraw.DrawCircle(vertices[0], m_radiusB, b2Color(0.5f, 0.9f, 0.5f)); + } + else + { + g_debugDraw.DrawPolygon(vertices, m_countB, b2Color(0.5f, 0.9f, 0.5f)); + } + + for (int32 i = 0; i < m_countB; ++i) + { + vertices[i] = b2Mul(transformB2, m_vBs[i]); + } + + if (m_countB == 1) + { + g_debugDraw.DrawCircle(vertices[0], m_radiusB, b2Color(0.5f, 0.7f, 0.9f)); + } + else + { + g_debugDraw.DrawPolygon(vertices, m_countB, b2Color(0.5f, 0.7f, 0.9f)); + } + + if (hit) + { + b2Vec2 p1 = output.point; + g_debugDraw.DrawPoint(p1, 10.0f, b2Color(0.9f, 0.3f, 0.3f)); + b2Vec2 p2 = p1 + output.normal; + g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.3f, 0.3f)); + } + } + + b2Vec2 m_vAs[b2_maxPolygonVertices]; + int32 m_countA; + float m_radiusA; + + b2Vec2 m_vBs[b2_maxPolygonVertices]; + int32 m_countB; + float m_radiusB; + + b2Transform m_transformA; + b2Transform m_transformB; + b2Vec2 m_translationB; }; static int testIndex = RegisterTest("Collision", "Shape Cast", ShapeCast::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/shape_editing.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/shape_editing.cpp index 357ed8fa280a..c7b753b52400 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/shape_editing.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/shape_editing.cpp @@ -25,84 +25,79 @@ class ShapeEditing : public Test { public: - - ShapeEditing() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 10.0f); - m_body = m_world->CreateBody(&bd); - - b2PolygonShape shape; - shape.SetAsBox(4.0f, 4.0f, b2Vec2(0.0f, 0.0f), 0.0f); - m_fixture1 = m_body->CreateFixture(&shape, 10.0f); - - m_fixture2 = NULL; - - m_sensor = false; - } - - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_C: - if (m_fixture2 == NULL) - { - b2CircleShape shape; - shape.m_radius = 3.0f; - shape.m_p.Set(0.5f, -4.0f); - m_fixture2 = m_body->CreateFixture(&shape, 10.0f); - m_body->SetAwake(true); - } - break; - - case GLFW_KEY_D: - if (m_fixture2 != NULL) - { - m_body->DestroyFixture(m_fixture2); - m_fixture2 = NULL; - m_body->SetAwake(true); - } - break; - - case GLFW_KEY_S: - if (m_fixture2 != NULL) - { - m_sensor = !m_sensor; - m_fixture2->SetSensor(m_sensor); - } - break; - } - } - - void Step(Settings& settings) override - { - Test::Step(settings); - DrawString(5, m_textLine, "Press: (c) create a shape, (d) destroy a shape."); - - DrawString(5, m_textLine, "sensor = %d", m_sensor); - - } - - static Test* Create() - { - return new ShapeEditing; - } - - b2Body* m_body; - b2Fixture* m_fixture1; - b2Fixture* m_fixture2; - bool m_sensor; + ShapeEditing() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 10.0f); + m_body = m_world->CreateBody(&bd); + + b2PolygonShape shape; + shape.SetAsBox(4.0f, 4.0f, b2Vec2(0.0f, 0.0f), 0.0f); + m_fixture1 = m_body->CreateFixture(&shape, 10.0f); + + m_fixture2 = NULL; + + m_sensor = false; + } + + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_C: + if (m_fixture2 == NULL) + { + b2CircleShape shape; + shape.m_radius = 3.0f; + shape.m_p.Set(0.5f, -4.0f); + m_fixture2 = m_body->CreateFixture(&shape, 10.0f); + m_body->SetAwake(true); + } + break; + + case GLFW_KEY_D: + if (m_fixture2 != NULL) + { + m_body->DestroyFixture(m_fixture2); + m_fixture2 = NULL; + m_body->SetAwake(true); + } + break; + + case GLFW_KEY_S: + if (m_fixture2 != NULL) + { + m_sensor = !m_sensor; + m_fixture2->SetSensor(m_sensor); + } + break; + } + } + + void Step(Settings& settings) override + { + Test::Step(settings); + DrawString(5, m_textLine, "Press: (c) create a shape, (d) destroy a shape."); + + DrawString(5, m_textLine, "sensor = %d", m_sensor); + } + + static Test* Create() { return new ShapeEditing; } + + b2Body* m_body; + b2Fixture* m_fixture1; + b2Fixture* m_fixture2; + bool m_sensor; }; static int testIndex = RegisterTest("Examples", "Shape Editing", ShapeEditing::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/skier.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/skier.cpp index c5ff52534002..05529640a25c 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/skier.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/skier.cpp @@ -10,141 +10,137 @@ Test case for collision/jerking issue. class Skier : public Test { public: - Skier() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); - - float const PlatformWidth = 8.0f; - - /* - First angle is from the horizontal and should be negative for a downward slope. - Second angle is relative to the preceding slope, and should be positive, creating a kind of - loose 'Z'-shape from the 3 edges. - If A1 = -10, then A2 <= ~1.5 will result in the collision glitch. - If A1 = -30, then A2 <= ~10.0 will result in the glitch. - */ - float const Angle1Degrees = -30.0f; - float const Angle2Degrees = 10.0f; - - /* - The larger the value of SlopeLength, the less likely the glitch will show up. - */ - float const SlopeLength = 2.0f; - - float const SurfaceFriction = 0.2f; - - // Convert to radians - float const Slope1Incline = -Angle1Degrees * b2_pi / 180.0f; - float const Slope2Incline = Slope1Incline - Angle2Degrees * b2_pi / 180.0f; - // - - m_platform_width = PlatformWidth; - - // Horizontal platform - b2Vec2 v1(-PlatformWidth, 0.0f); - b2Vec2 v2(0.0f, 0.0f); - b2Vec2 v3(SlopeLength * cosf(Slope1Incline), -SlopeLength * sinf(Slope1Incline)); - b2Vec2 v4(v3.x + SlopeLength * cosf(Slope2Incline), v3.y - SlopeLength * sinf(Slope2Incline)); - b2Vec2 v5(v4.x, v4.y - 1.0f); - - b2Vec2 vertices[5] = { v5, v4, v3, v2, v1 }; - - b2ChainShape shape; - shape.CreateLoop(vertices, 5); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 0.0f; - fd.friction = SurfaceFriction; - - ground->CreateFixture(&fd); - } - - { - float const BodyWidth = 1.0f; - float const BodyHeight = 2.5f; - float const SkiLength = 3.0f; - - /* - Larger values for this seem to alleviate the issue to some extent. - */ - float const SkiThickness = 0.3f; - - float const SkiFriction = 0.0f; - float const SkiRestitution = 0.15f; - - b2BodyDef bd; - bd.type = b2_dynamicBody; - - float initial_y = BodyHeight / 2 + SkiThickness; - bd.position.Set(-m_platform_width / 2, initial_y); - - b2Body* skier = m_world->CreateBody(&bd); - - b2PolygonShape ski; - b2Vec2 verts[4]; - verts[0].Set(-SkiLength / 2 - SkiThickness, -BodyHeight / 2); - verts[1].Set(-SkiLength / 2, -BodyHeight / 2 - SkiThickness); - verts[2].Set(SkiLength / 2, -BodyHeight / 2 - SkiThickness); - verts[3].Set(SkiLength / 2 + SkiThickness, -BodyHeight / 2); - ski.Set(verts, 4); - - b2FixtureDef fd; - fd.density = 1.0f; - - fd.friction = SkiFriction; - fd.restitution = SkiRestitution; - - fd.shape = &ski; - skier->CreateFixture(&fd); - - skier->SetLinearVelocity(b2Vec2(0.5f, 0.0f)); - - m_skier = skier; - } - - //g_camera.m_center = b2Vec2(m_platform_width / 2.0f, 0.0f); - //g_camera.m_zoom = 0.4f; - m_fixed_camera = true; - } - - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_C: - m_fixed_camera = !m_fixed_camera; - if(m_fixed_camera) - { - // g_camera.m_center = b2Vec2(m_platform_width / 2.0f, 0.0f); - } - break; - } - } - - void Step(Settings& settings) override - { - DrawString(5, m_textLine, "Keys: c = Camera fixed/tracking"); - - - if(!m_fixed_camera) - { - //g_camera.m_center = m_skier->GetPosition(); - } - - Test::Step(settings); - } - - static Test* Create() - { - return new Skier; - } - - b2Body* m_skier; - float m_platform_width; - bool m_fixed_camera; + Skier() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + + float const PlatformWidth = 8.0f; + + /* + First angle is from the horizontal and should be negative for a downward slope. + Second angle is relative to the preceding slope, and should be positive, creating a kind of + loose 'Z'-shape from the 3 edges. + If A1 = -10, then A2 <= ~1.5 will result in the collision glitch. + If A1 = -30, then A2 <= ~10.0 will result in the glitch. + */ + float const Angle1Degrees = -30.0f; + float const Angle2Degrees = 10.0f; + + /* + The larger the value of SlopeLength, the less likely the glitch will show up. + */ + float const SlopeLength = 2.0f; + + float const SurfaceFriction = 0.2f; + + // Convert to radians + float const Slope1Incline = -Angle1Degrees * b2_pi / 180.0f; + float const Slope2Incline = Slope1Incline - Angle2Degrees * b2_pi / 180.0f; + // + + m_platform_width = PlatformWidth; + + // Horizontal platform + b2Vec2 v1(-PlatformWidth, 0.0f); + b2Vec2 v2(0.0f, 0.0f); + b2Vec2 v3(SlopeLength * cosf(Slope1Incline), -SlopeLength * sinf(Slope1Incline)); + b2Vec2 v4(v3.x + SlopeLength * cosf(Slope2Incline), v3.y - SlopeLength * sinf(Slope2Incline)); + b2Vec2 v5(v4.x, v4.y - 1.0f); + + b2Vec2 vertices[5] = {v5, v4, v3, v2, v1}; + + b2ChainShape shape; + shape.CreateLoop(vertices, 5); + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 0.0f; + fd.friction = SurfaceFriction; + + ground->CreateFixture(&fd); + } + + { + float const BodyWidth = 1.0f; + float const BodyHeight = 2.5f; + float const SkiLength = 3.0f; + + /* + Larger values for this seem to alleviate the issue to some extent. + */ + float const SkiThickness = 0.3f; + + float const SkiFriction = 0.0f; + float const SkiRestitution = 0.15f; + + b2BodyDef bd; + bd.type = b2_dynamicBody; + + float initial_y = BodyHeight / 2 + SkiThickness; + bd.position.Set(-m_platform_width / 2, initial_y); + + b2Body* skier = m_world->CreateBody(&bd); + + b2PolygonShape ski; + b2Vec2 verts[4]; + verts[0].Set(-SkiLength / 2 - SkiThickness, -BodyHeight / 2); + verts[1].Set(-SkiLength / 2, -BodyHeight / 2 - SkiThickness); + verts[2].Set(SkiLength / 2, -BodyHeight / 2 - SkiThickness); + verts[3].Set(SkiLength / 2 + SkiThickness, -BodyHeight / 2); + ski.Set(verts, 4); + + b2FixtureDef fd; + fd.density = 1.0f; + + fd.friction = SkiFriction; + fd.restitution = SkiRestitution; + + fd.shape = &ski; + skier->CreateFixture(&fd); + + skier->SetLinearVelocity(b2Vec2(0.5f, 0.0f)); + + m_skier = skier; + } + + // g_camera.m_center = b2Vec2(m_platform_width / 2.0f, 0.0f); + // g_camera.m_zoom = 0.4f; + m_fixed_camera = true; + } + + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_C: + m_fixed_camera = !m_fixed_camera; + if (m_fixed_camera) + { + // g_camera.m_center = b2Vec2(m_platform_width / 2.0f, 0.0f); + } + break; + } + } + + void Step(Settings& settings) override + { + DrawString(5, m_textLine, "Keys: c = Camera fixed/tracking"); + + if (!m_fixed_camera) + { + // g_camera.m_center = m_skier->GetPosition(); + } + + Test::Step(settings); + } + + static Test* Create() { return new Skier; } + + b2Body* m_skier; + float m_platform_width; + bool m_fixed_camera; }; static int testIndex = RegisterTest("Bugs", "Skier", Skier::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/slider_crank_1.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/slider_crank_1.cpp index 395b93939edb..e09e8ade1992 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/slider_crank_1.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/slider_crank_1.cpp @@ -26,81 +26,78 @@ class SliderCrank1 : public Test { public: - SliderCrank1() - { - b2Body* ground = NULL; - { - b2BodyDef bd; + SliderCrank1() + { + b2Body* ground = NULL; + { + b2BodyDef bd; bd.position.Set(0.0f, 17.0f); - ground = m_world->CreateBody(&bd); - } - - { - b2Body* prevBody = ground; - - // Define crank. - { - b2PolygonShape shape; - shape.SetAsBox(4.0f, 1.0f); - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-8.0f, 20.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 2.0f); - - b2RevoluteJointDef rjd; - rjd.Initialize(prevBody, body, b2Vec2(-12.0f, 20.0f)); - m_world->CreateJoint(&rjd); - - prevBody = body; - } - - // Define connecting rod - { - b2PolygonShape shape; - shape.SetAsBox(8.0f, 1.0f); - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(4.0f, 20.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 2.0f); - - b2RevoluteJointDef rjd; - rjd.Initialize(prevBody, body, b2Vec2(-4.0f, 20.0f)); - m_world->CreateJoint(&rjd); - - prevBody = body; - } - - // Define piston - { - b2PolygonShape shape; - shape.SetAsBox(3.0f, 3.0f); - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.fixedRotation = true; - bd.position.Set(12.0f, 20.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 2.0f); - - b2RevoluteJointDef rjd; - rjd.Initialize(prevBody, body, b2Vec2(12.0f, 20.0f)); - m_world->CreateJoint(&rjd); - - b2PrismaticJointDef pjd; - pjd.Initialize(ground, body, b2Vec2(12.0f, 17.0f), b2Vec2(1.0f, 0.0f)); - m_world->CreateJoint(&pjd); - } - } - } - - static Test* Create() - { - return new SliderCrank1; - } + ground = m_world->CreateBody(&bd); + } + + { + b2Body* prevBody = ground; + + // Define crank. + { + b2PolygonShape shape; + shape.SetAsBox(4.0f, 1.0f); + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-8.0f, 20.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 2.0f); + + b2RevoluteJointDef rjd; + rjd.Initialize(prevBody, body, b2Vec2(-12.0f, 20.0f)); + m_world->CreateJoint(&rjd); + + prevBody = body; + } + + // Define connecting rod + { + b2PolygonShape shape; + shape.SetAsBox(8.0f, 1.0f); + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(4.0f, 20.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 2.0f); + + b2RevoluteJointDef rjd; + rjd.Initialize(prevBody, body, b2Vec2(-4.0f, 20.0f)); + m_world->CreateJoint(&rjd); + + prevBody = body; + } + + // Define piston + { + b2PolygonShape shape; + shape.SetAsBox(3.0f, 3.0f); + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.fixedRotation = true; + bd.position.Set(12.0f, 20.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 2.0f); + + b2RevoluteJointDef rjd; + rjd.Initialize(prevBody, body, b2Vec2(12.0f, 20.0f)); + m_world->CreateJoint(&rjd); + + b2PrismaticJointDef pjd; + pjd.Initialize(ground, body, b2Vec2(12.0f, 17.0f), b2Vec2(1.0f, 0.0f)); + m_world->CreateJoint(&pjd); + } + } + } + + static Test* Create() { return new SliderCrank1; } }; static int testIndex = RegisterTest("Examples", "Slider Crank 1", SliderCrank1::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/slider_crank_2.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/slider_crank_2.cpp index 22119e803a16..f55a05859cf6 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/slider_crank_2.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/slider_crank_2.cpp @@ -28,133 +28,129 @@ class SliderCrank2 : public Test { public: - SliderCrank2() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - { - b2Body* prevBody = ground; - - // Define crank. - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 2.0f); - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 7.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 2.0f); - - b2RevoluteJointDef rjd; - rjd.Initialize(prevBody, body, b2Vec2(0.0f, 5.0f)); - rjd.motorSpeed = 1.0f * b2_pi; - rjd.maxMotorTorque = 10000.0f; - rjd.enableMotor = true; - m_joint1 = (b2RevoluteJoint*)m_world->CreateJoint(&rjd); - - prevBody = body; - } - - // Define follower. - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 4.0f); - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 13.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 2.0f); - - b2RevoluteJointDef rjd; - rjd.Initialize(prevBody, body, b2Vec2(0.0f, 9.0f)); - rjd.enableMotor = false; - m_world->CreateJoint(&rjd); - - prevBody = body; - } - - // Define piston - { - b2PolygonShape shape; - shape.SetAsBox(1.5f, 1.5f); - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.fixedRotation = true; - bd.position.Set(0.0f, 17.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 2.0f); - - b2RevoluteJointDef rjd; - rjd.Initialize(prevBody, body, b2Vec2(0.0f, 17.0f)); - m_world->CreateJoint(&rjd); - - b2PrismaticJointDef pjd; - pjd.Initialize(ground, body, b2Vec2(0.0f, 17.0f), b2Vec2(0.0f, 1.0f)); - - pjd.maxMotorForce = 1000.0f; - pjd.enableMotor = true; - - m_joint2 = (b2PrismaticJoint*)m_world->CreateJoint(&pjd); - } - - // Create a payload - { - b2PolygonShape shape; - shape.SetAsBox(1.5f, 1.5f); - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 23.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 2.0f); - } - } - } - - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_F: - m_joint2->EnableMotor(!m_joint2->IsMotorEnabled()); - m_joint2->GetBodyB()->SetAwake(true); - break; - - case GLFW_KEY_M: - m_joint1->EnableMotor(!m_joint1->IsMotorEnabled()); - m_joint1->GetBodyB()->SetAwake(true); - break; - } - } - - void Step(Settings& settings) override - { - Test::Step(settings); - DrawString(5, m_textLine, "Keys: (f) toggle friction, (m) toggle motor"); - - float torque = m_joint1->GetMotorTorque(settings.m_hertz); - DrawString(5, m_textLine, "Motor Torque = %5.0f", (float) torque); - - } - - static Test* Create() - { - return new SliderCrank2; - } - - b2RevoluteJoint* m_joint1; - b2PrismaticJoint* m_joint2; + SliderCrank2() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + { + b2Body* prevBody = ground; + + // Define crank. + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 2.0f); + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 7.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 2.0f); + + b2RevoluteJointDef rjd; + rjd.Initialize(prevBody, body, b2Vec2(0.0f, 5.0f)); + rjd.motorSpeed = 1.0f * b2_pi; + rjd.maxMotorTorque = 10000.0f; + rjd.enableMotor = true; + m_joint1 = (b2RevoluteJoint*)m_world->CreateJoint(&rjd); + + prevBody = body; + } + + // Define follower. + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 4.0f); + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 13.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 2.0f); + + b2RevoluteJointDef rjd; + rjd.Initialize(prevBody, body, b2Vec2(0.0f, 9.0f)); + rjd.enableMotor = false; + m_world->CreateJoint(&rjd); + + prevBody = body; + } + + // Define piston + { + b2PolygonShape shape; + shape.SetAsBox(1.5f, 1.5f); + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.fixedRotation = true; + bd.position.Set(0.0f, 17.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 2.0f); + + b2RevoluteJointDef rjd; + rjd.Initialize(prevBody, body, b2Vec2(0.0f, 17.0f)); + m_world->CreateJoint(&rjd); + + b2PrismaticJointDef pjd; + pjd.Initialize(ground, body, b2Vec2(0.0f, 17.0f), b2Vec2(0.0f, 1.0f)); + + pjd.maxMotorForce = 1000.0f; + pjd.enableMotor = true; + + m_joint2 = (b2PrismaticJoint*)m_world->CreateJoint(&pjd); + } + + // Create a payload + { + b2PolygonShape shape; + shape.SetAsBox(1.5f, 1.5f); + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 23.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 2.0f); + } + } + } + + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_F: + m_joint2->EnableMotor(!m_joint2->IsMotorEnabled()); + m_joint2->GetBodyB()->SetAwake(true); + break; + + case GLFW_KEY_M: + m_joint1->EnableMotor(!m_joint1->IsMotorEnabled()); + m_joint1->GetBodyB()->SetAwake(true); + break; + } + } + + void Step(Settings& settings) override + { + Test::Step(settings); + DrawString(5, m_textLine, "Keys: (f) toggle friction, (m) toggle motor"); + + float torque = m_joint1->GetMotorTorque(settings.m_hertz); + DrawString(5, m_textLine, "Motor Torque = %5.0f", (float)torque); + } + + static Test* Create() { return new SliderCrank2; } + + b2RevoluteJoint* m_joint1; + b2PrismaticJoint* m_joint2; }; static int testIndex = RegisterTest("Examples", "Slider Crank 2", SliderCrank2::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/test.h b/tests/cpp-tests/Classes/Box2DTestBed/tests/test.h index 0d81acaa7221..f2a465e72925 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/test.h +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/test.h @@ -1,20 +1,20 @@ /* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ + * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + */ #ifndef TEST_H #define TEST_H @@ -27,123 +27,121 @@ class Test; struct Settings; -#define RAND_LIMIT 32767 +#define RAND_LIMIT 32767 #define DRAW_STRING_NEW_LINE 25 /// Random number in range [-1,1] inline float RandomFloat() { - float r = (float)(std::rand() & (RAND_LIMIT)); - r /= RAND_LIMIT; - r = 2.0f * r - 1.0f; - return r; + float r = (float)(std::rand() & (RAND_LIMIT)); + r /= RAND_LIMIT; + r = 2.0f * r - 1.0f; + return r; } /// Random floating point number in range [lo, hi] inline float RandomFloat(float lo, float hi) { - float r = (float)(std::rand() & (RAND_LIMIT)); - r /= RAND_LIMIT; - r = (hi - lo) * r + lo; - return r; + float r = (float)(std::rand() & (RAND_LIMIT)); + r /= RAND_LIMIT; + r = (hi - lo) * r + lo; + return r; } - // This is called when a joint in the world is implicitly destroyed // because an attached body is destroyed. This gives us a chance to // nullify the mouse joint. class DestructionListener : public b2DestructionListener { public: - void SayGoodbye(b2Fixture* fixture) { B2_NOT_USED(fixture); } - void SayGoodbye(b2Joint* joint); + void SayGoodbye(b2Fixture* fixture) { B2_NOT_USED(fixture); } + void SayGoodbye(b2Joint* joint); - Test* test; + Test* test; }; const int32 k_maxContactPoints = 2048; struct ContactPoint { - b2Fixture* fixtureA; - b2Fixture* fixtureB; - b2Vec2 normal; - b2Vec2 position; - b2PointState state; - float normalImpulse; - float tangentImpulse; - float separation; + b2Fixture* fixtureA; + b2Fixture* fixtureB; + b2Vec2 normal; + b2Vec2 position; + b2PointState state; + float normalImpulse; + float tangentImpulse; + float separation; }; class Test : public b2ContactListener { public: - - Test(); - virtual ~Test(); - - void DrawTitle(const char* string); - virtual void Step(Settings& settings); - virtual void UpdateUI() {} - virtual void Keyboard(int key) { B2_NOT_USED(key); } - virtual void KeyboardUp(int key) { B2_NOT_USED(key); } - void ShiftMouseDown(const b2Vec2& p); - virtual bool MouseDown(const b2Vec2& p); - virtual void MouseUp(const b2Vec2& p); - virtual void MouseMove(const b2Vec2& p); - void LaunchBomb(); - void LaunchBomb(const b2Vec2& position, const b2Vec2& velocity); - - void SpawnBomb(const b2Vec2& worldPt); - void CompleteBombSpawn(const b2Vec2& p); - - // Let derived tests know that a joint was destroyed. - virtual void JointDestroyed(b2Joint* joint) { B2_NOT_USED(joint); } - - // Callbacks for derived classes. - virtual void BeginContact(b2Contact* contact) override { B2_NOT_USED(contact); } - virtual void EndContact(b2Contact* contact) override { B2_NOT_USED(contact); } - virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override; - virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) override - { - B2_NOT_USED(contact); - B2_NOT_USED(impulse); - } - - void ShiftOrigin(const b2Vec2& newOrigin); - - void initShader(void); - void DrawString(int x, int y, const char* fmt, ...); - void DrawString(const b2Vec2& p, const char* fmt, ...); - void DrawAABB(b2AABB* aabb, const b2Color& color); - void Flush(); - - cocos2d::extension::PhysicsDebugNodeBox2D g_debugDraw; - cocos2d::DrawNode* debugDrawNode; - std::string debugString = ""; - - b2World* m_world; + Test(); + virtual ~Test(); + + void DrawTitle(const char* string); + virtual void Step(Settings& settings); + virtual void UpdateUI() {} + virtual void Keyboard(int key) { B2_NOT_USED(key); } + virtual void KeyboardUp(int key) { B2_NOT_USED(key); } + void ShiftMouseDown(const b2Vec2& p); + virtual bool MouseDown(const b2Vec2& p); + virtual void MouseUp(const b2Vec2& p); + virtual void MouseMove(const b2Vec2& p); + void LaunchBomb(); + void LaunchBomb(const b2Vec2& position, const b2Vec2& velocity); + + void SpawnBomb(const b2Vec2& worldPt); + void CompleteBombSpawn(const b2Vec2& p); + + // Let derived tests know that a joint was destroyed. + virtual void JointDestroyed(b2Joint* joint) { B2_NOT_USED(joint); } + + // Callbacks for derived classes. + virtual void BeginContact(b2Contact* contact) override { B2_NOT_USED(contact); } + virtual void EndContact(b2Contact* contact) override { B2_NOT_USED(contact); } + virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override; + virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) override + { + B2_NOT_USED(contact); + B2_NOT_USED(impulse); + } + + void ShiftOrigin(const b2Vec2& newOrigin); + + void initShader(void); + void DrawString(int x, int y, const char* fmt, ...); + void DrawString(const b2Vec2& p, const char* fmt, ...); + void DrawAABB(b2AABB* aabb, const b2Color& color); + void Flush(); + + cocos2d::extension::PhysicsDebugNodeBox2D g_debugDraw; + cocos2d::DrawNode* debugDrawNode; + std::string debugString = ""; + + b2World* m_world; protected: - friend class DestructionListener; - friend class BoundaryListener; - friend class ContactListener; - - b2Body* m_groundBody; - b2AABB m_worldAABB; - ContactPoint m_points[k_maxContactPoints]; - int32 m_pointCount; - DestructionListener m_destructionListener; - int32 m_textLine; - - b2Body* m_bomb; - b2MouseJoint* m_mouseJoint; - b2Vec2 m_bombSpawnPoint; - bool m_bombSpawning; - b2Vec2 m_mouseWorld; - int32 m_stepCount; - int32 m_textIncrement; - b2Profile m_maxProfile; - b2Profile m_totalProfile; + friend class DestructionListener; + friend class BoundaryListener; + friend class ContactListener; + + b2Body* m_groundBody; + b2AABB m_worldAABB; + ContactPoint m_points[k_maxContactPoints]; + int32 m_pointCount; + DestructionListener m_destructionListener; + int32 m_textLine; + + b2Body* m_bomb; + b2MouseJoint* m_mouseJoint; + b2Vec2 m_bombSpawnPoint; + bool m_bombSpawning; + b2Vec2 m_mouseWorld; + int32 m_stepCount; + int32 m_textIncrement; + b2Profile m_maxProfile; + b2Profile m_totalProfile; }; typedef Test* TestCreateFcn(); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/theo_jansen.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/theo_jansen.cpp index 4ff62c7a5d30..cab814037c1c 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/theo_jansen.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/theo_jansen.cpp @@ -28,239 +28,234 @@ class TheoJansen : public Test { public: - - void CreateLeg(float s, const b2Vec2& wheelAnchor) - { - b2Vec2 p1(5.4f * s, -6.1f); - b2Vec2 p2(7.2f * s, -1.2f); - b2Vec2 p3(4.3f * s, -1.9f); - b2Vec2 p4(3.1f * s, 0.8f); - b2Vec2 p5(6.0f * s, 1.5f); - b2Vec2 p6(2.5f * s, 3.7f); - - b2FixtureDef fd1, fd2; - fd1.filter.groupIndex = -1; - fd2.filter.groupIndex = -1; - fd1.density = 1.0f; - fd2.density = 1.0f; - - b2PolygonShape poly1, poly2; - - if (s > 0.0f) - { - b2Vec2 vertices[3]; - - vertices[0] = p1; - vertices[1] = p2; - vertices[2] = p3; - poly1.Set(vertices, 3); - - vertices[0] = b2Vec2_zero; - vertices[1] = p5 - p4; - vertices[2] = p6 - p4; - poly2.Set(vertices, 3); - } - else - { - b2Vec2 vertices[3]; - - vertices[0] = p1; - vertices[1] = p3; - vertices[2] = p2; - poly1.Set(vertices, 3); - - vertices[0] = b2Vec2_zero; - vertices[1] = p6 - p4; - vertices[2] = p5 - p4; - poly2.Set(vertices, 3); - } - - fd1.shape = &poly1; - fd2.shape = &poly2; - - b2BodyDef bd1, bd2; - bd1.type = b2_dynamicBody; - bd2.type = b2_dynamicBody; - bd1.position = m_offset; - bd2.position = p4 + m_offset; - - bd1.angularDamping = 10.0f; - bd2.angularDamping = 10.0f; - - b2Body* body1 = m_world->CreateBody(&bd1); - b2Body* body2 = m_world->CreateBody(&bd2); - - body1->CreateFixture(&fd1); - body2->CreateFixture(&fd2); - - { - b2DistanceJointDef jd; - - // Using a soft distance constraint can reduce some jitter. - // It also makes the structure seem a bit more fluid by - // acting like a suspension system. - float dampingRatio = 0.5f; - float frequencyHz = 10.0f; - - jd.Initialize(body1, body2, p2 + m_offset, p5 + m_offset); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_world->CreateJoint(&jd); - - jd.Initialize(body1, body2, p3 + m_offset, p4 + m_offset); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_world->CreateJoint(&jd); - - jd.Initialize(body1, m_wheel, p3 + m_offset, wheelAnchor + m_offset); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_world->CreateJoint(&jd); - - jd.Initialize(body2, m_wheel, p6 + m_offset, wheelAnchor + m_offset); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_world->CreateJoint(&jd); - } - - { - b2RevoluteJointDef jd; - jd.Initialize(body2, m_chassis, p4 + m_offset); - m_world->CreateJoint(&jd); - } - } - - TheoJansen() - { - m_offset.Set(0.0f, 8.0f); - m_motorSpeed = 2.0f; - m_motorOn = true; - b2Vec2 pivot(0.0f, 0.8f); - - // Ground - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-50.0f, 0.0f), b2Vec2(50.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - - shape.SetTwoSided(b2Vec2(-50.0f, 0.0f), b2Vec2(-50.0f, 10.0f)); - ground->CreateFixture(&shape, 0.0f); - - shape.SetTwoSided(b2Vec2(50.0f, 0.0f), b2Vec2(50.0f, 10.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - // Balls - for (int32 i = 0; i < 40; ++i) - { - b2CircleShape shape; - shape.m_radius = 0.25f; - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-40.0f + 2.0f * i, 0.5f); - - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 1.0f); - } - - // Chassis - { - b2PolygonShape shape; - shape.SetAsBox(2.5f, 1.0f); - - b2FixtureDef sd; - sd.density = 1.0f; - sd.shape = &shape; - sd.filter.groupIndex = -1; - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = pivot + m_offset; - m_chassis = m_world->CreateBody(&bd); - m_chassis->CreateFixture(&sd); - } - - { - b2CircleShape shape; - shape.m_radius = 1.6f; - - b2FixtureDef sd; - sd.density = 1.0f; - sd.shape = &shape; - sd.filter.groupIndex = -1; - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = pivot + m_offset; - m_wheel = m_world->CreateBody(&bd); - m_wheel->CreateFixture(&sd); - } - - { - b2RevoluteJointDef jd; - jd.Initialize(m_wheel, m_chassis, pivot + m_offset); - jd.collideConnected = false; - jd.motorSpeed = m_motorSpeed; - jd.maxMotorTorque = 400.0f; - jd.enableMotor = m_motorOn; - m_motorJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); - } - - b2Vec2 wheelAnchor; - - wheelAnchor = pivot + b2Vec2(0.0f, -0.8f); - - CreateLeg(-1.0f, wheelAnchor); - CreateLeg(1.0f, wheelAnchor); - - m_wheel->SetTransform(m_wheel->GetPosition(), 120.0f * b2_pi / 180.0f); - CreateLeg(-1.0f, wheelAnchor); - CreateLeg(1.0f, wheelAnchor); - - m_wheel->SetTransform(m_wheel->GetPosition(), -120.0f * b2_pi / 180.0f); - CreateLeg(-1.0f, wheelAnchor); - CreateLeg(1.0f, wheelAnchor); - } - - void Step(Settings& settings) override - { - DrawString(5, m_textLine, "Keys: left = a, brake = s, right = d, toggle motor = m"); - - - Test::Step(settings); - } - - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_A: - m_motorJoint->SetMotorSpeed(-m_motorSpeed); - break; - - case GLFW_KEY_S: - m_motorJoint->SetMotorSpeed(0.0f); - break; - - case GLFW_KEY_D: - m_motorJoint->SetMotorSpeed(m_motorSpeed); - break; - - case GLFW_KEY_M: - m_motorJoint->EnableMotor(!m_motorJoint->IsMotorEnabled()); - break; - } - } - - static Test* Create() - { - return new TheoJansen; - } - - b2Vec2 m_offset; - b2Body* m_chassis; - b2Body* m_wheel; - b2RevoluteJoint* m_motorJoint; - bool m_motorOn; - float m_motorSpeed; + void CreateLeg(float s, const b2Vec2& wheelAnchor) + { + b2Vec2 p1(5.4f * s, -6.1f); + b2Vec2 p2(7.2f * s, -1.2f); + b2Vec2 p3(4.3f * s, -1.9f); + b2Vec2 p4(3.1f * s, 0.8f); + b2Vec2 p5(6.0f * s, 1.5f); + b2Vec2 p6(2.5f * s, 3.7f); + + b2FixtureDef fd1, fd2; + fd1.filter.groupIndex = -1; + fd2.filter.groupIndex = -1; + fd1.density = 1.0f; + fd2.density = 1.0f; + + b2PolygonShape poly1, poly2; + + if (s > 0.0f) + { + b2Vec2 vertices[3]; + + vertices[0] = p1; + vertices[1] = p2; + vertices[2] = p3; + poly1.Set(vertices, 3); + + vertices[0] = b2Vec2_zero; + vertices[1] = p5 - p4; + vertices[2] = p6 - p4; + poly2.Set(vertices, 3); + } + else + { + b2Vec2 vertices[3]; + + vertices[0] = p1; + vertices[1] = p3; + vertices[2] = p2; + poly1.Set(vertices, 3); + + vertices[0] = b2Vec2_zero; + vertices[1] = p6 - p4; + vertices[2] = p5 - p4; + poly2.Set(vertices, 3); + } + + fd1.shape = &poly1; + fd2.shape = &poly2; + + b2BodyDef bd1, bd2; + bd1.type = b2_dynamicBody; + bd2.type = b2_dynamicBody; + bd1.position = m_offset; + bd2.position = p4 + m_offset; + + bd1.angularDamping = 10.0f; + bd2.angularDamping = 10.0f; + + b2Body* body1 = m_world->CreateBody(&bd1); + b2Body* body2 = m_world->CreateBody(&bd2); + + body1->CreateFixture(&fd1); + body2->CreateFixture(&fd2); + + { + b2DistanceJointDef jd; + + // Using a soft distance constraint can reduce some jitter. + // It also makes the structure seem a bit more fluid by + // acting like a suspension system. + float dampingRatio = 0.5f; + float frequencyHz = 10.0f; + + jd.Initialize(body1, body2, p2 + m_offset, p5 + m_offset); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_world->CreateJoint(&jd); + + jd.Initialize(body1, body2, p3 + m_offset, p4 + m_offset); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_world->CreateJoint(&jd); + + jd.Initialize(body1, m_wheel, p3 + m_offset, wheelAnchor + m_offset); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_world->CreateJoint(&jd); + + jd.Initialize(body2, m_wheel, p6 + m_offset, wheelAnchor + m_offset); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_world->CreateJoint(&jd); + } + + { + b2RevoluteJointDef jd; + jd.Initialize(body2, m_chassis, p4 + m_offset); + m_world->CreateJoint(&jd); + } + } + + TheoJansen() + { + m_offset.Set(0.0f, 8.0f); + m_motorSpeed = 2.0f; + m_motorOn = true; + b2Vec2 pivot(0.0f, 0.8f); + + // Ground + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-50.0f, 0.0f), b2Vec2(50.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + + shape.SetTwoSided(b2Vec2(-50.0f, 0.0f), b2Vec2(-50.0f, 10.0f)); + ground->CreateFixture(&shape, 0.0f); + + shape.SetTwoSided(b2Vec2(50.0f, 0.0f), b2Vec2(50.0f, 10.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + // Balls + for (int32 i = 0; i < 40; ++i) + { + b2CircleShape shape; + shape.m_radius = 0.25f; + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-40.0f + 2.0f * i, 0.5f); + + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 1.0f); + } + + // Chassis + { + b2PolygonShape shape; + shape.SetAsBox(2.5f, 1.0f); + + b2FixtureDef sd; + sd.density = 1.0f; + sd.shape = &shape; + sd.filter.groupIndex = -1; + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = pivot + m_offset; + m_chassis = m_world->CreateBody(&bd); + m_chassis->CreateFixture(&sd); + } + + { + b2CircleShape shape; + shape.m_radius = 1.6f; + + b2FixtureDef sd; + sd.density = 1.0f; + sd.shape = &shape; + sd.filter.groupIndex = -1; + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = pivot + m_offset; + m_wheel = m_world->CreateBody(&bd); + m_wheel->CreateFixture(&sd); + } + + { + b2RevoluteJointDef jd; + jd.Initialize(m_wheel, m_chassis, pivot + m_offset); + jd.collideConnected = false; + jd.motorSpeed = m_motorSpeed; + jd.maxMotorTorque = 400.0f; + jd.enableMotor = m_motorOn; + m_motorJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); + } + + b2Vec2 wheelAnchor; + + wheelAnchor = pivot + b2Vec2(0.0f, -0.8f); + + CreateLeg(-1.0f, wheelAnchor); + CreateLeg(1.0f, wheelAnchor); + + m_wheel->SetTransform(m_wheel->GetPosition(), 120.0f * b2_pi / 180.0f); + CreateLeg(-1.0f, wheelAnchor); + CreateLeg(1.0f, wheelAnchor); + + m_wheel->SetTransform(m_wheel->GetPosition(), -120.0f * b2_pi / 180.0f); + CreateLeg(-1.0f, wheelAnchor); + CreateLeg(1.0f, wheelAnchor); + } + + void Step(Settings& settings) override + { + DrawString(5, m_textLine, "Keys: left = a, brake = s, right = d, toggle motor = m"); + + Test::Step(settings); + } + + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_A: + m_motorJoint->SetMotorSpeed(-m_motorSpeed); + break; + + case GLFW_KEY_S: + m_motorJoint->SetMotorSpeed(0.0f); + break; + + case GLFW_KEY_D: + m_motorJoint->SetMotorSpeed(m_motorSpeed); + break; + + case GLFW_KEY_M: + m_motorJoint->EnableMotor(!m_motorJoint->IsMotorEnabled()); + break; + } + } + + static Test* Create() { return new TheoJansen; } + + b2Vec2 m_offset; + b2Body* m_chassis; + b2Body* m_wheel; + b2RevoluteJoint* m_motorJoint; + bool m_motorOn; + float m_motorSpeed; }; static int testIndex = RegisterTest("Examples", "Theo Jansen", TheoJansen::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/tiles.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/tiles.cpp index 945786219669..e5b9b5dd5f40 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/tiles.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/tiles.cpp @@ -27,133 +27,127 @@ class Tiles : public Test { public: - enum - { - e_count = 20 - }; - - Tiles() - { - m_fixtureCount = 0; - b2Timer timer; - - { - float a = 0.5f; - b2BodyDef bd; - bd.position.y = -a; - b2Body* ground = m_world->CreateBody(&bd); + enum + { + e_count = 20 + }; + + Tiles() + { + m_fixtureCount = 0; + b2Timer timer; + + { + float a = 0.5f; + b2BodyDef bd; + bd.position.y = -a; + b2Body* ground = m_world->CreateBody(&bd); #if 1 - int32 N = 200; - int32 M = 10; - b2Vec2 position; - position.y = 0.0f; - for (int32 j = 0; j < M; ++j) - { - position.x = -N * a; - for (int32 i = 0; i < N; ++i) - { - b2PolygonShape shape; - shape.SetAsBox(a, a, position, 0.0f); - ground->CreateFixture(&shape, 0.0f); - ++m_fixtureCount; - position.x += 2.0f * a; - } - position.y -= 2.0f * a; - } + int32 N = 200; + int32 M = 10; + b2Vec2 position; + position.y = 0.0f; + for (int32 j = 0; j < M; ++j) + { + position.x = -N * a; + for (int32 i = 0; i < N; ++i) + { + b2PolygonShape shape; + shape.SetAsBox(a, a, position, 0.0f); + ground->CreateFixture(&shape, 0.0f); + ++m_fixtureCount; + position.x += 2.0f * a; + } + position.y -= 2.0f * a; + } #else - int32 N = 200; - int32 M = 10; - b2Vec2 position; - position.x = -N * a; - for (int32 i = 0; i < N; ++i) - { - position.y = 0.0f; - for (int32 j = 0; j < M; ++j) - { - b2PolygonShape shape; - shape.SetAsBox(a, a, position, 0.0f); - ground->CreateFixture(&shape, 0.0f); - position.y -= 2.0f * a; - } - position.x += 2.0f * a; - } + int32 N = 200; + int32 M = 10; + b2Vec2 position; + position.x = -N * a; + for (int32 i = 0; i < N; ++i) + { + position.y = 0.0f; + for (int32 j = 0; j < M; ++j) + { + b2PolygonShape shape; + shape.SetAsBox(a, a, position, 0.0f); + ground->CreateFixture(&shape, 0.0f); + position.y -= 2.0f * a; + } + position.x += 2.0f * a; + } #endif - } - - { - float a = 0.5f; - b2PolygonShape shape; - shape.SetAsBox(a, a); - - b2Vec2 x(-7.0f, 0.75f); - b2Vec2 y; - b2Vec2 deltaX(0.5625f, 1.25f); - b2Vec2 deltaY(1.125f, 0.0f); - - for (int32 i = 0; i < e_count; ++i) - { - y = x; - - for (int32 j = i; j < e_count; ++j) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = y; - - //if (i == 0 && j == 0) - //{ - // bd.allowSleep = false; - //} - //else - //{ - // bd.allowSleep = true; - //} - - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 5.0f); - ++m_fixtureCount; - y += deltaY; - } - - x += deltaX; - } - } - - m_createTime = timer.GetMilliseconds(); - } - - void Step(Settings& settings) override - { - const b2ContactManager& cm = m_world->GetContactManager(); - int32 height = cm.m_broadPhase.GetTreeHeight(); - int32 leafCount = cm.m_broadPhase.GetProxyCount(); - int32 minimumNodeCount = 2 * leafCount - 1; - float minimumHeight = ceilf(logf(float(minimumNodeCount)) / logf(2.0f)); - DrawString(5, m_textLine, "dynamic tree height = %d, min = %d", height, int32(minimumHeight)); - - - Test::Step(settings); - - DrawString(5, m_textLine, "create time = %6.2f ms, fixture count = %d", - m_createTime, m_fixtureCount); - - - //b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_tree; - - //if (m_stepCount == 400) - //{ - // tree->RebuildBottomUp(); - //} - } - - static Test* Create() - { - return new Tiles; - } - - int32 m_fixtureCount; - float m_createTime; + } + + { + float a = 0.5f; + b2PolygonShape shape; + shape.SetAsBox(a, a); + + b2Vec2 x(-7.0f, 0.75f); + b2Vec2 y; + b2Vec2 deltaX(0.5625f, 1.25f); + b2Vec2 deltaY(1.125f, 0.0f); + + for (int32 i = 0; i < e_count; ++i) + { + y = x; + + for (int32 j = i; j < e_count; ++j) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = y; + + // if (i == 0 && j == 0) + //{ + // bd.allowSleep = false; + // } + // else + //{ + // bd.allowSleep = true; + // } + + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 5.0f); + ++m_fixtureCount; + y += deltaY; + } + + x += deltaX; + } + } + + m_createTime = timer.GetMilliseconds(); + } + + void Step(Settings& settings) override + { + const b2ContactManager& cm = m_world->GetContactManager(); + int32 height = cm.m_broadPhase.GetTreeHeight(); + int32 leafCount = cm.m_broadPhase.GetProxyCount(); + int32 minimumNodeCount = 2 * leafCount - 1; + float minimumHeight = ceilf(logf(float(minimumNodeCount)) / logf(2.0f)); + DrawString(5, m_textLine, "dynamic tree height = %d, min = %d", height, int32(minimumHeight)); + + Test::Step(settings); + + DrawString(5, m_textLine, "create time = %6.2f ms, fixture count = %d", m_createTime, m_fixtureCount); + + // b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_tree; + + // if (m_stepCount == 400) + //{ + // tree->RebuildBottomUp(); + // } + } + + static Test* Create() { return new Tiles; } + + int32 m_fixtureCount; + float m_createTime; }; static int testIndex = RegisterTest("Benchmark", "Tiles", Tiles::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/time_of_impact.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/time_of_impact.cpp index 3face36e2270..f33b53476ddd 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/time_of_impact.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/time_of_impact.cpp @@ -26,90 +26,85 @@ class TimeOfImpact : public Test { public: - TimeOfImpact() - { - m_shapeA.SetAsBox(25.0f, 5.0f); - m_shapeB.SetAsBox(2.5f, 2.5f); - } - - static Test* Create() - { - return new TimeOfImpact; - } - - void Step(Settings& settings) override - { - Test::Step(settings); - - b2Sweep sweepA; - sweepA.c0.Set(24.0f, -60.0f); - sweepA.a0 = 2.95f; - sweepA.c = sweepA.c0; - sweepA.a = sweepA.a0; - sweepA.localCenter.SetZero(); - - b2Sweep sweepB; - sweepB.c0.Set(53.474274f, -50.252514f); - sweepB.a0 = 513.36676f; // - 162.0f * b2_pi; - sweepB.c.Set(54.595478f, -51.083473f); - sweepB.a = 513.62781f; // - 162.0f * b2_pi; - sweepB.localCenter.SetZero(); - - //sweepB.a0 -= 300.0f * b2_pi; - //sweepB.a -= 300.0f * b2_pi; - - b2TOIInput input; - input.proxyA.Set(&m_shapeA, 0); - input.proxyB.Set(&m_shapeB, 0); - input.sweepA = sweepA; - input.sweepB = sweepB; - input.tMax = 1.0f; - - b2TOIOutput output; - - b2TimeOfImpact(&output, &input); - - DrawString(5, m_textLine, "toi = %g", output.t); - - - extern B2_API int32 b2_toiMaxIters, b2_toiMaxRootIters; - DrawString(5, m_textLine, "max toi iters = %d, max root iters = %d", b2_toiMaxIters, b2_toiMaxRootIters); - - - b2Vec2 vertices[b2_maxPolygonVertices]; - - b2Transform transformA; - sweepA.GetTransform(&transformA, 0.0f); - for (int32 i = 0; i < m_shapeA.m_count; ++i) - { - vertices[i] = b2Mul(transformA, m_shapeA.m_vertices[i]); - } - g_debugDraw.DrawPolygon(vertices, m_shapeA.m_count, b2Color(0.9f, 0.9f, 0.9f)); - - b2Transform transformB; - sweepB.GetTransform(&transformB, 0.0f); - - //b2Vec2 localPoint(2.0f, -0.1f); - - for (int32 i = 0; i < m_shapeB.m_count; ++i) - { - vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); - } - g_debugDraw.DrawPolygon(vertices, m_shapeB.m_count, b2Color(0.5f, 0.9f, 0.5f)); - - sweepB.GetTransform(&transformB, output.t); - for (int32 i = 0; i < m_shapeB.m_count; ++i) - { - vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); - } - g_debugDraw.DrawPolygon(vertices, m_shapeB.m_count, b2Color(0.5f, 0.7f, 0.9f)); - - sweepB.GetTransform(&transformB, 1.0f); - for (int32 i = 0; i < m_shapeB.m_count; ++i) - { - vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); - } - g_debugDraw.DrawPolygon(vertices, m_shapeB.m_count, b2Color(0.9f, 0.5f, 0.5f)); + TimeOfImpact() + { + m_shapeA.SetAsBox(25.0f, 5.0f); + m_shapeB.SetAsBox(2.5f, 2.5f); + } + + static Test* Create() { return new TimeOfImpact; } + + void Step(Settings& settings) override + { + Test::Step(settings); + + b2Sweep sweepA; + sweepA.c0.Set(24.0f, -60.0f); + sweepA.a0 = 2.95f; + sweepA.c = sweepA.c0; + sweepA.a = sweepA.a0; + sweepA.localCenter.SetZero(); + + b2Sweep sweepB; + sweepB.c0.Set(53.474274f, -50.252514f); + sweepB.a0 = 513.36676f; // - 162.0f * b2_pi; + sweepB.c.Set(54.595478f, -51.083473f); + sweepB.a = 513.62781f; // - 162.0f * b2_pi; + sweepB.localCenter.SetZero(); + + // sweepB.a0 -= 300.0f * b2_pi; + // sweepB.a -= 300.0f * b2_pi; + + b2TOIInput input; + input.proxyA.Set(&m_shapeA, 0); + input.proxyB.Set(&m_shapeB, 0); + input.sweepA = sweepA; + input.sweepB = sweepB; + input.tMax = 1.0f; + + b2TOIOutput output; + + b2TimeOfImpact(&output, &input); + + DrawString(5, m_textLine, "toi = %g", output.t); + + extern B2_API int32 b2_toiMaxIters, b2_toiMaxRootIters; + DrawString(5, m_textLine, "max toi iters = %d, max root iters = %d", b2_toiMaxIters, b2_toiMaxRootIters); + + b2Vec2 vertices[b2_maxPolygonVertices]; + + b2Transform transformA; + sweepA.GetTransform(&transformA, 0.0f); + for (int32 i = 0; i < m_shapeA.m_count; ++i) + { + vertices[i] = b2Mul(transformA, m_shapeA.m_vertices[i]); + } + g_debugDraw.DrawPolygon(vertices, m_shapeA.m_count, b2Color(0.9f, 0.9f, 0.9f)); + + b2Transform transformB; + sweepB.GetTransform(&transformB, 0.0f); + + // b2Vec2 localPoint(2.0f, -0.1f); + + for (int32 i = 0; i < m_shapeB.m_count; ++i) + { + vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); + } + g_debugDraw.DrawPolygon(vertices, m_shapeB.m_count, b2Color(0.5f, 0.9f, 0.5f)); + + sweepB.GetTransform(&transformB, output.t); + for (int32 i = 0; i < m_shapeB.m_count; ++i) + { + vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); + } + g_debugDraw.DrawPolygon(vertices, m_shapeB.m_count, b2Color(0.5f, 0.7f, 0.9f)); + + sweepB.GetTransform(&transformB, 1.0f); + for (int32 i = 0; i < m_shapeB.m_count; ++i) + { + vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); + } + g_debugDraw.DrawPolygon(vertices, m_shapeB.m_count, b2Color(0.9f, 0.5f, 0.5f)); #if 0 for (float t = 0.0f; t < 1.0f; t += 0.1f) @@ -122,10 +117,10 @@ class TimeOfImpact : public Test g_debugDraw.DrawPolygon(vertices, m_shapeB.m_count, b2Color(0.9f, 0.5f, 0.5f)); } #endif - } + } - b2PolygonShape m_shapeA; - b2PolygonShape m_shapeB; + b2PolygonShape m_shapeA; + b2PolygonShape m_shapeB; }; static int testIndex = RegisterTest("Collision", "Time of Impact", TimeOfImpact::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/tumbler.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/tumbler.cpp index f7972bc777cb..e19ffae13f29 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/tumbler.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/tumbler.cpp @@ -25,78 +25,74 @@ class Tumbler : public Test { public: - - enum - { - e_count = 800 - }; - - Tumbler() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); - } - - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.allowSleep = false; - bd.position.Set(0.0f, 10.0f); - b2Body* body = m_world->CreateBody(&bd); - - b2PolygonShape shape; - shape.SetAsBox(0.5f, 10.0f, b2Vec2( 10.0f, 0.0f), 0.0); - body->CreateFixture(&shape, 5.0f); - shape.SetAsBox(0.5f, 10.0f, b2Vec2(-10.0f, 0.0f), 0.0); - body->CreateFixture(&shape, 5.0f); - shape.SetAsBox(10.0f, 0.5f, b2Vec2(0.0f, 10.0f), 0.0); - body->CreateFixture(&shape, 5.0f); - shape.SetAsBox(10.0f, 0.5f, b2Vec2(0.0f, -10.0f), 0.0); - body->CreateFixture(&shape, 5.0f); - - b2RevoluteJointDef jd; - jd.bodyA = ground; - jd.bodyB = body; - jd.localAnchorA.Set(0.0f, 10.0f); - jd.localAnchorB.Set(0.0f, 0.0f); - jd.referenceAngle = 0.0f; - jd.motorSpeed = 0.05f * b2_pi; - jd.maxMotorTorque = 1e8f; - jd.enableMotor = true; - m_joint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); - } - - m_count = 0; - } - - void Step(Settings& settings) override - { - Test::Step(settings); - - if (m_count < e_count) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 10.0f); - b2Body* body = m_world->CreateBody(&bd); - - b2PolygonShape shape; - shape.SetAsBox(0.125f, 0.125f); - body->CreateFixture(&shape, 1.0f); - - ++m_count; - } - } - - static Test* Create() - { - return new Tumbler; - } - - b2RevoluteJoint* m_joint; - int32 m_count; + enum + { + e_count = 800 + }; + + Tumbler() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + } + + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.allowSleep = false; + bd.position.Set(0.0f, 10.0f); + b2Body* body = m_world->CreateBody(&bd); + + b2PolygonShape shape; + shape.SetAsBox(0.5f, 10.0f, b2Vec2(10.0f, 0.0f), 0.0); + body->CreateFixture(&shape, 5.0f); + shape.SetAsBox(0.5f, 10.0f, b2Vec2(-10.0f, 0.0f), 0.0); + body->CreateFixture(&shape, 5.0f); + shape.SetAsBox(10.0f, 0.5f, b2Vec2(0.0f, 10.0f), 0.0); + body->CreateFixture(&shape, 5.0f); + shape.SetAsBox(10.0f, 0.5f, b2Vec2(0.0f, -10.0f), 0.0); + body->CreateFixture(&shape, 5.0f); + + b2RevoluteJointDef jd; + jd.bodyA = ground; + jd.bodyB = body; + jd.localAnchorA.Set(0.0f, 10.0f); + jd.localAnchorB.Set(0.0f, 0.0f); + jd.referenceAngle = 0.0f; + jd.motorSpeed = 0.05f * b2_pi; + jd.maxMotorTorque = 1e8f; + jd.enableMotor = true; + m_joint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); + } + + m_count = 0; + } + + void Step(Settings& settings) override + { + Test::Step(settings); + + if (m_count < e_count) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 10.0f); + b2Body* body = m_world->CreateBody(&bd); + + b2PolygonShape shape; + shape.SetAsBox(0.125f, 0.125f); + body->CreateFixture(&shape, 1.0f); + + ++m_count; + } + } + + static Test* Create() { return new Tumbler; } + + b2RevoluteJoint* m_joint; + int32 m_count; }; static int testIndex = RegisterTest("Benchmark", "Tumbler", Tumbler::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/web.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/web.cpp index fdacf8aa8034..658bc9f87bc0 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/web.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/web.cpp @@ -26,193 +26,190 @@ class Web : public Test { public: - Web() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.5f); - - b2BodyDef bd; - bd.type = b2_dynamicBody; - - bd.position.Set(-5.0f, 5.0f); - m_bodies[0] = m_world->CreateBody(&bd); - m_bodies[0]->CreateFixture(&shape, 5.0f); - - bd.position.Set(5.0f, 5.0f); - m_bodies[1] = m_world->CreateBody(&bd); - m_bodies[1]->CreateFixture(&shape, 5.0f); - - bd.position.Set(5.0f, 15.0f); - m_bodies[2] = m_world->CreateBody(&bd); - m_bodies[2]->CreateFixture(&shape, 5.0f); - - bd.position.Set(-5.0f, 15.0f); - m_bodies[3] = m_world->CreateBody(&bd); - m_bodies[3]->CreateFixture(&shape, 5.0f); - - b2DistanceJointDef jd; - b2Vec2 p1, p2, d; - - float frequencyHz = 2.0f; - float dampingRatio = 0.0f; - - jd.bodyA = ground; - jd.bodyB = m_bodies[0]; - jd.localAnchorA.Set(-10.0f, 0.0f); - jd.localAnchorB.Set(-0.5f, -0.5f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_joints[0] = m_world->CreateJoint(&jd); - - jd.bodyA = ground; - jd.bodyB = m_bodies[1]; - jd.localAnchorA.Set(10.0f, 0.0f); - jd.localAnchorB.Set(0.5f, -0.5f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_joints[1] = m_world->CreateJoint(&jd); - - jd.bodyA = ground; - jd.bodyB = m_bodies[2]; - jd.localAnchorA.Set(10.0f, 20.0f); - jd.localAnchorB.Set(0.5f, 0.5f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_joints[2] = m_world->CreateJoint(&jd); - - jd.bodyA = ground; - jd.bodyB = m_bodies[3]; - jd.localAnchorA.Set(-10.0f, 20.0f); - jd.localAnchorB.Set(-0.5f, 0.5f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_joints[3] = m_world->CreateJoint(&jd); - - jd.bodyA = m_bodies[0]; - jd.bodyB = m_bodies[1]; - jd.localAnchorA.Set(0.5f, 0.0f); - jd.localAnchorB.Set(-0.5f, 0.0f);; - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_joints[4] = m_world->CreateJoint(&jd); - - jd.bodyA = m_bodies[1]; - jd.bodyB = m_bodies[2]; - jd.localAnchorA.Set(0.0f, 0.5f); - jd.localAnchorB.Set(0.0f, -0.5f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_joints[5] = m_world->CreateJoint(&jd); - - jd.bodyA = m_bodies[2]; - jd.bodyB = m_bodies[3]; - jd.localAnchorA.Set(-0.5f, 0.0f); - jd.localAnchorB.Set(0.5f, 0.0f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_joints[6] = m_world->CreateJoint(&jd); - - jd.bodyA = m_bodies[3]; - jd.bodyB = m_bodies[0]; - jd.localAnchorA.Set(0.0f, -0.5f); - jd.localAnchorB.Set(0.0f, 0.5f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); - m_joints[7] = m_world->CreateJoint(&jd); - } - } - - void Keyboard(int key) override - { - switch (key) - { - case GLFW_KEY_B: - for (int32 i = 0; i < 4; ++i) - { - if (m_bodies[i]) - { - m_world->DestroyBody(m_bodies[i]); - m_bodies[i] = NULL; - break; - } - } - break; - - case GLFW_KEY_J: - for (int32 i = 0; i < 8; ++i) - { - if (m_joints[i]) - { - m_world->DestroyJoint(m_joints[i]); - m_joints[i] = NULL; - break; - } - } - break; - } - } - - void Step(Settings& settings) override - { - Test::Step(settings); - DrawString(5, m_textLine, "Press: (b) to delete a body, (j) to delete a joint"); - - } - - void JointDestroyed(b2Joint* joint) override - { - for (int32 i = 0; i < 8; ++i) - { - if (m_joints[i] == joint) - { - m_joints[i] = NULL; - break; - } - } - } - - static Test* Create() - { - return new Web; - } - - b2Body* m_bodies[4]; - b2Joint* m_joints[8]; + Web() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); + + b2BodyDef bd; + bd.type = b2_dynamicBody; + + bd.position.Set(-5.0f, 5.0f); + m_bodies[0] = m_world->CreateBody(&bd); + m_bodies[0]->CreateFixture(&shape, 5.0f); + + bd.position.Set(5.0f, 5.0f); + m_bodies[1] = m_world->CreateBody(&bd); + m_bodies[1]->CreateFixture(&shape, 5.0f); + + bd.position.Set(5.0f, 15.0f); + m_bodies[2] = m_world->CreateBody(&bd); + m_bodies[2]->CreateFixture(&shape, 5.0f); + + bd.position.Set(-5.0f, 15.0f); + m_bodies[3] = m_world->CreateBody(&bd); + m_bodies[3]->CreateFixture(&shape, 5.0f); + + b2DistanceJointDef jd; + b2Vec2 p1, p2, d; + + float frequencyHz = 2.0f; + float dampingRatio = 0.0f; + + jd.bodyA = ground; + jd.bodyB = m_bodies[0]; + jd.localAnchorA.Set(-10.0f, 0.0f); + jd.localAnchorB.Set(-0.5f, -0.5f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_joints[0] = m_world->CreateJoint(&jd); + + jd.bodyA = ground; + jd.bodyB = m_bodies[1]; + jd.localAnchorA.Set(10.0f, 0.0f); + jd.localAnchorB.Set(0.5f, -0.5f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_joints[1] = m_world->CreateJoint(&jd); + + jd.bodyA = ground; + jd.bodyB = m_bodies[2]; + jd.localAnchorA.Set(10.0f, 20.0f); + jd.localAnchorB.Set(0.5f, 0.5f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_joints[2] = m_world->CreateJoint(&jd); + + jd.bodyA = ground; + jd.bodyB = m_bodies[3]; + jd.localAnchorA.Set(-10.0f, 20.0f); + jd.localAnchorB.Set(-0.5f, 0.5f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_joints[3] = m_world->CreateJoint(&jd); + + jd.bodyA = m_bodies[0]; + jd.bodyB = m_bodies[1]; + jd.localAnchorA.Set(0.5f, 0.0f); + jd.localAnchorB.Set(-0.5f, 0.0f); + ; + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_joints[4] = m_world->CreateJoint(&jd); + + jd.bodyA = m_bodies[1]; + jd.bodyB = m_bodies[2]; + jd.localAnchorA.Set(0.0f, 0.5f); + jd.localAnchorB.Set(0.0f, -0.5f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_joints[5] = m_world->CreateJoint(&jd); + + jd.bodyA = m_bodies[2]; + jd.bodyB = m_bodies[3]; + jd.localAnchorA.Set(-0.5f, 0.0f); + jd.localAnchorB.Set(0.5f, 0.0f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_joints[6] = m_world->CreateJoint(&jd); + + jd.bodyA = m_bodies[3]; + jd.bodyB = m_bodies[0]; + jd.localAnchorA.Set(0.0f, -0.5f); + jd.localAnchorB.Set(0.0f, 0.5f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + b2LinearStiffness(jd.stiffness, jd.damping, frequencyHz, dampingRatio, jd.bodyA, jd.bodyB); + m_joints[7] = m_world->CreateJoint(&jd); + } + } + + void Keyboard(int key) override + { + switch (key) + { + case GLFW_KEY_B: + for (int32 i = 0; i < 4; ++i) + { + if (m_bodies[i]) + { + m_world->DestroyBody(m_bodies[i]); + m_bodies[i] = NULL; + break; + } + } + break; + + case GLFW_KEY_J: + for (int32 i = 0; i < 8; ++i) + { + if (m_joints[i]) + { + m_world->DestroyJoint(m_joints[i]); + m_joints[i] = NULL; + break; + } + } + break; + } + } + + void Step(Settings& settings) override + { + Test::Step(settings); + DrawString(5, m_textLine, "Press: (b) to delete a body, (j) to delete a joint"); + } + + void JointDestroyed(b2Joint* joint) override + { + for (int32 i = 0; i < 8; ++i) + { + if (m_joints[i] == joint) + { + m_joints[i] = NULL; + break; + } + } + } + + static Test* Create() { return new Web; } + + b2Body* m_bodies[4]; + b2Joint* m_joints[8]; }; static int testIndex = RegisterTest("Examples", "Web", Web::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/wheel_joint.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/wheel_joint.cpp index 6be76ff26252..0388e757088a 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/wheel_joint.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/wheel_joint.cpp @@ -28,99 +28,94 @@ class WheelJoint : public Test { public: - WheelJoint() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - m_enableLimit = true; - m_enableMotor = false; - m_motorSpeed = 10.0f; - - { - b2CircleShape shape; - shape.m_radius = 2.0f; - - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 10.0f); - bd.allowSleep = false; - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 5.0f); - - b2WheelJointDef jd; - - // Horizontal - jd.Initialize(ground, body, bd.position, b2Vec2(0.0f, 1.0f)); - - jd.motorSpeed = m_motorSpeed; - jd.maxMotorTorque = 10000.0f; - jd.enableMotor = m_enableMotor; - jd.lowerTranslation = -3.0f; - jd.upperTranslation = 3.0f; - jd.enableLimit = m_enableLimit; - - float hertz = 1.0f; - float dampingRatio = 0.7f; - b2LinearStiffness(jd.stiffness, jd.damping, hertz, dampingRatio, ground, body); - - m_joint = (b2WheelJoint*)m_world->CreateJoint(&jd); - } - } - - void Step(Settings& settings) override - { - Test::Step(settings); - - float torque = m_joint->GetMotorTorque(settings.m_hertz); - DrawString(5, m_textLine, "Motor Torque = %4.0f", torque); - - - b2Vec2 F = m_joint->GetReactionForce(settings.m_hertz); - DrawString(5, m_textLine, "Reaction Force = (%4.1f, %4.1f)", F.x, F.y); - - } - - void UpdateUI() override - { - //ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); - ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); - ImGui::Begin("Joint Controls", nullptr, ImGuiWindowFlags_NoResize); - - if (ImGui::Checkbox("Limit", &m_enableLimit)) - { - m_joint->EnableLimit(m_enableLimit); - } - - if (ImGui::Checkbox("Motor", &m_enableMotor)) - { - m_joint->EnableMotor(m_enableMotor); - } - - if (ImGui::SliderFloat("Speed", &m_motorSpeed, -100.0f, 100.0f, "%.0f")) - { - m_joint->SetMotorSpeed(m_motorSpeed); - } - - ImGui::End(); - } - - static Test* Create() - { - return new WheelJoint; - } - - b2WheelJoint* m_joint; - float m_motorSpeed; - bool m_enableMotor; - bool m_enableLimit; + WheelJoint() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + m_enableLimit = true; + m_enableMotor = false; + m_motorSpeed = 10.0f; + + { + b2CircleShape shape; + shape.m_radius = 2.0f; + + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 10.0f); + bd.allowSleep = false; + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 5.0f); + + b2WheelJointDef jd; + + // Horizontal + jd.Initialize(ground, body, bd.position, b2Vec2(0.0f, 1.0f)); + + jd.motorSpeed = m_motorSpeed; + jd.maxMotorTorque = 10000.0f; + jd.enableMotor = m_enableMotor; + jd.lowerTranslation = -3.0f; + jd.upperTranslation = 3.0f; + jd.enableLimit = m_enableLimit; + + float hertz = 1.0f; + float dampingRatio = 0.7f; + b2LinearStiffness(jd.stiffness, jd.damping, hertz, dampingRatio, ground, body); + + m_joint = (b2WheelJoint*)m_world->CreateJoint(&jd); + } + } + + void Step(Settings& settings) override + { + Test::Step(settings); + + float torque = m_joint->GetMotorTorque(settings.m_hertz); + DrawString(5, m_textLine, "Motor Torque = %4.0f", torque); + + b2Vec2 F = m_joint->GetReactionForce(settings.m_hertz); + DrawString(5, m_textLine, "Reaction Force = (%4.1f, %4.1f)", F.x, F.y); + } + + void UpdateUI() override + { + // ImGui::SetNextWindowPos(ImVec2(10.0f, 100.0f)); + ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); + ImGui::Begin("Joint Controls", nullptr, ImGuiWindowFlags_NoResize); + + if (ImGui::Checkbox("Limit", &m_enableLimit)) + { + m_joint->EnableLimit(m_enableLimit); + } + + if (ImGui::Checkbox("Motor", &m_enableMotor)) + { + m_joint->EnableMotor(m_enableMotor); + } + + if (ImGui::SliderFloat("Speed", &m_motorSpeed, -100.0f, 100.0f, "%.0f")) + { + m_joint->SetMotorSpeed(m_motorSpeed); + } + + ImGui::End(); + } + + static Test* Create() { return new WheelJoint; } + + b2WheelJoint* m_joint; + float m_motorSpeed; + bool m_enableMotor; + bool m_enableLimit; }; static int testIndex = RegisterTest("Joints", "Wheel", WheelJoint::Create); diff --git a/tests/cpp-tests/Classes/Box2DTestBed/tests/wrecking_ball.cpp b/tests/cpp-tests/Classes/Box2DTestBed/tests/wrecking_ball.cpp index c1722a61cbb0..4ea57671db63 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/tests/wrecking_ball.cpp +++ b/tests/cpp-tests/Classes/Box2DTestBed/tests/wrecking_ball.cpp @@ -34,132 +34,128 @@ class WreckingBall : public Test { public: - WreckingBall() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); - - b2EdgeShape shape; - shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } - - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.125f); - - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - fd.friction = 0.2f; - fd.filter.categoryBits = 0x0001; - fd.filter.maskBits = 0xFFFF & ~0x0002; - - b2RevoluteJointDef jd; - jd.collideConnected = false; - - const int32 N = 10; - const float y = 15.0f; - m_distanceJointDef.localAnchorA.Set(0.0f, y); - - b2Body* prevBody = ground; - for (int32 i = 0; i < N; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.5f + 1.0f * i, y); - if (i == N - 1) - { - bd.position.Set(1.0f * i, y); - bd.angularDamping = 0.4f; - } - - b2Body* body = m_world->CreateBody(&bd); - - if (i == N - 1) - { - b2CircleShape circleShape; - circleShape.m_radius = 1.5f; - b2FixtureDef sfd; - sfd.shape = &circleShape; - sfd.density = 100.0f; - sfd.filter.categoryBits = 0x0002; - body->CreateFixture(&sfd); - } - else - { - body->CreateFixture(&fd); - } - - b2Vec2 anchor(float(i), y); - jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); - - prevBody = body; - } - - m_distanceJointDef.localAnchorB.SetZero(); - - float extraLength = 0.01f; - m_distanceJointDef.minLength = 0.0f; - m_distanceJointDef.maxLength = N - 1.0f + extraLength; - m_distanceJointDef.bodyB = prevBody; - } - - { - m_distanceJointDef.bodyA = ground; - m_distanceJoint = m_world->CreateJoint(&m_distanceJointDef); - m_stabilize = true; - } - } - - void UpdateUI() override - { -// ImGui::SetNextWindowPos(ImVec2(Test::g_debugDraw.debugNodeOffset.x, 100.0f)); - ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); - ImGui::Begin("Wrecking Ball Controls", nullptr, ImGuiWindowFlags_NoResize); - - if (ImGui::Checkbox("Stabilize", &m_stabilize)) - { - if (m_stabilize == true && m_distanceJoint == nullptr) - { - m_distanceJoint = m_world->CreateJoint(&m_distanceJointDef); - } - else if (m_stabilize == false && m_distanceJoint != nullptr) - { - m_world->DestroyJoint(m_distanceJoint); - m_distanceJoint = nullptr; - } - } - - ImGui::End(); - } - - void Step(Settings& settings) override - { - Test::Step(settings); - - if (m_distanceJoint) - { - DrawString(5, m_textLine, "Distance Joint ON"); - } - else - { - DrawString(5, m_textLine, "Distance Joint OFF"); - } - - } - - static Test* Create() - { - return new WreckingBall; - } - - b2DistanceJointDef m_distanceJointDef; - b2Joint* m_distanceJoint; - bool m_stabilize; + WreckingBall() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.SetTwoSided(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.125f); + + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + fd.friction = 0.2f; + fd.filter.categoryBits = 0x0001; + fd.filter.maskBits = 0xFFFF & ~0x0002; + + b2RevoluteJointDef jd; + jd.collideConnected = false; + + const int32 N = 10; + const float y = 15.0f; + m_distanceJointDef.localAnchorA.Set(0.0f, y); + + b2Body* prevBody = ground; + for (int32 i = 0; i < N; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.5f + 1.0f * i, y); + if (i == N - 1) + { + bd.position.Set(1.0f * i, y); + bd.angularDamping = 0.4f; + } + + b2Body* body = m_world->CreateBody(&bd); + + if (i == N - 1) + { + b2CircleShape circleShape; + circleShape.m_radius = 1.5f; + b2FixtureDef sfd; + sfd.shape = &circleShape; + sfd.density = 100.0f; + sfd.filter.categoryBits = 0x0002; + body->CreateFixture(&sfd); + } + else + { + body->CreateFixture(&fd); + } + + b2Vec2 anchor(float(i), y); + jd.Initialize(prevBody, body, anchor); + m_world->CreateJoint(&jd); + + prevBody = body; + } + + m_distanceJointDef.localAnchorB.SetZero(); + + float extraLength = 0.01f; + m_distanceJointDef.minLength = 0.0f; + m_distanceJointDef.maxLength = N - 1.0f + extraLength; + m_distanceJointDef.bodyB = prevBody; + } + + { + m_distanceJointDef.bodyA = ground; + m_distanceJoint = m_world->CreateJoint(&m_distanceJointDef); + m_stabilize = true; + } + } + + void UpdateUI() override + { + // ImGui::SetNextWindowPos(ImVec2(Test::g_debugDraw.debugNodeOffset.x, 100.0f)); + ImGui::SetNextWindowSize(ImVec2(200.0f, 100.0f)); + ImGui::Begin("Wrecking Ball Controls", nullptr, ImGuiWindowFlags_NoResize); + + if (ImGui::Checkbox("Stabilize", &m_stabilize)) + { + if (m_stabilize == true && m_distanceJoint == nullptr) + { + m_distanceJoint = m_world->CreateJoint(&m_distanceJointDef); + } + else if (m_stabilize == false && m_distanceJoint != nullptr) + { + m_world->DestroyJoint(m_distanceJoint); + m_distanceJoint = nullptr; + } + } + + ImGui::End(); + } + + void Step(Settings& settings) override + { + Test::Step(settings); + + if (m_distanceJoint) + { + DrawString(5, m_textLine, "Distance Joint ON"); + } + else + { + DrawString(5, m_textLine, "Distance Joint OFF"); + } + } + + static Test* Create() { return new WreckingBall; } + + b2DistanceJointDef m_distanceJointDef; + b2Joint* m_distanceJoint; + bool m_stabilize; }; static int testIndex = RegisterTest("Examples", "Wrecking Ball", WreckingBall::Create); diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-1159.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-1159.cpp index 217b173caa9e..34e10a024421 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-1159.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-1159.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -38,22 +38,21 @@ bool Bug1159Layer::init() auto sprite_a = LayerColor::create(Color4B(255, 0, 0, 255), 700, 700); sprite_a->setAnchorPoint(Vec2(0.5f, 0.5f)); sprite_a->setIgnoreAnchorPointForPosition(false); - sprite_a->setPosition(0.0f, s.height/2); + sprite_a->setPosition(0.0f, s.height / 2); addChild(sprite_a); - sprite_a->runAction(RepeatForever::create(Sequence::create( - MoveTo::create(1.0f, Vec2(1024.0f, 384.0f)), - MoveTo::create(1.0f, Vec2(0.0f, 384.0f)), - nullptr))); + sprite_a->runAction(RepeatForever::create(Sequence::create(MoveTo::create(1.0f, Vec2(1024.0f, 384.0f)), + MoveTo::create(1.0f, Vec2(0.0f, 384.0f)), nullptr))); auto sprite_b = LayerColor::create(Color4B(0, 0, 255, 255), 400, 400); sprite_b->setAnchorPoint(Vec2(0.5f, 0.5f)); sprite_b->setIgnoreAnchorPointForPosition(false); - sprite_b->setPosition(s.width/2, s.height/2); + sprite_b->setPosition(s.width / 2, s.height / 2); addChild(sprite_b); - auto label = MenuItemLabel::create(Label::createWithSystemFont("Flip Me", "Helvetica", 24), CC_CALLBACK_1(Bug1159Layer::callBack, this) ); - auto menu = Menu::create(label, nullptr); + auto label = MenuItemLabel::create(Label::createWithSystemFont("Flip Me", "Helvetica", 24), + CC_CALLBACK_1(Bug1159Layer::callBack, this)); + auto menu = Menu::create(label, nullptr); menu->setPosition(s.width - 200.0f, 50.0f); addChild(menu); diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-1159.h b/tests/cpp-tests/Classes/BugsTest/Bug-1159.h index 1a0e5a6a4998..1db64c6c2dd7 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-1159.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-1159.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -32,11 +32,11 @@ class Bug1159Layer : public BugsTestBase public: virtual bool init() override; virtual void onExit() override; - virtual std::string title() const override { return "Bug1159";} + virtual std::string title() const override { return "Bug1159"; } void callBack(cocos2d::Ref* sender); CREATE_FUNC(Bug1159Layer); }; -#endif // __BUG_1159_H__ +#endif // __BUG_1159_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-1174.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-1174.cpp index 0680e587abe7..7b35bba3aca3 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-1174.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-1174.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -31,23 +31,23 @@ USING_NS_CC; -int check_for_error( Vec2 p1, Vec2 p2, Vec2 p3, Vec2 p4, float s, float t ); +int check_for_error(Vec2 p1, Vec2 p2, Vec2 p3, Vec2 p4, float s, float t); -int check_for_error( Vec2 p1, Vec2 p2, Vec2 p3, Vec2 p4, float s, float t ) +int check_for_error(Vec2 p1, Vec2 p2, Vec2 p3, Vec2 p4, float s, float t) { // the hit point is p3 + t * (p4 - p3); // the hit point also is p1 + s * (p2 - p1); - - auto p4_p3 = p4 - p3; - auto p4_p3_t = p4_p3 * t; + + auto p4_p3 = p4 - p3; + auto p4_p3_t = p4_p3 * t; auto hitPoint1 = p3 + p4_p3_t; - - auto p2_p1 = p2 - p1; - auto p2_p1_s = p2_p1 * s; + + auto p2_p1 = p2 - p1; + auto p2_p1_s = p2_p1 * s; auto hitPoint2 = p1 + p2_p1_s; - + // Since float has rounding errors, only check if diff is < 0.05 - if( (fabs( hitPoint1.x - hitPoint2.x) > 0.1f) || ( fabs(hitPoint1.y - hitPoint2.y) > 0.1f) ) + if ((fabs(hitPoint1.x - hitPoint2.x) > 0.1f) || (fabs(hitPoint1.y - hitPoint2.y) > 0.1f)) { log("ERROR: (%f,%f) != (%f,%f)", hitPoint1.x, hitPoint1.y, hitPoint2.x, hitPoint2.y); return 1; @@ -60,20 +60,20 @@ bool Bug1174Layer::init() { if (BugsTestBase::init()) { -// // seed -// std::srand(0); - - Vec2 A,B,C,D,p1,p2,p3,p4; - float s,t; - - int err=0; - int ok=0; - + // // seed + // std::srand(0); + + Vec2 A, B, C, D, p1, p2, p3, p4; + float s, t; + + int err = 0; + int ok = 0; + // // Test 1. // log("Test1 - Start"); - for( int i=0; i < 10000; i++) + for (int i = 0; i < 10000; i++) { // A | b // ----- @@ -92,19 +92,20 @@ bool Bug1174Layer::init() // c | d float bx = CCRANDOM_0_1() * 5000; float by = CCRANDOM_0_1() * 5000; - + // a | b // ----- // C | d float cx = CCRANDOM_0_1() * -5000; float cy = CCRANDOM_0_1() * -5000; - - A = Vec2(ax,ay); - B = Vec2(bx,by); - C = Vec2(cx,cy); - D = Vec2(dx,dy); - if( Vec2::isLineIntersect( A, D, B, C, &s, &t) ) { - if( check_for_error(A, D, B, C, s, t) ) + + A = Vec2(ax, ay); + B = Vec2(bx, by); + C = Vec2(cx, cy); + D = Vec2(dx, dy); + if (Vec2::isLineIntersect(A, D, B, C, &s, &t)) + { + if (check_for_error(A, D, B, C, s, t)) err++; else ok++; @@ -116,69 +117,68 @@ bool Bug1174Layer::init() // Test 2. // log("Test2 - Start"); - - p1 = Vec2(220,480); - p2 = Vec2(304,325); - p3 = Vec2(264,416); - p4 = Vec2(186,416); - s = 0.0f; - t = 0.0f; - if( Vec2::isLineIntersect(p1, p2, p3, p4, &s, &t) ) - check_for_error(p1, p2, p3, p4, s,t ); + + p1 = Vec2(220, 480); + p2 = Vec2(304, 325); + p3 = Vec2(264, 416); + p4 = Vec2(186, 416); + s = 0.0f; + t = 0.0f; + if (Vec2::isLineIntersect(p1, p2, p3, p4, &s, &t)) + check_for_error(p1, p2, p3, p4, s, t); log("Test2 - End"); - // // Test 3 // log("Test3 - Start"); - - ok=0; - err=0; - for( int i=0;i<10000;i++) + + ok = 0; + err = 0; + for (int i = 0; i < 10000; i++) { // A | b // ----- // c | d float ax = CCRANDOM_0_1() * -500; float ay = CCRANDOM_0_1() * 500; - p1 = Vec2(ax,ay); - + p1 = Vec2(ax, ay); + // a | b // ----- // c | D float dx = CCRANDOM_0_1() * 500; float dy = CCRANDOM_0_1() * -500; - p2 = Vec2(dx,dy); - - + p2 = Vec2(dx, dy); + ////// - - float y = ay - ((ay - dy) /2.0f); + + float y = ay - ((ay - dy) / 2.0f); // a | b // ----- // C | d float cx = CCRANDOM_0_1() * -500; - p3 = Vec2(cx,y); - + p3 = Vec2(cx, y); + // a | B // ----- // c | d float bx = CCRANDOM_0_1() * 500; - p4 = Vec2(bx,y); + p4 = Vec2(bx, y); s = 0.0f; t = 0.0f; - if( Vec2::isLineIntersect(p1, p2, p3, p4, &s, &t) ) { - if( check_for_error(p1, p2, p3, p4, s,t ) ) + if (Vec2::isLineIntersect(p1, p2, p3, p4, &s, &t)) + { + if (check_for_error(p1, p2, p3, p4, s, t)) err++; else ok++; } } - + log("Test3 - End. OK=%i, err=%i", ok, err); return true; } diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-1174.h b/tests/cpp-tests/Classes/BugsTest/Bug-1174.h index 97cdf5291906..d813835e4775 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-1174.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-1174.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -33,7 +33,7 @@ class Bug1174Layer : public BugsTestBase CREATE_FUNC(Bug1174Layer); virtual bool init() override; - virtual std::string title() const override { return "Bug1174";} + virtual std::string title() const override { return "Bug1174"; } }; -#endif // __BUG_1174_H__ +#endif // __BUG_1174_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-12847.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-12847.cpp index 0d6ffb0af42c..f3cae71e5950 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-12847.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-12847.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -45,45 +45,44 @@ Bug12847Layer::~Bug12847Layer() Director::getInstance()->setProjection(_projection); } - bool Bug12847Layer::init() { if (BugsTestBase::init()) { Director::getInstance()->setProjection(Director::Projection::_2D); auto _visibleSize = Director::getInstance()->getVisibleSize(); - - //Create with Sprite + + // Create with Sprite { sprite1 = Sprite::create("Images/bug12847_sprite.png"); sprite1->getTexture()->setAliasTexParameters(); - sprite1->setPosition(Vec2(_visibleSize.width/3, 50.0f)); + sprite1->setPosition(Vec2(_visibleSize.width / 3, 50.0f)); this->addChild(sprite1, 1); - + sprite2 = Sprite::create("Images/bug12847_sprite.png"); sprite2->getTexture()->setAliasTexParameters(); sprite2->setPosition(sprite1->getPosition() + Vec2(0.0f, sprite1->getContentSize().height)); this->addChild(sprite2, 1); } - //Create with SpriteFrame + // Create with SpriteFrame { SpriteFrameCache::getInstance()->addSpriteFramesWithFile("Images/bug12847_spriteframe.plist"); - + sprite3 = Sprite::createWithSpriteFrameName("bug12847_sprite2.png"); sprite3->getTexture()->setAliasTexParameters(); - sprite3->setPosition(Vec2(_visibleSize.width * 2/3, 50.0f)); + sprite3->setPosition(Vec2(_visibleSize.width * 2 / 3, 50.0f)); this->addChild(sprite3, 1); - + sprite4 = Sprite::createWithSpriteFrameName("bug12847_sprite2.png"); sprite4->getTexture()->setAliasTexParameters(); sprite4->setPosition(sprite3->getPosition() + Vec2(0.0f, sprite3->getContentSize().height)); this->addChild(sprite4, 1); } - + this->scheduleUpdate(); return true; } - + return false; } diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-12847.h b/tests/cpp-tests/Classes/BugsTest/Bug-12847.h index c34ed2e072c7..864b26b3394f 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-12847.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-12847.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -31,20 +31,19 @@ class Bug12847Layer : public BugsTestBase { public: CREATE_FUNC(Bug12847Layer); - + Bug12847Layer(); virtual ~Bug12847Layer(); virtual bool init() override; - virtual std::string title() const override { return "Bug1287";} - + virtual std::string title() const override { return "Bug1287"; } + protected: virtual void update(float dt) override; virtual void onEnter() override; virtual void onExit() override; - + private: - cocos2d::Sprite* sprite1; cocos2d::Sprite* sprite2; cocos2d::Sprite* sprite3; diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-14327.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-14327.cpp index a5f56f5751b1..94723fdf4641 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-14327.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-14327.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -41,9 +41,9 @@ bool Bug14327Layer::init() { if (BugsTestBase::init()) { - auto glview = Director::getInstance()->getOpenGLView(); + auto glview = Director::getInstance()->getOpenGLView(); auto visibleOrigin = glview->getVisibleOrigin(); - auto visibleSize = glview->getVisibleSize(); + auto visibleSize = glview->getVisibleSize(); auto pBg = Sprite::create("Images/HelloWorld.png"); pBg->setPosition(Vec2(visibleOrigin.x + visibleSize.width / 2, visibleOrigin.y + visibleSize.height / 2)); @@ -52,10 +52,10 @@ bool Bug14327Layer::init() _removeTime = time(nullptr) + 20; _TTFShowTime = Label::createWithSystemFont("Edit control will be removed after 00:20!", "Arial", 20); - _TTFShowTime->setPosition(Vec2(visibleOrigin.x + visibleSize.width / 2, visibleOrigin.y + visibleSize.height - 60)); + _TTFShowTime->setPosition( + Vec2(visibleOrigin.x + visibleSize.width / 2, visibleOrigin.y + visibleSize.height - 60)); this->addChild(_TTFShowTime); - auto editBoxSize = Size(visibleSize.width - 100, visibleSize.height * 0.1); std::string pNormalSprite = "extensions/green_edit.png"; @@ -97,14 +97,15 @@ void Bug14327Layer::editBoxEditingDidBegin(cocos2d::ui::EditBox* editBox) log("editBox %p DidBegin !", editBox); } -void Bug14327Layer::editBoxEditingDidEndWithAction(cocos2d::ui::EditBox* editBox, cocos2d::ui::EditBoxDelegate::EditBoxEndAction EditBoxEndAction) +void Bug14327Layer::editBoxEditingDidEndWithAction(cocos2d::ui::EditBox* editBox, + cocos2d::ui::EditBoxDelegate::EditBoxEndAction EditBoxEndAction) { log("editBox %p DidEnd !", editBox); } -void Bug14327Layer::editBoxTextChanged(cocos2d::ui::EditBox* editBox, const std::string& text) +void Bug14327Layer::editBoxTextChanged(cocos2d::ui::EditBox* editBox, std::string_view text) { - log("editBox %p TextChanged, text: %s ", editBox, text.c_str()); + log("editBox %p TextChanged, text: %s ", editBox, text.data()); } void Bug14327Layer::editBoxReturn(ui::EditBox* editBox) diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-14327.h b/tests/cpp-tests/Classes/BugsTest/Bug-14327.h index db1b6e3bfa77..96e1cf157a0a 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-14327.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-14327.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,10 +27,9 @@ #include "BugsTest.h" - #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) -#include "ui/UIEditBox/UIEditBox.h" +# include "ui/UIEditBox/UIEditBox.h" class Bug14327Layer : public BugsTestBase, public cocos2d::ui::EditBoxDelegate { @@ -38,11 +37,13 @@ class Bug14327Layer : public BugsTestBase, public cocos2d::ui::EditBoxDelegate CREATE_FUNC(Bug14327Layer); virtual bool init() override; - virtual std::string title() const override { return "Bug14327";} + virtual std::string title() const override { return "Bug14327"; } virtual void editBoxEditingDidBegin(cocos2d::ui::EditBox* editBox) override; - virtual void editBoxEditingDidEndWithAction(cocos2d::ui::EditBox* editBox, cocos2d::ui::EditBoxDelegate::EditBoxEndAction EditBoxEndAction) override; - virtual void editBoxTextChanged(cocos2d::ui::EditBox* editBox, const std::string& text) override; + virtual void editBoxEditingDidEndWithAction( + cocos2d::ui::EditBox* editBox, + cocos2d::ui::EditBoxDelegate::EditBoxEndAction EditBoxEndAction) override; + virtual void editBoxTextChanged(cocos2d::ui::EditBox* editBox, std::string_view text) override; virtual void editBoxReturn(cocos2d::ui::EditBox* editBox) override; protected: @@ -50,7 +51,7 @@ class Bug14327Layer : public BugsTestBase, public cocos2d::ui::EditBoxDelegate private: time_t _removeTime; - cocos2d::Label *_TTFShowTime; + cocos2d::Label* _TTFShowTime; cocos2d::ui::EditBox* _edit; }; diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-15594.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-15594.cpp index c53821668ab0..95c3a4011a4d 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-15594.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-15594.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,24 +34,23 @@ #include "Bug-15594.h" - USING_NS_CC; bool Bug15594Layer::init() { - if (BugsTestBase::init()) - { + if (BugsTestBase::init()) + { auto sprite3d = Sprite3D::create("Images/bugs/bug15594.c3t", "Images/bugs/bug15594.jpg"); addChild(sprite3d); auto size = Director::getInstance()->getWinSize(); - sprite3d->setPosition(size/2); + sprite3d->setPosition(size / 2); auto animation = Animation3D::create("Images/bugs/bug15594.c3t"); - auto animate = Animate3D::create(animation); - auto repeat = RepeatForever::create(animate); + auto animate = Animate3D::create(animation); + auto repeat = RepeatForever::create(animate); sprite3d->runAction(repeat); - return true; - } + return true; + } return false; } diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-15594.h b/tests/cpp-tests/Classes/BugsTest/Bug-15594.h index abd4abde46b6..d55aa26c559d 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-15594.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-15594.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,7 +34,7 @@ class Bug15594Layer : public BugsTestBase CREATE_FUNC(Bug15594Layer); virtual bool init() override; - virtual std::string title() const override { return "Bug15594";} + virtual std::string title() const override { return "Bug15594"; } }; #endif /* defined(__cocos2d_tests__Bug_15594__) */ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-15776.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-15776.cpp index 1ea56ddd9e6d..5a3d08c069e3 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-15776.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-15776.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -32,10 +32,8 @@ #include "Bug-15776.h" - USING_NS_CC; - // // IMPORTANT: // THIS TEST WILL CRASH ON TextureCache::addImage() @@ -46,7 +44,7 @@ bool Bug15776Layer::init() { if (BugsTestBase::init()) { - cocos2d::Image *cocos2dxImage = new cocos2d::Image(); + cocos2d::Image* cocos2dxImage = new cocos2d::Image(); cocos2dxImage->initWithImageData(nullptr, 0, false); // should not crash. invalid cocos2dImage auto texture2d = Director::getInstance()->getTextureCache()->addImage(cocos2dxImage, "unused"); diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-15776.h b/tests/cpp-tests/Classes/BugsTest/Bug-15776.h index 97d21f907cb7..3485f8bcf524 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-15776.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-15776.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -46,5 +46,4 @@ class Bug15776Layer : public BugsTestBase virtual std::string subtitle() const override; }; - #endif /* Bug_15776_hpp */ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-350.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-350.cpp index 73e500f95877..f1e4ac21c20c 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-350.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-350.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -23,7 +23,7 @@ ****************************************************************************/ // -// Bug-350 +// Bug-350 // http://code.google.com/p/cocos2d-iphone/issues/detail?id=350 // @@ -35,9 +35,9 @@ bool Bug350Layer::init() { if (BugsTestBase::init()) { - auto size = Director::getInstance()->getWinSize(); + auto size = Director::getInstance()->getWinSize(); auto background = Sprite::create("Hello.png"); - background->setPosition(size.width/2, size.height/2); + background->setPosition(size.width / 2, size.height / 2); addChild(background); return true; } diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-350.h b/tests/cpp-tests/Classes/BugsTest/Bug-350.h index 4e8982f70e34..8f1d5d44a2da 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-350.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-350.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -33,7 +33,7 @@ class Bug350Layer : public BugsTestBase CREATE_FUNC(Bug350Layer); virtual bool init() override; - virtual std::string title() const override { return "Bug350";} + virtual std::string title() const override { return "Bug350"; } }; -#endif // __BUG_350_H__ +#endif // __BUG_350_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-422.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-422.cpp index 28b1d56776cb..542ba9a8f433 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-422.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-422.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -52,21 +52,21 @@ void Bug422Layer::reset() // The menu will be removed, but the instance will be alive // and then a new node will be allocated occupying the memory. // => CRASH BOOM BANG - auto node = getChildByTag(localtag-1); + auto node = getChildByTag(localtag - 1); log("Menu: %p", node); removeChild(node, true); -// [self removeChildByTag:localtag-1 cleanup:NO]; + // [self removeChildByTag:localtag-1 cleanup:NO]; - auto item1 = MenuItemFont::create("One", CC_CALLBACK_1(Bug422Layer::menuCallback, this) ); + auto item1 = MenuItemFont::create("One", CC_CALLBACK_1(Bug422Layer::menuCallback, this)); log("MenuItemFont: %p", item1); - MenuItem *item2 = MenuItemFont::create("Two", CC_CALLBACK_1(Bug422Layer::menuCallback, this) ); - auto menu = Menu::create(item1, item2, nullptr); + MenuItem* item2 = MenuItemFont::create("Two", CC_CALLBACK_1(Bug422Layer::menuCallback, this)); + auto menu = Menu::create(item1, item2, nullptr); menu->alignItemsVertically(); float x = CCRANDOM_0_1() * 50; float y = CCRANDOM_0_1() * 50; - menu->setPosition(menu->getPosition() + Vec2(x,y)); - addChild(menu, 0, localtag); + menu->setPosition(menu->getPosition() + Vec2(x, y)); + addChild(menu, 0, localtag); //[self check:self]; } @@ -74,7 +74,8 @@ void Bug422Layer::reset() void Bug422Layer::check(Node* t) { auto& children = t->getChildren(); - for(const auto &child : children) { + for (const auto& child : children) + { log("%p, rc: %d", child, child->getReferenceCount()); check(child); } diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-422.h b/tests/cpp-tests/Classes/BugsTest/Bug-422.h index 21c39580ad2f..dd229fffbf52 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-422.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-422.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -33,11 +33,11 @@ class Bug422Layer : public BugsTestBase CREATE_FUNC(Bug422Layer); virtual bool init() override; - virtual std::string title() const override { return "Bug422";} + virtual std::string title() const override { return "Bug422"; } void reset(); void check(Node* target); void menuCallback(cocos2d::Ref* sender); }; -#endif // __BUG_422_H__ +#endif // __BUG_422_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-458/Bug-458.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-458/Bug-458.cpp index 4b5db044aecc..eae96810a9d8 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-458/Bug-458.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-458/Bug-458.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,27 +34,27 @@ USING_NS_CC; bool Bug458Layer::init() { - if(BugsTestBase::init()) + if (BugsTestBase::init()) { // ask director the the window size auto size = Director::getInstance()->getWinSize(); - auto question = new QuestionContainerSprite(); + auto question = new QuestionContainerSprite(); auto question2 = new QuestionContainerSprite(); question->init(); question2->init(); -// [question setContentSize:CGSizeMake(50,50)]; -// [question2 setContentSize:CGSizeMake(50,50)]; - - auto sprite = MenuItemSprite::create(question2, question, CC_CALLBACK_1(Bug458Layer::selectAnswer, this) ); - auto layer = LayerColor::create(Color4B(0,0,255,255), 100, 100); + // [question setContentSize:CGSizeMake(50,50)]; + // [question2 setContentSize:CGSizeMake(50,50)]; + + auto sprite = MenuItemSprite::create(question2, question, CC_CALLBACK_1(Bug458Layer::selectAnswer, this)); + auto layer = LayerColor::create(Color4B(0, 0, 255, 255), 100, 100); question->release(); question2->release(); - auto layer2 = LayerColor::create(Color4B(255,0,0,255), 100, 100); - auto sprite2 = MenuItemSprite::create(layer, layer2, CC_CALLBACK_1(Bug458Layer::selectAnswer, this) ); - auto menu = Menu::create(sprite, sprite2, nullptr); + auto layer2 = LayerColor::create(Color4B(255, 0, 0, 255), 100, 100); + auto sprite2 = MenuItemSprite::create(layer, layer2, CC_CALLBACK_1(Bug458Layer::selectAnswer, this)); + auto menu = Menu::create(sprite, sprite2, nullptr); menu->alignItemsVerticallyWithPadding(100); menu->setPosition(size.width / 2, size.height / 2); diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-458/Bug-458.h b/tests/cpp-tests/Classes/BugsTest/Bug-458/Bug-458.h index 59a2509840e9..dc033564ec8a 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-458/Bug-458.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-458/Bug-458.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -36,4 +36,4 @@ class Bug458Layer : public BugsTestBase void selectAnswer(cocos2d::Ref* sender); }; -#endif // __BUG_458_H__ +#endif // __BUG_458_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp index b5f94bea11c2..e65c5ee32bd2 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -32,24 +32,24 @@ bool QuestionContainerSprite::init() { if (Sprite::init()) { - //Add label + // Add label auto label = Label::createWithTTF("Answer 1", "fonts/arial.ttf", 12); label->setTag(100); - //Add the background - auto size = Director::getInstance()->getWinSize(); + // Add the background + auto size = Director::getInstance()->getWinSize(); auto corner = Sprite::create("Images/bugs/corner.png"); - int width = size.width * 0.9f - (corner->getContentSize().width * 2); - int height = size.height * 0.15f - (corner->getContentSize().height * 2); + int width = size.width * 0.9f - (corner->getContentSize().width * 2); + int height = size.height * 0.15f - (corner->getContentSize().height * 2); auto layer = LayerColor::create(Color4B(255, 255, 255, 255 * .75), width, height); layer->setPosition(Vec2(-width / 2, -height / 2)); - //First button is blue, - //Second is red - //Used for testing - change later + // First button is blue, + // Second is red + // Used for testing - change later static int a = 0; - + if (a == 0) label->setColor(Color3B::BLUE); else @@ -60,7 +60,8 @@ bool QuestionContainerSprite::init() a++; addChild(layer); - corner->setPosition(Vec2(-(width / 2 + corner->getContentSize().width / 2), -(height / 2 + corner->getContentSize().height / 2))); + corner->setPosition(Vec2(-(width / 2 + corner->getContentSize().width / 2), + -(height / 2 + corner->getContentSize().height / 2))); addChild(corner); auto corner2 = Sprite::create("Images/bugs/corner.png"); @@ -81,25 +82,29 @@ bool QuestionContainerSprite::init() auto edge = Sprite::create("Images/bugs/edge.png"); edge->setScaleX(width); - edge->setPosition(Vec2(corner->getPosition().x + (corner->getContentSize().width / 2) + (width / 2), corner->getPosition().y)); + edge->setPosition(Vec2(corner->getPosition().x + (corner->getContentSize().width / 2) + (width / 2), + corner->getPosition().y)); addChild(edge); - + auto edge2 = Sprite::create("Images/bugs/edge.png"); edge2->setScaleX(width); - edge2->setPosition(Vec2(corner->getPosition().x + (corner->getContentSize().width / 2) + (width / 2), -corner->getPosition().y)); + edge2->setPosition(Vec2(corner->getPosition().x + (corner->getContentSize().width / 2) + (width / 2), + -corner->getPosition().y)); edge2->setFlippedY(true); addChild(edge2); auto edge3 = Sprite::create("Images/bugs/edge.png"); edge3->setRotation(90); edge3->setScaleX(height); - edge3->setPosition(Vec2(corner->getPosition().x, corner->getPosition().y + (corner->getContentSize().height / 2) + (height / 2))); + edge3->setPosition(Vec2(corner->getPosition().x, + corner->getPosition().y + (corner->getContentSize().height / 2) + (height / 2))); addChild(edge3); auto edge4 = Sprite::create("Images/bugs/edge.png"); edge4->setRotation(270); edge4->setScaleX(height); - edge4->setPosition(Vec2(-corner->getPosition().x, corner->getPosition().y + (corner->getContentSize().height / 2) + (height / 2))); + edge4->setPosition(Vec2(-corner->getPosition().x, + corner->getPosition().y + (corner->getContentSize().height / 2) + (height / 2))); addChild(edge4); addChild(label); diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-458/QuestionContainerSprite.h b/tests/cpp-tests/Classes/BugsTest/Bug-458/QuestionContainerSprite.h index 6e31c7744818..efc407f95a61 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-458/QuestionContainerSprite.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-458/QuestionContainerSprite.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,10 +27,10 @@ #include "cocos2d.h" -class QuestionContainerSprite : public cocos2d::Sprite +class QuestionContainerSprite : public cocos2d::Sprite { public: virtual bool init() override; }; -#endif // __QUESTION_CONTAINER_SPRITE_H__ +#endif // __QUESTION_CONTAINER_SPRITE_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-624.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-624.cpp index 038423e61316..62967df87240 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-624.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-624.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -43,23 +43,23 @@ Bug624Layer::~Bug624Layer() bool Bug624Layer::init() { - if(BugsTestBase::init()) + if (BugsTestBase::init()) { - auto size = Director::getInstance()->getWinSize(); + auto size = Director::getInstance()->getWinSize(); auto label = Label::createWithTTF("Layer1", "fonts/Marker Felt.ttf", 36.0f); - label->setPosition(size.width/2, size.height/2); + label->setPosition(size.width / 2, size.height / 2); addChild(label); - + Device::setAccelerometerEnabled(true); - auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer::onAcceleration, this)); + auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); schedule(CC_SCHEDULE_SELECTOR(Bug624Layer::switchLayer), 5.0f); return true; } - + return false; } @@ -67,13 +67,13 @@ void Bug624Layer::switchLayer(float dt) { unschedule(CC_SCHEDULE_SELECTOR(Bug624Layer::switchLayer)); - auto scene = Scene::create(); + auto scene = Scene::create(); scene->addChild(Bug624Layer2::create(), 0); Director::getInstance()->replaceScene(TransitionFade::create(2.0f, scene, Color3B::WHITE)); } void Bug624Layer::onAcceleration(Acceleration* acc, Event* event) -{ +{ log("Layer1 accel"); } @@ -89,19 +89,18 @@ Bug624Layer2::~Bug624Layer2() bool Bug624Layer2::init() { - if(BugsTestBase::init()) + if (BugsTestBase::init()) { - auto size = Director::getInstance()->getWinSize(); + auto size = Director::getInstance()->getWinSize(); auto label = Label::createWithTTF("Layer2", "fonts/Marker Felt.ttf", 36.0f); - label->setPosition(size.width/2, size.height/2); + label->setPosition(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); - - + schedule(CC_SCHEDULE_SELECTOR(Bug624Layer2::switchLayer), 5.0f); return true; @@ -114,12 +113,12 @@ void Bug624Layer2::switchLayer(float dt) { unschedule(CC_SCHEDULE_SELECTOR(Bug624Layer::switchLayer)); - auto scene = Scene::create(); + auto scene = Scene::create(); scene->addChild(Bug624Layer::create(), 0); Director::getInstance()->replaceScene(TransitionFade::create(2.0f, scene, Color3B::RED)); } void Bug624Layer2::onAcceleration(Acceleration* acc, Event* event) -{ +{ log("Layer2 accel"); } diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-624.h b/tests/cpp-tests/Classes/BugsTest/Bug-624.h index 37aa5a2b5066..f71b73e8a4c3 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-624.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-624.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,7 +34,7 @@ class Bug624Layer : public BugsTestBase virtual bool init() override; void switchLayer(float dt); virtual void onAcceleration(cocos2d::Acceleration* acc, cocos2d::Event* event); - virtual std::string title() const override { return "Bug624";} + virtual std::string title() const override { return "Bug624"; } CREATE_FUNC(Bug624Layer); }; @@ -46,9 +46,9 @@ class Bug624Layer2 : public BugsTestBase virtual bool init() override; void switchLayer(float dt); virtual void onAcceleration(cocos2d::Acceleration* acc, cocos2d::Event* event); - virtual std::string title() const override { return "Bug624-2";} + virtual std::string title() const override { return "Bug624-2"; } CREATE_FUNC(Bug624Layer2); }; -#endif // __BUG_624_H__ +#endif // __BUG_624_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-886.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-886.cpp index c7c1209a873d..9dd133ee0bad 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-886.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-886.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -33,11 +33,11 @@ USING_NS_CC; bool Bug886Layer::init() { - if(BugsTestBase::init()) + if (BugsTestBase::init()) { // ask director the the window size // auto size = [[Director sharedDirector] winSize]; - + auto sprite = Sprite::create("Images/bugs/bug886.jpg"); sprite->setAnchorPoint(Vec2::ZERO); sprite->setPosition(Vec2::ZERO); diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-886.h b/tests/cpp-tests/Classes/BugsTest/Bug-886.h index a3f189373565..aac1e9850cf4 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-886.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-886.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -33,7 +33,7 @@ class Bug886Layer : public BugsTestBase CREATE_FUNC(Bug886Layer); virtual bool init() override; - virtual std::string title() const override { return "Bug886";} + virtual std::string title() const override { return "Bug886"; } }; -#endif // __BUG_886_H__ +#endif // __BUG_886_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-899.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-899.cpp index cddfdb0b0d66..f759c4076884 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-899.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-899.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -35,7 +35,7 @@ USING_NS_CC; bool Bug899Layer::init() { -// Director::getInstance()->enableRetinaDisplay(true); + // Director::getInstance()->enableRetinaDisplay(true); if (BugsTestBase::init()) { auto bg = Sprite::create("Images/bugs/RetinaDisplay.jpg"); diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-899.h b/tests/cpp-tests/Classes/BugsTest/Bug-899.h index e61494ffdb2b..37b7bf8d5318 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-899.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-899.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -33,7 +33,7 @@ class Bug899Layer : public BugsTestBase CREATE_FUNC(Bug899Layer); virtual bool init() override; - virtual std::string title() const override { return "Bug899";} + virtual std::string title() const override { return "Bug899"; } }; -#endif // __BUG_899_H__ +#endif // __BUG_899_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-914.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-914.cpp index f80774c7d1a9..bd1d4b61ed6c 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-914.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-914.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -23,7 +23,7 @@ ****************************************************************************/ // Import the interfaces -#include"Bug-914.h" +#include "Bug-914.h" USING_NS_CC; @@ -34,22 +34,22 @@ bool Bug914Layer::init() // Apple recommends to re-assign "self" with the "super" return value if (BugsTestBase::init()) { - auto listener = EventListenerTouchAllAtOnce::create(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(Bug914Layer::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(Bug914Layer::onTouchesMoved, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - + // ask director the the window size auto size = Director::getInstance()->getWinSize(); - LayerColor *layer; - for( int i=0;i < 5;i++) + LayerColor* layer; + for (int i = 0; i < 5; i++) { - layer = LayerColor::create(Color4B(i*20, i*20, i*20,255)); - layer->setContentSize(Size(i*100.0f, i*100.0f)); - layer->setPosition(size.width/2, size.height/2); + layer = LayerColor::create(Color4B(i * 20, i * 20, i * 20, 255)); + layer->setContentSize(Size(i * 100.0f, i * 100.0f)); + layer->setPosition(size.width / 2, size.height / 2); layer->setAnchorPoint(Vec2(0.5f, 0.5f)); layer->setIgnoreAnchorPointForPosition(false); - addChild(layer, -1-i); + addChild(layer, -1 - i); } // create and initialize a Label @@ -58,11 +58,11 @@ bool Bug914Layer::init() auto menu = Menu::create(item1, nullptr); menu->alignItemsVertically(); - menu->setPosition(size.width/2, 100); + menu->setPosition(size.width / 2, 100); addChild(menu); // position the label on the center of the screen - label->setPosition(size.width /2 , size.height/2); + label->setPosition(size.width / 2, size.height / 2); // add the label as a child to this Layer addChild(label); @@ -71,12 +71,12 @@ bool Bug914Layer::init() return false; } -void Bug914Layer::onTouchesMoved(const std::vector& touches, Event * event) +void Bug914Layer::onTouchesMoved(const std::vector& touches, Event* event) { log("Number of touches: %d", (int)touches.size()); } -void Bug914Layer::onTouchesBegan(const std::vector& touches, Event * event) +void Bug914Layer::onTouchesBegan(const std::vector& touches, Event* event) { onTouchesMoved(touches, event); } diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-914.h b/tests/cpp-tests/Classes/BugsTest/Bug-914.h index c78952933f07..cd9d08f5aa1e 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-914.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-914.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -31,7 +31,7 @@ class Bug914Layer : public BugsTestBase { public: virtual bool init() override; - virtual std::string title() const override { return "Bug914";} + virtual std::string title() const override { return "Bug914"; } void onTouchesMoved(const std::vector& touches, cocos2d::Event* event); void onTouchesBegan(const std::vector& touches, cocos2d::Event* event); @@ -40,4 +40,4 @@ class Bug914Layer : public BugsTestBase CREATE_FUNC(Bug914Layer); }; -#endif // __BUG_914_H__ +#endif // __BUG_914_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.cpp index 3ed147bb4bb3..a1f2b51289f9 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -38,7 +38,7 @@ bool BugDrawNodeLayer::init() { if (BugsTestBase::init()) { - auto size = Director::getInstance()->getWinSize(); + auto size = Director::getInstance()->getWinSize(); auto testSprite = Sprite::create("Images/close.png"); BlendFunc blend; blend.src = backend::BlendFactor::ZERO; diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.h b/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.h index e48afef9b77e..47b947213890 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -33,7 +33,7 @@ class BugDrawNodeLayer : public BugsTestBase CREATE_FUNC(BugDrawNodeLayer); virtual bool init() override; - virtual std::string title() const override { return "BugDrawNode";} + virtual std::string title() const override { return "BugDrawNode"; } }; #endif \ No newline at end of file diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-Child.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-Child.cpp index abab81548f41..b53d10ff9447 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-Child.cpp +++ b/tests/cpp-tests/Classes/BugsTest/Bug-Child.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -39,37 +39,37 @@ bool BugChild::init() if (BugsTestBase::init()) { auto size = Director::getInstance()->getWinSize(); - + // create and initialize a Label auto item1 = MenuItemFont::create("Switch Child", CC_CALLBACK_1(BugChild::switchChild, this)); - + menu = Menu::create(item1, nullptr); - + menu->alignItemsVertically(); - menu->setPosition(size.width/2, 100); + menu->setPosition(size.width / 2, 100); addChild(menu); - + parent1 = Sprite::create("Images/grossini.png"); - parent1->setPosition(size.width/4, size.height/2); + parent1->setPosition(size.width / 4, size.height / 2); addChild(parent1); - + parent2 = Sprite::create("Images/grossinis_sister1.png"); - parent2->setPosition(size.width*3/4, size.height/2); + parent2->setPosition(size.width * 3 / 4, size.height / 2); addChild(parent2); - + child = Sprite::create("Images/grossinis_sister2.png"); child->setPosition(20, 20); child->retain(); parent1->addChild(child); return true; } - + return false; } -void BugChild::switchChild(Ref *sender) +void BugChild::switchChild(Ref* sender) { - if(parent1->getChildrenCount() > 0) + if (parent1->getChildrenCount() > 0) { parent1->removeChild(child, false); parent2->addChild(child); @@ -85,49 +85,49 @@ void BugChild::switchChild(Ref *sender) bool BugCameraMask::init() { - if (!BugsTestBase::init()) return false; - + if (!BugsTestBase::init()) + return false; + auto size = Director::getInstance()->getWinSize(); - + auto node = Node::create(); - node->setPosition(size.width/4, size.height/3); + node->setPosition(size.width / 4, size.height / 3); _sprite = Sprite::create("Images/grossini.png"); node->addChild(_sprite); node->setCameraMask((unsigned short)CameraFlag::USER1); - auto move = MoveBy::create(2, Vec2(200,0)); - + auto move = MoveBy::create(2, Vec2(200, 0)); + node->runAction(RepeatForever::create(Sequence::createWithTwoActions(move, move->reverse()))); addChild(node); - + auto camera = Camera::create(); camera->setCameraFlag(CameraFlag::USER1); addChild(camera); - - + auto item1 = MenuItemFont::create("Switch Child", CC_CALLBACK_1(BugCameraMask::switchSpriteFlag, this)); - + auto menu = Menu::create(item1, nullptr); - + menu->alignItemsVertically(); - menu->setPosition(size.width/2, 100); + menu->setPosition(size.width / 2, 100); addChild(menu); - + _spriteMaskLabel = Label::create(); - _spriteMaskLabel->setPosition(size.width/2, 120); + _spriteMaskLabel->setPosition(size.width / 2, 120); addChild(_spriteMaskLabel); updateSpriteMaskLabel(); - + auto label = Label::create(); - label->setPosition(size.width/2, size.height * 0.9f); + label->setPosition(size.width / 2, size.height * 0.9f); label->setString("Sprite should always run action."); addChild(label); - + return true; } -void BugCameraMask::switchSpriteFlag(Ref *sender) +void BugCameraMask::switchSpriteFlag(Ref* sender) { - if((unsigned short) CameraFlag::USER1 == _sprite->getCameraMask()) + if ((unsigned short)CameraFlag::USER1 == _sprite->getCameraMask()) { _sprite->setCameraMask((unsigned short)CameraFlag::DEFAULT); } @@ -135,13 +135,14 @@ void BugCameraMask::switchSpriteFlag(Ref *sender) { _sprite->setCameraMask((unsigned short)CameraFlag::USER1); } - + updateSpriteMaskLabel(); } void BugCameraMask::updateSpriteMaskLabel() { std::stringstream stream; - stream << "The camera Mask is " << (_sprite->getCameraMask() == 1 ? "CameraFlag::Default" : "CameraFlag::User1") << std::endl; + stream << "The camera Mask is " << (_sprite->getCameraMask() == 1 ? "CameraFlag::Default" : "CameraFlag::User1") + << std::endl; _spriteMaskLabel->setString(stream.str()); } diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-Child.h b/tests/cpp-tests/Classes/BugsTest/Bug-Child.h index fb603362f6af..df83634926f9 100644 --- a/tests/cpp-tests/Classes/BugsTest/Bug-Child.h +++ b/tests/cpp-tests/Classes/BugsTest/Bug-Child.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -41,17 +41,16 @@ class BugChild : public BugsTestBase CREATE_FUNC(BugChild); virtual bool init() override; - virtual std::string title() const override { return "BugChild";} - + virtual std::string title() const override { return "BugChild"; } + void switchChild(cocos2d::Ref* sender); - + protected: - cocos2d::Sprite* parent1; cocos2d::Sprite* parent2; - + cocos2d::Sprite* child; - + cocos2d::Menu* menu; }; @@ -59,10 +58,10 @@ class BugCameraMask : public BugsTestBase { public: CREATE_FUNC(BugCameraMask); - + virtual bool init() override; - virtual std::string title() const override { return "BugCameraMask";} - + virtual std::string title() const override { return "BugCameraMask"; } + void switchSpriteFlag(cocos2d::Ref* sender); void updateSpriteMaskLabel(); Node* _sprite; diff --git a/tests/cpp-tests/Classes/BugsTest/BugsTest.cpp b/tests/cpp-tests/Classes/BugsTest/BugsTest.cpp index a35705ebae74..074dd6f2195a 100644 --- a/tests/cpp-tests/Classes/BugsTest/BugsTest.cpp +++ b/tests/cpp-tests/Classes/BugsTest/BugsTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -39,7 +39,7 @@ #include "Bug-15776.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) -#include "Bug-14327.h" +# include "Bug-14327.h" #endif BugsTests::BugsTests() @@ -58,9 +58,9 @@ BugsTests::BugsTests() ADD_TEST_CASE(BugDrawNodeLayer); ADD_TEST_CASE(Bug12847Layer); ADD_TEST_CASE(Bug15594Layer); - + // NOTE: comment this out because it currently crashes during autotest - //ADD_TEST_CASE(Bug15776Layer); + // ADD_TEST_CASE(Bug15776Layer); #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) ADD_TEST_CASE(Bug14327Layer); diff --git a/tests/cpp-tests/Classes/BugsTest/BugsTest.h b/tests/cpp-tests/Classes/BugsTest/BugsTest.h index d06a1cc9c7d4..dacd08fc05e1 100644 --- a/tests/cpp-tests/Classes/BugsTest/BugsTest.h +++ b/tests/cpp-tests/Classes/BugsTest/BugsTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -30,7 +30,7 @@ class BugsTestBase : public TestCase { public: - virtual std::string title() const override {return "No Test Title set";} + virtual std::string title() const override { return "No Test Title set"; } }; DEFINE_TEST_SUITE(BugsTests); diff --git a/tests/cpp-tests/Classes/Camera3DTest/Camera3DTest.cpp b/tests/cpp-tests/Classes/Camera3DTest/Camera3DTest.cpp index a833ad3fb803..158543505ed7 100644 --- a/tests/cpp-tests/Classes/Camera3DTest/Camera3DTest.cpp +++ b/tests/cpp-tests/Classes/Camera3DTest/Camera3DTest.cpp @@ -27,17 +27,19 @@ THE SOFTWARE. #include "Camera3DTest.h" #include "testResource.h" #include "ui/UISlider.h" -#include "platform/CCFileUtils.h" +#include "platform/CCFileUtils.h" #include "renderer/backend/Device.h" USING_NS_CC; -#define SET_UNIFORM(name, addr, size) do { \ - auto _loc_ = _programState1->getUniformLocation(name); \ - _programState1->setUniform(_loc_, (addr), (size)); \ - _loc_ = _programState2->getUniformLocation(name); \ - _programState2->setUniform(_loc_, (addr), (size)); \ - } while(false) +#define SET_UNIFORM(name, addr, size) \ + do \ + { \ + auto _loc_ = _programState1->getUniformLocation(name); \ + _programState1->setUniform(_loc_, (addr), (size)); \ + _loc_ = _programState2->getUniformLocation(name); \ + _programState2->setUniform(_loc_, (addr), (size)); \ + } while (false) enum { @@ -53,7 +55,7 @@ Camera3DTests::Camera3DTests() ADD_TEST_CASE(CameraCullingDemo); ADD_TEST_CASE(FogTestDemo); ADD_TEST_CASE(CameraArcBallDemo); - //ADD_TEST_CASE(CameraFrameBufferTest); //TODO render target + // ADD_TEST_CASE(CameraFrameBufferTest); //TODO render target ADD_TEST_CASE(BackgroundColorBrushTest); } @@ -66,9 +68,9 @@ CameraRotationTest::CameraRotationTest() { auto s = Director::getInstance()->getWinSize(); - + _camControlNode = Node::create(); - _camControlNode->setPositionNormalized(Vec2(0.5f,0.5f)); + _camControlNode->setPositionNormalized(Vec2(0.5f, 0.5f)); addChild(_camControlNode); _camNode = Node::create(); @@ -76,61 +78,59 @@ CameraRotationTest::CameraRotationTest() _camControlNode->addChild(_camNode); auto sp3d = Sprite3D::create(); - sp3d->setPosition(s.width/2, s.height/2); + sp3d->setPosition(s.width / 2, s.height / 2); addChild(sp3d); - + auto lship = Label::create(); lship->setString("Ship"); lship->setPosition(0, 20); sp3d->addChild(lship); - - //Billboards - //Yellow is at the back + + // Billboards + // Yellow is at the back bill1 = BillBoard::create("Images/Icon.png"); bill1->setPosition3D(Vec3(50.0f, 10.0f, -10.0f)); bill1->setColor(Color3B::YELLOW); bill1->setScale(0.6f); sp3d->addChild(bill1); - + l1 = Label::create(); - l1->setPosition(Vec2(0.0f,-10.0f)); + l1->setPosition(Vec2(0.0f, -10.0f)); l1->setString("Billboard1"); l1->setColor(Color3B::WHITE); l1->setScale(3); bill1->addChild(l1); auto p1 = ParticleSystemQuad::create("Particles/SmallSun.plist"); - p1->setPosition(30.0f,80.0f); + p1->setPosition(30.0f, 80.0f); bill1->addChild(p1); - + bill2 = BillBoard::create("Images/Icon.png"); bill2->setPosition3D(Vec3(-50.0f, -10.0f, 10.0f)); bill2->setScale(0.6f); sp3d->addChild(bill2); - + l2 = Label::create(); l2->setString("Billboard2"); - l2->setPosition(Vec2(0.0f,-10.0f)); + l2->setPosition(Vec2(0.0f, -10.0f)); l2->setColor(Color3B::WHITE); l2->setScale(3); bill2->addChild(l2); - + auto p2 = ParticleSystemQuad::create("Particles/SmallSun.plist"); - p2->setPosition(30,80); + p2->setPosition(30, 80); bill2->addChild(p2); - //3D models + // 3D models auto model = Sprite3D::create("Sprite3DTest/boss1.obj"); model->setScale(4); model->setTexture("Sprite3DTest/boss.png"); - model->setPosition3D(Vec3(s.width/2, s.height/2, 0)); + model->setPosition3D(Vec3(s.width / 2, s.height / 2, 0)); addChild(model); - //Listener - _lis = EventListenerTouchOneByOne::create(); - _lis->onTouchBegan = [](Touch* t, Event* e) { - return true; - }; + // Listener + _lis = EventListenerTouchOneByOne::create(); + _lis->onTouchBegan = [](Touch* t, Event* e) { return true; }; _lis->onTouchMoved = [this](Touch* t, Event* e) { float dx = t->getDelta().x; @@ -146,7 +146,7 @@ CameraRotationTest::CameraRotationTest() }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(_lis, this); - + schedule(CC_SCHEDULE_SELECTOR(CameraRotationTest::update)); } @@ -175,9 +175,7 @@ void CameraRotationTest::onExit() CameraBaseTest::onExit(); } -void CameraRotationTest::update(float dt) -{ -} +void CameraRotationTest::update(float dt) {} //------------------------------------------------------------------ // @@ -185,80 +183,75 @@ void CameraRotationTest::update(float dt) // //------------------------------------------------------------------ Camera3DTestDemo::Camera3DTestDemo() -: _cameraType(CameraType::Free) -, _incRot(nullptr) -, _decRot(nullptr) -, _camera(nullptr) -, _bZoomOut(false) -, _bZoomIn(false) -, _bRotateLeft(false) -, _bRotateRight(false) -{ -} -Camera3DTestDemo::~Camera3DTestDemo() -{ -} -void Camera3DTestDemo::reachEndCallBack() -{ -} + : _cameraType(CameraType::Free) + , _incRot(nullptr) + , _decRot(nullptr) + , _camera(nullptr) + , _bZoomOut(false) + , _bZoomIn(false) + , _bRotateLeft(false) + , _bRotateRight(false) +{} +Camera3DTestDemo::~Camera3DTestDemo() {} +void Camera3DTestDemo::reachEndCallBack() {} std::string Camera3DTestDemo::title() const { return "Testing Camera"; } -void Camera3DTestDemo::scaleCameraCallback(Ref* sender,float value) +void Camera3DTestDemo::scaleCameraCallback(Ref* sender, float value) { - if(_camera&& _cameraType!=CameraType::FirstPerson) + if (_camera && _cameraType != CameraType::FirstPerson) { - Vec3 cameraPos= _camera->getPosition3D(); - cameraPos+= cameraPos.getNormalized()*value; + Vec3 cameraPos = _camera->getPosition3D(); + cameraPos += cameraPos.getNormalized() * value; _camera->setPosition3D(cameraPos); } } -void Camera3DTestDemo::rotateCameraCallback(Ref* sender,float value) +void Camera3DTestDemo::rotateCameraCallback(Ref* sender, float value) { - if(_cameraType==CameraType::Free || _cameraType==CameraType::FirstPerson) + if (_cameraType == CameraType::Free || _cameraType == CameraType::FirstPerson) { - Vec3 rotation3D= _camera->getRotation3D(); - rotation3D.y+= value; + Vec3 rotation3D = _camera->getRotation3D(); + rotation3D.y += value; _camera->setRotation3D(rotation3D); } } void Camera3DTestDemo::SwitchViewCallback(Ref* sender, CameraType cameraType) { - if(_cameraType==cameraType) + if (_cameraType == cameraType) { - return ; + return; } _cameraType = cameraType; - if(_cameraType==CameraType::Free) + if (_cameraType == CameraType::Free) { _camera->setPosition3D(Vec3(0, 130, 130) + _sprite3D->getPosition3D()); _camera->lookAt(_sprite3D->getPosition3D()); - + _RotateRightlabel->setColor(Color3B::WHITE); _RotateLeftlabel->setColor(Color3B::WHITE); _ZoomInlabel->setColor(Color3B::WHITE); _ZoomOutlabel->setColor(Color3B::WHITE); } - else if(_cameraType==CameraType::FirstPerson) + else if (_cameraType == CameraType::FirstPerson) { Vec3 newFaceDir; _sprite3D->getWorldToNodeTransform().getForwardVector(&newFaceDir); newFaceDir.normalize(); - _camera->setPosition3D(Vec3(0,35,0) + _sprite3D->getPosition3D()); - _camera->lookAt(_sprite3D->getPosition3D() + newFaceDir*50); - + _camera->setPosition3D(Vec3(0, 35, 0) + _sprite3D->getPosition3D()); + _camera->lookAt(_sprite3D->getPosition3D() + newFaceDir * 50); + _RotateRightlabel->setColor(Color3B::WHITE); _RotateLeftlabel->setColor(Color3B::WHITE); _ZoomInlabel->setColor(Color3B::GRAY); _ZoomOutlabel->setColor(Color3B::GRAY); } - else if(_cameraType==CameraType::ThirdPerson) + else if (_cameraType == CameraType::ThirdPerson) { _camera->setPosition3D(Vec3(0, 130, 130) + _sprite3D->getPosition3D()); _camera->lookAt(_sprite3D->getPosition3D()); - + _RotateRightlabel->setColor(Color3B::GRAY); _RotateLeftlabel->setColor(Color3B::GRAY); _ZoomInlabel->setColor(Color3B::WHITE); @@ -268,112 +261,115 @@ void Camera3DTestDemo::SwitchViewCallback(Ref* sender, CameraType cameraType) void Camera3DTestDemo::onEnter() { CameraBaseTest::onEnter(); - _sprite3D=nullptr; - auto s = Director::getInstance()->getWinSize(); - auto listener = EventListenerTouchAllAtOnce::create(); + _sprite3D = nullptr; + auto s = Director::getInstance()->getWinSize(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(Camera3DTestDemo::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(Camera3DTestDemo::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(Camera3DTestDemo::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - auto layer3D=Layer::create(); - addChild(layer3D,0); - _layer3D=layer3D; - _curState=State_None; - addNewSpriteWithCoords( Vec3(0,0,0),"Sprite3DTest/girl.c3b",true,0.2f,true); + auto layer3D = Layer::create(); + addChild(layer3D, 0); + _layer3D = layer3D; + _curState = State_None; + addNewSpriteWithCoords(Vec3(0, 0, 0), "Sprite3DTest/girl.c3b", true, 0.2f, true); TTFConfig ttfConfig("fonts/arial.ttf", 20); - + auto containerForLabel1 = Node::create(); - _ZoomOutlabel = Label::createWithTTF(ttfConfig,"zoom out"); - _ZoomOutlabel->setPosition(s.width-50, VisibleRect::top().y-20); + _ZoomOutlabel = Label::createWithTTF(ttfConfig, "zoom out"); + _ZoomOutlabel->setPosition(s.width - 50, VisibleRect::top().y - 20); containerForLabel1->addChild(_ZoomOutlabel); addChild(containerForLabel1, 10); - + auto listener1 = EventListenerTouchOneByOne::create(); listener1->setSwallowTouches(true); - + listener1->onTouchBegan = CC_CALLBACK_2(Camera3DTestDemo::onTouchesZoomOut, this); listener1->onTouchEnded = CC_CALLBACK_2(Camera3DTestDemo::onTouchesZoomOutEnd, this); - + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, _ZoomOutlabel); - + auto containerForLabel2 = Node::create(); - _ZoomInlabel = Label::createWithTTF(ttfConfig,"zoom in"); - _ZoomInlabel->setPosition(s.width-50, VisibleRect::top().y-70); + _ZoomInlabel = Label::createWithTTF(ttfConfig, "zoom in"); + _ZoomInlabel->setPosition(s.width - 50, VisibleRect::top().y - 70); containerForLabel2->addChild(_ZoomInlabel); addChild(containerForLabel2, 10); - + auto listener2 = EventListenerTouchOneByOne::create(); listener2->setSwallowTouches(true); - + listener2->onTouchBegan = CC_CALLBACK_2(Camera3DTestDemo::onTouchesZoomIn, this); listener2->onTouchEnded = CC_CALLBACK_2(Camera3DTestDemo::onTouchesZoomInEnd, this); - + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener2, _ZoomInlabel); - + auto containerForLabel3 = Node::create(); - _RotateLeftlabel = Label::createWithTTF(ttfConfig,"rotate left"); - _RotateLeftlabel->setPosition(s.width-50, VisibleRect::top().y-120); + _RotateLeftlabel = Label::createWithTTF(ttfConfig, "rotate left"); + _RotateLeftlabel->setPosition(s.width - 50, VisibleRect::top().y - 120); containerForLabel3->addChild(_RotateLeftlabel); addChild(containerForLabel3, 10); - + auto listener3 = EventListenerTouchOneByOne::create(); listener3->setSwallowTouches(true); - + listener3->onTouchBegan = CC_CALLBACK_2(Camera3DTestDemo::onTouchesRotateLeft, this); listener3->onTouchEnded = CC_CALLBACK_2(Camera3DTestDemo::onTouchesRotateLeftEnd, this); - + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener3, _RotateLeftlabel); - + auto containerForLabel4 = Node::create(); - _RotateRightlabel = Label::createWithTTF(ttfConfig,"rotate right"); - _RotateRightlabel->setPosition(s.width-50, VisibleRect::top().y-170); + _RotateRightlabel = Label::createWithTTF(ttfConfig, "rotate right"); + _RotateRightlabel->setPosition(s.width - 50, VisibleRect::top().y - 170); containerForLabel4->addChild(_RotateRightlabel); addChild(containerForLabel4, 10); - + auto listener4 = EventListenerTouchOneByOne::create(); listener4->setSwallowTouches(true); - + listener4->onTouchBegan = CC_CALLBACK_2(Camera3DTestDemo::onTouchesRotateRight, this); listener4->onTouchEnded = CC_CALLBACK_2(Camera3DTestDemo::onTouchesRotateRightEnd, this); - + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener4, _RotateRightlabel); - - auto label1 = Label::createWithTTF(ttfConfig,"free "); - auto menuItem1 = MenuItemLabel::create(label1, CC_CALLBACK_1(Camera3DTestDemo::SwitchViewCallback,this,CameraType::Free)); - auto label2 = Label::createWithTTF(ttfConfig,"third person"); - auto menuItem2 = MenuItemLabel::create(label2, CC_CALLBACK_1(Camera3DTestDemo::SwitchViewCallback,this,CameraType::ThirdPerson)); - auto label3 = Label::createWithTTF(ttfConfig,"first person"); - auto menuItem3 = MenuItemLabel::create(label3, CC_CALLBACK_1(Camera3DTestDemo::SwitchViewCallback,this,CameraType::FirstPerson)); + + auto label1 = Label::createWithTTF(ttfConfig, "free "); + auto menuItem1 = + MenuItemLabel::create(label1, CC_CALLBACK_1(Camera3DTestDemo::SwitchViewCallback, this, CameraType::Free)); + auto label2 = Label::createWithTTF(ttfConfig, "third person"); + auto menuItem2 = MenuItemLabel::create( + label2, CC_CALLBACK_1(Camera3DTestDemo::SwitchViewCallback, this, CameraType::ThirdPerson)); + auto label3 = Label::createWithTTF(ttfConfig, "first person"); + auto menuItem3 = MenuItemLabel::create( + label3, CC_CALLBACK_1(Camera3DTestDemo::SwitchViewCallback, this, CameraType::FirstPerson)); auto menu = Menu::create(menuItem1, menuItem2, menuItem3, nullptr); - + menu->setPosition(Vec2::ZERO); - - menuItem1->setPosition(VisibleRect::left().x+100, VisibleRect::top().y-50); - menuItem2->setPosition(VisibleRect::left().x+100, VisibleRect::top().y -100); - menuItem3->setPosition(VisibleRect::left().x+100, VisibleRect::top().y -150); + + menuItem1->setPosition(VisibleRect::left().x + 100, VisibleRect::top().y - 50); + menuItem2->setPosition(VisibleRect::left().x + 100, VisibleRect::top().y - 100); + menuItem3->setPosition(VisibleRect::left().x + 100, VisibleRect::top().y - 150); addChild(menu, 0); schedule(CC_SCHEDULE_SELECTOR(Camera3DTestDemo::updateCamera), 0.0f); if (_camera == nullptr) { - _camera=Camera::createPerspective(60, (float)s.width/s.height, 1, 1000); + _camera = Camera::createPerspective(60, (float)s.width / s.height, 1, 1000); _camera->setCameraFlag(CameraFlag::USER1); _layer3D->addChild(_camera); } - SwitchViewCallback(this,CameraType::ThirdPerson); - DrawNode3D* line =DrawNode3D::create(); - //draw x - for( int j =-20; j<=20 ;j++) + SwitchViewCallback(this, CameraType::ThirdPerson); + DrawNode3D* line = DrawNode3D::create(); + // draw x + for (int j = -20; j <= 20; j++) { - line->drawLine(Vec3(-100.0f, 0.0f, 5.0f*j),Vec3(100.0f,0.0f,5.0f*j),Color4F(1,0,0,1)); + line->drawLine(Vec3(-100.0f, 0.0f, 5.0f * j), Vec3(100.0f, 0.0f, 5.0f * j), Color4F(1, 0, 0, 1)); } - //draw z - for( int j =-20; j<=20 ;j++) + // draw z + for (int j = -20; j <= 20; j++) { - line->drawLine(Vec3(5.0f*j, 0.0f, -100.0f),Vec3(5.0f*j,0.0f,100.0f),Color4F(0,0,1,1)); + line->drawLine(Vec3(5.0f * j, 0.0f, -100.0f), Vec3(5.0f * j, 0.0f, 100.0f), Color4F(0, 0, 1, 1)); } - //draw y - line->drawLine(Vec3(0.0f, -50.0f, 0.0f),Vec3(0,0,0),Color4F(0,0.5,0,1)); - line->drawLine(Vec3(0, 0, 0),Vec3(0,50.0f,0),Color4F(0,1,0,1)); + // draw y + line->drawLine(Vec3(0.0f, -50.0f, 0.0f), Vec3(0, 0, 0), Color4F(0, 0.5, 0, 1)); + line->drawLine(Vec3(0, 0, 0), Vec3(0, 50.0f, 0), Color4F(0, 1, 0, 1)); _layer3D->addChild(line); _layer3D->setCameraMask(2); @@ -387,191 +383,192 @@ void Camera3DTestDemo::onExit() } } -void Camera3DTestDemo::addNewSpriteWithCoords(Vec3 p,std::string fileName,bool playAnimation,float scale,bool bindCamera) +void Camera3DTestDemo::addNewSpriteWithCoords(Vec3 p, + std::string fileName, + bool playAnimation, + float scale, + bool bindCamera) { auto sprite = Sprite3D::create(fileName); _layer3D->addChild(sprite); - float globalZOrder=sprite->getGlobalZOrder(); - sprite->setPosition3D( Vec3( p.x, p.y,p.z) ); + float globalZOrder = sprite->getGlobalZOrder(); + sprite->setPosition3D(Vec3(p.x, p.y, p.z)); sprite->setGlobalZOrder(globalZOrder); - if(playAnimation) + if (playAnimation) { - auto animation = Animation3D::create(fileName,"Take 001"); + auto animation = Animation3D::create(fileName, "Take 001"); if (animation) { auto animate = Animate3D::create(animation); sprite->runAction(RepeatForever::create(animate)); } } - if(bindCamera) + if (bindCamera) { - _sprite3D=sprite; + _sprite3D = sprite; } - sprite->setScale(scale); -} -void Camera3DTestDemo::onTouchesBegan(const std::vector& touches, cocos2d::Event *event) -{ + sprite->setScale(scale); } -void Camera3DTestDemo::onTouchesMoved(const std::vector& touches, cocos2d::Event *event) +void Camera3DTestDemo::onTouchesBegan(const std::vector& touches, cocos2d::Event* event) {} +void Camera3DTestDemo::onTouchesMoved(const std::vector& touches, cocos2d::Event* event) { - if(touches.size()==1) + if (touches.size() == 1) { - auto touch = touches[0]; + auto touch = touches[0]; auto location = touch->getLocation(); - Point newPos = touch->getPreviousLocation()-location; - if(_cameraType==CameraType::Free || _cameraType==CameraType::FirstPerson) + Point newPos = touch->getPreviousLocation() - location; + if (_cameraType == CameraType::Free || _cameraType == CameraType::FirstPerson) { Vec3 cameraDir; Vec3 cameraRightDir; _camera->getNodeToWorldTransform().getForwardVector(&cameraDir); cameraDir.normalize(); - cameraDir.y=0; + cameraDir.y = 0; _camera->getNodeToWorldTransform().getRightVector(&cameraRightDir); cameraRightDir.normalize(); - cameraRightDir.y=0; - Vec3 cameraPos= _camera->getPosition3D(); - cameraPos+=cameraDir*newPos.y*0.1f; - cameraPos+=cameraRightDir*newPos.x*0.1f; + cameraRightDir.y = 0; + Vec3 cameraPos = _camera->getPosition3D(); + cameraPos += cameraDir * newPos.y * 0.1f; + cameraPos += cameraRightDir * newPos.x * 0.1f; _camera->setPosition3D(cameraPos); - if(_sprite3D && _cameraType==CameraType::FirstPerson) + if (_sprite3D && _cameraType == CameraType::FirstPerson) { - _sprite3D->setPosition3D(Vec3(_camera->getPositionX(),0,_camera->getPositionZ())); - _targetPos=_sprite3D->getPosition3D(); + _sprite3D->setPosition3D(Vec3(_camera->getPositionX(), 0, _camera->getPositionZ())); + _targetPos = _sprite3D->getPosition3D(); } } } } void Camera3DTestDemo::move3D(float elapsedTime) { - if(_sprite3D) + if (_sprite3D) { - Vec3 curPos= _sprite3D->getPosition3D(); + Vec3 curPos = _sprite3D->getPosition3D(); Vec3 newFaceDir = _targetPos - curPos; - newFaceDir.y = 0.0f; + newFaceDir.y = 0.0f; newFaceDir.normalize(); Vec3 offset = newFaceDir * 25.0f * elapsedTime; - curPos+=offset; + curPos += offset; _sprite3D->setPosition3D(curPos); - if(_cameraType==CameraType::ThirdPerson) + if (_cameraType == CameraType::ThirdPerson) { - Vec3 cameraPos= _camera->getPosition3D(); - cameraPos.x+=offset.x; - cameraPos.z+=offset.z; + Vec3 cameraPos = _camera->getPosition3D(); + cameraPos.x += offset.x; + cameraPos.z += offset.z; _camera->setPosition3D(cameraPos); } } } void Camera3DTestDemo::updateState(float elapsedTime) { - if(_sprite3D) + if (_sprite3D) { - Vec3 curPos= _sprite3D->getPosition3D(); + Vec3 curPos = _sprite3D->getPosition3D(); Vec3 curFaceDir; _sprite3D->getNodeToWorldTransform().getForwardVector(&curFaceDir); - curFaceDir=-curFaceDir; + curFaceDir = -curFaceDir; curFaceDir.normalize(); Vec3 newFaceDir = _targetPos - curPos; - newFaceDir.y = 0.0f; + newFaceDir.y = 0.0f; newFaceDir.normalize(); - float cosAngle = std::fabs(Vec3::dot(curFaceDir,newFaceDir) - 1.0f); - float dist = curPos.distanceSquared(_targetPos); - if(dist<=4.0f) + float cosAngle = std::fabs(Vec3::dot(curFaceDir, newFaceDir) - 1.0f); + float dist = curPos.distanceSquared(_targetPos); + if (dist <= 4.0f) { - if(cosAngle<=0.01f) + if (cosAngle <= 0.01f) _curState = State_Idle; else _curState = State_Rotate; } else { - if(cosAngle>0.01f) + if (cosAngle > 0.01f) _curState = State_Rotate | State_Move; else _curState = State_Move; } } } -void Camera3DTestDemo::onTouchesEnded(const std::vector& touches, cocos2d::Event *event) +void Camera3DTestDemo::onTouchesEnded(const std::vector& touches, cocos2d::Event* event) { - for ( auto &item: touches ) + for (auto& item : touches) { - auto touch = item; + auto touch = item; auto location = touch->getLocationInView(); - if(_camera) + if (_camera) { - if(_sprite3D && _cameraType==CameraType::ThirdPerson && _bZoomOut == false && _bZoomIn == false && _bRotateLeft == false && _bRotateRight == false) + if (_sprite3D && _cameraType == CameraType::ThirdPerson && _bZoomOut == false && _bZoomIn == false && + _bRotateLeft == false && _bRotateRight == false) { Vec3 nearP(location.x, location.y, -1.0f), farP(location.x, location.y, 1.0f); - + auto size = Director::getInstance()->getWinSize(); - nearP = _camera->unproject(nearP); - farP = _camera->unproject(farP); + nearP = _camera->unproject(nearP); + farP = _camera->unproject(farP); Vec3 dir(farP - nearP); - float dist=0.0f; - float ndd = Vec3::dot(Vec3(0,1,0),dir); - if(ndd == 0) - dist=0.0f; - float ndo = Vec3::dot(Vec3(0,1,0),nearP); - dist= (0 - ndo) / ndd; - Vec3 p = nearP + dist * dir; - - if( p.x > 100) + float dist = 0.0f; + float ndd = Vec3::dot(Vec3(0, 1, 0), dir); + if (ndd == 0) + dist = 0.0f; + float ndo = Vec3::dot(Vec3(0, 1, 0), nearP); + dist = (0 - ndo) / ndd; + Vec3 p = nearP + dist * dir; + + if (p.x > 100) p.x = 100; - if( p.x < -100) + if (p.x < -100) p.x = -100; - if( p.z > 100) + if (p.z > 100) p.z = 100; - if( p.z < -100) + if (p.z < -100) p.z = -100; - - _targetPos=p; + + _targetPos = p; } } } } -void onTouchesCancelled(const std::vector& touches, cocos2d::Event *event) -{ -} +void onTouchesCancelled(const std::vector& touches, cocos2d::Event* event) {} void Camera3DTestDemo::updateCamera(float fDelta) { - if(_sprite3D) + if (_sprite3D) { - if( _cameraType==CameraType::ThirdPerson) + if (_cameraType == CameraType::ThirdPerson) { updateState(fDelta); - if(isState(_curState,State_Move)) + if (isState(_curState, State_Move)) { move3D(fDelta); - if(isState(_curState,State_Rotate)) + if (isState(_curState, State_Rotate)) { Vec3 curPos = _sprite3D->getPosition3D(); - + Vec3 newFaceDir = _targetPos - curPos; - newFaceDir.y = 0; + newFaceDir.y = 0; newFaceDir.normalize(); Vec3 up; _sprite3D->getNodeToWorldTransform().getUpVector(&up); up.normalize(); Vec3 right; - Vec3::cross(-newFaceDir,up,&right); + Vec3::cross(-newFaceDir, up, &right); right.normalize(); - Vec3 pos = Vec3(0,0,0); + Vec3 pos = Vec3(0, 0, 0); Mat4 mat; mat.m[0] = right.x; mat.m[1] = right.y; mat.m[2] = right.z; mat.m[3] = 0.0f; - + mat.m[4] = up.x; mat.m[5] = up.y; mat.m[6] = up.z; mat.m[7] = 0.0f; - + mat.m[8] = newFaceDir.x; mat.m[9] = newFaceDir.y; mat.m[10] = newFaceDir.z; mat.m[11] = 0.0f; - + mat.m[12] = pos.x; mat.m[13] = pos.y; mat.m[14] = pos.z; @@ -580,24 +577,24 @@ void Camera3DTestDemo::updateCamera(float fDelta) } } } - if(_bZoomOut == true) + if (_bZoomOut == true) { - if(_camera) + if (_camera) { - if(_cameraType == CameraType::ThirdPerson) + if (_cameraType == CameraType::ThirdPerson) { - Vec3 lookDir = _camera->getPosition3D() - _sprite3D->getPosition3D(); + Vec3 lookDir = _camera->getPosition3D() - _sprite3D->getPosition3D(); Vec3 cameraPos = _camera->getPosition3D(); - if(lookDir.length() <= 300) + if (lookDir.length() <= 300) { cameraPos += lookDir.getNormalized(); _camera->setPosition3D(cameraPos); } } - else if(_cameraType == CameraType::Free) + else if (_cameraType == CameraType::Free) { Vec3 cameraPos = _camera->getPosition3D(); - if(cameraPos.length() <= 300) + if (cameraPos.length() <= 300) { cameraPos += cameraPos.getNormalized(); _camera->setPosition3D(cameraPos); @@ -605,24 +602,24 @@ void Camera3DTestDemo::updateCamera(float fDelta) } } } - if(_bZoomIn == true) + if (_bZoomIn == true) { - if(_camera) + if (_camera) { - if(_cameraType == CameraType::ThirdPerson) + if (_cameraType == CameraType::ThirdPerson) { - Vec3 lookDir = _camera->getPosition3D() - _sprite3D->getPosition3D(); + Vec3 lookDir = _camera->getPosition3D() - _sprite3D->getPosition3D(); Vec3 cameraPos = _camera->getPosition3D(); - if(lookDir.length() >= 50) + if (lookDir.length() >= 50) { cameraPos -= lookDir.getNormalized(); _camera->setPosition3D(cameraPos); } } - else if(_cameraType == CameraType::Free) + else if (_cameraType == CameraType::Free) { Vec3 cameraPos = _camera->getPosition3D(); - if(cameraPos.length() >= 50) + if (cameraPos.length() >= 50) { cameraPos -= cameraPos.getNormalized(); _camera->setPosition3D(cameraPos); @@ -630,21 +627,21 @@ void Camera3DTestDemo::updateCamera(float fDelta) } } } - if(_bRotateLeft == true) + if (_bRotateLeft == true) { - if(_cameraType==CameraType::Free || _cameraType==CameraType::FirstPerson) + if (_cameraType == CameraType::Free || _cameraType == CameraType::FirstPerson) { - Vec3 rotation3D= _camera->getRotation3D(); - rotation3D.y+= 1; + Vec3 rotation3D = _camera->getRotation3D(); + rotation3D.y += 1; _camera->setRotation3D(rotation3D); } } - if(_bRotateRight == true) + if (_bRotateRight == true) { - if(_cameraType==CameraType::Free || _cameraType==CameraType::FirstPerson) + if (_cameraType == CameraType::Free || _cameraType == CameraType::FirstPerson) { - Vec3 rotation3D= _camera->getRotation3D(); - rotation3D.y-= 1; + Vec3 rotation3D = _camera->getRotation3D(); + rotation3D.y -= 1; _camera->setRotation3D(rotation3D); } } @@ -653,11 +650,11 @@ void Camera3DTestDemo::updateCamera(float fDelta) bool Camera3DTestDemo::onTouchesCommon(Touch* touch, Event* event, bool* touchProperty) { auto target = static_cast(event->getCurrentTarget()); - + Vec2 locationInNode = target->convertToNodeSpace(touch->getLocation()); - Size s = target->getContentSize(); - Rect rect = Rect(0, 0, s.width, s.height); - + Size s = target->getContentSize(); + Rect rect = Rect(0, 0, s.width, s.height); + if (rect.containsPoint(locationInNode)) { *touchProperty = true; @@ -665,7 +662,7 @@ bool Camera3DTestDemo::onTouchesCommon(Touch* touch, Event* event, bool* touchPr } return false; } -bool Camera3DTestDemo::isState(unsigned int state,unsigned int bit) const +bool Camera3DTestDemo::isState(unsigned int state, unsigned int bit) const { return (state & bit) == bit; } @@ -705,19 +702,16 @@ void Camera3DTestDemo::onTouchesRotateRightEnd(Touch* touch, Event* event) //////////////////////////////////////////////////////////// // CameraCullingDemo CameraCullingDemo::CameraCullingDemo() -: _layer3D(nullptr) -, _cameraType(CameraType::FirstPerson) -, _cameraFirst(nullptr) -, _cameraThird(nullptr) -, _moveAction(nullptr) -, _drawAABB(nullptr) -, _drawFrustum(nullptr) -, _row(3) -{ -} -CameraCullingDemo::~CameraCullingDemo() -{ -} + : _layer3D(nullptr) + , _cameraType(CameraType::FirstPerson) + , _cameraFirst(nullptr) + , _cameraThird(nullptr) + , _moveAction(nullptr) + , _drawAABB(nullptr) + , _drawFrustum(nullptr) + , _row(3) +{} +CameraCullingDemo::~CameraCullingDemo() {} std::string CameraCullingDemo::title() const { @@ -729,59 +723,59 @@ void CameraCullingDemo::onEnter() CameraBaseTest::onEnter(); schedule(CC_SCHEDULE_SELECTOR(CameraCullingDemo::update), 0.0f); - + auto s = Director::getInstance()->getWinSize(); /*auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(Camera3DTestDemo::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(Camera3DTestDemo::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(Camera3DTestDemo::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);*/ - auto layer3D=Layer::create(); - addChild(layer3D,0); - _layer3D=layer3D; - + auto layer3D = Layer::create(); + addChild(layer3D, 0); + _layer3D = layer3D; + // switch camera MenuItemFont::setFontName("fonts/arial.ttf"); MenuItemFont::setFontSize(20); - - auto menuItem1 = MenuItemFont::create("Switch Camera", CC_CALLBACK_1(CameraCullingDemo::switchViewCallback,this)); - menuItem1->setColor(Color3B(0,200,20)); - auto menu = Menu::create(menuItem1,NULL); + + auto menuItem1 = MenuItemFont::create("Switch Camera", CC_CALLBACK_1(CameraCullingDemo::switchViewCallback, this)); + menuItem1->setColor(Color3B(0, 200, 20)); + auto menu = Menu::create(menuItem1, NULL); menu->setPosition(Vec2::ZERO); - menuItem1->setPosition(VisibleRect::left().x + 80, VisibleRect::top().y -70); + menuItem1->setPosition(VisibleRect::left().x + 80, VisibleRect::top().y - 70); addChild(menu, 1); - + // + - MenuItemFont::setFontSize(40); auto decrease = MenuItemFont::create(" - ", CC_CALLBACK_1(CameraCullingDemo::delSpriteCallback, this)); - decrease->setColor(Color3B(0,200,20)); + decrease->setColor(Color3B(0, 200, 20)); auto increase = MenuItemFont::create(" + ", CC_CALLBACK_1(CameraCullingDemo::addSpriteCallback, this)); - increase->setColor(Color3B(0,200,20)); - + increase->setColor(Color3B(0, 200, 20)); + menu = Menu::create(decrease, increase, nullptr); menu->alignItemsHorizontally(); - menu->setPosition(Vec2(s.width - 60, VisibleRect::top().y -70)); + menu->setPosition(Vec2(s.width - 60, VisibleRect::top().y - 70)); addChild(menu, 1); - + TTFConfig ttfCount("fonts/Marker Felt.ttf", 30); - _labelSprite3DCount = Label::createWithTTF(ttfCount,"0 sprits"); - _labelSprite3DCount->setColor(Color3B(0,200,20)); - _labelSprite3DCount->setPosition(Vec2(s.width/2, VisibleRect::top().y -70)); + _labelSprite3DCount = Label::createWithTTF(ttfCount, "0 sprits"); + _labelSprite3DCount->setColor(Color3B(0, 200, 20)); + _labelSprite3DCount->setPosition(Vec2(s.width / 2, VisibleRect::top().y - 70)); addChild(_labelSprite3DCount); - + // aabb drawNode3D _drawAABB = DrawNode3D::create(); - _drawAABB->setCameraMask((unsigned short) CameraFlag::USER1); + _drawAABB->setCameraMask((unsigned short)CameraFlag::USER1); addChild(_drawAABB); - + // frustum drawNode3D _drawFrustum = DrawNode3D::create(); - _drawFrustum->setCameraMask((unsigned short) CameraFlag::USER1); + _drawFrustum->setCameraMask((unsigned short)CameraFlag::USER1); addChild(_drawFrustum); - + // set camera switchViewCallback(this); - + // add sprite addSpriteCallback(nullptr); } @@ -803,13 +797,13 @@ void CameraCullingDemo::update(float dt) { _drawAABB->clear(); - if(_cameraType == CameraType::ThirdPerson) + if (_cameraType == CameraType::ThirdPerson) drawCameraFrustum(); Vector& children = _layer3D->getChildren(); Vec3 corners[8]; - for (const auto& iter: children) + for (const auto& iter : children) { const AABB& aabb = static_cast(iter)->getAABB(); if (_cameraFirst->isVisibleInFrustum(&aabb)) @@ -825,11 +819,12 @@ void CameraCullingDemo::reachEndCallBack() _cameraFirst->stopActionByTag(100); auto inverse = MoveTo::create(4.f, Vec2(-_cameraFirst->getPositionX(), 0.0f)); inverse->retain(); - + _moveAction->release(); _moveAction = inverse; - auto rot = RotateBy::create(1.f, Vec3(0.f, 180.f, 0.f)); - auto seq = Sequence::create(rot, _moveAction, CallFunc::create(CC_CALLBACK_0(CameraCullingDemo::reachEndCallBack, this)), nullptr); + auto rot = RotateBy::create(1.f, Vec3(0.f, 180.f, 0.f)); + auto seq = Sequence::create(rot, _moveAction, + CallFunc::create(CC_CALLBACK_0(CameraCullingDemo::reachEndCallBack, this)), nullptr); seq->setTag(100); _cameraFirst->runAction(seq); } @@ -837,37 +832,38 @@ void CameraCullingDemo::reachEndCallBack() void CameraCullingDemo::switchViewCallback(Ref* sender) { auto s = Director::getInstance()->getWinSize(); - + if (_cameraFirst == nullptr) { - _cameraFirst = Camera::createPerspective(30.0f, (float)s.width/s.height, 10.0f, 200.0f); + _cameraFirst = Camera::createPerspective(30.0f, (float)s.width / s.height, 10.0f, 200.0f); _cameraFirst->setCameraFlag(CameraFlag::USER8); - _cameraFirst->setPosition3D(Vec3(-100.0f,0.0f,0.0f)); - _cameraFirst->lookAt(Vec3(1000.0f,0.0f,0.0f)); + _cameraFirst->setPosition3D(Vec3(-100.0f, 0.0f, 0.0f)); + _cameraFirst->lookAt(Vec3(1000.0f, 0.0f, 0.0f)); _moveAction = MoveTo::create(4.f, Vec2(-_cameraFirst->getPositionX(), 0.0f)); _moveAction->retain(); - auto seq = Sequence::create(_moveAction, CallFunc::create(CC_CALLBACK_0(CameraCullingDemo::reachEndCallBack, this)), nullptr); + auto seq = Sequence::create( + _moveAction, CallFunc::create(CC_CALLBACK_0(CameraCullingDemo::reachEndCallBack, this)), nullptr); seq->setTag(100); _cameraFirst->runAction(seq); addChild(_cameraFirst); } - + if (_cameraThird == nullptr) { - _cameraThird = Camera::createPerspective(60, (float)s.width/s.height, 1, 1000); + _cameraThird = Camera::createPerspective(60, (float)s.width / s.height, 1, 1000); _cameraThird->setCameraFlag(CameraFlag::USER8); _cameraThird->setPosition3D(Vec3(0.0f, 130.0f, 130.0f)); - _cameraThird->lookAt(Vec3(0,0,0)); + _cameraThird->lookAt(Vec3(0, 0, 0)); addChild(_cameraThird); } - - if(_cameraType == CameraType::FirstPerson) + + if (_cameraType == CameraType::FirstPerson) { _cameraType = CameraType::ThirdPerson; _cameraThird->setCameraFlag(CameraFlag::USER1); _cameraFirst->setCameraFlag(CameraFlag::USER8); } - else if(_cameraType == CameraType::ThirdPerson) + else if (_cameraType == CameraType::ThirdPerson) { _cameraType = CameraType::FirstPerson; _cameraFirst->setCameraFlag(CameraFlag::USER1); @@ -881,7 +877,7 @@ void CameraCullingDemo::addSpriteCallback(Ref* sender) _layer3D->removeAllChildren(); _objects.clear(); _drawAABB->clear(); - + ++_row; for (int x = -_row; x < _row; x++) { @@ -889,28 +885,29 @@ void CameraCullingDemo::addSpriteCallback(Ref* sender) { auto sprite = Sprite3D::create("Sprite3DTest/orc.c3b"); sprite->setPosition3D(Vec3(x * 30.0f, 0.0f, z * 30.0f)); - sprite->setRotation3D(Vec3(0.0f,180.0f,0.0f)); + sprite->setRotation3D(Vec3(0.0f, 180.0f, 0.0f)); _objects.push_back(sprite); _layer3D->addChild(sprite); } } - + // set layer mask. - _layer3D->setCameraMask( (unsigned short) CameraFlag::USER1); - + _layer3D->setCameraMask((unsigned short)CameraFlag::USER1); + // update sprite number char szText[16]; - sprintf(szText,"%d sprits", static_cast(_layer3D->getChildrenCount())); + sprintf(szText, "%d sprits", static_cast(_layer3D->getChildrenCount())); _labelSprite3DCount->setString(szText); } void CameraCullingDemo::delSpriteCallback(Ref* sender) { - if (_row == 0) return; - + if (_row == 0) + return; + _layer3D->removeAllChildren(); _objects.clear(); - + --_row; for (int x = -_row; x < _row; x++) { @@ -922,13 +919,13 @@ void CameraCullingDemo::delSpriteCallback(Ref* sender) _layer3D->addChild(sprite); } } - + // set layer mask. - _layer3D->setCameraMask((unsigned short) CameraFlag::USER1); - + _layer3D->setCameraMask((unsigned short)CameraFlag::USER1); + // update sprite number char szText[16]; - sprintf(szText,"%l sprits", static_cast(_layer3D->getChildrenCount())); + sprintf(szText, "%l sprits", static_cast(_layer3D->getChildrenCount())); _labelSprite3DCount->setString(szText); } @@ -936,47 +933,47 @@ void CameraCullingDemo::drawCameraFrustum() { _drawFrustum->clear(); auto size = Director::getInstance()->getWinSize(); - + Color4F color(1.f, 1.f, 0.f, 1); - + // top-left - Vec3 tl_0,tl_1; - Vec3 src(0,0,0); + Vec3 tl_0, tl_1; + Vec3 src(0, 0, 0); tl_0 = _cameraFirst->unproject(src); - src = Vec3(0,0,1); + src = Vec3(0, 0, 1); tl_1 = _cameraFirst->unproject(src); - + // top-right - Vec3 tr_0,tr_1; - src = Vec3(size.width,0,0); + Vec3 tr_0, tr_1; + src = Vec3(size.width, 0, 0); tr_0 = _cameraFirst->unproject(src); - src = Vec3(size.width,0,1); + src = Vec3(size.width, 0, 1); tr_1 = _cameraFirst->unproject(src); - + // bottom-left - Vec3 bl_0,bl_1; - src = Vec3(0,size.height,0); + Vec3 bl_0, bl_1; + src = Vec3(0, size.height, 0); bl_0 = _cameraFirst->unproject(src); - src = Vec3(0,size.height,1); + src = Vec3(0, size.height, 1); bl_1 = _cameraFirst->unproject(src); - + // bottom-right - Vec3 br_0,br_1; - src = Vec3(size.width,size.height,0); + Vec3 br_0, br_1; + src = Vec3(size.width, size.height, 0); br_0 = _cameraFirst->unproject(src); - src = Vec3(size.width,size.height,1); + src = Vec3(size.width, size.height, 1); br_1 = _cameraFirst->unproject(src); - + _drawFrustum->drawLine(tl_0, tl_1, color); _drawFrustum->drawLine(tr_0, tr_1, color); _drawFrustum->drawLine(bl_0, bl_1, color); _drawFrustum->drawLine(br_0, br_1, color); - + _drawFrustum->drawLine(tl_0, tr_0, color); _drawFrustum->drawLine(tr_0, br_0, color); _drawFrustum->drawLine(br_0, bl_0, color); _drawFrustum->drawLine(bl_0, tl_0, color); - + _drawFrustum->drawLine(tl_1, tr_1, color); _drawFrustum->drawLine(tr_1, br_1, color); _drawFrustum->drawLine(br_1, bl_1, color); @@ -986,23 +983,20 @@ void CameraCullingDemo::drawCameraFrustum() //////////////////////////////////////////////////////////// // CameraArcBallDemo CameraArcBallDemo::CameraArcBallDemo() -: CameraBaseTest() -, _layer3D(nullptr) -, _cameraType(CameraType::Free) -, _camera(nullptr) -, _drawGrid(nullptr) -, _radius(1.0f) -, _distanceZ(50.0f) -, _operate(OperateCamType::RotateCamera) -, _center(Vec3(0,0,0)) -, _target(0) -, _sprite3D1(nullptr) -, _sprite3D2(nullptr) -{ -} -CameraArcBallDemo::~CameraArcBallDemo() -{ -} + : CameraBaseTest() + , _layer3D(nullptr) + , _cameraType(CameraType::Free) + , _camera(nullptr) + , _drawGrid(nullptr) + , _radius(1.0f) + , _distanceZ(50.0f) + , _operate(OperateCamType::RotateCamera) + , _center(Vec3(0, 0, 0)) + , _target(0) + , _sprite3D1(nullptr) + , _sprite3D2(nullptr) +{} +CameraArcBallDemo::~CameraArcBallDemo() {} std::string CameraArcBallDemo::title() const { @@ -1014,32 +1008,34 @@ void CameraArcBallDemo::onEnter() CameraBaseTest::onEnter(); _rotationQuat.set(0.0f, 0.0f, 0.0f, 1.0f); schedule(CC_SCHEDULE_SELECTOR(CameraArcBallDemo::update), 0.0f); - auto s = Director::getInstance()->getWinSize(); - auto listener = EventListenerTouchAllAtOnce::create(); + auto s = Director::getInstance()->getWinSize(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesMoved = CC_CALLBACK_2(CameraArcBallDemo::onTouchsMoved, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // switch camera MenuItemFont::setFontName("fonts/arial.ttf"); MenuItemFont::setFontSize(20); - - auto menuItem1 = MenuItemFont::create("Switch Operation", CC_CALLBACK_1(CameraArcBallDemo::switchOperateCallback,this)); - menuItem1->setColor(Color3B(0,200,20)); - auto menuItem2 = MenuItemFont::create("Switch Target", CC_CALLBACK_1(CameraArcBallDemo::switchTargetCallback,this)); - menuItem2->setColor(Color3B(0,200,20)); - auto menu = Menu::create(menuItem1,menuItem2,NULL); + + auto menuItem1 = + MenuItemFont::create("Switch Operation", CC_CALLBACK_1(CameraArcBallDemo::switchOperateCallback, this)); + menuItem1->setColor(Color3B(0, 200, 20)); + auto menuItem2 = + MenuItemFont::create("Switch Target", CC_CALLBACK_1(CameraArcBallDemo::switchTargetCallback, this)); + menuItem2->setColor(Color3B(0, 200, 20)); + auto menu = Menu::create(menuItem1, menuItem2, NULL); menu->setPosition(Vec2::ZERO); - menuItem1->setPosition(VisibleRect::left().x + 80, VisibleRect::top().y -70); - menuItem2->setPosition(VisibleRect::left().x + 80, VisibleRect::top().y -100); + menuItem1->setPosition(VisibleRect::left().x + 80, VisibleRect::top().y - 70); + menuItem2->setPosition(VisibleRect::left().x + 80, VisibleRect::top().y - 100); addChild(menu, 1); - auto layer3D=Layer::create(); - addChild(layer3D,0); - _layer3D=layer3D; + auto layer3D = Layer::create(); + addChild(layer3D, 0); + _layer3D = layer3D; if (_camera == nullptr) { - _camera=Camera::createPerspective(60, (float)s.width/s.height, 1, 1000); + _camera = Camera::createPerspective(60, (float)s.width / s.height, 1, 1000); _camera->setCameraFlag(CameraFlag::USER1); _camera->setPosition3D(Vec3(0.0f, 10.0f, 50.0f)); _camera->lookAt(Vec3(0, 0, 0), Vec3(0.0f, 1.0f, 0.0f)); @@ -1049,36 +1045,35 @@ void CameraArcBallDemo::onEnter() _sprite3D1 = Sprite3D::create("Sprite3DTest/orc.c3b"); _sprite3D1->setScale(0.5); - _sprite3D1->setRotation3D(Vec3(0.0f,180.0f,0.0f)); - _sprite3D1->setPosition3D(Vec3(0,0,0)); + _sprite3D1->setRotation3D(Vec3(0.0f, 180.0f, 0.0f)); + _sprite3D1->setPosition3D(Vec3(0, 0, 0)); _layer3D->addChild(_sprite3D1); _sprite3D2 = Sprite3D::create("Sprite3DTest/boss.c3b"); _sprite3D2->setScale(0.6f); - _sprite3D2->setRotation3D(Vec3(-90.0f,0.0f,0.0f)); - _sprite3D2->setPosition3D(Vec3(20.0f,0.0f,0.0f)); + _sprite3D2->setRotation3D(Vec3(-90.0f, 0.0f, 0.0f)); + _sprite3D2->setPosition3D(Vec3(20.0f, 0.0f, 0.0f)); _layer3D->addChild(_sprite3D2); - _drawGrid =DrawNode3D::create(); + _drawGrid = DrawNode3D::create(); - //draw x - for( int j =-20; j<=20 ;j++) + // draw x + for (int j = -20; j <= 20; j++) { - _drawGrid->drawLine(Vec3(-100.0f, 0, 5.0f*j),Vec3(100.0f,0,5.0f*j),Color4F(1,0,0,1)); + _drawGrid->drawLine(Vec3(-100.0f, 0, 5.0f * j), Vec3(100.0f, 0, 5.0f * j), Color4F(1, 0, 0, 1)); } - //draw z - for( int j =-20; j<=20 ;j++) + // draw z + for (int j = -20; j <= 20; j++) { - _drawGrid->drawLine(Vec3(5.0f*j, 0, -100.0f),Vec3(5.0f*j,0,100.0f),Color4F(0,0,1,1)); + _drawGrid->drawLine(Vec3(5.0f * j, 0, -100.0f), Vec3(5.0f * j, 0, 100.0f), Color4F(0, 0, 1, 1)); } - //draw y - _drawGrid->drawLine(Vec3(0, 0, 0),Vec3(0,50.0f,0),Color4F(0,1,0,1)); + // draw y + _drawGrid->drawLine(Vec3(0, 0, 0), Vec3(0, 50.0f, 0), Color4F(0, 1, 0, 1)); _layer3D->addChild(_drawGrid); _layer3D->setCameraMask(2); updateCameraTransform(); - } void CameraArcBallDemo::onExit() @@ -1090,74 +1085,77 @@ void CameraArcBallDemo::onExit() } } -void CameraArcBallDemo::onTouchsMoved( const std::vector &touchs, Event *event ) +void CameraArcBallDemo::onTouchsMoved(const std::vector& touchs, Event* event) { if (!touchs.empty()) { - if(_operate == OperateCamType::RotateCamera) //arc ball rotate + if (_operate == OperateCamType::RotateCamera) // arc ball rotate { Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 prelocation = touchs[0]->getPreviousLocationInView(); - Vec2 location = touchs[0]->getLocationInView(); - location.x = 2.0f * (location.x) / (visibleSize.width) - 1.0f; - location.y = 2.0f * (visibleSize.height - location.y) / (visibleSize.height) - 1.0f; - prelocation.x = 2.0f * (prelocation.x) / (visibleSize.width) - 1.0f; - prelocation.y = 2.0f * (visibleSize.height - prelocation.y) / (visibleSize.height) - 1.0f; + Vec2 location = touchs[0]->getLocationInView(); + location.x = 2.0f * (location.x) / (visibleSize.width) - 1.0f; + location.y = 2.0f * (visibleSize.height - location.y) / (visibleSize.height) - 1.0f; + prelocation.x = 2.0f * (prelocation.x) / (visibleSize.width) - 1.0f; + prelocation.y = 2.0f * (visibleSize.height - prelocation.y) / (visibleSize.height) - 1.0f; Vec3 axes; float angle; - calculateArcBall(axes, angle, prelocation.x, prelocation.y, location.x, location.y); //calculate rotation quaternion parameters - Quaternion quat(axes, angle); //get rotation quaternion + calculateArcBall(axes, angle, prelocation.x, prelocation.y, location.x, + location.y); // calculate rotation quaternion parameters + Quaternion quat(axes, angle); // get rotation quaternion _rotationQuat = quat * _rotationQuat; - updateCameraTransform(); //update camera Transform + updateCameraTransform(); // update camera Transform } - else if(_operate == OperateCamType::MoveCamera) //camera zoom + else if (_operate == OperateCamType::MoveCamera) // camera zoom { Point newPos = touchs[0]->getPreviousLocation() - touchs[0]->getLocation(); - _distanceZ -= newPos.y*0.1f; + _distanceZ -= newPos.y * 0.1f; updateCameraTransform(); } } } -void CameraArcBallDemo::calculateArcBall( cocos2d::Vec3 & axis, float & angle, float p1x, float p1y, float p2x, float p2y ) +void CameraArcBallDemo::calculateArcBall(cocos2d::Vec3& axis, float& angle, float p1x, float p1y, float p2x, float p2y) { Mat4 rotation_matrix; Mat4::createRotation(_rotationQuat, &rotation_matrix); - Vec3 uv = rotation_matrix * Vec3(0.0f,1.0f,0.0f); //rotation y - Vec3 sv = rotation_matrix * Vec3(1.0f,0.0f,0.0f); //rotation x - Vec3 lv = rotation_matrix * Vec3(0.0f,0.0f,-1.0f);//rotation z + Vec3 uv = rotation_matrix * Vec3(0.0f, 1.0f, 0.0f); // rotation y + Vec3 sv = rotation_matrix * Vec3(1.0f, 0.0f, 0.0f); // rotation x + Vec3 lv = rotation_matrix * Vec3(0.0f, 0.0f, -1.0f); // rotation z - Vec3 p1 = sv * p1x + uv * p1y - lv * projectToSphere(_radius, p1x, p1y); //start point screen transform to 3d - Vec3 p2 = sv * p2x + uv * p2y - lv * projectToSphere(_radius, p2x, p2y); //end point screen transform to 3d + Vec3 p1 = sv * p1x + uv * p1y - lv * projectToSphere(_radius, p1x, p1y); // start point screen transform to 3d + Vec3 p2 = sv * p2x + uv * p2y - lv * projectToSphere(_radius, p2x, p2y); // end point screen transform to 3d - Vec3::cross(p2, p1, &axis); //calculate rotation axis + Vec3::cross(p2, p1, &axis); // calculate rotation axis axis.normalize(); float t = (p2 - p1).length() / (2.0f * _radius); - //clamp -1 to 1 - if (t > 1.0) t = 1.0; - if (t < -1.0) t = -1.0; - angle = asin(t); //rotation angle + // clamp -1 to 1 + if (t > 1.0) + t = 1.0; + if (t < -1.0) + t = -1.0; + angle = asin(t); // rotation angle } /* project an x,y pair onto a sphere of radius r or a hyperbolic sheet if we are away from the center of the sphere. */ -float CameraArcBallDemo::projectToSphere( float r, float x, float y ) +float CameraArcBallDemo::projectToSphere(float r, float x, float y) { float d, t, z; - d = sqrt(x*x + y*y); - if (d < r * 0.70710678118654752440)//inside sphere + d = sqrt(x * x + y * y); + if (d < r * 0.70710678118654752440) // inside sphere { - z = sqrt(r*r - d*d); - } - else //on hyperbola + z = sqrt(r * r - d * d); + } + else // on hyperbola { t = r / 1.41421356237309504880f; - z = t*t / d; + z = t * t / d; } return z; } @@ -1174,11 +1172,11 @@ void CameraArcBallDemo::updateCameraTransform() void CameraArcBallDemo::switchOperateCallback(Ref* sender) { - if(_operate == OperateCamType::MoveCamera) + if (_operate == OperateCamType::MoveCamera) { _operate = OperateCamType::RotateCamera; } - else if(_operate == OperateCamType::RotateCamera) + else if (_operate == OperateCamType::RotateCamera) { _operate = OperateCamType::MoveCamera; } @@ -1186,13 +1184,13 @@ void CameraArcBallDemo::switchOperateCallback(Ref* sender) void CameraArcBallDemo::switchTargetCallback(Ref* sender) { - if(_target == 0) + if (_target == 0) { _target = 1; _center = _sprite3D2->getPosition3D(); updateCameraTransform(); } - else if(_target == 1) + else if (_target == 1) { _target = 0; _center = _sprite3D1->getPosition3D(); @@ -1202,15 +1200,12 @@ void CameraArcBallDemo::switchTargetCallback(Ref* sender) void CameraArcBallDemo::update(float dt) { - //updateCameraTransform(); + // updateCameraTransform(); } //////////////////////////////////////////////////////////// // FogTestDemo -FogTestDemo::FogTestDemo() -: CameraBaseTest() -{ -} +FogTestDemo::FogTestDemo() : CameraBaseTest() {} FogTestDemo::~FogTestDemo() { CC_SAFE_RELEASE_NULL(_programState1); @@ -1226,159 +1221,152 @@ void FogTestDemo::onEnter() { CameraBaseTest::onEnter(); schedule(CC_SCHEDULE_SELECTOR(FogTestDemo::update), 0.0f); - Director::getInstance()->setClearColor(Color4F(0.5,0.5,0.5,1)); + Director::getInstance()->setClearColor(Color4F(0.5, 0.5, 0.5, 1)); - auto s = Director::getInstance()->getWinSize(); - auto listener = EventListenerTouchAllAtOnce::create(); + auto s = Director::getInstance()->getWinSize(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesMoved = CC_CALLBACK_2(FogTestDemo::onTouchesMoved, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // switch fog type TTFConfig ttfConfig("fonts/arial.ttf", 20); - - auto label1 = Label::createWithTTF(ttfConfig,"Linear "); - auto menuItem1 = MenuItemLabel::create(label1, CC_CALLBACK_1(FogTestDemo::switchTypeCallback,this,0)); - auto label2 = Label::createWithTTF(ttfConfig,"Exp"); - auto menuItem2 = MenuItemLabel::create(label2, CC_CALLBACK_1(FogTestDemo::switchTypeCallback,this,1)); - auto label3 = Label::createWithTTF(ttfConfig,"Exp2"); - auto menuItem3 = MenuItemLabel::create(label3, CC_CALLBACK_1(FogTestDemo::switchTypeCallback,this,2)); - auto menu = Menu::create(menuItem1, menuItem2, menuItem3, nullptr); - + + auto label1 = Label::createWithTTF(ttfConfig, "Linear "); + auto menuItem1 = MenuItemLabel::create(label1, CC_CALLBACK_1(FogTestDemo::switchTypeCallback, this, 0)); + auto label2 = Label::createWithTTF(ttfConfig, "Exp"); + auto menuItem2 = MenuItemLabel::create(label2, CC_CALLBACK_1(FogTestDemo::switchTypeCallback, this, 1)); + auto label3 = Label::createWithTTF(ttfConfig, "Exp2"); + auto menuItem3 = MenuItemLabel::create(label3, CC_CALLBACK_1(FogTestDemo::switchTypeCallback, this, 2)); + auto menu = Menu::create(menuItem1, menuItem2, menuItem3, nullptr); + menu->setPosition(Vec2::ZERO); - - menuItem1->setPosition(VisibleRect::left().x+60, VisibleRect::top().y-50); - menuItem2->setPosition(VisibleRect::left().x+60, VisibleRect::top().y -100); - menuItem3->setPosition(VisibleRect::left().x+60, VisibleRect::top().y -150); - addChild(menu, 0); + menuItem1->setPosition(VisibleRect::left().x + 60, VisibleRect::top().y - 50); + menuItem2->setPosition(VisibleRect::left().x + 60, VisibleRect::top().y - 100); + menuItem3->setPosition(VisibleRect::left().x + 60, VisibleRect::top().y - 150); + addChild(menu, 0); - auto layer3D=Layer::create(); - addChild(layer3D,0); - _layer3D=layer3D; + auto layer3D = Layer::create(); + addChild(layer3D, 0); + _layer3D = layer3D; CC_SAFE_RELEASE_NULL(_programState1); CC_SAFE_RELEASE_NULL(_programState2); auto vertexSource = FileUtils::getInstance()->getStringFromFile("Sprite3DTest/fog.vert"); - auto fragSource = FileUtils::getInstance()->getStringFromFile("Sprite3DTest/fog.frag"); - auto program = backend::Device::getInstance()->newProgram(vertexSource, fragSource); - _programState1 = new backend::ProgramState(program); - _programState2 = new backend::ProgramState(program); + auto fragSource = FileUtils::getInstance()->getStringFromFile("Sprite3DTest/fog.frag"); + auto program = backend::Device::getInstance()->newProgram(vertexSource, fragSource); + _programState1 = new backend::ProgramState(program); + _programState2 = new backend::ProgramState(program); CC_SAFE_RELEASE(program); - + _sprite3D1 = Sprite3D::create("Sprite3DTest/teapot.c3b"); _sprite3D2 = Sprite3D::create("Sprite3DTest/teapot.c3b"); _sprite3D1->setProgramState(_programState1); _sprite3D2->setProgramState(_programState2); - auto fogColor = Vec4(0.5, 0.5, 0.5, 1.0); - float fogStart = 10; - float fogEnd = 60; - int fogEquation = 0; + auto fogColor = Vec4(0.5, 0.5, 0.5, 1.0); + float fogStart = 10; + float fogEnd = 60; + int fogEquation = 0; - SET_UNIFORM("u_fogColor", &fogColor, sizeof(fogColor)); - SET_UNIFORM("u_fogStart", &fogStart, sizeof(fogStart)); - SET_UNIFORM("u_fogEnd", &fogEnd, sizeof(fogEnd)); - SET_UNIFORM("u_fogEquation", &fogEquation, sizeof(fogEquation)); + SET_UNIFORM("u_fogColor", &fogColor, sizeof(fogColor)); + SET_UNIFORM("u_fogStart", &fogStart, sizeof(fogStart)); + SET_UNIFORM("u_fogEnd", &fogEnd, sizeof(fogEnd)); + SET_UNIFORM("u_fogEquation", &fogEquation, sizeof(fogEquation)); _layer3D->addChild(_sprite3D1); - _sprite3D1->setPosition3D( Vec3( 0, 0,0 ) ); + _sprite3D1->setPosition3D(Vec3(0, 0, 0)); _sprite3D1->setScale(2.0f); - _sprite3D1->setRotation3D(Vec3(-90.0f,180.0f,0.0f)); + _sprite3D1->setRotation3D(Vec3(-90.0f, 180.0f, 0.0f)); _layer3D->addChild(_sprite3D2); - _sprite3D2->setPosition3D( Vec3( 0.0f, 0.0f,-20.0f) ); + _sprite3D2->setPosition3D(Vec3(0.0f, 0.0f, -20.0f)); _sprite3D2->setScale(2.0f); - _sprite3D2->setRotation3D(Vec3(-90.0f,180.0f,0.0f)); + _sprite3D2->setRotation3D(Vec3(-90.0f, 180.0f, 0.0f)); if (_camera == nullptr) { - _camera=Camera::createPerspective(60, (float)s.width/s.height, 1, 1000); + _camera = Camera::createPerspective(60, (float)s.width / s.height, 1, 1000); _camera->setCameraFlag(CameraFlag::USER1); _camera->setPosition3D(Vec3(0.0f, 30.0f, 40.0f)); - _camera->lookAt(Vec3(0,0,0), Vec3(0.0f, 1.0f, 0.0f)); + _camera->lookAt(Vec3(0, 0, 0), Vec3(0.0f, 1.0f, 0.0f)); _layer3D->addChild(_camera); } _layer3D->setCameraMask(2); - #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) - _backToForegroundListener = EventListenerCustom::create(EVENT_RENDERER_RECREATED, - [this](EventCustom*) - { - Director::getInstance()->setClearColor(Color4F(0.5,0.5,0.5,1)); - CC_SAFE_RELEASE_NULL(_programState1); - CC_SAFE_RELEASE_NULL(_programState2); - - auto vertexSource = FileUtils::getInstance()->getStringFromFile("Sprite3DTest/fog.vert"); - auto fragSource = FileUtils::getInstance()->getStringFromFile("Sprite3DTest/fog.frag"); - auto program = backend::Device::getInstance()->newProgram(vertexSource, fragSource); - _programState1 = new backend::ProgramState(program); - _programState2 = new backend::ProgramState(program); - - _sprite3D1->setProgramState(_programState1); - _sprite3D2->setProgramState(_programState2); - CC_SAFE_RELEASE(program); - - auto fogColor = Vec4(0.5, 0.5, 0.5, 1.0); - float fogStart = 10; - float fogEnd = 60; - int fogEquation = 0; - - SET_UNIFORM("u_fogColor", &fogColor, sizeof(fogColor)); - SET_UNIFORM("u_fogStart", &fogStart, sizeof(fogStart)); - SET_UNIFORM("u_fogEnd", &fogEnd, sizeof(fogEnd)); - SET_UNIFORM("u_fogEquation", &fogEquation, sizeof(fogEquation)); - } - ); + _backToForegroundListener = EventListenerCustom::create(EVENT_RENDERER_RECREATED, [this](EventCustom*) { + Director::getInstance()->setClearColor(Color4F(0.5, 0.5, 0.5, 1)); + CC_SAFE_RELEASE_NULL(_programState1); + CC_SAFE_RELEASE_NULL(_programState2); + + auto vertexSource = FileUtils::getInstance()->getStringFromFile("Sprite3DTest/fog.vert"); + auto fragSource = FileUtils::getInstance()->getStringFromFile("Sprite3DTest/fog.frag"); + auto program = backend::Device::getInstance()->newProgram(vertexSource, fragSource); + _programState1 = new backend::ProgramState(program); + _programState2 = new backend::ProgramState(program); + + _sprite3D1->setProgramState(_programState1); + _sprite3D2->setProgramState(_programState2); + CC_SAFE_RELEASE(program); + + auto fogColor = Vec4(0.5, 0.5, 0.5, 1.0); + float fogStart = 10; + float fogEnd = 60; + int fogEquation = 0; + + SET_UNIFORM("u_fogColor", &fogColor, sizeof(fogColor)); + SET_UNIFORM("u_fogStart", &fogStart, sizeof(fogStart)); + SET_UNIFORM("u_fogEnd", &fogEnd, sizeof(fogEnd)); + SET_UNIFORM("u_fogEquation", &fogEquation, sizeof(fogEquation)); + }); Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(_backToForegroundListener, -1); #endif - } -void FogTestDemo::switchTypeCallback(Ref* sender,int type) +void FogTestDemo::switchTypeCallback(Ref* sender, int type) { - if(type == 0) + if (type == 0) { auto fogColor = Vec4(0.5, 0.5, 0.5, 1.0); float fogStart = 10; float fogEnd = 60; int fogEquation = 0; - SET_UNIFORM("u_fogColor", &fogColor, sizeof(fogColor)); - SET_UNIFORM("u_fogStart", &fogStart, sizeof(fogStart)); - SET_UNIFORM("u_fogEnd", &fogEnd, sizeof(fogEnd)); - SET_UNIFORM("u_fogEquation", &fogEquation, sizeof(fogEquation)); - + SET_UNIFORM("u_fogColor", &fogColor, sizeof(fogColor)); + SET_UNIFORM("u_fogStart", &fogStart, sizeof(fogStart)); + SET_UNIFORM("u_fogEnd", &fogEnd, sizeof(fogEnd)); + SET_UNIFORM("u_fogEquation", &fogEquation, sizeof(fogEquation)); } - else if(type == 1) + else if (type == 1) { - auto fogColor = Vec4(0.5, 0.5, 0.5, 1.0); - float fogDensity = 0.03f; - int fogEquation = 1; + auto fogColor = Vec4(0.5, 0.5, 0.5, 1.0); + float fogDensity = 0.03f; + int fogEquation = 1; - SET_UNIFORM("u_fogColor", &fogColor, sizeof(fogColor)); - SET_UNIFORM("u_fogDensity", &fogDensity, sizeof(fogDensity)); - SET_UNIFORM("u_fogEquation", &fogEquation, sizeof(fogEquation)); + SET_UNIFORM("u_fogColor", &fogColor, sizeof(fogColor)); + SET_UNIFORM("u_fogDensity", &fogDensity, sizeof(fogDensity)); + SET_UNIFORM("u_fogEquation", &fogEquation, sizeof(fogEquation)); } - else if(type == 2) + else if (type == 2) { - auto fogColor = Vec4(0.5, 0.5, 0.5, 1.0); - float fogDensity = 0.03f; - int fogEquation = 2; + auto fogColor = Vec4(0.5, 0.5, 0.5, 1.0); + float fogDensity = 0.03f; + int fogEquation = 2; - SET_UNIFORM("u_fogColor", &fogColor, sizeof(fogColor)); - SET_UNIFORM("u_fogDensity", &fogDensity, sizeof(fogDensity)); - SET_UNIFORM("u_fogEquation", &fogEquation, sizeof(fogEquation)); + SET_UNIFORM("u_fogColor", &fogColor, sizeof(fogColor)); + SET_UNIFORM("u_fogDensity", &fogDensity, sizeof(fogDensity)); + SET_UNIFORM("u_fogEquation", &fogEquation, sizeof(fogEquation)); } } void FogTestDemo::onExit() { CameraBaseTest::onExit(); - Director::getInstance()->setClearColor(Color4F(0,0,0,1)); + Director::getInstance()->setClearColor(Color4F(0, 0, 0, 1)); if (_camera) { _camera = nullptr; @@ -1389,108 +1377,102 @@ void FogTestDemo::onExit() #endif } -void FogTestDemo::update(float dt) -{ -} +void FogTestDemo::update(float dt) {} -void FogTestDemo::onTouchesMoved(const std::vector& touches, cocos2d::Event *event) +void FogTestDemo::onTouchesMoved(const std::vector& touches, cocos2d::Event* event) { - if(touches.size()==1) + if (touches.size() == 1) { Vec2 prelocation = touches[0]->getPreviousLocationInView(); - Vec2 location = touches[0]->getLocationInView(); - Vec2 newPos = prelocation - location; - if(_cameraType==CameraType::Free) + Vec2 location = touches[0]->getLocationInView(); + Vec2 newPos = prelocation - location; + if (_cameraType == CameraType::Free) { Vec3 cameraDir; Vec3 cameraRightDir; _camera->getNodeToWorldTransform().getForwardVector(&cameraDir); cameraDir.normalize(); - cameraDir.y=0; + cameraDir.y = 0; _camera->getNodeToWorldTransform().getRightVector(&cameraRightDir); cameraRightDir.normalize(); - cameraRightDir.y=0; - Vec3 cameraPos= _camera->getPosition3D(); - cameraPos-=cameraDir*newPos.y*0.1f; - cameraPos+=cameraRightDir*newPos.x*0.1f; + cameraRightDir.y = 0; + Vec3 cameraPos = _camera->getPosition3D(); + cameraPos -= cameraDir * newPos.y * 0.1f; + cameraPos += cameraRightDir * newPos.x * 0.1f; _camera->setPosition3D(cameraPos); } } } -//CameraFrameBufferTest::CameraFrameBufferTest() +// CameraFrameBufferTest::CameraFrameBufferTest() //{ -// -//} // -//CameraFrameBufferTest::~CameraFrameBufferTest() +// } +// +// CameraFrameBufferTest::~CameraFrameBufferTest() //{ -// -//} // -//std::string CameraFrameBufferTest::title() const +// } +// +// std::string CameraFrameBufferTest::title() const //{ -// return "Camera FrameBuffer Object Test"; -//} +// return "Camera FrameBuffer Object Test"; +// } // -//void CameraFrameBufferTest::onEnter() +// void CameraFrameBufferTest::onEnter() //{ -// auto sizeInpixels = Director::getInstance()->getWinSizeInPixels(); -// auto size = Director::getInstance()->getWinSize(); -// auto fboSize = Size(sizeInpixels.width * 1, sizeInpixels.height * 1.5); -// auto fbo = experimental::FrameBuffer::create(1, fboSize.width, fboSize.height); -// -// CameraBaseTest::onEnter(); -// //auto sprite = Sprite::createWithTexture(fbo); -// //sprite->setPosition(Vec2(100,100)); -// //std::string filename = "Sprite3DTest/girl.c3b"; -// //auto sprite = Sprite3D::create(filename); -// //sprite->setScale(1.0); -// //auto animation = Animation3D::create(filename); -// //if (animation) -// //{ -// // auto animate = Animate3D::create(animation); -// -// // sprite->runAction(RepeatForever::create(animate)); -// //} -// //sprite->setPosition(Vec2(100,100)); -// auto rt = experimental::RenderTarget::create(fboSize.width, fboSize.height); -// auto rtDS = experimental::RenderTargetDepthStencil::create(fboSize.width, fboSize.height); -// fbo->attachRenderTarget(rt); -// fbo->attachDepthStencilTarget(rtDS); -// auto sprite = Sprite::createWithTexture(fbo->getRenderTarget()->getTexture()); -// sprite->setScale(0.3f); -// sprite->runAction(RepeatForever::create(RotateBy::create(1, 90))); -// sprite->setPosition(size.width/2, size.height/2); -// addChild(sprite); -// -// auto sprite2 = Sprite::create(s_pathGrossini); -// sprite2->setPosition(Vec2(size.width/5,size.height/5)); -// addChild(sprite2); -// sprite2->setCameraMask((unsigned short)CameraFlag::USER1); -// auto move = MoveBy::create(1.0, Vec2(100,100)); -// sprite2->runAction( -// RepeatForever::create( -// Sequence::createWithTwoActions( -// move, move->reverse()) -// ) -// ); -// -// auto camera = Camera::create(); -// camera->setCameraFlag(CameraFlag::USER1); -// camera->setDepth(-1); -// camera->setFrameBufferObject(fbo); -// fbo->setClearColor(Color4F(1,1,1,1)); -// addChild(camera); -//} - -BackgroundColorBrushTest::BackgroundColorBrushTest() -{ -} +// auto sizeInpixels = Director::getInstance()->getWinSizeInPixels(); +// auto size = Director::getInstance()->getWinSize(); +// auto fboSize = Size(sizeInpixels.width * 1, sizeInpixels.height * 1.5); +// auto fbo = experimental::FrameBuffer::create(1, fboSize.width, fboSize.height); +// +// CameraBaseTest::onEnter(); +// //auto sprite = Sprite::createWithTexture(fbo); +// //sprite->setPosition(Vec2(100,100)); +// //std::string filename = "Sprite3DTest/girl.c3b"; +// //auto sprite = Sprite3D::create(filename); +// //sprite->setScale(1.0); +// //auto animation = Animation3D::create(filename); +// //if (animation) +// //{ +// // auto animate = Animate3D::create(animation); +// +// // sprite->runAction(RepeatForever::create(animate)); +// //} +// //sprite->setPosition(Vec2(100,100)); +// auto rt = experimental::RenderTarget::create(fboSize.width, fboSize.height); +// auto rtDS = experimental::RenderTargetDepthStencil::create(fboSize.width, fboSize.height); +// fbo->attachRenderTarget(rt); +// fbo->attachDepthStencilTarget(rtDS); +// auto sprite = Sprite::createWithTexture(fbo->getRenderTarget()->getTexture()); +// sprite->setScale(0.3f); +// sprite->runAction(RepeatForever::create(RotateBy::create(1, 90))); +// sprite->setPosition(size.width/2, size.height/2); +// addChild(sprite); +// +// auto sprite2 = Sprite::create(s_pathGrossini); +// sprite2->setPosition(Vec2(size.width/5,size.height/5)); +// addChild(sprite2); +// sprite2->setCameraMask((unsigned short)CameraFlag::USER1); +// auto move = MoveBy::create(1.0, Vec2(100,100)); +// sprite2->runAction( +// RepeatForever::create( +// Sequence::createWithTwoActions( +// move, move->reverse()) +// ) +// ); +// +// auto camera = Camera::create(); +// camera->setCameraFlag(CameraFlag::USER1); +// camera->setDepth(-1); +// camera->setFrameBufferObject(fbo); +// fbo->setClearColor(Color4F(1,1,1,1)); +// addChild(camera); +// } -BackgroundColorBrushTest::~BackgroundColorBrushTest() -{ -} +BackgroundColorBrushTest::BackgroundColorBrushTest() {} + +BackgroundColorBrushTest::~BackgroundColorBrushTest() {} std::string BackgroundColorBrushTest::title() const { @@ -1505,18 +1487,18 @@ std::string BackgroundColorBrushTest::subtitle() const void BackgroundColorBrushTest::onEnter() { CameraBaseTest::onEnter(); - + auto s = Director::getInstance()->getWinSize(); - + { // 1st Camera - auto camera = Camera::createPerspective(60.0f, (float)s.width/s.height, 1.0f, 1000.0f); + auto camera = Camera::createPerspective(60.0f, (float)s.width / s.height, 1.0f, 1000.0f); camera->setPosition3D(Vec3(0.0f, 0.0f, 200.0f)); camera->lookAt(Vec3::ZERO); camera->setDepth(-2); camera->setCameraFlag(CameraFlag::USER1); addChild(camera); - + // 3D model auto model = Sprite3D::create("Sprite3DTest/boss1.obj"); model->setScale(4); @@ -1526,15 +1508,15 @@ void BackgroundColorBrushTest::onEnter() addChild(model); model->runAction(RepeatForever::create(RotateBy::create(1.f, Vec3(10.0f, 20.0f, 30.0f)))); } - + { auto base = Node::create(); base->setContentSize(s); base->setCameraMask(static_cast(CameraFlag::USER2)); addChild(base); - + // 2nd Camera - auto camera = Camera::createPerspective(60, (float)s.width/s.height, 1, 1000); + auto camera = Camera::createPerspective(60, (float)s.width / s.height, 1, 1000); auto colorBrush = CameraBackgroundBrush::createColorBrush(Color4F(.1f, .1f, 1.f, .5f), 1.f); camera->setBackgroundBrush(colorBrush); camera->setPosition3D(Vec3(0.0f, 0.0f, 200.0f)); @@ -1542,19 +1524,19 @@ void BackgroundColorBrushTest::onEnter() camera->setDepth(-1); camera->setCameraFlag(CameraFlag::USER2); base->addChild(camera); - + // for alpha setting auto slider = ui::Slider::create(); slider->loadBarTexture("cocosui/sliderTrack.png"); slider->loadSlidBallTextures("cocosui/sliderThumb.png", "cocosui/sliderThumb.png", ""); slider->loadProgressBarTexture("cocosui/sliderProgress.png"); - slider->setPosition(Vec2(s.width/2, s.height/4)); + slider->setPosition(Vec2(s.width / 2, s.height / 4)); slider->setPercent(50); - slider->addEventListener([slider, colorBrush](Ref*, ui::Slider::EventType){ - colorBrush->setColor(Color4F(.1f, .1f, 1.f, (float)slider->getPercent()/100.f)); + slider->addEventListener([slider, colorBrush](Ref*, ui::Slider::EventType) { + colorBrush->setColor(Color4F(.1f, .1f, 1.f, (float)slider->getPercent() / 100.f)); }); addChild(slider); - + // 3D model for 2nd camera auto model = Sprite3D::create("Sprite3DTest/boss1.obj"); model->setScale(4); diff --git a/tests/cpp-tests/Classes/Camera3DTest/Camera3DTest.h b/tests/cpp-tests/Classes/Camera3DTest/Camera3DTest.h index 75b4e244dbf6..f15d82be427a 100644 --- a/tests/cpp-tests/Classes/Camera3DTest/Camera3DTest.h +++ b/tests/cpp-tests/Classes/Camera3DTest/Camera3DTest.h @@ -33,33 +33,34 @@ THE SOFTWARE. #include -namespace cocos2d { - class Sprite3D; - class Delay; -} +namespace cocos2d +{ +class Sprite3D; +class Delay; +} // namespace cocos2d enum State { - State_None = 0, - State_Idle = 0x01, - State_Move = 0x02, - State_Rotate = 0x04, - State_Speak = 0x08, - State_MeleeAttack = 0x10, + State_None = 0, + State_Idle = 0x01, + State_Move = 0x02, + State_Rotate = 0x04, + State_Speak = 0x08, + State_MeleeAttack = 0x10, State_RemoteAttack = 0x20, - State_Attack = 0x40, + State_Attack = 0x40, }; enum class CameraType { - Free = 0, + Free = 0, FirstPerson = 1, ThirdPerson = 2, }; enum class OperateCamType { - MoveCamera=0, - RotateCamera=1, + MoveCamera = 0, + RotateCamera = 1, }; DEFINE_TEST_SUITE(Camera3DTests); @@ -67,7 +68,6 @@ DEFINE_TEST_SUITE(Camera3DTests); class CameraBaseTest : public TestCase { public: - protected: cocos2d::BillBoard* bill1; cocos2d::BillBoard* bill2; @@ -75,7 +75,8 @@ class CameraBaseTest : public TestCase cocos2d::Label* l2; }; -class CameraRotationTest : public CameraBaseTest { +class CameraRotationTest : public CameraBaseTest +{ public: CREATE_FUNC(CameraRotationTest); @@ -92,7 +93,6 @@ class CameraRotationTest : public CameraBaseTest { virtual std::string subtitle() const override; protected: - cocos2d::Node* _camControlNode; cocos2d::Node* _camNode; cocos2d::EventListenerTouchOneByOne* _lis; @@ -109,41 +109,46 @@ class Camera3DTestDemo : public CameraBaseTest virtual void onExit() override; // overrides virtual std::string title() const override; - void addNewSpriteWithCoords(cocos2d::Vec3 p,std::string fileName,bool playAnimation=false,float scale=1.0f,bool bindCamera=false); - - void onTouchesBegan(const std::vector& touches, cocos2d::Event *event); - void onTouchesMoved(const std::vector& touches, cocos2d::Event *event); - void onTouchesEnded(const std::vector& touches, cocos2d::Event *event); - - void scaleCameraCallback(cocos2d::Ref* sender,float value); - void rotateCameraCallback(cocos2d::Ref* sender,float value); - void SwitchViewCallback(cocos2d::Ref* sender,CameraType cameraType); + void addNewSpriteWithCoords(cocos2d::Vec3 p, + std::string fileName, + bool playAnimation = false, + float scale = 1.0f, + bool bindCamera = false); + + void onTouchesBegan(const std::vector& touches, cocos2d::Event* event); + void onTouchesMoved(const std::vector& touches, cocos2d::Event* event); + void onTouchesEnded(const std::vector& touches, cocos2d::Event* event); + + void scaleCameraCallback(cocos2d::Ref* sender, float value); + void rotateCameraCallback(cocos2d::Ref* sender, float value); + void SwitchViewCallback(cocos2d::Ref* sender, CameraType cameraType); void updateCamera(float fDelta); void move3D(float elapsedTime); void updateState(float elapsedTime); - bool isState(unsigned int state,unsigned int bit) const; + bool isState(unsigned int state, unsigned int bit) const; void reachEndCallBack(); - + bool onTouchesCommon(cocos2d::Touch* touch, cocos2d::Event* event, bool* touchProperty); bool onTouchesZoomOut(cocos2d::Touch* touch, cocos2d::Event* event); void onTouchesZoomOutEnd(cocos2d::Touch* touch, cocos2d::Event* event); bool onTouchesZoomIn(cocos2d::Touch* touch, cocos2d::Event* event); void onTouchesZoomInEnd(cocos2d::Touch* touch, cocos2d::Event* event); - + bool onTouchesRotateLeft(cocos2d::Touch* touch, cocos2d::Event* event); void onTouchesRotateLeftEnd(cocos2d::Touch* touch, cocos2d::Event* event); bool onTouchesRotateRight(cocos2d::Touch* touch, cocos2d::Event* event); void onTouchesRotateRightEnd(cocos2d::Touch* touch, cocos2d::Event* event); + protected: - std::string _title; - cocos2d::Layer* _layer3D; - cocos2d::Sprite3D* _sprite3D; - cocos2d::Vec3 _targetPos; - CameraType _cameraType; - cocos2d::MenuItem* _incRot; - cocos2d::MenuItem* _decRot; - unsigned int _curState; - cocos2d::Camera* _camera; + std::string _title; + cocos2d::Layer* _layer3D; + cocos2d::Sprite3D* _sprite3D; + cocos2d::Vec3 _targetPos; + CameraType _cameraType; + cocos2d::MenuItem* _incRot; + cocos2d::MenuItem* _decRot; + unsigned int _curState; + cocos2d::Camera* _camera; cocos2d::MoveTo* _moveAction; bool _bZoomOut; bool _bZoomIn; @@ -161,12 +166,12 @@ class CameraCullingDemo : public CameraBaseTest CREATE_FUNC(CameraCullingDemo); CameraCullingDemo(); virtual ~CameraCullingDemo(); - + virtual void onEnter() override; virtual void onExit() override; - + virtual void update(float dt) override; - + // overrides virtual std::string title() const override; void reachEndCallBack(); @@ -175,18 +180,18 @@ class CameraCullingDemo : public CameraBaseTest void delSpriteCallback(cocos2d::Ref* sender); void drawCameraFrustum(); - + protected: - cocos2d::Label* _labelSprite3DCount; - cocos2d::Layer* _layer3D; - std::vector _objects; - CameraType _cameraType; - cocos2d::Camera* _cameraFirst; - cocos2d::Camera* _cameraThird; - cocos2d::MoveBy* _moveAction; - cocos2d::DrawNode3D* _drawAABB; - cocos2d::DrawNode3D* _drawFrustum; - int _row; + cocos2d::Label* _labelSprite3DCount; + cocos2d::Layer* _layer3D; + std::vector _objects; + CameraType _cameraType; + cocos2d::Camera* _cameraFirst; + cocos2d::Camera* _cameraThird; + cocos2d::MoveBy* _moveAction; + cocos2d::DrawNode3D* _drawAABB; + cocos2d::DrawNode3D* _drawFrustum; + int _row; }; class CameraArcBallDemo : public CameraBaseTest @@ -195,35 +200,40 @@ class CameraArcBallDemo : public CameraBaseTest CREATE_FUNC(CameraArcBallDemo); CameraArcBallDemo(); virtual ~CameraArcBallDemo(); - + virtual void onEnter() override; virtual void onExit() override; - + virtual void update(float dt) override; - + // overrides virtual std::string title() const override; void switchOperateCallback(cocos2d::Ref* sender); void switchTargetCallback(cocos2d::Ref* sender); - void onTouchsMoved(const std::vector &touchs, cocos2d::Event *event); + void onTouchsMoved(const std::vector& touchs, cocos2d::Event* event); void updateCameraTransform(); - void calculateArcBall( cocos2d::Vec3 & axis, float & angle, float p1x, float p1y, float p2x, float p2y );//calculate rotation quaternion parameters - float projectToSphere( float r, float x, float y );//points on the screen project to arc ball + void calculateArcBall(cocos2d::Vec3& axis, + float& angle, + float p1x, + float p1y, + float p2x, + float p2y); // calculate rotation quaternion parameters + float projectToSphere(float r, float x, float y); // points on the screen project to arc ball protected: - cocos2d::Layer* _layer3D; - CameraType _cameraType; - cocos2d::Camera* _camera; - cocos2d::DrawNode3D* _drawGrid; - cocos2d::Quaternion _rotationQuat; //rotation Quaternion - float _radius; //arc ball radius - float _distanceZ; - OperateCamType _operate; //switch rotate or zoom - cocos2d::Vec3 _center; //camera look target - int _target; //switch camera look target - cocos2d::Sprite3D* _sprite3D1; - cocos2d::Sprite3D* _sprite3D2; + cocos2d::Layer* _layer3D; + CameraType _cameraType; + cocos2d::Camera* _camera; + cocos2d::DrawNode3D* _drawGrid; + cocos2d::Quaternion _rotationQuat; // rotation Quaternion + float _radius; // arc ball radius + float _distanceZ; + OperateCamType _operate; // switch rotate or zoom + cocos2d::Vec3 _center; // camera look target + int _target; // switch camera look target + cocos2d::Sprite3D* _sprite3D1; + cocos2d::Sprite3D* _sprite3D2; }; class FogTestDemo : public CameraBaseTest @@ -232,44 +242,44 @@ class FogTestDemo : public CameraBaseTest CREATE_FUNC(FogTestDemo); FogTestDemo(); virtual ~FogTestDemo(); - + virtual void onEnter() override; virtual void onExit() override; - + virtual void update(float dt) override; - + // overrides virtual std::string title() const override; - void onTouchesMoved(const std::vector& touches, cocos2d::Event *event); + void onTouchesMoved(const std::vector& touches, cocos2d::Event* event); + + void switchTypeCallback(cocos2d::Ref* sender, int type); - void switchTypeCallback(cocos2d::Ref* sender,int type); - protected: - CameraType _cameraType = CameraType::Free; - cocos2d::Layer* _layer3D = nullptr; - cocos2d::Camera* _camera = nullptr; - cocos2d::Sprite3D* _sprite3D1 = nullptr; - cocos2d::Sprite3D* _sprite3D2 = nullptr; - cocos2d::backend::ProgramState* _programState1 = nullptr; - cocos2d::backend::ProgramState* _programState2 = nullptr; + CameraType _cameraType = CameraType::Free; + cocos2d::Layer* _layer3D = nullptr; + cocos2d::Camera* _camera = nullptr; + cocos2d::Sprite3D* _sprite3D1 = nullptr; + cocos2d::Sprite3D* _sprite3D2 = nullptr; + cocos2d::backend::ProgramState* _programState1 = nullptr; + cocos2d::backend::ProgramState* _programState2 = nullptr; #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) cocos2d::EventListenerCustom* _backToForegroundListener; #endif }; -//class CameraFrameBufferTest : public CameraBaseTest +// class CameraFrameBufferTest : public CameraBaseTest //{ -//public: -// CREATE_FUNC(CameraFrameBufferTest); -// CameraFrameBufferTest(); -// virtual ~CameraFrameBufferTest(); -// // overrides -// virtual std::string title() const override; -// -// virtual void onEnter() override; -//}; +// public: +// CREATE_FUNC(CameraFrameBufferTest); +// CameraFrameBufferTest(); +// virtual ~CameraFrameBufferTest(); +// // overrides +// virtual std::string title() const override; +// +// virtual void onEnter() override; +// }; class BackgroundColorBrushTest : public CameraBaseTest { @@ -277,11 +287,10 @@ class BackgroundColorBrushTest : public CameraBaseTest CREATE_FUNC(BackgroundColorBrushTest); BackgroundColorBrushTest(); virtual ~BackgroundColorBrushTest(); - + // overrides virtual std::string title() const override; virtual std::string subtitle() const override; - + virtual void onEnter() override; }; - diff --git a/tests/cpp-tests/Classes/ChipmunkTest/ChipmunkTest.cpp b/tests/cpp-tests/Classes/ChipmunkTest/ChipmunkTest.cpp index 5e140b8fb87b..fed2238abd58 100644 --- a/tests/cpp-tests/Classes/ChipmunkTest/ChipmunkTest.cpp +++ b/tests/cpp-tests/Classes/ChipmunkTest/ChipmunkTest.cpp @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. Copyright (c) 2021 @aismann; Peter Eismann, Germany; dreifrankensoft - + 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 @@ -33,32 +33,33 @@ #include "ChipmunkTest.h" - USING_NS_CC; USING_NS_CC_EXT; -enum { +enum +{ kTagParentNode = 1, }; -enum { +enum +{ Z_PHYSICS_DEBUG = 100, }; // callback to remove Shapes from the Space ChipmunkTest::ChipmunkTest() -{ +{ // enable events - auto touchListener = EventListenerTouchAllAtOnce::create(); + auto touchListener = EventListenerTouchAllAtOnce::create(); touchListener->onTouchesEnded = CC_CALLBACK_2(ChipmunkTest::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); - + Device::setAccelerometerEnabled(true); auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(ChipmunkTest::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(accListener, this); - + // title auto label = Label::createWithTTF("Multi touch the screen", "fonts/Marker Felt.ttf", 36.0f); label->setPosition(VisibleRect::center().x, VisibleRect::top().y - 30); @@ -74,16 +75,16 @@ ChipmunkTest::ChipmunkTest() #if 1 // Use batch node. Faster - auto parent = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); + auto parent = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); _spriteTexture = parent->getTexture(); #else // doesn't use batch node. Slower _spriteTexture = Director::getInstance()->getTextureCache()->addImage("Images/grossini_dance_atlas.png"); - auto parent = Node::create(); + auto parent = Node::create(); #endif addChild(parent, 0, kTagParentNode); - addNewSpriteAtPosition(cocos2d::Vec2(200.0f,200.0f)); + addNewSpriteAtPosition(cocos2d::Vec2(200.0f, 200.0f)); // menu for debug layer MenuItemFont::setFontSize(18); @@ -91,29 +92,28 @@ ChipmunkTest::ChipmunkTest() auto menu = Menu::create(item, nullptr); this->addChild(menu); - menu->setPosition(VisibleRect::right().x-100, VisibleRect::top().y-60); - + menu->setPosition(VisibleRect::right().x - 100, VisibleRect::top().y - 60); scheduleUpdate(); - } void ChipmunkTest::toggleDebugCallback(Ref* sender) { - _debugLayer->setVisible(! _debugLayer->isVisible()); + _debugLayer->setVisible(!_debugLayer->isVisible()); } ChipmunkTest::~ChipmunkTest() { // manually Free rogue shapes - for( int i=0;i<4;i++) { - cpShapeFree( _walls[i] ); + for (int i = 0; i < 4; i++) + { + cpShapeFree(_walls[i]); } #if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 - cpSpaceFree(_space); + cpSpaceFree(_space); #else - cpHastySpaceFree(_space); + cpHastySpaceFree(_space); #endif Device::setAccelerometerEnabled(false); @@ -123,13 +123,13 @@ void ChipmunkTest::initPhysics() { // init chipmunk - //cpInitChipmunk(); + // cpInitChipmunk(); #if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 - _space = cpSpaceNew(); + _space = cpSpaceNew(); #else - _space = cpHastySpaceNew(); - cpHastySpaceSetThreads(_space, 0); + _space = cpHastySpaceNew(); + cpHastySpaceSetThreads(_space, 0); #endif cpSpaceSetGravity(_space, cpv(0.0f, -100.0f)); @@ -139,27 +139,27 @@ void ChipmunkTest::initPhysics() // We have to free them manually // // bottom - _walls[0] = cpSegmentShapeNew( cpSpaceGetStaticBody(_space), - cpv(VisibleRect::leftBottom().x,VisibleRect::leftBottom().y), - cpv(VisibleRect::rightBottom().x, VisibleRect::rightBottom().y), 0.0f); + _walls[0] = + cpSegmentShapeNew(cpSpaceGetStaticBody(_space), cpv(VisibleRect::leftBottom().x, VisibleRect::leftBottom().y), + cpv(VisibleRect::rightBottom().x, VisibleRect::rightBottom().y), 0.0f); // top - _walls[1] = cpSegmentShapeNew( cpSpaceGetStaticBody(_space), - cpv(VisibleRect::leftTop().x, VisibleRect::leftTop().y), - cpv(VisibleRect::rightTop().x, VisibleRect::rightTop().y), 0.0f); + _walls[1] = cpSegmentShapeNew(cpSpaceGetStaticBody(_space), cpv(VisibleRect::leftTop().x, VisibleRect::leftTop().y), + cpv(VisibleRect::rightTop().x, VisibleRect::rightTop().y), 0.0f); // left - _walls[2] = cpSegmentShapeNew( cpSpaceGetStaticBody(_space), - cpv(VisibleRect::leftBottom().x,VisibleRect::leftBottom().y), - cpv(VisibleRect::leftTop().x,VisibleRect::leftTop().y), 0.0f); + _walls[2] = + cpSegmentShapeNew(cpSpaceGetStaticBody(_space), cpv(VisibleRect::leftBottom().x, VisibleRect::leftBottom().y), + cpv(VisibleRect::leftTop().x, VisibleRect::leftTop().y), 0.0f); // right - _walls[3] = cpSegmentShapeNew( cpSpaceGetStaticBody(_space), - cpv(VisibleRect::rightBottom().x, VisibleRect::rightBottom().y), - cpv(VisibleRect::rightTop().x, VisibleRect::rightTop().y), 0.0f); + _walls[3] = + cpSegmentShapeNew(cpSpaceGetStaticBody(_space), cpv(VisibleRect::rightBottom().x, VisibleRect::rightBottom().y), + cpv(VisibleRect::rightTop().x, VisibleRect::rightTop().y), 0.0f); + + for (int i = 0; i < 4; i++) + { - for( int i=0;i<4;i++) { - cpShapeSetElasticity(_walls[i], 1.0f); cpShapeSetFriction(_walls[i], 1.0f); cpSpaceAddShape(_space, _walls[i]); @@ -168,21 +168,21 @@ void ChipmunkTest::initPhysics() // Physics debug layer _debugLayer = PhysicsDebugNodeChipmunk2D::create(_space); this->addChild(_debugLayer, Z_PHYSICS_DEBUG); - } void ChipmunkTest::update(float delta) { // Should use a fixed size step based on the animation interval. int steps = 2; - float dt = Director::getInstance()->getAnimationInterval()/(float)steps; + float dt = Director::getInstance()->getAnimationInterval() / (float)steps; - for(int i=0; isetCPBody(body); sprite->setPosition(pos); - } void ChipmunkTest::onEnter() @@ -248,30 +246,30 @@ void ChipmunkTest::onEnter() void ChipmunkTest::onTouchesEnded(const std::vector& touches, Event* event) { - //Add a new body/atlas sprite at the touched location + // Add a new body/atlas sprite at the touched location - for( auto &touch: touches) + for (auto& touch : touches) { auto location = touch->getLocation(); - addNewSpriteAtPosition( location ); + addNewSpriteAtPosition(location); } } void ChipmunkTest::onAcceleration(Acceleration* acc, Event* event) { - static float prevX=0, prevY=0; + static float prevX = 0, prevY = 0; #define kFilterFactor 0.05f - float accelX = (float) acc->x * kFilterFactor + (1- kFilterFactor)*prevX; - float accelY = (float) acc->y * kFilterFactor + (1- kFilterFactor)*prevY; + float accelX = (float)acc->x * kFilterFactor + (1 - kFilterFactor) * prevX; + float accelY = (float)acc->y * kFilterFactor + (1 - kFilterFactor) * prevY; prevX = accelX; prevY = accelY; - auto v = cocos2d::Vec2( accelX, accelY); - v = v * 200; + auto v = cocos2d::Vec2(accelX, accelY); + v = v * 200; cpSpaceSetGravity(_space, cpv(v.x, v.y)); } @@ -279,4 +277,3 @@ ChipmunkTests::ChipmunkTests() { ADD_TEST_CASE(ChipmunkTest); } - diff --git a/tests/cpp-tests/Classes/ChipmunkTest/ChipmunkTest.h b/tests/cpp-tests/Classes/ChipmunkTest/ChipmunkTest.h index b8d4bdea98df..9cc7c87ff21f 100644 --- a/tests/cpp-tests/Classes/ChipmunkTest/ChipmunkTest.h +++ b/tests/cpp-tests/Classes/ChipmunkTest/ChipmunkTest.h @@ -3,17 +3,17 @@ Copyright (c) 2021 @aismann; Peter Eismann, Germany; dreifrankensoft 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 @@ -53,10 +53,10 @@ class ChipmunkTest : public TestCase virtual void onAcceleration(cocos2d::Acceleration* acc, cocos2d::Event* event); private: - cocos2d::Texture2D* _spriteTexture; // weak ref - cocos2d::extension::PhysicsDebugNodeChipmunk2D* _debugLayer; // weak ref + cocos2d::Texture2D* _spriteTexture; // weak ref + cocos2d::extension::PhysicsDebugNodeChipmunk2D* _debugLayer; // weak ref - cpSpace* _space; // strong ref + cpSpace* _space; // strong ref cpShape* _walls[4]; }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/ChipmunkTestBed.cpp b/tests/cpp-tests/Classes/ChipmunkTestBed/ChipmunkTestBed.cpp index cbab6df3ee6a..f40ab497cad1 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/ChipmunkTestBed.cpp +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/ChipmunkTestBed.cpp @@ -20,7 +20,6 @@ THE SOFTWARE. ****************************************************************************/ - #include #include #include @@ -32,20 +31,20 @@ #include "ChipmunkTestBed.h" - USING_NS_CC; USING_NS_CC_EXT; -enum { - kTagParentNode = 1, +enum +{ + kTagParentNode = 1, }; -enum { - Z_PHYSICS_DEBUG = 100, +enum +{ + Z_PHYSICS_DEBUG = 100, }; - -extern ChipmunkDemo Example; // Use as template for new Chipmunk2D demos +extern ChipmunkDemo Example; // Use as template for new Chipmunk2D demos extern ChipmunkDemo LogoSmash; extern ChipmunkDemo PyramidStack; extern ChipmunkDemo Plink; @@ -73,391 +72,431 @@ extern ChipmunkDemo bench_list[]; extern int bench_count; int bench = 16; - -static Vec2 cpVert2Point(const cpVect& vert) { - return Vec2(vert.x, vert.y) + physicsDebugNodeOffset; +static Vec2 cpVert2Point(const cpVect& vert) +{ + return Vec2(vert.x, vert.y) + physicsDebugNodeOffset; } -ChipmunkDemo demos[] = { LogoSmash, PyramidStack, Plink, Tumble, PyramidTopple, Planet, Springies, Pump, TheoJansen, - Query, OneWay, Joints, Tank, Chains, Crane, ContactGraph, Buoyancy, PlatformerPlayer, Slice, Convex, Unicycle, - Sticky, Shatter }; +ChipmunkDemo demos[] = {LogoSmash, PyramidStack, Plink, Tumble, PyramidTopple, Planet, + Springies, Pump, TheoJansen, Query, OneWay, Joints, + Tank, Chains, Crane, ContactGraph, Buoyancy, PlatformerPlayer, + Slice, Convex, Unicycle, Sticky, Shatter}; int demo_count = sizeof(demos); cpVect ChipmunkDemoMouse; cpVect ChipmunkDemoKeyboard; cpBool ChipmunkDemoRightClick = cpFalse; -cpBool ChipmunkDemoRightDown = cpFalse; -cpBool ChipmunkDemoLeftDown = cpFalse; +cpBool ChipmunkDemoRightDown = cpFalse; +cpBool ChipmunkDemoLeftDown = cpFalse; double ChipmunkDemoTime; -cpBody* mouse_body = cpBodyNewKinematic(); +cpBody* mouse_body = cpBodyNewKinematic(); cpConstraint* mouse_joint = NULL; char const* ChipmunkDemoMessageString = NULL; #define GRABBABLE_MASK_BIT (1 << 31) -cpShapeFilter GRAB_FILTER = { CP_NO_GROUP, (unsigned int)GRABBABLE_MASK_BIT, (unsigned int)GRABBABLE_MASK_BIT }; -cpShapeFilter NOT_GRABBABLE_FILTER = { CP_NO_GROUP, ~GRABBABLE_MASK_BIT, ~GRABBABLE_MASK_BIT }; - +cpShapeFilter GRAB_FILTER = {CP_NO_GROUP, (unsigned int)GRABBABLE_MASK_BIT, (unsigned int)GRABBABLE_MASK_BIT}; +cpShapeFilter NOT_GRABBABLE_FILTER = {CP_NO_GROUP, ~GRABBABLE_MASK_BIT, ~GRABBABLE_MASK_BIT}; cocos2d::DrawNode* drawCP = NULL; -void ChipmunkDemoDefaultDrawImpl(cpSpace* space) {}; +void ChipmunkDemoDefaultDrawImpl(cpSpace* space){}; -void ChipmunkDebugDrawDot(cpFloat size, cpVect pos, cpSpaceDebugColor fillColor) { +void ChipmunkDebugDrawDot(cpFloat size, cpVect pos, cpSpaceDebugColor fillColor) +{ -drawCP->drawPoint(Vec2(pos.x, pos.y) + physicsDebugNodeOffset, size, Color4F(fillColor.r, fillColor.g, fillColor.b, fillColor.a)); + drawCP->drawPoint(Vec2(pos.x, pos.y) + physicsDebugNodeOffset, size, + Color4F(fillColor.r, fillColor.g, fillColor.b, fillColor.a)); } -void ChipmunkDebugDrawCircle(cpVect pos, cpFloat angle, cpFloat radius, cpSpaceDebugColor outlineColor, cpSpaceDebugColor fillColor) { +void ChipmunkDebugDrawCircle(cpVect pos, + cpFloat angle, + cpFloat radius, + cpSpaceDebugColor outlineColor, + cpSpaceDebugColor fillColor) +{ - drawCP->drawCircle(Vec2(pos.x, pos.y) + physicsDebugNodeOffset, 100, CC_DEGREES_TO_RADIANS(90), 50, true, 1.0f, - 2.0f, Color4F(fillColor.r, fillColor.g, fillColor.b, fillColor.a)); + drawCP->drawCircle(Vec2(pos.x, pos.y) + physicsDebugNodeOffset, 100, CC_DEGREES_TO_RADIANS(90), 50, true, 1.0f, + 2.0f, Color4F(fillColor.r, fillColor.g, fillColor.b, fillColor.a)); } -void ChipmunkDebugDrawSegment(cpVect a, cpVect b, cpSpaceDebugColor color) { - drawCP->drawLine(Vec2(a.x, a.y) + physicsDebugNodeOffset, Vec2(b.x, b.y) + physicsDebugNodeOffset, - Color4F(color.r, color.g, color.b, color.a)); +void ChipmunkDebugDrawSegment(cpVect a, cpVect b, cpSpaceDebugColor color) +{ + drawCP->drawLine(Vec2(a.x, a.y) + physicsDebugNodeOffset, Vec2(b.x, b.y) + physicsDebugNodeOffset, + Color4F(color.r, color.g, color.b, color.a)); } -void ChipmunkDebugDrawFatSegment(cpVect a, cpVect b, cpFloat radius, cpSpaceDebugColor outlineColor, cpSpaceDebugColor fillColor) { +void ChipmunkDebugDrawFatSegment(cpVect a, + cpVect b, + cpFloat radius, + cpSpaceDebugColor outlineColor, + cpSpaceDebugColor fillColor) +{ - drawCP->drawSegment(Vec2(a.x, a.y) + physicsDebugNodeOffset, Vec2(b.x, b.y) + physicsDebugNodeOffset, radius, - Color4F(outlineColor.r, outlineColor.g, outlineColor.b, outlineColor.a)); + drawCP->drawSegment(Vec2(a.x, a.y) + physicsDebugNodeOffset, Vec2(b.x, b.y) + physicsDebugNodeOffset, radius, + Color4F(outlineColor.r, outlineColor.g, outlineColor.b, outlineColor.a)); } +void ChipmunkDebugDrawPolygon(int count, + const cpVect* verts, + cpFloat radius, + cpSpaceDebugColor outlineColor, + cpSpaceDebugColor fillColor) +{ -void ChipmunkDebugDrawPolygon(int count, const cpVect* verts, cpFloat radius, cpSpaceDebugColor outlineColor, cpSpaceDebugColor fillColor) { - - Vec2* vec = new Vec2[count]; - for (size_t i = 0; i < count; i++) { - vec[i] = cpVert2Point(verts[i]); - } - drawCP->drawPolygon(vec, count, Color4F(1.0f, 0.0f, 0.0f, 0.5f), radius, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); + Vec2* vec = new Vec2[count]; + for (size_t i = 0; i < count; i++) + { + vec[i] = cpVert2Point(verts[i]); + } + drawCP->drawPolygon(vec, count, Color4F(1.0f, 0.0f, 0.0f, 0.5f), radius, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); - delete[] vec; + delete[] vec; } -void ChipmunkDebugDrawBB(cpBB bb, cpSpaceDebugColor color) { - Vec2 verts[] = { - Vec2(bb.r, bb.b) + physicsDebugNodeOffset, - Vec2(bb.r, bb.t) + physicsDebugNodeOffset, - Vec2(bb.l, bb.t) + physicsDebugNodeOffset, - Vec2(bb.l, bb.b) + physicsDebugNodeOffset, - }; - drawCP->drawPolygon(verts, sizeof(verts) / sizeof(verts[0]), Color4F(1.0f, 0.0f, 0.0f, 0.0f), 1, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); +void ChipmunkDebugDrawBB(cpBB bb, cpSpaceDebugColor color) +{ + Vec2 verts[] = { + Vec2(bb.r, bb.b) + physicsDebugNodeOffset, + Vec2(bb.r, bb.t) + physicsDebugNodeOffset, + Vec2(bb.l, bb.t) + physicsDebugNodeOffset, + Vec2(bb.l, bb.b) + physicsDebugNodeOffset, + }; + drawCP->drawPolygon(verts, sizeof(verts) / sizeof(verts[0]), Color4F(1.0f, 0.0f, 0.0f, 0.0f), 1, + Color4F(0.0f, 0.0f, 1.0f, 1.0f)); } - cocos2d::Label* label; - -static int max_arbiters = 0; -static int max_points = 0; +static int max_arbiters = 0; +static int max_points = 0; static int max_constraints = 0; -void ChipmunkTestBed::DrawInfo() { - int arbiters = _space->arbiters->num; - int points = 0; +void ChipmunkTestBed::DrawInfo() +{ + int arbiters = _space->arbiters->num; + int points = 0; - for (int i = 0; i < arbiters; i++) - points += ((cpArbiter*)(_space->arbiters->arr[i]))->count; + for (int i = 0; i < arbiters; i++) + points += ((cpArbiter*)(_space->arbiters->arr[i]))->count; - int constraints = (_space->constraints->num + points) * _space->iterations; + int constraints = (_space->constraints->num + points) * _space->iterations; - max_arbiters = arbiters > max_arbiters ? arbiters : max_arbiters; - max_points = points > max_points ? points : max_points; - max_constraints = constraints > max_constraints ? constraints : max_constraints; + max_arbiters = arbiters > max_arbiters ? arbiters : max_arbiters; + max_points = points > max_points ? points : max_points; + max_constraints = constraints > max_constraints ? constraints : max_constraints; - char buffer[1024]; - const char* format = "Arbiters: %d (%d) - " - "Contact Points: %d (%d)\n" - "Other Constraints: %d, Iterations: %d\n" - "Constraints x Iterations: %d (%d)\n" - "Time:% 5.2fs, KE:% 5.2e"; + char buffer[1024]; + const char* format = + "Arbiters: %d (%d) - " + "Contact Points: %d (%d)\n" + "Other Constraints: %d, Iterations: %d\n" + "Constraints x Iterations: %d (%d)\n" + "Time:% 5.2fs, KE:% 5.2e"; - cpArray* bodies = _space->dynamicBodies; - cpFloat ke = 0.0f; - for (int i = 0; i < bodies->num; i++) { - cpBody* body = (cpBody*)bodies->arr[i]; - if (body->m == INFINITY || body->i == INFINITY) - continue; + cpArray* bodies = _space->dynamicBodies; + cpFloat ke = 0.0f; + for (int i = 0; i < bodies->num; i++) + { + cpBody* body = (cpBody*)bodies->arr[i]; + if (body->m == INFINITY || body->i == INFINITY) + continue; - ke += body->m * cpvdot(body->v, body->v) + body->i * body->w * body->w; - } + ke += body->m * cpvdot(body->v, body->v) + body->i * body->w * body->w; + } - sprintf(buffer, format, arbiters, max_arbiters, points, max_points, _space->constraints->num, _space->iterations, - constraints, max_constraints, ChipmunkDemoTime, (ke < 1e-10f ? 0.0f : ke)); + sprintf(buffer, format, arbiters, max_arbiters, points, max_points, _space->constraints->num, _space->iterations, + constraints, max_constraints, ChipmunkDemoTime, (ke < 1e-10f ? 0.0f : ke)); - drawInfo->setString(buffer); + drawInfo->setString(buffer); } - static char PrintStringBuffer[1024 * 8]; static char* PrintStringCursor; -void ChipmunkDemoPrintString(char const* fmt, ...) { - if (PrintStringCursor == NULL) { - return; - } - - ChipmunkDemoMessageString = PrintStringBuffer; - - va_list args; - va_start(args, fmt); - int remaining = sizeof(PrintStringBuffer) - (PrintStringCursor - PrintStringBuffer); - int would_write = vsnprintf(PrintStringCursor, remaining, fmt, args); - if (would_write > 0 && would_write < remaining) { - PrintStringCursor += would_write; - } - else { - // encoding error or overflow, prevent further use until reinitialized - PrintStringCursor = NULL; - } - va_end(args); - - label->setString(ChipmunkDemoMessageString); -} - -cpSpaceDebugColor RGBAColor(float r, float g, float b, float a) { - cpSpaceDebugColor color = { r, g, b, a }; - return color; +void ChipmunkDemoPrintString(char const* fmt, ...) +{ + if (PrintStringCursor == NULL) + { + return; + } + + ChipmunkDemoMessageString = PrintStringBuffer; + + va_list args; + va_start(args, fmt); + int remaining = sizeof(PrintStringBuffer) - (PrintStringCursor - PrintStringBuffer); + int would_write = vsnprintf(PrintStringCursor, remaining, fmt, args); + if (would_write > 0 && would_write < remaining) + { + PrintStringCursor += would_write; + } + else + { + // encoding error or overflow, prevent further use until reinitialized + PrintStringCursor = NULL; + } + va_end(args); + + label->setString(ChipmunkDemoMessageString); +} + +cpSpaceDebugColor RGBAColor(float r, float g, float b, float a) +{ + cpSpaceDebugColor color = {r, g, b, a}; + return color; }; -cpSpaceDebugColor LAColor(float l, float a) { - cpSpaceDebugColor color = { l, l, l, a }; - return color; +cpSpaceDebugColor LAColor(float l, float a) +{ + cpSpaceDebugColor color = {l, l, l, a}; + return color; } - -static void ShapeFreeWrap(cpSpace* space, cpShape* shape, void* unused) { - cpSpaceRemoveShape(space, shape); - cpShapeFree(shape); +static void ShapeFreeWrap(cpSpace* space, cpShape* shape, void* unused) +{ + cpSpaceRemoveShape(space, shape); + cpShapeFree(shape); } -static void PostShapeFree(cpShape* shape, cpSpace* space) { - cpSpaceAddPostStepCallback(space, (cpPostStepFunc)ShapeFreeWrap, shape, NULL); +static void PostShapeFree(cpShape* shape, cpSpace* space) +{ + cpSpaceAddPostStepCallback(space, (cpPostStepFunc)ShapeFreeWrap, shape, NULL); } -static void ConstraintFreeWrap(cpSpace* space, cpConstraint* constraint, void* unused) { - cpSpaceRemoveConstraint(space, constraint); - cpConstraintFree(constraint); +static void ConstraintFreeWrap(cpSpace* space, cpConstraint* constraint, void* unused) +{ + cpSpaceRemoveConstraint(space, constraint); + cpConstraintFree(constraint); } -static void PostConstraintFree(cpConstraint* constraint, cpSpace* space) { - cpSpaceAddPostStepCallback(space, (cpPostStepFunc)ConstraintFreeWrap, constraint, NULL); +static void PostConstraintFree(cpConstraint* constraint, cpSpace* space) +{ + cpSpaceAddPostStepCallback(space, (cpPostStepFunc)ConstraintFreeWrap, constraint, NULL); } -static void BodyFreeWrap(cpSpace* space, cpBody* body, void* unused) { - cpSpaceRemoveBody(space, body); - cpBodyFree(body); +static void BodyFreeWrap(cpSpace* space, cpBody* body, void* unused) +{ + cpSpaceRemoveBody(space, body); + cpBodyFree(body); } -static void PostBodyFree(cpBody* body, cpSpace* space) { - cpSpaceAddPostStepCallback(space, (cpPostStepFunc)BodyFreeWrap, body, NULL); +static void PostBodyFree(cpBody* body, cpSpace* space) +{ + cpSpaceAddPostStepCallback(space, (cpPostStepFunc)BodyFreeWrap, body, NULL); } // Safe and future proof way to remove and free all objects that have been added to the space. -void ChipmunkDemoFreeSpaceChildren(cpSpace* space) { - // Must remove these BEFORE freeing the body or you will access dangling pointers. - cpSpaceEachShape(space, (cpSpaceShapeIteratorFunc)PostShapeFree, space); - cpSpaceEachConstraint(space, (cpSpaceConstraintIteratorFunc)PostConstraintFree, space); - cpSpaceEachBody(space, (cpSpaceBodyIteratorFunc)PostBodyFree, space); -} - - -void updateMouseBody(void) { - cpVect new_point = cpvlerp(mouse_body->p, ChipmunkDemoMouse, 0.25f); - mouse_body->v = cpvmult(cpvsub(new_point, mouse_body->p), 60.0f); - mouse_body->p = new_point; -} - -ChipmunkTestBed::ChipmunkTestBed() { - // halx99: since adxe init scene default camera at 'initWithXXX' function, only change design size at scene - // construct is ok see also: https://github.com/adxeproject/adxe/commit/581a7921554c09746616759d5a5ca6ce9d3eaa22 - auto director = Director::getInstance(); - auto glview = director->getOpenGLView(); - Size designSize(960 * 0.85, 640 * 0.85); - glview->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::NO_BORDER); - - // creating a keyboard event listener - auto listener = EventListenerKeyboard::create(); - listener->onKeyPressed = [](EventKeyboard::KeyCode keyCode, Event* event) { - if ((int)keyCode == 26) // Left - { - ChipmunkDemoKeyboard.x--; - } - if ((int)keyCode == 27) // Right - { - ChipmunkDemoKeyboard.x++; - } - if ((int)keyCode == 28) // Up - { - ChipmunkDemoKeyboard.y++; - } - if ((int)keyCode == 29) // Down - { - ChipmunkDemoKeyboard.y--; - } - }; - - listener->onKeyReleased = [](EventKeyboard::KeyCode keyCode, Event* event) - { - ChipmunkDemoKeyboard = { 0, 0 }; - }; - - _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - - // creating a mouse event listener - _mouseListener = EventListenerMouse::create(); - _mouseListener->onMouseMove = CC_CALLBACK_1(ChipmunkTestBed::onMouseMove, this); - _mouseListener->onMouseUp = CC_CALLBACK_1(ChipmunkTestBed::onMouseUp, this); - _mouseListener->onMouseDown = CC_CALLBACK_1(ChipmunkTestBed::onMouseDown, this); - _eventDispatcher->addEventListenerWithSceneGraphPriority(_mouseListener, this); - - // Some info text - auto label1 = Label::createWithTTF("Use the mouse to grab objects.", "fonts/Marker Felt.ttf", 12.0f); - label1->setPosition(VisibleRect::center().x, VisibleRect::top().y - 100); - label1->setColor(Color3B::WHITE); - this->addChild(label1, 1000); - - // ChipmunkDemoMessageString - label = Label::createWithTTF("", "fonts/Marker Felt.ttf", 12.0f); - label->setPosition(VisibleRect::center().x, VisibleRect::top().y - 130); - label->setColor(Color3B::MAGENTA); - this->addChild(label, 1000); - - drawInfo = Label::createWithTTF("Use the mouse to grab objects.", "fonts/Marker Felt.ttf", 12.0f); - drawInfo->setAnchorPoint(Vec2(0, 0)); - drawInfo->setPosition(VisibleRect::left().x + 10, VisibleRect::top().y - 60); - drawInfo->setColor(Color3B::WHITE); - this->addChild(drawInfo, 1000); - - - draw = DrawNode::create(); - addChild(draw, 100); - - drawCP = draw; - - scheduleUpdate(); -} - - -ChipmunkTestBed::~ChipmunkTestBed() +void ChipmunkDemoFreeSpaceChildren(cpSpace* space) { - ChipmunkDemoFreeSpaceChildren(_space); - _eventDispatcher->removeEventListener(_mouseListener); + // Must remove these BEFORE freeing the body or you will access dangling pointers. + cpSpaceEachShape(space, (cpSpaceShapeIteratorFunc)PostShapeFree, space); + cpSpaceEachConstraint(space, (cpSpaceConstraintIteratorFunc)PostConstraintFree, space); + cpSpaceEachBody(space, (cpSpaceBodyIteratorFunc)PostBodyFree, space); } - -void ChipmunkTestBed::initPhysics() { - if (ChipmunkDemoMessageString) { - label->setString(ChipmunkDemoMessageString); - } - else { - label->setString(""); - } - drawCP->clear(); - // Physics debug layer - _debugLayer = PhysicsDebugNodeChipmunk2D::create(_space); - this->addChild(_debugLayer, Z_PHYSICS_DEBUG); +void updateMouseBody(void) +{ + cpVect new_point = cpvlerp(mouse_body->p, ChipmunkDemoMouse, 0.25f); + mouse_body->v = cpvmult(cpvsub(new_point, mouse_body->p), 60.0f); + mouse_body->p = new_point; } -void ChipmunkTestBed::update(float delta) { - //#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 - // cpSpaceStep(_space, delta); - //#else - // cpHastySpaceStep(_space, delta); - //#endif +ChipmunkTestBed::ChipmunkTestBed() +{ + // halx99: since adxe init scene default camera at 'initWithXXX' function, only change design size at scene + // construct is ok see also: https://github.com/adxeproject/adxe/commit/581a7921554c09746616759d5a5ca6ce9d3eaa22 + auto director = Director::getInstance(); + auto glview = director->getOpenGLView(); + Size designSize(960 * 0.85, 640 * 0.85); + glview->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::NO_BORDER); + + // creating a keyboard event listener + auto listener = EventListenerKeyboard::create(); + listener->onKeyPressed = [](EventKeyboard::KeyCode keyCode, Event* event) { + if ((int)keyCode == 26) // Left + { + ChipmunkDemoKeyboard.x--; + } + if ((int)keyCode == 27) // Right + { + ChipmunkDemoKeyboard.x++; + } + if ((int)keyCode == 28) // Up + { + ChipmunkDemoKeyboard.y++; + } + if ((int)keyCode == 29) // Down + { + ChipmunkDemoKeyboard.y--; + } + }; + + listener->onKeyReleased = [](EventKeyboard::KeyCode keyCode, Event* event) { ChipmunkDemoKeyboard = {0, 0}; }; + + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); + + // creating a mouse event listener + _mouseListener = EventListenerMouse::create(); + _mouseListener->onMouseMove = CC_CALLBACK_1(ChipmunkTestBed::onMouseMove, this); + _mouseListener->onMouseUp = CC_CALLBACK_1(ChipmunkTestBed::onMouseUp, this); + _mouseListener->onMouseDown = CC_CALLBACK_1(ChipmunkTestBed::onMouseDown, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(_mouseListener, this); + + // Some info text + auto label1 = Label::createWithTTF("Use the mouse to grab objects.", "fonts/Marker Felt.ttf", 12.0f); + label1->setPosition(VisibleRect::center().x, VisibleRect::top().y - 100); + label1->setColor(Color3B::WHITE); + this->addChild(label1, 1000); + + // ChipmunkDemoMessageString + label = Label::createWithTTF("", "fonts/Marker Felt.ttf", 12.0f); + label->setPosition(VisibleRect::center().x, VisibleRect::top().y - 130); + label->setColor(Color3B::MAGENTA); + this->addChild(label, 1000); + + drawInfo = Label::createWithTTF("Use the mouse to grab objects.", "fonts/Marker Felt.ttf", 12.0f); + drawInfo->setAnchorPoint(Vec2(0, 0)); + drawInfo->setPosition(VisibleRect::left().x + 10, VisibleRect::top().y - 60); + drawInfo->setColor(Color3B::WHITE); + this->addChild(drawInfo, 1000); + + draw = DrawNode::create(); + addChild(draw, 100); + + drawCP = draw; + + scheduleUpdate(); } -void ChipmunkTestBed::createResetButton() { - auto reset = MenuItemImage::create("Images/r1.png", "Images/r2.png", CC_CALLBACK_1(ChipmunkTestBed::reset, this)); - auto menu = Menu::create(reset, nullptr); - menu->setPosition(VisibleRect::center().x, VisibleRect::bottom().y); - this->addChild(menu, -1); +ChipmunkTestBed::~ChipmunkTestBed() +{ + ChipmunkDemoFreeSpaceChildren(_space); + _eventDispatcher->removeEventListener(_mouseListener); } -void ChipmunkTestBed::reset(Ref* sender) { - ChipmunkDemoFreeSpaceChildren(_space); - getTestSuite()->restartCurrTest(); +void ChipmunkTestBed::initPhysics() +{ + if (ChipmunkDemoMessageString) + { + label->setString(ChipmunkDemoMessageString); + } + else + { + label->setString(""); + } + drawCP->clear(); + // Physics debug layer + _debugLayer = PhysicsDebugNodeChipmunk2D::create(_space); + this->addChild(_debugLayer, Z_PHYSICS_DEBUG); +} + +void ChipmunkTestBed::update(float delta) +{ + //#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + // cpSpaceStep(_space, delta); + //#else + // cpHastySpaceStep(_space, delta); + //#endif } -void ChipmunkTestBed::onEnter() { - TestCase::onEnter(); - physicsDebugNodeOffset = VisibleRect::center(); - physicsDebugNodeOffset.y += 20; - ChipmunkDemoMessageString = ""; - label->setString(""); +void ChipmunkTestBed::createResetButton() +{ + auto reset = MenuItemImage::create("Images/r1.png", "Images/r2.png", CC_CALLBACK_1(ChipmunkTestBed::reset, this)); + auto menu = Menu::create(reset, nullptr); + menu->setPosition(VisibleRect::center().x, VisibleRect::bottom().y); + this->addChild(menu, -1); } - -void ChipmunkTestBed::onMouseDown(Event* event) { - EventMouse* e = (EventMouse*)event; - - if ((int)e->getMouseButton() == 0) { - ChipmunkDemoLeftDown = cpTrue; - // give the mouse click a little radius to make it easier to click small shapes. - cpFloat radius = 5.0; - - cpPointQueryInfo info = { 0 }; - cpShape* shape = cpSpacePointQueryNearest(_space, ChipmunkDemoMouse, radius, GRAB_FILTER, &info); - - if (shape && cpBodyGetMass(cpShapeGetBody(shape)) < INFINITY) { - // Use the closest point on the surface if the click is outside of the shape. - cpVect nearest = (info.distance > 0.0f ? info.point : ChipmunkDemoMouse); - - cpBody* body = cpShapeGetBody(shape); - mouse_joint = cpPivotJointNew2(mouse_body, body, cpvzero, cpBodyWorldToLocal(body, nearest)); - mouse_joint->maxForce = 50000.0f; - mouse_joint->errorBias = cpfpow(1.0f - 0.15f, 60.0f); - cpSpaceAddConstraint(_space, mouse_joint); - } - } - else if ((int)e->getMouseButton() == 1) { - if (mouse_joint) { - cpSpaceRemoveConstraint(_space, mouse_joint); - cpConstraintFree(mouse_joint); - mouse_joint = NULL; - } - ChipmunkDemoRightDown = cpTrue; - ChipmunkDemoRightClick = cpTrue; - } +void ChipmunkTestBed::reset(Ref* sender) +{ + ChipmunkDemoFreeSpaceChildren(_space); + getTestSuite()->restartCurrTest(); } -void ChipmunkTestBed::onMouseUp(Event* event) { - EventMouse* e = (EventMouse*)event; - mousePresses = false; - if (mouse_joint) { - cpSpaceRemoveConstraint(_space, mouse_joint); - cpConstraintFree(mouse_joint); - mouse_joint = NULL; - } - ChipmunkDemoLeftDown = cpFalse; - ChipmunkDemoRightDown = cpFalse; - ChipmunkDemoRightClick = cpFalse; +void ChipmunkTestBed::onEnter() +{ + TestCase::onEnter(); + physicsDebugNodeOffset = VisibleRect::center(); + physicsDebugNodeOffset.y += 20; + ChipmunkDemoMessageString = ""; + label->setString(""); } -void ChipmunkTestBed::onMouseMove(Event* event) { - EventMouse* e = (EventMouse*)event; +void ChipmunkTestBed::onMouseDown(Event* event) +{ + EventMouse* e = (EventMouse*)event; + + if ((int)e->getMouseButton() == 0) + { + ChipmunkDemoLeftDown = cpTrue; + // give the mouse click a little radius to make it easier to click small shapes. + cpFloat radius = 5.0; + + cpPointQueryInfo info = {0}; + cpShape* shape = cpSpacePointQueryNearest(_space, ChipmunkDemoMouse, radius, GRAB_FILTER, &info); + + if (shape && cpBodyGetMass(cpShapeGetBody(shape)) < INFINITY) + { + // Use the closest point on the surface if the click is outside of the shape. + cpVect nearest = (info.distance > 0.0f ? info.point : ChipmunkDemoMouse); + + cpBody* body = cpShapeGetBody(shape); + mouse_joint = cpPivotJointNew2(mouse_body, body, cpvzero, cpBodyWorldToLocal(body, nearest)); + mouse_joint->maxForce = 50000.0f; + mouse_joint->errorBias = cpfpow(1.0f - 0.15f, 60.0f); + cpSpaceAddConstraint(_space, mouse_joint); + } + } + else if ((int)e->getMouseButton() == 1) + { + if (mouse_joint) + { + cpSpaceRemoveConstraint(_space, mouse_joint); + cpConstraintFree(mouse_joint); + mouse_joint = NULL; + } + ChipmunkDemoRightDown = cpTrue; + ChipmunkDemoRightClick = cpTrue; + } +} + +void ChipmunkTestBed::onMouseUp(Event* event) +{ + EventMouse* e = (EventMouse*)event; + mousePresses = false; + if (mouse_joint) + { + cpSpaceRemoveConstraint(_space, mouse_joint); + cpConstraintFree(mouse_joint); + mouse_joint = NULL; + } + ChipmunkDemoLeftDown = cpFalse; + ChipmunkDemoRightDown = cpFalse; + ChipmunkDemoRightClick = cpFalse; +} + +void ChipmunkTestBed::onMouseMove(Event* event) +{ + EventMouse* e = (EventMouse*)event; - ChipmunkDemoMouse.x = e->getCursorX() - physicsDebugNodeOffset.x; - ChipmunkDemoMouse.y = e->getCursorY() - physicsDebugNodeOffset.y; + ChipmunkDemoMouse.x = e->getCursorX() - physicsDebugNodeOffset.x; + ChipmunkDemoMouse.y = e->getCursorY() - physicsDebugNodeOffset.y; - cpBodySetPosition(mouse_body, ChipmunkDemoMouse); + cpBodySetPosition(mouse_body, ChipmunkDemoMouse); } +void ChipmunkTestBed::updateInit(ChipmunkDemo tt) +{ + PrintStringBuffer[0] = 0; + PrintStringCursor = PrintStringBuffer; -void ChipmunkTestBed::updateInit(ChipmunkDemo tt) { - PrintStringBuffer[0] = 0; - PrintStringCursor = PrintStringBuffer; - - - drawCP->clear(); - updateMouseBody(); - ChipmunkDemoTime += tt.timestep; - ChipmunkTestBed::DrawInfo(); - tt.updateFunc(_space, tt.timestep); + drawCP->clear(); + updateMouseBody(); + ChipmunkDemoTime += tt.timestep; + ChipmunkTestBed::DrawInfo(); + tt.updateFunc(_space, tt.timestep); } //------------------------------------------------------------------ @@ -465,22 +504,26 @@ void ChipmunkTestBed::updateInit(ChipmunkDemo tt) { // LogoSmashDemo // //------------------------------------------------------------------ -void LogoSmashDemo::onEnter() { - ChipmunkTestBed::onEnter(); - initPhysics(); +void LogoSmashDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); + initPhysics(); } -std::string LogoSmashDemo::title() const { - return LogoSmash.name; +std::string LogoSmashDemo::title() const +{ + return LogoSmash.name; } -void LogoSmashDemo::initPhysics() { - _space = LogoSmash.initFunc(); - ChipmunkTestBed::initPhysics(); +void LogoSmashDemo::initPhysics() +{ + _space = LogoSmash.initFunc(); + ChipmunkTestBed::initPhysics(); } -void LogoSmashDemo::update(float delta) { - ChipmunkTestBed::updateInit(LogoSmash); +void LogoSmashDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(LogoSmash); } //------------------------------------------------------------------ @@ -488,23 +531,27 @@ void LogoSmashDemo::update(float delta) { // PlinkDemo // //------------------------------------------------------------------ -void PlinkDemo::onEnter() { - ChipmunkTestBed::onEnter(); +void PlinkDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string PlinkDemo::title() const { - return Plink.name; +std::string PlinkDemo::title() const +{ + return Plink.name; } -void PlinkDemo::initPhysics() { - _space = Plink.initFunc(); - ChipmunkTestBed::initPhysics(); +void PlinkDemo::initPhysics() +{ + _space = Plink.initFunc(); + ChipmunkTestBed::initPhysics(); } -void PlinkDemo::update(float delta) { - ChipmunkTestBed::updateInit(Plink); +void PlinkDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(Plink); } //------------------------------------------------------------------ @@ -512,22 +559,26 @@ void PlinkDemo::update(float delta) { // TumbleDemo // //------------------------------------------------------------------ -void TumbleDemo::onEnter() { - ChipmunkTestBed::onEnter(); - initPhysics(); +void TumbleDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); + initPhysics(); } -std::string TumbleDemo::title() const { - return Tumble.name; +std::string TumbleDemo::title() const +{ + return Tumble.name; } -void TumbleDemo::initPhysics() { - _space = Tumble.initFunc(); - ChipmunkTestBed::initPhysics(); +void TumbleDemo::initPhysics() +{ + _space = Tumble.initFunc(); + ChipmunkTestBed::initPhysics(); } -void TumbleDemo::update(float delta) { - ChipmunkTestBed::updateInit(Tumble); +void TumbleDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(Tumble); } //------------------------------------------------------------------ @@ -535,71 +586,81 @@ void TumbleDemo::update(float delta) { // PyramidStackDemo // //------------------------------------------------------------------ -void PyramidStackDemo::onEnter() { - ChipmunkTestBed::onEnter(); - initPhysics(); +void PyramidStackDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); + initPhysics(); } -std::string PyramidStackDemo::title() const { - return PyramidStack.name; +std::string PyramidStackDemo::title() const +{ + return PyramidStack.name; } -void PyramidStackDemo::initPhysics() { - _space = PyramidStack.initFunc(); - ChipmunkTestBed::initPhysics(); +void PyramidStackDemo::initPhysics() +{ + _space = PyramidStack.initFunc(); + ChipmunkTestBed::initPhysics(); } -void PyramidStackDemo::update(float delta) { - ChipmunkTestBed::updateInit(PyramidStack); +void PyramidStackDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(PyramidStack); } - //------------------------------------------------------------------ // // PyramidToppleDemo // //------------------------------------------------------------------ -void PyramidToppleDemo::onEnter() { - ChipmunkTestBed::onEnter(); - initPhysics(); +void PyramidToppleDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); + initPhysics(); } -std::string PyramidToppleDemo::title() const { - return PyramidTopple.name; +std::string PyramidToppleDemo::title() const +{ + return PyramidTopple.name; } -void PyramidToppleDemo::initPhysics() { - _space = PyramidTopple.initFunc(); - ChipmunkTestBed::initPhysics(); +void PyramidToppleDemo::initPhysics() +{ + _space = PyramidTopple.initFunc(); + ChipmunkTestBed::initPhysics(); } -void PyramidToppleDemo::update(float delta) { - ChipmunkTestBed::updateInit(PyramidTopple); +void PyramidToppleDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(PyramidTopple); } - //------------------------------------------------------------------ // // ChainDemo // //------------------------------------------------------------------ -void ChainsDemo::onEnter() { - ChipmunkTestBed::onEnter(); +void ChainsDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string ChainsDemo::title() const { - return Chains.name; +std::string ChainsDemo::title() const +{ + return Chains.name; } -void ChainsDemo::initPhysics() { - _space = Chains.initFunc(); - ChipmunkTestBed::initPhysics(); +void ChainsDemo::initPhysics() +{ + _space = Chains.initFunc(); + ChipmunkTestBed::initPhysics(); } -void ChainsDemo::update(float delta) { - ChipmunkTestBed::updateInit(Chains); +void ChainsDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(Chains); } //------------------------------------------------------------------ @@ -607,23 +668,27 @@ void ChainsDemo::update(float delta) { // OneWayDemo // //------------------------------------------------------------------ -void OneWayDemo::onEnter() { - ChipmunkTestBed::onEnter(); +void OneWayDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string OneWayDemo::title() const { - return OneWay.name; +std::string OneWayDemo::title() const +{ + return OneWay.name; } -void OneWayDemo::initPhysics() { - _space = OneWay.initFunc(); - ChipmunkTestBed::initPhysics(); +void OneWayDemo::initPhysics() +{ + _space = OneWay.initFunc(); + ChipmunkTestBed::initPhysics(); } -void OneWayDemo::update(float delta) { - ChipmunkTestBed::updateInit(OneWay); +void OneWayDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(OneWay); } //------------------------------------------------------------------ @@ -631,23 +696,27 @@ void OneWayDemo::update(float delta) { // PlanetDemo // //------------------------------------------------------------------ -void PlanetDemo::onEnter() { - ChipmunkTestBed::onEnter(); +void PlanetDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string PlanetDemo::title() const { - return Planet.name; +std::string PlanetDemo::title() const +{ + return Planet.name; } -void PlanetDemo::initPhysics() { - _space = Planet.initFunc(); - ChipmunkTestBed::initPhysics(); +void PlanetDemo::initPhysics() +{ + _space = Planet.initFunc(); + ChipmunkTestBed::initPhysics(); } -void PlanetDemo::update(float delta) { - ChipmunkTestBed::updateInit(Planet); +void PlanetDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(Planet); } //------------------------------------------------------------------ @@ -655,153 +724,170 @@ void PlanetDemo::update(float delta) { // TheoJansenDemo // //------------------------------------------------------------------ -void TheoJansenDemo::onEnter() { - ChipmunkTestBed::onEnter(); +void TheoJansenDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string TheoJansenDemo::title() const { - return TheoJansen.name; +std::string TheoJansenDemo::title() const +{ + return TheoJansen.name; } -void TheoJansenDemo::initPhysics() { - _space = TheoJansen.initFunc(); - ChipmunkTestBed::initPhysics(); +void TheoJansenDemo::initPhysics() +{ + _space = TheoJansen.initFunc(); + ChipmunkTestBed::initPhysics(); } -void TheoJansenDemo::update(float delta) { - ChipmunkTestBed::updateInit(TheoJansen); +void TheoJansenDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(TheoJansen); } - //------------------------------------------------------------------ // // TankDemo // //------------------------------------------------------------------ -void TankDemo::onEnter() { - ChipmunkTestBed::onEnter(); +void TankDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string TankDemo::title() const { - return Tank.name; +std::string TankDemo::title() const +{ + return Tank.name; } -void TankDemo::initPhysics() { - _space = Tank.initFunc(); - ChipmunkTestBed::initPhysics(); +void TankDemo::initPhysics() +{ + _space = Tank.initFunc(); + ChipmunkTestBed::initPhysics(); } -void TankDemo::update(float delta) { - ChipmunkTestBed::updateInit(Tank); +void TankDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(Tank); } - //------------------------------------------------------------------ // // BenchDemo // //------------------------------------------------------------------ -void BenchDemo::onEnter() { - ChipmunkTestBed::onEnter(); +void BenchDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); - auto itemPrev = MenuItemImage::create("Images/b1.png", "Images/b2.png", [&](Ref* sender) { - bench = (bench > 0) ? bench - 1 : (bench_count - 1); - reset(sender); - }); + auto itemPrev = MenuItemImage::create("Images/b1.png", "Images/b2.png", [&](Ref* sender) { + bench = (bench > 0) ? bench - 1 : (bench_count - 1); + reset(sender); + }); - auto itemNext = MenuItemImage::create("Images/f1.png", "Images/f2.png", [&](Ref* sender) { - bench = (bench < (bench_count - 1)) ? bench + 1 : 0; - reset(sender); - }); + auto itemNext = MenuItemImage::create("Images/f1.png", "Images/f2.png", [&](Ref* sender) { + bench = (bench < (bench_count - 1)) ? bench + 1 : 0; + reset(sender); + }); - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); - auto menuPrev = Menu::create(itemPrev, nullptr); - menuPrev->alignItemsHorizontally(); - menuPrev->setScale(0.4); - menuPrev->setAnchorPoint(Vec2(0.0f, 0.0f)); - menuPrev->setPosition(Vec2(s.width / 2 - 45, 23.0f)); - addChild(menuPrev); + auto menuPrev = Menu::create(itemPrev, nullptr); + menuPrev->alignItemsHorizontally(); + menuPrev->setScale(0.4); + menuPrev->setAnchorPoint(Vec2(0.0f, 0.0f)); + menuPrev->setPosition(Vec2(s.width / 2 - 45, 23.0f)); + addChild(menuPrev); - auto menuNext = Menu::create(itemNext, nullptr); - menuNext->alignItemsHorizontally(); - menuNext->setScale(0.4); - menuNext->setAnchorPoint(Vec2(0.0f, 0.0f)); - menuNext->setPosition(Vec2(s.width / 2 + 45, 23.0f)); - addChild(menuNext); + auto menuNext = Menu::create(itemNext, nullptr); + menuNext->alignItemsHorizontally(); + menuNext->setScale(0.4); + menuNext->setAnchorPoint(Vec2(0.0f, 0.0f)); + menuNext->setPosition(Vec2(s.width / 2 + 45, 23.0f)); + addChild(menuNext); - initPhysics(); + initPhysics(); } -std::string BenchDemo::title() const { - return "Bench"; +std::string BenchDemo::title() const +{ + return "Bench"; } -std::string BenchDemo::subtitle() const { - std::string s = std::to_string(bench+1) + ". " + bench_list[bench].name; - return s.c_str(); +std::string BenchDemo::subtitle() const +{ + std::string s = std::to_string(bench + 1) + ". " + bench_list[bench].name; + return s.c_str(); } -void BenchDemo::initPhysics() { - _space = bench_list[bench].initFunc(); - ChipmunkTestBed::initPhysics(); +void BenchDemo::initPhysics() +{ + _space = bench_list[bench].initFunc(); + ChipmunkTestBed::initPhysics(); } -void BenchDemo::update(float delta) { - ChipmunkTestBed::updateInit(bench_list[bench]); +void BenchDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(bench_list[bench]); } - //------------------------------------------------------------------ // // SpringiesDemo // //------------------------------------------------------------------ -void SpringiesDemo::onEnter() { - ChipmunkTestBed::onEnter(); +void SpringiesDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string SpringiesDemo::title() const { - return Springies.name; +std::string SpringiesDemo::title() const +{ + return Springies.name; } -void SpringiesDemo::initPhysics() { - _space = Springies.initFunc(); - ChipmunkTestBed::initPhysics(); +void SpringiesDemo::initPhysics() +{ + _space = Springies.initFunc(); + ChipmunkTestBed::initPhysics(); } -void SpringiesDemo::update(float delta) { - ChipmunkTestBed::updateInit(Springies); +void SpringiesDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(Springies); } - //------------------------------------------------------------------ // // ShatterDemo // //------------------------------------------------------------------ -void ShatterDemo::onEnter() { - ChipmunkTestBed::onEnter(); - initPhysics(); +void ShatterDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); + initPhysics(); } -std::string ShatterDemo::title() const { - return Shatter.name; +std::string ShatterDemo::title() const +{ + return Shatter.name; } -void ShatterDemo::initPhysics() { - _space = Shatter.initFunc(); - ChipmunkTestBed::initPhysics(); +void ShatterDemo::initPhysics() +{ + _space = Shatter.initFunc(); + ChipmunkTestBed::initPhysics(); } -void ShatterDemo::update(float delta) { - ChipmunkTestBed::updateInit(Shatter); +void ShatterDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(Shatter); } //------------------------------------------------------------------ @@ -809,23 +895,27 @@ void ShatterDemo::update(float delta) { // StickyDemo // //------------------------------------------------------------------ -void StickyDemo::onEnter() { - ChipmunkTestBed::onEnter(); +void StickyDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string StickyDemo::title() const { - return Sticky.name; +std::string StickyDemo::title() const +{ + return Sticky.name; } -void StickyDemo::initPhysics() { - _space = Sticky.initFunc(); - ChipmunkTestBed::initPhysics(); +void StickyDemo::initPhysics() +{ + _space = Sticky.initFunc(); + ChipmunkTestBed::initPhysics(); } -void StickyDemo::update(float delta) { - ChipmunkTestBed::updateInit(Sticky); +void StickyDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(Sticky); } //------------------------------------------------------------------ @@ -833,23 +923,27 @@ void StickyDemo::update(float delta) { // CraneDemo // //------------------------------------------------------------------ -void CraneDemo::onEnter() { - ChipmunkTestBed::onEnter(); +void CraneDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string CraneDemo::title() const { - return Crane.name; +std::string CraneDemo::title() const +{ + return Crane.name; } -void CraneDemo::initPhysics() { - _space = Crane.initFunc(); - ChipmunkTestBed::initPhysics(); +void CraneDemo::initPhysics() +{ + _space = Crane.initFunc(); + ChipmunkTestBed::initPhysics(); } -void CraneDemo::update(float delta) { - ChipmunkTestBed::updateInit(Crane); +void CraneDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(Crane); } //------------------------------------------------------------------ @@ -857,23 +951,27 @@ void CraneDemo::update(float delta) { // JointsDemo // //------------------------------------------------------------------ -void JointsDemo::onEnter() { - ChipmunkTestBed::onEnter(); +void JointsDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string JointsDemo::title() const { - return Joints.name; +std::string JointsDemo::title() const +{ + return Joints.name; } -void JointsDemo::initPhysics() { - _space = Joints.initFunc(); - ChipmunkTestBed::initPhysics(); +void JointsDemo::initPhysics() +{ + _space = Joints.initFunc(); + ChipmunkTestBed::initPhysics(); } -void JointsDemo::update(float delta) { - ChipmunkTestBed::updateInit(Joints); +void JointsDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(Joints); } //------------------------------------------------------------------ @@ -881,23 +979,27 @@ void JointsDemo::update(float delta) { // ConvexDemo // //------------------------------------------------------------------ -void ConvexDemo::onEnter() { - ChipmunkTestBed::onEnter(); +void ConvexDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string ConvexDemo::title() const { - return Convex.name; +std::string ConvexDemo::title() const +{ + return Convex.name; } -void ConvexDemo::initPhysics() { - _space = Convex.initFunc(); - ChipmunkTestBed::initPhysics(); +void ConvexDemo::initPhysics() +{ + _space = Convex.initFunc(); + ChipmunkTestBed::initPhysics(); } -void ConvexDemo::update(float delta) { - ChipmunkTestBed::updateInit(Convex); +void ConvexDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(Convex); } //------------------------------------------------------------------ @@ -905,23 +1007,27 @@ void ConvexDemo::update(float delta) { // PumpDemo // //------------------------------------------------------------------ -void PumpDemo::onEnter() { - ChipmunkTestBed::onEnter(); +void PumpDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string PumpDemo::title() const { - return Pump.name; +std::string PumpDemo::title() const +{ + return Pump.name; } -void PumpDemo::initPhysics() { - _space = Pump.initFunc(); - ChipmunkTestBed::initPhysics(); +void PumpDemo::initPhysics() +{ + _space = Pump.initFunc(); + ChipmunkTestBed::initPhysics(); } -void PumpDemo::update(float delta) { - ChipmunkTestBed::updateInit(Pump); +void PumpDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(Pump); } //------------------------------------------------------------------ @@ -929,23 +1035,27 @@ void PumpDemo::update(float delta) { // PlatformerPlayerDemo // //------------------------------------------------------------------ -void PlatformerPlayerDemo::onEnter() { - ChipmunkTestBed::onEnter(); +void PlatformerPlayerDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string PlatformerPlayerDemo::title() const { - return PlatformerPlayer.name; +std::string PlatformerPlayerDemo::title() const +{ + return PlatformerPlayer.name; } -void PlatformerPlayerDemo::initPhysics() { - _space = PlatformerPlayer.initFunc(); - ChipmunkTestBed::initPhysics(); +void PlatformerPlayerDemo::initPhysics() +{ + _space = PlatformerPlayer.initFunc(); + ChipmunkTestBed::initPhysics(); } -void PlatformerPlayerDemo::update(float delta) { - ChipmunkTestBed::updateInit(PlatformerPlayer); +void PlatformerPlayerDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(PlatformerPlayer); } //------------------------------------------------------------------ @@ -953,23 +1063,27 @@ void PlatformerPlayerDemo::update(float delta) { // QueryDemo // //------------------------------------------------------------------ -void QueryDemo::onEnter() { - ChipmunkTestBed::onEnter(); +void QueryDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string QueryDemo::title() const { - return Query.name; +std::string QueryDemo::title() const +{ + return Query.name; } -void QueryDemo::initPhysics() { - _space = Query.initFunc(); - ChipmunkTestBed::initPhysics(); +void QueryDemo::initPhysics() +{ + _space = Query.initFunc(); + ChipmunkTestBed::initPhysics(); } -void QueryDemo::update(float delta) { - ChipmunkTestBed::updateInit(Query); +void QueryDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(Query); } //------------------------------------------------------------------ @@ -977,23 +1091,27 @@ void QueryDemo::update(float delta) { // ContactGraphDemo // //------------------------------------------------------------------ -void ContactGraphDemo::onEnter() { - ChipmunkTestBed::onEnter(); +void ContactGraphDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string ContactGraphDemo::title() const { - return ContactGraph.name; +std::string ContactGraphDemo::title() const +{ + return ContactGraph.name; } -void ContactGraphDemo::initPhysics() { - _space = ContactGraph.initFunc(); - ChipmunkTestBed::initPhysics(); +void ContactGraphDemo::initPhysics() +{ + _space = ContactGraph.initFunc(); + ChipmunkTestBed::initPhysics(); } -void ContactGraphDemo::update(float delta) { - ChipmunkTestBed::updateInit(ContactGraph); +void ContactGraphDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(ContactGraph); } //------------------------------------------------------------------ @@ -1001,23 +1119,27 @@ void ContactGraphDemo::update(float delta) { // BuoyancyDemo // //------------------------------------------------------------------ -void BuoyancyDemo::onEnter() { - ChipmunkTestBed::onEnter(); +void BuoyancyDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string BuoyancyDemo::title() const { - return Buoyancy.name; +std::string BuoyancyDemo::title() const +{ + return Buoyancy.name; } -void BuoyancyDemo::initPhysics() { - _space = Buoyancy.initFunc(); - ChipmunkTestBed::initPhysics(); +void BuoyancyDemo::initPhysics() +{ + _space = Buoyancy.initFunc(); + ChipmunkTestBed::initPhysics(); } -void BuoyancyDemo::update(float delta) { - ChipmunkTestBed::updateInit(Buoyancy); +void BuoyancyDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(Buoyancy); } //------------------------------------------------------------------ @@ -1025,23 +1147,27 @@ void BuoyancyDemo::update(float delta) { // SliceDemo // //------------------------------------------------------------------ -void SliceDemo::onEnter() { - ChipmunkTestBed::onEnter(); +void SliceDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string SliceDemo::title() const { - return Slice.name; +std::string SliceDemo::title() const +{ + return Slice.name; } -void SliceDemo::initPhysics() { - _space = Slice.initFunc(); - ChipmunkTestBed::initPhysics(); +void SliceDemo::initPhysics() +{ + _space = Slice.initFunc(); + ChipmunkTestBed::initPhysics(); } -void SliceDemo::update(float delta) { - ChipmunkTestBed::updateInit(Slice); +void SliceDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(Slice); } //------------------------------------------------------------------ @@ -1049,82 +1175,88 @@ void SliceDemo::update(float delta) { // UnicycleDemo // //------------------------------------------------------------------ -void UnicycleDemo::onEnter() { - ChipmunkTestBed::onEnter(); +void UnicycleDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string UnicycleDemo::title() const { - return Unicycle.name; +std::string UnicycleDemo::title() const +{ + return Unicycle.name; } -void UnicycleDemo::initPhysics() { - _space = Unicycle.initFunc(); - ChipmunkTestBed::initPhysics(); +void UnicycleDemo::initPhysics() +{ + _space = Unicycle.initFunc(); + ChipmunkTestBed::initPhysics(); } -void UnicycleDemo::update(float delta) { - ChipmunkTestBed::updateInit(Unicycle); +void UnicycleDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(Unicycle); } - //------------------------------------------------------------------ // // ExampleDemo // //------------------------------------------------------------------ -void ExampleDemo::onEnter() { - ChipmunkTestBed::onEnter(); +void ExampleDemo::onEnter() +{ + ChipmunkTestBed::onEnter(); - initPhysics(); + initPhysics(); } -std::string ExampleDemo::title() const { - return Example.name; +std::string ExampleDemo::title() const +{ + return Example.name; } -void ExampleDemo::initPhysics() { - _space = Example.initFunc(); - ChipmunkTestBed::initPhysics(); +void ExampleDemo::initPhysics() +{ + _space = Example.initFunc(); + ChipmunkTestBed::initPhysics(); } -void ExampleDemo::update(float delta) { - ChipmunkTestBed::updateInit(Example); +void ExampleDemo::update(float delta) +{ + ChipmunkTestBed::updateInit(Example); } - -ChipmunkTestBedTests::ChipmunkTestBedTests() { - ADD_TEST_CASE(BenchDemo); - ADD_TEST_CASE(LogoSmashDemo); - ADD_TEST_CASE(PlinkDemo); - ADD_TEST_CASE(TumbleDemo); - ADD_TEST_CASE(PyramidToppleDemo); - ADD_TEST_CASE(PyramidStackDemo); - ADD_TEST_CASE(ChainsDemo); - ADD_TEST_CASE(OneWayDemo); - ADD_TEST_CASE(PlanetDemo); - ADD_TEST_CASE(TheoJansenDemo); - ADD_TEST_CASE(TankDemo); - - ADD_TEST_CASE(SpringiesDemo); - - ADD_TEST_CASE(ShatterDemo); - ADD_TEST_CASE(StickyDemo); - ADD_TEST_CASE(CraneDemo); - ADD_TEST_CASE(JointsDemo); - - ADD_TEST_CASE(ConvexDemo); - - ADD_TEST_CASE(PumpDemo); - ADD_TEST_CASE(PlatformerPlayerDemo); - - ADD_TEST_CASE(QueryDemo); - ADD_TEST_CASE(ContactGraphDemo); - ADD_TEST_CASE(BuoyancyDemo); - ADD_TEST_CASE(SliceDemo); - ADD_TEST_CASE(UnicycleDemo); - - ADD_TEST_CASE(ExampleDemo); // the template for your one examples/Demos +ChipmunkTestBedTests::ChipmunkTestBedTests() +{ + ADD_TEST_CASE(BenchDemo); + ADD_TEST_CASE(LogoSmashDemo); + ADD_TEST_CASE(PlinkDemo); + ADD_TEST_CASE(TumbleDemo); + ADD_TEST_CASE(PyramidToppleDemo); + ADD_TEST_CASE(PyramidStackDemo); + ADD_TEST_CASE(ChainsDemo); + ADD_TEST_CASE(OneWayDemo); + ADD_TEST_CASE(PlanetDemo); + ADD_TEST_CASE(TheoJansenDemo); + ADD_TEST_CASE(TankDemo); + + ADD_TEST_CASE(SpringiesDemo); + + ADD_TEST_CASE(ShatterDemo); + ADD_TEST_CASE(StickyDemo); + ADD_TEST_CASE(CraneDemo); + ADD_TEST_CASE(JointsDemo); + + ADD_TEST_CASE(ConvexDemo); + + ADD_TEST_CASE(PumpDemo); + ADD_TEST_CASE(PlatformerPlayerDemo); + + ADD_TEST_CASE(QueryDemo); + ADD_TEST_CASE(ContactGraphDemo); + ADD_TEST_CASE(BuoyancyDemo); + ADD_TEST_CASE(SliceDemo); + ADD_TEST_CASE(UnicycleDemo); + + ADD_TEST_CASE(ExampleDemo); // the template for your one examples/Demos } - diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/ChipmunkTestBed.h b/tests/cpp-tests/Classes/ChipmunkTestBed/ChipmunkTestBed.h index 2cce89d31b40..c080f5711084 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/ChipmunkTestBed.h +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/ChipmunkTestBed.h @@ -20,9 +20,9 @@ THE SOFTWARE. ****************************************************************************/ - // - // cocos2d - // +// +// cocos2d +// #ifndef __CHIPMUNKTESTBED_H__ #define __CHIPMUNKTESTBED_H__ @@ -33,290 +33,312 @@ #include "demo/ChipmunkDemo.h" -class ChipmunkTestBed : public TestCase { +class ChipmunkTestBed : public TestCase +{ public: - CREATE_FUNC(ChipmunkTestBed); + CREATE_FUNC(ChipmunkTestBed); - ChipmunkTestBed(); - ~ChipmunkTestBed(); + ChipmunkTestBed(); + ~ChipmunkTestBed(); - void onEnter() override; - void createResetButton(); - void reset(cocos2d::Ref* sender); + void onEnter() override; + void createResetButton(); + void reset(cocos2d::Ref* sender); - void update(float dt) override; - virtual void initPhysics(); + void update(float dt) override; + virtual void initPhysics(); - void onMouseDown(cocos2d::Event* event); - void onMouseUp(cocos2d::Event* event); - void onMouseMove(cocos2d::Event* event); - void DrawInfo(); - void updateInit(ChipmunkDemo tt); + void onMouseDown(cocos2d::Event* event); + void onMouseUp(cocos2d::Event* event); + void onMouseMove(cocos2d::Event* event); + void DrawInfo(); + void updateInit(ChipmunkDemo tt); - cpSpace* _space; // strong ref - cocos2d::extension::PhysicsDebugNodeChipmunk2D* _debugLayer; // weak ref - int keyPresses; - bool mousePresses = false; + cpSpace* _space; // strong ref + cocos2d::extension::PhysicsDebugNodeChipmunk2D* _debugLayer; // weak ref + int keyPresses; + bool mousePresses = false; private: - cocos2d::EventListenerMouse* _mouseListener; - cocos2d::Node* _trackNode; - cocos2d::DrawNode* draw; - cocos2d::Label* drawInfo; - + cocos2d::EventListenerMouse* _mouseListener; + cocos2d::Node* _trackNode; + cocos2d::DrawNode* draw; + cocos2d::Label* drawInfo; }; -class LogoSmashDemo : public ChipmunkTestBed { +class LogoSmashDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(LogoSmashDemo); - std::string title() const override; - void onEnter() override; + CREATE_FUNC(LogoSmashDemo); + std::string title() const override; + void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class PlinkDemo : public ChipmunkTestBed { +class PlinkDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(PlinkDemo); - virtual std::string title() const override; - virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + CREATE_FUNC(PlinkDemo); + virtual std::string title() const override; + virtual void onEnter() override; + void initPhysics() override; + virtual void update(float dt) override; }; - -class TumbleDemo : public ChipmunkTestBed { +class TumbleDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(TumbleDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(TumbleDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class PyramidStackDemo : public ChipmunkTestBed { +class PyramidStackDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(PyramidStackDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(PyramidStackDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class PyramidToppleDemo : public ChipmunkTestBed { +class PyramidToppleDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(PyramidToppleDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(PyramidToppleDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class ChainsDemo : public ChipmunkTestBed { +class ChainsDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(ChainsDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(ChainsDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class OneWayDemo : public ChipmunkTestBed { +class OneWayDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(OneWayDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(OneWayDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class PlanetDemo : public ChipmunkTestBed { +class PlanetDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(PlanetDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(PlanetDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class TheoJansenDemo : public ChipmunkTestBed { +class TheoJansenDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(TheoJansenDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(TheoJansenDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class TankDemo : public ChipmunkTestBed { +class TankDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(TankDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(TankDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class BenchDemo : public ChipmunkTestBed { +class BenchDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(BenchDemo); - virtual std::string title() const override; - virtual std::string subtitle() const override; - virtual void onEnter() override; + CREATE_FUNC(BenchDemo); + virtual std::string title() const override; + virtual std::string subtitle() const override; + virtual void onEnter() override; - - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class SpringiesDemo : public ChipmunkTestBed { +class SpringiesDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(SpringiesDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(SpringiesDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class StickyDemo : public ChipmunkTestBed { +class StickyDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(StickyDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(StickyDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class ShatterDemo : public ChipmunkTestBed { +class ShatterDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(ShatterDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(ShatterDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class CraneDemo : public ChipmunkTestBed { +class CraneDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(CraneDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(CraneDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class JointsDemo : public ChipmunkTestBed { +class JointsDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(JointsDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(JointsDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class ConvexDemo : public ChipmunkTestBed { +class ConvexDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(ConvexDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(ConvexDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class PumpDemo : public ChipmunkTestBed { +class PumpDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(PumpDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(PumpDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class PlatformerPlayerDemo : public ChipmunkTestBed { +class PlatformerPlayerDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(PlatformerPlayerDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(PlatformerPlayerDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class QueryDemo : public ChipmunkTestBed { +class QueryDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(QueryDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(QueryDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; - -class ContactGraphDemo : public ChipmunkTestBed { +class ContactGraphDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(ContactGraphDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(ContactGraphDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class BuoyancyDemo : public ChipmunkTestBed { +class BuoyancyDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(BuoyancyDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(BuoyancyDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class SliceDemo : public ChipmunkTestBed { +class SliceDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(SliceDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(SliceDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class UnicycleDemo : public ChipmunkTestBed { +class UnicycleDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(UnicycleDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(UnicycleDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; -class ExampleDemo : public ChipmunkTestBed { +class ExampleDemo : public ChipmunkTestBed +{ public: - CREATE_FUNC(ExampleDemo); - virtual std::string title() const override; - virtual void onEnter() override; + CREATE_FUNC(ExampleDemo); + virtual std::string title() const override; + virtual void onEnter() override; - void initPhysics() override; - virtual void update(float dt) override; + void initPhysics() override; + virtual void update(float dt) override; }; DEFINE_TEST_SUITE(ChipmunkTestBedTests); diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Bench.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Bench.c index d99c0216da5c..d85a8d6fe1f4 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Bench.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Bench.c @@ -4,485 +4,611 @@ #define ENABLE_HASTY 0 #if ENABLE_HASTY - #include "chipmunk/cpHastySpace.h" - - static cpSpace *MakeHastySpace(){ - cpSpace *space = cpHastySpaceNew(); - cpHastySpaceSetThreads(space, 0); - return space; - } - - #define BENCH_SPACE_NEW MakeHastySpace - #define BENCH_SPACE_FREE cpHastySpaceFree - #define BENCH_SPACE_STEP cpHastySpaceStep +# include "chipmunk/cpHastySpace.h" + +static cpSpace* MakeHastySpace() +{ + cpSpace* space = cpHastySpaceNew(); + cpHastySpaceSetThreads(space, 0); + return space; +} + +# define BENCH_SPACE_NEW MakeHastySpace +# define BENCH_SPACE_FREE cpHastySpaceFree +# define BENCH_SPACE_STEP cpHastySpaceStep #else - #define BENCH_SPACE_NEW cpSpaceNew - #define BENCH_SPACE_FREE cpSpaceFree - #define BENCH_SPACE_STEP cpSpaceStep +# define BENCH_SPACE_NEW cpSpaceNew +# define BENCH_SPACE_FREE cpSpaceFree +# define BENCH_SPACE_STEP cpSpaceStep #endif const cpFloat bevel = 1.0; static cpVect simple_terrain_verts[] = { - {350.00, 425.07}, {336.00, 436.55}, {272.00, 435.39}, {258.00, 427.63}, {225.28, 420.00}, {202.82, 396.00}, - {191.81, 388.00}, {189.00, 381.89}, {173.00, 380.39}, {162.59, 368.00}, {150.47, 319.00}, {128.00, 311.55}, - {119.14, 286.00}, {126.84, 263.00}, {120.56, 227.00}, {141.14, 178.00}, {137.52, 162.00}, {146.51, 142.00}, - {156.23, 136.00}, {158.00, 118.27}, {170.00, 100.77}, {208.43, 84.00}, {224.00, 69.65}, {249.30, 68.00}, - {257.00, 54.77}, {363.00, 45.94}, {374.15, 54.00}, {386.00, 69.60}, {413.00, 70.73}, {456.00, 84.89}, - {468.09, 99.00}, {467.09, 123.00}, {464.92, 135.00}, {469.00, 141.03}, {497.00, 148.67}, {513.85, 180.00}, - {509.56, 223.00}, {523.51, 247.00}, {523.00, 277.00}, {497.79, 311.00}, {478.67, 348.00}, {467.90, 360.00}, - {456.76, 382.00}, {432.95, 389.00}, {417.00, 411.32}, {373.00, 433.19}, {361.00, 430.02}, {350.00, 425.07}, + {350.00, 425.07}, {336.00, 436.55}, {272.00, 435.39}, {258.00, 427.63}, {225.28, 420.00}, {202.82, 396.00}, + {191.81, 388.00}, {189.00, 381.89}, {173.00, 380.39}, {162.59, 368.00}, {150.47, 319.00}, {128.00, 311.55}, + {119.14, 286.00}, {126.84, 263.00}, {120.56, 227.00}, {141.14, 178.00}, {137.52, 162.00}, {146.51, 142.00}, + {156.23, 136.00}, {158.00, 118.27}, {170.00, 100.77}, {208.43, 84.00}, {224.00, 69.65}, {249.30, 68.00}, + {257.00, 54.77}, {363.00, 45.94}, {374.15, 54.00}, {386.00, 69.60}, {413.00, 70.73}, {456.00, 84.89}, + {468.09, 99.00}, {467.09, 123.00}, {464.92, 135.00}, {469.00, 141.03}, {497.00, 148.67}, {513.85, 180.00}, + {509.56, 223.00}, {523.51, 247.00}, {523.00, 277.00}, {497.79, 311.00}, {478.67, 348.00}, {467.90, 360.00}, + {456.76, 382.00}, {432.95, 389.00}, {417.00, 411.32}, {373.00, 433.19}, {361.00, 430.02}, {350.00, 425.07}, }; -static int simple_terrain_count = sizeof(simple_terrain_verts)/sizeof(cpVect); - -//cpBody bodies[1000] = {}; -//cpCircleShape circles[1000] = {}; - -static void add_circle(cpSpace *space, int index, cpFloat radius){ - cpFloat mass = radius*radius/25.0f; - cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); -// cpBody *body = cpSpaceAddBody(space, cpBodyInit(&bodies[i], mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); - cpBodySetPosition(body, cpvmult(frand_unit_circle(), 180.0f)); - - - cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); -// cpShape *shape = cpSpaceAddShape(space, cpCircleShapeInit(&circles[i], body, radius, cpvzero)); - cpShapeSetElasticity(shape, 0.0); cpShapeSetFriction(shape, 0.9); +static int simple_terrain_count = sizeof(simple_terrain_verts) / sizeof(cpVect); + +// cpBody bodies[1000] = {}; +// cpCircleShape circles[1000] = {}; + +static void add_circle(cpSpace* space, int index, cpFloat radius) +{ + cpFloat mass = radius * radius / 25.0f; + cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); + // cpBody *body = cpSpaceAddBody(space, cpBodyInit(&bodies[i], mass, cpMomentForCircle(mass, 0.0f, radius, + // cpvzero))); + cpBodySetPosition(body, cpvmult(frand_unit_circle(), 180.0f)); + + cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); + // cpShape *shape = cpSpaceAddShape(space, cpCircleShapeInit(&circles[i], body, radius, cpvzero)); + cpShapeSetElasticity(shape, 0.0); + cpShapeSetFriction(shape, 0.9); } -static void add_box(cpSpace *space, int index, cpFloat size){ - cpFloat mass = size*size/100.0f; - cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForBox(mass, size, size))); -// cpBody *body = cpSpaceAddBody(space, cpBodyInit(&bodies[i], mass, cpMomentForBox(mass, size, size))); - cpBodySetPosition(body, cpvmult(frand_unit_circle(), 180.0f)); - - - cpShape *shape = cpSpaceAddShape(space, cpBoxShapeNew(body, size - bevel*2, size - bevel*2, 0.0)); - cpPolyShapeSetRadius(shape, bevel); - cpShapeSetElasticity(shape, 0.0); cpShapeSetFriction(shape, 0.9); +static void add_box(cpSpace* space, int index, cpFloat size) +{ + cpFloat mass = size * size / 100.0f; + cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForBox(mass, size, size))); + // cpBody *body = cpSpaceAddBody(space, cpBodyInit(&bodies[i], mass, cpMomentForBox(mass, size, size))); + cpBodySetPosition(body, cpvmult(frand_unit_circle(), 180.0f)); + + cpShape* shape = cpSpaceAddShape(space, cpBoxShapeNew(body, size - bevel * 2, size - bevel * 2, 0.0)); + cpPolyShapeSetRadius(shape, bevel); + cpShapeSetElasticity(shape, 0.0); + cpShapeSetFriction(shape, 0.9); } -static void add_hexagon(cpSpace *space, int index, cpFloat radius){ - cpVect hexagon[6]; - for(int i=0; i<6; i++){ - cpFloat angle = -CP_PI*2.0f*i/6.0f; - hexagon[i] = cpvmult(cpv(cos(angle), sin(angle)), radius - bevel); - } - - cpFloat mass = radius*radius; - cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 6, hexagon, cpvzero, 0.0f))); - cpBodySetPosition(body, cpvmult(frand_unit_circle(), 180.0f)); - - cpShape *shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 6, hexagon, cpTransformIdentity, bevel)); - cpShapeSetElasticity(shape, 0.0); cpShapeSetFriction(shape, 0.9); +static void add_hexagon(cpSpace* space, int index, cpFloat radius) +{ + cpVect hexagon[6]; + for (int i = 0; i < 6; i++) + { + cpFloat angle = -CP_PI * 2.0f * i / 6.0f; + hexagon[i] = cpvmult(cpv(cos(angle), sin(angle)), radius - bevel); + } + + cpFloat mass = radius * radius; + cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 6, hexagon, cpvzero, 0.0f))); + cpBodySetPosition(body, cpvmult(frand_unit_circle(), 180.0f)); + + cpShape* shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 6, hexagon, cpTransformIdentity, bevel)); + cpShapeSetElasticity(shape, 0.0); + cpShapeSetFriction(shape, 0.9); } - -static cpSpace * -SetupSpace_simpleTerrain(){ - cpSpace *space = BENCH_SPACE_NEW(); - cpSpaceSetIterations(space, 10); - cpSpaceSetGravity(space, cpv(0, -100)); - cpSpaceSetCollisionSlop(space, 0.5f); - - cpVect offset = cpv(-320, -240); - for(int i=0; i<(simple_terrain_count - 1); i++){ - cpVect a = simple_terrain_verts[i], b = simple_terrain_verts[i+1]; - cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpvadd(a, offset), cpvadd(b, offset), 0.0f)); - } - - return space; +static cpSpace* SetupSpace_simpleTerrain() +{ + cpSpace* space = BENCH_SPACE_NEW(); + cpSpaceSetIterations(space, 10); + cpSpaceSetGravity(space, cpv(0, -100)); + cpSpaceSetCollisionSlop(space, 0.5f); + + cpVect offset = cpv(-320, -240); + for (int i = 0; i < (simple_terrain_count - 1); i++) + { + cpVect a = simple_terrain_verts[i], b = simple_terrain_verts[i + 1]; + cpSpaceAddShape(space, + cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpvadd(a, offset), cpvadd(b, offset), 0.0f)); + } + + return space; } - // SimpleTerrain constant sized objects -static cpSpace *init_SimpleTerrainCircles_1000(void){ - cpSpace *space = SetupSpace_simpleTerrain(); - for(int i=0; i<1000; i++) add_circle(space, i, 5.0f); - - return space; -} +static cpSpace* init_SimpleTerrainCircles_1000(void) +{ + cpSpace* space = SetupSpace_simpleTerrain(); + for (int i = 0; i < 1000; i++) + add_circle(space, i, 5.0f); -static cpSpace *init_SimpleTerrainCircles_500(void){ - cpSpace *space = SetupSpace_simpleTerrain(); - for(int i=0; i<500; i++) add_circle(space, i, 5.0f); - - return space; + return space; } -static cpSpace *init_SimpleTerrainCircles_100(void){ - cpSpace *space = SetupSpace_simpleTerrain(); - for(int i=0; i<100; i++) add_circle(space, i, 5.0f); - - return space; +static cpSpace* init_SimpleTerrainCircles_500(void) +{ + cpSpace* space = SetupSpace_simpleTerrain(); + for (int i = 0; i < 500; i++) + add_circle(space, i, 5.0f); + + return space; } -static cpSpace *init_SimpleTerrainBoxes_1000(void){ - cpSpace *space = SetupSpace_simpleTerrain(); - for(int i=0; i<1000; i++) add_box(space, i, 10.0f); - - return space; +static cpSpace* init_SimpleTerrainCircles_100(void) +{ + cpSpace* space = SetupSpace_simpleTerrain(); + for (int i = 0; i < 100; i++) + add_circle(space, i, 5.0f); + + return space; } -static cpSpace *init_SimpleTerrainBoxes_500(void){ - cpSpace *space = SetupSpace_simpleTerrain(); - for(int i=0; i<500; i++) add_box(space, i, 10.0f); - - return space; +static cpSpace* init_SimpleTerrainBoxes_1000(void) +{ + cpSpace* space = SetupSpace_simpleTerrain(); + for (int i = 0; i < 1000; i++) + add_box(space, i, 10.0f); + + return space; } -static cpSpace *init_SimpleTerrainBoxes_100(void){ - cpSpace *space = SetupSpace_simpleTerrain(); - for(int i=0; i<100; i++) add_box(space, i, 10.0f); - - return space; +static cpSpace* init_SimpleTerrainBoxes_500(void) +{ + cpSpace* space = SetupSpace_simpleTerrain(); + for (int i = 0; i < 500; i++) + add_box(space, i, 10.0f); + + return space; } -static cpSpace *init_SimpleTerrainHexagons_1000(void){ - cpSpace *space = SetupSpace_simpleTerrain(); - for(int i=0; i<1000; i++) add_hexagon(space, i, 5.0f); - - return space; +static cpSpace* init_SimpleTerrainBoxes_100(void) +{ + cpSpace* space = SetupSpace_simpleTerrain(); + for (int i = 0; i < 100; i++) + add_box(space, i, 10.0f); + + return space; } -static cpSpace *init_SimpleTerrainHexagons_500(void){ - cpSpace *space = SetupSpace_simpleTerrain(); - for(int i=0; i<500; i++) add_hexagon(space, i, 5.0f); - - return space; +static cpSpace* init_SimpleTerrainHexagons_1000(void) +{ + cpSpace* space = SetupSpace_simpleTerrain(); + for (int i = 0; i < 1000; i++) + add_hexagon(space, i, 5.0f); + + return space; } -static cpSpace *init_SimpleTerrainHexagons_100(void){ - cpSpace *space = SetupSpace_simpleTerrain(); - for(int i=0; i<100; i++) add_hexagon(space, i, 5.0f); - - return space; +static cpSpace* init_SimpleTerrainHexagons_500(void) +{ + cpSpace* space = SetupSpace_simpleTerrain(); + for (int i = 0; i < 500; i++) + add_hexagon(space, i, 5.0f); + + return space; } +static cpSpace* init_SimpleTerrainHexagons_100(void) +{ + cpSpace* space = SetupSpace_simpleTerrain(); + for (int i = 0; i < 100; i++) + add_hexagon(space, i, 5.0f); -// SimpleTerrain variable sized objects -static cpFloat rand_size(){ - return cpfpow(1.5, cpflerp(-1.5, 3.5, frand())); + return space; } -static cpSpace *init_SimpleTerrainVCircles_200(void){ - cpSpace *space = SetupSpace_simpleTerrain(); - for(int i=0; i<200; i++) add_circle(space, i, 5.0f*rand_size()); - - return space; +// SimpleTerrain variable sized objects +static cpFloat rand_size() +{ + return cpfpow(1.5, cpflerp(-1.5, 3.5, frand())); } -static cpSpace *init_SimpleTerrainVBoxes_200(void){ - cpSpace *space = SetupSpace_simpleTerrain(); - for(int i=0; i<200; i++) add_box(space, i, 8.0f*rand_size()); - - return space; +static cpSpace* init_SimpleTerrainVCircles_200(void) +{ + cpSpace* space = SetupSpace_simpleTerrain(); + for (int i = 0; i < 200; i++) + add_circle(space, i, 5.0f * rand_size()); + + return space; } -static cpSpace *init_SimpleTerrainVHexagons_200(void){ - cpSpace *space = SetupSpace_simpleTerrain(); - for(int i=0; i<200; i++) add_hexagon(space, i, 5.0f*rand_size()); - - return space; +static cpSpace* init_SimpleTerrainVBoxes_200(void) +{ + cpSpace* space = SetupSpace_simpleTerrain(); + for (int i = 0; i < 200; i++) + add_box(space, i, 8.0f * rand_size()); + + return space; } +static cpSpace* init_SimpleTerrainVHexagons_200(void) +{ + cpSpace* space = SetupSpace_simpleTerrain(); + for (int i = 0; i < 200; i++) + add_hexagon(space, i, 5.0f * rand_size()); + + return space; +} // ComplexTerrain static cpVect complex_terrain_verts[] = { - { 46.78, 479.00}, { 35.00, 475.63}, { 27.52, 469.00}, { 23.52, 455.00}, { 23.78, 441.00}, { 28.41, 428.00}, { 49.61, 394.00}, { 59.00, 381.56}, { 80.00, 366.03}, { 81.46, 358.00}, { 86.31, 350.00}, { 77.74, 320.00}, - { 70.26, 278.00}, { 67.51, 270.00}, { 58.86, 260.00}, { 57.19, 247.00}, { 38.00, 235.60}, { 25.76, 221.00}, { 24.58, 209.00}, { 27.63, 202.00}, { 31.28, 198.00}, { 40.00, 193.72}, { 48.00, 193.73}, { 55.00, 196.70}, - { 62.10, 204.00}, { 71.00, 209.04}, { 79.00, 206.55}, { 88.00, 206.81}, { 95.88, 211.00}, {103.00, 220.49}, {131.00, 220.51}, {137.00, 222.66}, {143.08, 228.00}, {146.22, 234.00}, {147.08, 241.00}, {145.45, 248.00}, - {142.31, 253.00}, {132.00, 259.30}, {115.00, 259.70}, {109.28, 270.00}, {112.91, 296.00}, {119.69, 324.00}, {129.00, 336.26}, {141.00, 337.59}, {153.00, 331.57}, {175.00, 325.74}, {188.00, 325.19}, {235.00, 317.46}, - {250.00, 317.19}, {255.00, 309.12}, {262.62, 302.00}, {262.21, 295.00}, {248.00, 273.59}, {229.00, 257.93}, {221.00, 255.48}, {215.00, 251.59}, {210.79, 246.00}, {207.47, 234.00}, {203.25, 227.00}, {179.00, 205.90}, - {148.00, 189.54}, {136.00, 181.45}, {120.00, 180.31}, {110.00, 181.65}, { 95.00, 179.31}, { 63.00, 166.96}, { 50.00, 164.23}, { 31.00, 154.49}, { 19.76, 145.00}, { 15.96, 136.00}, { 16.65, 127.00}, { 20.57, 120.00}, - { 28.00, 114.63}, { 40.00, 113.67}, { 65.00, 127.22}, { 73.00, 128.69}, { 81.96, 120.00}, { 77.58, 103.00}, { 78.18, 92.00}, { 59.11, 77.00}, { 52.00, 67.29}, { 31.29, 55.00}, { 25.67, 47.00}, { 24.65, 37.00}, - { 27.82, 29.00}, { 35.00, 22.55}, { 44.00, 20.35}, { 49.00, 20.81}, { 61.00, 25.69}, { 79.00, 37.81}, { 88.00, 49.64}, { 97.00, 56.65}, {109.00, 49.61}, {143.00, 38.96}, {197.00, 37.27}, {215.00, 35.30}, - {222.00, 36.65}, {228.42, 41.00}, {233.30, 49.00}, {234.14, 57.00}, {231.00, 65.80}, {224.00, 72.38}, {218.00, 74.50}, {197.00, 76.62}, {145.00, 78.81}, {123.00, 87.41}, {117.59, 98.00}, {117.79, 104.00}, - {119.00, 106.23}, {138.73, 120.00}, {148.00, 129.50}, {158.50, 149.00}, {203.93, 175.00}, {229.00, 196.60}, {238.16, 208.00}, {245.20, 221.00}, {275.45, 245.00}, {289.00, 263.24}, {303.60, 287.00}, {312.00, 291.57}, - {339.25, 266.00}, {366.33, 226.00}, {363.43, 216.00}, {364.13, 206.00}, {353.00, 196.72}, {324.00, 181.05}, {307.00, 169.63}, {274.93, 156.00}, {256.00, 152.48}, {228.00, 145.13}, {221.09, 142.00}, {214.87, 135.00}, - {212.67, 127.00}, {213.81, 119.00}, {219.32, 111.00}, {228.00, 106.52}, {236.00, 106.39}, {290.00, 119.40}, {299.33, 114.00}, {300.52, 109.00}, {300.30, 53.00}, {301.46, 47.00}, {305.00, 41.12}, {311.00, 36.37}, - {317.00, 34.43}, {325.00, 34.81}, {334.90, 41.00}, {339.45, 50.00}, {339.82, 132.00}, {346.09, 139.00}, {350.00, 150.26}, {380.00, 167.38}, {393.00, 166.48}, {407.00, 155.54}, {430.00, 147.30}, {437.78, 135.00}, - {433.13, 122.00}, {410.23, 78.00}, {401.59, 69.00}, {393.48, 56.00}, {392.80, 44.00}, {395.50, 38.00}, {401.00, 32.49}, {409.00, 29.41}, {420.00, 30.84}, {426.92, 36.00}, {432.32, 44.00}, {439.49, 51.00}, - {470.13, 108.00}, {475.71, 124.00}, {483.00, 130.11}, {488.00, 139.43}, {529.00, 139.40}, {536.00, 132.52}, {543.73, 129.00}, {540.47, 115.00}, {541.11, 100.00}, {552.18, 68.00}, {553.78, 47.00}, {559.00, 39.76}, - {567.00, 35.52}, {577.00, 35.45}, {585.00, 39.58}, {591.38, 50.00}, {591.67, 66.00}, {590.31, 79.00}, {579.76, 109.00}, {582.25, 119.00}, {583.66, 136.00}, {586.45, 143.00}, {586.44, 151.00}, {580.42, 168.00}, - {577.15, 173.00}, {572.00, 177.13}, {564.00, 179.49}, {478.00, 178.81}, {443.00, 184.76}, {427.10, 190.00}, {424.00, 192.11}, {415.94, 209.00}, {408.82, 228.00}, {405.82, 241.00}, {411.00, 250.82}, {415.00, 251.50}, - {428.00, 248.89}, {469.00, 246.29}, {505.00, 246.49}, {533.00, 243.60}, {541.87, 248.00}, {547.55, 256.00}, {548.48, 267.00}, {544.00, 276.00}, {534.00, 282.24}, {513.00, 285.46}, {468.00, 285.76}, {402.00, 291.70}, - {392.00, 290.29}, {377.00, 294.46}, {367.00, 294.43}, {356.44, 304.00}, {354.22, 311.00}, {362.00, 321.36}, {390.00, 322.44}, {433.00, 330.16}, {467.00, 332.76}, {508.00, 347.64}, {522.00, 357.67}, {528.00, 354.46}, - {536.00, 352.96}, {546.06, 336.00}, {553.47, 306.00}, {564.19, 282.00}, {567.84, 268.00}, {578.72, 246.00}, {585.00, 240.97}, {592.00, 238.91}, {600.00, 239.72}, {606.00, 242.82}, {612.36, 251.00}, {613.35, 263.00}, - {588.75, 324.00}, {583.25, 350.00}, {572.12, 370.00}, {575.45, 378.00}, {575.20, 388.00}, {589.00, 393.81}, {599.20, 404.00}, {607.14, 416.00}, {609.96, 430.00}, {615.45, 441.00}, {613.44, 462.00}, {610.48, 469.00}, - {603.00, 475.63}, {590.96, 479.00}, + {46.78, 479.00}, {35.00, 475.63}, {27.52, 469.00}, {23.52, 455.00}, {23.78, 441.00}, {28.41, 428.00}, + {49.61, 394.00}, {59.00, 381.56}, {80.00, 366.03}, {81.46, 358.00}, {86.31, 350.00}, {77.74, 320.00}, + {70.26, 278.00}, {67.51, 270.00}, {58.86, 260.00}, {57.19, 247.00}, {38.00, 235.60}, {25.76, 221.00}, + {24.58, 209.00}, {27.63, 202.00}, {31.28, 198.00}, {40.00, 193.72}, {48.00, 193.73}, {55.00, 196.70}, + {62.10, 204.00}, {71.00, 209.04}, {79.00, 206.55}, {88.00, 206.81}, {95.88, 211.00}, {103.00, 220.49}, + {131.00, 220.51}, {137.00, 222.66}, {143.08, 228.00}, {146.22, 234.00}, {147.08, 241.00}, {145.45, 248.00}, + {142.31, 253.00}, {132.00, 259.30}, {115.00, 259.70}, {109.28, 270.00}, {112.91, 296.00}, {119.69, 324.00}, + {129.00, 336.26}, {141.00, 337.59}, {153.00, 331.57}, {175.00, 325.74}, {188.00, 325.19}, {235.00, 317.46}, + {250.00, 317.19}, {255.00, 309.12}, {262.62, 302.00}, {262.21, 295.00}, {248.00, 273.59}, {229.00, 257.93}, + {221.00, 255.48}, {215.00, 251.59}, {210.79, 246.00}, {207.47, 234.00}, {203.25, 227.00}, {179.00, 205.90}, + {148.00, 189.54}, {136.00, 181.45}, {120.00, 180.31}, {110.00, 181.65}, {95.00, 179.31}, {63.00, 166.96}, + {50.00, 164.23}, {31.00, 154.49}, {19.76, 145.00}, {15.96, 136.00}, {16.65, 127.00}, {20.57, 120.00}, + {28.00, 114.63}, {40.00, 113.67}, {65.00, 127.22}, {73.00, 128.69}, {81.96, 120.00}, {77.58, 103.00}, + {78.18, 92.00}, {59.11, 77.00}, {52.00, 67.29}, {31.29, 55.00}, {25.67, 47.00}, {24.65, 37.00}, + {27.82, 29.00}, {35.00, 22.55}, {44.00, 20.35}, {49.00, 20.81}, {61.00, 25.69}, {79.00, 37.81}, + {88.00, 49.64}, {97.00, 56.65}, {109.00, 49.61}, {143.00, 38.96}, {197.00, 37.27}, {215.00, 35.30}, + {222.00, 36.65}, {228.42, 41.00}, {233.30, 49.00}, {234.14, 57.00}, {231.00, 65.80}, {224.00, 72.38}, + {218.00, 74.50}, {197.00, 76.62}, {145.00, 78.81}, {123.00, 87.41}, {117.59, 98.00}, {117.79, 104.00}, + {119.00, 106.23}, {138.73, 120.00}, {148.00, 129.50}, {158.50, 149.00}, {203.93, 175.00}, {229.00, 196.60}, + {238.16, 208.00}, {245.20, 221.00}, {275.45, 245.00}, {289.00, 263.24}, {303.60, 287.00}, {312.00, 291.57}, + {339.25, 266.00}, {366.33, 226.00}, {363.43, 216.00}, {364.13, 206.00}, {353.00, 196.72}, {324.00, 181.05}, + {307.00, 169.63}, {274.93, 156.00}, {256.00, 152.48}, {228.00, 145.13}, {221.09, 142.00}, {214.87, 135.00}, + {212.67, 127.00}, {213.81, 119.00}, {219.32, 111.00}, {228.00, 106.52}, {236.00, 106.39}, {290.00, 119.40}, + {299.33, 114.00}, {300.52, 109.00}, {300.30, 53.00}, {301.46, 47.00}, {305.00, 41.12}, {311.00, 36.37}, + {317.00, 34.43}, {325.00, 34.81}, {334.90, 41.00}, {339.45, 50.00}, {339.82, 132.00}, {346.09, 139.00}, + {350.00, 150.26}, {380.00, 167.38}, {393.00, 166.48}, {407.00, 155.54}, {430.00, 147.30}, {437.78, 135.00}, + {433.13, 122.00}, {410.23, 78.00}, {401.59, 69.00}, {393.48, 56.00}, {392.80, 44.00}, {395.50, 38.00}, + {401.00, 32.49}, {409.00, 29.41}, {420.00, 30.84}, {426.92, 36.00}, {432.32, 44.00}, {439.49, 51.00}, + {470.13, 108.00}, {475.71, 124.00}, {483.00, 130.11}, {488.00, 139.43}, {529.00, 139.40}, {536.00, 132.52}, + {543.73, 129.00}, {540.47, 115.00}, {541.11, 100.00}, {552.18, 68.00}, {553.78, 47.00}, {559.00, 39.76}, + {567.00, 35.52}, {577.00, 35.45}, {585.00, 39.58}, {591.38, 50.00}, {591.67, 66.00}, {590.31, 79.00}, + {579.76, 109.00}, {582.25, 119.00}, {583.66, 136.00}, {586.45, 143.00}, {586.44, 151.00}, {580.42, 168.00}, + {577.15, 173.00}, {572.00, 177.13}, {564.00, 179.49}, {478.00, 178.81}, {443.00, 184.76}, {427.10, 190.00}, + {424.00, 192.11}, {415.94, 209.00}, {408.82, 228.00}, {405.82, 241.00}, {411.00, 250.82}, {415.00, 251.50}, + {428.00, 248.89}, {469.00, 246.29}, {505.00, 246.49}, {533.00, 243.60}, {541.87, 248.00}, {547.55, 256.00}, + {548.48, 267.00}, {544.00, 276.00}, {534.00, 282.24}, {513.00, 285.46}, {468.00, 285.76}, {402.00, 291.70}, + {392.00, 290.29}, {377.00, 294.46}, {367.00, 294.43}, {356.44, 304.00}, {354.22, 311.00}, {362.00, 321.36}, + {390.00, 322.44}, {433.00, 330.16}, {467.00, 332.76}, {508.00, 347.64}, {522.00, 357.67}, {528.00, 354.46}, + {536.00, 352.96}, {546.06, 336.00}, {553.47, 306.00}, {564.19, 282.00}, {567.84, 268.00}, {578.72, 246.00}, + {585.00, 240.97}, {592.00, 238.91}, {600.00, 239.72}, {606.00, 242.82}, {612.36, 251.00}, {613.35, 263.00}, + {588.75, 324.00}, {583.25, 350.00}, {572.12, 370.00}, {575.45, 378.00}, {575.20, 388.00}, {589.00, 393.81}, + {599.20, 404.00}, {607.14, 416.00}, {609.96, 430.00}, {615.45, 441.00}, {613.44, 462.00}, {610.48, 469.00}, + {603.00, 475.63}, {590.96, 479.00}, }; -static int complex_terrain_count = sizeof(complex_terrain_verts)/sizeof(cpVect); - -static cpSpace *init_ComplexTerrainCircles_1000(void){ - cpSpace *space = BENCH_SPACE_NEW(); - cpSpaceSetIterations(space, 10); - cpSpaceSetGravity(space, cpv(0, -100)); - cpSpaceSetCollisionSlop(space, 0.5f); - - cpVect offset = cpv(-320, -240); - for(int i=0; i<(complex_terrain_count - 1); i++){ - cpVect a = complex_terrain_verts[i], b = complex_terrain_verts[i+1]; - cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpvadd(a, offset), cpvadd(b, offset), 0.0f)); - } - - for(int i=0; i<1000; i++){ - cpFloat radius = 5.0f; - cpFloat mass = radius*radius; - cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); - cpBodySetPosition(body, cpvadd(cpvmult(frand_unit_circle(), 180.0f), cpv(0.0f, 300.0f))); - - cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); - cpShapeSetElasticity(shape, 0.0); cpShapeSetFriction(shape, 0.0); - } - - return space; +static int complex_terrain_count = sizeof(complex_terrain_verts) / sizeof(cpVect); + +static cpSpace* init_ComplexTerrainCircles_1000(void) +{ + cpSpace* space = BENCH_SPACE_NEW(); + cpSpaceSetIterations(space, 10); + cpSpaceSetGravity(space, cpv(0, -100)); + cpSpaceSetCollisionSlop(space, 0.5f); + + cpVect offset = cpv(-320, -240); + for (int i = 0; i < (complex_terrain_count - 1); i++) + { + cpVect a = complex_terrain_verts[i], b = complex_terrain_verts[i + 1]; + cpSpaceAddShape(space, + cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpvadd(a, offset), cpvadd(b, offset), 0.0f)); + } + + for (int i = 0; i < 1000; i++) + { + cpFloat radius = 5.0f; + cpFloat mass = radius * radius; + cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); + cpBodySetPosition(body, cpvadd(cpvmult(frand_unit_circle(), 180.0f), cpv(0.0f, 300.0f))); + + cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); + cpShapeSetElasticity(shape, 0.0); + cpShapeSetFriction(shape, 0.0); + } + + return space; } -static cpSpace *init_ComplexTerrainHexagons_1000(void){ - cpSpace *space = BENCH_SPACE_NEW(); - cpSpaceSetIterations(space, 10); - cpSpaceSetGravity(space, cpv(0, -100)); - cpSpaceSetCollisionSlop(space, 0.5f); - - cpVect offset = cpv(-320, -240); - for(int i=0; i<(complex_terrain_count - 1); i++){ - cpVect a = complex_terrain_verts[i], b = complex_terrain_verts[i+1]; - cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpvadd(a, offset), cpvadd(b, offset), 0.0f)); - } - - cpFloat radius = 5.0f; - cpVect hexagon[6]; - for(int i=0; i<6; i++){ - cpFloat angle = -CP_PI*2.0f*i/6.0f; - hexagon[i] = cpvmult(cpv(cos(angle), sin(angle)), radius - bevel); - } - - for(int i=0; i<1000; i++){ - cpFloat mass = radius*radius; - cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 6, hexagon, cpvzero, 0.0f))); - cpBodySetPosition(body, cpvadd(cpvmult(frand_unit_circle(), 180.0f), cpv(0.0f, 300.0f))); - - cpShape *shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 6, hexagon, cpTransformIdentity, bevel)); - cpShapeSetElasticity(shape, 0.0); cpShapeSetFriction(shape, 0.0); - } - - return space; +static cpSpace* init_ComplexTerrainHexagons_1000(void) +{ + cpSpace* space = BENCH_SPACE_NEW(); + cpSpaceSetIterations(space, 10); + cpSpaceSetGravity(space, cpv(0, -100)); + cpSpaceSetCollisionSlop(space, 0.5f); + + cpVect offset = cpv(-320, -240); + for (int i = 0; i < (complex_terrain_count - 1); i++) + { + cpVect a = complex_terrain_verts[i], b = complex_terrain_verts[i + 1]; + cpSpaceAddShape(space, + cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpvadd(a, offset), cpvadd(b, offset), 0.0f)); + } + + cpFloat radius = 5.0f; + cpVect hexagon[6]; + for (int i = 0; i < 6; i++) + { + cpFloat angle = -CP_PI * 2.0f * i / 6.0f; + hexagon[i] = cpvmult(cpv(cos(angle), sin(angle)), radius - bevel); + } + + for (int i = 0; i < 1000; i++) + { + cpFloat mass = radius * radius; + cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 6, hexagon, cpvzero, 0.0f))); + cpBodySetPosition(body, cpvadd(cpvmult(frand_unit_circle(), 180.0f), cpv(0.0f, 300.0f))); + + cpShape* shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 6, hexagon, cpTransformIdentity, bevel)); + cpShapeSetElasticity(shape, 0.0); + cpShapeSetFriction(shape, 0.0); + } + + return space; } - // BouncyTerrain static cpVect bouncy_terrain_verts[] = { - {537.18, 23.00}, {520.50, 36.00}, {501.53, 63.00}, {496.14, 76.00}, {498.86, 86.00}, {504.00, 90.51}, {508.00, 91.36}, {508.77, 84.00}, {513.00, 77.73}, {519.00, 74.48}, {530.00, 74.67}, {545.00, 54.65}, - {554.00, 48.77}, {562.00, 46.39}, {568.00, 45.94}, {568.61, 47.00}, {567.94, 55.00}, {571.27, 64.00}, {572.92, 80.00}, {572.00, 81.39}, {563.00, 79.93}, {556.00, 82.69}, {551.49, 88.00}, {549.00, 95.76}, - {538.00, 93.40}, {530.00, 102.38}, {523.00, 104.00}, {517.00, 103.02}, {516.22, 109.00}, {518.96, 116.00}, {526.00, 121.15}, {534.00, 116.48}, {543.00, 116.77}, {549.28, 121.00}, {554.00, 130.17}, {564.00, 125.67}, - {575.60, 129.00}, {573.31, 121.00}, {567.77, 111.00}, {575.00, 106.47}, {578.51, 102.00}, {580.25, 95.00}, {577.98, 87.00}, {582.00, 85.71}, {597.00, 89.46}, {604.80, 95.00}, {609.28, 104.00}, {610.55, 116.00}, - {609.30, 125.00}, {600.80, 142.00}, {597.31, 155.00}, {584.00, 167.23}, {577.86, 175.00}, {583.52, 184.00}, {582.64, 195.00}, {591.00, 196.56}, {597.81, 201.00}, {607.45, 219.00}, {607.51, 246.00}, {600.00, 275.46}, - {588.00, 267.81}, {579.00, 264.91}, {557.00, 264.41}, {552.98, 259.00}, {548.00, 246.18}, {558.00, 247.12}, {565.98, 244.00}, {571.10, 237.00}, {571.61, 229.00}, {568.25, 222.00}, {562.00, 217.67}, {544.00, 213.93}, - {536.73, 214.00}, {535.60, 204.00}, {539.69, 181.00}, {542.84, 171.00}, {550.43, 161.00}, {540.00, 156.27}, {536.62, 152.00}, {534.70, 146.00}, {527.00, 141.88}, {518.59, 152.00}, {514.51, 160.00}, {510.33, 175.00}, - {519.38, 183.00}, {520.52, 194.00}, {516.00, 201.27}, {505.25, 206.00}, {507.57, 223.00}, {519.90, 260.00}, {529.00, 260.48}, {534.00, 262.94}, {538.38, 268.00}, {540.00, 275.00}, {537.06, 284.00}, {530.00, 289.23}, - {520.00, 289.23}, {513.00, 284.18}, {509.71, 286.00}, {501.69, 298.00}, {501.56, 305.00}, {504.30, 311.00}, {512.00, 316.43}, {521.00, 316.42}, {525.67, 314.00}, {535.00, 304.98}, {562.00, 294.80}, {573.00, 294.81}, - {587.52, 304.00}, {600.89, 310.00}, {596.96, 322.00}, {603.28, 327.00}, {606.52, 333.00}, {605.38, 344.00}, {597.65, 352.00}, {606.36, 375.00}, {607.16, 384.00}, {603.40, 393.00}, {597.00, 398.14}, {577.00, 386.15}, - {564.35, 373.00}, {565.21, 364.00}, {562.81, 350.00}, {553.00, 346.06}, {547.48, 338.00}, {547.48, 330.00}, {550.00, 323.30}, {544.00, 321.53}, {537.00, 322.70}, {532.00, 326.23}, {528.89, 331.00}, {527.83, 338.00}, - {533.02, 356.00}, {542.00, 360.73}, {546.68, 369.00}, {545.38, 379.00}, {537.58, 386.00}, {537.63, 388.00}, {555.00, 407.47}, {563.00, 413.52}, {572.57, 418.00}, {582.72, 426.00}, {578.00, 431.12}, {563.21, 440.00}, - {558.00, 449.27}, {549.00, 452.94}, {541.00, 451.38}, {536.73, 448.00}, {533.00, 441.87}, {520.00, 437.96}, {514.00, 429.69}, {490.00, 415.15}, {472.89, 399.00}, {472.03, 398.00}, {474.00, 396.71}, {486.00, 393.61}, - {492.00, 385.85}, {492.00, 376.15}, {489.04, 371.00}, {485.00, 368.11}, {480.00, 376.27}, {472.00, 379.82}, {463.00, 378.38}, {455.08, 372.00}, {446.00, 377.69}, {439.00, 385.24}, {436.61, 391.00}, {437.52, 404.00}, - {440.00, 409.53}, {463.53, 433.00}, {473.80, 441.00}, {455.00, 440.30}, {443.00, 436.18}, {436.00, 431.98}, {412.00, 440.92}, {397.00, 442.46}, {393.59, 431.00}, {393.71, 412.00}, {400.00, 395.10}, {407.32, 387.00}, - {408.54, 380.00}, {407.42, 375.00}, {403.97, 370.00}, {399.00, 366.74}, {393.00, 365.68}, {391.23, 374.00}, {387.00, 380.27}, {381.00, 383.52}, {371.56, 384.00}, {364.98, 401.00}, {362.96, 412.00}, {363.63, 435.00}, - {345.00, 433.55}, {344.52, 442.00}, {342.06, 447.00}, {337.00, 451.38}, {330.00, 453.00}, {325.00, 452.23}, {318.00, 448.17}, {298.00, 453.70}, {284.00, 451.49}, {278.62, 449.00}, {291.47, 408.00}, {291.77, 398.00}, - {301.00, 393.83}, {305.00, 393.84}, {305.60, 403.00}, {310.00, 409.47}, {318.00, 413.07}, {325.00, 412.40}, {332.31, 407.00}, {335.07, 400.00}, {334.40, 393.00}, {329.00, 385.69}, {319.00, 382.79}, {301.00, 389.23}, - {289.00, 389.97}, {265.00, 389.82}, {251.00, 385.85}, {245.00, 389.23}, {239.00, 389.94}, {233.00, 388.38}, {226.00, 382.04}, {206.00, 374.75}, {206.00, 394.00}, {204.27, 402.00}, {197.00, 401.79}, {191.00, 403.49}, - {186.53, 407.00}, {183.60, 412.00}, {183.60, 422.00}, {189.00, 429.31}, {196.00, 432.07}, {203.00, 431.40}, {209.47, 427.00}, {213.00, 419.72}, {220.00, 420.21}, {227.00, 418.32}, {242.00, 408.41}, {258.98, 409.00}, - {250.00, 435.43}, {239.00, 438.78}, {223.00, 448.19}, {209.00, 449.70}, {205.28, 456.00}, {199.00, 460.23}, {190.00, 460.52}, {182.73, 456.00}, {178.00, 446.27}, {160.00, 441.42}, {148.35, 435.00}, {149.79, 418.00}, - {157.72, 401.00}, {161.00, 396.53}, {177.00, 385.00}, {180.14, 380.00}, {181.11, 374.00}, {180.00, 370.52}, {170.00, 371.68}, {162.72, 368.00}, {158.48, 361.00}, {159.56, 349.00}, {154.00, 342.53}, {146.00, 339.85}, - {136.09, 343.00}, {130.64, 351.00}, {131.74, 362.00}, {140.61, 374.00}, {130.68, 387.00}, {120.75, 409.00}, {118.09, 421.00}, {117.92, 434.00}, {100.00, 432.40}, { 87.00, 427.48}, { 81.59, 423.00}, { 73.64, 409.00}, - { 72.57, 398.00}, { 74.62, 386.00}, { 78.80, 378.00}, { 88.00, 373.43}, { 92.49, 367.00}, { 93.32, 360.00}, { 91.30, 353.00}, {103.00, 342.67}, {109.00, 343.10}, {116.00, 340.44}, {127.33, 330.00}, {143.00, 327.24}, - {154.30, 322.00}, {145.00, 318.06}, {139.77, 311.00}, {139.48, 302.00}, {144.95, 293.00}, {143.00, 291.56}, {134.00, 298.21}, {118.00, 300.75}, {109.40, 305.00}, { 94.67, 319.00}, { 88.00, 318.93}, { 81.00, 321.69}, - { 67.24, 333.00}, { 56.68, 345.00}, { 53.00, 351.40}, { 47.34, 333.00}, { 50.71, 314.00}, { 56.57, 302.00}, { 68.00, 287.96}, { 91.00, 287.24}, {110.00, 282.36}, {133.80, 271.00}, {147.34, 256.00}, {156.47, 251.00}, - {157.26, 250.00}, {154.18, 242.00}, {154.48, 236.00}, {158.72, 229.00}, {166.71, 224.00}, {170.15, 206.00}, {170.19, 196.00}, {167.24, 188.00}, {160.00, 182.67}, {150.00, 182.66}, {143.60, 187.00}, {139.96, 195.00}, - {139.50, 207.00}, {136.45, 221.00}, {136.52, 232.00}, {133.28, 238.00}, {129.00, 241.38}, {119.00, 243.07}, {115.00, 246.55}, {101.00, 253.16}, { 86.00, 257.32}, { 63.00, 259.24}, { 57.00, 257.31}, { 50.54, 252.00}, - { 47.59, 247.00}, { 46.30, 240.00}, { 47.58, 226.00}, { 50.00, 220.57}, { 58.00, 226.41}, { 69.00, 229.17}, { 79.00, 229.08}, { 94.50, 225.00}, {100.21, 231.00}, {107.00, 233.47}, {107.48, 224.00}, {109.94, 219.00}, - {115.00, 214.62}, {122.57, 212.00}, {116.00, 201.49}, {104.00, 194.57}, { 90.00, 194.04}, { 79.00, 198.21}, { 73.00, 198.87}, { 62.68, 191.00}, { 62.58, 184.00}, { 64.42, 179.00}, { 75.00, 167.70}, { 80.39, 157.00}, - { 68.79, 140.00}, { 61.67, 126.00}, { 61.47, 117.00}, { 64.43, 109.00}, { 63.10, 96.00}, { 56.48, 82.00}, { 48.00, 73.88}, { 43.81, 66.00}, { 43.81, 56.00}, { 50.11, 46.00}, { 59.00, 41.55}, { 71.00, 42.64}, - { 78.00, 36.77}, { 83.00, 34.75}, { 99.00, 34.32}, {117.00, 38.92}, {133.00, 55.15}, {142.00, 50.70}, {149.74, 51.00}, {143.55, 68.00}, {153.28, 74.00}, {156.23, 79.00}, {157.00, 84.00}, {156.23, 89.00}, - {153.28, 94.00}, {144.58, 99.00}, {151.52, 112.00}, {151.51, 124.00}, {150.00, 126.36}, {133.00, 130.25}, {126.71, 125.00}, {122.00, 117.25}, {114.00, 116.23}, {107.73, 112.00}, {104.48, 106.00}, {104.32, 99.00}, - {106.94, 93.00}, {111.24, 89.00}, {111.60, 85.00}, {107.24, 73.00}, {102.00, 67.57}, { 99.79, 67.00}, { 99.23, 76.00}, { 95.00, 82.27}, { 89.00, 85.52}, { 79.84, 86.00}, { 86.73, 114.00}, { 98.00, 136.73}, - { 99.00, 137.61}, {109.00, 135.06}, {117.00, 137.94}, {122.52, 146.00}, {122.94, 151.00}, {121.00, 158.58}, {134.00, 160.97}, {153.00, 157.45}, {171.30, 150.00}, {169.06, 142.00}, {169.77, 136.00}, {174.00, 129.73}, - {181.46, 126.00}, {182.22, 120.00}, {182.20, 111.00}, {180.06, 101.00}, {171.28, 85.00}, {171.75, 80.00}, {182.30, 53.00}, {189.47, 50.00}, {190.62, 38.00}, {194.00, 33.73}, {199.00, 30.77}, {208.00, 30.48}, - {216.00, 34.94}, {224.00, 31.47}, {240.00, 30.37}, {247.00, 32.51}, {249.77, 35.00}, {234.75, 53.00}, {213.81, 93.00}, {212.08, 99.00}, {213.00, 101.77}, {220.00, 96.77}, {229.00, 96.48}, {236.28, 101.00}, - {240.00, 107.96}, {245.08, 101.00}, {263.00, 65.32}, {277.47, 48.00}, {284.00, 47.03}, {286.94, 41.00}, {292.00, 36.62}, {298.00, 35.06}, {304.00, 35.77}, {314.00, 43.81}, {342.00, 32.56}, {359.00, 31.32}, - {365.00, 32.57}, {371.00, 36.38}, {379.53, 48.00}, {379.70, 51.00}, {356.00, 52.19}, {347.00, 54.74}, {344.38, 66.00}, {341.00, 70.27}, {335.00, 73.52}, {324.00, 72.38}, {317.00, 65.75}, {313.00, 67.79}, - {307.57, 76.00}, {315.00, 78.62}, {319.28, 82.00}, {322.23, 87.00}, {323.00, 94.41}, {334.00, 92.49}, {347.00, 87.47}, {349.62, 80.00}, {353.00, 75.73}, {359.00, 72.48}, {366.00, 72.32}, {372.00, 74.94}, - {377.00, 81.34}, {382.00, 83.41}, {392.00, 83.40}, {399.00, 79.15}, {404.00, 85.74}, {411.00, 85.06}, {417.00, 86.62}, {423.38, 93.00}, {425.05, 104.00}, {438.00, 110.35}, {450.00, 112.17}, {452.62, 103.00}, - {456.00, 98.73}, {462.00, 95.48}, {472.00, 95.79}, {471.28, 92.00}, {464.00, 84.62}, {445.00, 80.39}, {436.00, 75.33}, {428.00, 68.46}, {419.00, 68.52}, {413.00, 65.27}, {408.48, 58.00}, {409.87, 46.00}, - {404.42, 39.00}, {408.00, 33.88}, {415.00, 29.31}, {429.00, 26.45}, {455.00, 28.77}, {470.00, 33.81}, {482.00, 42.16}, {494.00, 46.85}, {499.65, 36.00}, {513.00, 25.95}, {529.00, 22.42}, {537.18, 23.00}, + {537.18, 23.00}, {520.50, 36.00}, {501.53, 63.00}, {496.14, 76.00}, {498.86, 86.00}, {504.00, 90.51}, + {508.00, 91.36}, {508.77, 84.00}, {513.00, 77.73}, {519.00, 74.48}, {530.00, 74.67}, {545.00, 54.65}, + {554.00, 48.77}, {562.00, 46.39}, {568.00, 45.94}, {568.61, 47.00}, {567.94, 55.00}, {571.27, 64.00}, + {572.92, 80.00}, {572.00, 81.39}, {563.00, 79.93}, {556.00, 82.69}, {551.49, 88.00}, {549.00, 95.76}, + {538.00, 93.40}, {530.00, 102.38}, {523.00, 104.00}, {517.00, 103.02}, {516.22, 109.00}, {518.96, 116.00}, + {526.00, 121.15}, {534.00, 116.48}, {543.00, 116.77}, {549.28, 121.00}, {554.00, 130.17}, {564.00, 125.67}, + {575.60, 129.00}, {573.31, 121.00}, {567.77, 111.00}, {575.00, 106.47}, {578.51, 102.00}, {580.25, 95.00}, + {577.98, 87.00}, {582.00, 85.71}, {597.00, 89.46}, {604.80, 95.00}, {609.28, 104.00}, {610.55, 116.00}, + {609.30, 125.00}, {600.80, 142.00}, {597.31, 155.00}, {584.00, 167.23}, {577.86, 175.00}, {583.52, 184.00}, + {582.64, 195.00}, {591.00, 196.56}, {597.81, 201.00}, {607.45, 219.00}, {607.51, 246.00}, {600.00, 275.46}, + {588.00, 267.81}, {579.00, 264.91}, {557.00, 264.41}, {552.98, 259.00}, {548.00, 246.18}, {558.00, 247.12}, + {565.98, 244.00}, {571.10, 237.00}, {571.61, 229.00}, {568.25, 222.00}, {562.00, 217.67}, {544.00, 213.93}, + {536.73, 214.00}, {535.60, 204.00}, {539.69, 181.00}, {542.84, 171.00}, {550.43, 161.00}, {540.00, 156.27}, + {536.62, 152.00}, {534.70, 146.00}, {527.00, 141.88}, {518.59, 152.00}, {514.51, 160.00}, {510.33, 175.00}, + {519.38, 183.00}, {520.52, 194.00}, {516.00, 201.27}, {505.25, 206.00}, {507.57, 223.00}, {519.90, 260.00}, + {529.00, 260.48}, {534.00, 262.94}, {538.38, 268.00}, {540.00, 275.00}, {537.06, 284.00}, {530.00, 289.23}, + {520.00, 289.23}, {513.00, 284.18}, {509.71, 286.00}, {501.69, 298.00}, {501.56, 305.00}, {504.30, 311.00}, + {512.00, 316.43}, {521.00, 316.42}, {525.67, 314.00}, {535.00, 304.98}, {562.00, 294.80}, {573.00, 294.81}, + {587.52, 304.00}, {600.89, 310.00}, {596.96, 322.00}, {603.28, 327.00}, {606.52, 333.00}, {605.38, 344.00}, + {597.65, 352.00}, {606.36, 375.00}, {607.16, 384.00}, {603.40, 393.00}, {597.00, 398.14}, {577.00, 386.15}, + {564.35, 373.00}, {565.21, 364.00}, {562.81, 350.00}, {553.00, 346.06}, {547.48, 338.00}, {547.48, 330.00}, + {550.00, 323.30}, {544.00, 321.53}, {537.00, 322.70}, {532.00, 326.23}, {528.89, 331.00}, {527.83, 338.00}, + {533.02, 356.00}, {542.00, 360.73}, {546.68, 369.00}, {545.38, 379.00}, {537.58, 386.00}, {537.63, 388.00}, + {555.00, 407.47}, {563.00, 413.52}, {572.57, 418.00}, {582.72, 426.00}, {578.00, 431.12}, {563.21, 440.00}, + {558.00, 449.27}, {549.00, 452.94}, {541.00, 451.38}, {536.73, 448.00}, {533.00, 441.87}, {520.00, 437.96}, + {514.00, 429.69}, {490.00, 415.15}, {472.89, 399.00}, {472.03, 398.00}, {474.00, 396.71}, {486.00, 393.61}, + {492.00, 385.85}, {492.00, 376.15}, {489.04, 371.00}, {485.00, 368.11}, {480.00, 376.27}, {472.00, 379.82}, + {463.00, 378.38}, {455.08, 372.00}, {446.00, 377.69}, {439.00, 385.24}, {436.61, 391.00}, {437.52, 404.00}, + {440.00, 409.53}, {463.53, 433.00}, {473.80, 441.00}, {455.00, 440.30}, {443.00, 436.18}, {436.00, 431.98}, + {412.00, 440.92}, {397.00, 442.46}, {393.59, 431.00}, {393.71, 412.00}, {400.00, 395.10}, {407.32, 387.00}, + {408.54, 380.00}, {407.42, 375.00}, {403.97, 370.00}, {399.00, 366.74}, {393.00, 365.68}, {391.23, 374.00}, + {387.00, 380.27}, {381.00, 383.52}, {371.56, 384.00}, {364.98, 401.00}, {362.96, 412.00}, {363.63, 435.00}, + {345.00, 433.55}, {344.52, 442.00}, {342.06, 447.00}, {337.00, 451.38}, {330.00, 453.00}, {325.00, 452.23}, + {318.00, 448.17}, {298.00, 453.70}, {284.00, 451.49}, {278.62, 449.00}, {291.47, 408.00}, {291.77, 398.00}, + {301.00, 393.83}, {305.00, 393.84}, {305.60, 403.00}, {310.00, 409.47}, {318.00, 413.07}, {325.00, 412.40}, + {332.31, 407.00}, {335.07, 400.00}, {334.40, 393.00}, {329.00, 385.69}, {319.00, 382.79}, {301.00, 389.23}, + {289.00, 389.97}, {265.00, 389.82}, {251.00, 385.85}, {245.00, 389.23}, {239.00, 389.94}, {233.00, 388.38}, + {226.00, 382.04}, {206.00, 374.75}, {206.00, 394.00}, {204.27, 402.00}, {197.00, 401.79}, {191.00, 403.49}, + {186.53, 407.00}, {183.60, 412.00}, {183.60, 422.00}, {189.00, 429.31}, {196.00, 432.07}, {203.00, 431.40}, + {209.47, 427.00}, {213.00, 419.72}, {220.00, 420.21}, {227.00, 418.32}, {242.00, 408.41}, {258.98, 409.00}, + {250.00, 435.43}, {239.00, 438.78}, {223.00, 448.19}, {209.00, 449.70}, {205.28, 456.00}, {199.00, 460.23}, + {190.00, 460.52}, {182.73, 456.00}, {178.00, 446.27}, {160.00, 441.42}, {148.35, 435.00}, {149.79, 418.00}, + {157.72, 401.00}, {161.00, 396.53}, {177.00, 385.00}, {180.14, 380.00}, {181.11, 374.00}, {180.00, 370.52}, + {170.00, 371.68}, {162.72, 368.00}, {158.48, 361.00}, {159.56, 349.00}, {154.00, 342.53}, {146.00, 339.85}, + {136.09, 343.00}, {130.64, 351.00}, {131.74, 362.00}, {140.61, 374.00}, {130.68, 387.00}, {120.75, 409.00}, + {118.09, 421.00}, {117.92, 434.00}, {100.00, 432.40}, {87.00, 427.48}, {81.59, 423.00}, {73.64, 409.00}, + {72.57, 398.00}, {74.62, 386.00}, {78.80, 378.00}, {88.00, 373.43}, {92.49, 367.00}, {93.32, 360.00}, + {91.30, 353.00}, {103.00, 342.67}, {109.00, 343.10}, {116.00, 340.44}, {127.33, 330.00}, {143.00, 327.24}, + {154.30, 322.00}, {145.00, 318.06}, {139.77, 311.00}, {139.48, 302.00}, {144.95, 293.00}, {143.00, 291.56}, + {134.00, 298.21}, {118.00, 300.75}, {109.40, 305.00}, {94.67, 319.00}, {88.00, 318.93}, {81.00, 321.69}, + {67.24, 333.00}, {56.68, 345.00}, {53.00, 351.40}, {47.34, 333.00}, {50.71, 314.00}, {56.57, 302.00}, + {68.00, 287.96}, {91.00, 287.24}, {110.00, 282.36}, {133.80, 271.00}, {147.34, 256.00}, {156.47, 251.00}, + {157.26, 250.00}, {154.18, 242.00}, {154.48, 236.00}, {158.72, 229.00}, {166.71, 224.00}, {170.15, 206.00}, + {170.19, 196.00}, {167.24, 188.00}, {160.00, 182.67}, {150.00, 182.66}, {143.60, 187.00}, {139.96, 195.00}, + {139.50, 207.00}, {136.45, 221.00}, {136.52, 232.00}, {133.28, 238.00}, {129.00, 241.38}, {119.00, 243.07}, + {115.00, 246.55}, {101.00, 253.16}, {86.00, 257.32}, {63.00, 259.24}, {57.00, 257.31}, {50.54, 252.00}, + {47.59, 247.00}, {46.30, 240.00}, {47.58, 226.00}, {50.00, 220.57}, {58.00, 226.41}, {69.00, 229.17}, + {79.00, 229.08}, {94.50, 225.00}, {100.21, 231.00}, {107.00, 233.47}, {107.48, 224.00}, {109.94, 219.00}, + {115.00, 214.62}, {122.57, 212.00}, {116.00, 201.49}, {104.00, 194.57}, {90.00, 194.04}, {79.00, 198.21}, + {73.00, 198.87}, {62.68, 191.00}, {62.58, 184.00}, {64.42, 179.00}, {75.00, 167.70}, {80.39, 157.00}, + {68.79, 140.00}, {61.67, 126.00}, {61.47, 117.00}, {64.43, 109.00}, {63.10, 96.00}, {56.48, 82.00}, + {48.00, 73.88}, {43.81, 66.00}, {43.81, 56.00}, {50.11, 46.00}, {59.00, 41.55}, {71.00, 42.64}, + {78.00, 36.77}, {83.00, 34.75}, {99.00, 34.32}, {117.00, 38.92}, {133.00, 55.15}, {142.00, 50.70}, + {149.74, 51.00}, {143.55, 68.00}, {153.28, 74.00}, {156.23, 79.00}, {157.00, 84.00}, {156.23, 89.00}, + {153.28, 94.00}, {144.58, 99.00}, {151.52, 112.00}, {151.51, 124.00}, {150.00, 126.36}, {133.00, 130.25}, + {126.71, 125.00}, {122.00, 117.25}, {114.00, 116.23}, {107.73, 112.00}, {104.48, 106.00}, {104.32, 99.00}, + {106.94, 93.00}, {111.24, 89.00}, {111.60, 85.00}, {107.24, 73.00}, {102.00, 67.57}, {99.79, 67.00}, + {99.23, 76.00}, {95.00, 82.27}, {89.00, 85.52}, {79.84, 86.00}, {86.73, 114.00}, {98.00, 136.73}, + {99.00, 137.61}, {109.00, 135.06}, {117.00, 137.94}, {122.52, 146.00}, {122.94, 151.00}, {121.00, 158.58}, + {134.00, 160.97}, {153.00, 157.45}, {171.30, 150.00}, {169.06, 142.00}, {169.77, 136.00}, {174.00, 129.73}, + {181.46, 126.00}, {182.22, 120.00}, {182.20, 111.00}, {180.06, 101.00}, {171.28, 85.00}, {171.75, 80.00}, + {182.30, 53.00}, {189.47, 50.00}, {190.62, 38.00}, {194.00, 33.73}, {199.00, 30.77}, {208.00, 30.48}, + {216.00, 34.94}, {224.00, 31.47}, {240.00, 30.37}, {247.00, 32.51}, {249.77, 35.00}, {234.75, 53.00}, + {213.81, 93.00}, {212.08, 99.00}, {213.00, 101.77}, {220.00, 96.77}, {229.00, 96.48}, {236.28, 101.00}, + {240.00, 107.96}, {245.08, 101.00}, {263.00, 65.32}, {277.47, 48.00}, {284.00, 47.03}, {286.94, 41.00}, + {292.00, 36.62}, {298.00, 35.06}, {304.00, 35.77}, {314.00, 43.81}, {342.00, 32.56}, {359.00, 31.32}, + {365.00, 32.57}, {371.00, 36.38}, {379.53, 48.00}, {379.70, 51.00}, {356.00, 52.19}, {347.00, 54.74}, + {344.38, 66.00}, {341.00, 70.27}, {335.00, 73.52}, {324.00, 72.38}, {317.00, 65.75}, {313.00, 67.79}, + {307.57, 76.00}, {315.00, 78.62}, {319.28, 82.00}, {322.23, 87.00}, {323.00, 94.41}, {334.00, 92.49}, + {347.00, 87.47}, {349.62, 80.00}, {353.00, 75.73}, {359.00, 72.48}, {366.00, 72.32}, {372.00, 74.94}, + {377.00, 81.34}, {382.00, 83.41}, {392.00, 83.40}, {399.00, 79.15}, {404.00, 85.74}, {411.00, 85.06}, + {417.00, 86.62}, {423.38, 93.00}, {425.05, 104.00}, {438.00, 110.35}, {450.00, 112.17}, {452.62, 103.00}, + {456.00, 98.73}, {462.00, 95.48}, {472.00, 95.79}, {471.28, 92.00}, {464.00, 84.62}, {445.00, 80.39}, + {436.00, 75.33}, {428.00, 68.46}, {419.00, 68.52}, {413.00, 65.27}, {408.48, 58.00}, {409.87, 46.00}, + {404.42, 39.00}, {408.00, 33.88}, {415.00, 29.31}, {429.00, 26.45}, {455.00, 28.77}, {470.00, 33.81}, + {482.00, 42.16}, {494.00, 46.85}, {499.65, 36.00}, {513.00, 25.95}, {529.00, 22.42}, {537.18, 23.00}, }; -static int bouncy_terrain_count = sizeof(bouncy_terrain_verts)/sizeof(cpVect); - -static cpSpace *init_BouncyTerrainCircles_500(void){ - cpSpace *space = BENCH_SPACE_NEW(); - cpSpaceSetIterations(space, 10); - - cpVect offset = cpv(-320, -240); - for(int i=0; i<(bouncy_terrain_count - 1); i++){ - cpVect a = bouncy_terrain_verts[i], b = bouncy_terrain_verts[i+1]; - cpShape *shape = cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpvadd(a, offset), cpvadd(b, offset), 0.0f)); - cpShapeSetElasticity(shape, 1.0); - } - - for(int i=0; i<500; i++){ - cpFloat radius = 5.0f; - cpFloat mass = radius*radius; - cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); - cpBodySetPosition(body, cpvadd(cpvmult(frand_unit_circle(), 130.0f), cpvzero)); - cpBodySetVelocity(body, cpvmult(frand_unit_circle(), 50.0f)); - - cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); - cpShapeSetElasticity(shape, 1.0); - } - - return space; +static int bouncy_terrain_count = sizeof(bouncy_terrain_verts) / sizeof(cpVect); + +static cpSpace* init_BouncyTerrainCircles_500(void) +{ + cpSpace* space = BENCH_SPACE_NEW(); + cpSpaceSetIterations(space, 10); + + cpVect offset = cpv(-320, -240); + for (int i = 0; i < (bouncy_terrain_count - 1); i++) + { + cpVect a = bouncy_terrain_verts[i], b = bouncy_terrain_verts[i + 1]; + cpShape* shape = cpSpaceAddShape( + space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpvadd(a, offset), cpvadd(b, offset), 0.0f)); + cpShapeSetElasticity(shape, 1.0); + } + + for (int i = 0; i < 500; i++) + { + cpFloat radius = 5.0f; + cpFloat mass = radius * radius; + cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); + cpBodySetPosition(body, cpvadd(cpvmult(frand_unit_circle(), 130.0f), cpvzero)); + cpBodySetVelocity(body, cpvmult(frand_unit_circle(), 50.0f)); + + cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); + cpShapeSetElasticity(shape, 1.0); + } + + return space; } -static cpSpace *init_BouncyTerrainHexagons_500(void){ - cpSpace *space = BENCH_SPACE_NEW(); - cpSpaceSetIterations(space, 10); - - cpVect offset = cpv(-320, -240); - for(int i=0; i<(bouncy_terrain_count - 1); i++){ - cpVect a = bouncy_terrain_verts[i], b = bouncy_terrain_verts[i+1]; - cpShape *shape = cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpvadd(a, offset), cpvadd(b, offset), 0.0f)); - cpShapeSetElasticity(shape, 1.0); - } - - cpFloat radius = 5.0f; - cpVect hexagon[6]; - for(int i=0; i<6; i++){ - cpFloat angle = -CP_PI*2.0f*i/6.0f; - hexagon[i] = cpvmult(cpv(cos(angle), sin(angle)), radius - bevel); - } - - for(int i=0; i<500; i++){ - cpFloat mass = radius*radius; - cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 6, hexagon, cpvzero, 0.0f))); - cpBodySetPosition(body, cpvadd(cpvmult(frand_unit_circle(), 130.0f), cpvzero)); - cpBodySetVelocity(body, cpvmult(frand_unit_circle(), 50.0f)); - - cpShape *shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 6, hexagon, cpTransformIdentity, bevel)); - cpShapeSetElasticity(shape, 1.0); - } - - return space; +static cpSpace* init_BouncyTerrainHexagons_500(void) +{ + cpSpace* space = BENCH_SPACE_NEW(); + cpSpaceSetIterations(space, 10); + + cpVect offset = cpv(-320, -240); + for (int i = 0; i < (bouncy_terrain_count - 1); i++) + { + cpVect a = bouncy_terrain_verts[i], b = bouncy_terrain_verts[i + 1]; + cpShape* shape = cpSpaceAddShape( + space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpvadd(a, offset), cpvadd(b, offset), 0.0f)); + cpShapeSetElasticity(shape, 1.0); + } + + cpFloat radius = 5.0f; + cpVect hexagon[6]; + for (int i = 0; i < 6; i++) + { + cpFloat angle = -CP_PI * 2.0f * i / 6.0f; + hexagon[i] = cpvmult(cpv(cos(angle), sin(angle)), radius - bevel); + } + + for (int i = 0; i < 500; i++) + { + cpFloat mass = radius * radius; + cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 6, hexagon, cpvzero, 0.0f))); + cpBodySetPosition(body, cpvadd(cpvmult(frand_unit_circle(), 130.0f), cpvzero)); + cpBodySetVelocity(body, cpvmult(frand_unit_circle(), 50.0f)); + + cpShape* shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 6, hexagon, cpTransformIdentity, bevel)); + cpShapeSetElasticity(shape, 1.0); + } + + return space; } - // No collisions static cpFloat pentagon_mass = 0.0f; static cpFloat pentagon_moment = 0.0f; -static cpBool NoCollide_begin(cpArbiter *arb, cpSpace *space, void *data){ - - // CCLOG("NoCollide_begin"); - - return cpTrue; -} +static cpBool NoCollide_begin(cpArbiter* arb, cpSpace* space, void* data) +{ + // CCLOG("NoCollide_begin"); -static cpSpace *init_NoCollide(void){ - cpSpace *space = BENCH_SPACE_NEW(); - cpSpaceSetIterations(space, 10); - - cpCollisionHandler *handler = cpSpaceAddCollisionHandler(space, 2, 2); - handler->beginFunc = NoCollide_begin; - - - float radius = 4.5f; - - cpShapeSetElasticity(cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpv(-330-radius, -250-radius), cpv( 330+radius, -250-radius), 0.0f)), 1.0f); - cpShapeSetElasticity(cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpv( 330+radius, 250+radius), cpv( 330+radius, -250-radius), 0.0f)), 1.0f); - cpShapeSetElasticity(cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpv( 330+radius, 250+radius), cpv(-330-radius, 250+radius), 0.0f)), 1.0f); - cpShapeSetElasticity(cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpv(-330-radius, -250-radius), cpv(-330-radius, 250+radius), 0.0f)), 1.0f); - - for(int x=-320; x<=320; x+=20){ - for(int y=-240; y<=240; y+=20){ - cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(cpSpaceGetStaticBody(space), radius, cpv(x, y))); - cpShapeSetElasticity(shape, 1.0); - cpShapeSetCollisionType(shape, 2); - } - } - - for(int y=10-240; y<=240; y+=40){ - cpFloat mass = 7.0f; - cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); - cpBodySetPosition(body, cpv(-320.0f, y)); - cpBodySetVelocity(body, cpv(100.0f, 0.0f)); - - cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); - cpShapeSetElasticity(shape, 1.0); - cpShapeSetCollisionType(shape, 2); - } - - for(int x=30-320; x<=320; x+=40){ - cpFloat mass = 7.0f; - cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); - cpBodySetPosition(body, cpv(x, -240.0f)); - cpBodySetVelocity(body, cpv(0.0f, 100.0f)); - - cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); - cpShapeSetElasticity(shape, 1.0); - cpShapeSetCollisionType(shape, 2); - } - - return space; + return cpTrue; } +static cpSpace* init_NoCollide(void) +{ + cpSpace* space = BENCH_SPACE_NEW(); + cpSpaceSetIterations(space, 10); + + cpCollisionHandler* handler = cpSpaceAddCollisionHandler(space, 2, 2); + handler->beginFunc = NoCollide_begin; + + float radius = 4.5f; + + cpShapeSetElasticity( + cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpv(-330 - radius, -250 - radius), + cpv(330 + radius, -250 - radius), 0.0f)), + 1.0f); + cpShapeSetElasticity( + cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpv(330 + radius, 250 + radius), + cpv(330 + radius, -250 - radius), 0.0f)), + 1.0f); + cpShapeSetElasticity( + cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpv(330 + radius, 250 + radius), + cpv(-330 - radius, 250 + radius), 0.0f)), + 1.0f); + cpShapeSetElasticity( + cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpv(-330 - radius, -250 - radius), + cpv(-330 - radius, 250 + radius), 0.0f)), + 1.0f); + + for (int x = -320; x <= 320; x += 20) + { + for (int y = -240; y <= 240; y += 20) + { + cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(cpSpaceGetStaticBody(space), radius, cpv(x, y))); + cpShapeSetElasticity(shape, 1.0); + cpShapeSetCollisionType(shape, 2); + } + } + + for (int y = 10 - 240; y <= 240; y += 40) + { + cpFloat mass = 7.0f; + cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); + cpBodySetPosition(body, cpv(-320.0f, y)); + cpBodySetVelocity(body, cpv(100.0f, 0.0f)); + + cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); + cpShapeSetElasticity(shape, 1.0); + cpShapeSetCollisionType(shape, 2); + } + + for (int x = 30 - 320; x <= 320; x += 40) + { + cpFloat mass = 7.0f; + cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); + cpBodySetPosition(body, cpv(x, -240.0f)); + cpBodySetVelocity(body, cpv(0.0f, 100.0f)); + + cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); + cpShapeSetElasticity(shape, 1.0); + cpShapeSetCollisionType(shape, 2); + } + + return space; +} // TODO ideas: // addition/removal // Memory usage? (too small to matter?) // http://forums.tigsource.com/index.php?topic=18077.msg518578#msg518578 - // Build benchmark list -static void update(cpSpace *space, double dt){ - BENCH_SPACE_STEP(space, dt); +static void update(cpSpace* space, double dt) +{ + BENCH_SPACE_STEP(space, dt); } -static void destroy(cpSpace *space){ - ChipmunkDemoFreeSpaceChildren(space); - BENCH_SPACE_FREE(space); +static void destroy(cpSpace* space) +{ + ChipmunkDemoFreeSpaceChildren(space); + BENCH_SPACE_FREE(space); } // Make a second demo declaration for this demo to use in the regular demo set. ChipmunkDemo BouncyHexagons = { - "Bouncy Hexagons", - 1.0/60.0, - init_BouncyTerrainHexagons_500, - update, - ChipmunkDemoDefaultDrawImpl, - destroy, + "Bouncy Hexagons", 1.0 / 60.0, init_BouncyTerrainHexagons_500, update, ChipmunkDemoDefaultDrawImpl, destroy, }; -#define BENCH(n) {#n, 1.0/60.0, init_##n, update, ChipmunkDemoDefaultDrawImpl, destroy} +#define BENCH(n) \ + { \ +# n, 1.0 / 60.0, init_##n, update, ChipmunkDemoDefaultDrawImpl, destroy \ + } ChipmunkDemo bench_list[] = { - BENCH(SimpleTerrainCircles_1000), - BENCH(SimpleTerrainCircles_500), - BENCH(SimpleTerrainCircles_100), - BENCH(SimpleTerrainBoxes_1000), - BENCH(SimpleTerrainBoxes_500), - BENCH(SimpleTerrainBoxes_100), - BENCH(SimpleTerrainHexagons_1000), - BENCH(SimpleTerrainHexagons_500), - BENCH(SimpleTerrainHexagons_100), - BENCH(SimpleTerrainVCircles_200), - BENCH(SimpleTerrainVBoxes_200), - BENCH(SimpleTerrainVHexagons_200), - BENCH(ComplexTerrainCircles_1000), - BENCH(ComplexTerrainHexagons_1000), - BENCH(BouncyTerrainCircles_500), - BENCH(BouncyTerrainHexagons_500), - BENCH(NoCollide), + BENCH(SimpleTerrainCircles_1000), + BENCH(SimpleTerrainCircles_500), + BENCH(SimpleTerrainCircles_100), + BENCH(SimpleTerrainBoxes_1000), + BENCH(SimpleTerrainBoxes_500), + BENCH(SimpleTerrainBoxes_100), + BENCH(SimpleTerrainHexagons_1000), + BENCH(SimpleTerrainHexagons_500), + BENCH(SimpleTerrainHexagons_100), + BENCH(SimpleTerrainVCircles_200), + BENCH(SimpleTerrainVBoxes_200), + BENCH(SimpleTerrainVHexagons_200), + BENCH(ComplexTerrainCircles_1000), + BENCH(ComplexTerrainHexagons_1000), + BENCH(BouncyTerrainCircles_500), + BENCH(BouncyTerrainHexagons_500), + BENCH(NoCollide), }; -int bench_count = sizeof(bench_list)/sizeof(ChipmunkDemo); +int bench_count = sizeof(bench_list) / sizeof(ChipmunkDemo); diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Buoyancy.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Buoyancy.c index 71b607e7790a..05224adbf800 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Buoyancy.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Buoyancy.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -23,10 +23,9 @@ #include "ChipmunkDemo.h" -static void -update(cpSpace *space, double dt) +static void update(cpSpace* space, double dt) { - cpSpaceStep(space, dt); + cpSpaceStep(space, dt); } #define FLUID_DENSITY 0.00014 @@ -35,193 +34,187 @@ update(cpSpace *space, double dt) char messageBuffer[1024]; // Modified from chipmunk_private.h -static inline cpFloat -k_scalar_body(cpBody *body, cpVect point, cpVect n) +static inline cpFloat k_scalar_body(cpBody* body, cpVect point, cpVect n) { - cpFloat rcn = cpvcross(cpvsub(point, cpBodyGetPosition(body)), n); - return 1.0f/cpBodyGetMass(body) + rcn*rcn/cpBodyGetMoment(body); + cpFloat rcn = cpvcross(cpvsub(point, cpBodyGetPosition(body)), n); + return 1.0f / cpBodyGetMass(body) + rcn * rcn / cpBodyGetMoment(body); } -static cpBool -waterPreSolve(cpArbiter *arb, cpSpace *space, void *ptr) +static cpBool waterPreSolve(cpArbiter* arb, cpSpace* space, void* ptr) { - CP_ARBITER_GET_SHAPES(arb, water, poly); - cpBody *body = cpShapeGetBody(poly); - - // Get the top of the water sensor bounding box to use as the water level. - cpFloat level = cpShapeGetBB(water).t; - - // Clip the polygon against the water level - int count = cpPolyShapeGetCount(poly); - int clippedCount = 0; + CP_ARBITER_GET_SHAPES(arb, water, poly); + cpBody* body = cpShapeGetBody(poly); + + // Get the top of the water sensor bounding box to use as the water level. + cpFloat level = cpShapeGetBB(water).t; + + // Clip the polygon against the water level + int count = cpPolyShapeGetCount(poly); + int clippedCount = 0; #ifdef _MSC_VER - // MSVC is pretty much the only compiler in existence that doesn't support variable sized arrays. - cpVect clipped[10]; + // MSVC is pretty much the only compiler in existence that doesn't support variable sized arrays. + cpVect clipped[10]; #else - cpVect clipped[count + 1]; + cpVect clipped[count + 1]; #endif - for(int i=0, j=count-1; ipreSolveFunc = (cpCollisionPreSolveFunc)waterPreSolve; - - return space; + ChipmunkDemoMessageString = messageBuffer; + + cpSpace* space = cpSpaceNew(); + cpSpaceSetIterations(space, 30); + cpSpaceSetGravity(space, cpv(0, -500)); + // cpSpaceSetDamping(space, 0.5); + cpSpaceSetSleepTimeThreshold(space, 0.5f); + cpSpaceSetCollisionSlop(space, 0.5f); + + cpBody *body, *staticBody = cpSpaceGetStaticBody(space); + cpShape* shape; + + // Create segments around the edge of the screen. + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(-320, 240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320, -240), cpv(320, 240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(320, -240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, 240), cpv(320, 240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + { + // Add the edges of the bucket + cpBB bb = cpBBNew(-300, -200, 100, 0); + cpFloat radius = 5.0f; + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(bb.l, bb.b), cpv(bb.l, bb.t), radius)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(bb.r, bb.b), cpv(bb.r, bb.t), radius)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(bb.l, bb.b), cpv(bb.r, bb.b), radius)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + // Add the sensor for the water. + shape = cpSpaceAddShape(space, cpBoxShapeNew2(staticBody, bb, 0.0)); + cpShapeSetSensor(shape, cpTrue); + cpShapeSetCollisionType(shape, 1); + } + + { + cpFloat width = 200.0f; + cpFloat height = 50.0f; + cpFloat mass = 0.3 * FLUID_DENSITY * width * height; + cpFloat moment = cpMomentForBox(mass, width, height); + + body = cpSpaceAddBody(space, cpBodyNew(mass, moment)); + cpBodySetPosition(body, cpv(-50, -100)); + cpBodySetVelocity(body, cpv(0, -100)); + cpBodySetAngularVelocity(body, 1); + + shape = cpSpaceAddShape(space, cpBoxShapeNew(body, width, height, 0.0)); + cpShapeSetFriction(shape, 0.8f); + } + + { + cpFloat width = 40.0f; + cpFloat height = width * 2; + cpFloat mass = 0.3 * FLUID_DENSITY * width * height; + cpFloat moment = cpMomentForBox(mass, width, height); + + body = cpSpaceAddBody(space, cpBodyNew(mass, moment)); + cpBodySetPosition(body, cpv(-200, -50)); + cpBodySetVelocity(body, cpv(0, -100)); + cpBodySetAngularVelocity(body, 1); + + shape = cpSpaceAddShape(space, cpBoxShapeNew(body, width, height, 0.0)); + cpShapeSetFriction(shape, 0.8f); + } + + cpCollisionHandler* handler = cpSpaceAddCollisionHandler(space, 1, 0); + handler->preSolveFunc = (cpCollisionPreSolveFunc)waterPreSolve; + + return space; } -static void -destroy(cpSpace *space) +static void destroy(cpSpace* space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo Buoyancy = { - "Simple Sensor based fluids.", - 1.0/180.0, - init, - update, - ChipmunkDemoDefaultDrawImpl, - destroy, + "Simple Sensor based fluids.", 1.0 / 180.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Chains.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Chains.c index e1c727060bf8..41cbf8cd2a11 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Chains.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Chains.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,133 +18,132 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" #define CHAIN_COUNT 8 #define LINK_COUNT 10 -static void -BreakablejointPostStepRemove(cpSpace *space, cpConstraint *joint, void *unused) +static void BreakablejointPostStepRemove(cpSpace* space, cpConstraint* joint, void* unused) { - cpSpaceRemoveConstraint(space, joint); - cpConstraintFree(joint); + cpSpaceRemoveConstraint(space, joint); + cpConstraintFree(joint); } -static void -BreakableJointPostSolve(cpConstraint *joint, cpSpace *space) +static void BreakableJointPostSolve(cpConstraint* joint, cpSpace* space) { - cpFloat dt = cpSpaceGetCurrentTimeStep(space); - - // Convert the impulse to a force by dividing it by the timestep. - cpFloat force = cpConstraintGetImpulse(joint)/dt; - cpFloat maxForce = cpConstraintGetMaxForce(joint); - - // If the force is almost as big as the joint's max force, break it. - if(force > 0.9*maxForce){ - cpSpaceAddPostStepCallback(space, (cpPostStepFunc)BreakablejointPostStepRemove, joint, NULL); - } + cpFloat dt = cpSpaceGetCurrentTimeStep(space); + + // Convert the impulse to a force by dividing it by the timestep. + cpFloat force = cpConstraintGetImpulse(joint) / dt; + cpFloat maxForce = cpConstraintGetMaxForce(joint); + + // If the force is almost as big as the joint's max force, break it. + if (force > 0.9 * maxForce) + { + cpSpaceAddPostStepCallback(space, (cpPostStepFunc)BreakablejointPostStepRemove, joint, NULL); + } } -static void -update(cpSpace *space, double dt) +static void update(cpSpace* space, double dt) { - cpSpaceStep(space, dt); + cpSpaceStep(space, dt); } -static cpSpace * -init(void) +static cpSpace* init(void) { - cpSpace *space = cpSpaceNew(); - cpSpaceSetIterations(space, 30); - cpSpaceSetGravity(space, cpv(0, -100)); - cpSpaceSetSleepTimeThreshold(space, 0.5f); - - cpBody *body, *staticBody = cpSpaceGetStaticBody(space); - cpShape *shape; - - // Create segments around the edge of the screen. - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(-320,240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320,-240), cpv(320,240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,240), cpv(320,240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - cpFloat mass = 1; - cpFloat width = 20; - cpFloat height = 30; - - cpFloat spacing = width*0.3; - - // Add lots of boxes. - for(int i=0; imagnitudeSum += cpvlength(j); - context->vectorSum = cpvadd(context->vectorSum, j); + cpVect j = cpArbiterTotalImpulse(arb); + context->magnitudeSum += cpvlength(j); + context->vectorSum = cpvadd(context->vectorSum, j); } #endif -static void -update(cpSpace *space, double dt) +static void update(cpSpace* space, double dt) { - cpSpaceStep(space, dt); - - ChipmunkDemoPrintString("Place objects on the scale to weigh them. The ball marks the shapes it's sitting on.\n"); - - // Sum the total impulse applied to the scale from all collision pairs in the contact graph. - // If your compiler supports blocks, your life is a little easier. - // You can use the "Block" versions of the functions without needing the callbacks above. - #if USE_BLOCKS - __block cpVect impulseSum = cpvzero; - cpBodyEachArbiter_b(scaleStaticBody, ^(cpArbiter *arb){ - impulseSum = cpvadd(impulseSum, cpArbiterTotalImpulse(arb)); - }); - #else - cpVect impulseSum = cpvzero; - cpBodyEachArbiter(scaleStaticBody, (cpBodyArbiterIteratorFunc)ScaleIterator, &impulseSum); - #endif - - // Force is the impulse divided by the timestep. - cpFloat force = cpvlength(impulseSum)/dt; - - // Weight can be found similarly from the gravity vector. - cpVect g = cpSpaceGetGravity(space); - cpFloat weight = cpvdot(g, impulseSum)/(cpvlengthsq(g)*dt); - - ChipmunkDemoPrintString("Total force: %5.2f, Total weight: %5.2f. ", force, weight); - - - // Highlight and count the number of shapes the ball is touching. - #if USE_BLOCKS - __block int count = 0; - cpBodyEachArbiter_b(ballBody, ^(cpArbiter *arb){ - // body is the body we are iterating the arbiters for. - // CP_ARBITER_GET_*() in an arbiter iterator always returns the body/shape for the iterated body first. - CP_ARBITER_GET_SHAPES(arb, ball, other); - ChipmunkDebugDrawBB(cpShapeGetBB(other), RGBAColor(1, 0, 0, 1)); - - count++; - }); - #else - int count = 0; - cpBodyEachArbiter(ballBody, (cpBodyArbiterIteratorFunc)BallIterator, &count); - #endif - - ChipmunkDemoPrintString("The ball is touching %d shapes.\n", count); - - #if USE_BLOCKS - __block cpFloat magnitudeSum = 0.0f; - __block cpVect vectorSum = cpvzero; - cpBodyEachArbiter_b(ballBody, ^(cpArbiter *arb){ - cpVect j = cpArbiterTotalImpulse(arb); - magnitudeSum += cpvlength(j); - vectorSum = cpvadd(vectorSum, j); - }); - - cpFloat crushForce = (magnitudeSum - cpvlength(vectorSum))*dt; - #else - struct CrushingContext crush = {0.0f, cpvzero}; - cpBodyEachArbiter(ballBody, (cpBodyArbiterIteratorFunc)EstimateCrushing, &crush); - - cpFloat crushForce = (crush.magnitudeSum - cpvlength(crush.vectorSum))*dt; - #endif - - - if(crushForce > 10.0f){ - ChipmunkDemoPrintString("The ball is being crushed. (f: %.2f)", crushForce); - } else { - ChipmunkDemoPrintString("The ball is not being crushed. (f: %.2f)", crushForce); - } + cpSpaceStep(space, dt); + + ChipmunkDemoPrintString("Place objects on the scale to weigh them. The ball marks the shapes it's sitting on.\n"); + +// Sum the total impulse applied to the scale from all collision pairs in the contact graph. +// If your compiler supports blocks, your life is a little easier. +// You can use the "Block" versions of the functions without needing the callbacks above. +#if USE_BLOCKS + __block cpVect impulseSum = cpvzero; + cpBodyEachArbiter_b(scaleStaticBody, ^(cpArbiter* arb) { + impulseSum = cpvadd(impulseSum, cpArbiterTotalImpulse(arb)); + }); +#else + cpVect impulseSum = cpvzero; + cpBodyEachArbiter(scaleStaticBody, (cpBodyArbiterIteratorFunc)ScaleIterator, &impulseSum); +#endif + + // Force is the impulse divided by the timestep. + cpFloat force = cpvlength(impulseSum) / dt; + + // Weight can be found similarly from the gravity vector. + cpVect g = cpSpaceGetGravity(space); + cpFloat weight = cpvdot(g, impulseSum) / (cpvlengthsq(g) * dt); + + ChipmunkDemoPrintString("Total force: %5.2f, Total weight: %5.2f. ", force, weight); + +// Highlight and count the number of shapes the ball is touching. +#if USE_BLOCKS + __block int count = 0; + cpBodyEachArbiter_b(ballBody, ^(cpArbiter* arb) { + // body is the body we are iterating the arbiters for. + // CP_ARBITER_GET_*() in an arbiter iterator always returns the body/shape for the iterated body first. + CP_ARBITER_GET_SHAPES(arb, ball, other); + ChipmunkDebugDrawBB(cpShapeGetBB(other), RGBAColor(1, 0, 0, 1)); + + count++; + }); +#else + int count = 0; + cpBodyEachArbiter(ballBody, (cpBodyArbiterIteratorFunc)BallIterator, &count); +#endif + + ChipmunkDemoPrintString("The ball is touching %d shapes.\n", count); + +#if USE_BLOCKS + __block cpFloat magnitudeSum = 0.0f; + __block cpVect vectorSum = cpvzero; + cpBodyEachArbiter_b(ballBody, ^(cpArbiter* arb) { + cpVect j = cpArbiterTotalImpulse(arb); + magnitudeSum += cpvlength(j); + vectorSum = cpvadd(vectorSum, j); + }); + + cpFloat crushForce = (magnitudeSum - cpvlength(vectorSum)) * dt; +#else + struct CrushingContext crush = {0.0f, cpvzero}; + cpBodyEachArbiter(ballBody, (cpBodyArbiterIteratorFunc)EstimateCrushing, &crush); + + cpFloat crushForce = (crush.magnitudeSum - cpvlength(crush.vectorSum)) * dt; +#endif + + if (crushForce > 10.0f) + { + ChipmunkDemoPrintString("The ball is being crushed. (f: %.2f)", crushForce); + } + else + { + ChipmunkDemoPrintString("The ball is not being crushed. (f: %.2f)", crushForce); + } } #define WIDTH 4.0f #define HEIGHT 30.0f -static cpSpace * -init(void) +static cpSpace* init(void) { - cpSpace *space = cpSpaceNew(); - cpSpaceSetIterations(space, 30); - cpSpaceSetGravity(space, cpv(0, -300)); - cpSpaceSetCollisionSlop(space, 0.5); - cpSpaceSetSleepTimeThreshold(space, 1.0f); - - cpBody *body, *staticBody = cpSpaceGetStaticBody(space); - cpShape *shape; - - // Create segments around the edge of the screen. - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(-320, 240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320, -240), cpv(320, 240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(320, -240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - scaleStaticBody = cpSpaceAddBody(space, cpBodyNewStatic()); - shape = cpSpaceAddShape(space, cpSegmentShapeNew(scaleStaticBody, cpv(-240,-180), cpv(-140,-180), 4.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - // add some boxes to stack on the scale - for(int i=0; i<5; i++){ - body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForBox(1.0f, 30.0f, 30.0f))); - cpBodySetPosition(body, cpv(0, i*32 - 120)); - - shape = cpSpaceAddShape(space, cpBoxShapeNew(body, 30.0f, 30.0f, 0.0)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.8f); - } - - // Add a ball that we'll track which objects are beneath it. - cpFloat radius = 15.0f; - ballBody = cpSpaceAddBody(space, cpBodyNew(10.0f, cpMomentForCircle(10.0f, 0.0f, radius, cpvzero))); - cpBodySetPosition(ballBody, cpv(120, -140 + radius+5)); - - shape = cpSpaceAddShape(space, cpCircleShapeNew(ballBody, radius, cpvzero)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.9f); - - return space; + cpSpace* space = cpSpaceNew(); + cpSpaceSetIterations(space, 30); + cpSpaceSetGravity(space, cpv(0, -300)); + cpSpaceSetCollisionSlop(space, 0.5); + cpSpaceSetSleepTimeThreshold(space, 1.0f); + + cpBody *body, *staticBody = cpSpaceGetStaticBody(space); + cpShape* shape; + + // Create segments around the edge of the screen. + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(-320, 240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320, -240), cpv(320, 240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(320, -240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + scaleStaticBody = cpSpaceAddBody(space, cpBodyNewStatic()); + shape = cpSpaceAddShape(space, cpSegmentShapeNew(scaleStaticBody, cpv(-240, -180), cpv(-140, -180), 4.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + // add some boxes to stack on the scale + for (int i = 0; i < 5; i++) + { + body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForBox(1.0f, 30.0f, 30.0f))); + cpBodySetPosition(body, cpv(0, i * 32 - 120)); + + shape = cpSpaceAddShape(space, cpBoxShapeNew(body, 30.0f, 30.0f, 0.0)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.8f); + } + + // Add a ball that we'll track which objects are beneath it. + cpFloat radius = 15.0f; + ballBody = cpSpaceAddBody(space, cpBodyNew(10.0f, cpMomentForCircle(10.0f, 0.0f, radius, cpvzero))); + cpBodySetPosition(ballBody, cpv(120, -140 + radius + 5)); + + shape = cpSpaceAddShape(space, cpCircleShapeNew(ballBody, radius, cpvzero)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.9f); + + return space; } -static void -destroy(cpSpace *space) +static void destroy(cpSpace* space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo ContactGraph = { - "Contact Graph", - 1.0/60.0, - init, - update, - ChipmunkDemoDefaultDrawImpl, - destroy, + "Contact Graph", 1.0 / 60.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Convex.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Convex.c index 72d5506074b9..b4e457f26be3 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Convex.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Convex.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,99 +18,93 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include "chipmunk/chipmunk.h" #include "chipmunk/chipmunk_unsafe.h" #include "ChipmunkDemo.h" -#define DENSITY (1.0/10000.0) +#define DENSITY (1.0 / 10000.0) -static cpShape *shape; +static cpShape* shape; -static void -update(cpSpace *space, double dt) +static void update(cpSpace* space, double dt) { - cpFloat tolerance = 2.0; - - if(ChipmunkDemoRightClick && cpShapePointQuery(shape, ChipmunkDemoMouse, NULL) > tolerance){ - cpBody *body = cpShapeGetBody(shape); - int count = cpPolyShapeGetCount(shape); - - // Allocate the space for the new vertexes on the stack. - cpVect *verts = (cpVect *)alloca((count + 1)*sizeof(cpVect)); - - for(int i=0; i tolerance) + { + cpBody* body = cpShapeGetBody(shape); + int count = cpPolyShapeGetCount(shape); + + // Allocate the space for the new vertexes on the stack. + cpVect* verts = (cpVect*)alloca((count + 1) * sizeof(cpVect)); + + for (int i = 0; i < count; i++) + { + verts[i] = cpPolyShapeGetVert(shape, i); + } + + verts[count] = cpBodyWorldToLocal(body, ChipmunkDemoMouse); + + // This function builds a convex hull for the vertexes. + // Because the result array is the same as verts, it will reduce it in place. + int hullCount = cpConvexHull(count + 1, verts, verts, NULL, tolerance); + + // Figure out how much to shift the body by. + cpVect centroid = cpCentroidForPoly(hullCount, verts); + + // Recalculate the body properties to match the updated shape. + cpFloat mass = cpAreaForPoly(hullCount, verts, 0.0f) * DENSITY; + cpBodySetMass(body, mass); + cpBodySetMoment(body, cpMomentForPoly(mass, hullCount, verts, cpvneg(centroid), 0.0f)); + cpBodySetPosition(body, cpBodyLocalToWorld(body, centroid)); + + // Use the setter function from chipmunk_unsafe.h. + // You could also remove and recreate the shape if you wanted. + cpPolyShapeSetVerts(shape, hullCount, verts, cpTransformTranslate(cpvneg(centroid))); + } + + cpSpaceStep(space, dt); } -static cpSpace * -init(void) +static cpSpace* init(void) { - ChipmunkDemoMessageString = "Right click and drag to change the blocks's shape."; - - cpSpace *space = cpSpaceNew(); - cpSpaceSetIterations(space, 30); - cpSpaceSetGravity(space, cpv(0, -500)); - cpSpaceSetSleepTimeThreshold(space, 0.5f); - cpSpaceSetCollisionSlop(space, 0.5f); - - cpBody *body, *staticBody = cpSpaceGetStaticBody(space); - - // Create segments around the edge of the screen. - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - cpFloat width = 50.0f; - cpFloat height = 70.0f; - cpFloat mass = width*height*DENSITY; - cpFloat moment = cpMomentForBox(mass, width, height); - - body = cpSpaceAddBody(space, cpBodyNew(mass, moment)); - - shape = cpSpaceAddShape(space, cpBoxShapeNew(body, width, height, 0.0)); - cpShapeSetFriction(shape, 0.6f); - - return space; + ChipmunkDemoMessageString = "Right click and drag to change the blocks's shape."; + + cpSpace* space = cpSpaceNew(); + cpSpaceSetIterations(space, 30); + cpSpaceSetGravity(space, cpv(0, -500)); + cpSpaceSetSleepTimeThreshold(space, 0.5f); + cpSpaceSetCollisionSlop(space, 0.5f); + + cpBody *body, *staticBody = cpSpaceGetStaticBody(space); + + // Create segments around the edge of the screen. + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(320, -240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + cpFloat width = 50.0f; + cpFloat height = 70.0f; + cpFloat mass = width * height * DENSITY; + cpFloat moment = cpMomentForBox(mass, width, height); + + body = cpSpaceAddBody(space, cpBodyNew(mass, moment)); + + shape = cpSpaceAddShape(space, cpBoxShapeNew(body, width, height, 0.0)); + cpShapeSetFriction(shape, 0.6f); + + return space; } -static void -destroy(cpSpace *space) +static void destroy(cpSpace* space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo Convex = { - "Convex.", - 1.0/60.0, - init, - update, - ChipmunkDemoDefaultDrawImpl, - destroy, + "Convex.", 1.0 / 60.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Crane.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Crane.c index 9141e85c321d..7d0cfe9e021d 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Crane.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Crane.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,155 +18,143 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" -static cpBody *dollyBody = NULL; +static cpBody* dollyBody = NULL; // Constraint used as a servo motor to move the dolly back and forth. -static cpConstraint *dollyServo = NULL; +static cpConstraint* dollyServo = NULL; // Constraint used as a winch motor to lift the load. -static cpConstraint *winchServo = NULL; +static cpConstraint* winchServo = NULL; // Temporary joint used to hold the hook to the load. -static cpConstraint *hookJoint = NULL; - +static cpConstraint* hookJoint = NULL; -static void -update(cpSpace *space, double dt) +static void update(cpSpace* space, double dt) { - // Set the first anchor point (the one attached to the static body) of the dolly servo to the mouse's x position. - cpPivotJointSetAnchorA(dollyServo, cpv(ChipmunkDemoMouse.x, 100)); - - // Set the max length of the winch servo to match the mouse's height. - cpSlideJointSetMax(winchServo, cpfmax(100 - ChipmunkDemoMouse.y, 50)); - - if(hookJoint && ChipmunkDemoRightClick){ - cpSpaceRemoveConstraint(space, hookJoint); - cpConstraintFree(hookJoint); - hookJoint = NULL; - } - - cpSpaceStep(space, dt); + // Set the first anchor point (the one attached to the static body) of the dolly servo to the mouse's x position. + cpPivotJointSetAnchorA(dollyServo, cpv(ChipmunkDemoMouse.x, 100)); + + // Set the max length of the winch servo to match the mouse's height. + cpSlideJointSetMax(winchServo, cpfmax(100 - ChipmunkDemoMouse.y, 50)); + + if (hookJoint && ChipmunkDemoRightClick) + { + cpSpaceRemoveConstraint(space, hookJoint); + cpConstraintFree(hookJoint); + hookJoint = NULL; + } + + cpSpaceStep(space, dt); } -enum COLLISION_TYPES { - HOOK_SENSOR = 1, - CRATE, +enum COLLISION_TYPES +{ + HOOK_SENSOR = 1, + CRATE, }; -static void -AttachHook(cpSpace *space, cpBody *hook, cpBody *crate) +static void AttachHook(cpSpace* space, cpBody* hook, cpBody* crate) { - hookJoint = cpSpaceAddConstraint(space, cpPivotJointNew(hook, crate, cpBodyGetPosition(hook))); + hookJoint = cpSpaceAddConstraint(space, cpPivotJointNew(hook, crate, cpBodyGetPosition(hook))); } - -static cpBool -HookCrate(cpArbiter *arb, cpSpace *space, void *data) +static cpBool HookCrate(cpArbiter* arb, cpSpace* space, void* data) { - if(hookJoint == NULL){ - // Get pointers to the two bodies in the collision pair and define local variables for them. - // Their order matches the order of the collision types passed - // to the collision handler this function was defined for - CP_ARBITER_GET_BODIES(arb, hook, crate); - - // additions and removals can't be done in a normal callback. - // Schedule a post step callback to do it. - // Use the hook as the key and pass along the arbiter. - cpSpaceAddPostStepCallback(space, (cpPostStepFunc)AttachHook, hook, crate); - } - - return cpTrue; // return value is ignored for sensor callbacks anyway -} + if (hookJoint == NULL) + { + // Get pointers to the two bodies in the collision pair and define local variables for them. + // Their order matches the order of the collision types passed + // to the collision handler this function was defined for + CP_ARBITER_GET_BODIES(arb, hook, crate); + + // additions and removals can't be done in a normal callback. + // Schedule a post step callback to do it. + // Use the hook as the key and pass along the arbiter. + cpSpaceAddPostStepCallback(space, (cpPostStepFunc)AttachHook, hook, crate); + } + return cpTrue; // return value is ignored for sensor callbacks anyway +} -static cpSpace * -init(void) +static cpSpace* init(void) { - ChipmunkDemoMessageString = "Control the crane by moving the mouse. Right click to release."; - - cpSpace *space = cpSpaceNew(); - cpSpaceSetIterations(space, 30); - cpSpaceSetGravity(space, cpv(0, -100)); - cpSpaceSetDamping(space, 0.8); - - cpBody *staticBody = cpSpaceGetStaticBody(space); - cpShape *shape; - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - // Add a body for the dolly. - dollyBody = cpSpaceAddBody(space, cpBodyNew(10, INFINITY)); - cpBodySetPosition(dollyBody, cpv(0, 100)); - - // Add a block so you can see it. - cpSpaceAddShape(space, cpBoxShapeNew(dollyBody, 30, 30, 0.0)); - - // Add a groove joint for it to move back and forth on. - cpSpaceAddConstraint(space, cpGrooveJointNew(staticBody, dollyBody, cpv(-250, 100), cpv(250, 100), cpvzero)); - - // Add a pivot joint to act as a servo motor controlling it's position - // By updating the anchor points of the pivot joint, you can move the dolly. - dollyServo = cpSpaceAddConstraint(space, cpPivotJointNew(staticBody, dollyBody, cpBodyGetPosition(dollyBody))); - // Max force the dolly servo can generate. - cpConstraintSetMaxForce(dollyServo, 10000); - // Max speed of the dolly servo - cpConstraintSetMaxBias(dollyServo, 100); - // You can also change the error bias to control how it slows down. - //cpConstraintSetErrorBias(dollyServo, 0.2); - - - // Add the crane hook. - cpBody *hookBody = cpSpaceAddBody(space, cpBodyNew(1, INFINITY)); - cpBodySetPosition(hookBody, cpv(0, 50)); - - // Add a sensor shape for it. This will be used to figure out when the hook touches a box. - shape = cpSpaceAddShape(space, cpCircleShapeNew(hookBody, 10, cpvzero)); - cpShapeSetSensor(shape, cpTrue); - cpShapeSetCollisionType(shape, HOOK_SENSOR); - - // Add a slide joint to act as a winch motor - // By updating the max length of the joint you can make it pull up the load. - winchServo = cpSpaceAddConstraint(space, cpSlideJointNew(dollyBody, hookBody, cpvzero, cpvzero, 0, INFINITY)); - // Max force the dolly servo can generate. - cpConstraintSetMaxForce(winchServo, 30000); - // Max speed of the dolly servo - cpConstraintSetMaxBias(winchServo, 60); - - // TODO: cleanup - // Finally a box to play with - cpBody *boxBody = cpSpaceAddBody(space, cpBodyNew(30, cpMomentForBox(30, 50, 50))); - cpBodySetPosition(boxBody, cpv(200, -200)); - - // Add a block so you can see it. - shape = cpSpaceAddShape(space, cpBoxShapeNew(boxBody, 50, 50, 0.0)); - cpShapeSetFriction(shape, 0.7); - cpShapeSetCollisionType(shape, CRATE); - - cpCollisionHandler *handler = cpSpaceAddCollisionHandler(space, HOOK_SENSOR, CRATE); - handler->beginFunc = (cpCollisionBeginFunc)HookCrate; - - - return space; + ChipmunkDemoMessageString = "Control the crane by moving the mouse. Right click to release."; + + cpSpace* space = cpSpaceNew(); + cpSpaceSetIterations(space, 30); + cpSpaceSetGravity(space, cpv(0, -100)); + cpSpaceSetDamping(space, 0.8); + + cpBody* staticBody = cpSpaceGetStaticBody(space); + cpShape* shape; + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(320, -240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + // Add a body for the dolly. + dollyBody = cpSpaceAddBody(space, cpBodyNew(10, INFINITY)); + cpBodySetPosition(dollyBody, cpv(0, 100)); + + // Add a block so you can see it. + cpSpaceAddShape(space, cpBoxShapeNew(dollyBody, 30, 30, 0.0)); + + // Add a groove joint for it to move back and forth on. + cpSpaceAddConstraint(space, cpGrooveJointNew(staticBody, dollyBody, cpv(-250, 100), cpv(250, 100), cpvzero)); + + // Add a pivot joint to act as a servo motor controlling it's position + // By updating the anchor points of the pivot joint, you can move the dolly. + dollyServo = cpSpaceAddConstraint(space, cpPivotJointNew(staticBody, dollyBody, cpBodyGetPosition(dollyBody))); + // Max force the dolly servo can generate. + cpConstraintSetMaxForce(dollyServo, 10000); + // Max speed of the dolly servo + cpConstraintSetMaxBias(dollyServo, 100); + // You can also change the error bias to control how it slows down. + // cpConstraintSetErrorBias(dollyServo, 0.2); + + // Add the crane hook. + cpBody* hookBody = cpSpaceAddBody(space, cpBodyNew(1, INFINITY)); + cpBodySetPosition(hookBody, cpv(0, 50)); + + // Add a sensor shape for it. This will be used to figure out when the hook touches a box. + shape = cpSpaceAddShape(space, cpCircleShapeNew(hookBody, 10, cpvzero)); + cpShapeSetSensor(shape, cpTrue); + cpShapeSetCollisionType(shape, HOOK_SENSOR); + + // Add a slide joint to act as a winch motor + // By updating the max length of the joint you can make it pull up the load. + winchServo = cpSpaceAddConstraint(space, cpSlideJointNew(dollyBody, hookBody, cpvzero, cpvzero, 0, INFINITY)); + // Max force the dolly servo can generate. + cpConstraintSetMaxForce(winchServo, 30000); + // Max speed of the dolly servo + cpConstraintSetMaxBias(winchServo, 60); + + // TODO: cleanup + // Finally a box to play with + cpBody* boxBody = cpSpaceAddBody(space, cpBodyNew(30, cpMomentForBox(30, 50, 50))); + cpBodySetPosition(boxBody, cpv(200, -200)); + + // Add a block so you can see it. + shape = cpSpaceAddShape(space, cpBoxShapeNew(boxBody, 50, 50, 0.0)); + cpShapeSetFriction(shape, 0.7); + cpShapeSetCollisionType(shape, CRATE); + + cpCollisionHandler* handler = cpSpaceAddCollisionHandler(space, HOOK_SENSOR, CRATE); + handler->beginFunc = (cpCollisionBeginFunc)HookCrate; + + return space; } -static void -destroy(cpSpace *space) +static void destroy(cpSpace* space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo Crane = { - "Crane", - 1.0/60.0, - init, - update, - ChipmunkDemoDefaultDrawImpl, - destroy, + "Crane", 1.0 / 60.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Example.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Example.c index 75279f57795c..d3436dda5ace 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Example.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Example.c @@ -29,12 +29,13 @@ #include "chipmunk/chipmunk_unsafe.h" #include "ChipmunkDemo.h" -static void update(cpSpace* space, double dt) { +static void update(cpSpace* space, double dt) +{ cpSpaceStep(space, dt); } - -static cpSpace* init(void) { +static cpSpace* init(void) +{ cpSpace* space = cpSpaceNew(); cpSpaceSetIterations(space, 5); space->damping = 0.1; @@ -43,7 +44,6 @@ static cpSpace* init(void) { cpFloat mass = 1.0f; - { cpFloat size = 100.0; @@ -67,8 +67,9 @@ static cpSpace* init(void) { const int NUM_VERTS = 5; cpVect verts[NUM_VERTS]; - for (int i = 0; i < NUM_VERTS; i++) { - cpFloat angle = -2 * M_PI * i / ((cpFloat) NUM_VERTS); + for (int i = 0; i < NUM_VERTS; i++) + { + cpFloat angle = -2 * M_PI * i / ((cpFloat)NUM_VERTS); verts[i] = cpv(size / 2.0 * cos(angle), size / 2.0 * sin(angle)); } @@ -82,8 +83,9 @@ static cpSpace* init(void) { const int NUM_VERTS = 4; cpVect verts[NUM_VERTS]; - for (int i = 0; i < NUM_VERTS; i++) { - cpFloat angle = -2 * M_PI * i / ((cpFloat) NUM_VERTS); + for (int i = 0; i < NUM_VERTS; i++) + { + cpFloat angle = -2 * M_PI * i / ((cpFloat)NUM_VERTS); verts[i] = cpv(size / 2.0 * cos(angle), size / 2.0 * sin(angle)); } @@ -115,16 +117,12 @@ static cpSpace* init(void) { return space; } -static void destroy(cpSpace* space) { +static void destroy(cpSpace* space) +{ ChipmunkDemoFreeSpaceChildren(space); cpSpaceFree(space); } ChipmunkDemo Example = { - "Template to start (GJK)", - 1.0f / 60.0f, - init, - update, - ChipmunkDemoDefaultDrawImpl, - destroy, + "Template to start (GJK)", 1.0f / 60.0f, init, update, ChipmunkDemoDefaultDrawImpl, destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Joints.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Joints.c index 3a7f23a6e16d..db27fe805351 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Joints.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Joints.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,281 +18,267 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" -static cpBody * -addBall(cpSpace *space, cpVect pos, cpVect boxOffset) +static cpBody* addBall(cpSpace* space, cpVect pos, cpVect boxOffset) { - cpFloat radius = 15.0f; - cpFloat mass = 1.0f; - cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); - cpBodySetPosition(body, cpvadd(pos, boxOffset)); - - cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.7f); - - return body; + cpFloat radius = 15.0f; + cpFloat mass = 1.0f; + cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); + cpBodySetPosition(body, cpvadd(pos, boxOffset)); + + cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.7f); + + return body; } -static cpBody * -addLever(cpSpace *space, cpVect pos, cpVect boxOffset) +static cpBody* addLever(cpSpace* space, cpVect pos, cpVect boxOffset) { - cpFloat mass = 1.0f; - cpVect a = cpv(0, 15); - cpVect b = cpv(0, -15); - - cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForSegment(mass, a, b, 0.0f))); - cpBodySetPosition(body, cpvadd(pos, cpvadd(boxOffset, cpv(0, -15)))); - - cpShape *shape = cpSpaceAddShape(space, cpSegmentShapeNew(body, a, b, 5.0f)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.7f); - - return body; + cpFloat mass = 1.0f; + cpVect a = cpv(0, 15); + cpVect b = cpv(0, -15); + + cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForSegment(mass, a, b, 0.0f))); + cpBodySetPosition(body, cpvadd(pos, cpvadd(boxOffset, cpv(0, -15)))); + + cpShape* shape = cpSpaceAddShape(space, cpSegmentShapeNew(body, a, b, 5.0f)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.7f); + + return body; } -static cpBody * -addBar(cpSpace *space, cpVect pos, cpVect boxOffset) +static cpBody* addBar(cpSpace* space, cpVect pos, cpVect boxOffset) { - cpFloat mass = 2.0f; - cpVect a = cpv(0, 30); - cpVect b = cpv(0, -30); - - cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForSegment(mass, a, b, 0.0f))); - cpBodySetPosition(body, cpvadd(pos, boxOffset)); - - cpShape *shape = cpSpaceAddShape(space, cpSegmentShapeNew(body, a, b, 5.0f)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.7f); - cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); - - return body; + cpFloat mass = 2.0f; + cpVect a = cpv(0, 30); + cpVect b = cpv(0, -30); + + cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForSegment(mass, a, b, 0.0f))); + cpBodySetPosition(body, cpvadd(pos, boxOffset)); + + cpShape* shape = cpSpaceAddShape(space, cpSegmentShapeNew(body, a, b, 5.0f)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.7f); + cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); + + return body; } -static cpBody * -addWheel(cpSpace *space, cpVect pos, cpVect boxOffset) +static cpBody* addWheel(cpSpace* space, cpVect pos, cpVect boxOffset) { - cpFloat radius = 15.0f; - cpFloat mass = 1.0f; - cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); - cpBodySetPosition(body, cpvadd(pos, boxOffset)); - - cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.7f); - cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); - - return body; + cpFloat radius = 15.0f; + cpFloat mass = 1.0f; + cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); + cpBodySetPosition(body, cpvadd(pos, boxOffset)); + + cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.7f); + cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); + + return body; } -static cpBody * -addChassis(cpSpace *space, cpVect pos, cpVect boxOffset) +static cpBody* addChassis(cpSpace* space, cpVect pos, cpVect boxOffset) { - cpFloat mass = 5.0f; - cpFloat width = 80; - cpFloat height = 30; - - cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForBox(mass, width, height))); - cpBodySetPosition(body, cpvadd(pos, boxOffset)); - - cpShape *shape = cpSpaceAddShape(space, cpBoxShapeNew(body, width, height, 0.0)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.7f); - cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); - - return body; + cpFloat mass = 5.0f; + cpFloat width = 80; + cpFloat height = 30; + + cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForBox(mass, width, height))); + cpBodySetPosition(body, cpvadd(pos, boxOffset)); + + cpShape* shape = cpSpaceAddShape(space, cpBoxShapeNew(body, width, height, 0.0)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.7f); + cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); + + return body; } -static cpSpace * -init(void) +static cpSpace* init(void) { - cpSpace *space = cpSpaceNew(); - cpSpaceSetIterations(space, 10); - cpSpaceSetGravity(space, cpv(0, -100)); - cpSpaceSetSleepTimeThreshold(space, 0.5f); - - cpBody *staticBody = cpSpaceGetStaticBody(space); - cpShape *shape; - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,240), cpv(320,240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,120), cpv(320,120), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,0), cpv(320,0), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-120), cpv(320,-120), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(-320,240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-160,-240), cpv(-160,240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(0,-240), cpv(0,240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(160,-240), cpv(160,240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320,-240), cpv(320,240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - cpVect boxOffset; - cpBody *body1, *body2; - - cpVect posA = cpv( 50, 60); - cpVect posB = cpv(110, 60); - - #define POS_A cpvadd(boxOffset, posA) - #define POS_B cpvadd(boxOffset, posB) - - // Pin Joints - Link shapes with a solid bar or pin. - // Keeps the anchor points the same distance apart from when the joint was created. - boxOffset = cpv(-320, -240); - body1 = addBall(space, posA, boxOffset); - body2 = addBall(space, posB, boxOffset); - cpSpaceAddConstraint(space, cpPinJointNew(body1, body2, cpv(15,0), cpv(-15,0))); - - // Slide Joints - Like pin joints but with a min/max distance. - // Can be used for a cheap approximation of a rope. - boxOffset = cpv(-160, -240); - body1 = addBall(space, posA, boxOffset); - body2 = addBall(space, posB, boxOffset); - cpSpaceAddConstraint(space, cpSlideJointNew(body1, body2, cpv(15,0), cpv(-15,0), 20.0f, 40.0f)); - - // Pivot Joints - Holds the two anchor points together. Like a swivel. - boxOffset = cpv(0, -240); - body1 = addBall(space, posA, boxOffset); - body2 = addBall(space, posB, boxOffset); - cpSpaceAddConstraint(space, cpPivotJointNew(body1, body2, cpvadd(boxOffset, cpv(80,60)))); - // cpPivotJointNew() takes it's anchor parameter in world coordinates. The anchors are calculated from that - // cpPivotJointNew2() lets you specify the two anchor points explicitly - - // Groove Joints - Like a pivot joint, but one of the anchors is a line segment that the pivot can slide in - boxOffset = cpv(160, -240); - body1 = addBall(space, posA, boxOffset); - body2 = addBall(space, posB, boxOffset); - cpSpaceAddConstraint(space, cpGrooveJointNew(body1, body2, cpv(30,30), cpv(30,-30), cpv(-30,0))); - - // Damped Springs - boxOffset = cpv(-320, -120); - body1 = addBall(space, posA, boxOffset); - body2 = addBall(space, posB, boxOffset); - cpSpaceAddConstraint(space, cpDampedSpringNew(body1, body2, cpv(15,0), cpv(-15,0), 20.0f, 5.0f, 0.3f)); - - // Damped Rotary Springs - boxOffset = cpv(-160, -120); - body1 = addBar(space, posA, boxOffset); - body2 = addBar(space, posB, boxOffset); - // Add some pin joints to hold the circles in place. - cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A)); - cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B)); - cpSpaceAddConstraint(space, cpDampedRotarySpringNew(body1, body2, 0.0f, 3000.0f, 60.0f)); - - // Rotary Limit Joint - boxOffset = cpv(0, -120); - body1 = addLever(space, posA, boxOffset); - body2 = addLever(space, posB, boxOffset); - // Add some pin joints to hold the circles in place. - cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A)); - cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B)); - // Hold their rotation within 90 degrees of each other. - cpSpaceAddConstraint(space, cpRotaryLimitJointNew(body1, body2, -CP_PI/2.0f, CP_PI/2.0f)); - - // Ratchet Joint - A rotary ratchet, like a socket wrench - boxOffset = cpv(160, -120); - body1 = addLever(space, posA, boxOffset); - body2 = addLever(space, posB, boxOffset); - // Add some pin joints to hold the circles in place. - cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A)); - cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B)); - // Ratchet every 90 degrees - cpSpaceAddConstraint(space, cpRatchetJointNew(body1, body2, 0.0f, CP_PI/2.0f)); - - // Gear Joint - Maintain a specific angular velocity ratio - boxOffset = cpv(-320, 0); - body1 = addBar(space, posA, boxOffset); - body2 = addBar(space, posB, boxOffset); - // Add some pin joints to hold the circles in place. - cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A)); - cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B)); - // Force one to sping 2x as fast as the other - cpSpaceAddConstraint(space, cpGearJointNew(body1, body2, 0.0f, 2.0f)); - - // Simple Motor - Maintain a specific angular relative velocity - boxOffset = cpv(-160, 0); - body1 = addBar(space, posA, boxOffset); - body2 = addBar(space, posB, boxOffset); - // Add some pin joints to hold the circles in place. - cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A)); - cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B)); - // Make them spin at 1/2 revolution per second in relation to each other. - cpSpaceAddConstraint(space, cpSimpleMotorNew(body1, body2, CP_PI)); - - // Make a car with some nice soft suspension - boxOffset = cpv(0, 0); - cpBody *wheel1 = addWheel(space, posA, boxOffset); - cpBody *wheel2 = addWheel(space, posB, boxOffset); - cpBody *chassis = addChassis(space, cpv(80, 100), boxOffset); - - cpSpaceAddConstraint(space, cpGrooveJointNew(chassis, wheel1, cpv(-30, -10), cpv(-30, -40), cpvzero)); - cpSpaceAddConstraint(space, cpGrooveJointNew(chassis, wheel2, cpv( 30, -10), cpv( 30, -40), cpvzero)); - - cpSpaceAddConstraint(space, cpDampedSpringNew(chassis, wheel1, cpv(-30, 0), cpvzero, 50.0f, 20.0f, 10.0f)); - cpSpaceAddConstraint(space, cpDampedSpringNew(chassis, wheel2, cpv( 30, 0), cpvzero, 50.0f, 20.0f, 10.0f)); - - return space; + cpSpace* space = cpSpaceNew(); + cpSpaceSetIterations(space, 10); + cpSpaceSetGravity(space, cpv(0, -100)); + cpSpaceSetSleepTimeThreshold(space, 0.5f); + + cpBody* staticBody = cpSpaceGetStaticBody(space); + cpShape* shape; + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, 240), cpv(320, 240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, 120), cpv(320, 120), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, 0), cpv(320, 0), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -120), cpv(320, -120), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(320, -240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(-320, 240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-160, -240), cpv(-160, 240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(0, -240), cpv(0, 240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(160, -240), cpv(160, 240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320, -240), cpv(320, 240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + cpVect boxOffset; + cpBody *body1, *body2; + + cpVect posA = cpv(50, 60); + cpVect posB = cpv(110, 60); + +#define POS_A cpvadd(boxOffset, posA) +#define POS_B cpvadd(boxOffset, posB) + + // Pin Joints - Link shapes with a solid bar or pin. + // Keeps the anchor points the same distance apart from when the joint was created. + boxOffset = cpv(-320, -240); + body1 = addBall(space, posA, boxOffset); + body2 = addBall(space, posB, boxOffset); + cpSpaceAddConstraint(space, cpPinJointNew(body1, body2, cpv(15, 0), cpv(-15, 0))); + + // Slide Joints - Like pin joints but with a min/max distance. + // Can be used for a cheap approximation of a rope. + boxOffset = cpv(-160, -240); + body1 = addBall(space, posA, boxOffset); + body2 = addBall(space, posB, boxOffset); + cpSpaceAddConstraint(space, cpSlideJointNew(body1, body2, cpv(15, 0), cpv(-15, 0), 20.0f, 40.0f)); + + // Pivot Joints - Holds the two anchor points together. Like a swivel. + boxOffset = cpv(0, -240); + body1 = addBall(space, posA, boxOffset); + body2 = addBall(space, posB, boxOffset); + cpSpaceAddConstraint(space, cpPivotJointNew(body1, body2, cpvadd(boxOffset, cpv(80, 60)))); + // cpPivotJointNew() takes it's anchor parameter in world coordinates. The anchors are calculated from that + // cpPivotJointNew2() lets you specify the two anchor points explicitly + + // Groove Joints - Like a pivot joint, but one of the anchors is a line segment that the pivot can slide in + boxOffset = cpv(160, -240); + body1 = addBall(space, posA, boxOffset); + body2 = addBall(space, posB, boxOffset); + cpSpaceAddConstraint(space, cpGrooveJointNew(body1, body2, cpv(30, 30), cpv(30, -30), cpv(-30, 0))); + + // Damped Springs + boxOffset = cpv(-320, -120); + body1 = addBall(space, posA, boxOffset); + body2 = addBall(space, posB, boxOffset); + cpSpaceAddConstraint(space, cpDampedSpringNew(body1, body2, cpv(15, 0), cpv(-15, 0), 20.0f, 5.0f, 0.3f)); + + // Damped Rotary Springs + boxOffset = cpv(-160, -120); + body1 = addBar(space, posA, boxOffset); + body2 = addBar(space, posB, boxOffset); + // Add some pin joints to hold the circles in place. + cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A)); + cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B)); + cpSpaceAddConstraint(space, cpDampedRotarySpringNew(body1, body2, 0.0f, 3000.0f, 60.0f)); + + // Rotary Limit Joint + boxOffset = cpv(0, -120); + body1 = addLever(space, posA, boxOffset); + body2 = addLever(space, posB, boxOffset); + // Add some pin joints to hold the circles in place. + cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A)); + cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B)); + // Hold their rotation within 90 degrees of each other. + cpSpaceAddConstraint(space, cpRotaryLimitJointNew(body1, body2, -CP_PI / 2.0f, CP_PI / 2.0f)); + + // Ratchet Joint - A rotary ratchet, like a socket wrench + boxOffset = cpv(160, -120); + body1 = addLever(space, posA, boxOffset); + body2 = addLever(space, posB, boxOffset); + // Add some pin joints to hold the circles in place. + cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A)); + cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B)); + // Ratchet every 90 degrees + cpSpaceAddConstraint(space, cpRatchetJointNew(body1, body2, 0.0f, CP_PI / 2.0f)); + + // Gear Joint - Maintain a specific angular velocity ratio + boxOffset = cpv(-320, 0); + body1 = addBar(space, posA, boxOffset); + body2 = addBar(space, posB, boxOffset); + // Add some pin joints to hold the circles in place. + cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A)); + cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B)); + // Force one to sping 2x as fast as the other + cpSpaceAddConstraint(space, cpGearJointNew(body1, body2, 0.0f, 2.0f)); + + // Simple Motor - Maintain a specific angular relative velocity + boxOffset = cpv(-160, 0); + body1 = addBar(space, posA, boxOffset); + body2 = addBar(space, posB, boxOffset); + // Add some pin joints to hold the circles in place. + cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A)); + cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B)); + // Make them spin at 1/2 revolution per second in relation to each other. + cpSpaceAddConstraint(space, cpSimpleMotorNew(body1, body2, CP_PI)); + + // Make a car with some nice soft suspension + boxOffset = cpv(0, 0); + cpBody* wheel1 = addWheel(space, posA, boxOffset); + cpBody* wheel2 = addWheel(space, posB, boxOffset); + cpBody* chassis = addChassis(space, cpv(80, 100), boxOffset); + + cpSpaceAddConstraint(space, cpGrooveJointNew(chassis, wheel1, cpv(-30, -10), cpv(-30, -40), cpvzero)); + cpSpaceAddConstraint(space, cpGrooveJointNew(chassis, wheel2, cpv(30, -10), cpv(30, -40), cpvzero)); + + cpSpaceAddConstraint(space, cpDampedSpringNew(chassis, wheel1, cpv(-30, 0), cpvzero, 50.0f, 20.0f, 10.0f)); + cpSpaceAddConstraint(space, cpDampedSpringNew(chassis, wheel2, cpv(30, 0), cpvzero, 50.0f, 20.0f, 10.0f)); + + return space; } -static void -update(cpSpace *space, double dt) +static void update(cpSpace* space, double dt) { - cpSpaceStep(space, dt); + cpSpaceStep(space, dt); } -static void -destroy(cpSpace *space) +static void destroy(cpSpace* space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo Joints = { - "Joints and Constraints", - 1.0/60.0, - init, - update, - ChipmunkDemoDefaultDrawImpl, - destroy, + "Joints and Constraints", 1.0 / 60.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/LogoSmash.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/LogoSmash.c index 3b1fc4bc670e..4971f05a5e62 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/LogoSmash.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/LogoSmash.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,149 +18,147 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" -static const int image_width = 188; -static const int image_height = 35; -static const int image_row_length = 24; +static const int image_width = 188; +static const int image_height = 35; +static const int image_row_length = 24; float ChipmunkDebugDrawPointLineScale = 1.0f; static const char image_bitmap[] = { - 15,-16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7,-64,15,63,-32,-2,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,31,-64,15,127,-125,-1,-128,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,127,-64,15,127,15,-1,-64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-1,-64,15,-2, - 31,-1,-64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-1,-64,0,-4,63,-1,-32,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,1,-1,-64,15,-8,127,-1,-32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 1,-1,-64,0,-8,-15,-1,-32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-31,-1,-64,15,-8,-32, - -1,-32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7,-15,-1,-64,9,-15,-32,-1,-32,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,31,-15,-1,-64,0,-15,-32,-1,-32,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,63,-7,-1,-64,9,-29,-32,127,-61,-16,63,15,-61,-1,-8,31,-16,15,-8,126,7,-31, - -8,31,-65,-7,-1,-64,9,-29,-32,0,7,-8,127,-97,-25,-1,-2,63,-8,31,-4,-1,15,-13, - -4,63,-1,-3,-1,-64,9,-29,-32,0,7,-8,127,-97,-25,-1,-2,63,-8,31,-4,-1,15,-13, - -2,63,-1,-3,-1,-64,9,-29,-32,0,7,-8,127,-97,-25,-1,-1,63,-4,63,-4,-1,15,-13, - -2,63,-33,-1,-1,-32,9,-25,-32,0,7,-8,127,-97,-25,-1,-1,63,-4,63,-4,-1,15,-13, - -1,63,-33,-1,-1,-16,9,-25,-32,0,7,-8,127,-97,-25,-1,-1,63,-4,63,-4,-1,15,-13, - -1,63,-49,-1,-1,-8,9,-57,-32,0,7,-8,127,-97,-25,-8,-1,63,-2,127,-4,-1,15,-13, - -1,-65,-49,-1,-1,-4,9,-57,-32,0,7,-8,127,-97,-25,-8,-1,63,-2,127,-4,-1,15,-13, - -1,-65,-57,-1,-1,-2,9,-57,-32,0,7,-8,127,-97,-25,-8,-1,63,-2,127,-4,-1,15,-13, - -1,-1,-57,-1,-1,-1,9,-57,-32,0,7,-1,-1,-97,-25,-8,-1,63,-1,-1,-4,-1,15,-13,-1, - -1,-61,-1,-1,-1,-119,-57,-32,0,7,-1,-1,-97,-25,-8,-1,63,-1,-1,-4,-1,15,-13,-1, - -1,-61,-1,-1,-1,-55,-49,-32,0,7,-1,-1,-97,-25,-8,-1,63,-1,-1,-4,-1,15,-13,-1, - -1,-63,-1,-1,-1,-23,-49,-32,127,-57,-1,-1,-97,-25,-1,-1,63,-1,-1,-4,-1,15,-13, - -1,-1,-63,-1,-1,-1,-16,-49,-32,-1,-25,-1,-1,-97,-25,-1,-1,63,-33,-5,-4,-1,15, - -13,-1,-1,-64,-1,-9,-1,-7,-49,-32,-1,-25,-8,127,-97,-25,-1,-1,63,-33,-5,-4,-1, - 15,-13,-1,-1,-64,-1,-13,-1,-32,-49,-32,-1,-25,-8,127,-97,-25,-1,-2,63,-49,-13, - -4,-1,15,-13,-1,-1,-64,127,-7,-1,-119,-17,-15,-1,-25,-8,127,-97,-25,-1,-2,63, - -49,-13,-4,-1,15,-13,-3,-1,-64,127,-8,-2,15,-17,-1,-1,-25,-8,127,-97,-25,-1, - -8,63,-49,-13,-4,-1,15,-13,-3,-1,-64,63,-4,120,0,-17,-1,-1,-25,-8,127,-97,-25, - -8,0,63,-57,-29,-4,-1,15,-13,-4,-1,-64,63,-4,0,15,-17,-1,-1,-25,-8,127,-97, - -25,-8,0,63,-57,-29,-4,-1,-1,-13,-4,-1,-64,31,-2,0,0,103,-1,-1,-57,-8,127,-97, - -25,-8,0,63,-57,-29,-4,-1,-1,-13,-4,127,-64,31,-2,0,15,103,-1,-1,-57,-8,127, - -97,-25,-8,0,63,-61,-61,-4,127,-1,-29,-4,127,-64,15,-8,0,0,55,-1,-1,-121,-8, - 127,-97,-25,-8,0,63,-61,-61,-4,127,-1,-29,-4,63,-64,15,-32,0,0,23,-1,-2,3,-16, - 63,15,-61,-16,0,31,-127,-127,-8,31,-1,-127,-8,31,-128,7,-128,0,0 -}; + 15, -16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 7, -64, 15, 63, -32, -2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 31, -64, 15, 127, -125, -1, -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 127, -64, 15, 127, 15, -1, -64, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -64, 15, -2, 31, -1, -64, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -64, 0, -4, 63, -1, -32, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -64, 15, -8, 127, -1, + -32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -64, 0, + -8, -15, -1, -32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -31, + -1, -64, 15, -8, -32, -1, -32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 7, -15, -1, -64, 9, -15, -32, -1, -32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 31, -15, -1, -64, 0, -15, -32, -1, -32, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 63, -7, -1, -64, 9, -29, -32, 127, -61, -16, 63, 15, -61, -1, + -8, 31, -16, 15, -8, 126, 7, -31, -8, 31, -65, -7, -1, -64, 9, -29, -32, 0, 7, -8, 127, + -97, -25, -1, -2, 63, -8, 31, -4, -1, 15, -13, -4, 63, -1, -3, -1, -64, 9, -29, -32, 0, + 7, -8, 127, -97, -25, -1, -2, 63, -8, 31, -4, -1, 15, -13, -2, 63, -1, -3, -1, -64, 9, + -29, -32, 0, 7, -8, 127, -97, -25, -1, -1, 63, -4, 63, -4, -1, 15, -13, -2, 63, -33, -1, + -1, -32, 9, -25, -32, 0, 7, -8, 127, -97, -25, -1, -1, 63, -4, 63, -4, -1, 15, -13, -1, + 63, -33, -1, -1, -16, 9, -25, -32, 0, 7, -8, 127, -97, -25, -1, -1, 63, -4, 63, -4, -1, + 15, -13, -1, 63, -49, -1, -1, -8, 9, -57, -32, 0, 7, -8, 127, -97, -25, -8, -1, 63, -2, + 127, -4, -1, 15, -13, -1, -65, -49, -1, -1, -4, 9, -57, -32, 0, 7, -8, 127, -97, -25, -8, + -1, 63, -2, 127, -4, -1, 15, -13, -1, -65, -57, -1, -1, -2, 9, -57, -32, 0, 7, -8, 127, + -97, -25, -8, -1, 63, -2, 127, -4, -1, 15, -13, -1, -1, -57, -1, -1, -1, 9, -57, -32, 0, + 7, -1, -1, -97, -25, -8, -1, 63, -1, -1, -4, -1, 15, -13, -1, -1, -61, -1, -1, -1, -119, + -57, -32, 0, 7, -1, -1, -97, -25, -8, -1, 63, -1, -1, -4, -1, 15, -13, -1, -1, -61, -1, + -1, -1, -55, -49, -32, 0, 7, -1, -1, -97, -25, -8, -1, 63, -1, -1, -4, -1, 15, -13, -1, + -1, -63, -1, -1, -1, -23, -49, -32, 127, -57, -1, -1, -97, -25, -1, -1, 63, -1, -1, -4, -1, + 15, -13, -1, -1, -63, -1, -1, -1, -16, -49, -32, -1, -25, -1, -1, -97, -25, -1, -1, 63, -33, + -5, -4, -1, 15, -13, -1, -1, -64, -1, -9, -1, -7, -49, -32, -1, -25, -8, 127, -97, -25, -1, + -1, 63, -33, -5, -4, -1, 15, -13, -1, -1, -64, -1, -13, -1, -32, -49, -32, -1, -25, -8, 127, + -97, -25, -1, -2, 63, -49, -13, -4, -1, 15, -13, -1, -1, -64, 127, -7, -1, -119, -17, -15, -1, + -25, -8, 127, -97, -25, -1, -2, 63, -49, -13, -4, -1, 15, -13, -3, -1, -64, 127, -8, -2, 15, + -17, -1, -1, -25, -8, 127, -97, -25, -1, -8, 63, -49, -13, -4, -1, 15, -13, -3, -1, -64, 63, + -4, 120, 0, -17, -1, -1, -25, -8, 127, -97, -25, -8, 0, 63, -57, -29, -4, -1, 15, -13, -4, + -1, -64, 63, -4, 0, 15, -17, -1, -1, -25, -8, 127, -97, -25, -8, 0, 63, -57, -29, -4, -1, + -1, -13, -4, -1, -64, 31, -2, 0, 0, 103, -1, -1, -57, -8, 127, -97, -25, -8, 0, 63, -57, + -29, -4, -1, -1, -13, -4, 127, -64, 31, -2, 0, 15, 103, -1, -1, -57, -8, 127, -97, -25, -8, + 0, 63, -61, -61, -4, 127, -1, -29, -4, 127, -64, 15, -8, 0, 0, 55, -1, -1, -121, -8, 127, + -97, -25, -8, 0, 63, -61, -61, -4, 127, -1, -29, -4, 63, -64, 15, -32, 0, 0, 23, -1, -2, + 3, -16, 63, 15, -61, -16, 0, 31, -127, -127, -8, 31, -1, -127, -8, 31, -128, 7, -128, 0, 0}; -static inline int -get_pixel(int x, int y) +static inline int get_pixel(int x, int y) { - return (image_bitmap[(x>>3) + y*image_row_length]>>(~x&0x7)) & 1; + return (image_bitmap[(x >> 3) + y * image_row_length] >> (~x & 0x7)) & 1; } static int bodyCount = 0; -static void -update(cpSpace *space, double dt) +static void update(cpSpace* space, double dt) { - cpSpaceStep(space, dt); + cpSpaceStep(space, dt); } -static void -DrawDot(cpBody *body, void *unused) +static void DrawDot(cpBody* body, void* unused) { - ChipmunkDebugDrawDot(3.5/ChipmunkDebugDrawPointLineScale, cpBodyGetPosition(body), RGBAColor(0xee/255.0f, 0xe8/255.0f, 0xd5/255.0f, 1.0f)); + ChipmunkDebugDrawDot(3.5 / ChipmunkDebugDrawPointLineScale, cpBodyGetPosition(body), + RGBAColor(0xee / 255.0f, 0xe8 / 255.0f, 0xd5 / 255.0f, 1.0f)); } -static void -draw(cpSpace *space) +static void draw(cpSpace* space) { - cpSpaceEachBody(space, DrawDot, NULL); - -// ChipmunkDebugDrawCollisionPoints(space); + cpSpaceEachBody(space, DrawDot, NULL); + + // ChipmunkDebugDrawCollisionPoints(space); } -static cpShape * -make_ball(cpFloat x, cpFloat y) +static cpShape* make_ball(cpFloat x, cpFloat y) { - cpBody *body = cpBodyNew(1.0, INFINITY); - cpBodySetPosition(body, cpv(x, y)); - - cpShape *shape = cpCircleShapeNew(body, 0.95, cpvzero); - cpShapeSetElasticity(shape, 0.0); - cpShapeSetFriction(shape, 0.0); - - return shape; + cpBody* body = cpBodyNew(1.0, INFINITY); + cpBodySetPosition(body, cpv(x, y)); + + cpShape* shape = cpCircleShapeNew(body, 0.95, cpvzero); + cpShapeSetElasticity(shape, 0.0); + cpShapeSetFriction(shape, 0.0); + + return shape; } -static cpSpace * -init(void) +static cpSpace* init(void) { - cpSpace *space = cpSpaceNew(); - cpSpaceSetIterations(space, 1); - - // The space will contain a very large number of similary sized objects. - // This is the perfect candidate for using the spatial hash. - // Generally you will never need to do this. - cpSpaceUseSpatialHash(space, 2.0, 10000); - - bodyCount = 0; - - cpBody *body; - cpShape *shape; - - for(int y=0; yn) < 0){ - return cpArbiterIgnore(arb); - } - - return cpTrue; + CP_ARBITER_GET_SHAPES(arb, a, b); + OneWayPlatform* platform = (OneWayPlatform*)cpShapeGetUserData(a); + + if (cpvdot(cpArbiterGetNormal(arb), platform->n) < 0) + { + return cpArbiterIgnore(arb); + } + + return cpTrue; } -static void -update(cpSpace *space, double dt) +static void update(cpSpace* space, double dt) { - cpSpaceStep(space, dt); + cpSpaceStep(space, dt); } -static cpSpace * -init(void) +static cpSpace* init(void) { - ChipmunkDemoMessageString = "One way platforms are trivial in Chipmunk using a very simple collision callback."; - - cpSpace *space = cpSpaceNew(); - cpSpaceSetIterations(space, 10); - cpSpaceSetGravity(space, cpv(0, -100)); - - cpBody *body, *staticBody = cpSpaceGetStaticBody(space); - cpShape *shape; - - // Create segments around the edge of the screen. - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(-320,240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320,-240), cpv(320,240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - // Add our one way segment - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-160,-100), cpv(160,-100), 10.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetCollisionType(shape, COLLISION_TYPE_ONE_WAY); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - // We'll use the data pointer for the OneWayPlatform struct - platformInstance.n = cpv(0, 1); // let objects pass upwards - cpShapeSetUserData(shape, &platformInstance); - - - // Add a ball to test it out - cpFloat radius = 15.0f; - body = cpSpaceAddBody(space, cpBodyNew(10.0f, cpMomentForCircle(10.0f, 0.0f, radius, cpvzero))); - cpBodySetPosition(body, cpv(0, -200)); - cpBodySetVelocity(body, cpv(0, 170)); - - shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.9f); - cpShapeSetCollisionType(shape, 2); - - cpCollisionHandler *handler = cpSpaceAddWildcardHandler(space, COLLISION_TYPE_ONE_WAY); - handler->preSolveFunc = PreSolve; - - return space; + ChipmunkDemoMessageString = "One way platforms are trivial in Chipmunk using a very simple collision callback."; + + cpSpace* space = cpSpaceNew(); + cpSpaceSetIterations(space, 10); + cpSpaceSetGravity(space, cpv(0, -100)); + + cpBody *body, *staticBody = cpSpaceGetStaticBody(space); + cpShape* shape; + + // Create segments around the edge of the screen. + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(-320, 240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320, -240), cpv(320, 240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(320, -240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + // Add our one way segment + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-160, -100), cpv(160, -100), 10.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetCollisionType(shape, COLLISION_TYPE_ONE_WAY); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + // We'll use the data pointer for the OneWayPlatform struct + platformInstance.n = cpv(0, 1); // let objects pass upwards + cpShapeSetUserData(shape, &platformInstance); + + // Add a ball to test it out + cpFloat radius = 15.0f; + body = cpSpaceAddBody(space, cpBodyNew(10.0f, cpMomentForCircle(10.0f, 0.0f, radius, cpvzero))); + cpBodySetPosition(body, cpv(0, -200)); + cpBodySetVelocity(body, cpv(0, 170)); + + shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.9f); + cpShapeSetCollisionType(shape, 2); + + cpCollisionHandler* handler = cpSpaceAddWildcardHandler(space, COLLISION_TYPE_ONE_WAY); + handler->preSolveFunc = PreSolve; + + return space; } -static void -destroy(cpSpace *space) +static void destroy(cpSpace* space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo OneWay = { - "One Way Platforms", - 1.0/60.0, - init, - update, - ChipmunkDemoDefaultDrawImpl, - destroy, + "One Way Platforms", 1.0 / 60.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Planet.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Planet.c index e169e184175f..cc7d4f8c6985 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Planet.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Planet.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,114 +18,105 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" -static cpBody *planetBody; +static cpBody* planetBody; static cpFloat gravityStrength = 5.0e6f; -static void -update(cpSpace *space, double dt) +static void update(cpSpace* space, double dt) { - cpSpaceStep(space, dt); + cpSpaceStep(space, dt); } -static void -planetGravityVelocityFunc(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt) +static void planetGravityVelocityFunc(cpBody* body, cpVect gravity, cpFloat damping, cpFloat dt) { - // Gravitational acceleration is proportional to the inverse square of - // distance, and directed toward the origin. The central planet is assumed - // to be massive enough that it affects the satellites but not vice versa. - cpVect p = cpBodyGetPosition(body); - cpFloat sqdist = cpvlengthsq(p); - cpVect g = cpvmult(p, -gravityStrength / (sqdist * cpfsqrt(sqdist))); - - cpBodyUpdateVelocity(body, g, damping, dt); + // Gravitational acceleration is proportional to the inverse square of + // distance, and directed toward the origin. The central planet is assumed + // to be massive enough that it affects the satellites but not vice versa. + cpVect p = cpBodyGetPosition(body); + cpFloat sqdist = cpvlengthsq(p); + cpVect g = cpvmult(p, -gravityStrength / (sqdist * cpfsqrt(sqdist))); + + cpBodyUpdateVelocity(body, g, damping, dt); } -static cpVect -rand_pos(cpFloat radius) +static cpVect rand_pos(cpFloat radius) { - cpVect v; - do { - v = cpv(frand()*(640 - 2*radius) - (320 - radius), frand()*(480 - 2*radius) - (240 - radius)); - } while(cpvlength(v) < 85.0f); - - return v; + cpVect v; + do + { + v = cpv(frand() * (640 - 2 * radius) - (320 - radius), frand() * (480 - 2 * radius) - (240 - radius)); + } while (cpvlength(v) < 85.0f); + + return v; } -static void -add_box(cpSpace *space) +static void add_box(cpSpace* space) { - const cpFloat size = 10.0f; - const cpFloat mass = 1.0f; - - cpVect verts[] = { - cpv(-size,-size), - cpv(-size, size), - cpv( size, size), - cpv( size,-size), - }; - - cpFloat radius = cpvlength(cpv(size, size)); - cpVect pos = rand_pos(radius); - - cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 4, verts, cpvzero, 0.0f))); - cpBodySetVelocityUpdateFunc(body, planetGravityVelocityFunc); - cpBodySetPosition(body, pos); - - // Set the box's velocity to put it into a circular orbit from its - // starting position. - cpFloat r = cpvlength(pos); - cpFloat v = cpfsqrt(gravityStrength / r) / r; - cpBodySetVelocity(body, cpvmult(cpvperp(pos), v)); - - // Set the box's angular velocity to match its orbital period and - // align its initial angle with its position. - cpBodySetAngularVelocity(body, v); - cpBodySetAngle(body, cpfatan2(pos.y, pos.x)); - - cpShape *shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 4, verts, cpTransformIdentity, 0.0)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.7f); + const cpFloat size = 10.0f; + const cpFloat mass = 1.0f; + + cpVect verts[] = { + cpv(-size, -size), + cpv(-size, size), + cpv(size, size), + cpv(size, -size), + }; + + cpFloat radius = cpvlength(cpv(size, size)); + cpVect pos = rand_pos(radius); + + cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 4, verts, cpvzero, 0.0f))); + cpBodySetVelocityUpdateFunc(body, planetGravityVelocityFunc); + cpBodySetPosition(body, pos); + + // Set the box's velocity to put it into a circular orbit from its + // starting position. + cpFloat r = cpvlength(pos); + cpFloat v = cpfsqrt(gravityStrength / r) / r; + cpBodySetVelocity(body, cpvmult(cpvperp(pos), v)); + + // Set the box's angular velocity to match its orbital period and + // align its initial angle with its position. + cpBodySetAngularVelocity(body, v); + cpBodySetAngle(body, cpfatan2(pos.y, pos.x)); + + cpShape* shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 4, verts, cpTransformIdentity, 0.0)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.7f); } -static cpSpace * -init(void) +static cpSpace* init(void) { - // Create a rouge body to control the planet manually. - cpSpace *space = cpSpaceNew(); - cpSpaceSetIterations(space, 20); - - planetBody = cpSpaceAddBody(space, cpBodyNewKinematic()); - cpBodySetAngularVelocity(planetBody, 0.2f); - - for(int i=0; i<30; i++){ - add_box(space); - } - - cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(planetBody, 70.0f, cpvzero)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - return space; + // Create a rouge body to control the planet manually. + cpSpace* space = cpSpaceNew(); + cpSpaceSetIterations(space, 20); + + planetBody = cpSpaceAddBody(space, cpBodyNewKinematic()); + cpBodySetAngularVelocity(planetBody, 0.2f); + + for (int i = 0; i < 30; i++) + { + add_box(space); + } + + cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(planetBody, 70.0f, cpvzero)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + return space; } -static void -destroy(cpSpace *space) +static void destroy(cpSpace* space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo Planet = { - "Planet", - 1.0/60.0, - init, - update, - ChipmunkDemoDefaultDrawImpl, - destroy, + "Planet", 1.0 / 60.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Player.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Player.c index a1d9ddcbb764..0ed950dc8077 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Player.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Player.c @@ -25,153 +25,156 @@ #define PLAYER_VELOCITY 500.0 #define PLAYER_GROUND_ACCEL_TIME 0.1 -#define PLAYER_GROUND_ACCEL (PLAYER_VELOCITY / PLAYER_GROUND_ACCEL_TIME) +#define PLAYER_GROUND_ACCEL (PLAYER_VELOCITY / PLAYER_GROUND_ACCEL_TIME) #define PLAYER_AIR_ACCEL_TIME 0.25 -#define PLAYER_AIR_ACCEL (PLAYER_VELOCITY / PLAYER_AIR_ACCEL_TIME) +#define PLAYER_AIR_ACCEL (PLAYER_VELOCITY / PLAYER_AIR_ACCEL_TIME) -#define JUMP_HEIGHT 50.0 +#define JUMP_HEIGHT 50.0 #define JUMP_BOOST_HEIGHT 55.0 -#define FALL_VELOCITY 900.0 -#define GRAVITY 2000.0 +#define FALL_VELOCITY 900.0 +#define GRAVITY 2000.0 - -static cpBody* playerBody = NULL; +static cpBody* playerBody = NULL; static cpShape* playerShape = NULL; static cpFloat remainingBoost = 0; -static cpBool grounded = cpFalse; -static cpBool lastJumpState = cpFalse; +static cpBool grounded = cpFalse; +static cpBool lastJumpState = cpFalse; -static void SelectPlayerGroundNormal(cpBody* body, cpArbiter* arb, cpVect* groundNormal) { - cpVect n = cpvneg(cpArbiterGetNormal(arb)); +static void SelectPlayerGroundNormal(cpBody* body, cpArbiter* arb, cpVect* groundNormal) +{ + cpVect n = cpvneg(cpArbiterGetNormal(arb)); - if (n.y > groundNormal->y) { - (*groundNormal) = n; - } + if (n.y > groundNormal->y) + { + (*groundNormal) = n; + } } -static void playerUpdateVelocity(cpBody* body, cpVect gravity, cpFloat damping, cpFloat dt) { - int jumpState = (ChipmunkDemoKeyboard.y > 0.0f); - - // Grab the grounding normal from last frame - cpVect groundNormal = cpvzero; - cpBodyEachArbiter(playerBody, (cpBodyArbiterIteratorFunc)SelectPlayerGroundNormal, &groundNormal); +static void playerUpdateVelocity(cpBody* body, cpVect gravity, cpFloat damping, cpFloat dt) +{ + int jumpState = (ChipmunkDemoKeyboard.y > 0.0f); - grounded = (groundNormal.y > 0.0); - if (groundNormal.y < 0.0f) - remainingBoost = 0.0f; + // Grab the grounding normal from last frame + cpVect groundNormal = cpvzero; + cpBodyEachArbiter(playerBody, (cpBodyArbiterIteratorFunc)SelectPlayerGroundNormal, &groundNormal); - // Do a normal-ish update - cpBool boost = (jumpState && remainingBoost > 0.0f); - cpVect g = (boost ? cpvzero : gravity); - cpBodyUpdateVelocity(body, g, damping, dt); + grounded = (groundNormal.y > 0.0); + if (groundNormal.y < 0.0f) + remainingBoost = 0.0f; - // Target horizontal speed for air/ground control - cpFloat target_vx = PLAYER_VELOCITY * ChipmunkDemoKeyboard.x; + // Do a normal-ish update + cpBool boost = (jumpState && remainingBoost > 0.0f); + cpVect g = (boost ? cpvzero : gravity); + cpBodyUpdateVelocity(body, g, damping, dt); + // Target horizontal speed for air/ground control + cpFloat target_vx = PLAYER_VELOCITY * ChipmunkDemoKeyboard.x; - // Update the surface velocity and friction - // Note that the "feet" move in the opposite direction of the player. - cpVect surface_v = cpv(-target_vx, 0.0); - playerShape->surfaceV = surface_v; - playerShape->u = (grounded ? PLAYER_GROUND_ACCEL / GRAVITY : 0.0); + // Update the surface velocity and friction + // Note that the "feet" move in the opposite direction of the player. + cpVect surface_v = cpv(-target_vx, 0.0); + playerShape->surfaceV = surface_v; + playerShape->u = (grounded ? PLAYER_GROUND_ACCEL / GRAVITY : 0.0); - // Apply air control if not grounded - if (!grounded) { - // Smoothly accelerate the velocity - playerBody->v.x = cpflerpconst(playerBody->v.x, target_vx, PLAYER_AIR_ACCEL * dt); - } + // Apply air control if not grounded + if (!grounded) + { + // Smoothly accelerate the velocity + playerBody->v.x = cpflerpconst(playerBody->v.x, target_vx, PLAYER_AIR_ACCEL * dt); + } - body->v.y = cpfclamp(body->v.y, -FALL_VELOCITY, INFINITY); + body->v.y = cpfclamp(body->v.y, -FALL_VELOCITY, INFINITY); } -static void update(cpSpace* space, double dt) { - int jumpState = (ChipmunkDemoKeyboard.y > 0.0f); +static void update(cpSpace* space, double dt) +{ + int jumpState = (ChipmunkDemoKeyboard.y > 0.0f); - // If the jump key was just pressed this frame, jump! - if (jumpState && !lastJumpState && grounded) { - cpFloat jump_v = cpfsqrt(2.0 * JUMP_HEIGHT * GRAVITY); - playerBody->v = cpvadd(playerBody->v, cpv(0.0, jump_v)); + // If the jump key was just pressed this frame, jump! + if (jumpState && !lastJumpState && grounded) + { + cpFloat jump_v = cpfsqrt(2.0 * JUMP_HEIGHT * GRAVITY); + playerBody->v = cpvadd(playerBody->v, cpv(0.0, jump_v)); - remainingBoost = JUMP_BOOST_HEIGHT / jump_v; - } + remainingBoost = JUMP_BOOST_HEIGHT / jump_v; + } - // Step the space - cpSpaceStep(space, dt); + // Step the space + cpSpaceStep(space, dt); - remainingBoost -= dt; - lastJumpState = jumpState; + remainingBoost -= dt; + lastJumpState = jumpState; } -static cpSpace* init(void) { - cpSpace* space = cpSpaceNew(); - space->iterations = 10; - space->gravity = cpv(0, -GRAVITY); - // space->sleepTimeThreshold = 1000; - - cpBody* body, * staticBody = cpSpaceGetStaticBody(space); - cpShape* shape; - - // Create segments around the edge of the screen. - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(-320, 240), 0.0f)); - shape->e = 1.0f; - shape->u = 1.0f; - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320, -240), cpv(320, 240), 0.0f)); - shape->e = 1.0f; - shape->u = 1.0f; - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(320, -240), 0.0f)); - shape->e = 1.0f; - shape->u = 1.0f; - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, 240), cpv(320, 240), 0.0f)); - shape->e = 1.0f; - shape->u = 1.0f; - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - // Set up the player - body = cpSpaceAddBody(space, cpBodyNew(1.0f, INFINITY)); - body->p = cpv(0, -200); - body->velocity_func = playerUpdateVelocity; - playerBody = body; - - shape = cpSpaceAddShape(space, cpBoxShapeNew2(body, cpBBNew(-15.0, -27.5, 15.0, 27.5), 1.0)); - // shape = cpSpaceAddShape(space, cpSegmentShapeNew(playerBody, cpvzero, cpv(0, radius), radius)); - shape->e = 0.0f; - shape->u = 0.0f; - shape->type = 1; - playerShape = shape; - - // Add some boxes to jump on - for (int i = 0; i < 6; i++) { - for (int j = 0; j < 3; j++) { - body = cpSpaceAddBody(space, cpBodyNew(4.0f, INFINITY)); - body->p = cpv(100 + j * 60, -200 + i * 60); - - shape = cpSpaceAddShape(space, cpBoxShapeNew(body, 50, 50, 0.0)); - shape->e = 0.0f; - shape->u = 0.7f; - } - } - - return space; +static cpSpace* init(void) +{ + cpSpace* space = cpSpaceNew(); + space->iterations = 10; + space->gravity = cpv(0, -GRAVITY); + // space->sleepTimeThreshold = 1000; + + cpBody *body, *staticBody = cpSpaceGetStaticBody(space); + cpShape* shape; + + // Create segments around the edge of the screen. + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(-320, 240), 0.0f)); + shape->e = 1.0f; + shape->u = 1.0f; + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320, -240), cpv(320, 240), 0.0f)); + shape->e = 1.0f; + shape->u = 1.0f; + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(320, -240), 0.0f)); + shape->e = 1.0f; + shape->u = 1.0f; + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, 240), cpv(320, 240), 0.0f)); + shape->e = 1.0f; + shape->u = 1.0f; + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + // Set up the player + body = cpSpaceAddBody(space, cpBodyNew(1.0f, INFINITY)); + body->p = cpv(0, -200); + body->velocity_func = playerUpdateVelocity; + playerBody = body; + + shape = cpSpaceAddShape(space, cpBoxShapeNew2(body, cpBBNew(-15.0, -27.5, 15.0, 27.5), 1.0)); + // shape = cpSpaceAddShape(space, cpSegmentShapeNew(playerBody, cpvzero, cpv(0, radius), radius)); + shape->e = 0.0f; + shape->u = 0.0f; + shape->type = 1; + playerShape = shape; + + // Add some boxes to jump on + for (int i = 0; i < 6; i++) + { + for (int j = 0; j < 3; j++) + { + body = cpSpaceAddBody(space, cpBodyNew(4.0f, INFINITY)); + body->p = cpv(100 + j * 60, -200 + i * 60); + + shape = cpSpaceAddShape(space, cpBoxShapeNew(body, 50, 50, 0.0)); + shape->e = 0.0f; + shape->u = 0.7f; + } + } + + return space; } -static void destroy(cpSpace* space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); +static void destroy(cpSpace* space) +{ + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo PlatformerPlayer = { - "Platformer Player Controls", - 1.0 / 180.0, - init, - update, - ChipmunkDemoDefaultDrawImpl, - destroy, + "Platformer Player Controls", 1.0 / 180.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Plink.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Plink.c index ecf7ca2129a5..dec53e8bc4e4 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Plink.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Plink.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,115 +18,116 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" -static cpFloat pentagon_mass = 0.0f; +static cpFloat pentagon_mass = 0.0f; static cpFloat pentagon_moment = 0.0f; // Iterate over all of the bodies and reset the ones that have fallen offscreen. -static void -eachBody(cpBody *body, void *unused) +static void eachBody(cpBody* body, void* unused) { - cpVect pos = cpBodyGetPosition(body); - if(pos.y < -260){ - cpFloat x = rand()/(cpFloat)RAND_MAX*640 - 320; - cpBodySetPosition(body, cpv(x, 260)); - } + cpVect pos = cpBodyGetPosition(body); + if (pos.y < -260) + { + cpFloat x = rand() / (cpFloat)RAND_MAX * 640 - 320; + cpBodySetPosition(body, cpv(x, 260)); + } } -static void -update(cpSpace *space, double dt) +static void update(cpSpace* space, double dt) { - if(ChipmunkDemoRightDown){ + if (ChipmunkDemoRightDown) + { ChipmunkDemoRightDown = cpFalse; - cpShape *nearest = cpSpacePointQueryNearest(space, ChipmunkDemoMouse, 0.0, GRAB_FILTER, NULL); - if(nearest){ - cpBody *body = cpShapeGetBody(nearest); - if(cpBodyGetType(body) == CP_BODY_TYPE_STATIC){ - cpBodySetType(body, CP_BODY_TYPE_DYNAMIC); - cpBodySetMass(body, pentagon_mass); - cpBodySetMoment(body, pentagon_moment); - } else if(cpBodyGetType(body) == CP_BODY_TYPE_DYNAMIC) { - cpBodySetType(body, CP_BODY_TYPE_STATIC); - } - } - } - - cpSpaceEachBody(space, &eachBody, NULL); - cpSpaceStep(space, dt); + cpShape* nearest = cpSpacePointQueryNearest(space, ChipmunkDemoMouse, 0.0, GRAB_FILTER, NULL); + if (nearest) + { + cpBody* body = cpShapeGetBody(nearest); + if (cpBodyGetType(body) == CP_BODY_TYPE_STATIC) + { + cpBodySetType(body, CP_BODY_TYPE_DYNAMIC); + cpBodySetMass(body, pentagon_mass); + cpBodySetMoment(body, pentagon_moment); + } + else if (cpBodyGetType(body) == CP_BODY_TYPE_DYNAMIC) + { + cpBodySetType(body, CP_BODY_TYPE_STATIC); + } + } + } + + cpSpaceEachBody(space, &eachBody, NULL); + cpSpaceStep(space, dt); } #define NUM_VERTS 5 -static cpSpace * -init(void) +static cpSpace* init(void) { - ChipmunkDemoMessageString = "Right click to make pentagons static/dynamic."; - - cpSpace *space = cpSpaceNew(); - cpSpaceSetIterations(space, 5); - cpSpaceSetGravity(space, cpv(0, -100)); - - cpBody *body, *staticBody = cpSpaceGetStaticBody(space); - cpShape *shape; - - // Vertexes for a triangle shape. - cpVect tris[] = { - cpv(-15,-15), - cpv( 0, 10), - cpv( 15,-15), - }; - - // Create the static triangles. - for(int i=0; i<10; i++){ - for(int j=0; j<6; j++){ - cpFloat stagger = (j%2)*40; - cpVect offset = cpv(i*80 - 360 + stagger, j*70 - 200); - shape = cpSpaceAddShape(space, cpPolyShapeNew(staticBody, 3, tris, cpTransformTranslate(offset), 0.0)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - } - } - - // Create vertexes for a pentagon shape. - cpVect verts[NUM_VERTS]; - for(int i=0; i 320.0f){ - cpBodySetVelocity(ball, cpvzero); - cpBodySetPosition(ball, cpv(-224.0f, 200.0f)); - } - } + cpFloat coef = (2.0f + ChipmunkDemoKeyboard.y) / 3.0f; + cpFloat rate = ChipmunkDemoKeyboard.x * 30.0f * coef; + + cpSimpleMotorSetRate(motor, rate); + cpConstraintSetMaxForce(motor, rate ? 1000000.0f : 0.0f); + + cpSpaceStep(space, dt); + + for (int i = 0; i < numBalls; i++) + { + cpBody* ball = balls[i]; + cpVect pos = cpBodyGetPosition(ball); + + if (pos.x > 320.0f) + { + cpBodySetVelocity(ball, cpvzero); + cpBodySetPosition(ball, cpv(-224.0f, 200.0f)); + } + } } -static cpBody * -add_ball(cpSpace *space, cpVect pos) +static cpBody* add_ball(cpSpace* space, cpVect pos) { - cpBody *body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForCircle(1.0f, 30, 0, cpvzero))); - cpBodySetPosition(body, pos); - - cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, 30, cpvzero)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.5f); - - return body; + cpBody* body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForCircle(1.0f, 30, 0, cpvzero))); + cpBodySetPosition(body, pos); + + cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(body, 30, cpvzero)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.5f); + + return body; } -static cpSpace * -init(void) +static cpSpace* init(void) { - ChipmunkDemoMessageString = "Use the arrow keys to control the machine."; - - cpSpace *space = cpSpaceNew(); - cpSpaceSetGravity(space, cpv(0, -600)); - - cpBody *staticBody = cpSpaceGetStaticBody(space); - cpShape *shape; - - // beveling all of the line segments slightly helps prevent things from getting stuck on cracks - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-256,16), cpv(-256,300), 2.0f)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.5f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-256,16), cpv(-192,0), 2.0f)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.5f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-192,0), cpv(-192, -64), 2.0f)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.5f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-128,-64), cpv(-128,144), 2.0f)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.5f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-192,80), cpv(-192,176), 2.0f)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.5f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-192,176), cpv(-128,240), 2.0f)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.5f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-128,144), cpv(192,64), 2.0f)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.5f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - cpVect verts[] = { - cpv(-30,-80), - cpv(-30, 80), - cpv( 30, 64), - cpv( 30,-80), - }; - - cpBody *plunger = cpSpaceAddBody(space, cpBodyNew(1.0f, INFINITY)); - cpBodySetPosition(plunger, cpv(-160,-80)); - - shape = cpSpaceAddShape(space, cpPolyShapeNew(plunger, 4, verts, cpTransformIdentity, 0.0)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 0.5f); - cpShapeSetFilter(shape, cpShapeFilterNew(CP_NO_GROUP, 1, 1)); - - // add balls to hopper - for(int i=0; i> 16) & 0xFFFF) / (cpFloat) 0xFFFF)); + return cpv(cpflerp(border, 1.0f - border, (cpFloat)(h & 0xFFFF) / (cpFloat)0xFFFF), + cpflerp(border, 1.0f - border, (cpFloat)((h >> 16) & 0xFFFF) / (cpFloat)0xFFFF)); } -static cpVect WorleyPoint(int i, int j, struct WorleyContex* context) { +static cpVect WorleyPoint(int i, int j, struct WorleyContex* context) +{ cpFloat size = context->cellSize; int width = context->width; int height = context->height; @@ -56,18 +59,28 @@ static cpVect WorleyPoint(int i, int j, struct WorleyContex* context) { cpVect fv = HashVect(i, j, context->seed); return cpv(cpflerp(bb.l, bb.r, 0.5f) + size * (i + fv.x - width * 0.5f), - cpflerp(bb.b, bb.t, 0.5f) + size * (j + fv.y - height * 0.5f)); + cpflerp(bb.b, bb.t, 0.5f) + size * (j + fv.y - height * 0.5f)); } -static int ClipCell(cpShape* shape, cpVect center, int i, int j, struct WorleyContex* context, cpVect* verts, - cpVect* clipped, int count) { +static int ClipCell(cpShape* shape, + cpVect center, + int i, + int j, + struct WorleyContex* context, + cpVect* verts, + cpVect* clipped, + int count) +{ cpVect other = WorleyPoint(i, j, context); // printf(" other %dx%d: (% 5.2f, % 5.2f) ", i, j, other.x, other.y); - if (cpShapePointQuery(shape, other, NULL) > 0.0f) { + if (cpShapePointQuery(shape, other, NULL) > 0.0f) + { // printf("excluded\n"); memcpy(clipped, verts, count * sizeof(cpVect)); return count; - } else { + } + else + { // printf("clipped\n"); } @@ -75,11 +88,13 @@ static int ClipCell(cpShape* shape, cpVect center, int i, int j, struct WorleyCo cpFloat dist = cpvdot(n, cpvlerp(center, other, 0.5f)); int clipped_count = 0; - for (int j = 0, i = count - 1; j < count; i = j, j++) { + for (int j = 0, i = count - 1; j < count; i = j, j++) + { cpVect a = verts[i]; cpFloat a_dist = cpvdot(a, n) - dist; - if (a_dist <= 0.0) { + if (a_dist <= 0.0) + { clipped[clipped_count] = a; clipped_count++; } @@ -87,7 +102,8 @@ static int ClipCell(cpShape* shape, cpVect center, int i, int j, struct WorleyCo cpVect b = verts[j]; cpFloat b_dist = cpvdot(b, n) - dist; - if (a_dist * b_dist < 0.0f) { + if (a_dist * b_dist < 0.0f) + { cpFloat t = cpfabs(a_dist) / (cpfabs(a_dist) + cpfabs(b_dist)); clipped[clipped_count] = cpvlerp(a, b, t); @@ -98,25 +114,34 @@ static int ClipCell(cpShape* shape, cpVect center, int i, int j, struct WorleyCo return clipped_count; } -static void ShatterCell( - cpSpace* space, cpShape* shape, cpVect cell, int cell_i, int cell_j, struct WorleyContex* context) { +static void ShatterCell(cpSpace* space, + cpShape* shape, + cpVect cell, + int cell_i, + int cell_j, + struct WorleyContex* context) +{ // printf("cell %dx%d: (% 5.2f, % 5.2f)\n", cell_i, cell_j, cell.x, cell.y); cpBody* body = cpShapeGetBody(shape); - cpVect* ping = (cpVect*) alloca(MAX_VERTEXES_PER_VORONOI * sizeof(cpVect)); - cpVect* pong = (cpVect*) alloca(MAX_VERTEXES_PER_VORONOI * sizeof(cpVect)); + cpVect* ping = (cpVect*)alloca(MAX_VERTEXES_PER_VORONOI * sizeof(cpVect)); + cpVect* pong = (cpVect*)alloca(MAX_VERTEXES_PER_VORONOI * sizeof(cpVect)); int count = cpPolyShapeGetCount(shape); count = (count > MAX_VERTEXES_PER_VORONOI ? MAX_VERTEXES_PER_VORONOI : count); - for (int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { ping[i] = cpBodyLocalToWorld(body, cpPolyShapeGetVert(shape, i)); } - for (int i = 0; i < context->width; i++) { - for (int j = 0; j < context->height; j++) { - if (!(i == cell_i && j == cell_j) && cpShapePointQuery(shape, cell, NULL) < 0.0f) { + for (int i = 0; i < context->width; i++) + { + for (int j = 0; j < context->height; j++) + { + if (!(i == cell_i && j == cell_j) && cpShapePointQuery(shape, cell, NULL) < 0.0f) + { count = ClipCell(shape, cell, i, j, context, ping, pong, count); memcpy(ping, pong, count * sizeof(cpVect)); } @@ -138,20 +163,24 @@ static void ShatterCell( cpShapeSetFriction(new_shape, cpShapeGetFriction(shape)); } -static void ShatterShape(cpSpace* space, cpShape* shape, cpFloat cellSize, cpVect focus) { +static void ShatterShape(cpSpace* space, cpShape* shape, cpFloat cellSize, cpVect focus) +{ cpSpaceRemoveShape(space, shape); cpSpaceRemoveBody(space, cpShapeGetBody(shape)); cpBB bb = cpShapeGetBB(shape); - int width = (int) ((bb.r - bb.l) / cellSize) + 1; - int height = (int) ((bb.t - bb.b) / cellSize) + 1; + int width = (int)((bb.r - bb.l) / cellSize) + 1; + int height = (int)((bb.t - bb.b) / cellSize) + 1; // printf("Splitting as %dx%d\n", width, height); struct WorleyContex context = {(uint32_t)rand(), cellSize, width, height, bb, focus}; - for (int i = 0; i < context.width; i++) { - for (int j = 0; j < context.height; j++) { + for (int i = 0; i < context.width; i++) + { + for (int j = 0; j < context.height; j++) + { cpVect cell = WorleyPoint(i, j, &context); - if (cpShapePointQuery(shape, cell, NULL) < 0.0f) { + if (cpShapePointQuery(shape, cell, NULL) < 0.0f) + { ShatterCell(space, shape, cell, i, j, &context); } } @@ -161,17 +190,23 @@ static void ShatterShape(cpSpace* space, cpShape* shape, cpFloat cellSize, cpVec cpShapeFree(shape); } -static void update(cpSpace* space, double dt) { +static void update(cpSpace* space, double dt) +{ cpSpaceStep(space, dt); - if (ChipmunkDemoRightDown) { + if (ChipmunkDemoRightDown) + { cpPointQueryInfo info; - if (cpSpacePointQueryNearest(space, ChipmunkDemoMouse, 0, GRAB_FILTER, &info)) { + if (cpSpacePointQueryNearest(space, ChipmunkDemoMouse, 0, GRAB_FILTER, &info)) + { cpBB bb = cpShapeGetBB(info.shape); cpFloat cell_size = cpfmax(bb.r - bb.l, bb.t - bb.b) / 5.0f; - if (cell_size > 5.0f) { - ShatterShape(space, (cpShape*) info.shape, cell_size, ChipmunkDemoMouse); - } else { + if (cell_size > 5.0f) + { + ShatterShape(space, (cpShape*)info.shape, cell_size, ChipmunkDemoMouse); + } + else + { // printf("Too small to splinter %f\n", cell_size); } } @@ -179,7 +214,8 @@ static void update(cpSpace* space, double dt) { } } -static cpSpace* init(void) { +static cpSpace* init(void) +{ ChipmunkDemoMessageString = "Right click something to shatter it."; cpSpace* space = cpSpaceNew(); @@ -210,16 +246,12 @@ static cpSpace* init(void) { return space; } -static void destroy(cpSpace* space) { +static void destroy(cpSpace* space) +{ ChipmunkDemoFreeSpaceChildren(space); cpSpaceFree(space); } ChipmunkDemo Shatter = { - "Shatter.", - 1.0f / 60.0f, - init, - update, - ChipmunkDemoDefaultDrawImpl, - destroy, + "Shatter.", 1.0f / 60.0f, init, update, ChipmunkDemoDefaultDrawImpl, destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Slice.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Slice.c index 069de159dc70..445452e17a6a 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Slice.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Slice.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,171 +18,171 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" -#define DENSITY (1.0/10000.0) +#define DENSITY (1.0 / 10000.0) -static void -ClipPoly(cpSpace *space, cpShape *shape, cpVect n, cpFloat dist) +static void ClipPoly(cpSpace* space, cpShape* shape, cpVect n, cpFloat dist) { - cpBody *body = cpShapeGetBody(shape); - - int count = cpPolyShapeGetCount(shape); - int clippedCount = 0; - - cpVect *clipped = (cpVect *)alloca((count + 1)*sizeof(cpVect)); - - for(int i=0, j=count-1; ia; - cpVect b = context->b; - - // Clipping plane normal and distance. - cpVect n = cpvnormalize(cpvperp(cpvsub(b, a))); - cpFloat dist = cpvdot(a, n); - - ClipPoly(space, shape, n, dist); - ClipPoly(space, shape, cpvneg(n), -dist); - - cpBody *body = cpShapeGetBody(shape); - cpSpaceRemoveShape(space, shape); - cpSpaceRemoveBody(space, body); - cpShapeFree(shape); - cpBodyFree(body); + cpVect a = context->a; + cpVect b = context->b; + + // Clipping plane normal and distance. + cpVect n = cpvnormalize(cpvperp(cpvsub(b, a))); + cpFloat dist = cpvdot(a, n); + + ClipPoly(space, shape, n, dist); + ClipPoly(space, shape, cpvneg(n), -dist); + + cpBody* body = cpShapeGetBody(shape); + cpSpaceRemoveShape(space, shape); + cpSpaceRemoveBody(space, body); + cpShapeFree(shape); + cpBodyFree(body); } -static void -SliceQuery(cpShape *shape, cpVect point, cpVect normal, cpFloat alpha, struct SliceContext *context) +static void SliceQuery(cpShape* shape, cpVect point, cpVect normal, cpFloat alpha, struct SliceContext* context) { - cpVect a = context->a; - cpVect b = context->b; - - // Check that the slice was complete by checking that the endpoints aren't in the sliced shape. - if(cpShapePointQuery(shape, a, NULL) > 0.0f && cpShapePointQuery(shape, b, NULL) > 0.0f){ - // Can't modify the space during a query. - // Must make a post-step callback to do the actual slicing. - cpSpaceAddPostStepCallback(context->space, (cpPostStepFunc)SliceShapePostStep, shape, context); - } + cpVect a = context->a; + cpVect b = context->b; + + // Check that the slice was complete by checking that the endpoints aren't in the sliced shape. + if (cpShapePointQuery(shape, a, NULL) > 0.0f && cpShapePointQuery(shape, b, NULL) > 0.0f) + { + // Can't modify the space during a query. + // Must make a post-step callback to do the actual slicing. + cpSpaceAddPostStepCallback(context->space, (cpPostStepFunc)SliceShapePostStep, shape, context); + } } -static void -update(cpSpace *space, double dt) +static void update(cpSpace* space, double dt) { - cpSpaceStep(space, dt); - - static cpBool lastClickState = cpFalse; - static cpVect sliceStart = {0.0, 0.0}; - - // Annoying state tracking code that you wouldn't need - // in a real event driven system. - if(ChipmunkDemoRightClick != lastClickState){ - if(ChipmunkDemoRightClick){ - // MouseDown - sliceStart = ChipmunkDemoMouse; - } else { - // MouseUp - struct SliceContext context = {sliceStart, ChipmunkDemoMouse, space}; - cpSpaceSegmentQuery(space, sliceStart, ChipmunkDemoMouse, 0.0, GRAB_FILTER, (cpSpaceSegmentQueryFunc)SliceQuery, &context); - } - - lastClickState = ChipmunkDemoRightClick; - } - - if(ChipmunkDemoRightClick){ - ChipmunkDebugDrawSegment(sliceStart, ChipmunkDemoMouse, RGBAColor(1, 0, 0, 1)); - } + cpSpaceStep(space, dt); + + static cpBool lastClickState = cpFalse; + static cpVect sliceStart = {0.0, 0.0}; + + // Annoying state tracking code that you wouldn't need + // in a real event driven system. + if (ChipmunkDemoRightClick != lastClickState) + { + if (ChipmunkDemoRightClick) + { + // MouseDown + sliceStart = ChipmunkDemoMouse; + } + else + { + // MouseUp + struct SliceContext context = {sliceStart, ChipmunkDemoMouse, space}; + cpSpaceSegmentQuery(space, sliceStart, ChipmunkDemoMouse, 0.0, GRAB_FILTER, + (cpSpaceSegmentQueryFunc)SliceQuery, &context); + } + + lastClickState = ChipmunkDemoRightClick; + } + + if (ChipmunkDemoRightClick) + { + ChipmunkDebugDrawSegment(sliceStart, ChipmunkDemoMouse, RGBAColor(1, 0, 0, 1)); + } } -static cpSpace * -init(void) +static cpSpace* init(void) { - ChipmunkDemoMessageString = "Right click and drag to slice up the block."; - - cpSpace *space = cpSpaceNew(); - cpSpaceSetIterations(space, 30); - cpSpaceSetGravity(space, cpv(0, -500)); - cpSpaceSetSleepTimeThreshold(space, 0.5f); - cpSpaceSetCollisionSlop(space, 0.5f); - - cpBody *body, *staticBody = cpSpaceGetStaticBody(space); - cpShape *shape; - - // Create segments around the edge of the screen. - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-1000,-240), cpv(1000,-240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - cpFloat width = 200.0f; - cpFloat height = 300.0f; - cpFloat mass = width*height*DENSITY; - cpFloat moment = cpMomentForBox(mass, width, height); - - body = cpSpaceAddBody(space, cpBodyNew(mass, moment)); - - shape = cpSpaceAddShape(space, cpBoxShapeNew(body, width, height, 0.0)); - cpShapeSetFriction(shape, 0.6f); - - return space; + ChipmunkDemoMessageString = "Right click and drag to slice up the block."; + + cpSpace* space = cpSpaceNew(); + cpSpaceSetIterations(space, 30); + cpSpaceSetGravity(space, cpv(0, -500)); + cpSpaceSetSleepTimeThreshold(space, 0.5f); + cpSpaceSetCollisionSlop(space, 0.5f); + + cpBody *body, *staticBody = cpSpaceGetStaticBody(space); + cpShape* shape; + + // Create segments around the edge of the screen. + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-1000, -240), cpv(1000, -240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + cpFloat width = 200.0f; + cpFloat height = 300.0f; + cpFloat mass = width * height * DENSITY; + cpFloat moment = cpMomentForBox(mass, width, height); + + body = cpSpaceAddBody(space, cpBodyNew(mass, moment)); + + shape = cpSpaceAddShape(space, cpBoxShapeNew(body, width, height, 0.0)); + cpShapeSetFriction(shape, 0.6f); + + return space; } -static void -destroy(cpSpace *space) +static void destroy(cpSpace* space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo Slice = { - "Slice.", - 1.0/60.0, - init, - update, - ChipmunkDemoDefaultDrawImpl, - destroy, + "Slice.", 1.0 / 60.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Springies.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Springies.c index 8673e08fbee6..89fdfab17025 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Springies.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Springies.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,145 +18,135 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" -static cpFloat -springForce(cpConstraint *spring, cpFloat dist) +static cpFloat springForce(cpConstraint* spring, cpFloat dist) { - cpFloat clamp = 20.0f; - return cpfclamp(cpDampedSpringGetRestLength(spring) - dist, -clamp, clamp)*cpDampedSpringGetStiffness(spring); + cpFloat clamp = 20.0f; + return cpfclamp(cpDampedSpringGetRestLength(spring) - dist, -clamp, clamp) * cpDampedSpringGetStiffness(spring); } -static cpConstraint * -new_spring(cpBody *a, cpBody *b, cpVect anchorA, cpVect anchorB, cpFloat restLength, cpFloat stiff, cpFloat damp) +static cpConstraint* +new_spring(cpBody* a, cpBody* b, cpVect anchorA, cpVect anchorB, cpFloat restLength, cpFloat stiff, cpFloat damp) { - cpConstraint *spring = cpDampedSpringNew(a, b, anchorA, anchorB, restLength, stiff, damp); - cpDampedSpringSetSpringForceFunc(spring, springForce); - - return spring; + cpConstraint* spring = cpDampedSpringNew(a, b, anchorA, anchorB, restLength, stiff, damp); + cpDampedSpringSetSpringForceFunc(spring, springForce); + + return spring; } -static void -update(cpSpace *space, double dt) +static void update(cpSpace* space, double dt) { - cpSpaceStep(space, dt); + cpSpaceStep(space, dt); } -static cpBody * -add_bar(cpSpace *space, cpVect a, cpVect b, int group) +static cpBody* add_bar(cpSpace* space, cpVect a, cpVect b, int group) { - cpVect center = cpvmult(cpvadd(a, b), 1.0f/2.0f); - cpFloat length = cpvlength(cpvsub(b, a)); - cpFloat mass = length/160.0f; - - cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, mass*length*length/12.0f)); - cpBodySetPosition(body, center); - - cpShape *shape = cpSpaceAddShape(space, cpSegmentShapeNew(body, cpvsub(a, center), cpvsub(b, center), 10.0f)); - cpShapeSetFilter(shape, cpShapeFilterNew(group, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); - - return body; + cpVect center = cpvmult(cpvadd(a, b), 1.0f / 2.0f); + cpFloat length = cpvlength(cpvsub(b, a)); + cpFloat mass = length / 160.0f; + + cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, mass * length * length / 12.0f)); + cpBodySetPosition(body, center); + + cpShape* shape = cpSpaceAddShape(space, cpSegmentShapeNew(body, cpvsub(a, center), cpvsub(b, center), 10.0f)); + cpShapeSetFilter(shape, cpShapeFilterNew(group, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); + + return body; } -static cpSpace * -init(void) +static cpSpace* init(void) { - cpSpace *space = cpSpaceNew(); - cpBody *staticBody = cpSpaceGetStaticBody(space); - - cpBody *body1 = add_bar(space, cpv(-240, 160), cpv(-160, 80), 1); - cpBody *body2 = add_bar(space, cpv(-160, 80), cpv( -80, 160), 1); - cpBody *body3 = add_bar(space, cpv( 0, 160), cpv( 80, 0), 0); - cpBody *body4 = add_bar(space, cpv( 160, 160), cpv( 240, 160), 0); - cpBody *body5 = add_bar(space, cpv(-240, 0), cpv(-160, -80), 2); - cpBody *body6 = add_bar(space, cpv(-160, -80), cpv( -80, 0), 2); - cpBody *body7 = add_bar(space, cpv( -80, 0), cpv( 0, 0), 2); - cpBody *body8 = add_bar(space, cpv( 0, -80), cpv( 80, -80), 0); - cpBody *body9 = add_bar(space, cpv( 240, 80), cpv( 160, 0), 3); - cpBody *body10 = add_bar(space, cpv( 160, 0), cpv( 240, -80), 3); - cpBody *body11 = add_bar(space, cpv(-240, -80), cpv(-160, -160), 4); - cpBody *body12 = add_bar(space, cpv(-160, -160), cpv( -80, -160), 4); - cpBody *body13 = add_bar(space, cpv( 0, -160), cpv( 80, -160), 0); - cpBody *body14 = add_bar(space, cpv( 160, -160), cpv( 240, -160), 0); - - cpSpaceAddConstraint(space, cpPivotJointNew2( body1, body2, cpv( 40,-40), cpv(-40,-40))); - cpSpaceAddConstraint(space, cpPivotJointNew2( body5, body6, cpv( 40,-40), cpv(-40,-40))); - cpSpaceAddConstraint(space, cpPivotJointNew2( body6, body7, cpv( 40, 40), cpv(-40, 0))); - cpSpaceAddConstraint(space, cpPivotJointNew2( body9, body10, cpv(-40,-40), cpv(-40, 40))); - cpSpaceAddConstraint(space, cpPivotJointNew2(body11, body12, cpv( 40,-40), cpv(-40, 0))); - - cpFloat stiff = 100.0f; - cpFloat damp = 0.5f; - cpSpaceAddConstraint(space, new_spring(staticBody, body1, cpv(-320, 240), cpv(-40, 40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body1, cpv(-320, 80), cpv(-40, 40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body1, cpv(-160, 240), cpv(-40, 40), 0.0f, stiff, damp)); - - cpSpaceAddConstraint(space, new_spring(staticBody, body2, cpv(-160, 240), cpv( 40, 40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body2, cpv( 0, 240), cpv( 40, 40), 0.0f, stiff, damp)); - - cpSpaceAddConstraint(space, new_spring(staticBody, body3, cpv( 80, 240), cpv(-40, 80), 0.0f, stiff, damp)); - - cpSpaceAddConstraint(space, new_spring(staticBody, body4, cpv( 80, 240), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body4, cpv( 320, 240), cpv( 40, 0), 0.0f, stiff, damp)); - - cpSpaceAddConstraint(space, new_spring(staticBody, body5, cpv(-320, 80), cpv(-40, 40), 0.0f, stiff, damp)); - - cpSpaceAddConstraint(space, new_spring(staticBody, body9, cpv( 320, 80), cpv( 40, 40), 0.0f, stiff, damp)); - - cpSpaceAddConstraint(space, new_spring(staticBody, body10, cpv( 320, 0), cpv( 40,-40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body10, cpv( 320,-160), cpv( 40,-40), 0.0f, stiff, damp)); - - cpSpaceAddConstraint(space, new_spring(staticBody, body11, cpv(-320,-160), cpv(-40, 40), 0.0f, stiff, damp)); - - cpSpaceAddConstraint(space, new_spring(staticBody, body12, cpv(-240,-240), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body12, cpv( 0,-240), cpv( 40, 0), 0.0f, stiff, damp)); - - cpSpaceAddConstraint(space, new_spring(staticBody, body13, cpv( 0,-240), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body13, cpv( 80,-240), cpv( 40, 0), 0.0f, stiff, damp)); - - cpSpaceAddConstraint(space, new_spring(staticBody, body14, cpv( 80,-240), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body14, cpv( 240,-240), cpv( 40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(staticBody, body14, cpv( 320,-160), cpv( 40, 0), 0.0f, stiff, damp)); - - cpSpaceAddConstraint(space, new_spring( body1, body5, cpv( 40,-40), cpv(-40, 40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring( body1, body6, cpv( 40,-40), cpv( 40, 40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring( body2, body3, cpv( 40, 40), cpv(-40, 80), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring( body3, body4, cpv(-40, 80), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring( body3, body4, cpv( 40,-80), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring( body3, body7, cpv( 40,-80), cpv( 40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring( body3, body7, cpv(-40, 80), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring( body3, body8, cpv( 40,-80), cpv( 40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring( body3, body9, cpv( 40,-80), cpv(-40,-40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring( body4, body9, cpv( 40, 0), cpv( 40, 40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring( body5, body11, cpv(-40, 40), cpv(-40, 40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring( body5, body11, cpv( 40,-40), cpv( 40,-40), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring( body7, body8, cpv( 40, 0), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring( body8, body12, cpv(-40, 0), cpv( 40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring( body8, body13, cpv(-40, 0), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring( body8, body13, cpv( 40, 0), cpv( 40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring( body8, body14, cpv( 40, 0), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(body10, body14, cpv( 40,-40), cpv(-40, 0), 0.0f, stiff, damp)); - cpSpaceAddConstraint(space, new_spring(body10, body14, cpv( 40,-40), cpv(-40, 0), 0.0f, stiff, damp)); - - return space; + cpSpace* space = cpSpaceNew(); + cpBody* staticBody = cpSpaceGetStaticBody(space); + + cpBody* body1 = add_bar(space, cpv(-240, 160), cpv(-160, 80), 1); + cpBody* body2 = add_bar(space, cpv(-160, 80), cpv(-80, 160), 1); + cpBody* body3 = add_bar(space, cpv(0, 160), cpv(80, 0), 0); + cpBody* body4 = add_bar(space, cpv(160, 160), cpv(240, 160), 0); + cpBody* body5 = add_bar(space, cpv(-240, 0), cpv(-160, -80), 2); + cpBody* body6 = add_bar(space, cpv(-160, -80), cpv(-80, 0), 2); + cpBody* body7 = add_bar(space, cpv(-80, 0), cpv(0, 0), 2); + cpBody* body8 = add_bar(space, cpv(0, -80), cpv(80, -80), 0); + cpBody* body9 = add_bar(space, cpv(240, 80), cpv(160, 0), 3); + cpBody* body10 = add_bar(space, cpv(160, 0), cpv(240, -80), 3); + cpBody* body11 = add_bar(space, cpv(-240, -80), cpv(-160, -160), 4); + cpBody* body12 = add_bar(space, cpv(-160, -160), cpv(-80, -160), 4); + cpBody* body13 = add_bar(space, cpv(0, -160), cpv(80, -160), 0); + cpBody* body14 = add_bar(space, cpv(160, -160), cpv(240, -160), 0); + + cpSpaceAddConstraint(space, cpPivotJointNew2(body1, body2, cpv(40, -40), cpv(-40, -40))); + cpSpaceAddConstraint(space, cpPivotJointNew2(body5, body6, cpv(40, -40), cpv(-40, -40))); + cpSpaceAddConstraint(space, cpPivotJointNew2(body6, body7, cpv(40, 40), cpv(-40, 0))); + cpSpaceAddConstraint(space, cpPivotJointNew2(body9, body10, cpv(-40, -40), cpv(-40, 40))); + cpSpaceAddConstraint(space, cpPivotJointNew2(body11, body12, cpv(40, -40), cpv(-40, 0))); + + cpFloat stiff = 100.0f; + cpFloat damp = 0.5f; + cpSpaceAddConstraint(space, new_spring(staticBody, body1, cpv(-320, 240), cpv(-40, 40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body1, cpv(-320, 80), cpv(-40, 40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body1, cpv(-160, 240), cpv(-40, 40), 0.0f, stiff, damp)); + + cpSpaceAddConstraint(space, new_spring(staticBody, body2, cpv(-160, 240), cpv(40, 40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body2, cpv(0, 240), cpv(40, 40), 0.0f, stiff, damp)); + + cpSpaceAddConstraint(space, new_spring(staticBody, body3, cpv(80, 240), cpv(-40, 80), 0.0f, stiff, damp)); + + cpSpaceAddConstraint(space, new_spring(staticBody, body4, cpv(80, 240), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body4, cpv(320, 240), cpv(40, 0), 0.0f, stiff, damp)); + + cpSpaceAddConstraint(space, new_spring(staticBody, body5, cpv(-320, 80), cpv(-40, 40), 0.0f, stiff, damp)); + + cpSpaceAddConstraint(space, new_spring(staticBody, body9, cpv(320, 80), cpv(40, 40), 0.0f, stiff, damp)); + + cpSpaceAddConstraint(space, new_spring(staticBody, body10, cpv(320, 0), cpv(40, -40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body10, cpv(320, -160), cpv(40, -40), 0.0f, stiff, damp)); + + cpSpaceAddConstraint(space, new_spring(staticBody, body11, cpv(-320, -160), cpv(-40, 40), 0.0f, stiff, damp)); + + cpSpaceAddConstraint(space, new_spring(staticBody, body12, cpv(-240, -240), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body12, cpv(0, -240), cpv(40, 0), 0.0f, stiff, damp)); + + cpSpaceAddConstraint(space, new_spring(staticBody, body13, cpv(0, -240), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body13, cpv(80, -240), cpv(40, 0), 0.0f, stiff, damp)); + + cpSpaceAddConstraint(space, new_spring(staticBody, body14, cpv(80, -240), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body14, cpv(240, -240), cpv(40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(staticBody, body14, cpv(320, -160), cpv(40, 0), 0.0f, stiff, damp)); + + cpSpaceAddConstraint(space, new_spring(body1, body5, cpv(40, -40), cpv(-40, 40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(body1, body6, cpv(40, -40), cpv(40, 40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(body2, body3, cpv(40, 40), cpv(-40, 80), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(body3, body4, cpv(-40, 80), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(body3, body4, cpv(40, -80), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(body3, body7, cpv(40, -80), cpv(40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(body3, body7, cpv(-40, 80), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(body3, body8, cpv(40, -80), cpv(40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(body3, body9, cpv(40, -80), cpv(-40, -40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(body4, body9, cpv(40, 0), cpv(40, 40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(body5, body11, cpv(-40, 40), cpv(-40, 40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(body5, body11, cpv(40, -40), cpv(40, -40), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(body7, body8, cpv(40, 0), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(body8, body12, cpv(-40, 0), cpv(40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(body8, body13, cpv(-40, 0), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(body8, body13, cpv(40, 0), cpv(40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(body8, body14, cpv(40, 0), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(body10, body14, cpv(40, -40), cpv(-40, 0), 0.0f, stiff, damp)); + cpSpaceAddConstraint(space, new_spring(body10, body14, cpv(40, -40), cpv(-40, 0), 0.0f, stiff, damp)); + + return space; } -static void -destroy(cpSpace *space) +static void destroy(cpSpace* space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo Springies = { - "Springies", - 1.0/60.0, - init, - update, - ChipmunkDemoDefaultDrawImpl, - destroy, + "Springies", 1.0 / 60.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Sticky.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Sticky.c index 29924d19156e..f7545afdbf17 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Sticky.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Sticky.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,180 +18,173 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" -enum { - COLLISION_TYPE_STICKY = 1, +enum +{ + COLLISION_TYPE_STICKY = 1, }; #define STICK_SENSOR_THICKNESS 2.5f -static void -PostStepAddJoint(cpSpace *space, void *key, void *data) +static void PostStepAddJoint(cpSpace* space, void* key, void* data) { -// printf("Adding joint for %p\n", data); - - cpConstraint *joint = (cpConstraint *)key; - cpSpaceAddConstraint(space, joint); + // printf("Adding joint for %p\n", data); + + cpConstraint* joint = (cpConstraint*)key; + cpSpaceAddConstraint(space, joint); } -static cpBool -StickyPreSolve(cpArbiter *arb, cpSpace *space, void *data) +static cpBool StickyPreSolve(cpArbiter* arb, cpSpace* space, void* data) { - // We want to fudge the collisions a bit to allow shapes to overlap more. - // This simulates their squishy sticky surface, and more importantly - // keeps them from separating and destroying the joint. - - // Track the deepest collision point and use that to determine if a rigid collision should occur. - cpFloat deepest = INFINITY; - - // Grab the contact set and iterate over them. - cpContactPointSet contacts = cpArbiterGetContactPointSet(arb); - for(int i=0; ipreSolveFunc = StickyPreSolve; - handler->separateFunc = StickySeparate; - - return space; + ChipmunkDemoMessageString = "Sticky collisions using the cpArbiter data pointer."; + + cpSpace* space = cpSpaceNew(); + cpSpaceSetIterations(space, 10); + cpSpaceSetGravity(space, cpv(0, -1000)); + cpSpaceSetCollisionSlop(space, 2.0); + + cpBody* staticBody = cpSpaceGetStaticBody(space); + cpShape* shape; + + // Create segments around the edge of the screen. + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-340, -260), cpv(-340, 260), 20.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(340, -260), cpv(340, 260), 20.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-340, -260), cpv(340, -260), 20.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-340, 260), cpv(340, 260), 20.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + for (int i = 0; i < 200; i++) + { + cpFloat mass = 0.15f; + cpFloat radius = 10.0f; + + cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero))); + cpBodySetPosition(body, cpv(cpflerp(-150.0f, 150.0f, frand()), cpflerp(-150.0f, 150.0f, frand()))); + + cpShape* shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius + STICK_SENSOR_THICKNESS, cpvzero)); + cpShapeSetFriction(shape, 0.9f); + cpShapeSetCollisionType(shape, COLLISION_TYPE_STICKY); + } + + cpCollisionHandler* handler = cpSpaceAddWildcardHandler(space, COLLISION_TYPE_STICKY); + handler->preSolveFunc = StickyPreSolve; + handler->separateFunc = StickySeparate; + + return space; } -static void -destroy(cpSpace *space) +static void destroy(cpSpace* space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo Sticky = { - "Sticky Surfaces", - 1.0/60.0, - init, - update, - ChipmunkDemoDefaultDrawImpl, - destroy, + "Sticky Surfaces", 1.0 / 60.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Tank.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Tank.c index 249828966a29..3b5d1d41b417 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Tank.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/Tank.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -18,119 +18,115 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" static cpBody *tankBody, *tankControlBody; -static void -update(cpSpace *space, double dt) +static void update(cpSpace* space, double dt) { - // turn the control body based on the angle relative to the actual body - cpVect mouseDelta = cpvsub(ChipmunkDemoMouse, cpBodyGetPosition(tankBody)); - cpFloat turn = cpvtoangle(cpvunrotate(cpBodyGetRotation(tankBody), mouseDelta)); - cpBodySetAngle(tankControlBody, cpBodyGetAngle(tankBody) - turn); - - // drive the tank towards the mouse - if(cpvnear(ChipmunkDemoMouse, cpBodyGetPosition(tankBody), 30.0)){ - cpBodySetVelocity(tankControlBody, cpvzero); // stop - } else { - cpFloat direction = (cpvdot(mouseDelta, cpBodyGetRotation(tankBody)) > 0.0 ? 1.0 : -1.0); - cpBodySetVelocity(tankControlBody, cpvrotate(cpBodyGetRotation(tankBody), cpv(30.0f*direction, 0.0f))); - } - - cpSpaceStep(space, dt); + // turn the control body based on the angle relative to the actual body + cpVect mouseDelta = cpvsub(ChipmunkDemoMouse, cpBodyGetPosition(tankBody)); + cpFloat turn = cpvtoangle(cpvunrotate(cpBodyGetRotation(tankBody), mouseDelta)); + cpBodySetAngle(tankControlBody, cpBodyGetAngle(tankBody) - turn); + + // drive the tank towards the mouse + if (cpvnear(ChipmunkDemoMouse, cpBodyGetPosition(tankBody), 30.0)) + { + cpBodySetVelocity(tankControlBody, cpvzero); // stop + } + else + { + cpFloat direction = (cpvdot(mouseDelta, cpBodyGetRotation(tankBody)) > 0.0 ? 1.0 : -1.0); + cpBodySetVelocity(tankControlBody, cpvrotate(cpBodyGetRotation(tankBody), cpv(30.0f * direction, 0.0f))); + } + + cpSpaceStep(space, dt); } -static cpBody * -add_box(cpSpace *space, cpFloat size, cpFloat mass) +static cpBody* add_box(cpSpace* space, cpFloat size, cpFloat mass) { - cpFloat radius = cpvlength(cpv(size, size)); - - cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForBox(mass, size, size))); - cpBodySetPosition(body, cpv(frand()*(640 - 2*radius) - (320 - radius), frand()*(480 - 2*radius) - (240 - radius))); - - cpShape *shape = cpSpaceAddShape(space, cpBoxShapeNew(body, size, size, 0.0)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 0.7f); - - return body; + cpFloat radius = cpvlength(cpv(size, size)); + + cpBody* body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForBox(mass, size, size))); + cpBodySetPosition( + body, cpv(frand() * (640 - 2 * radius) - (320 - radius), frand() * (480 - 2 * radius) - (240 - radius))); + + cpShape* shape = cpSpaceAddShape(space, cpBoxShapeNew(body, size, size, 0.0)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 0.7f); + + return body; } -static cpSpace * -init(void) +static cpSpace* init(void) { - ChipmunkDemoMessageString = "Use the mouse to drive the tank, it will follow the cursor."; - - cpSpace *space = cpSpaceNew(); - cpSpaceSetIterations(space, 10); - cpSpaceSetSleepTimeThreshold(space, 0.5f); - - cpBody *staticBody = cpSpaceGetStaticBody(space); - cpShape *shape; - - // Create segments around the edge of the screen. - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(-320,240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320,-240), cpv(320,240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,240), cpv(320,240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - for(int i=0; i<50; i++){ - cpBody *body = add_box(space, 20, 1); - - cpConstraint *pivot = cpSpaceAddConstraint(space, cpPivotJointNew2(staticBody, body, cpvzero, cpvzero)); - cpConstraintSetMaxBias(pivot, 0); // disable joint correction - cpConstraintSetMaxForce(pivot, 1000.0f); // emulate linear friction - - cpConstraint *gear = cpSpaceAddConstraint(space, cpGearJointNew(staticBody, body, 0.0f, 1.0f)); - cpConstraintSetMaxBias(gear, 0); // disable joint correction - cpConstraintSetMaxForce(gear, 5000.0f); // emulate angular friction - } - - // We joint the tank to the control body and control the tank indirectly by modifying the control body. - tankControlBody = cpSpaceAddBody(space, cpBodyNewKinematic()); - tankBody = add_box(space, 30, 10); - - cpConstraint *pivot = cpSpaceAddConstraint(space, cpPivotJointNew2(tankControlBody, tankBody, cpvzero, cpvzero)); - cpConstraintSetMaxBias(pivot, 0); // disable joint correction - cpConstraintSetMaxForce(pivot, 10000.0f); // emulate linear friction - - cpConstraint *gear = cpSpaceAddConstraint(space, cpGearJointNew(tankControlBody, tankBody, 0.0f, 1.0f)); - cpConstraintSetErrorBias(gear, 0); // attempt to fully correct the joint each step - cpConstraintSetMaxBias(gear, 1.2f); // but limit it's angular correction rate - cpConstraintSetMaxForce(gear, 50000.0f); // emulate angular friction - - return space; + ChipmunkDemoMessageString = "Use the mouse to drive the tank, it will follow the cursor."; + + cpSpace* space = cpSpaceNew(); + cpSpaceSetIterations(space, 10); + cpSpaceSetSleepTimeThreshold(space, 0.5f); + + cpBody* staticBody = cpSpaceGetStaticBody(space); + cpShape* shape; + + // Create segments around the edge of the screen. + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(-320, 240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320, -240), cpv(320, 240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, -240), cpv(320, -240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320, 240), cpv(320, 240), 0.0f)); + cpShapeSetElasticity(shape, 1.0f); + cpShapeSetFriction(shape, 1.0f); + cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); + + for (int i = 0; i < 50; i++) + { + cpBody* body = add_box(space, 20, 1); + + cpConstraint* pivot = cpSpaceAddConstraint(space, cpPivotJointNew2(staticBody, body, cpvzero, cpvzero)); + cpConstraintSetMaxBias(pivot, 0); // disable joint correction + cpConstraintSetMaxForce(pivot, 1000.0f); // emulate linear friction + + cpConstraint* gear = cpSpaceAddConstraint(space, cpGearJointNew(staticBody, body, 0.0f, 1.0f)); + cpConstraintSetMaxBias(gear, 0); // disable joint correction + cpConstraintSetMaxForce(gear, 5000.0f); // emulate angular friction + } + + // We joint the tank to the control body and control the tank indirectly by modifying the control body. + tankControlBody = cpSpaceAddBody(space, cpBodyNewKinematic()); + tankBody = add_box(space, 30, 10); + + cpConstraint* pivot = cpSpaceAddConstraint(space, cpPivotJointNew2(tankControlBody, tankBody, cpvzero, cpvzero)); + cpConstraintSetMaxBias(pivot, 0); // disable joint correction + cpConstraintSetMaxForce(pivot, 10000.0f); // emulate linear friction + + cpConstraint* gear = cpSpaceAddConstraint(space, cpGearJointNew(tankControlBody, tankBody, 0.0f, 1.0f)); + cpConstraintSetErrorBias(gear, 0); // attempt to fully correct the joint each step + cpConstraintSetMaxBias(gear, 1.2f); // but limit it's angular correction rate + cpConstraintSetMaxForce(gear, 50000.0f); // emulate angular friction + + return space; } -static void -destroy(cpSpace *space) +static void destroy(cpSpace* space) { - ChipmunkDemoFreeSpaceChildren(space); - cpSpaceFree(space); + ChipmunkDemoFreeSpaceChildren(space); + cpSpaceFree(space); } ChipmunkDemo Tank = { - "Tank", - 1.0/60.0, - init, - update, - ChipmunkDemoDefaultDrawImpl, - destroy, + "Tank", 1.0 / 60.0, init, update, ChipmunkDemoDefaultDrawImpl, destroy, }; diff --git a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/TheoJansen.c b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/TheoJansen.c index 262dedbcd1f1..7888cf861cab 100644 --- a/tests/cpp-tests/Classes/ChipmunkTestBed/demo/TheoJansen.c +++ b/tests/cpp-tests/Classes/ChipmunkTestBed/demo/TheoJansen.c @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * 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 @@ -24,145 +24,140 @@ * the mechanism that Theo Jansen uses in his kinetic sculptures. Brilliant. * Read more here: http://en.wikipedia.org/wiki/Theo_Jansen */ - + #include "chipmunk/chipmunk.h" #include "ChipmunkDemo.h" -static cpConstraint *motor; +static cpConstraint* motor; -static void -update(cpSpace *space, double dt) +static void update(cpSpace* space, double dt) { cpFloat coef = (2.0f + ChipmunkDemoKeyboard.y) / 3.0f; cpFloat rate = ChipmunkDemoKeyboard.x * 10.0f * coef; - cpSimpleMotorSetRate(motor, rate); - cpConstraintSetMaxForce(motor, (rate) ? 100000.0f : 0.0f); - - cpSpaceStep(space, dt); + cpSimpleMotorSetRate(motor, rate); + cpConstraintSetMaxForce(motor, (rate) ? 100000.0f : 0.0f); + + cpSpaceStep(space, dt); } static cpFloat seg_radius = 3.0f; -static void -make_leg(cpSpace *space, cpFloat side, cpFloat offset, cpBody *chassis, cpBody *crank, cpVect anchor) +static void make_leg(cpSpace* space, cpFloat side, cpFloat offset, cpBody* chassis, cpBody* crank, cpVect anchor) { - cpVect a, b; - cpShape *shape; - - cpFloat leg_mass = 1.0f; - - // make leg - a = cpvzero, b = cpv(0.0f, side); - cpBody *upper_leg = cpSpaceAddBody(space, cpBodyNew(leg_mass, cpMomentForSegment(leg_mass, a, b, 0.0f))); - cpBodySetPosition(upper_leg, cpv(offset, 0.0f)); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(upper_leg, a, b, seg_radius)); - cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); - - cpSpaceAddConstraint(space, cpPivotJointNew2(chassis, upper_leg, cpv(offset, 0.0f), cpvzero)); - - // lower leg - a = cpvzero, b = cpv(0.0f, -1.0f*side); - cpBody *lower_leg = cpSpaceAddBody(space, cpBodyNew(leg_mass, cpMomentForSegment(leg_mass, a, b, 0.0f))); - cpBodySetPosition(lower_leg, cpv(offset, -side)); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(lower_leg, a, b, seg_radius)); - cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); - - shape = cpSpaceAddShape(space, cpCircleShapeNew(lower_leg, seg_radius*2.0f, b)); - cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); - cpShapeSetElasticity(shape, 0.0f); - cpShapeSetFriction(shape, 1.0f); - - cpSpaceAddConstraint(space, cpPinJointNew(chassis, lower_leg, cpv(offset, 0.0f), cpvzero)); - - cpSpaceAddConstraint(space, cpGearJointNew(upper_leg, lower_leg, 0.0f, 1.0f)); - - cpConstraint *constraint; - cpFloat diag = cpfsqrt(side*side + offset*offset); - - constraint = cpSpaceAddConstraint(space, cpPinJointNew(crank, upper_leg, anchor, cpv(0.0f, side))); - cpPinJointSetDist(constraint, diag); - - constraint = cpSpaceAddConstraint(space, cpPinJointNew(crank, lower_leg, anchor, cpvzero)); - cpPinJointSetDist(constraint, diag); + cpVect a, b; + cpShape* shape; + + cpFloat leg_mass = 1.0f; + + // make leg + a = cpvzero, b = cpv(0.0f, side); + cpBody* upper_leg = cpSpaceAddBody(space, cpBodyNew(leg_mass, cpMomentForSegment(leg_mass, a, b, 0.0f))); + cpBodySetPosition(upper_leg, cpv(offset, 0.0f)); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(upper_leg, a, b, seg_radius)); + cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); + + cpSpaceAddConstraint(space, cpPivotJointNew2(chassis, upper_leg, cpv(offset, 0.0f), cpvzero)); + + // lower leg + a = cpvzero, b = cpv(0.0f, -1.0f * side); + cpBody* lower_leg = cpSpaceAddBody(space, cpBodyNew(leg_mass, cpMomentForSegment(leg_mass, a, b, 0.0f))); + cpBodySetPosition(lower_leg, cpv(offset, -side)); + + shape = cpSpaceAddShape(space, cpSegmentShapeNew(lower_leg, a, b, seg_radius)); + cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); + + shape = cpSpaceAddShape(space, cpCircleShapeNew(lower_leg, seg_radius * 2.0f, b)); + cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); + cpShapeSetElasticity(shape, 0.0f); + cpShapeSetFriction(shape, 1.0f); + + cpSpaceAddConstraint(space, cpPinJointNew(chassis, lower_leg, cpv(offset, 0.0f), cpvzero)); + + cpSpaceAddConstraint(space, cpGearJointNew(upper_leg, lower_leg, 0.0f, 1.0f)); + + cpConstraint* constraint; + cpFloat diag = cpfsqrt(side * side + offset * offset); + + constraint = cpSpaceAddConstraint(space, cpPinJointNew(crank, upper_leg, anchor, cpv(0.0f, side))); + cpPinJointSetDist(constraint, diag); + + constraint = cpSpaceAddConstraint(space, cpPinJointNew(crank, lower_leg, anchor, cpvzero)); + cpPinJointSetDist(constraint, diag); } -static cpSpace * -init(void) +static cpSpace* init(void) { - ChipmunkDemoMessageString = "Use the arrow keys to control the machine."; - - cpSpace *space = cpSpaceNew(); - cpSpaceSetIterations(space, 20); - cpSpaceSetGravity(space, cpv(0,-500)); - - cpBody *staticBody = cpSpaceGetStaticBody(space); - cpShape *shape; - cpVect a, b; - - // Create segments around the edge of the screen. - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(-320,240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(320,-240), cpv(320,240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f)); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); - cpShapeSetFilter(shape, NOT_GRABBABLE_FILTER); - - cpFloat offset = 30.0f; - - // make chassis - cpFloat chassis_mass = 2.0f; - a = cpv(-offset, 0.0f), b = cpv(offset, 0.0f); - cpBody *chassis = cpSpaceAddBody(space, cpBodyNew(chassis_mass, cpMomentForSegment(chassis_mass, a, b, 0.0f))); - - shape = cpSpaceAddShape(space, cpSegmentShapeNew(chassis, a, b, seg_radius)); - cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); - - // make crank - cpFloat crank_mass = 1.0f; - cpFloat crank_radius = 13.0f; - cpBody *crank = cpSpaceAddBody(space, cpBodyNew(crank_mass, cpMomentForCircle(crank_mass, crank_radius, 0.0f, cpvzero))); - - shape = cpSpaceAddShape(space, cpCircleShapeNew(crank, crank_radius, cpvzero)); - cpShapeSetFilter(shape, cpShapeFilterNew(1, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES)); - - cpSpaceAddConstraint(space, cpPivotJointNew2(chassis, crank, cpvzero, cpvzero)); - - cpFloat side = 30.0f; - - int num_legs = 2; - for(int i=0; ionTouchBegan = CC_CALLBACK_2(ClickAndMoveTestCase::onTouchBegan, this); listener->onTouchEnded = CC_CALLBACK_2(ClickAndMoveTestCase::onTouchEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - + auto sprite = Sprite::create(s_pathGrossini); - - auto layer = LayerColor::create(Color4B(255,255,0,255)); + + auto layer = LayerColor::create(Color4B(255, 255, 0, 255)); addChild(layer, -1); - + addChild(sprite, 0, kTagSprite); - sprite->setPosition(20,150); - - sprite->runAction( JumpTo::create(4, Vec2(300,48), 100, 4) ); - - layer->runAction( RepeatForever::create( - Sequence::create( - FadeIn::create(1), - FadeOut::create(1), - nullptr) - )); + sprite->setPosition(20, 150); + + sprite->runAction(JumpTo::create(4, Vec2(300, 48), 100, 4)); + + layer->runAction(RepeatForever::create(Sequence::create(FadeIn::create(1), FadeOut::create(1), nullptr))); } -bool ClickAndMoveTestCase::onTouchBegan(Touch* touch, Event *event) +bool ClickAndMoveTestCase::onTouchBegan(Touch* touch, Event* event) { return true; } -void ClickAndMoveTestCase::onTouchEnded(Touch* touch, Event *event) +void ClickAndMoveTestCase::onTouchEnded(Touch* touch, Event* event) { auto location = touch->getLocation(); auto s = getChildByTag(kTagSprite); s->stopAllActions(); - s->runAction( MoveTo::create(1, Vec2(location.x, location.y) ) ); - float o = location.x - s->getPosition().x; - float a = location.y - s->getPosition().y; - float at = (float) CC_RADIANS_TO_DEGREES( atanf( o/a) ); - - if( a < 0 ) + s->runAction(MoveTo::create(1, Vec2(location.x, location.y))); + float o = location.x - s->getPosition().x; + float a = location.y - s->getPosition().y; + float at = (float)CC_RADIANS_TO_DEGREES(atanf(o / a)); + + if (a < 0) { - if( o < 0 ) + if (o < 0) at = 180 + fabs(at); else - at = 180 - fabs(at); + at = 180 - fabs(at); } - - s->runAction( RotateTo::create(1, at) ); + + s->runAction(RotateTo::create(1, at)); } diff --git a/tests/cpp-tests/Classes/ClickAndMoveTest/ClickAndMoveTest.h b/tests/cpp-tests/Classes/ClickAndMoveTest/ClickAndMoveTest.h index e69bdd723cd5..f11276c7876b 100644 --- a/tests/cpp-tests/Classes/ClickAndMoveTest/ClickAndMoveTest.h +++ b/tests/cpp-tests/Classes/ClickAndMoveTest/ClickAndMoveTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 diff --git a/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.cpp b/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.cpp index 1621f3927add..3aaa08dae4bb 100644 --- a/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.cpp +++ b/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -24,7 +24,7 @@ // // ClippingNodeTest -// +// // // by Pierre-David Bélanger // @@ -37,12 +37,13 @@ USING_NS_CC; -enum { - kTagTitleLabel = 1, - kTagSubtitleLabel = 2, - kTagStencilNode = 100, - kTagClipperNode = 101, - kTagContentNode = 102, +enum +{ + kTagTitleLabel = 1, + kTagSubtitleLabel = 2, + kTagStencilNode = 100, + kTagClipperNode = 101, + kTagContentNode = 102, }; ClippingNodeTests::ClippingNodeTests() @@ -71,62 +72,59 @@ ClippingNodeTests::ClippingNodeTests() bool BaseClippingNodeTest::init() { - if (TestCase::init()) { - + if (TestCase::init()) + { + auto background = Sprite::create(s_back3); - background->setAnchorPoint( Vec2::ZERO ); - background->setPosition( Vec2::ZERO ); + background->setAnchorPoint(Vec2::ZERO); + background->setPosition(Vec2::ZERO); this->addChild(background, -1); this->setup(); return true; - } - return false; + } + return false; } BaseClippingNodeTest::~BaseClippingNodeTest() { - Director::getInstance()->getTextureCache()->removeUnusedTextures(); + Director::getInstance()->getTextureCache()->removeUnusedTextures(); } std::string BaseClippingNodeTest::title() const { - return "Clipping Demo"; -} - -void BaseClippingNodeTest::setup() -{ - + return "Clipping Demo"; } +void BaseClippingNodeTest::setup() {} // BasicTest std::string BasicTest::title() const { - return "Basic Test"; + return "Basic Test"; } std::string BasicTest::subtitle() const { - return ""; + return ""; } void BasicTest::setup() { auto s = Director::getInstance()->getWinSize(); - + auto stencil = this->stencil(); - stencil->setTag( kTagStencilNode ); + stencil->setTag(kTagStencilNode); stencil->setPosition(50, 50); - + auto clipper = this->clipper(); - clipper->setTag( kTagClipperNode ); + clipper->setTag(kTagClipperNode); clipper->setAnchorPoint(Vec2(0.5f, 0.5f)); clipper->setPosition(s.width / 2 - 50, s.height / 2 - 50); clipper->setStencil(stencil); this->addChild(clipper); - + auto content = this->content(); content->setPosition(50, 50); clipper->addChild(content); @@ -159,7 +157,7 @@ DrawNode* BasicTest::shape() Sprite* BasicTest::grossini() { auto grossini = Sprite::create(s_pathGrossini); - grossini->setScale( 1.5 ); + grossini->setScale(1.5); return grossini; } @@ -178,17 +176,16 @@ Node* BasicTest::content() return nullptr; } - // ShapeTest std::string ShapeTest::title() const { - return "Shape Basic Test"; + return "Shape Basic Test"; } std::string ShapeTest::subtitle() const { - return "A DrawNode as stencil and Sprite as content"; + return "A DrawNode as stencil and Sprite as content"; } Node* ShapeTest::stencil() @@ -205,17 +202,16 @@ Node* ShapeTest::content() return node; } - // ShapeInvertedTest std::string ShapeInvertedTest::title() const { - return "Shape Inverted Basic Test"; + return "Shape Inverted Basic Test"; } std::string ShapeInvertedTest::subtitle() const { - return "A DrawNode as stencil and Sprite as content, inverted"; + return "A DrawNode as stencil and Sprite as content, inverted"; } ClippingNode* ShapeInvertedTest::clipper() @@ -229,12 +225,12 @@ ClippingNode* ShapeInvertedTest::clipper() std::string SpriteTest::title() const { - return "Sprite Basic Test"; + return "Sprite Basic Test"; } std::string SpriteTest::subtitle() const { - return "A Sprite as stencil and DrawNode as content"; + return "A Sprite as stencil and DrawNode as content"; } Node* SpriteTest::stencil() @@ -262,12 +258,12 @@ Node* SpriteTest::content() std::string SpriteNoAlphaTest::title() const { - return "Sprite No Alpha Basic Test"; + return "Sprite No Alpha Basic Test"; } std::string SpriteNoAlphaTest::subtitle() const { - return "A Sprite as stencil and DrawNode as content, no alpha"; + return "A Sprite as stencil and DrawNode as content, no alpha"; } ClippingNode* SpriteNoAlphaTest::clipper() @@ -281,12 +277,12 @@ ClippingNode* SpriteNoAlphaTest::clipper() std::string SpriteInvertedTest::title() const { - return "Sprite Inverted Basic Test"; + return "Sprite Inverted Basic Test"; } std::string SpriteInvertedTest::subtitle() const { - return "A Sprite as stencil and DrawNode as content, inverted"; + return "A Sprite as stencil and DrawNode as content, inverted"; } ClippingNode* SpriteInvertedTest::clipper() @@ -301,22 +297,23 @@ ClippingNode* SpriteInvertedTest::clipper() std::string NestedTest::title() const { - return "Nested Test"; + return "Nested Test"; } std::string NestedTest::subtitle() const { - return "Nest 9 Clipping Nodes, max is usually 8"; + return "Nest 9 Clipping Nodes, max is usually 8"; } void NestedTest::setup() { static int depth = 9; - + Node* parent = this; - - for (int i = 0; i < depth; i++) { - + + for (int i = 0; i < depth; i++) + { + int size = 225 - i * (225 / (depth * 2)); auto clipper = ClippingNode::create(); @@ -326,20 +323,19 @@ void NestedTest::setup() clipper->setAlphaThreshold(0.05f); clipper->runAction(RepeatForever::create(RotateBy::create(i % 3 ? 1.33f : 1.66f, i % 2 ? 90.0f : -90.0f))); parent->addChild(clipper); - + auto stencil = Sprite::create(s_pathGrossini); - stencil->setScale( 2.5f - (i * (2.5f / depth)) ); - stencil->setAnchorPoint( Vec2(0.5f, 0.5f) ); + stencil->setScale(2.5f - (i * (2.5f / depth))); + stencil->setAnchorPoint(Vec2(0.5f, 0.5f)); stencil->setPosition(clipper->getContentSize().width / 2, clipper->getContentSize().height / 2); stencil->setVisible(false); stencil->runAction(Sequence::createWithTwoActions(DelayTime::create(i), Show::create())); clipper->setStencil(stencil); clipper->addChild(stencil); - + parent = clipper; } - } // HoleDemo @@ -353,12 +349,12 @@ HoleDemo::~HoleDemo() std::string HoleDemo::title() const { - return "Hole Demo"; + return "Hole Demo"; } std::string HoleDemo::subtitle() const { - return "Touch/click to poke holes"; + return "Touch/click to poke holes"; } void HoleDemo::setup() @@ -366,74 +362,73 @@ void HoleDemo::setup() auto target = Sprite::create(s_pathBlock); target->setAnchorPoint(Vec2::ZERO); target->setScale(3); - + _outerClipper = ClippingNode::create(); _outerClipper->retain(); AffineTransform transform = AffineTransform::IDENTITY; - transform = AffineTransformScale(transform, target->getScale(), target->getScale()); + transform = AffineTransformScale(transform, target->getScale(), target->getScale()); _outerClipper->setContentSize(SizeApplyAffineTransform(target->getContentSize(), transform)); - _outerClipper->setAnchorPoint( Vec2(0.5f, 0.5f) ); + _outerClipper->setAnchorPoint(Vec2(0.5f, 0.5f)); _outerClipper->setPosition(Vec2(this->getContentSize()) * 0.5f); _outerClipper->runAction(RepeatForever::create(RotateBy::create(1, 45))); - - _outerClipper->setStencil( target ); - + + _outerClipper->setStencil(target); + auto holesClipper = ClippingNode::create(); holesClipper->setInverted(true); - holesClipper->setAlphaThreshold( 0.05f ); - + holesClipper->setAlphaThreshold(0.05f); + holesClipper->addChild(target); - + _holes = Node::create(); _holes->retain(); - + holesClipper->addChild(_holes); - + _holesStencil = Node::create(); _holesStencil->retain(); - - holesClipper->setStencil( _holesStencil); - + + holesClipper->setStencil(_holesStencil); + _outerClipper->addChild(holesClipper); this->addChild(_outerClipper); - auto listener = EventListenerTouchAllAtOnce::create(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(HoleDemo::onTouchesBegan, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); } void HoleDemo::pokeHoleAtPoint(Vec2 point) { - float scale = CCRANDOM_0_1() * 0.2 + 0.9; + float scale = CCRANDOM_0_1() * 0.2 + 0.9; float rotation = CCRANDOM_0_1() * 360; - + auto hole = Sprite::create("Images/hole_effect.png"); - hole->setPosition( point ); - hole->setRotation( rotation ); - hole->setScale( scale ); - + hole->setPosition(point); + hole->setRotation(rotation); + hole->setScale(scale); + _holes->addChild(hole); - + auto holeStencil = Sprite::create("Images/hole_stencil.png"); - holeStencil->setPosition( point ); - holeStencil->setRotation( rotation ); - holeStencil->setScale( scale ); - + holeStencil->setPosition(point); + holeStencil->setRotation(rotation); + holeStencil->setScale(scale); + _holesStencil->addChild(holeStencil); - _outerClipper->runAction(Sequence::createWithTwoActions(ScaleBy::create(0.05f, 0.95f), - ScaleTo::create(0.125f, 1))); + _outerClipper->runAction(Sequence::createWithTwoActions(ScaleBy::create(0.05f, 0.95f), ScaleTo::create(0.125f, 1))); } - void HoleDemo::onTouchesBegan(const std::vector& touches, Event* event) { - Touch *touch = (Touch *)touches[0]; - Vec2 point = _outerClipper->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView())); - auto rect = Rect(0, 0, _outerClipper->getContentSize().width, _outerClipper->getContentSize().height); - if (!rect.containsPoint(point)) return; + Touch* touch = (Touch*)touches[0]; + Vec2 point = _outerClipper->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView())); + auto rect = Rect(0, 0, _outerClipper->getContentSize().width, _outerClipper->getContentSize().height); + if (!rect.containsPoint(point)) + return; this->pokeHoleAtPoint(point); } @@ -441,20 +436,20 @@ void HoleDemo::onTouchesBegan(const std::vector& touches, Event* event) std::string ScrollViewDemo::title() const { - return "Scroll View Demo"; + return "Scroll View Demo"; } std::string ScrollViewDemo::subtitle() const { - return "Move/drag to scroll the content"; + return "Move/drag to scroll the content"; } void ScrollViewDemo::setup() { auto clipper = ClippingNode::create(); - clipper->setTag( kTagClipperNode ); - clipper->setContentSize( Size(200.0f, 200.0f) ); - clipper->setAnchorPoint( Vec2(0.5f, 0.5f) ); + clipper->setTag(kTagClipperNode); + clipper->setContentSize(Size(200.0f, 200.0f)); + clipper->setAnchorPoint(Vec2(0.5f, 0.5f)); clipper->setPosition(this->getContentSize().width / 2, this->getContentSize().height / 2); clipper->runAction(RepeatForever::create(RotateBy::create(1, 45))); this->addChild(clipper); @@ -465,51 +460,53 @@ void ScrollViewDemo::setup() rectangle[1] = Vec2(clipper->getContentSize().width, 0.0f); rectangle[2] = Vec2(clipper->getContentSize().width, clipper->getContentSize().height); rectangle[3] = Vec2(0.0f, clipper->getContentSize().height); - + Color4F white(1, 1, 1, 1); stencil->drawPolygon(rectangle, 4, white, 1, white); clipper->setStencil(stencil); auto content = Sprite::create(s_back2); - content->setTag( kTagContentNode ); - content->setAnchorPoint( Vec2(0.5f, 0.5f) ); + content->setTag(kTagContentNode); + content->setAnchorPoint(Vec2(0.5f, 0.5f)); content->setPosition(clipper->getContentSize().width / 2, clipper->getContentSize().height / 2); clipper->addChild(content); - + _scrolling = false; - auto listener = EventListenerTouchAllAtOnce::create(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(ScrollViewDemo::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(ScrollViewDemo::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(ScrollViewDemo::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); } -void ScrollViewDemo::onTouchesBegan(const std::vector& touches, Event *event) +void ScrollViewDemo::onTouchesBegan(const std::vector& touches, Event* event) { - Touch *touch = touches[0]; + Touch* touch = touches[0]; auto clipper = this->getChildByTag(kTagClipperNode); - Vec2 point = clipper->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView())); - auto rect = Rect(0, 0, clipper->getContentSize().width, clipper->getContentSize().height); - _scrolling = rect.containsPoint(point); - _lastPoint = point; + Vec2 point = clipper->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView())); + auto rect = Rect(0, 0, clipper->getContentSize().width, clipper->getContentSize().height); + _scrolling = rect.containsPoint(point); + _lastPoint = point; } -void ScrollViewDemo::onTouchesMoved(const std::vector& touches, Event *event) +void ScrollViewDemo::onTouchesMoved(const std::vector& touches, Event* event) { - if (!_scrolling) return; - Touch *touch = touches[0]; + if (!_scrolling) + return; + Touch* touch = touches[0]; auto clipper = this->getChildByTag(kTagClipperNode); - auto point = clipper->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView())); - Vec2 diff = point - _lastPoint; + auto point = clipper->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView())); + Vec2 diff = point - _lastPoint; auto content = clipper->getChildByTag(kTagContentNode); content->setPosition(content->getPosition() + diff); _lastPoint = point; } -void ScrollViewDemo::onTouchesEnded(const std::vector& touches, Event *event) +void ScrollViewDemo::onTouchesEnded(const std::vector& touches, Event* event) { - if (!_scrolling) return; + if (!_scrolling) + return; _scrolling = false; } @@ -519,44 +516,36 @@ void ScrollViewDemo::onTouchesEnded(const std::vector& touches, Event * static const float _alphaThreshold = 0.05f; -static const int _planeCount = 8; +static const int _planeCount = 8; static const float _planeColor[][4] = { - {0, 0, 0, 0.65f}, - {0.7f, 0, 0, 0.6f}, - {0, 0.7f, 0, 0.55f}, - {0, 0, 0.7f, 0.5f}, - {0.7f, 0.7f, 0, 0.45f}, - {0, 0.7f, 0.7f, 0.4f}, - {0.7f, 0, 0.7f, 0.35f}, - {0.7f, 0.7f, 0.7f, 0.3f}, + {0, 0, 0, 0.65f}, {0.7f, 0, 0, 0.6f}, {0, 0.7f, 0, 0.55f}, {0, 0, 0.7f, 0.5f}, + {0.7f, 0.7f, 0, 0.45f}, {0, 0.7f, 0.7f, 0.4f}, {0.7f, 0, 0.7f, 0.35f}, {0.7f, 0.7f, 0.7f, 0.3f}, }; -RawStencilBufferTest::~RawStencilBufferTest() -{ -} +RawStencilBufferTest::~RawStencilBufferTest() {} std::string RawStencilBufferTest::title() const { - return "Raw Stencil Tests"; + return "Raw Stencil Tests"; } std::string RawStencilBufferTest::subtitle() const { - return "1:Default"; + return "1:Default"; } void RawStencilBufferTest::setup() { - for(int i = 0; i < _planeCount; ++i) + for (int i = 0; i < _planeCount; ++i) { Sprite* sprite = Sprite::create(s_pathGrossini); - sprite->setAnchorPoint( Vec2(0.5, 0) ); - sprite->setScale( 2.5f ); + sprite->setAnchorPoint(Vec2(0.5, 0)); + sprite->setScale(2.5f); _sprites.pushBack(sprite); Sprite* sprite2 = Sprite::create(s_pathGrossini); - sprite2->setAnchorPoint( Vec2(0.5, 0) ); - sprite2->setScale( 2.5f ); + sprite2->setAnchorPoint(Vec2(0.5, 0)); + sprite2->setScale(2.5f); _spritesStencil.pushBack(sprite2); } @@ -565,27 +554,23 @@ void RawStencilBufferTest::setup() void RawStencilBufferTest::initCommands() { - auto renderer = Director::getInstance()->getRenderer(); - _enableStencilCallback.func = [=](){ - renderer->setStencilTest(true); - }; + auto renderer = Director::getInstance()->getRenderer(); + _enableStencilCallback.func = [=]() { renderer->setStencilTest(true); }; _enableStencilCallback.init(_globalZOrder); - _disableStencilCallback.func = [=](){ - renderer->setStencilTest(false); - }; + _disableStencilCallback.func = [=]() { renderer->setStencilTest(false); }; _disableStencilCallback.init(_globalZOrder); - auto program = backend::Program::getBuiltinProgram(backend::ProgramType::POSITION_UCOLOR); - _programState = new backend::ProgramState(program); - _locColor = _programState->getProgram()->getUniformLocation("u_color"); - _locMVPMatrix = _programState->getProgram()->getUniformLocation("u_MVPMatrix"); + auto program = backend::Program::getBuiltinProgram(backend::ProgramType::POSITION_UCOLOR); + _programState = new backend::ProgramState(program); + _locColor = _programState->getProgram()->getUniformLocation("u_color"); + _locMVPMatrix = _programState->getProgram()->getUniformLocation("u_MVPMatrix"); const auto& projectionMat = Director::getInstance()->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); _programState->setUniform(_locMVPMatrix, projectionMat.m, sizeof(projectionMat.m)); size_t neededCmdSize = _planeCount * 2; _renderCmds.resize(neededCmdSize); - auto winPoint = Vec2(Director::getInstance()->getWinSize()); + auto winPoint = Vec2(Director::getInstance()->getWinSize()); auto planeSize = winPoint * (1.0 / _planeCount); BlendFunc blend; blend.src = backend::BlendFactor::ONE; @@ -593,42 +578,31 @@ void RawStencilBufferTest::initCommands() for (int i = 0, cmdIndex = 0; i < _planeCount; i++) { auto stencilPoint = planeSize * (_planeCount - i); - stencilPoint.x = winPoint.x; + stencilPoint.x = winPoint.x; auto& cmd = _renderCmds[cmdIndex]; cmdIndex++; cmd.init(_globalZOrder, blend); - cmd.setBeforeCallback( CC_CALLBACK_0(RawStencilBufferTest::onBeforeDrawClip, this, i) ); - Vec2 vertices[] = { - Vec2::ZERO, - Vec2(stencilPoint.x, 0.0f), - stencilPoint, - Vec2(0.0f, stencilPoint.y) - }; + cmd.setBeforeCallback(CC_CALLBACK_0(RawStencilBufferTest::onBeforeDrawClip, this, i)); + Vec2 vertices[] = {Vec2::ZERO, Vec2(stencilPoint.x, 0.0f), stencilPoint, Vec2(0.0f, stencilPoint.y)}; unsigned short indices[] = {0, 2, 1, 0, 3, 2}; cmd.createVertexBuffer(sizeof(Vec2), 4, backend::BufferUsage::STATIC); cmd.updateVertexBuffer(vertices, sizeof(vertices)); cmd.createIndexBuffer(backend::IndexFormat::U_SHORT, 6, backend::BufferUsage::STATIC); cmd.updateIndexBuffer(indices, sizeof(indices)); cmd.getPipelineDescriptor().programState = _programState; - auto vertexLayout = _programState->getVertexLayout(); - auto& attributes = _programState->getProgram()->getActiveAttributes(); - auto iter = attributes.find("a_position"); + auto vertexLayout = _programState->getVertexLayout(); + auto& attributes = _programState->getProgram()->getActiveAttributes(); + auto iter = attributes.find("a_position"); if (iter != attributes.end()) vertexLayout->setAttribute("a_position", iter->second.location, backend::VertexFormat::FLOAT2, 0, false); vertexLayout->setLayout(sizeof(Vec2)); - auto& cmd2 = _renderCmds[cmdIndex]; cmdIndex++; cmd2.init(_globalZOrder, blend); cmd2.setBeforeCallback(CC_CALLBACK_0(RawStencilBufferTest::onBeforeDrawSprite, this, i)); - Vec2 vertices2[] = { - Vec2::ZERO, - Vec2(winPoint.x, 0.0f), - winPoint, - Vec2(0.0f, winPoint.y) - }; + Vec2 vertices2[] = {Vec2::ZERO, Vec2(winPoint.x, 0.0f), winPoint, Vec2(0.0f, winPoint.y)}; cmd2.createVertexBuffer(sizeof(Vec2), 4, backend::BufferUsage::STATIC); cmd2.updateVertexBuffer(vertices2, sizeof(vertices2)); cmd2.createIndexBuffer(backend::IndexFormat::U_SHORT, 6, backend::BufferUsage::STATIC); @@ -637,9 +611,9 @@ void RawStencilBufferTest::initCommands() } } -void RawStencilBufferTest::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) -{ - auto winPoint = Vec2(Director::getInstance()->getWinSize()); +void RawStencilBufferTest::draw(Renderer* renderer, const Mat4& transform, uint32_t flags) +{ + auto winPoint = Vec2(Director::getInstance()->getWinSize()); auto planeSize = winPoint * (1.0 / _planeCount); renderer->addCommand(&_enableStencilCallback); @@ -649,25 +623,25 @@ void RawStencilBufferTest::draw(Renderer *renderer, const Mat4 &transform, uint3 auto spritePoint = planeSize * i; spritePoint.x += planeSize.x / 2; spritePoint.y = 0; - _sprites.at(i)->setPosition( spritePoint ); - _spritesStencil.at(i)->setPosition( spritePoint ); + _sprites.at(i)->setPosition(spritePoint); + _spritesStencil.at(i)->setPosition(spritePoint); renderer->clear(ClearFlag::STENCIL, Color4F::BLACK, 0.f, 0x0, _globalZOrder); renderer->addCommand(&_renderCmds[cmdIndex]); cmdIndex++; - + Director* director = Director::getInstance(); CCASSERT(nullptr != director, "Director is null when setting matrix stack"); director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); - + _modelViewTransform = this->transform(transform); _spritesStencil.at(i)->visit(renderer, _modelViewTransform, flags); director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); - + renderer->addCommand(&_renderCmds[cmdIndex]); cmdIndex++; - + director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); _modelViewTransform = this->transform(transform); _sprites.at(i)->visit(renderer, _modelViewTransform, flags); @@ -693,26 +667,28 @@ void RawStencilBufferTest::onBeforeDrawSprite(int planeIndex) void RawStencilBufferTest::setupStencilForClippingOnPlane(int plane) { - auto renderer = Director::getInstance()->getRenderer(); + auto renderer = Director::getInstance()->getRenderer(); unsigned int planeMask = 0x1 << plane; renderer->setStencilWriteMask(planeMask); renderer->setStencilCompareFunction(backend::CompareFunction::NEVER, planeMask, planeMask); - renderer->setStencilOperation(backend::StencilOperation::REPLACE, backend::StencilOperation::KEEP, backend::StencilOperation::KEEP); + renderer->setStencilOperation(backend::StencilOperation::REPLACE, backend::StencilOperation::KEEP, + backend::StencilOperation::KEEP); } void RawStencilBufferTest::setupStencilForDrawingOnPlane(int plane) { - auto renderer = Director::getInstance()->getRenderer(); + auto renderer = Director::getInstance()->getRenderer(); unsigned int planeMask = 0x1 << plane; renderer->setStencilCompareFunction(backend::CompareFunction::EQUAL, planeMask, planeMask); - renderer->setStencilOperation(backend::StencilOperation::KEEP, backend::StencilOperation::KEEP, backend::StencilOperation::KEEP); + renderer->setStencilOperation(backend::StencilOperation::KEEP, backend::StencilOperation::KEEP, + backend::StencilOperation::KEEP); } //@implementation RawStencilBufferTest2 std::string RawStencilBufferTest2::subtitle() const { - return "2:DepthMask:FALSE"; + return "2:DepthMask:FALSE"; } void RawStencilBufferTest2::setupStencilForClippingOnPlane(int plane) @@ -731,7 +707,7 @@ void RawStencilBufferTest2::setupStencilForDrawingOnPlane(int plane) std::string RawStencilBufferTest3::subtitle() const { - return "3:DepthTest:DISABLE,DepthMask:FALSE"; + return "3:DepthTest:DISABLE,DepthMask:FALSE"; } void RawStencilBufferTest3::setupStencilForClippingOnPlane(int plane) @@ -751,11 +727,12 @@ void RawStencilBufferTest3::setupStencilForDrawingOnPlane(int plane) void RawStencilBufferTestAlphaTest::setup() { RawStencilBufferTest::setup(); - for(int i = 0; i < _planeCount; ++i) + for (int i = 0; i < _planeCount; ++i) { auto program = backend::Program::getBuiltinProgram(backend::ProgramType::POSITION_TEXTURE_COLOR_ALPHA_TEST); auto programState = new backend::ProgramState(program); - programState->setUniform(programState->getUniformLocation("u_alpha_value"), &_alphaThreshold, sizeof(_alphaThreshold)); + programState->setUniform(programState->getUniformLocation("u_alpha_value"), &_alphaThreshold, + sizeof(_alphaThreshold)); _spritesStencil.at(i)->setProgramState(programState); } } @@ -763,7 +740,7 @@ void RawStencilBufferTestAlphaTest::setup() std::string RawStencilBufferTest4::subtitle() const { - return "4:DepthMask:FALSE,AlphaTest:ENABLE"; + return "4:DepthMask:FALSE,AlphaTest:ENABLE"; } void RawStencilBufferTest4::setupStencilForClippingOnPlane(int plane) @@ -783,7 +760,7 @@ void RawStencilBufferTest4::setupStencilForDrawingOnPlane(int plane) std::string RawStencilBufferTest5::subtitle() const { - return "5:DepthTest:DISABLE,DepthMask:FALSE,AlphaTest:ENABLE"; + return "5:DepthTest:DISABLE,DepthMask:FALSE,AlphaTest:ENABLE"; } void RawStencilBufferTest5::setupStencilForClippingOnPlane(int plane) @@ -805,7 +782,7 @@ void RawStencilBufferTest5::setupStencilForDrawingOnPlane(int plane) std::string RawStencilBufferTest6::subtitle() const { - return "6:ManualClear,AlphaTest:ENABLE"; + return "6:ManualClear,AlphaTest:ENABLE"; } void RawStencilBufferTest6::setup() @@ -819,7 +796,8 @@ void RawStencilBufferTest6::setupStencilForClippingOnPlane(int plane) int planeMask = 0x1 << plane; auto renderer = Director::getInstance()->getRenderer(); renderer->setStencilCompareFunction(backend::CompareFunction::NEVER, planeMask, planeMask); - renderer->setStencilOperation(backend::StencilOperation::REPLACE, backend::StencilOperation::KEEP, backend::StencilOperation::KEEP); + renderer->setStencilOperation(backend::StencilOperation::REPLACE, backend::StencilOperation::KEEP, + backend::StencilOperation::KEEP); renderer->setDepthTest(false); renderer->setDepthWrite(false); } @@ -833,7 +811,7 @@ void RawStencilBufferTest6::setupStencilForDrawingOnPlane(int plane) //#endif // COCOS2D_DEBUG > 1 -//ClippingToRenderTextureTest +// ClippingToRenderTextureTest std::string ClippingToRenderTextureTest::title() const { @@ -847,9 +825,9 @@ std::string ClippingToRenderTextureTest::subtitle() const void ClippingToRenderTextureTest::setup() { - auto button = MenuItemFont::create("Reproduce bug", [&](Ref *sender) { + auto button = MenuItemFont::create("Reproduce bug", [&](Ref* sender) { std::vector nodes; - enumerateChildren("remove me [0-9]", [&](Node *node) { + enumerateChildren("remove me [0-9]", [&](Node* node) { nodes.push_back(node); return false; }); @@ -863,7 +841,7 @@ void ClippingToRenderTextureTest::setup() auto s = Director::getInstance()->getWinSize(); // create menu, it's an autorelease object auto menu = Menu::create(button, nullptr); - menu->setPosition(Point(s.width/2, s.height/2)); + menu->setPosition(Point(s.width / 2, s.height / 2)); this->addChild(menu, 1); expectedBehaviour(); @@ -871,16 +849,15 @@ void ClippingToRenderTextureTest::setup() void ClippingToRenderTextureTest::expectedBehaviour() { - auto director = Director::getInstance(); + auto director = Director::getInstance(); Size visibleSize = director->getVisibleSize(); - Point origin = director->getVisibleOrigin(); - + Point origin = director->getVisibleOrigin(); // add "HelloWorld" splash screen" auto sprite = Sprite::create("Images/grossini.png"); // position the sprite on the center of the screen - sprite->setPosition(Point(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); + sprite->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y)); // add the sprite as a child to this layer this->addChild(sprite, 0); @@ -901,13 +878,12 @@ void ClippingToRenderTextureTest::expectedBehaviour() auto clipper = ClippingNode::create(); clipper->setAnchorPoint(Point(0.5f, 0.5f)); - clipper->setPosition( Point(visibleSize.width/2, visibleSize.height/2) ); + clipper->setPosition(Point(visibleSize.width / 2, visibleSize.height / 2)); clipper->setStencil(stencil); clipper->setInverted(true); container->addChild(clipper, 1); - - auto img = DrawNode::create(); + auto img = DrawNode::create(); triangle[0] = Point(-200, -200); triangle[1] = Point(200, -200); triangle[2] = Point(0, 200); @@ -918,21 +894,19 @@ void ClippingToRenderTextureTest::expectedBehaviour() void ClippingToRenderTextureTest::reproduceBug() { - auto director = Director::getInstance(); + auto director = Director::getInstance(); Size visibleSize = director->getVisibleSize(); - Point origin = director->getVisibleOrigin(); - + Point origin = director->getVisibleOrigin(); // add "HelloWorld" splash screen" auto sprite = Sprite::create("Images/grossini.png"); // position the sprite on the center of the screen - sprite->setPosition(Point(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); + sprite->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y)); // add the sprite as a child to this layer this->addChild(sprite, 0); - // container node that will contain the clippingNode auto container = Node::create(); container->retain(); @@ -947,13 +921,12 @@ void ClippingToRenderTextureTest::reproduceBug() auto clipper = ClippingNode::create(); clipper->setAnchorPoint(Point(0.5f, 0.5f)); - clipper->setPosition( Point(visibleSize.width/2, visibleSize.height/2) ); + clipper->setPosition(Point(visibleSize.width / 2, visibleSize.height / 2)); clipper->setStencil(stencil); clipper->setInverted(true); container->addChild(clipper, 1); - - auto img = DrawNode::create(); + auto img = DrawNode::create(); triangle[0] = Point(-200, -200); triangle[1] = Point(200, -200); triangle[2] = Point(0, 200); @@ -963,8 +936,9 @@ void ClippingToRenderTextureTest::reproduceBug() // container rendered on Texture the size of the screen and because Clipping node use stencil buffer so we need to // create RenderTexture with depthStencil format parameter - RenderTexture* rt = RenderTexture::create(visibleSize.width, visibleSize.height, backend::PixelFormat::RGBA8, PixelFormat::D24S8); - rt->setPosition(visibleSize.width/2, visibleSize.height/2); + RenderTexture* rt = + RenderTexture::create(visibleSize.width, visibleSize.height, backend::PixelFormat::RGBA8, PixelFormat::D24S8); + rt->setPosition(visibleSize.width / 2, visibleSize.height / 2); this->addChild(rt); rt->begin(); @@ -976,24 +950,25 @@ void ClippingToRenderTextureTest::reproduceBug() std::string ClippingRectangleNodeTest::title() const { - return "ClippingRectangleNode Test"; + return "ClippingRectangleNode Test"; } std::string ClippingRectangleNodeTest::subtitle() const { - return "more effectively"; + return "more effectively"; } void ClippingRectangleNodeTest::setup() { auto clipper = ClippingRectangleNode::create(); - clipper->setClippingRegion(Rect(this->getContentSize().width / 2 - 100, this->getContentSize().height / 2 - 100, 200.0f, 200.0f)); - clipper->setTag( kTagClipperNode ); + clipper->setClippingRegion( + Rect(this->getContentSize().width / 2 - 100, this->getContentSize().height / 2 - 100, 200.0f, 200.0f)); + clipper->setTag(kTagClipperNode); this->addChild(clipper); - + auto content = Sprite::create(s_back2); - content->setTag( kTagContentNode ); - content->setAnchorPoint( Vec2(0.5f, 0.5f) ); + content->setTag(kTagContentNode); + content->setAnchorPoint(Vec2(0.5f, 0.5f)); content->setPosition(this->getContentSize().width / 2, this->getContentSize().height / 2); clipper->addChild(content); } diff --git a/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.h b/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.h index 29f89a650c68..a631ad659d2a 100644 --- a/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.h +++ b/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,9 +27,13 @@ #include "renderer/CCCustomCommand.h" #include -namespace cocos2d { namespace backend { +namespace cocos2d +{ +namespace backend +{ class ProgramState; -}} +} +} // namespace cocos2d DEFINE_TEST_SUITE(ClippingNodeTests); @@ -41,7 +45,7 @@ class BaseClippingNodeTest : public TestCase ~BaseClippingNodeTest(); virtual bool init() override; - virtual std::string title() const override; + virtual std::string title() const override; virtual void setup(); }; @@ -54,15 +58,15 @@ class BasicTest : public BaseClippingNodeTest virtual std::string subtitle() const override; virtual void setup() override; - virtual cocos2d::Action* actionRotate(); - virtual cocos2d::Action* actionScale(); + virtual cocos2d::Action* actionRotate(); + virtual cocos2d::Action* actionScale(); - virtual cocos2d::DrawNode* shape(); - virtual cocos2d::Sprite* grossini(); + virtual cocos2d::DrawNode* shape(); + virtual cocos2d::Sprite* grossini(); - virtual cocos2d::Node* stencil(); - virtual cocos2d::ClippingNode* clipper(); - virtual cocos2d::Node* content(); + virtual cocos2d::Node* stencil(); + virtual cocos2d::ClippingNode* clipper(); + virtual cocos2d::Node* content(); }; class ShapeTest : public BasicTest @@ -140,9 +144,10 @@ class HoleDemo : public BaseClippingNodeTest virtual std::string title() const override; virtual std::string subtitle() const override; void pokeHoleAtPoint(cocos2d::Vec2 point); - void onTouchesBegan(const std::vector& touches, cocos2d::Event *event); + void onTouchesBegan(const std::vector& touches, cocos2d::Event* event); + private: - cocos2d::ClippingNode* _outerClipper; + cocos2d::ClippingNode* _outerClipper; cocos2d::Node* _holes; cocos2d::Node* _holesStencil; }; @@ -155,11 +160,12 @@ class ScrollViewDemo : public BaseClippingNodeTest virtual std::string title() const override; virtual std::string subtitle() const override; virtual void setup() override; - void onTouchesBegan(const std::vector& touches, cocos2d::Event *event); - void onTouchesMoved(const std::vector& touches, cocos2d::Event *event); - void onTouchesEnded(const std::vector& touches, cocos2d::Event *event); + void onTouchesBegan(const std::vector& touches, cocos2d::Event* event); + void onTouchesMoved(const std::vector& touches, cocos2d::Event* event); + void onTouchesEnded(const std::vector& touches, cocos2d::Event* event); + private: - bool _scrolling; + bool _scrolling; cocos2d::Vec2 _lastPoint; }; @@ -175,10 +181,10 @@ class RawStencilBufferTest : public BaseClippingNodeTest virtual std::string title() const override; virtual std::string subtitle() const override; virtual void setup() override; - virtual void draw(cocos2d::Renderer *renderer, const cocos2d::Mat4 &transform, uint32_t flags) override; + virtual void draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, uint32_t flags) override; - virtual void setupStencilForClippingOnPlane(int plane); - virtual void setupStencilForDrawingOnPlane(int plane); + virtual void setupStencilForClippingOnPlane(int plane); + virtual void setupStencilForDrawingOnPlane(int plane); protected: void onBeforeDrawClip(int planeIndex); @@ -276,7 +282,7 @@ class ClippingRectangleNodeTest : public BaseClippingNodeTest { public: CREATE_FUNC(ClippingRectangleNodeTest); - + virtual std::string title() const override; virtual std::string subtitle() const override; virtual void setup() override; diff --git a/tests/cpp-tests/Classes/ConfigurationTest/ConfigurationTest.cpp b/tests/cpp-tests/Classes/ConfigurationTest/ConfigurationTest.cpp index 5381f8772a89..d947af82639c 100644 --- a/tests/cpp-tests/Classes/ConfigurationTest/ConfigurationTest.cpp +++ b/tests/cpp-tests/Classes/ConfigurationTest/ConfigurationTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -22,7 +22,6 @@ THE SOFTWARE. ****************************************************************************/ - #include "ConfigurationTest.h" #include "../testResource.h" #include "cocos2d.h" @@ -52,7 +51,7 @@ void ConfigurationLoadConfig::onEnter() { ConfigurationBase::onEnter(); - Configuration::getInstance()->loadConfigFile("configs/config-test-ok.plist"); + Configuration::getInstance()->loadConfigFile("configs/config-test-ok.plist"); std::string config = Configuration::getInstance()->getInfo(); log("%s\n", config.c_str()); } @@ -71,8 +70,8 @@ void ConfigurationQuery::onEnter() { ConfigurationBase::onEnter(); - log("cocos2d version: %s", Configuration::getInstance()->getValue("adxe.version").asString().c_str() ); - log("OpenGL version: %s", Configuration::getInstance()->getValue("gl.version").asString().c_str() ); + log("cocos2d version: %s", Configuration::getInstance()->getValue("adxe.version").asString().c_str()); + log("OpenGL version: %s", Configuration::getInstance()->getValue("gl.version").asString().c_str()); } std::string ConfigurationQuery::subtitle() const @@ -89,7 +88,7 @@ void ConfigurationInvalid::onEnter() { ConfigurationBase::onEnter(); - Configuration::getInstance()->loadConfigFile("configs/config-test-invalid.plist"); + Configuration::getInstance()->loadConfigFile("configs/config-test-invalid.plist"); } std::string ConfigurationInvalid::subtitle() const @@ -107,23 +106,22 @@ void ConfigurationDefault::onEnter() ConfigurationBase::onEnter(); std::string c_value = Configuration::getInstance()->getValue("invalid.key", Value("no key")).asString(); - if( c_value != "no key" ) - log("1. Test failed!"); - else - log("1. Test OK!"); - - bool b_value = Configuration::getInstance()->getValue("invalid.key", Value(true)).asBool(); - if( ! b_value ) - log("2. Test failed!"); - else - log("2. Test OK!"); - - double d_value = Configuration::getInstance()->getValue("invalid.key", Value(42.42)).asDouble(); - if( d_value != 42.42 ) - log("3. Test failed!"); - else - log("3. Test OK!"); - + if (c_value != "no key") + log("1. Test failed!"); + else + log("1. Test OK!"); + + bool b_value = Configuration::getInstance()->getValue("invalid.key", Value(true)).asBool(); + if (!b_value) + log("2. Test failed!"); + else + log("2. Test OK!"); + + double d_value = Configuration::getInstance()->getValue("invalid.key", Value(42.42)).asDouble(); + if (d_value != 42.42) + log("3. Test failed!"); + else + log("3. Test OK!"); } std::string ConfigurationDefault::subtitle() const @@ -140,13 +138,13 @@ void ConfigurationSet::onEnter() { ConfigurationBase::onEnter(); - Configuration *conf = Configuration::getInstance(); + Configuration* conf = Configuration::getInstance(); - conf->setValue("this.is.an.int.value", Value(10) ); - conf->setValue("this.is.a.bool.value", Value(true) ); - conf->setValue("this.is.a.string.value", Value("hello world") ); + conf->setValue("this.is.an.int.value", Value(10)); + conf->setValue("this.is.a.bool.value", Value(true)); + conf->setValue("this.is.a.string.value", Value("hello world")); - auto str = conf->getInfo(); + auto str = conf->getInfo(); log("%s\n", str.c_str()); } @@ -154,4 +152,3 @@ std::string ConfigurationSet::subtitle() const { return "Tests setting values manually"; } - diff --git a/tests/cpp-tests/Classes/ConfigurationTest/ConfigurationTest.h b/tests/cpp-tests/Classes/ConfigurationTest/ConfigurationTest.h index 802c1512642a..04f97b559822 100644 --- a/tests/cpp-tests/Classes/ConfigurationTest/ConfigurationTest.h +++ b/tests/cpp-tests/Classes/ConfigurationTest/ConfigurationTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -32,7 +32,6 @@ DEFINE_TEST_SUITE(ConfigurationTests); class ConfigurationBase : public TestCase { protected: - public: virtual std::string title() const override; }; @@ -82,5 +81,4 @@ class ConfigurationSet : public ConfigurationBase virtual std::string subtitle() const override; }; - -#endif // __CONFIGURATIONTEST_H__ +#endif // __CONFIGURATIONTEST_H__ diff --git a/tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.cpp b/tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.cpp index d7a40b21fc8d..ae09e42ee1a0 100644 --- a/tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.cpp +++ b/tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.cpp @@ -28,13 +28,13 @@ #include #include #if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) -#include -#include -#include -#include +# include +# include +# include +# include #else -#include -#include +# include +# include #endif USING_NS_CC; @@ -51,13 +51,9 @@ ConsoleTests::ConsoleTests() ADD_TEST_CASE(ConsoleUploadFile); } -BaseTestConsole::BaseTestConsole() -{ -} +BaseTestConsole::BaseTestConsole() {} -BaseTestConsole::~BaseTestConsole() -{ -} +BaseTestConsole::~BaseTestConsole() {} std::string BaseTestConsole::title() const { @@ -72,21 +68,20 @@ std::string BaseTestConsole::title() const ConsoleCustomCommand::ConsoleCustomCommand() { - _console = Director::getInstance()->getConsole(); + _console = Director::getInstance()->getConsole(); static Console::Command commands[] = { - {"hello", "This is just a user generated command", [](int fd, const std::string& args) { - const char msg[] = "how are you?\nArguments passed: "; - send(fd, msg, sizeof(msg),0); - send(fd, args.c_str(), args.length(),0); - send(fd, "\n",1,0); - }}, + {"hello", "This is just a user generated command", + [](int fd, std::string_view args) { + const char msg[] = "how are you?\nArguments passed: "; + send(fd, msg, sizeof(msg), 0); + send(fd, args.data(), args.length(), 0); + send(fd, "\n", 1, 0); + }}, }; _console->addCommand(commands[0]); } -ConsoleCustomCommand::~ConsoleCustomCommand() -{ -} +ConsoleCustomCommand::~ConsoleCustomCommand() {} void ConsoleCustomCommand::onEnter() { @@ -103,7 +98,6 @@ std::string ConsoleCustomCommand::subtitle() const return "telnet localhost 5678"; } - //------------------------------------------------------------------ // // ConsoleUploadFile @@ -112,26 +106,22 @@ std::string ConsoleCustomCommand::subtitle() const ConsoleUploadFile::ConsoleUploadFile() { - std::srand ((unsigned)time(nullptr)); - int id = rand()%100000; + std::srand((unsigned)time(nullptr)); + int id = rand() % 100000; char buf[32]; sprintf(buf, "%d", id); _targetFileName = std::string("grossini") + buf + ".png"; - std::thread t = std::thread( &ConsoleUploadFile::uploadFile, this); + std::thread t = std::thread(&ConsoleUploadFile::uploadFile, this); t.detach(); } void ConsoleUploadFile::onEnter() { BaseTestConsole::onEnter(); - } -ConsoleUploadFile::~ConsoleUploadFile() -{ - -} +ConsoleUploadFile::~ConsoleUploadFile() {} void ConsoleUploadFile::uploadFile() { @@ -150,14 +140,14 @@ void ConsoleUploadFile::uploadFile() /* Obtain address(es) matching host/port */ memset(&hints, 0, sizeof(struct addrinfo)); - hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ + hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ hints.ai_socktype = SOCK_STREAM; /* stream socket */ - hints.ai_flags = 0; - hints.ai_protocol = 0; /* Any protocol */ + hints.ai_flags = 0; + hints.ai_protocol = 0; /* Any protocol */ #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) WSADATA wsaData; - WSAStartup(MAKEWORD(2, 2),&wsaData); + WSAStartup(MAKEWORD(2, 2), &wsaData); #endif std::string nodeName; @@ -167,7 +157,7 @@ void ConsoleUploadFile::uploadFile() nodeName = "localhost"; s = getaddrinfo(nodeName.c_str(), "5678", &hints, &result); - if (s != 0) + if (s != 0) { CCLOG("ConsoleUploadFile: getaddrinfo error"); return; @@ -178,14 +168,14 @@ void ConsoleUploadFile::uploadFile() If socket(2) (or connect(2)) fails, we (close the socket and) try the next address. */ - for (rp = result; rp != nullptr; rp = rp->ai_next) { - sfd = socket(rp->ai_family, rp->ai_socktype, - rp->ai_protocol); + for (rp = result; rp != nullptr; rp = rp->ai_next) + { + sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (sfd == -1) continue; if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1) - break; /* Success */ + break; /* Success */ #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) closesocket(sfd); @@ -194,12 +184,13 @@ void ConsoleUploadFile::uploadFile() #endif } - if (rp == nullptr) { /* No address succeeded */ + if (rp == nullptr) + { /* No address succeeded */ CCLOG("ConsoleUploadFile: could not connect!"); return; } - freeaddrinfo(result); /* No longer needed */ + freeaddrinfo(result); /* No longer needed */ std::string tmp = "upload"; @@ -209,9 +200,9 @@ void ConsoleUploadFile::uploadFile() char cmd[512] = {0}; strcpy(cmd, tmp.c_str()); - send(sfd,cmd,strlen(cmd),0); + send(sfd, cmd, strlen(cmd), 0); - size_t offset = 0; + size_t offset = 0; auto readBuffer = [&offset](char* buf, size_t bytes, const Data& data) -> ssize_t { if (offset >= data.getSize()) return 0; @@ -224,11 +215,11 @@ void ConsoleUploadFile::uploadFile() return actualReadBytes; }; - while(true) + while (true) { char buffer[3], *out; - unsigned char *in; - in = (unsigned char *)buffer; + unsigned char* in; + in = (unsigned char*)buffer; // copy the file into the buffer: ssize_t ret = readBuffer(buffer, 3, srcFileData); if (ret > 0) @@ -236,16 +227,16 @@ void ConsoleUploadFile::uploadFile() int len = base64Encode(in, (unsigned int)ret, &out); send(sfd, out, len, 0); free(out); - if(ret < 3) + if (ret < 3) { - //eof + // eof log("Reach the end, total send: %d bytes", (int)offset); break; } } else { - //read error + // read error break; } } @@ -271,9 +262,8 @@ std::string ConsoleUploadFile::title() const std::string ConsoleUploadFile::subtitle() const { auto sharedFileUtils = FileUtils::getInstance(); - + std::string writablePath = sharedFileUtils->getWritablePath(); return "file uploaded to:" + writablePath + _targetFileName; } - diff --git a/tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.h b/tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.h index 4f06e3618e82..d8ee9ae90be1 100644 --- a/tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.h +++ b/tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.h @@ -39,7 +39,6 @@ class BaseTestConsole : public TestCase virtual std::string title() const override; }; - class ConsoleCustomCommand : public BaseTestConsole { public: @@ -53,7 +52,7 @@ class ConsoleCustomCommand : public BaseTestConsole ConsoleCustomCommand(); virtual ~ConsoleCustomCommand(); - cocos2d::Console *_console; + cocos2d::Console* _console; private: CC_DISALLOW_COPY_AND_ASSIGN(ConsoleCustomCommand); @@ -73,10 +72,11 @@ class ConsoleUploadFile : public BaseTestConsole virtual ~ConsoleUploadFile(); void uploadFile(); + private: CC_DISALLOW_COPY_AND_ASSIGN(ConsoleUploadFile); std::string _targetFileName; }; -#endif // _CONSOLE_TEST_H_ +#endif // _CONSOLE_TEST_H_ diff --git a/tests/cpp-tests/Classes/CurlTest/CurlTest.cpp b/tests/cpp-tests/Classes/CurlTest/CurlTest.cpp index 595383452f67..1f7a17004737 100644 --- a/tests/cpp-tests/Classes/CurlTest/CurlTest.cpp +++ b/tests/cpp-tests/Classes/CurlTest/CurlTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -39,9 +39,9 @@ CurlTest::CurlTest() { auto label = Label::createWithTTF("Curl Test", "fonts/arial.ttf", 28); addChild(label, 0); - label->setPosition(VisibleRect::center().x, VisibleRect::top().y-50); + label->setPosition(VisibleRect::center().x, VisibleRect::top().y - 50); - auto listener = EventListenerTouchAllAtOnce::create(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesEnded = CC_CALLBACK_2(CurlTest::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); @@ -49,57 +49,57 @@ CurlTest::CurlTest() _label = Label::createWithTTF("Touch the screen to connect", "fonts/arial.ttf", 22); _label->setPosition(VisibleRect::center()); addChild(_label, 0); - + _label->retain(); } -struct MemoryStruct { - char *memory; - size_t size; +struct MemoryStruct +{ + char* memory; + size_t size; }; -static size_t -WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) +static size_t WriteMemoryCallback(void* contents, size_t size, size_t nmemb, void* userp) { - size_t realsize = size * nmemb; - struct MemoryStruct *mem = (struct MemoryStruct *)userp; - - mem->memory = (char*)realloc(mem->memory, mem->size + realsize + 1); - if(mem->memory == NULL) { - /* out of memory! */ - printf("not enough memory (realloc returned NULL)\n"); - return 0; - } - - memcpy(&(mem->memory[mem->size]), contents, realsize); - mem->size += realsize; - mem->memory[mem->size] = 0; - - return realsize; + size_t realsize = size * nmemb; + struct MemoryStruct* mem = (struct MemoryStruct*)userp; + + mem->memory = (char*)realloc(mem->memory, mem->size + realsize + 1); + if (mem->memory == NULL) + { + /* out of memory! */ + printf("not enough memory (realloc returned NULL)\n"); + return 0; + } + + memcpy(&(mem->memory[mem->size]), contents, realsize); + mem->size += realsize; + mem->memory[mem->size] = 0; + + return realsize; } - // the test code is // http://curl.haxx.se/mail/lib-2009-12/0071.html -void CurlTest::onTouchesEnded(const std::vector& touches, Event *event) +void CurlTest::onTouchesEnded(const std::vector& touches, Event* event) { - CURL *curl; + CURL* curl; CURLcode res; char buffer[10]; struct MemoryStruct chunk; - - chunk.memory = (char*)malloc(1); /* will be grown as needed by the realloc above */ - chunk.size = 0; /* no data at this point */ + + chunk.memory = (char*)malloc(1); /* will be grown as needed by the realloc above */ + chunk.size = 0; /* no data at this point */ curl = curl_easy_init(); - if (curl) + if (curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://webtest.cocos2d-x.org/curltest"); - //code from http://curl.haxx.se/libcurl/c/getinmemory.html + // code from http://curl.haxx.se/libcurl/c/getinmemory.html /* we pass our 'chunk' struct to the callback function */ - curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk); - //If we don't provide a write function for curl, it will receive error code 23 on windows. + curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&chunk); + // If we don't provide a write function for curl, it will receive error code 23 on windows. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); res = curl_easy_perform(curl); @@ -111,14 +111,14 @@ void CurlTest::onTouchesEnded(const std::vector& touches, Event *event) } else { - sprintf(buffer,"code: %i",res); + sprintf(buffer, "code: %i", res); _label->setString(buffer); } - } - else + } + else { _label->setString("no curl"); - } + } } CurlTest::~CurlTest() diff --git a/tests/cpp-tests/Classes/CurlTest/CurlTest.h b/tests/cpp-tests/Classes/CurlTest/CurlTest.h index e36ba2f7a43b..15e23a9ffaf7 100644 --- a/tests/cpp-tests/Classes/CurlTest/CurlTest.h +++ b/tests/cpp-tests/Classes/CurlTest/CurlTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -38,10 +38,10 @@ class CurlTest : public TestCase CurlTest(); ~CurlTest(); - void onTouchesEnded(const std::vector& touches, cocos2d::Event *event); + void onTouchesEnded(const std::vector& touches, cocos2d::Event* event); private: cocos2d::Label* _label; }; -#endif // _CURL_TEST_H_ +#endif // _CURL_TEST_H_ diff --git a/tests/cpp-tests/Classes/CurrentLanguageTest/CurrentLanguageTest.cpp b/tests/cpp-tests/Classes/CurrentLanguageTest/CurrentLanguageTest.cpp index b2b58c8e2fbe..33230b057079 100644 --- a/tests/cpp-tests/Classes/CurrentLanguageTest/CurrentLanguageTest.cpp +++ b/tests/cpp-tests/Classes/CurrentLanguageTest/CurrentLanguageTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -35,16 +35,16 @@ CurrentLanguageTest::CurrentLanguageTest() { auto label = Label::createWithTTF("Current language Test", "fonts/arial.ttf", 28); addChild(label, 0); - label->setPosition(VisibleRect::center().x, VisibleRect::top().y-50); + label->setPosition(VisibleRect::center().x, VisibleRect::top().y - 50); auto labelLanguage = Label::createWithTTF("", "fonts/arial.ttf", 20); labelLanguage->setPosition(VisibleRect::center()); - + auto labelLanguageCode = Label::createWithTTF("", "fonts/arial.ttf", 20); - labelLanguageCode->setPosition(VisibleRect::center().x, VisibleRect::center().y-50); - + labelLanguageCode->setPosition(VisibleRect::center().x, VisibleRect::center().y - 50); + const char* currentLanguageCode = Application::getInstance()->getCurrentLanguageCode(); - + labelLanguageCode->setString(currentLanguageCode); LanguageType currentLanguageType = Application::getInstance()->getCurrentLanguage(); @@ -103,4 +103,3 @@ CurrentLanguageTest::CurrentLanguageTest() addChild(labelLanguage); addChild(labelLanguageCode); } - diff --git a/tests/cpp-tests/Classes/CurrentLanguageTest/CurrentLanguageTest.h b/tests/cpp-tests/Classes/CurrentLanguageTest/CurrentLanguageTest.h index 6c5bfb83afd3..19fb74937264 100644 --- a/tests/cpp-tests/Classes/CurrentLanguageTest/CurrentLanguageTest.h +++ b/tests/cpp-tests/Classes/CurrentLanguageTest/CurrentLanguageTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -38,4 +38,4 @@ class CurrentLanguageTest : public TestCase CurrentLanguageTest(); }; -#endif // _CURRENT_LANGUAGE_TEST_H_ +#endif // _CURRENT_LANGUAGE_TEST_H_ diff --git a/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.cpp b/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.cpp index 58b09ff4f3f8..2e1dbf6c6cb2 100644 --- a/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.cpp +++ b/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -44,19 +44,19 @@ std::string PrettyPrinterDemo::subtitle() const void PrettyPrinterDemo::addSprite() { // create sprites - + auto s1 = Sprite::create("Images/grossini.png"); auto s2 = Sprite::create("Images/grossini_dance_01.png"); auto s3 = Sprite::create("Images/grossini_dance_02.png"); auto s4 = Sprite::create("Images/grossini_dance_03.png"); auto s5 = Sprite::create("Images/grossini_dance_04.png"); - + s1->setPosition(50, 50); s2->setPosition(60, 50); s3->setPosition(70, 50); s4->setPosition(80, 50); s5->setPosition(90, 50); - + this->addChild(s1); this->addChild(s2); this->addChild(s3); @@ -68,41 +68,41 @@ void PrettyPrinterDemo::onEnter() { TestCase::onEnter(); auto s = Director::getInstance()->getWinSize(); - + auto label = Label::createWithTTF(title().c_str(), "fonts/arial.ttf", 28); - label->setPosition(s.width/2, s.height * 4/5); + label->setPosition(s.width / 2, s.height * 4 / 5); this->addChild(label, 1); - + std::string strSubtitle = subtitle(); - if(strSubtitle.empty() == false) + if (strSubtitle.empty() == false) { auto subLabel = Label::createWithTTF(strSubtitle.c_str(), "fonts/Thonburi.ttf", 16); - subLabel->setPosition(s.width/2, s.height * 3/5); + subLabel->setPosition(s.width / 2, s.height * 3 / 5); this->addChild(subLabel, 1); } - + // Test code - //TODO: minggo -// PrettyPrinter visitor; -// -// // print dictionary -// auto dict = __Dictionary::createWithContentsOfFile("animations/animations.plist"); -// dict->acceptVisitor(visitor); -// log("%s", visitor.getResult().c_str()); -// log("-------------------------------"); -// -// __Set myset; -// for (int i = 0; i < 30; ++i) { -// myset.addObject(__String::createWithFormat("str: %d", i)); -// } -// visitor.clear(); -// myset.acceptVisitor(visitor); -// log("%s", visitor.getResult().c_str()); -// log("-------------------------------"); -// -// visitor.clear(); + // TODO: minggo + // PrettyPrinter visitor; + // + // // print dictionary + // auto dict = __Dictionary::createWithContentsOfFile("animations/animations.plist"); + // dict->acceptVisitor(visitor); + // log("%s", visitor.getResult().c_str()); + // log("-------------------------------"); + // + // __Set myset; + // for (int i = 0; i < 30; ++i) { + // myset.addObject(__String::createWithFormat("str: %d", i)); + // } + // visitor.clear(); + // myset.acceptVisitor(visitor); + // log("%s", visitor.getResult().c_str()); + // log("-------------------------------"); + // + // visitor.clear(); addSprite(); -// dict = Director::getInstance()->getTextureCache()->snapshotTextures(); -// dict->acceptVisitor(visitor); -// log("%s", visitor.getResult().c_str()); + // dict = Director::getInstance()->getTextureCache()->snapshotTextures(); + // dict->acceptVisitor(visitor); + // log("%s", visitor.getResult().c_str()); } diff --git a/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.h b/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.h index 6742f6c1620c..d576ea3ecc29 100644 --- a/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.h +++ b/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -39,9 +39,9 @@ class PrettyPrinterDemo : public TestCase virtual std::string subtitle() const override; virtual void onEnter() override; void addSprite(); + protected: - std::string _title; + std::string _title; }; - -#endif // __DATAVISITOR_TEST_H__ +#endif // __DATAVISITOR_TEST_H__ diff --git a/tests/cpp-tests/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp b/tests/cpp-tests/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp index 1c94ff53ab22..3efcd947ea2c 100644 --- a/tests/cpp-tests/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp +++ b/tests/cpp-tests/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -45,126 +45,151 @@ string DrawPrimitivesBaseTest::title() const DrawNodeTest::DrawNodeTest() { auto s = Director::getInstance()->getWinSize(); - + auto draw = DrawNode::create(); addChild(draw, 10); - - draw->drawPoint(Vec2(s.width/2-120, s.height/2-120), 10, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); - - draw->drawPoint(Vec2(s.width/2+120, s.height/2+120), 10, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); - + + draw->drawPoint(Vec2(s.width / 2 - 120, s.height / 2 - 120), 10, + Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); + + draw->drawPoint(Vec2(s.width / 2 + 120, s.height / 2 + 120), 10, + Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); + // draw 4 small points - Vec2 position[] = { Vec2(60,60), Vec2(70,70), Vec2(60,70), Vec2(70,60) }; - draw->drawPoints( position, 4, 5, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); - + Vec2 position[] = {Vec2(60, 60), Vec2(70, 70), Vec2(60, 70), Vec2(70, 60)}; + draw->drawPoints(position, 4, 5, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); + // draw a line - draw->drawLine(Vec2(0,0), Vec2(s.width, s.height), Color4F(1.0, 0.0, 0.0, 0.5)); - + draw->drawLine(Vec2(0, 0), Vec2(s.width, s.height), Color4F(1.0, 0.0, 0.0, 0.5)); + // draw a rectangle - draw->drawRect(Vec2(23,23), Vec2(7,7), Color4F(1,1,0,1)); - - draw->drawRect(Vec2(15,30), Vec2(30,15), Vec2(15,0), Vec2(0,15), Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); - + draw->drawRect(Vec2(23, 23), Vec2(7, 7), Color4F(1, 1, 0, 1)); + + draw->drawRect(Vec2(15, 30), Vec2(30, 15), Vec2(15, 0), Vec2(0, 15), + Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); + // draw a circle - draw->drawCircle(VisibleRect::center() + Vec2(140,0), 100, CC_DEGREES_TO_RADIANS(90), 50, true, 1.0f, 2.0f, Color4F(1.0f, 0.0f, 0.0f, 0.5f)); - - draw->drawCircle(VisibleRect::center() - Vec2(140,0), 50, CC_DEGREES_TO_RADIANS(90), 30, false, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); + draw->drawCircle(VisibleRect::center() + Vec2(140, 0), 100, CC_DEGREES_TO_RADIANS(90), 50, true, 1.0f, 2.0f, + Color4F(1.0f, 0.0f, 0.0f, 0.5f)); + + draw->drawCircle(VisibleRect::center() - Vec2(140, 0), 50, CC_DEGREES_TO_RADIANS(90), 30, false, + Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); // Draw some beziers - draw->drawQuadBezier(Vec2(s.width - 150, s.height - 150), Vec2(s.width - 70, s.height - 10), Vec2(s.width - 10, s.height - 10), 10, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); - - draw->drawQuadBezier(Vec2(0.0f, s.height), Vec2(s.width/2, s.height/2), Vec2(s.width, s.height), 50, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); - - draw->drawCubicBezier(VisibleRect::center(), Vec2(VisibleRect::center().x+30,VisibleRect::center().y+50), Vec2(VisibleRect::center().x+60,VisibleRect::center().y-50),VisibleRect::right(),100, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); - - draw->drawCubicBezier(Vec2(s.width - 250, 40.0f), Vec2(s.width - 70, 100.0f), Vec2(s.width - 30, 250.0f), Vec2(s.width - 10, s.height - 50), 10, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); - + draw->drawQuadBezier(Vec2(s.width - 150, s.height - 150), Vec2(s.width - 70, s.height - 10), + Vec2(s.width - 10, s.height - 10), 10, + Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); + + draw->drawQuadBezier(Vec2(0.0f, s.height), Vec2(s.width / 2, s.height / 2), Vec2(s.width, s.height), 50, + Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); + + draw->drawCubicBezier(VisibleRect::center(), Vec2(VisibleRect::center().x + 30, VisibleRect::center().y + 50), + Vec2(VisibleRect::center().x + 60, VisibleRect::center().y - 50), VisibleRect::right(), 100, + Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); + + draw->drawCubicBezier(Vec2(s.width - 250, 40.0f), Vec2(s.width - 70, 100.0f), Vec2(s.width - 30, 250.0f), + Vec2(s.width - 10, s.height - 50), 10, + Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); + auto array = PointArray::create(20); - array->addControlPoint(Vec2(0.0f,0.0f)); - array->addControlPoint(Vec2(80.0f,80.0f)); - array->addControlPoint(Vec2(s.width-80,80.0f)); - array->addControlPoint(Vec2(s.width-80,s.height-80)); - array->addControlPoint(Vec2(80.0f,s.height-80)); - array->addControlPoint(Vec2(80.0f,80.0f)); - array->addControlPoint(Vec2(s.width/2, s.height/2)); + array->addControlPoint(Vec2(0.0f, 0.0f)); + array->addControlPoint(Vec2(80.0f, 80.0f)); + array->addControlPoint(Vec2(s.width - 80, 80.0f)); + array->addControlPoint(Vec2(s.width - 80, s.height - 80)); + array->addControlPoint(Vec2(80.0f, s.height - 80)); + array->addControlPoint(Vec2(80.0f, 80.0f)); + array->addControlPoint(Vec2(s.width / 2, s.height / 2)); draw->drawCardinalSpline(array, 0.5f, 50, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); - + auto array2 = PointArray::create(20); array2->addControlPoint(Vec2(s.width / 2, 30.0f)); - array2->addControlPoint(Vec2(s.width -80, 30.0f)); + array2->addControlPoint(Vec2(s.width - 80, 30.0f)); array2->addControlPoint(Vec2(s.width - 80, s.height - 80)); array2->addControlPoint(Vec2(s.width / 2, s.height - 80)); array2->addControlPoint(Vec2(s.width / 2, 30.0f)); draw->drawCatmullRom(array2, 50, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); - + // open random color poly - Vec2 vertices[] = { Vec2(0.0f,0.0f), Vec2(50.0f,50.0f), Vec2(100.0f,50.0f), Vec2(100.0f,100.0f), Vec2(50.0f,100.0f) }; - draw->drawPoly( vertices, 5, false, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); - + Vec2 vertices[] = {Vec2(0.0f, 0.0f), Vec2(50.0f, 50.0f), Vec2(100.0f, 50.0f), Vec2(100.0f, 100.0f), + Vec2(50.0f, 100.0f)}; + draw->drawPoly(vertices, 5, false, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); + // closed random color poly - Vec2 vertices2[] = { Vec2(30.0f,130.0f), Vec2(30.0f,230.0f), Vec2(50.0f,200.0f) }; - draw->drawPoly( vertices2, 3, true, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); - + Vec2 vertices2[] = {Vec2(30.0f, 130.0f), Vec2(30.0f, 230.0f), Vec2(50.0f, 200.0f)}; + draw->drawPoly(vertices2, 3, true, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); + // Draw 10 circles - for( int i=0; i < 10; i++) + for (int i = 0; i < 10; i++) { - draw->drawDot(Vec2(s.width/2, s.height/2), 10*(10-i), Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); + draw->drawDot(Vec2(s.width / 2, s.height / 2), 10 * (10 - i), + Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); } - + // Draw polygons - Vec2 points[] = { Vec2(s.height/4,0.0f), Vec2(s.width,s.height/5), Vec2(s.width/3*2,s.height) }; - draw->drawPolygon(points, sizeof(points)/sizeof(points[0]), Color4F(1.0f,0.0f,0.0f,0.5f), 4, Color4F(0.0f,0.0f,1.0f,0.5f)); - + Vec2 points[] = {Vec2(s.height / 4, 0.0f), Vec2(s.width, s.height / 5), Vec2(s.width / 3 * 2, s.height)}; + draw->drawPolygon(points, sizeof(points) / sizeof(points[0]), Color4F(1.0f, 0.0f, 0.0f, 0.5f), 4, + Color4F(0.0f, 0.0f, 1.0f, 0.5f)); + // star poly (triggers buggs) { - const float o=80; - const float w=20; - const float h=50; - Vec2 star[] = { - Vec2(o+w,o-h), Vec2(o+w*2, o), // lower spike - Vec2(o + w*2 + h, o+w ), Vec2(o + w*2, o+w*2), // right spike + const float o = 80; + const float w = 20; + const float h = 50; + Vec2 star[] = { + Vec2(o + w, o - h), Vec2(o + w * 2, o), // lower spike + Vec2(o + w * 2 + h, o + w), Vec2(o + w * 2, o + w * 2), // right spike // {o +w, o+w*2+h}, {o,o+w*2}, // top spike // {o -h, o+w}, {o,o}, // left spike }; - - draw->drawPolygon(star, sizeof(star)/sizeof(star[0]), Color4F(1.0f,0.0f,0.0f,0.5f), 1, Color4F(0.0f,0.0f,1.0f,1.0f)); + + draw->drawPolygon(star, sizeof(star) / sizeof(star[0]), Color4F(1.0f, 0.0f, 0.0f, 0.5f), 1, + Color4F(0.0f, 0.0f, 1.0f, 1.0f)); } - + // star poly (doesn't trigger bug... order is important un tesselation is supported. { - const float o=180; - const float w=20; - const float h=50; - Vec2 star[] = { - Vec2(o,o), Vec2(o+w,o-h), Vec2(o+w*2, o), // lower spike - Vec2(o + w*2 + h, o+w ), Vec2(o + w*2, o+w*2), // right spike - Vec2(o +w, o+w*2+h), Vec2(o,o+w*2), // top spike - Vec2(o -h, o+w), // left spike + const float o = 180; + const float w = 20; + const float h = 50; + Vec2 star[] = { + Vec2(o, o), + Vec2(o + w, o - h), + Vec2(o + w * 2, o), // lower spike + Vec2(o + w * 2 + h, o + w), + Vec2(o + w * 2, o + w * 2), // right spike + Vec2(o + w, o + w * 2 + h), + Vec2(o, o + w * 2), // top spike + Vec2(o - h, o + w), // left spike }; - - draw->drawPolygon(star, sizeof(star)/sizeof(star[0]), Color4F(1.0f,0.0f,0.0f,0.5f), 1, Color4F(0.0f,0.0f,1.0f,1.0f)); + + draw->drawPolygon(star, sizeof(star) / sizeof(star[0]), Color4F(1.0f, 0.0f, 0.0f, 0.5f), 1, + Color4F(0.0f, 0.0f, 1.0f, 1.0f)); } - - //draw a solid polygon - Vec2 vertices3[] = {Vec2(60.0f,160.0f), Vec2(70.0f,190.0f), Vec2(100.0f,190.0f), Vec2(90.0f,160.0f)}; - draw->drawSolidPoly( vertices3, 4, Color4F(1.0f,1.0f,0.0f,1.0f) ); - - //draw a solid rectangle - draw->drawSolidRect(Vec2(10.0f,10.0f), Vec2(20.0f,20.0f), Color4F(1.0f,1.0f,0.0f,1.0f)); - - //draw a solid circle - draw->drawSolidCircle( VisibleRect::center() + Vec2(140.0f,0.0f), 40, CC_DEGREES_TO_RADIANS(90), 50, 2.0f, 2.0f, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); - + + // draw a solid polygon + Vec2 vertices3[] = {Vec2(60.0f, 160.0f), Vec2(70.0f, 190.0f), Vec2(100.0f, 190.0f), Vec2(90.0f, 160.0f)}; + draw->drawSolidPoly(vertices3, 4, Color4F(1.0f, 1.0f, 0.0f, 1.0f)); + + // draw a solid rectangle + draw->drawSolidRect(Vec2(10.0f, 10.0f), Vec2(20.0f, 20.0f), Color4F(1.0f, 1.0f, 0.0f, 1.0f)); + + // draw a solid circle + draw->drawSolidCircle(VisibleRect::center() + Vec2(140.0f, 0.0f), 40, CC_DEGREES_TO_RADIANS(90), 50, 2.0f, 2.0f, + Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + // Draw segment - draw->drawSegment(Vec2(20.0f,s.height), Vec2(20.0f,s.height/2), 10, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); - - draw->drawSegment(Vec2(10.0f,s.height/2), Vec2(s.width/2, s.height/2), 40, Color4F(1.0f, 0.0f, 1.0f, 0.5f)); + draw->drawSegment(Vec2(20.0f, s.height), Vec2(20.0f, s.height / 2), 10, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + + draw->drawSegment(Vec2(10.0f, s.height / 2), Vec2(s.width / 2, s.height / 2), 40, Color4F(1.0f, 0.0f, 1.0f, 0.5f)); // Draw triangle - draw->drawTriangle(Vec2(10.0f, 10.0f), Vec2(70.0f, 30.0f), Vec2(100.0f, 140.0f), Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); - - for (int i = 0; i < 100; i++) { - draw->drawPoint(Vec2(i*7.0f, 5.0f), (float)i/5+1, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); + draw->drawTriangle(Vec2(10.0f, 10.0f), Vec2(70.0f, 30.0f), Vec2(100.0f, 140.0f), + Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5f)); + + for (int i = 0; i < 100; i++) + { + draw->drawPoint(Vec2(i * 7.0f, 5.0f), (float)i / 5 + 1, + Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1.0f)); } auto draw1 = DrawNode::create(); @@ -173,8 +198,8 @@ DrawNodeTest::DrawNodeTest() draw1->drawLine(Vec2(0.0f, s.height), Vec2(s.width, s.height - 20), Color4F::YELLOW); draw1->drawLine(Vec2(0.0f, 0.0f), Vec2(s.width, s.height - 20), Color4F::YELLOW); - draw->runAction(RepeatForever::create(Sequence::create(FadeIn::create(1.2),FadeOut::create(1.2), NULL))); - draw1->runAction(RepeatForever::create(Sequence::create(FadeIn::create(1.2),FadeOut::create(1.2), NULL))); + draw->runAction(RepeatForever::create(Sequence::create(FadeIn::create(1.2), FadeOut::create(1.2), NULL))); + draw1->runAction(RepeatForever::create(Sequence::create(FadeIn::create(1.2), FadeOut::create(1.2), NULL))); } string DrawNodeTest::title() const @@ -197,9 +222,11 @@ Issue11942Test::Issue11942Test() // draw a circle draw->setLineWidth(1); - draw->drawCircle(VisibleRect::center() - Vec2(140.0f,0.0f), 50, CC_DEGREES_TO_RADIANS(90), 30, false, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); + draw->drawCircle(VisibleRect::center() - Vec2(140.0f, 0.0f), 50, CC_DEGREES_TO_RADIANS(90), 30, false, + Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); draw->setLineWidth(10); - draw->drawCircle(VisibleRect::center() + Vec2(140.0f,0.0f), 50, CC_DEGREES_TO_RADIANS(90), 30, false, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); + draw->drawCircle(VisibleRect::center() + Vec2(140.0f, 0.0f), 50, CC_DEGREES_TO_RADIANS(90), 30, false, + Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1)); } string Issue11942Test::title() const diff --git a/tests/cpp-tests/Classes/DrawPrimitivesTest/DrawPrimitivesTest.h b/tests/cpp-tests/Classes/DrawPrimitivesTest/DrawPrimitivesTest.h index e5aae33dcbaf..37c10faf4683 100644 --- a/tests/cpp-tests/Classes/DrawPrimitivesTest/DrawPrimitivesTest.h +++ b/tests/cpp-tests/Classes/DrawPrimitivesTest/DrawPrimitivesTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -42,7 +42,7 @@ class DrawNodeTest : public DrawPrimitivesBaseTest CREATE_FUNC(DrawNodeTest); DrawNodeTest(); - + virtual std::string title() const override; virtual std::string subtitle() const override; }; @@ -56,5 +56,4 @@ class Issue11942Test : public DrawPrimitivesBaseTest virtual std::string title() const override; virtual std::string subtitle() const override; - }; diff --git a/tests/cpp-tests/Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp b/tests/cpp-tests/Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp index 1ccd5aadba18..ed7b7075221a 100644 --- a/tests/cpp-tests/Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp +++ b/tests/cpp-tests/Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -26,7 +26,7 @@ USING_NS_CC; -enum +enum { kTagTextLayer = 1, @@ -34,7 +34,7 @@ enum kTagSprite2 = 2, kTagBackground = 1, - kTagLabel = 2, + kTagLabel = 2, }; EffectAdvanceTests::EffectAdvanceTests() @@ -56,25 +56,25 @@ void Effect1::onEnter() { EffectAdvanceBaseTest::onEnter(); - //auto target = getChildByTag(kTagBackground); - + // auto target = getChildByTag(kTagBackground); + // To reuse a grid the grid size and the grid type must be the same. // in this case: // Lens3D is Grid3D and it's size is (15,10) // Waves3D is Grid3D and it's size is (15,10) - - auto size = Director::getInstance()->getWinSize(); - auto lens = Lens3D::create(0.0f, Size(15,10), Vec2(size.width/2,size.height/2), 240); - auto waves = Waves3D::create(10, Size(15,10), 18, 15); + + auto size = Director::getInstance()->getWinSize(); + auto lens = Lens3D::create(0.0f, Size(15, 10), Vec2(size.width / 2, size.height / 2), 240); + auto waves = Waves3D::create(10, Size(15, 10), 18, 15); auto reuse = ReuseGrid::create(1); auto delay = DelayTime::create(8); -// auto orbit = OrbitCamera::create(5, 1, 2, 0, 180, 0, -90); -// auto orbit_back = orbit->reverse(); + // auto orbit = OrbitCamera::create(5, 1, 2, 0, 180, 0, -90); + // auto orbit_back = orbit->reverse(); //_bgNode->runAction( RepeatForever::create( Sequence::create( orbit, orbit_back, nullptr) ) ); - _bgNode->runAction( Sequence::create(lens, delay, reuse, waves, nullptr) ); + _bgNode->runAction(Sequence::create(lens, delay, reuse, waves, nullptr)); } std::string Effect1::title() const @@ -91,18 +91,18 @@ void Effect2::onEnter() { EffectAdvanceBaseTest::onEnter(); - //auto target = getChildByTag(kTagBackground); - + // auto target = getChildByTag(kTagBackground); + // To reuse a grid the grid size and the grid type must be the same. // in this case: // ShakyTiles is TiledGrid3D and it's size is (15,10) // Shuffletiles is TiledGrid3D and it's size is (15,10) // TurnOfftiles is TiledGrid3D and it's size is (15,10) - auto shaky = ShakyTiles3D::create(5, Size(15,10), 4, false); - auto shuffle = ShuffleTiles::create(0, Size(15,10), 3); - auto turnoff = TurnOffTiles::create(0, Size(15,10), 3); - auto turnon = turnoff->reverse(); - + auto shaky = ShakyTiles3D::create(5, Size(15, 10), 4, false); + auto shuffle = ShuffleTiles::create(0, Size(15, 10), 3); + auto turnoff = TurnOffTiles::create(0, Size(15, 10), 3); + auto turnon = turnoff->reverse(); + // reuse 2 times: // 1 for shuffle // 2 for turn off @@ -110,12 +110,12 @@ void Effect2::onEnter() auto reuse = ReuseGrid::create(2); auto delay = DelayTime::create(1); - -// id orbit = [OrbitCamera::create:5 radius:1 deltaRadius:2 angleZ:0 deltaAngleZ:180 angleX:0 deltaAngleX:-90]; -// id orbit_back = [orbit reverse]; -// -// [target runAction: [RepeatForever::create: [Sequence actions: orbit, orbit_back, nil]]]; - _bgNode->runAction(Sequence::create( shaky, delay, reuse, shuffle, delay->clone(), turnoff, turnon, nullptr) ); + + // id orbit = [OrbitCamera::create:5 radius:1 deltaRadius:2 angleZ:0 deltaAngleZ:180 angleX:0 deltaAngleX:-90]; + // id orbit_back = [orbit reverse]; + // + // [target runAction: [RepeatForever::create: [Sequence actions: orbit, orbit_back, nil]]]; + _bgNode->runAction(Sequence::create(shaky, delay, reuse, shuffle, delay->clone(), turnoff, turnon, nullptr)); } std::string Effect2::title() const @@ -123,7 +123,6 @@ std::string Effect2::title() const return "ShakyTiles + ShuffleTiles + TurnOffTiles"; } - //------------------------------------------------------------------ // // Effect3 @@ -132,18 +131,18 @@ std::string Effect2::title() const void Effect3::onEnter() { EffectAdvanceBaseTest::onEnter(); - //auto bg = getChildByTag(kTagBackground); - //auto target1 = bg->getChildByTag(kTagSprite1); - //auto target2 = bg->getChildByTag(kTagSprite2); - auto waves = Waves::create(5, Size(15,10), 5, 20, true, false); - auto shaky = Shaky3D::create(5, Size(15,10), 4, false); - - _target1->runAction( RepeatForever::create( waves ) ); - _target2->runAction( RepeatForever::create( shaky ) ); - + // auto bg = getChildByTag(kTagBackground); + // auto target1 = bg->getChildByTag(kTagSprite1); + // auto target2 = bg->getChildByTag(kTagSprite2); + auto waves = Waves::create(5, Size(15, 10), 5, 20, true, false); + auto shaky = Shaky3D::create(5, Size(15, 10), 4, false); + + _target1->runAction(RepeatForever::create(waves)); + _target2->runAction(RepeatForever::create(shaky)); + // moving background. Testing issue #244 - auto move = MoveBy::create(3, Vec2(200,0) ); - _bgNode->runAction(RepeatForever::create( Sequence::create(move, move->reverse(), nullptr) )); + auto move = MoveBy::create(3, Vec2(200, 0)); + _bgNode->runAction(RepeatForever::create(Sequence::create(move, move->reverse(), nullptr))); } std::string Effect3::title() const @@ -151,7 +150,6 @@ std::string Effect3::title() const return "Effects on 2 sprites"; } - //------------------------------------------------------------------ // // Effect4 @@ -161,28 +159,20 @@ std::string Effect3::title() const class Lens3DTarget : public Node { public: - virtual void setPosition(const Vec2& var) - { - _lens3D->setPosition(var); - } - - virtual const Vec2& getPosition() const - { - return _lens3D->getPosition(); - } - + virtual void setPosition(const Vec2& var) { _lens3D->setPosition(var); } + + virtual const Vec2& getPosition() const { return _lens3D->getPosition(); } + static Lens3DTarget* create(Lens3D* pAction) { Lens3DTarget* pRet = new Lens3DTarget(); - pRet->_lens3D = pAction; + pRet->_lens3D = pAction; pRet->autorelease(); return pRet; } -private: - Lens3DTarget() - : _lens3D(nullptr) - {} +private: + Lens3DTarget() : _lens3D(nullptr) {} Lens3D* _lens3D; }; @@ -190,27 +180,27 @@ class Lens3DTarget : public Node void Effect4::onEnter() { EffectAdvanceBaseTest::onEnter(); - //Node* gridNode = NodeGrid::create(); - - auto lens = Lens3D::create(10, Size(32,24), Vec2(100,180), 150); - auto move = JumpBy::create(5, Vec2(380,0), 100, 4); + // Node* gridNode = NodeGrid::create(); + + auto lens = Lens3D::create(10, Size(32, 24), Vec2(100, 180), 150); + auto move = JumpBy::create(5, Vec2(380, 0), 100, 4); auto move_back = move->reverse(); - auto seq = Sequence::create( move, move_back, nullptr); + auto seq = Sequence::create(move, move_back, nullptr); - /* In cocos2d-iphone, the type of action's target is 'id', so it supports using the instance of 'Lens3D' as its target. - While in cocos2d-x, the target of action only supports Node or its subclass, - so we make an encapsulation for Lens3D to achieve that. + /* In cocos2d-iphone, the type of action's target is 'id', so it supports using the instance of 'Lens3D' as its + target. While in cocos2d-x, the target of action only supports Node or its subclass, so we make an encapsulation + for Lens3D to achieve that. */ auto director = Director::getInstance(); - auto pTarget = Lens3DTarget::create(lens); + auto pTarget = Lens3DTarget::create(lens); // Please make sure the target been added to its parent. this->addChild(pTarget); - //gridNode->addChild(pTarget); + // gridNode->addChild(pTarget); director->getActionManager()->addAction(seq, pTarget, false); - - _bgNode->runAction( lens ); + + _bgNode->runAction(lens); } std::string Effect4::title() const @@ -227,19 +217,16 @@ void Effect5::onEnter() { EffectAdvanceBaseTest::onEnter(); - //CCDirector::getInstance()->setProjection(DirectorProjection2D); - - auto effect = Liquid::create(2, Size(32,24), 1, 20); - - auto stopEffect = Sequence::create( - effect, - DelayTime::create(2), - StopGrid::create(), - // [DelayTime::create:2], - // [[effect copy] autorelease], - nullptr); - - //auto bg = getChildByTag(kTagBackground); + // CCDirector::getInstance()->setProjection(DirectorProjection2D); + + auto effect = Liquid::create(2, Size(32, 24), 1, 20); + + auto stopEffect = Sequence::create(effect, DelayTime::create(2), StopGrid::create(), + // [DelayTime::create:2], + // [[effect copy] autorelease], + nullptr); + + // auto bg = getChildByTag(kTagBackground); _bgNode->runAction(stopEffect); } @@ -263,32 +250,32 @@ void Effect5::onExit() void Issue631::onEnter() { EffectAdvanceBaseTest::onEnter(); - - auto effect = Sequence::create( DelayTime::create(2.0f), Shaky3D::create(5.0f, Size(5, 5), 16, false), nullptr); + + auto effect = Sequence::create(DelayTime::create(2.0f), Shaky3D::create(5.0f, Size(5, 5), 16, false), nullptr); // cleanup - //auto bg = getChildByTag(kTagBackground); + // auto bg = getChildByTag(kTagBackground); removeChild(_bgNode, true); // background - auto layer = LayerColor::create( Color4B(255,0,0,255) ); + auto layer = LayerColor::create(Color4B(255, 0, 0, 255)); addChild(layer, -10); auto sprite = Sprite::create("Images/grossini.png"); - sprite->setPosition(50,80); + sprite->setPosition(50, 80); layer->addChild(sprite, 10); - + // foreground auto layer2BaseGrid = NodeGrid::create(); - auto layer2 = LayerColor::create(Color4B( 0, 255,0,255 ) ); - auto fog = Sprite::create("Images/Fog.png"); + auto layer2 = LayerColor::create(Color4B(0, 255, 0, 255)); + auto fog = Sprite::create("Images/Fog.png"); BlendFunc bf = {backend::BlendFactor::SRC_ALPHA, backend::BlendFactor::ONE_MINUS_SRC_ALPHA}; fog->setBlendFunc(bf); layer2->addChild(fog, 1); addChild(layer2BaseGrid, 1); layer2BaseGrid->addChild(layer2); - - layer2BaseGrid->runAction( RepeatForever::create(effect) ); + + layer2BaseGrid->runAction(RepeatForever::create(effect)); } std::string Issue631::title() const @@ -310,43 +297,41 @@ std::string Issue631::subtitle() const void EffectAdvanceBaseTest::onEnter() { TestCase::onEnter(); - + _bgNode = NodeGrid::create(); - _bgNode->setAnchorPoint(Vec2(0.5f,0.5f)); + _bgNode->setAnchorPoint(Vec2(0.5f, 0.5f)); addChild(_bgNode); //_bgNode->setPosition( VisibleRect::center() ); auto bg = Sprite::create("Images/background3.png"); - bg->setPosition( VisibleRect::center() ); - //addChild(bg, 0, kTagBackground); - //bg->setPosition( VisibleRect::center() ); + bg->setPosition(VisibleRect::center()); + // addChild(bg, 0, kTagBackground); + // bg->setPosition( VisibleRect::center() ); _bgNode->addChild(bg); _target1 = NodeGrid::create(); - _target1->setAnchorPoint(Vec2(0.5f,0.5f)); + _target1->setAnchorPoint(Vec2(0.5f, 0.5f)); auto grossini = Sprite::create("Images/grossinis_sister2.png"); _target1->addChild(grossini); _bgNode->addChild(_target1); - _target1->setPosition(VisibleRect::left().x+VisibleRect::getVisibleRect().size.width/3.0f, VisibleRect::bottom().y+ 200); - auto sc = ScaleBy::create(2, 5); + _target1->setPosition(VisibleRect::left().x + VisibleRect::getVisibleRect().size.width / 3.0f, + VisibleRect::bottom().y + 200); + auto sc = ScaleBy::create(2, 5); auto sc_back = sc->reverse(); - _target1->runAction( RepeatForever::create(Sequence::create(sc, sc_back, nullptr) ) ); - + _target1->runAction(RepeatForever::create(Sequence::create(sc, sc_back, nullptr))); _target2 = NodeGrid::create(); - _target2->setAnchorPoint(Vec2(0.5f,0.5f)); + _target2->setAnchorPoint(Vec2(0.5f, 0.5f)); auto tamara = Sprite::create("Images/grossinis_sister1.png"); _target2->addChild(tamara); _bgNode->addChild(_target2); - _target2->setPosition(VisibleRect::left().x+2*VisibleRect::getVisibleRect().size.width/3.0f,VisibleRect::bottom().y+200); - auto sc2 = ScaleBy::create(2, 5); + _target2->setPosition(VisibleRect::left().x + 2 * VisibleRect::getVisibleRect().size.width / 3.0f, + VisibleRect::bottom().y + 200); + auto sc2 = ScaleBy::create(2, 5); auto sc2_back = sc2->reverse(); - _target2->runAction( RepeatForever::create(Sequence::create(sc2, sc2_back, nullptr) ) ); - + _target2->runAction(RepeatForever::create(Sequence::create(sc2, sc2_back, nullptr))); } -EffectAdvanceBaseTest::~EffectAdvanceBaseTest() -{ -} +EffectAdvanceBaseTest::~EffectAdvanceBaseTest() {} std::string EffectAdvanceBaseTest::title() const { diff --git a/tests/cpp-tests/Classes/EffectsAdvancedTest/EffectsAdvancedTest.h b/tests/cpp-tests/Classes/EffectsAdvancedTest/EffectsAdvancedTest.h index da9bcee86570..3613e224783d 100644 --- a/tests/cpp-tests/Classes/EffectsAdvancedTest/EffectsAdvancedTest.h +++ b/tests/cpp-tests/Classes/EffectsAdvancedTest/EffectsAdvancedTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -30,12 +30,12 @@ DEFINE_TEST_SUITE(EffectAdvanceTests); -class EffectAdvanceBaseTest: public TestCase +class EffectAdvanceBaseTest : public TestCase { protected: cocos2d::TextureAtlas* _atlas; - std::string _title; + std::string _title; cocos2d::Node* _bgNode; cocos2d::Node* _target1; diff --git a/tests/cpp-tests/Classes/EffectsTest/EffectsTest.cpp b/tests/cpp-tests/Classes/EffectsTest/EffectsTest.cpp index 6963dde53187..de2b32641c5b 100644 --- a/tests/cpp-tests/Classes/EffectsTest/EffectsTest.cpp +++ b/tests/cpp-tests/Classes/EffectsTest/EffectsTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -50,250 +50,250 @@ EffectTests::EffectTests() ADD_TEST_CASE(JumpTiles3DDemo); ADD_TEST_CASE(SplitRowsDemo); ADD_TEST_CASE(SplitColsDemo); -// ADD_TEST_CASE(PageTurn3DDemo); // TODO crash on iPhone X -// ADD_TEST_CASE(PageTurn3DRectDemo); + // ADD_TEST_CASE(PageTurn3DDemo); // TODO crash on iPhone X + // ADD_TEST_CASE(PageTurn3DRectDemo); } Shaky3DDemo::Shaky3DDemo() { - _title = "Shaky3D"; + _title = "Shaky3D"; _subtitle = ""; } cocos2d::ActionInterval* Shaky3DDemo::createEffect(float t) { - return Shaky3D::create(t, Size(15,10), 5, false); + return Shaky3D::create(t, Size(15, 10), 5, false); } Waves3DDemo::Waves3DDemo() { - _title = "Waves3D"; + _title = "Waves3D"; _subtitle = ""; } cocos2d::ActionInterval* Waves3DDemo::createEffect(float t) { - return Waves3D::create(t, Size(15,10), 5, 40); + return Waves3D::create(t, Size(15, 10), 5, 40); } cocos2d::ActionInterval* FlipX3DDemo::createEffect(float t) { - auto flipx = FlipX3D::create(t); + auto flipx = FlipX3D::create(t); auto flipx_back = flipx->reverse(); - auto delay = DelayTime::create(2); + auto delay = DelayTime::create(2); return Sequence::create(flipx, delay, flipx_back, nullptr); } FlipX3DDemo::FlipX3DDemo() { - _title = "FlipX3D"; + _title = "FlipX3D"; _subtitle = ""; } cocos2d::ActionInterval* FlipY3DDemo::createEffect(float t) { - auto flipy = FlipY3D::create(t); + auto flipy = FlipY3D::create(t); auto flipy_back = flipy->reverse(); - auto delay = DelayTime::create(2); - + auto delay = DelayTime::create(2); + return Sequence::create(flipy, delay, flipy_back, nullptr); } FlipY3DDemo::FlipY3DDemo() { - _title = "FlipY3D"; + _title = "FlipY3D"; _subtitle = ""; } cocos2d::ActionInterval* Lens3DDemo::createEffect(float t) { auto size = Director::getInstance()->getWinSize(); - return Lens3D::create(t, Size(15,10), Vec2(size.width/2,size.height/2), 240); + return Lens3D::create(t, Size(15, 10), Vec2(size.width / 2, size.height / 2), 240); } Lens3DDemo::Lens3DDemo() { - _title = "Lens3D"; + _title = "Lens3D"; _subtitle = ""; } cocos2d::ActionInterval* Ripple3DDemo::createEffect(float t) { auto size = Director::getInstance()->getWinSize(); - return Ripple3D::create(t, Size(32,24), Vec2(size.width/2,size.height/2), 240, 4, 160); + return Ripple3D::create(t, Size(32, 24), Vec2(size.width / 2, size.height / 2), 240, 4, 160); } Ripple3DDemo::Ripple3DDemo() { - _title = "Ripple3D"; + _title = "Ripple3D"; _subtitle = ""; } cocos2d::ActionInterval* LiquidDemo::createEffect(float t) { - return Liquid::create(t, Size(16,12), 4, 20); + return Liquid::create(t, Size(16, 12), 4, 20); } LiquidDemo::LiquidDemo() { - _title = "Liquid"; + _title = "Liquid"; _subtitle = ""; } cocos2d::ActionInterval* WavesDemo::createEffect(float t) { - return Waves::create(t, Size(16,12), 4, 20, true, true); + return Waves::create(t, Size(16, 12), 4, 20, true, true); } WavesDemo::WavesDemo() { - _title = "Waves"; + _title = "Waves"; _subtitle = ""; } cocos2d::ActionInterval* TwirlDemo::createEffect(float t) { auto size = Director::getInstance()->getWinSize(); - return Twirl::create(t, Size(12,8), Vec2(size.width/2, size.height/2), 1, 2.5f); + return Twirl::create(t, Size(12, 8), Vec2(size.width / 2, size.height / 2), 1, 2.5f); } TwirlDemo::TwirlDemo() { - _title = "Twirl"; + _title = "Twirl"; _subtitle = ""; } cocos2d::ActionInterval* ShakyTiles3DDemo::createEffect(float t) { - return ShakyTiles3D::create(t, Size(16,12), 5, false) ; + return ShakyTiles3D::create(t, Size(16, 12), 5, false); } ShakyTiles3DDemo::ShakyTiles3DDemo() { - _title = "ShakyTiles3D"; + _title = "ShakyTiles3D"; _subtitle = ""; } cocos2d::ActionInterval* ShatteredTiles3DDemo::createEffect(float t) { - return ShatteredTiles3D::create(t, Size(16,12), 5, false); + return ShatteredTiles3D::create(t, Size(16, 12), 5, false); } ShatteredTiles3DDemo::ShatteredTiles3DDemo() { - _title = "ShatteredTiles3D"; + _title = "ShatteredTiles3D"; _subtitle = ""; } cocos2d::ActionInterval* ShuffleTilesDemo::createEffect(float t) { - auto shuffle = ShuffleTiles::create(t, Size(16,12), 25); + auto shuffle = ShuffleTiles::create(t, Size(16, 12), 25); auto shuffle_back = shuffle->reverse(); - auto delay = DelayTime::create(2); - + auto delay = DelayTime::create(2); + return Sequence::create(shuffle, delay, shuffle_back, nullptr); } ShuffleTilesDemo::ShuffleTilesDemo() { - _title = "ShuffleTiles"; + _title = "ShuffleTiles"; _subtitle = ""; } cocos2d::ActionInterval* FadeOutTRTilesDemo::createEffect(float t) { - auto fadeout = FadeOutTRTiles::create(t, Size(16,12)); - auto back = fadeout->reverse(); - auto delay = DelayTime::create(0.5f); - + auto fadeout = FadeOutTRTiles::create(t, Size(16, 12)); + auto back = fadeout->reverse(); + auto delay = DelayTime::create(0.5f); + return Sequence::create(fadeout, delay, back, nullptr); } FadeOutTRTilesDemo::FadeOutTRTilesDemo() { - _title = "FadeOutTRTiles"; + _title = "FadeOutTRTiles"; _subtitle = ""; } cocos2d::ActionInterval* FadeOutBLTilesDemo::createEffect(float t) { - auto fadeout = FadeOutBLTiles::create(t, Size(16,12)); - auto back = fadeout->reverse(); - auto delay = DelayTime::create(0.5f); - + auto fadeout = FadeOutBLTiles::create(t, Size(16, 12)); + auto back = fadeout->reverse(); + auto delay = DelayTime::create(0.5f); + return Sequence::create(fadeout, delay, back, nullptr); } FadeOutBLTilesDemo::FadeOutBLTilesDemo() { - _title = "FadeOutBLTiles"; + _title = "FadeOutBLTiles"; _subtitle = ""; } cocos2d::ActionInterval* FadeOutUpTilesDemo::createEffect(float t) { - auto fadeout = FadeOutUpTiles::create(t, Size(16,12)); - auto back = fadeout->reverse(); - auto delay = DelayTime::create(0.5f); - + auto fadeout = FadeOutUpTiles::create(t, Size(16, 12)); + auto back = fadeout->reverse(); + auto delay = DelayTime::create(0.5f); + return Sequence::create(fadeout, delay, back, nullptr); } FadeOutUpTilesDemo::FadeOutUpTilesDemo() { - _title = "FadeOutUpTiles"; + _title = "FadeOutUpTiles"; _subtitle = ""; } cocos2d::ActionInterval* FadeOutDownTilesDemo::createEffect(float t) { - auto fadeout = FadeOutDownTiles::create(t, Size(16,12)); - auto back = fadeout->reverse(); - auto delay = DelayTime::create(0.5f); - + auto fadeout = FadeOutDownTiles::create(t, Size(16, 12)); + auto back = fadeout->reverse(); + auto delay = DelayTime::create(0.5f); + return Sequence::create(fadeout, delay, back, nullptr); } FadeOutDownTilesDemo::FadeOutDownTilesDemo() { - _title = "FadeOutDownTiles"; + _title = "FadeOutDownTiles"; _subtitle = ""; } cocos2d::ActionInterval* TurnOffTilesDemo::createEffect(float t) { - auto fadeout = TurnOffTiles::create(t, Size(48,32), 25); - auto back = fadeout->reverse(); - auto delay = DelayTime::create(0.5f); - + auto fadeout = TurnOffTiles::create(t, Size(48, 32), 25); + auto back = fadeout->reverse(); + auto delay = DelayTime::create(0.5f); + return Sequence::create(fadeout, delay, back, nullptr); } TurnOffTilesDemo::TurnOffTilesDemo() { - _title = "TurnOffTiles"; + _title = "TurnOffTiles"; _subtitle = ""; } cocos2d::ActionInterval* WavesTiles3DDemo::createEffect(float t) { - return WavesTiles3D::create(t, Size(15,10), 4, 120); + return WavesTiles3D::create(t, Size(15, 10), 4, 120); } WavesTiles3DDemo::WavesTiles3DDemo() { - _title = "WavesTiles3D"; + _title = "WavesTiles3D"; _subtitle = ""; } cocos2d::ActionInterval* JumpTiles3DDemo::createEffect(float t) { - return JumpTiles3D::create(t, Size(15,10), 2, 30); + return JumpTiles3D::create(t, Size(15, 10), 2, 30); } JumpTiles3DDemo::JumpTiles3DDemo() { - _title = "JumpTiles3D"; + _title = "JumpTiles3D"; _subtitle = ""; } @@ -304,7 +304,7 @@ cocos2d::ActionInterval* SplitRowsDemo::createEffect(float t) SplitRowsDemo::SplitRowsDemo() { - _title = "SplitRows"; + _title = "SplitRows"; _subtitle = ""; } @@ -315,54 +315,48 @@ cocos2d::ActionInterval* SplitColsDemo::createEffect(float t) SplitColsDemo::SplitColsDemo() { - _title = "SplitCols"; + _title = "SplitCols"; _subtitle = ""; } cocos2d::ActionInterval* PageTurn3DDemo::createEffect(float t) { - return PageTurn3D::create(t, Size(15,10)); + return PageTurn3D::create(t, Size(15, 10)); } PageTurn3DDemo::PageTurn3DDemo() { - _title = "PageTurn3D"; + _title = "PageTurn3D"; _subtitle = ""; } cocos2d::ActionInterval* PageTurn3DRectDemo::createEffect(float t) { - return PageTurn3D::create(t, Size(15,10)); + return PageTurn3D::create(t, Size(15, 10)); } PageTurn3DRectDemo::PageTurn3DRectDemo() { - _title = "PageTurn3D-Rect"; + _title = "PageTurn3D-Rect"; _subtitle = ""; } -#define SID_RESTART 1 +#define SID_RESTART 1 -EffectBaseTest::EffectBaseTest() -: _gridNodeTarget(nullptr) -{ - -} +EffectBaseTest::EffectBaseTest() : _gridNodeTarget(nullptr) {} bool EffectBaseTest::init() { - if(TestCase::init()) + if (TestCase::init()) { - LayerColor *background = LayerColor::create( Color4B(32,128,32,255) ); - this->addChild(background,-20); - if(isRectEffect()) + LayerColor* background = LayerColor::create(Color4B(32, 128, 32, 255)); + this->addChild(background, -20); + if (isRectEffect()) { Size visibleSize = Director::getInstance()->getVisibleSize(); - Rect gridRect = Rect(visibleSize.width * 0.2, - visibleSize.height * 0.2, - visibleSize.width * 0.6, - visibleSize.height * 0.6); - _gridNodeTarget = NodeGrid::create(gridRect); + Rect gridRect = Rect(visibleSize.width * 0.2, visibleSize.height * 0.2, visibleSize.width * 0.6, + visibleSize.height * 0.6); + _gridNodeTarget = NodeGrid::create(gridRect); } else { @@ -370,27 +364,29 @@ bool EffectBaseTest::init() } addChild(_gridNodeTarget, 0); _gridNodeTarget->runAction(createEffect(3)); - + auto bg = Sprite::create(s_back3); _gridNodeTarget->addChild(bg, 0); bg->setPosition(VisibleRect::center()); - + auto grossini = Sprite::create(s_pathSister2); _gridNodeTarget->addChild(grossini, 1); - grossini->setPosition(VisibleRect::left().x+VisibleRect::getVisibleRect().size.width/3,VisibleRect::center().y); - auto sc = ScaleBy::create(2, 5); + grossini->setPosition(VisibleRect::left().x + VisibleRect::getVisibleRect().size.width / 3, + VisibleRect::center().y); + auto sc = ScaleBy::create(2, 5); auto sc_back = sc->reverse(); - grossini->runAction( RepeatForever::create(Sequence::create(sc, sc_back, nullptr) ) ); - + grossini->runAction(RepeatForever::create(Sequence::create(sc, sc_back, nullptr))); + auto tamara = Sprite::create(s_pathSister1); _gridNodeTarget->addChild(tamara, 1); - tamara->setPosition(VisibleRect::left().x+2*VisibleRect::getVisibleRect().size.width/3,VisibleRect::center().y); - auto sc2 = ScaleBy::create(2, 5); + tamara->setPosition(VisibleRect::left().x + 2 * VisibleRect::getVisibleRect().size.width / 3, + VisibleRect::center().y); + auto sc2 = ScaleBy::create(2, 5); auto sc2_back = sc2->reverse(); - tamara->runAction( RepeatForever::create(Sequence::create(sc2, sc2_back, nullptr)) ); - - schedule( CC_SCHEDULE_SELECTOR(EffectBaseTest::checkAnim) ); - + tamara->runAction(RepeatForever::create(Sequence::create(sc2, sc2_back, nullptr))); + + schedule(CC_SCHEDULE_SELECTOR(EffectBaseTest::checkAnim)); + return true; } return false; @@ -398,10 +394,8 @@ bool EffectBaseTest::init() void EffectBaseTest::checkAnim(float dt) { - if ( _gridNodeTarget->getNumberOfRunningActions() == 0 && _gridNodeTarget->getGrid() != nullptr) + if (_gridNodeTarget->getNumberOfRunningActions() == 0 && _gridNodeTarget->getGrid() != nullptr) _gridNodeTarget->setGrid(nullptr); } -EffectBaseTest::~EffectBaseTest() -{ -} +EffectBaseTest::~EffectBaseTest() {} diff --git a/tests/cpp-tests/Classes/EffectsTest/EffectsTest.h b/tests/cpp-tests/Classes/EffectsTest/EffectsTest.h index 3d9e7670642b..7a6bf22a68be 100644 --- a/tests/cpp-tests/Classes/EffectsTest/EffectsTest.h +++ b/tests/cpp-tests/Classes/EffectsTest/EffectsTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,13 +34,14 @@ class EffectBaseTest : public TestCase public: EffectBaseTest(); virtual ~EffectBaseTest(); + protected: virtual bool init() override; - virtual cocos2d::ActionInterval* createEffect(float t) {return nullptr;} + virtual cocos2d::ActionInterval* createEffect(float t) { return nullptr; } void checkAnim(float dt); - virtual bool isRectEffect(){return false;} - virtual std::string title() const override {return _title;}; - virtual std::string subtitle() const override {return _subtitle;}; + virtual bool isRectEffect() { return false; } + virtual std::string title() const override { return _title; }; + virtual std::string subtitle() const override { return _subtitle; }; std::string _title; std::string _subtitle; cocos2d::NodeGrid* _gridNodeTarget; @@ -51,6 +52,7 @@ class Shaky3DDemo : public EffectBaseTest public: CREATE_FUNC(Shaky3DDemo); Shaky3DDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -60,6 +62,7 @@ class Waves3DDemo : public EffectBaseTest public: CREATE_FUNC(Waves3DDemo); Waves3DDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -69,6 +72,7 @@ class FlipX3DDemo : public EffectBaseTest public: CREATE_FUNC(FlipX3DDemo); FlipX3DDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -78,6 +82,7 @@ class FlipY3DDemo : public EffectBaseTest public: CREATE_FUNC(FlipY3DDemo); FlipY3DDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -87,6 +92,7 @@ class Lens3DDemo : public EffectBaseTest public: CREATE_FUNC(Lens3DDemo); Lens3DDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -96,6 +102,7 @@ class Ripple3DDemo : public EffectBaseTest public: CREATE_FUNC(Ripple3DDemo); Ripple3DDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -105,6 +112,7 @@ class LiquidDemo : public EffectBaseTest public: CREATE_FUNC(LiquidDemo); LiquidDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -114,6 +122,7 @@ class WavesDemo : public EffectBaseTest public: CREATE_FUNC(WavesDemo); WavesDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -123,6 +132,7 @@ class TwirlDemo : public EffectBaseTest public: CREATE_FUNC(TwirlDemo); TwirlDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -132,6 +142,7 @@ class ShakyTiles3DDemo : public EffectBaseTest public: CREATE_FUNC(ShakyTiles3DDemo); ShakyTiles3DDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -141,6 +152,7 @@ class ShatteredTiles3DDemo : public EffectBaseTest public: CREATE_FUNC(ShatteredTiles3DDemo); ShatteredTiles3DDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -150,6 +162,7 @@ class ShuffleTilesDemo : public EffectBaseTest public: CREATE_FUNC(ShuffleTilesDemo); ShuffleTilesDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -159,6 +172,7 @@ class FadeOutTRTilesDemo : public EffectBaseTest public: CREATE_FUNC(FadeOutTRTilesDemo); FadeOutTRTilesDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -168,6 +182,7 @@ class FadeOutBLTilesDemo : public EffectBaseTest public: CREATE_FUNC(FadeOutBLTilesDemo); FadeOutBLTilesDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -177,6 +192,7 @@ class FadeOutUpTilesDemo : public EffectBaseTest public: CREATE_FUNC(FadeOutUpTilesDemo); FadeOutUpTilesDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -186,6 +202,7 @@ class FadeOutDownTilesDemo : public EffectBaseTest public: CREATE_FUNC(FadeOutDownTilesDemo); FadeOutDownTilesDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -195,6 +212,7 @@ class TurnOffTilesDemo : public EffectBaseTest public: CREATE_FUNC(TurnOffTilesDemo); TurnOffTilesDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -204,6 +222,7 @@ class WavesTiles3DDemo : public EffectBaseTest public: CREATE_FUNC(WavesTiles3DDemo); WavesTiles3DDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -213,6 +232,7 @@ class JumpTiles3DDemo : public EffectBaseTest public: CREATE_FUNC(JumpTiles3DDemo); JumpTiles3DDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -222,6 +242,7 @@ class SplitRowsDemo : public EffectBaseTest public: CREATE_FUNC(SplitRowsDemo); SplitRowsDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -231,6 +252,7 @@ class SplitColsDemo : public EffectBaseTest public: CREATE_FUNC(SplitColsDemo); SplitColsDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -240,6 +262,7 @@ class PageTurn3DDemo : public EffectBaseTest public: CREATE_FUNC(PageTurn3DDemo); PageTurn3DDemo(); + protected: virtual cocos2d::ActionInterval* createEffect(float t) override; }; @@ -249,8 +272,9 @@ class PageTurn3DRectDemo : public EffectBaseTest public: CREATE_FUNC(PageTurn3DRectDemo); PageTurn3DRectDemo(); + protected: - virtual bool isRectEffect() override {return true;} + virtual bool isRectEffect() override { return true; } virtual cocos2d::ActionInterval* createEffect(float t) override; }; diff --git a/tests/cpp-tests/Classes/ExtensionsTest/AssetsManagerExTest/AssetsManagerExTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/AssetsManagerExTest/AssetsManagerExTest.cpp index dc0ddcf96798..fd9115ce5e42 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/AssetsManagerExTest/AssetsManagerExTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/AssetsManagerExTest/AssetsManagerExTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -29,15 +29,18 @@ USING_NS_CC; USING_NS_CC_EXT; -const char* sceneManifests[] = {"Manifests/AMTestScene1/project.manifest", "Manifests/AMTestScene2/project.manifest", "Manifests/AMTestScene3/project.manifest"}; -const char* storagePaths[] = {"CppTests/AssetsManagerExTest/scene1/", "CppTests/AssetsManagerExTest/scene2/", "CppTests/AssetsManagerExTest/scene3"}; -const char* backgroundPaths[] = {"Images/assetMgrBackground1.jpg", "Images/assetMgrBackground2.png", "Images/assetMgrBackground3.png"}; +const char* sceneManifests[] = {"Manifests/AMTestScene1/project.manifest", "Manifests/AMTestScene2/project.manifest", + "Manifests/AMTestScene3/project.manifest"}; +const char* storagePaths[] = {"CppTests/AssetsManagerExTest/scene1/", "CppTests/AssetsManagerExTest/scene2/", + "CppTests/AssetsManagerExTest/scene3"}; +const char* backgroundPaths[] = {"Images/assetMgrBackground1.jpg", "Images/assetMgrBackground2.png", + "Images/assetMgrBackground3.png"}; AssetsManagerExTests::AssetsManagerExTests() { - addTestCase("AssetsManager Test1", [](){ return AssetsManagerExLoaderScene::create(0); }); - addTestCase("AssetsManager Test2", [](){ return AssetsManagerExLoaderScene::create(1); }); - addTestCase("AssetsManager Test3", [](){ return AssetsManagerExLoaderScene::create(2); }); + addTestCase("AssetsManager Test1", []() { return AssetsManagerExLoaderScene::create(0); }); + addTestCase("AssetsManager Test2", []() { return AssetsManagerExLoaderScene::create(1); }); + addTestCase("AssetsManager Test3", []() { return AssetsManagerExLoaderScene::create(2); }); } AssetsManagerExLoaderScene* AssetsManagerExLoaderScene::create(int testIndex) @@ -57,15 +60,13 @@ AssetsManagerExLoaderScene* AssetsManagerExLoaderScene::create(int testIndex) } AssetsManagerExLoaderScene::AssetsManagerExLoaderScene(int testIndex) -: _testIndex(testIndex) -, _loadLayer(nullptr) -, _downloadMenu(nullptr) -, _am(nullptr) -, _progress(nullptr) -, _amListener(nullptr) -{ - -} + : _testIndex(testIndex) + , _loadLayer(nullptr) + , _downloadMenu(nullptr) + , _am(nullptr) + , _progress(nullptr) + , _amListener(nullptr) +{} bool AssetsManagerExLoaderScene::init() { @@ -75,7 +76,8 @@ bool AssetsManagerExLoaderScene::init() } auto downloadLabel = Label::createWithTTF("Start Download", "fonts/arial.ttf", 16); - auto downloadItem = MenuItemLabel::create(downloadLabel, CC_CALLBACK_1(AssetsManagerExLoaderScene::startDownloadCallback, this)); + auto downloadItem = + MenuItemLabel::create(downloadLabel, CC_CALLBACK_1(AssetsManagerExLoaderScene::startDownloadCallback, this)); downloadItem->setPosition(Vec2(VisibleRect::center().x, VisibleRect::bottom().y + 100)); _downloadMenu = Menu::create(downloadItem, nullptr); _downloadMenu->setPosition(Vec2::ZERO); @@ -86,14 +88,15 @@ bool AssetsManagerExLoaderScene::init() auto sprite = Sprite::create("Images/Icon.png"); _loadLayer->addChild(sprite); - sprite->setPosition( VisibleRect::center() ); - + sprite->setPosition(VisibleRect::center()); + TTFConfig config("fonts/tahoma.ttf", 30); _progress = Label::createWithTTF(config, "0%", TextHAlignment::CENTER); - _progress->setPosition( Vec2(VisibleRect::center().x, VisibleRect::center().y + 50) ); + _progress->setPosition(Vec2(VisibleRect::center().x, VisibleRect::center().y + 50)); _loadLayer->addChild(_progress); - - std::string manifestPath = sceneManifests[_testIndex], storagePath = FileUtils::getInstance()->getWritablePath() + storagePaths[_testIndex]; + + std::string manifestPath = sceneManifests[_testIndex], + storagePath = FileUtils::getInstance()->getWritablePath() + storagePaths[_testIndex]; CCLOG("Storage path for this test : %s", storagePath.c_str()); _am = AssetsManagerEx::create(manifestPath, storagePath); _am->retain(); @@ -123,83 +126,84 @@ void AssetsManagerExLoaderScene::startDownloadCallback(Ref* sender) } else { - _amListener = cocos2d::extension::EventListenerAssetsManagerEx::create(_am, [this](EventAssetsManagerEx* event){ - static int failCount = 0; - switch (event->getEventCode()) - { - case EventAssetsManagerEx::EventCode::ERROR_NO_LOCAL_MANIFEST: - { - CCLOG("No local manifest file found, skip assets update."); - this->onLoadEnd(); - } - break; - case EventAssetsManagerEx::EventCode::UPDATE_PROGRESSION: - { - std::string assetId = event->getAssetId(); - float percent = event->getPercent(); - std::string str; - if (assetId == AssetsManagerEx::VERSION_ID) + _amListener = + cocos2d::extension::EventListenerAssetsManagerEx::create(_am, [this](EventAssetsManagerEx* event) { + static int failCount = 0; + switch (event->getEventCode()) { - str = StringUtils::format("Version file: %.2f", percent) + "%"; - } - else if (assetId == AssetsManagerEx::MANIFEST_ID) + case EventAssetsManagerEx::EventCode::ERROR_NO_LOCAL_MANIFEST: { - str = StringUtils::format("Manifest file: %.2f", percent) + "%"; + CCLOG("No local manifest file found, skip assets update."); + this->onLoadEnd(); } - else + break; + case EventAssetsManagerEx::EventCode::UPDATE_PROGRESSION: { - str = StringUtils::format("%.2f", percent) + "%"; - CCLOG("%.2f Percent", percent); + std::string assetId = event->getAssetId(); + float percent = event->getPercent(); + std::string str; + if (assetId == AssetsManagerEx::VERSION_ID) + { + str = StringUtils::format("Version file: %.2f", percent) + "%"; + } + else if (assetId == AssetsManagerEx::MANIFEST_ID) + { + str = StringUtils::format("Manifest file: %.2f", percent) + "%"; + } + else + { + str = StringUtils::format("%.2f", percent) + "%"; + CCLOG("%.2f Percent", percent); + } + if (this->_progress != nullptr) + this->_progress->setString(str); } - if (this->_progress != nullptr) - this->_progress->setString(str); - } - break; - case EventAssetsManagerEx::EventCode::ERROR_DOWNLOAD_MANIFEST: - case EventAssetsManagerEx::EventCode::ERROR_PARSE_MANIFEST: - { - CCLOG("Fail to download manifest file, update skipped."); - this->onLoadEnd(); - } - break; - case EventAssetsManagerEx::EventCode::ALREADY_UP_TO_DATE: - case EventAssetsManagerEx::EventCode::UPDATE_FINISHED: - { - CCLOG("Update finished. %s", event->getMessage().c_str()); - this->onLoadEnd(); - } - break; - case EventAssetsManagerEx::EventCode::UPDATE_FAILED: - { - CCLOG("Update failed. %s", event->getMessage().c_str()); - - failCount++; - if (failCount < 5) + break; + case EventAssetsManagerEx::EventCode::ERROR_DOWNLOAD_MANIFEST: + case EventAssetsManagerEx::EventCode::ERROR_PARSE_MANIFEST: { - _am->downloadFailedAssets(); + CCLOG("Fail to download manifest file, update skipped."); + this->onLoadEnd(); } - else + break; + case EventAssetsManagerEx::EventCode::ALREADY_UP_TO_DATE: + case EventAssetsManagerEx::EventCode::UPDATE_FINISHED: { - CCLOG("Reach maximum fail count, exit update process"); - failCount = 0; + CCLOG("Update finished. %s", event->getMessage().c_str()); this->onLoadEnd(); } - } - break; - case EventAssetsManagerEx::EventCode::ERROR_UPDATING: - { - CCLOG("Asset %s : %s", event->getAssetId().c_str(), event->getMessage().c_str()); - } - break; - case EventAssetsManagerEx::EventCode::ERROR_DECOMPRESS: - { - CCLOG("%s", event->getMessage().c_str()); - } - break; - default: break; - } - }); + case EventAssetsManagerEx::EventCode::UPDATE_FAILED: + { + CCLOG("Update failed. %s", event->getMessage().c_str()); + + failCount++; + if (failCount < 5) + { + _am->downloadFailedAssets(); + } + else + { + CCLOG("Reach maximum fail count, exit update process"); + failCount = 0; + this->onLoadEnd(); + } + } + break; + case EventAssetsManagerEx::EventCode::ERROR_UPDATING: + { + CCLOG("Asset %s : %s", event->getAssetId().c_str(), event->getMessage().c_str()); + } + break; + case EventAssetsManagerEx::EventCode::ERROR_DECOMPRESS: + { + CCLOG("%s", event->getMessage().c_str()); + } + break; + default: + break; + } + }); Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(_amListener, 1); _am->update(); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/AssetsManagerExTest/AssetsManagerExTest.h b/tests/cpp-tests/Classes/ExtensionsTest/AssetsManagerExTest/AssetsManagerExTest.h index b817ff9bf819..a3ba81dc8935 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/AssetsManagerExTest/AssetsManagerExTest.h +++ b/tests/cpp-tests/Classes/ExtensionsTest/AssetsManagerExTest/AssetsManagerExTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -36,14 +36,14 @@ class AssetsManagerExLoaderScene : public TestCase static AssetsManagerExLoaderScene* create(int testIndex); AssetsManagerExLoaderScene(int testIndex); - + void startDownloadCallback(cocos2d::Ref* sender); virtual std::string title() const override; virtual bool init() override; virtual void onExit() override; - + private: int _testIndex; cocos2d::Layer* _loadLayer; diff --git a/tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.cpp index 4e8460233be1..d30100ae5f11 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -29,6 +29,6 @@ ExtensionsTests::ExtensionsTests() { - addTest("AssetsManagerExTest", [](){ return new AssetsManagerExTests; }); - addTest("TableViewTest", [](){ return new TableViewTests; }); + addTest("AssetsManagerExTest", []() { return new AssetsManagerExTests; }); + addTest("TableViewTest", []() { return new TableViewTests; }); } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.h b/tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.h index 2a02f0627fe4..665686ae9092 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.h +++ b/tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 diff --git a/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp b/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp index badafef57f76..2cdde3fb2317 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -26,18 +26,18 @@ USING_NS_CC; -void CustomTableViewCell::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) +void CustomTableViewCell::draw(Renderer* renderer, const Mat4& transform, uint32_t flags) { - TableViewCell::draw(renderer, transform, flags); - // draw bounding box -// auto pos = getPosition(); -// auto size = Size(178, 200); -// Vec2 vertices[4]={ -// Vec2(pos.x+1, pos.y+1), -// Vec2(pos.x+size.width-1, pos.y+1), -// Vec2(pos.x+size.width-1, pos.y+size.height-1), -// Vec2(pos.x+1, pos.y+size.height-1), -// }; -// DrawPrimitives::drawColor4B(0, 0, 255, 255); -// DrawPrimitives::drawPoly(vertices, 4, true); + TableViewCell::draw(renderer, transform, flags); + // draw bounding box + // auto pos = getPosition(); + // auto size = Size(178, 200); + // Vec2 vertices[4]={ + // Vec2(pos.x+1, pos.y+1), + // Vec2(pos.x+size.width-1, pos.y+1), + // Vec2(pos.x+size.width-1, pos.y+size.height-1), + // Vec2(pos.x+1, pos.y+size.height-1), + // }; + // DrawPrimitives::drawColor4B(0, 0, 255, 255); + // DrawPrimitives::drawPoly(vertices, 4, true); } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.h b/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.h index 4fd2f0fe41c6..60ab09bad99c 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.h +++ b/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,8 +34,7 @@ class CustomTableViewCell : public cocos2d::extension::TableViewCell { public: - virtual void draw(cocos2d::Renderer *renderer, const cocos2d::Mat4 &transform, uint32_t flags) override; + virtual void draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, uint32_t flags) override; }; #endif /* __CUSTOMTABELVIEWCELL_H__ */ - diff --git a/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp b/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp index e496b7735915..249c4fa07f93 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -37,16 +37,16 @@ TableViewTests::TableViewTests() // on "init" you need to initialize your instance bool TableViewTest::init() { - if ( !TestCase::init() ) + if (!TestCase::init()) { return false; } - Size winSize = Director::getInstance()->getWinSize(); + Size winSize = Director::getInstance()->getWinSize(); TableView* tableView = TableView::create(this, Size(250.0f, 60.0f)); tableView->setDirection(ScrollView::Direction::HORIZONTAL); - tableView->setPosition(Vec2(20.0f,winSize.height/2-30)); + tableView->setPosition(Vec2(20.0f, winSize.height / 2 - 30)); tableView->setDelegate(this); this->addChild(tableView); tableView->reloadData(); @@ -57,14 +57,13 @@ bool TableViewTest::init() tableView->removeChild(testNode, true); CCAssert(nullptr == tableView->getChildByName("testNode"), "The added child has been removed!"); - - tableView = TableView::create(this, Size(60.0f, 250.0f)); - tableView->setDirection(ScrollView::Direction::VERTICAL); - tableView->setPosition(Vec2(winSize.width-150,winSize.height/2-120)); - tableView->setDelegate(this); - tableView->setVerticalFillOrder(TableView::VerticalFillOrder::TOP_DOWN); - this->addChild(tableView); - tableView->reloadData(); + tableView = TableView::create(this, Size(60.0f, 250.0f)); + tableView->setDirection(ScrollView::Direction::VERTICAL); + tableView->setPosition(Vec2(winSize.width - 150, winSize.height / 2 - 120)); + tableView->setDelegate(this); + tableView->setVerticalFillOrder(TableView::VerticalFillOrder::TOP_DOWN); + this->addChild(tableView); + tableView->reloadData(); return true; } @@ -74,19 +73,21 @@ void TableViewTest::tableCellTouched(TableView* table, TableViewCell* cell) CCLOG("cell touched at index: %d", static_cast(cell->getIdx())); } -Size TableViewTest::tableCellSizeForIndex(TableView *table, ssize_t idx) +Size TableViewTest::tableCellSizeForIndex(TableView* table, ssize_t idx) { - if (idx == 2) { + if (idx == 2) + { return Size(100, 100); } return Size(60, 60); } -TableViewCell* TableViewTest::tableCellAtIndex(TableView *table, ssize_t idx) +TableViewCell* TableViewTest::tableCellAtIndex(TableView* table, ssize_t idx) { - auto string = StringUtils::format("%d", static_cast(idx)); - TableViewCell *cell = table->dequeueCell(); - if (!cell) { + auto string = StringUtils::format("%d", static_cast(idx)); + TableViewCell* cell = table->dequeueCell(); + if (!cell) + { cell = new CustomTableViewCell(); cell->autorelease(); auto sprite = Sprite::create("Images/Icon.png"); @@ -96,7 +97,7 @@ TableViewCell* TableViewTest::tableCellAtIndex(TableView *table, ssize_t idx) auto label = Label::createWithSystemFont(string, "Helvetica", 20.0); label->setPosition(Vec2::ZERO); - label->setAnchorPoint(Vec2::ZERO); + label->setAnchorPoint(Vec2::ZERO); label->setTag(123); cell->addChild(label); } @@ -106,11 +107,10 @@ TableViewCell* TableViewTest::tableCellAtIndex(TableView *table, ssize_t idx) label->setString(string); } - return cell; } -ssize_t TableViewTest::numberOfCellsInTableView(TableView *table) +ssize_t TableViewTest::numberOfCellsInTableView(TableView* table) { return 20; } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h b/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h index f01df050ccc8..a439f924dbd5 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h +++ b/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -31,19 +31,23 @@ DEFINE_TEST_SUITE(TableViewTests); -class TableViewTest : public TestCase, public cocos2d::extension::TableViewDataSource, public cocos2d::extension::TableViewDelegate +class TableViewTest : public TestCase, + public cocos2d::extension::TableViewDataSource, + public cocos2d::extension::TableViewDelegate { public: CREATE_FUNC(TableViewTest); - virtual bool init() override; - - virtual void scrollViewDidScroll(cocos2d::extension::ScrollView* view)override {}; - virtual void scrollViewDidZoom(cocos2d::extension::ScrollView* view)override {} - virtual void tableCellTouched(cocos2d::extension::TableView* table, cocos2d::extension::TableViewCell* cell)override; - virtual cocos2d::Size tableCellSizeForIndex(cocos2d::extension::TableView *table, ssize_t idx)override; - virtual cocos2d::extension::TableViewCell* tableCellAtIndex(cocos2d::extension::TableView *table, ssize_t idx)override; - virtual ssize_t numberOfCellsInTableView(cocos2d::extension::TableView *table)override; + virtual bool init() override; + + virtual void scrollViewDidScroll(cocos2d::extension::ScrollView* view) override{}; + virtual void scrollViewDidZoom(cocos2d::extension::ScrollView* view) override {} + virtual void tableCellTouched(cocos2d::extension::TableView* table, + cocos2d::extension::TableViewCell* cell) override; + virtual cocos2d::Size tableCellSizeForIndex(cocos2d::extension::TableView* table, ssize_t idx) override; + virtual cocos2d::extension::TableViewCell* tableCellAtIndex(cocos2d::extension::TableView* table, + ssize_t idx) override; + virtual ssize_t numberOfCellsInTableView(cocos2d::extension::TableView* table) override; }; -#endif // __TABLEVIEWTESTSCENE_H__ +#endif // __TABLEVIEWTESTSCENE_H__ diff --git a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp index 831a1e2cdcad..4a8d50b81913 100644 --- a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp +++ b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -60,26 +60,27 @@ void TestResolutionDirectories::onEnter() std::string ret; sharedFileUtils->purgeCachedEntries(); - _defaultSearchPathArray = sharedFileUtils->getOriginalSearchPaths(); + _defaultSearchPathArray = sharedFileUtils->getOriginalSearchPaths(); std::vector searchPaths = _defaultSearchPathArray; - searchPaths.insert(searchPaths.begin(), "Misc"); + searchPaths.insert(searchPaths.begin(), "Misc"); sharedFileUtils->setSearchPaths(searchPaths); - _defaultResolutionsOrderArray = sharedFileUtils->getSearchResolutionsOrder(); + _defaultResolutionsOrderArray = sharedFileUtils->getSearchResolutionsOrder(); std::vector resolutionsOrder = _defaultResolutionsOrderArray; resolutionsOrder.insert(resolutionsOrder.begin(), "resources-ipadhd"); - resolutionsOrder.insert(resolutionsOrder.begin()+1, "resources-ipad"); - resolutionsOrder.insert(resolutionsOrder.begin()+2, "resources-widehd"); - resolutionsOrder.insert(resolutionsOrder.begin()+3, "resources-wide"); - resolutionsOrder.insert(resolutionsOrder.begin()+4, "resources-hd"); - resolutionsOrder.insert(resolutionsOrder.begin()+5, "resources-iphone"); + resolutionsOrder.insert(resolutionsOrder.begin() + 1, "resources-ipad"); + resolutionsOrder.insert(resolutionsOrder.begin() + 2, "resources-widehd"); + resolutionsOrder.insert(resolutionsOrder.begin() + 3, "resources-wide"); + resolutionsOrder.insert(resolutionsOrder.begin() + 4, "resources-hd"); + resolutionsOrder.insert(resolutionsOrder.begin() + 5, "resources-iphone"); sharedFileUtils->setSearchResolutionsOrder(resolutionsOrder); - for( int i=1; i<7; i++) { + for (int i = 1; i < 7; i++) + { auto filename = StringUtils::format("test%d.txt", i); - ret = sharedFileUtils->fullPathForFilename(filename); + ret = sharedFileUtils->fullPathForFilename(filename); log("%s -> %s", filename.c_str(), ret.c_str()); } } @@ -114,12 +115,12 @@ void TestSearchPath::onEnter() std::string ret; sharedFileUtils->purgeCachedEntries(); - _defaultSearchPathArray = sharedFileUtils->getOriginalSearchPaths(); + _defaultSearchPathArray = sharedFileUtils->getOriginalSearchPaths(); std::vector searchPaths = _defaultSearchPathArray; - std::string writablePath = sharedFileUtils->getWritablePath(); - std::string fileName = writablePath+"external.txt"; - char szBuf[100] = "Hello Cocos2d-x!"; - FILE* fp = fopen(fileName.c_str(), "wb"); + std::string writablePath = sharedFileUtils->getWritablePath(); + std::string fileName = writablePath + "external.txt"; + char szBuf[100] = "Hello Cocos2d-x!"; + FILE* fp = fopen(fileName.c_str(), "wb"); if (fp) { size_t ret = fwrite(szBuf, 1, strlen(szBuf), fp); @@ -130,19 +131,20 @@ void TestSearchPath::onEnter() } searchPaths.insert(searchPaths.begin(), writablePath); - searchPaths.insert(searchPaths.begin()+1, "Misc/searchpath1"); - searchPaths.insert(searchPaths.begin()+2, "Misc/searchpath2"); + searchPaths.insert(searchPaths.begin() + 1, "Misc/searchpath1"); + searchPaths.insert(searchPaths.begin() + 2, "Misc/searchpath2"); sharedFileUtils->setSearchPaths(searchPaths); - _defaultResolutionsOrderArray = sharedFileUtils->getSearchResolutionsOrder(); + _defaultResolutionsOrderArray = sharedFileUtils->getSearchResolutionsOrder(); std::vector resolutionsOrder = _defaultResolutionsOrderArray; resolutionsOrder.insert(resolutionsOrder.begin(), "resources-ipad"); sharedFileUtils->setSearchResolutionsOrder(resolutionsOrder); - for( int i=1; i<3; i++) { + for (int i = 1; i < 3; i++) + { auto filename = StringUtils::format("file%d.txt", i); - ret = sharedFileUtils->fullPathForFilename(filename); + ret = sharedFileUtils->fullPathForFilename(filename); log("%s -> %s", filename.c_str(), ret.c_str()); } @@ -155,7 +157,7 @@ void TestSearchPath::onEnter() if (fp) { char szReadBuf[100] = {0}; - size_t read = fread(szReadBuf, 1, strlen(szReadBuf), fp); + size_t read = fread(szReadBuf, 1, strlen(szReadBuf), fp); if (read > 0) log("The content of file from writable path: %s", szReadBuf); fclose(fp); @@ -188,7 +190,7 @@ void TestSearchPath::onEnter() void TestSearchPath::onExit() { - FileUtils *sharedFileUtils = FileUtils::getInstance(); + FileUtils* sharedFileUtils = FileUtils::getInstance(); // reset search path sharedFileUtils->setSearchPaths(_defaultSearchPathArray); @@ -225,13 +227,13 @@ void TestFilenameLookup::onEnter() this->addChild(sprite); auto s = Director::getInstance()->getWinSize(); - sprite->setPosition(s.width/2, s.height/2); + sprite->setPosition(s.width / 2, s.height / 2); } void TestFilenameLookup::onExit() { - FileUtils *sharedFileUtils = FileUtils::getInstance(); + FileUtils* sharedFileUtils = FileUtils::getInstance(); // reset filename lookup sharedFileUtils->setFilenameLookupDictionary(ValueMap()); @@ -249,7 +251,7 @@ std::string TestFilenameLookup::title() const void TestIsFileExist::onEnter() { FileUtilsDemo::onEnter(); - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto sharedFileUtils = FileUtils::getInstance(); Label* label = nullptr; @@ -257,20 +259,22 @@ void TestIsFileExist::onEnter() isExist = sharedFileUtils->isFileExist("Images/grossini.png"); - label = Label::createWithSystemFont(isExist ? "Images/grossini.png exists" : "Images/grossini.png doesn't exist", "", 20); - label->setPosition(s.width/2, s.height/3); + label = Label::createWithSystemFont(isExist ? "Images/grossini.png exists" : "Images/grossini.png doesn't exist", + "", 20); + label->setPosition(s.width / 2, s.height / 3); this->addChild(label); isExist = sharedFileUtils->isFileExist("Images/grossini.xcf"); - label = Label::createWithSystemFont(isExist ? "Images/grossini.xcf exists" : "Images/grossini.xcf doesn't exist", "", 20); - label->setPosition(s.width/2, s.height/3*2); + label = Label::createWithSystemFont(isExist ? "Images/grossini.xcf exists" : "Images/grossini.xcf doesn't exist", + "", 20); + label->setPosition(s.width / 2, s.height / 3 * 2); this->addChild(label); } void TestIsFileExist::onExit() { - FileUtils *sharedFileUtils = FileUtils::getInstance(); + FileUtils* sharedFileUtils = FileUtils::getInstance(); // reset filename lookup sharedFileUtils->setFilenameLookupDictionary(ValueMap()); @@ -293,30 +297,29 @@ std::string TestIsFileExist::subtitle() const void TestIsDirectoryExist::onEnter() { FileUtilsDemo::onEnter(); - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto util = FileUtils::getInstance(); - int x = s.width/2, y = s.height/3; + int x = s.width / 2, y = s.height / 3; Label* label = nullptr; std::string dir; - auto getMsg = [&dir](bool b)-> std::string - { + auto getMsg = [&dir](bool b) -> std::string { char msg[512]; - snprintf((char *)msg, 512, "%s for dir: \"%s\"", b ? "success" : "failed", dir.c_str()); + snprintf((char*)msg, 512, "%s for dir: \"%s\"", b ? "success" : "failed", dir.c_str()); return std::string(msg); }; - dir = "Images"; + dir = "Images"; label = Label::createWithSystemFont(getMsg(util->isDirectoryExist(dir)), "", 20); label->setPosition(x, y * 2); this->addChild(label); - dir = util->getWritablePath(); + dir = util->getWritablePath(); label = Label::createWithSystemFont(getMsg(util->isDirectoryExist(dir)), "", 20); label->setPosition(x, y * 1); this->addChild(label); - dir = util->getWritablePath(); + dir = util->getWritablePath(); label = Label::createWithSystemFont(getMsg(util->isDirectoryExist(dir)), "", 20); label->setPosition(x, y * 1); this->addChild(label); @@ -325,7 +328,7 @@ void TestIsDirectoryExist::onEnter() void TestIsDirectoryExist::onExit() { - FileUtils *sharedFileUtils = FileUtils::getInstance(); + FileUtils* sharedFileUtils = FileUtils::getInstance(); // reset filename lookup sharedFileUtils->purgeCachedEntries(); @@ -348,20 +351,19 @@ std::string TestIsDirectoryExist::subtitle() const void TestFileFuncs::onEnter() { FileUtilsDemo::onEnter(); - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto sharedFileUtils = FileUtils::getInstance(); - int x = s.width/2, - y = s.height/5; + int x = s.width / 2, y = s.height / 5; Label* label = nullptr; - std::string filename = "__test.test"; + std::string filename = "__test.test"; std::string filename2 = "__newtest.test"; - std::string filepath = sharedFileUtils->getWritablePath() + filename; - std::string content = "Test string content to put into created file"; + std::string filepath = sharedFileUtils->getWritablePath() + filename; + std::string content = "Test string content to put into created file"; std::string msg; - FILE *out = fopen(filepath.c_str(), "w"); + FILE* out = fopen(filepath.c_str(), "w"); fputs(content.c_str(), out); fclose(out); @@ -374,8 +376,8 @@ void TestFileFuncs::onEnter() // getFileSize Test int32_t size = sharedFileUtils->getFileSize(filepath); - msg = StringUtils::format("getFileSize: Test file size equals %d", size); - label = Label::createWithSystemFont(msg, "", 20); + msg = StringUtils::format("getFileSize: Test file size equals %d", size); + label = Label::createWithSystemFont(msg, "", 20); label->setPosition(x, y * 3); this->addChild(label); @@ -403,7 +405,8 @@ void TestFileFuncs::onEnter() } else { - label = Label::createWithSystemFont("renameFile: Failed to rename test file to '__newtest.test', further test skipped", "", 20); + label = Label::createWithSystemFont( + "renameFile: Failed to rename test file to '__newtest.test', further test skipped", "", 20); label->setPosition(x, y * 2); this->addChild(label); } @@ -431,15 +434,14 @@ std::string TestFileFuncs::subtitle() const void TestDirectoryFuncs::onEnter() { FileUtilsDemo::onEnter(); - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto sharedFileUtils = FileUtils::getInstance(); - int x = s.width/2, - y = s.height/4; + int x = s.width / 2, y = s.height / 4; Label* label = nullptr; - std::string dir = sharedFileUtils->getWritablePath() + "__test"; - std::string subDir = "dir1/dir2"; + std::string dir = sharedFileUtils->getWritablePath() + "__test"; + std::string subDir = "dir1/dir2"; std::string fullSubDir = dir + "/" + subDir; std::string msg; bool ok; @@ -448,7 +450,7 @@ void TestDirectoryFuncs::onEnter() ok = sharedFileUtils->createDirectory(dir); if (ok && sharedFileUtils->isDirectoryExist(dir)) { - msg = StringUtils::format("createDirectory: Directory '__test' created"); + msg = StringUtils::format("createDirectory: Directory '__test' created"); label = Label::createWithSystemFont(msg, "", 20); label->setPosition(x, y * 3); this->addChild(label); @@ -457,14 +459,14 @@ void TestDirectoryFuncs::onEnter() ok = sharedFileUtils->createDirectory(fullSubDir); if (ok && sharedFileUtils->isDirectoryExist(fullSubDir)) { - msg = StringUtils::format("createDirectory: Sub directories '%s' created", subDir.c_str()); + msg = StringUtils::format("createDirectory: Sub directories '%s' created", subDir.c_str()); label = Label::createWithSystemFont(msg, "", 20); label->setPosition(x, y * 2); this->addChild(label); } else { - msg = StringUtils::format("createDirectory: Failed to create sub directories '%s'", subDir.c_str()); + msg = StringUtils::format("createDirectory: Failed to create sub directories '%s'", subDir.c_str()); label = Label::createWithSystemFont(msg, "", 20); label->setPosition(x, y * 2); this->addChild(label); @@ -474,14 +476,14 @@ void TestDirectoryFuncs::onEnter() ok = sharedFileUtils->removeDirectory(dir); if (ok && !sharedFileUtils->isDirectoryExist(dir)) { - msg = StringUtils::format("removeDirectory: Directory '__test' removed"); + msg = StringUtils::format("removeDirectory: Directory '__test' removed"); label = Label::createWithSystemFont(msg, "", 20); label->setPosition(x, y); this->addChild(label); } else { - msg = StringUtils::format("removeDirectory: Failed to remove directory '__test'"); + msg = StringUtils::format("removeDirectory: Failed to remove directory '__test'"); label = Label::createWithSystemFont(msg, "", 20); label->setPosition(x, y); this->addChild(label); @@ -489,7 +491,7 @@ void TestDirectoryFuncs::onEnter() } else { - msg = StringUtils::format("createDirectory: Directory '__test' can not be created"); + msg = StringUtils::format("createDirectory: Directory '__test' can not be created"); label = Label::createWithSystemFont(msg, "", 20); label->setPosition(x, y * 2); this->addChild(label); @@ -521,11 +523,11 @@ void TestWriteString::onEnter() readResult->setPosition(winSize.width / 2, winSize.height / 3); std::string writablePath = FileUtils::getInstance()->getWritablePath(); - std::string fileName = "writeStringTest.txt"; + std::string fileName = "writeStringTest.txt"; // writeTest std::string writeDataStr = "the string data will be write into a file"; - std::string fullPath = writablePath + fileName; + std::string fullPath = writablePath + fileName; if (FileUtils::getInstance()->writeStringToFile(writeDataStr, fullPath.c_str())) { log("see the plist file at %s", fullPath.c_str()); @@ -557,42 +559,34 @@ std::string TestWriteString::subtitle() const return ""; } -class CustomBuffer : public ResizableBuffer {}; +class CustomBuffer : public ResizableBuffer +{}; -struct AlreadyExistsBuffer {}; +struct AlreadyExistsBuffer +{}; NS_CC_BEGIN -template<> -class ResizableBufferAdapter : public ResizableBuffer { +template <> +class ResizableBufferAdapter : public ResizableBuffer +{ public: - explicit ResizableBufferAdapter(AlreadyExistsBuffer* buffer) { - } - virtual void resize(size_t size) override { - - } - virtual void* buffer() const override { - return nullptr; - } + explicit ResizableBufferAdapter(AlreadyExistsBuffer* buffer) {} + virtual void resize(size_t size) override {} + virtual void* buffer() const override { return nullptr; } }; NS_CC_END -static void saveAsBinaryText(const std::string& filename, const std::vector& binary){ +static void saveAsBinaryText(std::string_view filename, const std::vector& binary) +{ auto fs = FileUtils::getInstance(); std::string text(binary.begin(), binary.end()); fs->writeStringToFile(text, filename); } static const std::string FileErrors[] = { - "OK", - "NotExists", - "OpenFailed", - "ReadFailed", - "NotInitialized", - "TooLarge", - "ObtainSizeFailed", + "OK", "NotExists", "OpenFailed", "ReadFailed", "NotInitialized", "TooLarge", "ObtainSizeFailed", }; - void TestGetContents::onEnter() { FileUtilsDemo::onEnter(); @@ -612,26 +606,25 @@ void TestGetContents::onEnter() this->addChild(readResult); readResult->setPosition(winSize.width / 2, winSize.height / 2); - std::vector binary = {'\r','\n','\r','\n','\0','\0','\r','\n'}; - _generatedFile = fs->getWritablePath() + "file-with-zeros-and-crlf"; + std::vector binary = {'\r', '\n', '\r', '\n', '\0', '\0', '\r', '\n'}; + _generatedFile = fs->getWritablePath() + "file-with-zeros-and-crlf"; saveAsBinaryText(_generatedFile, binary); - auto runTests = [&]() { // Test read string in binary mode std::string bs; fs->getContents(_generatedFile, &bs); - if ( bs.size() != binary.size() || !std::equal( bs.begin(), bs.end(), binary.begin() ) ) + if (bs.size() != binary.size() || !std::equal(bs.begin(), bs.end(), binary.begin())) return std::string("failed: read as binary string"); // Text read string in text mode std::string ts = fs->getStringFromFile(_generatedFile); - if (strcmp(ts.c_str(), "\r\n\r\n")!=0) + if (strcmp(ts.c_str(), "\r\n\r\n") != 0) return std::string("failed: read as zero terminated string"); - std::string files[] = {_generatedFile, "background.wav", "fileLookup.plist"}; - for (auto& file : files) { + for (auto& file : files) + { std::string sbuf; auto serr = fs->getContents(file, &sbuf); @@ -695,12 +688,12 @@ void TestWriteData::onEnter() readResult->setPosition(winSize.width / 2, winSize.height / 3); std::string writablePath = FileUtils::getInstance()->getWritablePath(); - std::string fileName = "writeDataTest.txt"; + std::string fileName = "writeDataTest.txt"; // writeTest std::string writeDataStr = "the binary data will be write into a file"; Data writeData; - writeData.copy((unsigned char *)writeDataStr.c_str(), writeDataStr.size()); + writeData.copy((unsigned char*)writeDataStr.c_str(), writeDataStr.size()); std::string fullPath = writablePath + fileName; if (FileUtils::getInstance()->writeDataToFile(writeData, fullPath.c_str())) { @@ -715,8 +708,8 @@ void TestWriteData::onEnter() // readTest unsigned char* buffer = nullptr; - Data readData = FileUtils::getInstance()->getDataFromFile(fullPath); - buffer = (unsigned char*)malloc(sizeof(unsigned char) * (readData.getSize() + 1)); + Data readData = FileUtils::getInstance()->getDataFromFile(fullPath); + buffer = (unsigned char*)malloc(sizeof(unsigned char) * (readData.getSize() + 1)); memcpy(buffer, readData.getBytes(), readData.getSize()); buffer[readData.getSize()] = '\0'; std::string readDataStr((const char*)buffer); @@ -760,7 +753,7 @@ void TestWriteValueMap::onEnter() mapInValueMap["string1"] = "string in dictInMap key 0"; mapInValueMap["string2"] = "string in dictInMap key 1"; mapInValueMap["none"].getType(); - + valueMap["data0"] = Value(mapInValueMap); valueMap["data1"] = Value("string in array"); @@ -770,26 +763,25 @@ void TestWriteValueMap::onEnter() arrayInMap.push_back(Value("string 1 in arrayInMap")); valueMap["data2"] = arrayInMap; - //add boolean to the plist + // add boolean to the plist auto booleanObject = Value(true); - valueMap["data3"] = booleanObject; + valueMap["data3"] = booleanObject; - //add integer to the plist - auto intObject = Value(1024); + // add integer to the plist + auto intObject = Value(1024); valueMap["data4"] = intObject; - //add float to the plist - auto floatObject = Value(1024.1024f); + // add float to the plist + auto floatObject = Value(1024.1024f); valueMap["data5"] = floatObject; - //add double to the plist + // add double to the plist auto doubleObject = Value(1024.123); valueMap["data6"] = doubleObject; - // end with / std::string writablePath = FileUtils::getInstance()->getWritablePath(); - std::string fullPath = writablePath + "testWriteValueMap.plist"; + std::string fullPath = writablePath + "testWriteValueMap.plist"; if (FileUtils::getInstance()->writeValueMapToFile(valueMap, fullPath.c_str())) { log("see the plist file at %s", fullPath.c_str()); @@ -801,7 +793,7 @@ void TestWriteValueMap::onEnter() writeResult->setString("write failed"); } - ValueMap readValueMap = FileUtils::getInstance()->getValueMapFromFile(fullPath.c_str()); + ValueMap readValueMap = FileUtils::getInstance()->getValueMapFromFile(fullPath.c_str()); std::string readDataStr = "read data:\n"; // read value map data ValueMap readMapInMap = readValueMap["data0"].asValueMap(); @@ -873,26 +865,25 @@ void TestWriteValueVector::onEnter() arrayInArray.push_back(Value("string 1 in arrayInArray")); array.push_back(Value(arrayInArray)); - //add boolean to the plist + // add boolean to the plist auto booleanObject = Value(true); array.push_back(booleanObject); - //add integer to the plist + // add integer to the plist auto intObject = Value(1024); array.push_back(intObject); - //add float to the plist + // add float to the plist auto floatObject = Value(1024.1024f); array.push_back(floatObject); - //add double to the plist + // add double to the plist auto doubleObject = Value(1024.123); array.push_back(doubleObject); - // end with / std::string writablePath = FileUtils::getInstance()->getWritablePath(); - std::string fullPath = writablePath + "testWriteValueVector.plist"; + std::string fullPath = writablePath + "testWriteValueVector.plist"; if (FileUtils::getInstance()->writeValueVectorToFile(array, fullPath.c_str())) { log("see the plist file at %s", fullPath.c_str()); @@ -904,7 +895,7 @@ void TestWriteValueVector::onEnter() writeResult->setString("write failed"); } - ValueVector readArray = FileUtils::getInstance()->getValueVectorFromFile(fullPath.c_str()); + ValueVector readArray = FileUtils::getInstance()->getValueVectorFromFile(fullPath.c_str()); std::string readDataStr = "read data:\n"; // read value map data ValueMap readMapInArray = readArray.at(0).asValueMap(); @@ -954,21 +945,19 @@ std::string TestWriteValueVector::subtitle() const void TestUnicodePath::onEnter() { FileUtilsDemo::onEnter(); - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto util = FileUtils::getInstance(); - int x = s.width/2, - y = s.height/5; + int x = s.width / 2, y = s.height / 5; Label* label = nullptr; - std::string dir = "中文路径/"; + std::string dir = "中文路径/"; std::string filename = "测试文件.test"; std::string act; - auto getMsg = [&act](bool b, const std::string& path)-> std::string - { + auto getMsg = [&act](bool b, std::string_view path) -> std::string { char msg[512]; - snprintf((char *)msg, 512, "%s for %s path: \"%s\"", b ? "success" : "failed", act.c_str(), path.c_str()); + snprintf((char*)msg, 512, "%s for %s path: \"%s\"", b ? "success" : "failed", act.c_str(), path.data()); return std::string(msg); }; @@ -979,9 +968,9 @@ void TestUnicodePath::onEnter() util->createDirectory(dirPath); } - act = "create"; + act = "create"; bool isExist = util->isDirectoryExist(dirPath); - label = Label::createWithSystemFont(getMsg(isExist, dirPath), "", 12, Size(s.width, 0)); + label = Label::createWithSystemFont(getMsg(isExist, dirPath), "", 12, Size(s.width, 0)); label->setPosition(x, y * 4); this->addChild(label); @@ -989,16 +978,16 @@ void TestUnicodePath::onEnter() { // Check whether unicode file should be create or not std::string filePath = dirPath + filename; - if (! util->isFileExist(filePath)) + if (!util->isFileExist(filePath)) { std::string writeDataStr = " 测试字符串."; Data writeData; - writeData.copy((unsigned char *)writeDataStr.c_str(), writeDataStr.size()); + writeData.copy((unsigned char*)writeDataStr.c_str(), writeDataStr.size()); util->writeDataToFile(writeData, filePath); } isExist = util->isFileExist(filePath); - label = Label::createWithSystemFont(getMsg(isExist, filePath), "", 12, Size(s.width, 0)); + label = Label::createWithSystemFont(getMsg(isExist, filePath), "", 12, Size(s.width, 0)); label->setPosition(x, y * 3); this->addChild(label); @@ -1007,8 +996,8 @@ void TestUnicodePath::onEnter() { // read file content and log it unsigned char* buffer = nullptr; - Data readData = util->getDataFromFile(filePath); - buffer = (unsigned char*)malloc(sizeof(unsigned char) * (readData.getSize() + 1)); + Data readData = util->getDataFromFile(filePath); + buffer = (unsigned char*)malloc(sizeof(unsigned char) * (readData.getSize() + 1)); memcpy(buffer, readData.getBytes(), readData.getSize()); buffer[readData.getSize()] = '\0'; // vc can't treat unicode string correctly, don't use unicode string in code @@ -1031,7 +1020,7 @@ void TestUnicodePath::onEnter() void TestUnicodePath::onExit() { - FileUtils *sharedFileUtils = FileUtils::getInstance(); + FileUtils* sharedFileUtils = FileUtils::getInstance(); sharedFileUtils->purgeCachedEntries(); sharedFileUtils->setFilenameLookupDictionary(ValueMap()); FileUtilsDemo::onExit(); @@ -1052,30 +1041,33 @@ std::string TestUnicodePath::subtitle() const void TestIsFileExistAsync::onEnter() { FileUtilsDemo::onEnter(); - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto sharedFileUtils = FileUtils::getInstance(); - + sharedFileUtils->isFileExist("Images/grossini.png", [=](bool isExist) { - CCASSERT(std::this_thread::get_id() == Director::getInstance()->getCocos2dThreadId(), "Callback should be on cocos thread"); - auto label = Label::createWithSystemFont(isExist ? "Images/grossini.png exists" : "Images/grossini.png doesn't exist", "", 20); - label->setPosition(s.width/2, s.height/3); + CCASSERT(std::this_thread::get_id() == Director::getInstance()->getCocos2dThreadId(), + "Callback should be on cocos thread"); + auto label = Label::createWithSystemFont( + isExist ? "Images/grossini.png exists" : "Images/grossini.png doesn't exist", "", 20); + label->setPosition(s.width / 2, s.height / 3); this->addChild(label); - + isExist = sharedFileUtils->isFileExist("Images/grossini.xcf"); - label = Label::createWithSystemFont(isExist ? "Images/grossini.xcf exists" : "Images/grossini.xcf doesn't exist", "", 20); - label->setPosition(s.width/2, s.height/3*2); + label = Label::createWithSystemFont( + isExist ? "Images/grossini.xcf exists" : "Images/grossini.xcf doesn't exist", "", 20); + label->setPosition(s.width / 2, s.height / 3 * 2); this->addChild(label); }); } void TestIsFileExistAsync::onExit() { - - FileUtils *sharedFileUtils = FileUtils::getInstance(); - + + FileUtils* sharedFileUtils = FileUtils::getInstance(); + // reset filename lookup sharedFileUtils->setFilenameLookupDictionary(ValueMap()); - + FileUtilsDemo::onExit(); } @@ -1092,18 +1084,17 @@ std::string TestIsFileExistAsync::subtitle() const void TestIsDirectoryExistAsync::onEnter() { FileUtilsDemo::onEnter(); - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto util = FileUtils::getInstance(); - int x = s.width/2, y = s.height/3; - + int x = s.width / 2, y = s.height / 3; + std::string dir; - auto getMsg = [](bool b, const std::string& dir)-> std::string - { + auto getMsg = [](bool b, std::string_view dir) -> std::string { char msg[512]; - snprintf((char *)msg, 512, "%s for dir: \"%s\"", b ? "success" : "failed", dir.c_str()); + snprintf((char*)msg, 512, "%s for dir: \"%s\"", b ? "success" : "failed", dir.data()); return std::string(msg); }; - + dir = util->getWritablePath(); util->isDirectoryExist(dir, [=](bool exists) { CCAssert(exists, "Writable path should exist"); @@ -1115,12 +1106,12 @@ void TestIsDirectoryExistAsync::onEnter() void TestIsDirectoryExistAsync::onExit() { - - FileUtils *sharedFileUtils = FileUtils::getInstance(); - + + FileUtils* sharedFileUtils = FileUtils::getInstance(); + // reset filename lookup sharedFileUtils->purgeCachedEntries(); - + FileUtilsDemo::onExit(); } @@ -1137,41 +1128,39 @@ std::string TestIsDirectoryExistAsync::subtitle() const void TestFileFuncsAsync::onEnter() { FileUtilsDemo::onEnter(); - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); auto sharedFileUtils = FileUtils::getInstance(); - - int x = s.width/2, - y = s.height/5; - - std::string filename = "__test.test"; + + int x = s.width / 2, y = s.height / 5; + + std::string filename = "__test.test"; std::string filename2 = "__newtest.test"; - std::string filepath = sharedFileUtils->getWritablePath() + filename; - std::string content = "Test string content to put into created file"; + std::string filepath = sharedFileUtils->getWritablePath() + filename; + std::string content = "Test string content to put into created file"; std::string msg; - - FILE *out = fopen(filepath.c_str(), "w"); + + FILE* out = fopen(filepath.c_str(), "w"); fputs(content.c_str(), out); fclose(out); - - + sharedFileUtils->isFileExist(filepath, [=](bool exists) { CCASSERT(exists, "File could not be found"); auto label = Label::createWithSystemFont("Test file '__test.test' created", "", 20); label->setPosition(x, y * 4); this->addChild(label); - + sharedFileUtils->getFileSize(filepath, [=](int32_t size) { - auto msg = StringUtils::format("getFileSize: Test file size equals %d", size); + auto msg = StringUtils::format("getFileSize: Test file size equals %d", size); auto label = Label::createWithSystemFont(msg, "", 20); label->setPosition(x, y * 3); this->addChild(label); - - sharedFileUtils->renameFile(sharedFileUtils->getWritablePath(), filename, filename2, [=] (bool success) { + + sharedFileUtils->renameFile(sharedFileUtils->getWritablePath(), filename, filename2, [=](bool success) { CCASSERT(success, "Was not able to properly rename file"); auto label = Label::createWithSystemFont("renameFile: Test file renamed to '__newtest.test'", "", 20); label->setPosition(x, y * 2); this->addChild(label); - + sharedFileUtils->removeFile(sharedFileUtils->getWritablePath() + filename2, [=](bool success) { CCASSERT(success, "Was not able to remove file"); auto label = Label::createWithSystemFont("removeFile: Test file removed", "", 20); @@ -1180,7 +1169,6 @@ void TestFileFuncsAsync::onEnter() }); }); }); - }); } @@ -1197,32 +1185,33 @@ std::string TestFileFuncsAsync::subtitle() const void TestWriteStringAsync::onEnter() { FileUtilsDemo::onEnter(); - + auto winSize = Director::getInstance()->getWinSize(); - + auto writeResult = Label::createWithTTF("show writeResult", "fonts/Thonburi.ttf", 18); this->addChild(writeResult); writeResult->setPosition(winSize.width / 2, winSize.height * 3 / 4); - + auto readResult = Label::createWithTTF("show readResult", "fonts/Thonburi.ttf", 18); this->addChild(readResult); readResult->setPosition(winSize.width / 2, winSize.height / 3); - + std::string writablePath = FileUtils::getInstance()->getWritablePath(); - std::string fileName = "writeStringTest.txt"; - + std::string fileName = "writeStringTest.txt"; + // writeTest std::string writeDataStr = "the string data will be write into a file"; - std::string fullPath = writablePath + fileName; - - FileUtils::getInstance()->writeStringToFile(writeDataStr, fullPath, [=](bool success) - { + std::string fullPath = writablePath + fileName; + + FileUtils::getInstance()->writeStringToFile(writeDataStr, fullPath, [=](bool success) { CCASSERT(success, "Write String to data failed"); writeResult->setString("write success:" + writeDataStr); - FileUtils::getInstance()->getStringFromFile(fullPath, [=](const std::string& value) { + FileUtils::getInstance()->getStringFromFile(fullPath, [=](std::string_view value) { CCASSERT(!value.empty(), "String should be readable"); - readResult->setString("read success: " + value); + + std::string strVal = "read success: "; + readResult->setString(strVal.append(value)); }); }); } @@ -1257,25 +1246,24 @@ void TestWriteDataAsync::onEnter() readResult->setPosition(winSize.width / 2, winSize.height / 3); std::string writablePath = FileUtils::getInstance()->getWritablePath(); - std::string fileName = "writeDataTest.txt"; + std::string fileName = "writeDataTest.txt"; // writeTest std::string writeDataStr = "the binary data will be write into a file"; Data writeData; - writeData.copy((unsigned char *)writeDataStr.c_str(), writeDataStr.size()); + writeData.copy((unsigned char*)writeDataStr.c_str(), writeDataStr.size()); std::string fullPath = writablePath + fileName; - FileUtils::getInstance()->writeDataToFile(writeData, fullPath, [=](bool success) { if (success) { writeResult->setString("Write result success"); - } + } else { writeResult->setString("Write result failure"); } - + FileUtils::getInstance()->getDataFromFile(fullPath, [=](const Data& readData) { auto buffer = (unsigned char*)malloc(sizeof(unsigned char) * (readData.getSize() + 1)); memcpy(buffer, readData.getBytes(), readData.getSize()); @@ -1318,24 +1306,23 @@ void TestListFiles::onEnter() cntLabel->setPosition(winSize.width / 2, winSize.height / 3); // writeTest std::vector listFonts = FileUtils::getInstance()->listFiles("fonts"); - auto defaultPath = FileUtils::getInstance()->getDefaultResourceRootPath(); - std::vector list = FileUtils::getInstance()->listFiles (defaultPath); + auto defaultPath = FileUtils::getInstance()->getDefaultResourceRootPath(); + std::vector list = FileUtils::getInstance()->listFiles(defaultPath); - char cntBuffer[200] = { 0 }; - snprintf(cntBuffer, 200, "'fonts/' %zu, $defaultResourceRootPath %zu",listFonts.size(), list.size()); + char cntBuffer[200] = {0}; + snprintf(cntBuffer, 200, "'fonts/' %zu, $defaultResourceRootPath %zu", listFonts.size(), list.size()); - for(int i=0;isetString(cntBuffer); - } void TestListFiles::onExit() @@ -1353,8 +1340,6 @@ std::string TestListFiles::subtitle() const return ""; } - - void TestIsFileExistRejectFolder::onEnter() { FileUtilsDemo::onEnter(); @@ -1368,14 +1353,13 @@ void TestIsFileExistRejectFolder::onEnter() auto cntLabel = Label::createWithTTF("waiting...", "fonts/Thonburi.ttf", 18); this->addChild(cntLabel); cntLabel->setPosition(winSize.width / 2, winSize.height / 3); - - auto exists = FileUtils::getInstance()->isFileExist("NavMesh/maps"); + + auto exists = FileUtils::getInstance()->isFileExist("NavMesh/maps"); auto isDirectory = FileUtils::getInstance()->isDirectoryExist("NavMesh/maps"); - char cntBuffer[200] = { 0 }; - snprintf(cntBuffer, 200, "isDir: %s, isFile: %s", isDirectory ? "true": "false" , exists ? "true" : "false"); + char cntBuffer[200] = {0}; + snprintf(cntBuffer, 200, "isDir: %s, isFile: %s", isDirectory ? "true" : "false", exists ? "true" : "false"); cntLabel->setString(cntBuffer); - } void TestIsFileExistRejectFolder::onExit() diff --git a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.h b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.h index ead129feaca9..4187f38aedbd 100644 --- a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.h +++ b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,7 +27,6 @@ #include "../BaseTest.h" - DEFINE_TEST_SUITE(FileUtilsTests); class FileUtilsDemo : public TestCase @@ -44,6 +43,7 @@ class TestResolutionDirectories : public FileUtilsDemo virtual void onExit() override; virtual std::string title() const override; virtual std::string subtitle() const override; + private: std::vector _defaultSearchPathArray; std::vector _defaultResolutionsOrderArray; @@ -58,6 +58,7 @@ class TestSearchPath : public FileUtilsDemo virtual void onExit() override; virtual std::string title() const override; virtual std::string subtitle() const override; + private: std::vector _defaultSearchPathArray; std::vector _defaultResolutionsOrderArray; @@ -135,6 +136,7 @@ class TestGetContents : public FileUtilsDemo virtual void onExit() override; virtual std::string title() const override; virtual std::string subtitle() const override; + private: std::string _generatedFile; }; @@ -187,7 +189,7 @@ class TestIsFileExistAsync : public FileUtilsDemo { public: CREATE_FUNC(TestIsFileExistAsync); - + virtual void onEnter() override; virtual void onExit() override; virtual std::string title() const override; @@ -198,7 +200,7 @@ class TestIsDirectoryExistAsync : public FileUtilsDemo { public: CREATE_FUNC(TestIsDirectoryExistAsync); - + virtual void onEnter() override; virtual void onExit() override; virtual std::string title() const override; @@ -209,7 +211,7 @@ class TestFileFuncsAsync : public FileUtilsDemo { public: CREATE_FUNC(TestFileFuncsAsync); - + virtual void onEnter() override; virtual std::string title() const override; virtual std::string subtitle() const override; @@ -219,7 +221,7 @@ class TestDirectoryFuncsAsync : public FileUtilsDemo { public: CREATE_FUNC(TestDirectoryFuncsAsync); - + virtual void onEnter() override; virtual std::string title() const override; virtual std::string subtitle() const override; @@ -229,7 +231,7 @@ class TestWriteStringAsync : public FileUtilsDemo { public: CREATE_FUNC(TestWriteStringAsync); - + virtual void onEnter() override; virtual void onExit() override; virtual std::string title() const override; @@ -240,7 +242,7 @@ class TestWriteDataAsync : public FileUtilsDemo { public: CREATE_FUNC(TestWriteDataAsync); - + virtual void onEnter() override; virtual void onExit() override; virtual std::string title() const override; diff --git a/tests/cpp-tests/Classes/FontTest/FontTest.cpp b/tests/cpp-tests/Classes/FontTest/FontTest.cpp index 6e131ce06f21..f47dd7a77568 100644 --- a/tests/cpp-tests/Classes/FontTest/FontTest.cpp +++ b/tests/cpp-tests/Classes/FontTest/FontTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -29,62 +29,65 @@ USING_NS_CC; -enum { +enum +{ kTagLabel1, kTagLabel2, kTagLabel3, kTagLabel4, - + kTagColor1, kTagColor2, kTagColor3, }; -//you don't need any ifdef anymore -static std::string fontList[] = -{ - "fonts/A Damn Mess.ttf", - "fonts/Abberancy.ttf", - "fonts/Abduction.ttf", - "fonts/Paint Boy.ttf", - "fonts/Schwarzwald.ttf", - "fonts/Scissor Cuts.ttf", +// you don't need any ifdef anymore +static std::string fontList[] = { + "fonts/A Damn Mess.ttf", "fonts/Abberancy.ttf", "fonts/Abduction.ttf", + "fonts/Paint Boy.ttf", "fonts/Schwarzwald.ttf", "fonts/Scissor Cuts.ttf", }; -static int vAlignIdx = 0; -static TextVAlignment verticalAlignment[] = -{ +static int vAlignIdx = 0; +static TextVAlignment verticalAlignment[] = { TextVAlignment::TOP, TextVAlignment::CENTER, TextVAlignment::BOTTOM, }; - FontTests::FontTests() { for (auto& fontFile : fontList) { - addTestCase("FontTests", [&](){vAlignIdx = 0; return FontTest::create(fontFile); }); + addTestCase("FontTests", [&]() { + vAlignIdx = 0; + return FontTest::create(fontFile); + }); } - + for (auto& fontFile : fontList) { - addTestCase("FontTests", [&](){ vAlignIdx = 1; return FontTest::create(fontFile); }); + addTestCase("FontTests", [&]() { + vAlignIdx = 1; + return FontTest::create(fontFile); + }); } - + for (auto& fontFile : fontList) { - addTestCase("FontTests", [&](){vAlignIdx = 2; return FontTest::create(fontFile); }); + addTestCase("FontTests", [&]() { + vAlignIdx = 2; + return FontTest::create(fontFile); + }); } - ADD_TEST_CASE(FontNoReplacementTest); - ADD_TEST_CASE(FontReplacementTest); + ADD_TEST_CASE(FontNoReplacementTest); + ADD_TEST_CASE(FontReplacementTest); } -void FontTest::showFont(const std::string& fontFile) +void FontTest::showFont(std::string_view fontFile) { auto s = Director::getInstance()->getWinSize(); - auto blockSize = Size(s.width/3, 200); + auto blockSize = Size(s.width / 3, 200); float fontSize = 26; removeChildByTag(kTagLabel1, true); @@ -95,37 +98,36 @@ void FontTest::showFont(const std::string& fontFile) removeChildByTag(kTagColor2, true); removeChildByTag(kTagColor3, true); - auto top = Label::createWithSystemFont(fontFile, fontFile, 24); - auto left = Label::createWithSystemFont("alignment left", fontFile, fontSize, - blockSize, TextHAlignment::LEFT, verticalAlignment[vAlignIdx]); - auto center = Label::createWithSystemFont("alignment center", fontFile, fontSize, - blockSize, TextHAlignment::CENTER, verticalAlignment[vAlignIdx]); - auto right = Label::createWithSystemFont("alignment right", fontFile, fontSize, - blockSize, TextHAlignment::RIGHT, verticalAlignment[vAlignIdx]); + auto top = Label::createWithSystemFont(fontFile, fontFile, 24); + auto left = Label::createWithSystemFont("alignment left", fontFile, fontSize, blockSize, TextHAlignment::LEFT, + verticalAlignment[vAlignIdx]); + auto center = Label::createWithSystemFont("alignment center", fontFile, fontSize, blockSize, TextHAlignment::CENTER, + verticalAlignment[vAlignIdx]); + auto right = Label::createWithSystemFont("alignment right", fontFile, fontSize, blockSize, TextHAlignment::RIGHT, + verticalAlignment[vAlignIdx]); - auto leftColor = LayerColor::create(Color4B(100, 100, 100, 255), blockSize.width, blockSize.height); + auto leftColor = LayerColor::create(Color4B(100, 100, 100, 255), blockSize.width, blockSize.height); auto centerColor = LayerColor::create(Color4B(200, 100, 100, 255), blockSize.width, blockSize.height); - auto rightColor = LayerColor::create(Color4B(100, 100, 200, 255), blockSize.width, blockSize.height); + auto rightColor = LayerColor::create(Color4B(100, 100, 200, 255), blockSize.width, blockSize.height); leftColor->setIgnoreAnchorPointForPosition(false); centerColor->setIgnoreAnchorPointForPosition(false); rightColor->setIgnoreAnchorPointForPosition(false); - top->setAnchorPoint(Vec2(0.5, 1)); - left->setAnchorPoint(Vec2(0,0.5)); - leftColor->setAnchorPoint(Vec2(0,0.5)); - center->setAnchorPoint(Vec2(0,0.5)); - centerColor->setAnchorPoint(Vec2(0,0.5)); - right->setAnchorPoint(Vec2(0,0.5)); - rightColor->setAnchorPoint(Vec2(0,0.5)); - - top->setPosition(s.width/2,s.height-20); - left->setPosition(0,s.height/2); + left->setAnchorPoint(Vec2(0, 0.5)); + leftColor->setAnchorPoint(Vec2(0, 0.5)); + center->setAnchorPoint(Vec2(0, 0.5)); + centerColor->setAnchorPoint(Vec2(0, 0.5)); + right->setAnchorPoint(Vec2(0, 0.5)); + rightColor->setAnchorPoint(Vec2(0, 0.5)); + + top->setPosition(s.width / 2, s.height - 20); + left->setPosition(0, s.height / 2); leftColor->setPosition(left->getPosition()); - center->setPosition(blockSize.width, s.height/2); + center->setPosition(blockSize.width, s.height / 2); centerColor->setPosition(center->getPosition()); - right->setPosition(blockSize.width*2, s.height/2); + right->setPosition(blockSize.width * 2, s.height / 2); rightColor->setPosition(right->getPosition()); this->addChild(leftColor, -1, kTagColor1); @@ -144,138 +146,136 @@ std::string FontTest::title() const FontNoReplacementTest* FontNoReplacementTest::create() { - auto ret = new FontNoReplacementTest; - if (ret->init()) - { - ret->autorelease(); - } - else - { - delete ret; - ret = nullptr; - } - - return ret; + auto ret = new FontNoReplacementTest; + if (ret->init()) + { + ret->autorelease(); + } + else + { + delete ret; + ret = nullptr; + } + + return ret; } FontNoReplacementTest::FontNoReplacementTest() { - _replace = false; + _replace = false; } FontNoReplacementTest::~FontNoReplacementTest() { - // need to clear the caches since we change the lookup dictionary after the application init. - FontAtlasCache::unloadFontAtlasTTF("fonts/A Damn Mess.ttf"); - FontFreeType::releaseFont("fonts/A Damn Mess.ttf"); - FontAtlasCache::unloadFontAtlasTTF("fonts/Abberancy.ttf"); - FontFreeType::releaseFont("fonts/Abberancy.ttf"); - FontAtlasCache::unloadFontAtlasTTF("fonts/Abduction.ttf"); - FontFreeType::releaseFont("fonts/Abduction.ttf"); - FontAtlasCache::unloadFontAtlasTTF("fonts/Schwarzwald.ttf"); - FontFreeType::releaseFont("fonts/Schwarzwald.ttf"); - FileUtils::getInstance()->setFilenameLookupDictionary(ValueMap()); + // need to clear the caches since we change the lookup dictionary after the application init. + FontAtlasCache::unloadFontAtlasTTF("fonts/A Damn Mess.ttf"); + FontFreeType::releaseFont("fonts/A Damn Mess.ttf"); + FontAtlasCache::unloadFontAtlasTTF("fonts/Abberancy.ttf"); + FontFreeType::releaseFont("fonts/Abberancy.ttf"); + FontAtlasCache::unloadFontAtlasTTF("fonts/Abduction.ttf"); + FontFreeType::releaseFont("fonts/Abduction.ttf"); + FontAtlasCache::unloadFontAtlasTTF("fonts/Schwarzwald.ttf"); + FontFreeType::releaseFont("fonts/Schwarzwald.ttf"); + FileUtils::getInstance()->setFilenameLookupDictionary(ValueMap()); } void FontNoReplacementTest::onEnter() { - TestCase::onEnter(); - - std::string suffix; - if (_replace) - { - ValueMap dict{ - { "fonts/A Damn Mess.ttf", Value("fonts/arial.ttf") }, - { "fonts/Abberancy.ttf", Value("fonts/arial.ttf") }, - { "fonts/Abduction.ttf", Value("fonts/arial.ttf") }, - { "fonts/Schwarzwald.ttf", Value("fonts/arial.ttf") } - }; - - FileUtils::getInstance()->setFilenameLookupDictionary(dict); - suffix = " replaced by arial.ttf"; - } - - auto s = Director::getInstance()->getWinSize(); - - auto blockSize = Size(s.width / 3, 200); - float fontSize = 26; - - removeChildByTag(kTagLabel1, true); - removeChildByTag(kTagLabel2, true); - removeChildByTag(kTagLabel3, true); - removeChildByTag(kTagLabel4, true); - removeChildByTag(kTagColor1, true); - removeChildByTag(kTagColor2, true); - removeChildByTag(kTagColor3, true); - - auto top = Label::createWithTTF("fonts/A Damn Mess.ttf" + suffix, "fonts/A Damn Mess.ttf", 24); - auto left = Label::createWithTTF("fonts/Abberancy.ttf" + suffix, "fonts/Abberancy.ttf", fontSize, - blockSize, TextHAlignment::LEFT, verticalAlignment[0]); - auto center = Label::createWithTTF("fonts/Abduction.ttf" + suffix, "fonts/Abduction.ttf", fontSize, - blockSize, TextHAlignment::CENTER, verticalAlignment[0]); - auto right = Label::createWithTTF("fonts/Schwarzwald.ttf" + suffix, "fonts/Schwarzwald.ttf", fontSize, - blockSize, TextHAlignment::RIGHT, verticalAlignment[0]); - - auto leftColor = LayerColor::create(Color4B(100, 100, 100, 255), blockSize.width, blockSize.height); - auto centerColor = LayerColor::create(Color4B(200, 100, 100, 255), blockSize.width, blockSize.height); - auto rightColor = LayerColor::create(Color4B(100, 100, 200, 255), blockSize.width, blockSize.height); - - leftColor->setIgnoreAnchorPointForPosition(false); - centerColor->setIgnoreAnchorPointForPosition(false); - rightColor->setIgnoreAnchorPointForPosition(false); - - top->setAnchorPoint(Vec2(0.5, 1)); - left->setAnchorPoint(Vec2(0, 0.5)); - leftColor->setAnchorPoint(Vec2(0, 0.5)); - center->setAnchorPoint(Vec2(0, 0.5)); - centerColor->setAnchorPoint(Vec2(0, 0.5)); - right->setAnchorPoint(Vec2(0, 0.5)); - rightColor->setAnchorPoint(Vec2(0, 0.5)); - - top->setPosition(s.width / 2, s.height - 20); - left->setPosition(0, s.height / 2); - leftColor->setPosition(left->getPosition()); - center->setPosition(blockSize.width, s.height / 2); - centerColor->setPosition(center->getPosition()); - right->setPosition(blockSize.width * 2, s.height / 2); - rightColor->setPosition(right->getPosition()); - - this->addChild(leftColor, -1, kTagColor1); - this->addChild(left, 0, kTagLabel1); - this->addChild(rightColor, -1, kTagColor2); - this->addChild(right, 0, kTagLabel2); - this->addChild(centerColor, -1, kTagColor3); - this->addChild(center, 0, kTagLabel3); - this->addChild(top, 0, kTagLabel4); + TestCase::onEnter(); + + std::string suffix; + if (_replace) + { + ValueMap dict{{"fonts/A Damn Mess.ttf", Value("fonts/arial.ttf")}, + {"fonts/Abberancy.ttf", Value("fonts/arial.ttf")}, + {"fonts/Abduction.ttf", Value("fonts/arial.ttf")}, + {"fonts/Schwarzwald.ttf", Value("fonts/arial.ttf")}}; + + FileUtils::getInstance()->setFilenameLookupDictionary(dict); + suffix = " replaced by arial.ttf"; + } + + auto s = Director::getInstance()->getWinSize(); + + auto blockSize = Size(s.width / 3, 200); + float fontSize = 26; + + removeChildByTag(kTagLabel1, true); + removeChildByTag(kTagLabel2, true); + removeChildByTag(kTagLabel3, true); + removeChildByTag(kTagLabel4, true); + removeChildByTag(kTagColor1, true); + removeChildByTag(kTagColor2, true); + removeChildByTag(kTagColor3, true); + + auto top = Label::createWithTTF("fonts/A Damn Mess.ttf" + suffix, "fonts/A Damn Mess.ttf", 24); + auto left = Label::createWithTTF("fonts/Abberancy.ttf" + suffix, "fonts/Abberancy.ttf", fontSize, blockSize, + TextHAlignment::LEFT, verticalAlignment[0]); + auto center = Label::createWithTTF("fonts/Abduction.ttf" + suffix, "fonts/Abduction.ttf", fontSize, blockSize, + TextHAlignment::CENTER, verticalAlignment[0]); + auto right = Label::createWithTTF("fonts/Schwarzwald.ttf" + suffix, "fonts/Schwarzwald.ttf", fontSize, blockSize, + TextHAlignment::RIGHT, verticalAlignment[0]); + + auto leftColor = LayerColor::create(Color4B(100, 100, 100, 255), blockSize.width, blockSize.height); + auto centerColor = LayerColor::create(Color4B(200, 100, 100, 255), blockSize.width, blockSize.height); + auto rightColor = LayerColor::create(Color4B(100, 100, 200, 255), blockSize.width, blockSize.height); + + leftColor->setIgnoreAnchorPointForPosition(false); + centerColor->setIgnoreAnchorPointForPosition(false); + rightColor->setIgnoreAnchorPointForPosition(false); + + top->setAnchorPoint(Vec2(0.5, 1)); + left->setAnchorPoint(Vec2(0, 0.5)); + leftColor->setAnchorPoint(Vec2(0, 0.5)); + center->setAnchorPoint(Vec2(0, 0.5)); + centerColor->setAnchorPoint(Vec2(0, 0.5)); + right->setAnchorPoint(Vec2(0, 0.5)); + rightColor->setAnchorPoint(Vec2(0, 0.5)); + + top->setPosition(s.width / 2, s.height - 20); + left->setPosition(0, s.height / 2); + leftColor->setPosition(left->getPosition()); + center->setPosition(blockSize.width, s.height / 2); + centerColor->setPosition(center->getPosition()); + right->setPosition(blockSize.width * 2, s.height / 2); + rightColor->setPosition(right->getPosition()); + + this->addChild(leftColor, -1, kTagColor1); + this->addChild(left, 0, kTagLabel1); + this->addChild(rightColor, -1, kTagColor2); + this->addChild(right, 0, kTagLabel2); + this->addChild(centerColor, -1, kTagColor3); + this->addChild(center, 0, kTagLabel3); + this->addChild(top, 0, kTagLabel4); } std::string FontNoReplacementTest::title() const { - return "Font no replacement test"; + return "Font no replacement test"; } FontReplacementTest* FontReplacementTest::create() { - auto ret = new FontReplacementTest; - if (ret->init()) - { - ret->autorelease(); - } - else - { - delete ret; - ret = nullptr; - } - - return ret; + auto ret = new FontReplacementTest; + if (ret->init()) + { + ret->autorelease(); + } + else + { + delete ret; + ret = nullptr; + } + + return ret; } FontReplacementTest::FontReplacementTest() { - _replace = true; + _replace = true; } std::string FontReplacementTest::title() const { - return "Font replacement test"; + return "Font replacement test"; } diff --git a/tests/cpp-tests/Classes/FontTest/FontTest.h b/tests/cpp-tests/Classes/FontTest/FontTest.h index 2659dd5a15ee..d7dc5a5b3367 100644 --- a/tests/cpp-tests/Classes/FontTest/FontTest.h +++ b/tests/cpp-tests/Classes/FontTest/FontTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -33,7 +33,7 @@ DEFINE_TEST_SUITE(FontTests); class FontTest : public TestCase { public: - static FontTest* create(const std::string& fontFile) + static FontTest* create(std::string_view fontFile) { auto ret = new FontTest; if (ret->init()) @@ -50,7 +50,7 @@ class FontTest : public TestCase return ret; } - void showFont(const std::string& fontFile); + void showFont(std::string_view fontFile); virtual std::string title() const override; }; @@ -58,23 +58,25 @@ class FontTest : public TestCase class FontNoReplacementTest : public TestCase { public: - static FontNoReplacementTest* create(); - ~FontNoReplacementTest(); - virtual void onEnter() override; - virtual std::string title() const override; + static FontNoReplacementTest* create(); + ~FontNoReplacementTest(); + virtual void onEnter() override; + virtual std::string title() const override; + protected: - FontNoReplacementTest(); + FontNoReplacementTest(); - bool _replace; + bool _replace; }; class FontReplacementTest : public FontNoReplacementTest { public: - static FontReplacementTest* create(); - virtual std::string title() const override; + static FontReplacementTest* create(); + virtual std::string title() const override; + protected: - FontReplacementTest(); + FontReplacementTest(); }; -#endif // _FONT_TEST_H_ +#endif // _FONT_TEST_H_ diff --git a/tests/cpp-tests/Classes/ImGuiEXTTest/ImGuiEXTTest.cpp b/tests/cpp-tests/Classes/ImGuiEXTTest/ImGuiEXTTest.cpp index cbf141f585dc..575a3d35525c 100644 --- a/tests/cpp-tests/Classes/ImGuiEXTTest/ImGuiEXTTest.cpp +++ b/tests/cpp-tests/Classes/ImGuiEXTTest/ImGuiEXTTest.cpp @@ -8,15 +8,15 @@ USING_NS_CC_EXT; #if defined(CC_PLATFORM_PC) -static bool show_test_window = true; +static bool show_test_window = true; static bool show_another_window = true; -static ImVec4 clear_color = ImColor(114, 144, 154); +static ImVec4 clear_color = ImColor(114, 144, 154); ImGuiEXTTests::ImGuiEXTTests() { - // Resize (expand) window + // Resize (expand) window static Size resourceSize(1280, 720); - auto director = Director::getInstance(); + auto director = Director::getInstance(); GLViewImpl* view = (GLViewImpl*)Director::getInstance()->getOpenGLView(); view->setWindowed(resourceSize.width, resourceSize.height); @@ -50,9 +50,12 @@ void ImGuiEXTTest::onDrawImGui() ImGui::Text("Hello, world!"); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ImGui::ColorEdit3("clear color", (float*)&clear_color); - if (ImGui::Button("Test Window")) show_test_window ^= 1; - if (ImGui::Button("Another Window")) show_another_window ^= 1; - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + if (ImGui::Button("Test Window")) + show_test_window ^= 1; + if (ImGui::Button("Another Window")) + show_another_window ^= 1; + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, + ImGui::GetIO().Framerate); } // 2. Show another simple window, this time using an explicit Begin/End pair diff --git a/tests/cpp-tests/Classes/ImGuiEXTTest/ImGuiEXTTest.h b/tests/cpp-tests/Classes/ImGuiEXTTest/ImGuiEXTTest.h index c3c60ca57f3f..e55ff3821b11 100644 --- a/tests/cpp-tests/Classes/ImGuiEXTTest/ImGuiEXTTest.h +++ b/tests/cpp-tests/Classes/ImGuiEXTTest/ImGuiEXTTest.h @@ -47,4 +47,4 @@ class ImGuiEXTTest : public TestCase #endif -#endif // _CURL_TEST_H_ +#endif // _CURL_TEST_H_ diff --git a/tests/cpp-tests/Classes/InputTest/MouseTest.cpp b/tests/cpp-tests/Classes/InputTest/MouseTest.cpp index c810030515bd..c39e1da6fdeb 100644 --- a/tests/cpp-tests/Classes/InputTest/MouseTest.cpp +++ b/tests/cpp-tests/Classes/InputTest/MouseTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -26,7 +26,13 @@ USING_NS_CC; -template std::string tostr(const T& t) { std::ostringstream os; os< +std::string tostr(const T& t) +{ + std::ostringstream os; + os << t; + return os.str(); +} MouseTests::MouseTests() { @@ -43,21 +49,20 @@ MouseEventTest::MouseEventTest() { auto s = Director::getInstance()->getWinSize(); - //Create a label to display the mouse action + // Create a label to display the mouse action _labelAction = Label::createWithTTF("Click mouse button and see this change", "fonts/arial.ttf", 22); - _labelAction->setPosition(Vec2(s.width/2, s.height*2/3)); + _labelAction->setPosition(Vec2(s.width / 2, s.height * 2 / 3)); addChild(_labelAction, 0); - //Create a label to display the mouse position + // Create a label to display the mouse position _labelPosition = Label::createWithTTF("Mouse not supported on this device", "fonts/arial.ttf", 22); - _labelPosition->setPosition(Vec2(s.width/2, s.height/3)); + _labelPosition->setPosition(Vec2(s.width / 2, s.height / 3)); addChild(_labelPosition); - - _mouseListener = EventListenerMouse::create(); - _mouseListener->onMouseMove = CC_CALLBACK_1(MouseEventTest::onMouseMove, this); - _mouseListener->onMouseUp = CC_CALLBACK_1(MouseEventTest::onMouseUp, this); - _mouseListener->onMouseDown = CC_CALLBACK_1(MouseEventTest::onMouseDown, this); + _mouseListener = EventListenerMouse::create(); + _mouseListener->onMouseMove = CC_CALLBACK_1(MouseEventTest::onMouseMove, this); + _mouseListener->onMouseUp = CC_CALLBACK_1(MouseEventTest::onMouseUp, this); + _mouseListener->onMouseDown = CC_CALLBACK_1(MouseEventTest::onMouseDown, this); _mouseListener->onMouseScroll = CC_CALLBACK_1(MouseEventTest::onMouseScroll, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(_mouseListener, this); @@ -68,35 +73,35 @@ MouseEventTest::~MouseEventTest() _eventDispatcher->removeEventListener(_mouseListener); } -void MouseEventTest::onMouseDown(Event *event) +void MouseEventTest::onMouseDown(Event* event) { - EventMouse* e = (EventMouse*)event; + EventMouse* e = (EventMouse*)event; std::string str = "Mouse Down detected, Key: "; str += tostr(static_cast(e->getMouseButton())); _labelAction->setString(str.c_str()); } -void MouseEventTest::onMouseUp(Event *event) +void MouseEventTest::onMouseUp(Event* event) { - EventMouse* e = (EventMouse*)event; + EventMouse* e = (EventMouse*)event; std::string str = "Mouse Up detected, Key: "; str += tostr(static_cast(e->getMouseButton())); _labelAction->setString(str.c_str()); } -void MouseEventTest::onMouseMove(Event *event) +void MouseEventTest::onMouseMove(Event* event) { - EventMouse* e = (EventMouse*)event; + EventMouse* e = (EventMouse*)event; std::string str = "MousePosition X:"; - str = str + tostr(e->getCursorX()) + " Y:" + tostr(e->getCursorY()); + str = str + tostr(e->getCursorX()) + " Y:" + tostr(e->getCursorY()); _labelPosition->setString(str.c_str()); } -void MouseEventTest::onMouseScroll(Event *event) +void MouseEventTest::onMouseScroll(Event* event) { - EventMouse* e = (EventMouse*)event; + EventMouse* e = (EventMouse*)event; std::string str = "Mouse Scroll detected, X: "; - str = str + tostr(e->getScrollX()) + " Y: " + tostr(e->getScrollY()); + str = str + tostr(e->getScrollX()) + " Y: " + tostr(e->getScrollY()); _labelAction->setString(str.c_str()); } @@ -118,16 +123,12 @@ std::string MouseEventTest::subtitle() const HideMouseTest::HideMouseTest() { - - _lis = EventListenerMouse::create(); - _lis->onMouseDown = [](Event* e){ - Director::getInstance()->getOpenGLView()->setCursorVisible(false); - }; - - _lis->onMouseUp = [](Event* e){ - Director::getInstance()->getOpenGLView()->setCursorVisible(true); - }; - + + _lis = EventListenerMouse::create(); + _lis->onMouseDown = [](Event* e) { Director::getInstance()->getOpenGLView()->setCursorVisible(false); }; + + _lis->onMouseUp = [](Event* e) { Director::getInstance()->getOpenGLView()->setCursorVisible(true); }; + _eventDispatcher->addEventListenerWithSceneGraphPriority(_lis, this); } @@ -145,4 +146,3 @@ std::string HideMouseTest::subtitle() const { return "Click to hide mouse"; } - diff --git a/tests/cpp-tests/Classes/InputTest/MouseTest.h b/tests/cpp-tests/Classes/InputTest/MouseTest.h index cc2162dad881..dd8be001f8f6 100644 --- a/tests/cpp-tests/Classes/InputTest/MouseTest.h +++ b/tests/cpp-tests/Classes/InputTest/MouseTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -33,7 +33,6 @@ DEFINE_TEST_SUITE(MouseTests); class BaseMouseTest : public TestCase { public: - }; class MouseEventTest : public BaseMouseTest @@ -47,13 +46,13 @@ class MouseEventTest : public BaseMouseTest void onMouseUp(cocos2d::Event* event); void onMouseMove(cocos2d::Event* event); void onMouseScroll(cocos2d::Event* event); - + virtual std::string title() const override; virtual std::string subtitle() const override; private: - cocos2d::Label* _labelAction; - cocos2d::Label* _labelPosition; + cocos2d::Label* _labelAction; + cocos2d::Label* _labelPosition; cocos2d::EventListenerMouse* _mouseListener; }; @@ -63,10 +62,10 @@ class HideMouseTest : public BaseMouseTest CREATE_FUNC(HideMouseTest); HideMouseTest(); ~HideMouseTest(); - + virtual std::string title() const override; virtual std::string subtitle() const override; - + private: cocos2d::EventListenerMouse* _lis; }; diff --git a/tests/cpp-tests/Classes/IntervalTest/IntervalTest.cpp b/tests/cpp-tests/Classes/IntervalTest/IntervalTest.cpp index a998e7edeb60..16398102fe2d 100644 --- a/tests/cpp-tests/Classes/IntervalTest/IntervalTest.cpp +++ b/tests/cpp-tests/Classes/IntervalTest/IntervalTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,11 +27,11 @@ USING_NS_CC; -#define SID_STEP1 100 -#define SID_STEP2 101 -#define SID_STEP3 102 +#define SID_STEP1 100 +#define SID_STEP2 101 +#define SID_STEP3 102 -#define IDC_PAUSE 200 +#define IDC_PAUSE 200 IntervalTests::IntervalTests() { @@ -46,7 +46,7 @@ IntervalTest::IntervalTest() // sun auto sun = ParticleSun::create(); sun->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); - sun->setPosition(VisibleRect::rightTop().x-32,VisibleRect::rightTop().y-32); + sun->setPosition(VisibleRect::rightTop().x - 32, VisibleRect::rightTop().y - 32); sun->setTotalParticles(130); sun->setLife(0.6f); @@ -60,43 +60,51 @@ IntervalTest::IntervalTest() _label4 = Label::createWithBMFont("fonts/bitmapFontTest4.fnt", "0"); scheduleUpdate(); - schedule([&](float dt){ - _time1 +=dt; - - char str[10] = {0}; - sprintf(str, "%2.1f", _time1); - _label1->setString( str ); - }, "step_1"); - - schedule([&](float dt){ - _time2 +=dt; - - char str[10] = {0}; - sprintf(str, "%2.1f", _time2); - _label2->setString( str ); - }, 0.5, "step_2"); - - schedule([&](float dt){ - _time3 +=dt; - - char str[10] = {0}; - sprintf(str, "%2.1f", _time3); - _label3->setString( str ); - }, 1, "step_3"); - - schedule([&](float dt){ - _time4 +=dt; - - char str[10] = {0}; - sprintf(str, "%2.1f", _time4); - _label4->setString( str ); - }, 2, "step_4"); - - _label0->setPosition(s.width*1/6, s.height/2); - _label1->setPosition(s.width*2/6, s.height/2); - _label2->setPosition(s.width*3/6, s.height/2); - _label3->setPosition(s.width*4/6, s.height/2); - _label4->setPosition(s.width*5/6, s.height/2); + schedule( + [&](float dt) { + _time1 += dt; + + char str[10] = {0}; + sprintf(str, "%2.1f", _time1); + _label1->setString(str); + }, + "step_1"); + + schedule( + [&](float dt) { + _time2 += dt; + + char str[10] = {0}; + sprintf(str, "%2.1f", _time2); + _label2->setString(str); + }, + 0.5, "step_2"); + + schedule( + [&](float dt) { + _time3 += dt; + + char str[10] = {0}; + sprintf(str, "%2.1f", _time3); + _label3->setString(str); + }, + 1, "step_3"); + + schedule( + [&](float dt) { + _time4 += dt; + + char str[10] = {0}; + sprintf(str, "%2.1f", _time4); + _label4->setString(str); + }, + 2, "step_4"); + + _label0->setPosition(s.width * 1 / 6, s.height / 2); + _label1->setPosition(s.width * 2 / 6, s.height / 2); + _label2->setPosition(s.width * 3 / 6, s.height / 2); + _label3->setPosition(s.width * 4 / 6, s.height / 2); + _label4->setPosition(s.width * 5 / 6, s.height / 2); addChild(_label0); addChild(_label1); @@ -107,27 +115,27 @@ IntervalTest::IntervalTest() // Sprite auto sprite = Sprite::create(s_pathGrossini); sprite->setPosition(VisibleRect::left().x + 40, VisibleRect::bottom().y + 50); - - auto jump = JumpBy::create(3, Vec2(s.width-80,0.0f), 50, 4); - + + auto jump = JumpBy::create(3, Vec2(s.width - 80, 0.0f), 50, 4); + addChild(sprite); - sprite->runAction( RepeatForever::create(Sequence::create(jump, jump->reverse(), nullptr) )); + sprite->runAction(RepeatForever::create(Sequence::create(jump, jump->reverse(), nullptr))); // pause button auto item1 = MenuItemFont::create("Pause", [&](Ref* sender) { - if(Director::getInstance()->isPaused()) - Director::getInstance()->resume(); - else - Director::getInstance()->pause(); - }); - auto menu = Menu::create(item1, nullptr); - menu->setPosition(s.width/2, s.height-50); - - addChild( menu ); + if (Director::getInstance()->isPaused()) + Director::getInstance()->resume(); + else + Director::getInstance()->pause(); + }); + auto menu = Menu::create(item1, nullptr); + menu->setPosition(s.width / 2, s.height - 50); + + addChild(menu); } IntervalTest::~IntervalTest() { - if(Director::getInstance()->isPaused()) + if (Director::getInstance()->isPaused()) { Director::getInstance()->resume(); } @@ -135,7 +143,7 @@ IntervalTest::~IntervalTest() void IntervalTest::update(float dt) { - _time0 +=dt; + _time0 += dt; char time[10] = {0}; sprintf(time, "%2.1f", _time0); _label0->setString(time); diff --git a/tests/cpp-tests/Classes/IntervalTest/IntervalTest.h b/tests/cpp-tests/Classes/IntervalTest/IntervalTest.h index 68bd6ca6ae9e..f885358abc02 100644 --- a/tests/cpp-tests/Classes/IntervalTest/IntervalTest.h +++ b/tests/cpp-tests/Classes/IntervalTest/IntervalTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -38,16 +38,16 @@ class IntervalTest : public TestCase virtual void update(float dt) override; - //CREATE_NODE(IntervalLayer); + // CREATE_NODE(IntervalLayer); protected: - cocos2d::Label* _label0; - cocos2d::Label* _label1; - cocos2d::Label* _label2; - cocos2d::Label* _label3; - cocos2d::Label* _label4; + cocos2d::Label* _label0; + cocos2d::Label* _label1; + cocos2d::Label* _label2; + cocos2d::Label* _label3; + cocos2d::Label* _label4; - float _time0, _time1, _time2, _time3, _time4; + float _time0, _time1, _time2, _time3, _time4; }; #endif diff --git a/tests/cpp-tests/Classes/JNITest/JNITest.cpp b/tests/cpp-tests/Classes/JNITest/JNITest.cpp index d873f93cee8b..feba30d292cf 100644 --- a/tests/cpp-tests/Classes/JNITest/JNITest.cpp +++ b/tests/cpp-tests/Classes/JNITest/JNITest.cpp @@ -1,18 +1,19 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - + Copyright (c) 2021 Bytedance inc. + + https://adxeproject.github.io/ + 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 @@ -24,12 +25,11 @@ #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) -#include "JNITest.h" - +# include "JNITest.h" -#include "platform/android/jni/JniHelper.h" +# include "platform/android/jni/JniHelper.h" -#include +# include USING_NS_CC; @@ -48,7 +48,7 @@ JNITest::JNITest() checkLabel->setPosition(VisibleRect::center()); addChild(checkLabel); - const std::string classPath = "org.cocos2dx.cpp_tests.JNITest"; + const char* classPath = "org.cocos2dx.cpp_tests.JNITest"; JniHelper::callStaticVoidMethod(classPath, "voidMethod1"); @@ -65,23 +65,24 @@ JNITest::JNITest() CC_ASSERT(i == 20); float f = JniHelper::callStaticFloatMethod(classPath, "floatMethod", float(2.35), float(7.65)); - CC_ASSERT(f == 10.0); - + CC_ASSERT(f == 10.0); + double d = JniHelper::callStaticDoubleMethod(classPath, "doubleMethod", double(2.5), int(4)); - CC_ASSERT(d == 10.0); + CC_ASSERT(d == 10.0); std::string str = "ABCDEF"; - std::string s1 = JniHelper::callStaticStringMethod(classPath, "stringMethod", str, true); + std::string s1 = JniHelper::callStaticStringMethod(classPath, "stringMethod", str, true); CC_ASSERT(s1 == "FEDCBA"); std::string s2 = JniHelper::callStaticStringMethod(classPath, "stringMethod", str, false); CC_ASSERT(s2 == "ABCDEF"); const char* cstr = "XYZ"; - std::string s3 = JniHelper::callStaticStringMethod(classPath, "stringMethod", cstr, true); + std::string s3 = JniHelper::callStaticStringMethod(classPath, "stringMethod", cstr, true); CC_ASSERT(s3 == "ZYX"); // should not crash - for (int i = 0; i < 10000; i++) { + for (int i = 0; i < 10000; i++) + { JniHelper::callStaticVoidMethod(classPath, "voidMethod4", "ABCDEF"); } diff --git a/tests/cpp-tests/Classes/JNITest/JNITest.h b/tests/cpp-tests/Classes/JNITest/JNITest.h index 1cc3a59ddf8b..2d00e229372f 100644 --- a/tests/cpp-tests/Classes/JNITest/JNITest.h +++ b/tests/cpp-tests/Classes/JNITest/JNITest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,8 +27,8 @@ #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) -#include "cocos2d.h" -#include "../BaseTest.h" +# include "cocos2d.h" +# include "../BaseTest.h" DEFINE_TEST_SUITE(JNITests); @@ -40,4 +40,4 @@ class JNITest : public TestCase JNITest(); }; #endif -#endif // _JNI_TEST_H_ +#endif // _JNI_TEST_H_ diff --git a/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp b/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp index 0918b0f48a0c..b490f025c7ba 100644 --- a/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp +++ b/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -31,16 +31,18 @@ USING_NS_CC; using namespace ui; using namespace extension; -enum { - kTagTileMap = 1, +enum +{ + kTagTileMap = 1, kTagSpriteManager = 1, - kTagAnimation1 = 1, - kTagBitmapAtlas1 = 1, - kTagBitmapAtlas2 = 2, - kTagBitmapAtlas3 = 3, + kTagAnimation1 = 1, + kTagBitmapAtlas1 = 1, + kTagBitmapAtlas2 = 2, + kTagBitmapAtlas3 = 3, }; -enum { +enum +{ kTagSprite1, kTagSprite2, kTagSprite3, @@ -150,36 +152,34 @@ LabelFNTColorAndOpacity::LabelFNTColorAndOpacity() { _time = 0; - auto col = LayerColor::create( Color4B(128,128,128,255) ); + auto col = LayerColor::create(Color4B(128, 128, 128, 255)); addChild(col, -10); - + auto label1 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "Test"); - - label1->setAnchorPoint( Vec2(0,0) ); + + label1->setAnchorPoint(Vec2(0, 0)); addChild(label1, 0, kTagBitmapAtlas1); - auto fade = FadeOut::create(1.0f); + auto fade = FadeOut::create(1.0f); auto fade_in = fade->reverse(); - auto seq = Sequence::create(fade, fade_in, nullptr); - auto repeat = RepeatForever::create(seq); + auto seq = Sequence::create(fade, fade_in, nullptr); + auto repeat = RepeatForever::create(seq); label1->runAction(repeat); - + auto label2 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "Test"); - label2->setColor( Color3B::RED ); + label2->setColor(Color3B::RED); addChild(label2, 0, kTagBitmapAtlas2); - auto tint = Sequence::create(TintTo::create(1, 255, 0, 0), - TintTo::create(1, 0, 255, 0), - TintTo::create(1, 0, 0, 255), - nullptr); - label2->runAction( RepeatForever::create(tint) ); - + auto tint = Sequence::create(TintTo::create(1, 255, 0, 0), TintTo::create(1, 0, 255, 0), + TintTo::create(1, 0, 0, 255), nullptr); + label2->runAction(RepeatForever::create(tint)); + auto label3 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "Test"); - label3->setAnchorPoint( Vec2(1,1) ); + label3->setAnchorPoint(Vec2(1, 1)); addChild(label3, 0, kTagBitmapAtlas3); - - label1->setPosition( VisibleRect::leftBottom() ); - label2->setPosition( VisibleRect::center() ); - label3->setPosition( VisibleRect::rightTop() ); - + + label1->setPosition(VisibleRect::leftBottom()); + label2->setPosition(VisibleRect::center()); + label3->setPosition(VisibleRect::rightTop()); + schedule(CC_CALLBACK_1(LabelFNTColorAndOpacity::step, this), "step_key"); } @@ -188,14 +188,14 @@ void LabelFNTColorAndOpacity::step(float dt) _time += dt; char string[15] = {0}; sprintf(string, "%2.2f Test j", _time); - - auto label1 = (Label*) getChildByTag(kTagBitmapAtlas1); + + auto label1 = (Label*)getChildByTag(kTagBitmapAtlas1); label1->setString(string); - - auto label2 = (Label*) getChildByTag(kTagBitmapAtlas2); + + auto label2 = (Label*)getChildByTag(kTagBitmapAtlas2); label2->setString(string); - - auto label3 = (Label*) getChildByTag(kTagBitmapAtlas3); + + auto label3 = (Label*)getChildByTag(kTagBitmapAtlas3); label3->setString(string); } @@ -212,56 +212,53 @@ std::string LabelFNTColorAndOpacity::subtitle() const LabelFNTSpriteActions::LabelFNTSpriteActions() { _time = 0; - + auto s = Director::getInstance()->getWinSize(); - + auto drawNode = DrawNode::create(); - drawNode->drawLine( Vec2(0.0f, s.height/2), Vec2(s.width, s.height/2), Color4F(1.0f, 1.0f, 1.0f, 1.0f) ); - drawNode->drawLine( Vec2(s.width/2, 0.0f), Vec2(s.width/2, s.height), Color4F(1.0f, 1.0f, 1.0f, 1.0f) ); + drawNode->drawLine(Vec2(0.0f, s.height / 2), Vec2(s.width, s.height / 2), Color4F(1.0f, 1.0f, 1.0f, 1.0f)); + drawNode->drawLine(Vec2(s.width / 2, 0.0f), Vec2(s.width / 2, s.height), Color4F(1.0f, 1.0f, 1.0f, 1.0f)); addChild(drawNode, -1); // Upper Label auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Bitmap Font Atlas"); addChild(label); - - - label->setPosition( Vec2(s.width/2, s.height/2) ); - - auto BChar = (Sprite*) label->getLetter(0); - auto FChar = (Sprite*) label->getLetter(7); - auto AChar = (Sprite*) label->getLetter(12); - - - auto rotate = RotateBy::create(2, 360); + + label->setPosition(Vec2(s.width / 2, s.height / 2)); + + auto BChar = (Sprite*)label->getLetter(0); + auto FChar = (Sprite*)label->getLetter(7); + auto AChar = (Sprite*)label->getLetter(12); + + auto rotate = RotateBy::create(2, 360); auto rot_4ever = RepeatForever::create(rotate); - - auto scale = ScaleBy::create(2, 1.5f); - auto scale_back = scale->reverse(); - auto scale_seq = Sequence::create(scale, scale_back,nullptr); + + auto scale = ScaleBy::create(2, 1.5f); + auto scale_back = scale->reverse(); + auto scale_seq = Sequence::create(scale, scale_back, nullptr); auto scale_4ever = RepeatForever::create(scale_seq); - - auto jump = JumpBy::create(0.5f, Vec2::ZERO, 60, 1); + + auto jump = JumpBy::create(0.5f, Vec2::ZERO, 60, 1); auto jump_4ever = RepeatForever::create(jump); - - auto fade_out = FadeOut::create(1); - auto fade_in = FadeIn::create(1); - auto seq = Sequence::create(fade_out, fade_in, nullptr); + + auto fade_out = FadeOut::create(1); + auto fade_in = FadeIn::create(1); + auto seq = Sequence::create(fade_out, fade_in, nullptr); auto fade_4ever = RepeatForever::create(seq); - + BChar->runAction(rot_4ever); BChar->runAction(scale_4ever); FChar->runAction(jump_4ever); AChar->runAction(fade_4ever); - - + // Bottom Label auto label2 = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "00.0"); addChild(label2, 0, kTagBitmapAtlas2); - label2->setPosition( Vec2(s.width/2.0f, 80.0f) ); - - auto lastChar = (Sprite*) label2->getLetter(3); - lastChar->runAction( rot_4ever->clone() ); - + label2->setPosition(Vec2(s.width / 2.0f, 80.0f)); + + auto lastChar = (Sprite*)label2->getLetter(3); + lastChar->runAction(rot_4ever->clone()); + schedule(CC_CALLBACK_1(LabelFNTSpriteActions::step, this), 0.1f, "step_key"); } @@ -270,7 +267,7 @@ void LabelFNTSpriteActions::step(float dt) _time += dt; char string[10] = {0}; sprintf(string, "%04.1f", _time); - auto label1 = (Label*) getChildByTag(kTagBitmapAtlas2); + auto label1 = (Label*)getChildByTag(kTagBitmapAtlas2); label1->setString(string); } @@ -288,10 +285,10 @@ LabelFNTPadding::LabelFNTPadding() { auto label = Label::createWithBMFont("fonts/bitmapFontTest4.fnt", "abcdefg"); addChild(label); - + auto s = Director::getInstance()->getWinSize(); - - label->setPosition( Vec2(s.width/2, s.height/2) ); + + label->setPosition(Vec2(s.width / 2, s.height / 2)); } std::string LabelFNTPadding::title() const @@ -309,17 +306,17 @@ LabelFNTOffset::LabelFNTOffset() auto s = Director::getInstance()->getWinSize(); Label* label = nullptr; - label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "FaFeFiFoFu"); + label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "FaFeFiFoFu"); addChild(label); - label->setPosition( Vec2(s.width/2, s.height/2+50) ); - + label->setPosition(Vec2(s.width / 2, s.height / 2 + 50)); + label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "fafefifofu"); addChild(label); - label->setPosition( Vec2(s.width/2, s.height/2) ); + label->setPosition(Vec2(s.width / 2, s.height / 2)); label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "aeiou"); addChild(label); - label->setPosition( Vec2(s.width/2, s.height/2-50) ); + label->setPosition(Vec2(s.width / 2, s.height / 2 - 50)); } std::string LabelFNTOffset::title() const @@ -335,21 +332,21 @@ std::string LabelFNTOffset::subtitle() const LabelFNTColor::LabelFNTColor() { auto winSize = Director::getInstance()->getWinSize(); - + auto label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "Blue"); - label->setColor( Color3B::BLUE ); + label->setColor(Color3B::BLUE); addChild(label); label->setPosition(winSize.width / 2, winSize.height * 0.7f); label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "Red"); addChild(label); label->setPosition(winSize.width / 2, winSize.height * 0.5f); - label->setColor( Color3B::RED ); + label->setColor(Color3B::RED); label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "Green"); addChild(label); - label->setPosition(winSize.width / 2, winSize.height * 0.3f); - label->setColor( Color3B::GREEN ); + label->setPosition(winSize.width / 2, winSize.height * 0.3f); + label->setColor(Color3B::GREEN); label->setString("Green"); } @@ -391,17 +388,17 @@ std::string LabelFNTOpacity::subtitle() const LabelFNTHundredLabels::LabelFNTHundredLabels() { // Upper Label - for ( int i=0 ; i < 100;i ++ ) + for (int i = 0; i < 100; i++) { char str[6] = {0}; sprintf(str, "-%d-", i); auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", str); addChild(label); - + auto s = Director::getInstance()->getWinSize(); - auto p = Vec2( CCRANDOM_0_1() * s.width, CCRANDOM_0_1() * s.height); - label->setPosition( p ); + auto p = Vec2(CCRANDOM_0_1() * s.width, CCRANDOM_0_1() * s.height); + label->setPosition(p); } } @@ -421,18 +418,17 @@ LabelFNTMultiLine::LabelFNTMultiLine() // Left auto label1 = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", " Multi line\nLeft"); - label1->setAnchorPoint(Vec2(0,0)); + label1->setAnchorPoint(Vec2(0, 0)); addChild(label1, 0, kTagBitmapAtlas1); s = label1->getContentSize(); CCLOG("content size: %.2fx%.2f", s.width, s.height); - // Center - auto label2 = Label::createWithBMFont( "fonts/bitmapFontTest3.fnt", "Multi line\nCenter"); + auto label2 = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", "Multi line\nCenter"); addChild(label2, 0, kTagBitmapAtlas2); - s= label2->getContentSize(); + s = label2->getContentSize(); CCLOG("content size: %.2fx%.2f", s.width, s.height); // right @@ -465,17 +461,17 @@ LabelFNTandTTFEmpty::LabelFNTandTTFEmpty() // LabelBMFont auto label1 = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", "", TextHAlignment::CENTER, s.width); addChild(label1, 0, kTagBitmapAtlas1); - label1->setPosition(Vec2(s.width/2, s.height - 100)); + label1->setPosition(Vec2(s.width / 2, s.height - 100)); // LabelTTF - TTFConfig ttfConfig("fonts/arial.ttf",24); - auto label2 = Label::createWithTTF(ttfConfig,"", TextHAlignment::CENTER,s.width); + TTFConfig ttfConfig("fonts/arial.ttf", 24); + auto label2 = Label::createWithTTF(ttfConfig, "", TextHAlignment::CENTER, s.width); addChild(label2, 0, kTagBitmapAtlas2); - label2->setPosition(Vec2(s.width/2, s.height / 2)); - + label2->setPosition(Vec2(s.width / 2, s.height / 2)); + auto label3 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.plist"); addChild(label3, 0, kTagBitmapAtlas3); - label3->setPosition(Vec2(s.width/2, 100.0f)); + label3->setPosition(Vec2(s.width / 2, 100.0f)); schedule(CC_CALLBACK_1(LabelFNTandTTFEmpty::updateStrings, this), 1.0f, "update_strings_key"); @@ -484,16 +480,16 @@ LabelFNTandTTFEmpty::LabelFNTandTTFEmpty() void LabelFNTandTTFEmpty::updateStrings(float dt) { - auto label1 = static_cast( getChildByTag(kTagBitmapAtlas1) ); - auto label2 = static_cast( getChildByTag(kTagBitmapAtlas2) ); - auto label3 = static_cast( getChildByTag(kTagBitmapAtlas3) ); + auto label1 = static_cast(getChildByTag(kTagBitmapAtlas1)); + auto label2 = static_cast(getChildByTag(kTagBitmapAtlas2)); + auto label3 = static_cast(getChildByTag(kTagBitmapAtlas3)); - if( ! setEmpty ) + if (!setEmpty) { label1->setString("not empty"); label2->setString("not empty"); label3->setString("hi"); - + setEmpty = true; } else @@ -501,7 +497,7 @@ void LabelFNTandTTFEmpty::updateStrings(float dt) label1->setString(""); label2->setString(""); label3->setString(""); - + setEmpty = false; } } @@ -523,7 +519,7 @@ LabelFNTRetina::LabelFNTRetina() // LabelBMFont auto label1 = Label::createWithBMFont("fonts/konqa32.fnt", "TESTING RETINA DISPLAY"); addChild(label1); - label1->setPosition(Vec2(s.width/2, s.height/2)); + label1->setPosition(Vec2(s.width / 2, s.height / 2)); } std::string LabelFNTRetina::title() const @@ -540,7 +536,7 @@ LabelFNTGlyphDesigner::LabelFNTGlyphDesigner() { auto winSize = Director::getInstance()->getWinSize(); - auto layer = LayerColor::create(Color4B(128,128,128,255)); + auto layer = LayerColor::create(Color4B(128, 128, 128, 255)); addChild(layer, -10); auto label1 = Label::createWithBMFont("fonts/futura-48.fnt", "Testing Glyph Designer"); @@ -568,9 +564,12 @@ std::string LabelFNTGlyphDesigner::subtitle() const /// BitmapFontMultiLineAlignmentNew -#define LongSentencesExample "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." -#define LineBreaksExample "Lorem ipsum dolor\nsit amet\nconsectetur adipisicing elit\nblah\nblah" -#define MixedExample "ABC\nLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt\nDEF" +#define LongSentencesExample \ + "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore " \ + "magna aliqua." +#define LineBreaksExample "Lorem ipsum dolor\nsit amet\nconsectetur adipisicing elit\nblah\nblah" +#define MixedExample \ + "ABC\nLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt\nDEF" #define ArrowsMax 0.95 #define ArrowsMin 0.7 @@ -593,26 +592,29 @@ bool LabelFNTMultiLineAlignment::init() return false; } - auto listener = EventListenerTouchAllAtOnce::create(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(LabelFNTMultiLineAlignment::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(LabelFNTMultiLineAlignment::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(LabelFNTMultiLineAlignment::onTouchesEnded, this); - + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // ask director the the window size auto size = Director::getInstance()->getWinSize(); // create and initialize a Label - this->_label = Label::createWithBMFont("fonts/markerFelt.fnt", "", TextHAlignment::CENTER, size.width/1.5); + this->_label = Label::createWithBMFont("fonts/markerFelt.fnt", "", TextHAlignment::CENTER, size.width / 1.5); this->_arrowsBar = Sprite::create("Images/arrowsBar.png"); - this->_arrows = Sprite::create("Images/arrows.png"); + this->_arrows = Sprite::create("Images/arrows.png"); MenuItemFont::setFontSize(20); - auto longSentences = MenuItemFont::create("Long Flowing Sentences", CC_CALLBACK_1(LabelFNTMultiLineAlignment::stringChanged, this)); - auto lineBreaks = MenuItemFont::create("Short Sentences With Intentional Line Breaks", CC_CALLBACK_1(LabelFNTMultiLineAlignment::stringChanged, this)); - auto mixed = MenuItemFont::create("Long Sentences Mixed With Intentional Line Breaks", CC_CALLBACK_1(LabelFNTMultiLineAlignment::stringChanged, this)); - auto stringMenu = Menu::create(longSentences, lineBreaks, mixed, nullptr); + auto longSentences = + MenuItemFont::create("Long Flowing Sentences", CC_CALLBACK_1(LabelFNTMultiLineAlignment::stringChanged, this)); + auto lineBreaks = MenuItemFont::create("Short Sentences With Intentional Line Breaks", + CC_CALLBACK_1(LabelFNTMultiLineAlignment::stringChanged, this)); + auto mixed = MenuItemFont::create("Long Sentences Mixed With Intentional Line Breaks", + CC_CALLBACK_1(LabelFNTMultiLineAlignment::stringChanged, this)); + auto stringMenu = Menu::create(longSentences, lineBreaks, mixed, nullptr); stringMenu->alignItemsVertically(); longSentences->setTag(LongSentences); @@ -625,9 +627,9 @@ bool LabelFNTMultiLineAlignment::init() MenuItemFont::setFontSize(30); - auto left = MenuItemFont::create("Left", CC_CALLBACK_1(LabelFNTMultiLineAlignment::alignmentChanged, this)); + auto left = MenuItemFont::create("Left", CC_CALLBACK_1(LabelFNTMultiLineAlignment::alignmentChanged, this)); auto center = MenuItemFont::create("Center", CC_CALLBACK_1(LabelFNTMultiLineAlignment::alignmentChanged, this)); - auto right = MenuItemFont::create("Right", CC_CALLBACK_1(LabelFNTMultiLineAlignment::alignmentChanged, this)); + auto right = MenuItemFont::create("Right", CC_CALLBACK_1(LabelFNTMultiLineAlignment::alignmentChanged, this)); auto alignmentMenu = Menu::create(left, center, right, nullptr); alignmentMenu->alignItemsHorizontallyWithPadding(alignmentItemPadding); @@ -637,7 +639,7 @@ bool LabelFNTMultiLineAlignment::init() right->setTag(RightAlign); // position the label on the center of the screen - this->_label->setPosition(Vec2(size.width/2, size.height/2)); + this->_label->setPosition(Vec2(size.width / 2, size.height / 2)); this->_arrowsBar->setVisible(false); @@ -645,8 +647,8 @@ bool LabelFNTMultiLineAlignment::init() this->_arrowsBar->setScaleX(arrowsWidth / this->_arrowsBar->getContentSize().width); this->_arrowsBar->setPosition(Vec2(((ArrowsMax + ArrowsMin) / 2) * size.width, this->_label->getPosition().y)); - stringMenu->setPosition(Vec2(size.width/2, size.height - menuItemPaddingCenter)); - alignmentMenu->setPosition(Vec2(size.width/2, menuItemPaddingCenter+15)); + stringMenu->setPosition(Vec2(size.width / 2, size.height - menuItemPaddingCenter)); + alignmentMenu->setPosition(Vec2(size.width / 2, menuItemPaddingCenter + 15)); this->selectSentenceItem(longSentences); this->selectAlignmentItem(center); @@ -671,7 +673,7 @@ std::string LabelFNTMultiLineAlignment::subtitle() const return ""; } -void LabelFNTMultiLineAlignment::selectAlignmentItem(cocos2d::MenuItemFont * item) +void LabelFNTMultiLineAlignment::selectAlignmentItem(cocos2d::MenuItemFont* item) { if (this->_lastAlignmentItem && this->_lastAlignmentItem != item) { @@ -735,7 +737,7 @@ std::string LabelFNTMultiLineAlignment::getItemString(cocos2d::MenuItemFont* ite return str; } -void LabelFNTMultiLineAlignment::stringChanged(cocos2d::Ref *sender) +void LabelFNTMultiLineAlignment::stringChanged(cocos2d::Ref* sender) { auto item = (MenuItemFont*)sender; @@ -744,7 +746,7 @@ void LabelFNTMultiLineAlignment::stringChanged(cocos2d::Ref *sender) this->snapArrowsToEdge(); } -void LabelFNTMultiLineAlignment::alignmentChanged(cocos2d::Ref *sender) +void LabelFNTMultiLineAlignment::alignmentChanged(cocos2d::Ref* sender) { auto item = static_cast(sender); @@ -753,9 +755,9 @@ void LabelFNTMultiLineAlignment::alignmentChanged(cocos2d::Ref *sender) this->snapArrowsToEdge(); } -void LabelFNTMultiLineAlignment::onTouchesBegan(const std::vector& touches, cocos2d::Event *event) +void LabelFNTMultiLineAlignment::onTouchesBegan(const std::vector& touches, cocos2d::Event* event) { - auto touch = touches[0]; + auto touch = touches[0]; auto location = touch->getLocationInView(); if (this->_arrows->getBoundingBox().containsPoint(location)) @@ -765,7 +767,7 @@ void LabelFNTMultiLineAlignment::onTouchesBegan(const std::vector& touch } } -void LabelFNTMultiLineAlignment::onTouchesEnded(const std::vector& touches, cocos2d::Event *event) +void LabelFNTMultiLineAlignment::onTouchesEnded(const std::vector& touches, cocos2d::Event* event) { _drag = false; this->snapArrowsToEdge(); @@ -773,20 +775,20 @@ void LabelFNTMultiLineAlignment::onTouchesEnded(const std::vector& touch this->_arrowsBar->setVisible(false); } -void LabelFNTMultiLineAlignment::onTouchesMoved(const std::vector& touches, cocos2d::Event *event) +void LabelFNTMultiLineAlignment::onTouchesMoved(const std::vector& touches, cocos2d::Event* event) { - if (! _drag) + if (!_drag) { return; } - auto touch = touches[0]; + auto touch = touches[0]; auto location = touch->getLocationInView(); auto winSize = Director::getInstance()->getWinSize(); - this->_arrows->setPosition(Vec2(MAX(MIN(location.x, ArrowsMax*winSize.width), ArrowsMin*winSize.width), - this->_arrows->getPosition().y)); + this->_arrows->setPosition(Vec2(MAX(MIN(location.x, ArrowsMax * winSize.width), ArrowsMin * winSize.width), + this->_arrows->getPosition().y)); float labelWidth = fabs(this->_arrows->getPosition().x - this->_label->getPosition().x) * 2; @@ -795,8 +797,8 @@ void LabelFNTMultiLineAlignment::onTouchesMoved(const std::vector& touch void LabelFNTMultiLineAlignment::snapArrowsToEdge() { - this->_arrows->setPosition(Vec2(this->_label->getPosition().x + this->_label->getContentSize().width/2, - this->_label->getPosition().y)); + this->_arrows->setPosition( + Vec2(this->_label->getPosition().x + this->_label->getContentSize().width / 2, this->_label->getPosition().y)); } /// LabelFNTMultiLineAlignmentUNICODE @@ -812,8 +814,8 @@ bool LabelFNTMultiLineAlignmentUNICODE::init() this->_menuItems[1]->setString("Spanish"); this->_menuItems[2]->setString("Ukrainian"); - auto ttfConfig = this->_label->getTTFConfig(); - ttfConfig.fontSize = 20; + auto ttfConfig = this->_label->getTTFConfig(); + ttfConfig.fontSize = 20; ttfConfig.fontFilePath = "fonts/tahoma.ttf"; this->_label->setTTFConfig(ttfConfig); @@ -861,7 +863,7 @@ std::string LabelFNTMultiLineAlignmentUNICODE::getItemString(cocos2d::MenuItemFo /// BMFontUnicodeNew LabelFNTUNICODELanguages::LabelFNTUNICODELanguages() { - auto strings = FileUtils::getInstance()->getValueMapFromFile("strings/LabelFNTUNICODELanguages.xml"); + auto strings = FileUtils::getInstance()->getValueMapFromFile("strings/LabelFNTUNICODELanguages.xml"); std::string chinese = strings["chinese1"].asString(); std::string russian = strings["russian"].asString(); std::string spanish = strings["spanish"].asString(); @@ -871,19 +873,19 @@ LabelFNTUNICODELanguages::LabelFNTUNICODELanguages() auto label1 = Label::createWithBMFont("fonts/arial-unicode-26.fnt", spanish, TextHAlignment::CENTER, 200); addChild(label1); - label1->setPosition(Vec2(s.width/2, s.height/5*3)); - + label1->setPosition(Vec2(s.width / 2, s.height / 5 * 3)); + auto label2 = Label::createWithBMFont("fonts/arial-unicode-26.fnt", chinese); addChild(label2); - label2->setPosition(Vec2(s.width/2, s.height/5*2.5)); + label2->setPosition(Vec2(s.width / 2, s.height / 5 * 2.5)); auto label3 = Label::createWithBMFont("fonts/arial-26-en-ru.fnt", russian); addChild(label3); - label3->setPosition(Vec2(s.width/2, s.height/5*2)); + label3->setPosition(Vec2(s.width / 2, s.height / 5 * 2)); auto label4 = Label::createWithBMFont("fonts/arial-unicode-26.fnt", japanese); addChild(label4); - label4->setPosition(Vec2(s.width/2, s.height/5*1.5)); + label4->setPosition(Vec2(s.width / 2, s.height / 5 * 1.5)); } std::string LabelFNTUNICODELanguages::title() const @@ -899,29 +901,26 @@ std::string LabelFNTUNICODELanguages::subtitle() const LabelFNTBounds::LabelFNTBounds() { auto s = Director::getInstance()->getWinSize(); - - auto layer = LayerColor::create(Color4B(128,128,128,255)); + + auto layer = LayerColor::create(Color4B(128, 128, 128, 255)); addChild(layer, -10); - + // LabelBMFont - auto label1 = Label::createWithBMFont("fonts/boundsTestFont.fnt", "Testing Glyph Designer", TextHAlignment::CENTER,s.width); + auto label1 = + Label::createWithBMFont("fonts/boundsTestFont.fnt", "Testing Glyph Designer", TextHAlignment::CENTER, s.width); addChild(label1); - label1->setPosition(Vec2(s.width/2, s.height/2)); + label1->setPosition(Vec2(s.width / 2, s.height / 2)); - auto drawNode = DrawNode::create(); + auto drawNode = DrawNode::create(); auto labelSize = label1->getContentSize(); auto origin = Director::getInstance()->getWinSize(); - - origin.width = origin.width / 2 - (labelSize.width / 2); + + origin.width = origin.width / 2 - (labelSize.width / 2); origin.height = origin.height / 2 - (labelSize.height / 2); - - Vec2 vertices[4]= - { - Vec2(origin.width, origin.height), - Vec2(labelSize.width + origin.width, origin.height), - Vec2(labelSize.width + origin.width, labelSize.height + origin.height), - Vec2(origin.width, labelSize.height + origin.height) - }; + + Vec2 vertices[4] = {Vec2(origin.width, origin.height), Vec2(labelSize.width + origin.width, origin.height), + Vec2(labelSize.width + origin.width, labelSize.height + origin.height), + Vec2(origin.width, labelSize.height + origin.height)}; drawNode->drawPoly(vertices, 4, true, Color4F(1.0f, 1.0f, 1.0f, 1.0f)); addChild(drawNode); } @@ -944,7 +943,8 @@ LabelFNTMultiFontAtlasNoRotation::LabelFNTMultiFontAtlasNoRotation() addChild(label1); label1->setPosition(Vec2(s.width / 2, s.height / 3 * 2)); - auto label2 = Label::createWithBMFont("fonts/geneva-32.fnt", "And this is Geneva", TextHAlignment::LEFT, 0, Rect(0, 128, 0, 0), false); + auto label2 = Label::createWithBMFont("fonts/geneva-32.fnt", "And this is Geneva", TextHAlignment::LEFT, 0, + Rect(0, 128, 0, 0), false); addChild(label2); label2->setPosition(Vec2(s.width / 2, s.height / 3 * 1)); } @@ -967,12 +967,14 @@ LabelFNTMultiFontAtlasWithRotation::LabelFNTMultiFontAtlasWithRotation() spriteCache->addSpriteFramesWithFile("fonts/bmfont-rotated-test.plist"); // Label BMFont - auto label1 = Label::createWithBMFont("fonts/helvetica-regular-32.fnt", "Helvetica with SubTextureKey", TextHAlignment::CENTER, 0, "helvetica-regular-32.png"); + auto label1 = Label::createWithBMFont("fonts/helvetica-regular-32.fnt", "Helvetica with SubTextureKey", + TextHAlignment::CENTER, 0, "helvetica-regular-32.png"); label1->setPosition(Vec2(s.width / 2, s.height / 3 * 2)); this->addChild(label1); const auto frame = spriteCache->getSpriteFrameByName("geneva-regular-32.png"); - auto label2 = Label::createWithBMFont("fonts/geneva-regular-32.fnt", "Geneva with Rect and Rotated", TextHAlignment::CENTER, 0, frame->getRectInPixels(), frame->isRotated()); + auto label2 = Label::createWithBMFont("fonts/geneva-regular-32.fnt", "Geneva with Rect and Rotated", + TextHAlignment::CENTER, 0, frame->getRectInPixels(), frame->isRotated()); label2->setPosition(Vec2(s.width / 2, s.height / 3 * 1)); this->addChild(label2); } @@ -993,8 +995,8 @@ LabelTTFLongLineWrapping::LabelTTFLongLineWrapping() // Long sentence TTFConfig ttfConfig("fonts/arial.ttf", 14); - auto label1 = Label::createWithTTF(ttfConfig, LongSentencesExample, TextHAlignment::CENTER,size.width); - label1->setPosition( Vec2(size.width/2, size.height/2) ); + auto label1 = Label::createWithTTF(ttfConfig, LongSentencesExample, TextHAlignment::CENTER, size.width); + label1->setPosition(Vec2(size.width / 2, size.height / 2)); label1->setAnchorPoint(Vec2(0.5f, 1.0f)); addChild(label1); } @@ -1015,21 +1017,21 @@ LabelTTFColor::LabelTTFColor() TTFConfig ttfConfig("fonts/arial.ttf", 18); // Green - auto label1 = Label::createWithTTF(ttfConfig,"Green", TextHAlignment::CENTER, size.width); - label1->setPosition(size.width/2, size.height * 0.5f); - label1->setTextColor( Color4B::GREEN ); + auto label1 = Label::createWithTTF(ttfConfig, "Green", TextHAlignment::CENTER, size.width); + label1->setPosition(size.width / 2, size.height * 0.5f); + label1->setTextColor(Color4B::GREEN); addChild(label1); // Red - auto label2 = Label::createWithTTF(ttfConfig,"Red", TextHAlignment::CENTER, size.width); - label2->setPosition(size.width/2, size.height * 0.65f); - label2->setTextColor( Color4B::RED ); + auto label2 = Label::createWithTTF(ttfConfig, "Red", TextHAlignment::CENTER, size.width); + label2->setPosition(size.width / 2, size.height * 0.65f); + label2->setTextColor(Color4B::RED); addChild(label2); // Blue - auto label3 = Label::createWithTTF(ttfConfig,"Blue", TextHAlignment::CENTER, size.width); - label3->setPosition(size.width/2, size.height * 0.35f); - label3->setTextColor( Color4B::BLUE ); + auto label3 = Label::createWithTTF(ttfConfig, "Blue", TextHAlignment::CENTER, size.width); + label3->setPosition(size.width / 2, size.height * 0.35f); + label3->setTextColor(Color4B::BLUE); addChild(label3); } @@ -1053,17 +1055,16 @@ LabelTTFDynamicAlignment::LabelTTFDynamicAlignment() addChild(_label); auto menu = Menu::create( - MenuItemFont::create("Left", CC_CALLBACK_1(LabelTTFDynamicAlignment::setAlignmentLeft, this)), - MenuItemFont::create("Center", CC_CALLBACK_1(LabelTTFDynamicAlignment::setAlignmentCenter, this)), - MenuItemFont::create("Right", CC_CALLBACK_1(LabelTTFDynamicAlignment::setAlignmentRight, this)), - nullptr); - + MenuItemFont::create("Left", CC_CALLBACK_1(LabelTTFDynamicAlignment::setAlignmentLeft, this)), + MenuItemFont::create("Center", CC_CALLBACK_1(LabelTTFDynamicAlignment::setAlignmentCenter, this)), + MenuItemFont::create("Right", CC_CALLBACK_1(LabelTTFDynamicAlignment::setAlignmentRight, this)), nullptr); + menu->alignItemsHorizontallyWithPadding(20); menu->setPosition(winSize.width / 2, winSize.height * 0.25f); addChild(menu); } -void LabelTTFDynamicAlignment::updateAlignment() +void LabelTTFDynamicAlignment::updateAlignment() { if (_label) { @@ -1105,21 +1106,20 @@ std::string LabelTTFDynamicAlignment::subtitle() const LabelTTFCJKWrappingTest::LabelTTFCJKWrappingTest() { auto size = Director::getInstance()->getWinSize(); - + auto drawNode = DrawNode::create(); drawNode->setAnchorPoint(Vec2(0, 0)); this->addChild(drawNode); - drawNode->drawSegment( - Vec2(size.width * 0.1f, size.height * 0.8f), - Vec2(size.width * 0.1, 0.0f), 1, Color4F(1.0f, 0.0f, 0.0f, 1.0f)); - drawNode->drawSegment( - Vec2(size.width * 0.85f, size.height * 0.8f), - Vec2(size.width * 0.85f, 0.0f), 1, Color4F(1.0f, 0.0f, 0.0f, 1.0f)); - + drawNode->drawSegment(Vec2(size.width * 0.1f, size.height * 0.8f), Vec2(size.width * 0.1, 0.0f), 1, + Color4F(1.0f, 0.0f, 0.0f, 1.0f)); + drawNode->drawSegment(Vec2(size.width * 0.85f, size.height * 0.8f), Vec2(size.width * 0.85f, 0.0f), 1, + Color4F(1.0f, 0.0f, 0.0f, 1.0f)); + TTFConfig ttfConfig("fonts/HKYuanMini.ttf", 25, GlyphCollection::DYNAMIC); - auto label1 = Label::createWithTTF(ttfConfig, - "你好,Cocos2d-x v3的New Label.", TextHAlignment::LEFT, size.width * 0.75f); - if(label1) { + auto label1 = + Label::createWithTTF(ttfConfig, "你好,Cocos2d-x v3的New Label.", TextHAlignment::LEFT, size.width * 0.75f); + if (label1) + { label1->setTextColor(Color4B(128, 255, 255, 255)); label1->setPosition(Vec2(size.width * 0.1f, size.height * 0.6f)); label1->setAnchorPoint(Vec2(0.0f, 0.5f)); @@ -1130,18 +1130,20 @@ LabelTTFCJKWrappingTest::LabelTTFCJKWrappingTest() label1->setTTFConfig(ttfConfig); } - auto label2 = Label::createWithTTF(ttfConfig, - "早上好,Cocos2d-x v3的New Label.", TextHAlignment::LEFT, size.width * 0.75f); - if(label2) { + auto label2 = + Label::createWithTTF(ttfConfig, "早上好,Cocos2d-x v3的New Label.", TextHAlignment::LEFT, size.width * 0.75f); + if (label2) + { label2->setTextColor(Color4B(255, 128, 255, 255)); label2->setPosition(Vec2(size.width * 0.1f, size.height * 0.4f)); label2->setAnchorPoint(Vec2(0.0f, 0.5f)); this->addChild(label2); } - auto label3 = Label::createWithTTF(ttfConfig, - "美好的一天啊美好的一天啊美好的一天啊", TextHAlignment::LEFT, size.width * 0.75f); - if(label3) { + auto label3 = Label::createWithTTF(ttfConfig, "美好的一天啊美好的一天啊美好的一天啊", TextHAlignment::LEFT, + size.width * 0.75f); + if (label3) + { label3->setTextColor(Color4B(255, 255, 128, 255)); label3->setPosition(Vec2(size.width * 0.1f, size.height * 0.2f)); label3->setAnchorPoint(Vec2(0.0f, 0.5f)); @@ -1157,7 +1159,7 @@ std::string LabelTTFCJKWrappingTest::title() const std::string LabelTTFCJKWrappingTest::subtitle() const { return "New Label with CJK + ASCII characters\n" - "Characters should stay in the correct position"; + "Characters should stay in the correct position"; } // @@ -1165,20 +1167,20 @@ std::string LabelTTFCJKWrappingTest::subtitle() const // LabelTTFUnicodeNew::LabelTTFUnicodeNew() { - auto strings = FileUtils::getInstance()->getValueMapFromFile("strings/LabelFNTUNICODELanguages.xml"); - std::string chinese = strings["chinese1"].asString(); - auto winSize = Director::getInstance()->getWinSize(); + auto strings = FileUtils::getInstance()->getValueMapFromFile("strings/LabelFNTUNICODELanguages.xml"); + std::string chinese = strings["chinese1"].asString(); + auto winSize = Director::getInstance()->getWinSize(); // Spanish auto label1 = Label::createWithTTF("Buen día, ¿cómo te llamas?", "fonts/arial.ttf", 23); label1->setPosition(winSize.width / 2, winSize.height * 0.65f); addChild(label1); - + // German auto label2 = Label::createWithTTF("In welcher Straße haben Sie gelebt?", "fonts/arial.ttf", 23); label2->setPosition(winSize.width / 2, winSize.height * 0.5f); addChild(label2); - + // Chinese auto label3 = Label::createWithTTF(chinese, "fonts/HKYuanMini.ttf", 24); label3->setPosition(winSize.width / 2, winSize.height * 0.35f); @@ -1201,8 +1203,8 @@ std::string LabelTTFUnicodeNew::subtitle() const LabelTTFEmoji::LabelTTFEmoji() { std::string emojiString = FileUtils::getInstance()->getStringFromFile("fonts/emoji.txt"); - auto winSize = Director::getInstance()->getWinSize(); - + auto winSize = Director::getInstance()->getWinSize(); + auto label = Label::createWithTTF(emojiString, "fonts/NotoEmoji-Regular.ttf", 23); label->setPosition(winSize.width / 2, winSize.height / 2); label->setDimensions(winSize.width, winSize.height); @@ -1221,30 +1223,28 @@ std::string LabelTTFEmoji::subtitle() const return "Uses the new Label with TTF. Testing Emoji"; } - LabelTTFFontsTestNew::LabelTTFFontsTestNew() { - const char *ttfpaths[] = { - "fonts/A Damn Mess.ttf", - "fonts/Abberancy.ttf", - "fonts/Abduction.ttf", - "fonts/American Typewriter.ttf", - "fonts/Paint Boy.ttf", - "fonts/Schwarzwald.ttf", - "fonts/Scissor Cuts.ttf", + const char* ttfpaths[] = { + "fonts/A Damn Mess.ttf", "fonts/Abberancy.ttf", "fonts/Abduction.ttf", "fonts/American Typewriter.ttf", + "fonts/Paint Boy.ttf", "fonts/Schwarzwald.ttf", "fonts/Scissor Cuts.ttf", }; int fontCount = sizeof(ttfpaths) / sizeof(ttfpaths[0]); - auto size = Director::getInstance()->getWinSize(); - TTFConfig ttfConfig(ttfpaths[0],20, GlyphCollection::NEHE); + auto size = Director::getInstance()->getWinSize(); + TTFConfig ttfConfig(ttfpaths[0], 20, GlyphCollection::NEHE); - for (int i = 0; i < fontCount; ++i) { + for (int i = 0; i < fontCount; ++i) + { ttfConfig.fontFilePath = ttfpaths[i]; - auto label = Label::createWithTTF(ttfConfig, ttfpaths[i], TextHAlignment::CENTER,0); - if( label ) { + auto label = Label::createWithTTF(ttfConfig, ttfpaths[i], TextHAlignment::CENTER, 0); + if (label) + { label->setPosition(size.width / 2, ((size.height * 0.6) / fontCount * i) + (size.height / 4)); addChild(label); - } else { + } + else + { log("ERROR: Cannot load: %s", ttfpaths[i]); } } @@ -1263,53 +1263,40 @@ std::string LabelTTFFontsTestNew::subtitle() const LabelTTFDistanceField::LabelTTFDistanceField() { auto size = Director::getInstance()->getWinSize(); - TTFConfig ttfConfig("fonts/arial.ttf", 40, GlyphCollection::DYNAMIC,nullptr,true); + TTFConfig ttfConfig("fonts/arial.ttf", 40, GlyphCollection::DYNAMIC, nullptr, true); - auto label1 = Label::createWithTTF(ttfConfig,"Distance Field",TextHAlignment::CENTER,size.width); - label1->setPosition( Vec2(size.width/2, size.height * 0.6f) ); - label1->setTextColor( Color4B::GREEN ); + auto label1 = Label::createWithTTF(ttfConfig, "Distance Field", TextHAlignment::CENTER, size.width); + label1->setPosition(Vec2(size.width / 2, size.height * 0.6f)); + label1->setTextColor(Color4B::GREEN); addChild(label1); - auto action = Sequence::create( - DelayTime::create(1.0f), - ScaleTo::create(6.0f,5.0f,5.0f), - ScaleTo::create(6.0f,1.0f,1.0f), - nullptr); + auto action = Sequence::create(DelayTime::create(1.0f), ScaleTo::create(6.0f, 5.0f, 5.0f), + ScaleTo::create(6.0f, 1.0f, 1.0f), nullptr); label1->runAction(RepeatForever::create(action)); // Draw the label border auto& labelContentSize = label1->getContentSize(); - auto borderDraw = DrawNode::create(); + auto borderDraw = DrawNode::create(); label1->addChild(borderDraw); borderDraw->clear(); borderDraw->setLineWidth(1); - Vec2 vertices[4] = - { - Vec2::ZERO, - Vec2(labelContentSize.width, 0.0f), - Vec2(labelContentSize.width, labelContentSize.height), - Vec2(0.0f, labelContentSize.height) - }; + Vec2 vertices[4] = {Vec2::ZERO, Vec2(labelContentSize.width, 0.0f), + Vec2(labelContentSize.width, labelContentSize.height), Vec2(0.0f, labelContentSize.height)}; borderDraw->drawPoly(vertices, 4, true, Color4F::RED); - auto label2 = Label::createWithTTF(ttfConfig,"Distance Field",TextHAlignment::CENTER,size.width); - label2->setPosition( Vec2(size.width/2, size.height * 0.3f) ); - label2->setTextColor( Color4B::RED ); + auto label2 = Label::createWithTTF(ttfConfig, "Distance Field", TextHAlignment::CENTER, size.width); + label2->setPosition(Vec2(size.width / 2, size.height * 0.3f)); + label2->setTextColor(Color4B::RED); addChild(label2); - + // Draw the label border auto& labelContentSize2 = label2->getContentSize(); - auto borderDraw2 = DrawNode::create(); + auto borderDraw2 = DrawNode::create(); label2->addChild(borderDraw2); borderDraw2->clear(); borderDraw2->setLineWidth(1); - Vec2 vertices2[4] = - { - Vec2::ZERO, - Vec2(labelContentSize2.width, 0.0f), - Vec2(labelContentSize2.width, labelContentSize2.height), - Vec2(0.0f, labelContentSize2.height) - }; + Vec2 vertices2[4] = {Vec2::ZERO, Vec2(labelContentSize2.width, 0.0f), + Vec2(labelContentSize2.width, labelContentSize2.height), Vec2(0.0f, labelContentSize2.height)}; borderDraw2->drawPoly(vertices2, 4, true, Color4F::GREEN); } @@ -1327,35 +1314,35 @@ LabelOutlineAndGlowTest::LabelOutlineAndGlowTest() { auto size = Director::getInstance()->getWinSize(); - auto bg = LayerColor::create(Color4B(200,191,231,255)); + auto bg = LayerColor::create(Color4B(200, 191, 231, 255)); this->addChild(bg); - TTFConfig ttfConfig("fonts/arial.ttf", 40, GlyphCollection::DYNAMIC,nullptr,true); + TTFConfig ttfConfig("fonts/arial.ttf", 40, GlyphCollection::DYNAMIC, nullptr, true); - auto label1 = Label::createWithTTF(ttfConfig,"Glow", TextHAlignment::CENTER, size.width); - label1->setPosition( Vec2(size.width/2, size.height*0.7) ); - label1->setTextColor( Color4B::GREEN ); + auto label1 = Label::createWithTTF(ttfConfig, "Glow", TextHAlignment::CENTER, size.width); + label1->setPosition(Vec2(size.width / 2, size.height * 0.7)); + label1->setTextColor(Color4B::GREEN); label1->enableGlow(Color4B::YELLOW); addChild(label1); ttfConfig.outlineSize = 1; - auto label2 = Label::createWithTTF(ttfConfig,"Outline", TextHAlignment::CENTER, size.width); - label2->setPosition( Vec2(size.width/2, size.height*0.6) ); - label2->setTextColor( Color4B::RED ); + auto label2 = Label::createWithTTF(ttfConfig, "Outline", TextHAlignment::CENTER, size.width); + label2->setPosition(Vec2(size.width / 2, size.height * 0.6)); + label2->setTextColor(Color4B::RED); label2->enableOutline(Color4B::BLUE); addChild(label2); ttfConfig.outlineSize = 2; - auto label3 = Label::createWithTTF(ttfConfig,"Outline", TextHAlignment::CENTER, size.width); - label3->setPosition( Vec2(size.width/2, size.height*0.48) ); - label3->setTextColor( Color4B::RED ); + auto label3 = Label::createWithTTF(ttfConfig, "Outline", TextHAlignment::CENTER, size.width); + label3->setPosition(Vec2(size.width / 2, size.height * 0.48)); + label3->setTextColor(Color4B::RED); label3->enableOutline(Color4B::BLUE); addChild(label3); ttfConfig.outlineSize = 3; - auto label4 = Label::createWithTTF(ttfConfig,"Outline", TextHAlignment::CENTER, size.width); - label4->setPosition( Vec2(size.width/2, size.height*0.36) ); - label4->setTextColor( Color4B::RED ); + auto label4 = Label::createWithTTF(ttfConfig, "Outline", TextHAlignment::CENTER, size.width); + label4->setPosition(Vec2(size.width / 2, size.height * 0.36)); + label4->setTextColor(Color4B::RED); label4->enableOutline(Color4B::BLUE); addChild(label4); } @@ -1370,10 +1357,7 @@ std::string LabelOutlineAndGlowTest::subtitle() const return "Testing outline and glow of label"; } -LabelShadowTest::LabelShadowTest() -{ - -} +LabelShadowTest::LabelShadowTest() {} void LabelShadowTest::onEnter() { @@ -1381,7 +1365,7 @@ void LabelShadowTest::onEnter() auto size = Director::getInstance()->getWinSize(); - auto bg = LayerColor::create(Color4B(200,191,231,255)); + auto bg = LayerColor::create(Color4B(200, 191, 231, 255)); this->addChild(bg); auto slider = ui::Slider::create(); @@ -1407,51 +1391,51 @@ void LabelShadowTest::onEnter() slider2->addEventListener(CC_CALLBACK_2(LabelShadowTest::sliderEvent, this)); addChild(slider2, 999); - float subtitleY = _subtitleLabel->getPosition().y; + float subtitleY = _subtitleLabel->getPosition().y; float horizontalSliderY = slider->getPosition().y; - float step = (subtitleY - horizontalSliderY) / 4; + float step = (subtitleY - horizontalSliderY) / 4; - TTFConfig ttfConfig("fonts/arial.ttf", 40, GlyphCollection::DYNAMIC,nullptr,true); + TTFConfig ttfConfig("fonts/arial.ttf", 40, GlyphCollection::DYNAMIC, nullptr, true); - shadowLabelTTF = Label::createWithTTF(ttfConfig,"TTF:Shadow"); - shadowLabelTTF->setPosition( Vec2(size.width/2, horizontalSliderY + step * (0.5f + 3)) ); - shadowLabelTTF->setTextColor( Color4B::RED ); + shadowLabelTTF = Label::createWithTTF(ttfConfig, "TTF:Shadow"); + shadowLabelTTF->setPosition(Vec2(size.width / 2, horizontalSliderY + step * (0.5f + 3))); + shadowLabelTTF->setTextColor(Color4B::RED); shadowLabelTTF->enableShadow(Color4B::BLACK); addChild(shadowLabelTTF); - shadowLabelOutline = Label::createWithTTF(ttfConfig,"TTF:Shadow"); - shadowLabelOutline->setPosition( Vec2(size.width/2, horizontalSliderY + step * (0.5f + 2)) ); - shadowLabelOutline->setTextColor( Color4B::RED ); - shadowLabelOutline->enableOutline(Color4B::YELLOW,1); + shadowLabelOutline = Label::createWithTTF(ttfConfig, "TTF:Shadow"); + shadowLabelOutline->setPosition(Vec2(size.width / 2, horizontalSliderY + step * (0.5f + 2))); + shadowLabelOutline->setTextColor(Color4B::RED); + shadowLabelOutline->enableOutline(Color4B::YELLOW, 1); shadowLabelOutline->enableShadow(Color4B::GREEN); addChild(shadowLabelOutline); - shadowLabelGrow = Label::createWithTTF(ttfConfig,"TTF:Shadow"); - shadowLabelGrow->setPosition( Vec2(size.width/2, horizontalSliderY + step * (0.5f + 1)) ); - shadowLabelGrow->setTextColor( Color4B::RED ); + shadowLabelGrow = Label::createWithTTF(ttfConfig, "TTF:Shadow"); + shadowLabelGrow->setPosition(Vec2(size.width / 2, horizontalSliderY + step * (0.5f + 1))); + shadowLabelGrow->setTextColor(Color4B::RED); shadowLabelGrow->enableGlow(Color4B::YELLOW); shadowLabelGrow->enableShadow(Color4B::BLUE); addChild(shadowLabelGrow); shadowLabelBMFont = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "BMFont:Shadow"); - shadowLabelBMFont->setPosition( Vec2(size.width/2, horizontalSliderY + step * 0.5f)); - shadowLabelBMFont->setColor( Color3B::RED ); + shadowLabelBMFont->setPosition(Vec2(size.width / 2, horizontalSliderY + step * 0.5f)); + shadowLabelBMFont->setColor(Color3B::RED); shadowLabelBMFont->enableShadow(Color4B::GREEN); addChild(shadowLabelBMFont); } -void LabelShadowTest::sliderEvent(Ref *pSender, ui::Slider::EventType type) +void LabelShadowTest::sliderEvent(Ref* pSender, ui::Slider::EventType type) { if (type == Slider::EventType::ON_PERCENTAGE_CHANGED) { - Slider* slider = (Slider*)this->getChildByTag(1); - Slider* slider2 = (Slider*)this->getChildByTag(2); - - auto offset = Size(slider->getPercent()-50,50 - slider2->getPercent()); - shadowLabelTTF->enableShadow(Color4B::BLACK,offset); - shadowLabelBMFont->enableShadow(Color4B::GREEN,offset); - shadowLabelOutline->enableShadow(Color4B::GREEN,offset); - shadowLabelGrow->enableShadow(Color4B::BLUE,offset); + Slider* slider = (Slider*)this->getChildByTag(1); + Slider* slider2 = (Slider*)this->getChildByTag(2); + + auto offset = Size(slider->getPercent() - 50, 50 - slider2->getPercent()); + shadowLabelTTF->enableShadow(Color4B::BLACK, offset); + shadowLabelBMFont->enableShadow(Color4B::GREEN, offset); + shadowLabelOutline->enableShadow(Color4B::GREEN, offset); + shadowLabelGrow->enableShadow(Color4B::BLUE, offset); } } @@ -1472,14 +1456,14 @@ LabelCharMapTest::LabelCharMapTest() auto label1 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.plist"); addChild(label1, 0, kTagSprite1); label1->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT); - label1->setPosition( Vec2(10,100) ); - label1->setOpacity( 200 ); + label1->setPosition(Vec2(10, 100)); + label1->setOpacity(200); auto label2 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.plist"); addChild(label2, 0, kTagSprite2); label2->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT); - label2->setPosition( Vec2(10,200) ); - label2->setOpacity( 32 ); + label2->setPosition(Vec2(10, 200)); + label2->setOpacity(32); schedule(CC_CALLBACK_1(LabelCharMapTest::step, this), "step_key"); } @@ -1515,24 +1499,24 @@ std::string LabelCharMapTest::subtitle() const //------------------------------------------------------------------ LabelCharMapColorTest::LabelCharMapColorTest() { - auto label1 = Label::createWithCharMap( "fonts/tuffy_bold_italic-charmap.plist"); + auto label1 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.plist"); addChild(label1, 0, kTagSprite1); label1->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT); - label1->setPosition( Vec2(10,100) ); - label1->setOpacity( 200 ); + label1->setPosition(Vec2(10, 100)); + label1->setOpacity(200); auto label2 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.plist"); addChild(label2, 0, kTagSprite2); label2->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT); - label2->setPosition( Vec2(10,200) ); - label2->setColor( Color3B::RED ); + label2->setPosition(Vec2(10, 200)); + label2->setColor(Color3B::RED); - auto fade = FadeOut::create(1.0f); + auto fade = FadeOut::create(1.0f); auto fade_in = fade->reverse(); - auto cb = CallFunc::create(CC_CALLBACK_0(LabelCharMapColorTest::actionFinishCallback, this)); - auto seq = Sequence::create(fade, fade_in, cb, nullptr); - auto repeat = RepeatForever::create( seq ); - label2->runAction( repeat ); + auto cb = CallFunc::create(CC_CALLBACK_0(LabelCharMapColorTest::actionFinishCallback, this)); + auto seq = Sequence::create(fade, fade_in, cb, nullptr); + auto repeat = RepeatForever::create(seq); + label2->runAction(repeat); _time = 0; @@ -1554,7 +1538,7 @@ void LabelCharMapColorTest::step(float dt) auto label2 = (Label*)getChildByTag(kTagSprite2); sprintf(string, "%d", (int)_time); - label2->setString( string ); + label2->setString(string); } std::string LabelCharMapColorTest::title() const @@ -1571,10 +1555,10 @@ LabelCrashTest::LabelCrashTest() { auto size = Director::getInstance()->getWinSize(); - TTFConfig ttfConfig("fonts/arial.ttf", 40, GlyphCollection::DYNAMIC,nullptr,true); + TTFConfig ttfConfig("fonts/arial.ttf", 40, GlyphCollection::DYNAMIC, nullptr, true); - auto label1 = Label::createWithTTF(ttfConfig,"Test崩溃123", TextHAlignment::CENTER, size.width); - label1->setPosition( Vec2(size.width/2, size.height/2) ); + auto label1 = Label::createWithTTF(ttfConfig, "Test崩溃123", TextHAlignment::CENTER, size.width); + label1->setPosition(Vec2(size.width / 2, size.height / 2)); addChild(label1); } @@ -1590,50 +1574,42 @@ std::string LabelCrashTest::subtitle() const LabelTTFOldNew::LabelTTFOldNew() { - auto s = Director::getInstance()->getWinSize(); - float delta = s.height/4; + auto s = Director::getInstance()->getWinSize(); + float delta = s.height / 4; auto label1 = Label::createWithSystemFont("Cocos2d-x Label Test", "arial", 24); addChild(label1, 0, kTagBitmapAtlas1); - label1->setPosition(Vec2(s.width/2, delta * 2)); + label1->setPosition(Vec2(s.width / 2, delta * 2)); label1->setColor(Color3B::RED); TTFConfig ttfConfig("fonts/arial.ttf", 24); auto label2 = Label::createWithTTF(ttfConfig, "Cocos2d-x Label Test"); addChild(label2, 0, kTagBitmapAtlas2); - label2->setPosition(Vec2(s.width/2, delta * 2)); + label2->setPosition(Vec2(s.width / 2, delta * 2)); - auto drawNode = DrawNode::create(); + auto drawNode = DrawNode::create(); auto labelSize = label1->getContentSize(); auto origin = Director::getInstance()->getWinSize(); - - origin.width = origin.width / 2 - (labelSize.width / 2); + + origin.width = origin.width / 2 - (labelSize.width / 2); origin.height = origin.height / 2 - (labelSize.height / 2); - - Vec2 vertices[4]= - { - Vec2(origin.width, origin.height), - Vec2(labelSize.width + origin.width, origin.height), - Vec2(labelSize.width + origin.width, labelSize.height + origin.height), - Vec2(origin.width, labelSize.height + origin.height) - }; + + Vec2 vertices[4] = {Vec2(origin.width, origin.height), Vec2(labelSize.width + origin.width, origin.height), + Vec2(labelSize.width + origin.width, labelSize.height + origin.height), + Vec2(origin.width, labelSize.height + origin.height)}; drawNode->drawPoly(vertices, 4, true, Color4F(1.0f, 0.0f, 0.0f, 1.0f)); - + labelSize = label2->getContentSize(); origin = Director::getInstance()->getWinSize(); - - origin.width = origin.width / 2 - (labelSize.width / 2); + + origin.width = origin.width / 2 - (labelSize.width / 2); origin.height = origin.height / 2 - (labelSize.height / 2); - - Vec2 vertices2[4]= - { - Vec2(origin.width, origin.height), - Vec2(labelSize.width + origin.width, origin.height), - Vec2(labelSize.width + origin.width, labelSize.height + origin.height), - Vec2(origin.width, labelSize.height + origin.height) - }; + + Vec2 vertices2[4] = {Vec2(origin.width, origin.height), Vec2(labelSize.width + origin.width, origin.height), + Vec2(labelSize.width + origin.width, labelSize.height + origin.height), + Vec2(origin.width, labelSize.height + origin.height)}; drawNode->drawPoly(vertices2, 4, true, Color4F(1.0f, 1.0f, 1.0f, 1.0f)); - + addChild(drawNode); } @@ -1653,11 +1629,11 @@ LabelFontNameTest::LabelFontNameTest() auto label1 = Label::create(); label1->setString("Default Font"); - label1->setPosition( Vec2(size.width/2, size.height * 0.7) ); + label1->setPosition(Vec2(size.width / 2, size.height * 0.7)); addChild(label1); - auto label3 = Label::createWithSystemFont("Marker Felt","Marker Felt",32); - label3->setPosition( Vec2(size.width/2, size.height * 0.5) ); + auto label3 = Label::createWithSystemFont("Marker Felt", "Marker Felt", 32); + label3->setPosition(Vec2(size.width / 2, size.height * 0.5)); addChild(label3); } @@ -1674,9 +1650,9 @@ std::string LabelFontNameTest::subtitle() const LabelAlignmentTest::LabelAlignmentTest() { auto blockSize = Size(200, 160); - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); - auto pos = Vec2((s.width - blockSize.width) / 2, (s.height - blockSize.height) / 2); + auto pos = Vec2((s.width - blockSize.width) / 2, (s.height - blockSize.height) / 2); auto colorLayer = LayerColor::create(Color4B(100, 100, 100, 255), blockSize.width, blockSize.height); colorLayer->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT); colorLayer->setPosition(pos); @@ -1687,17 +1663,15 @@ LabelAlignmentTest::LabelAlignmentTest() auto menu = Menu::create( MenuItemFont::create("Left", CC_CALLBACK_1(LabelAlignmentTest::setAlignmentLeft, this)), MenuItemFont::create("Center", CC_CALLBACK_1(LabelAlignmentTest::setAlignmentCenter, this)), - MenuItemFont::create("Right", CC_CALLBACK_1(LabelAlignmentTest::setAlignmentRight, this)), - nullptr); + MenuItemFont::create("Right", CC_CALLBACK_1(LabelAlignmentTest::setAlignmentRight, this)), nullptr); menu->alignItemsVerticallyWithPadding(4); menu->setPosition(Vec2(50.0f, s.height / 2 - 20)); this->addChild(menu); - menu = Menu::create( - MenuItemFont::create("Top", CC_CALLBACK_1(LabelAlignmentTest::setAlignmentTop, this)), - MenuItemFont::create("Middle", CC_CALLBACK_1(LabelAlignmentTest::setAlignmentMiddle, this)), - MenuItemFont::create("Bottom", CC_CALLBACK_1(LabelAlignmentTest::setAlignmentBottom, this)), - nullptr); + menu = Menu::create(MenuItemFont::create("Top", CC_CALLBACK_1(LabelAlignmentTest::setAlignmentTop, this)), + MenuItemFont::create("Middle", CC_CALLBACK_1(LabelAlignmentTest::setAlignmentMiddle, this)), + MenuItemFont::create("Bottom", CC_CALLBACK_1(LabelAlignmentTest::setAlignmentBottom, this)), + nullptr); menu->alignItemsVerticallyWithPadding(4); menu->setPosition(Vec2(s.width - 50, s.height / 2 - 20)); this->addChild(menu); @@ -1754,8 +1728,8 @@ LabelIssue4428Test::LabelIssue4428Test() { auto size = Director::getInstance()->getWinSize(); - auto label = Label::createWithBMFont( "fonts/bitmapFontTest3.fnt", "123\n456"); - label->setPosition(Vec2(size.width /2.0f, size.height / 2.0f)); + auto label = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", "123\n456"); + label->setPosition(Vec2(size.width / 2.0f, size.height / 2.0f)); label->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT); addChild(label); @@ -1782,7 +1756,7 @@ std::string LabelIssue4428Test::subtitle() const LabelIssue4999Test::LabelIssue4999Test() { - auto label = Label::createWithTTF("Smaller font test", "fonts/arial.ttf",5); + auto label = Label::createWithTTF("Smaller font test", "fonts/arial.ttf", 5); label->setPosition(VisibleRect::center()); label->setAnchorPoint(Vec2::ANCHOR_MIDDLE); addChild(label); @@ -1802,14 +1776,14 @@ LabelLineHeightTest::LabelLineHeightTest() { auto size = Director::getInstance()->getWinSize(); - auto bg = LayerColor::create(Color4B(200,191,231,255)); + auto bg = LayerColor::create(Color4B(200, 191, 231, 255)); this->addChild(bg); - TTFConfig ttfConfig("fonts/arial.ttf", 25, GlyphCollection::DYNAMIC,nullptr,false); + TTFConfig ttfConfig("fonts/arial.ttf", 25, GlyphCollection::DYNAMIC, nullptr, false); - label = Label::createWithTTF(ttfConfig,"Test\nLine\nHeight"); - label->setPosition( Vec2(size.width/2, size.height*0.5f) ); - label->setTextColor( Color4B::RED ); + label = Label::createWithTTF(ttfConfig, "Test\nLine\nHeight"); + label->setPosition(Vec2(size.width / 2, size.height * 0.5f)); + label->setTextColor(Color4B::RED); addChild(label); auto slider = ui::Slider::create(); @@ -1823,11 +1797,11 @@ LabelLineHeightTest::LabelLineHeightTest() addChild(slider); } -void LabelLineHeightTest::sliderEvent(Ref *sender, ui::Slider::EventType type) +void LabelLineHeightTest::sliderEvent(Ref* sender, ui::Slider::EventType type) { if (type == Slider::EventType::ON_PERCENTAGE_CHANGED) { - Slider* slider = (Slider*)sender; + Slider* slider = (Slider*)sender; label->setLineHeight(slider->getPercent()); } } @@ -1846,14 +1820,14 @@ LabelAdditionalKerningTest::LabelAdditionalKerningTest() { auto size = Director::getInstance()->getWinSize(); - auto bg = LayerColor::create(Color4B(200,191,231,255)); + auto bg = LayerColor::create(Color4B(200, 191, 231, 255)); this->addChild(bg); - TTFConfig ttfConfig("fonts/arial.ttf", 40, GlyphCollection::DYNAMIC,nullptr,false); + TTFConfig ttfConfig("fonts/arial.ttf", 40, GlyphCollection::DYNAMIC, nullptr, false); - label = Label::createWithTTF(ttfConfig,"Test additional kerning"); - label->setPosition(size.width/2, size.height * 0.5f); - label->setTextColor( Color4B::RED ); + label = Label::createWithTTF(ttfConfig, "Test additional kerning"); + label->setPosition(size.width / 2, size.height * 0.5f); + label->setTextColor(Color4B::RED); addChild(label); auto slider = ui::Slider::create(); @@ -1867,11 +1841,11 @@ LabelAdditionalKerningTest::LabelAdditionalKerningTest() addChild(slider); } -void LabelAdditionalKerningTest::sliderEvent(Ref *sender, ui::Slider::EventType type) +void LabelAdditionalKerningTest::sliderEvent(Ref* sender, ui::Slider::EventType type) { if (type == Slider::EventType::ON_PERCENTAGE_CHANGED) { - Slider* slider = (Slider*)sender; + Slider* slider = (Slider*)sender; label->setAdditionalKerning(slider->getPercent()); } } @@ -1889,7 +1863,7 @@ std::string LabelAdditionalKerningTest::subtitle() const LabelIssue8492Test::LabelIssue8492Test() { auto label = Label::createWithBMFont("fonts/bitmapFontChinese.fnt", "中国中国中国中国中国"); - label->setDimensions(5,100); + label->setDimensions(5, 100); label->setPosition(VisibleRect::center()); addChild(label); } @@ -1906,8 +1880,8 @@ std::string LabelIssue8492Test::subtitle() const LabelMultilineWithOutline::LabelMultilineWithOutline() { - auto label = Label::createWithTTF("Multi-line text\nwith\noutline feature", "fonts/arial.ttf", 24); - label->enableOutline(Color4B::ORANGE,1); + auto label = Label::createWithTTF("Multi-line text\nwith\noutline feature", "fonts/arial.ttf", 24); + label->enableOutline(Color4B::ORANGE, 1); label->setPosition(VisibleRect::center()); addChild(label); } @@ -1922,16 +1896,15 @@ std::string LabelMultilineWithOutline::subtitle() const return "end in string 'outline feature'"; } - LabelIssue9255Test::LabelIssue9255Test() { - Size s = Director::getInstance()->getWinSize(); + Size s = Director::getInstance()->getWinSize(); auto parent = Node::create(); - parent->setPosition(s.width/2, s.height/2); + parent->setPosition(s.width / 2, s.height / 2); parent->setVisible(false); this->addChild(parent); - auto label = Label::createWithTTF("Crashed!!!", "fonts/HKYuanMini.ttf", 24); + auto label = Label::createWithTTF("Crashed!!!", "fonts/HKYuanMini.ttf", 24); label->setPosition(VisibleRect::center()); parent->addChild(label); } @@ -1948,7 +1921,7 @@ std::string LabelIssue9255Test::subtitle() const LabelSmallDimensionsTest::LabelSmallDimensionsTest() { - auto label = Label::createWithSystemFont("Hello World!", "fonts/arial.ttf", 24, Size(30.0f,100.0f)); + auto label = Label::createWithSystemFont("Hello World!", "fonts/arial.ttf", 24, Size(30.0f, 100.0f)); label->setPosition(VisibleRect::center()); addChild(label); } @@ -1968,13 +1941,13 @@ LabelIssue10089Test::LabelIssue10089Test() auto center = VisibleRect::center(); auto labelA = Label::createWithSystemFont("create label with system font", "fonts/arial.ttf", 24); - auto size = labelA->getContentSize(); + auto size = labelA->getContentSize(); labelA->setDimensions(size.width, size.height); labelA->setPosition(center.x, center.y + 50); addChild(labelA); auto labelB = Label::createWithTTF("create label with TTF", "fonts/arial.ttf", 24); - size = labelB->getContentSize(); + size = labelB->getContentSize(); labelB->setDimensions(size.width, size.height); labelB->setPosition(center.x, center.y - 50); addChild(labelB); @@ -2056,9 +2029,8 @@ LabelIssue11576Test::LabelIssue11576Test() label->getLetter(index); } - this->runAction(Sequence::create(DelayTime::create(2.0f), CallFunc::create([label](){ - label->setString("Hello World!"); - }), nullptr)); + this->runAction(Sequence::create(DelayTime::create(2.0f), + CallFunc::create([label]() { label->setString("Hello World!"); }), nullptr)); label->setPosition(center.x, center.y); addChild(label); @@ -2105,17 +2077,13 @@ LabelIssue12409Test::LabelIssue12409Test() addChild(label); auto labelSize = label->getContentSize(); - auto winSize = Director::getInstance()->getWinSize(); + auto winSize = Director::getInstance()->getWinSize(); Vec2 labelOrigin; - labelOrigin.x = winSize.width / 2 - (labelSize.width / 2); - labelOrigin.y = winSize.height / 2 - (labelSize.height / 2); - Vec2 vertices[4] = - { - Vec2(labelOrigin.x, labelOrigin.y), - Vec2(labelOrigin.x + labelSize.width, labelOrigin.y), - Vec2(labelOrigin.x + labelSize.width, labelOrigin.y + labelSize.height), - Vec2(labelOrigin.x, labelOrigin.y + labelSize.height) - }; + labelOrigin.x = winSize.width / 2 - (labelSize.width / 2); + labelOrigin.y = winSize.height / 2 - (labelSize.height / 2); + Vec2 vertices[4] = {Vec2(labelOrigin.x, labelOrigin.y), Vec2(labelOrigin.x + labelSize.width, labelOrigin.y), + Vec2(labelOrigin.x + labelSize.width, labelOrigin.y + labelSize.height), + Vec2(labelOrigin.x, labelOrigin.y + labelSize.height)}; auto drawNode = DrawNode::create(); drawNode->drawPoly(vertices, 4, true, Color4F::WHITE); @@ -2140,13 +2108,13 @@ LabelAddChildTest::LabelAddChildTest() label->setPosition(center.x, center.y); addChild(label); - auto jump = JumpBy::create(1.0f, Vec2::ZERO, 60, 1); + auto jump = JumpBy::create(1.0f, Vec2::ZERO, 60, 1); auto jump_4ever = RepeatForever::create(jump); label->runAction(jump_4ever); auto spite = Sprite::create("Images/SpookyPeas.png"); spite->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT); - spite->setPosition(label->getContentSize().width, label->getContentSize().height/2); + spite->setPosition(label->getContentSize().width, label->getContentSize().height / 2); label->addChild(spite); } @@ -2185,8 +2153,7 @@ LabelIssue11585Test::LabelIssue11585Test() label->getLetter(0)->setColor(Color3B::RED); label->getLetter(1)->setColor(Color3B::GREEN); label->getLetter(2)->setColor(Color3B::BLUE); - auto action = RepeatForever::create(Sequence::create( - FadeOut::create(2), FadeIn::create(2),nullptr)); + auto action = RepeatForever::create(Sequence::create(FadeOut::create(2), FadeIn::create(2), nullptr)); label->runAction(action); } @@ -2207,9 +2174,9 @@ LabelIssue10688Test::LabelIssue10688Test() auto label = Label::createWithTTF("Glow MenuItemLabel", "fonts/arial.ttf", 30); label->setTextColor(Color4B::RED); label->enableGlow(Color4B::YELLOW); - auto menuItem1 = MenuItemLabel::create(label, [](Ref*){}); + auto menuItem1 = MenuItemLabel::create(label, [](Ref*) {}); menuItem1->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT); - menuItem1->setPosition(center.x - label->getContentSize().width/2, center.y); + menuItem1->setPosition(center.x - label->getContentSize().width / 2, center.y); auto menu = Menu::create(menuItem1, NULL); menu->setPosition(Vec2::ZERO); @@ -2236,9 +2203,7 @@ LabelIssue13202Test::LabelIssue13202Test() label->getContentSize(); label->setString("A"); - this->scheduleOnce([](float dt){ - FontAtlasCache::purgeCachedData(); - }, 0.15f, "FontAtlasCache::purgeCachedData"); + this->scheduleOnce([](float dt) { FontAtlasCache::purgeCachedData(); }, 0.15f, "FontAtlasCache::purgeCachedData"); } std::string LabelIssue13202Test::title() const @@ -2270,18 +2235,18 @@ std::string LabelIssue9500Test::subtitle() const return "Spaces should not be lost if label created with Fingerpop.ttf"; } -ControlStepper *LabelLayoutBaseTest::makeControlStepper() +ControlStepper* LabelLayoutBaseTest::makeControlStepper() { - auto minusSprite = Sprite::create("extensions/stepper-minus.png"); - auto plusSprite = Sprite::create("extensions/stepper-plus.png"); - + auto minusSprite = Sprite::create("extensions/stepper-minus.png"); + auto plusSprite = Sprite::create("extensions/stepper-plus.png"); + return ControlStepper::create(minusSprite, plusSprite); } LabelLayoutBaseTest::LabelLayoutBaseTest() { auto size = Director::getInstance()->getVisibleSize(); - + this->initTestLabel(size); this->initFontSizeChange(size); @@ -2301,19 +2266,18 @@ void LabelLayoutBaseTest::initFontSizeChange(const cocos2d::Size& size) auto fontSizeLabel = Label::createWithSystemFont("font size:20", "Arial", 10); fontSizeLabel->setName("fontSize"); - ControlStepper *stepper = this->makeControlStepper(); - stepper->setPosition(size.width * 0.5 - stepper->getContentSize().width / 2, - size.height * 0.8); + ControlStepper* stepper = this->makeControlStepper(); + stepper->setPosition(size.width * 0.5 - stepper->getContentSize().width / 2, size.height * 0.8); stepper->setValue(20); - stepper->addTargetWithActionForControlEvents(this, - cccontrol_selector(LabelLayoutBaseTest::valueChanged), + stepper->addTargetWithActionForControlEvents(this, cccontrol_selector(LabelLayoutBaseTest::valueChanged), Control::EventType::VALUE_CHANGED); this->addChild(stepper); stepper->setName("stepper"); stepper->setScale(0.5); - fontSizeLabel->setPosition(stepper->getPosition() - - Vec2(stepper->getContentSize().width/2 + fontSizeLabel->getContentSize().width/2,0.0f)); + fontSizeLabel->setPosition( + stepper->getPosition() - + Vec2(stepper->getContentSize().width / 2 + fontSizeLabel->getContentSize().width / 2, 0.0f)); this->addChild(fontSizeLabel); } @@ -2324,20 +2288,21 @@ void LabelLayoutBaseTest::initWrapOption(const cocos2d::Size& size) label->setPosition(Vec2(size.width * 0.8f - 100, size.height * 0.8f)); this->addChild(label); - CheckBox* checkBox = CheckBox::create("cocosui/check_box_normal.png", - "cocosui/check_box_normal_press.png", - "cocosui/check_box_active.png", - "cocosui/check_box_normal_disable.png", + CheckBox* checkBox = CheckBox::create("cocosui/check_box_normal.png", "cocosui/check_box_normal_press.png", + "cocosui/check_box_active.png", "cocosui/check_box_normal_disable.png", "cocosui/check_box_active_disable.png"); checkBox->setPosition(Vec2(size.width * 0.8f - 55, size.height * 0.8f)); checkBox->setScale(0.5); checkBox->setSelected(true); checkBox->setName("toggleWrap"); - checkBox->addEventListener([=](Ref* ref, CheckBox::EventType event){ - if (event == CheckBox::EventType::SELECTED) { + checkBox->addEventListener([=](Ref* ref, CheckBox::EventType event) { + if (event == CheckBox::EventType::SELECTED) + { _label->enableWrap(true); - }else{ + } + else + { _label->enableWrap(false); } this->updateDrawNodeSize(_label->getContentSize()); @@ -2351,55 +2316,53 @@ void LabelLayoutBaseTest::initToggleLabelTypeOption(const cocos2d::Size& size) label->setColor(Color3B::WHITE); label->setPosition(Vec2(size.width * 0.8f + 15, size.height * 0.8f)); this->addChild(label); - - CheckBox* checkBox = CheckBox::create("cocosui/check_box_normal.png", - "cocosui/check_box_normal_press.png", - "cocosui/check_box_active.png", - "cocosui/check_box_normal_disable.png", + + CheckBox* checkBox = CheckBox::create("cocosui/check_box_normal.png", "cocosui/check_box_normal_press.png", + "cocosui/check_box_active.png", "cocosui/check_box_normal_disable.png", "cocosui/check_box_active_disable.png"); checkBox->setPosition(Vec2(size.width * 0.8f + 70, size.height * 0.8f)); checkBox->setScale(0.5); checkBox->setName("toggleType"); checkBox->setSelected(true); - auto stepper = (ControlStepper*)this->getChildByName("stepper"); + auto stepper = (ControlStepper*)this->getChildByName("stepper"); - checkBox->addEventListener([=](Ref* ref, CheckBox::EventType event){ - float fontSize = stepper->getValue(); + checkBox->addEventListener([=](Ref* ref, CheckBox::EventType event) { + float fontSize = stepper->getValue(); - if (event == CheckBox::EventType::SELECTED) { - _labelType = 0; - auto ttfConfig = _label->getTTFConfig(); + if (event == CheckBox::EventType::SELECTED) + { + _labelType = 0; + auto ttfConfig = _label->getTTFConfig(); ttfConfig.fontSize = fontSize; _label->setTTFConfig(ttfConfig); - }else{ + } + else + { _labelType = 1; _label->setBMFontFilePath("fonts/enligsh-chinese.fnt"); _label->setBMFontSize(fontSize); } }); this->addChild(checkBox); - } void LabelLayoutBaseTest::initAlignmentOption(const cocos2d::Size& size) { - //add text alignment settings + // add text alignment settings MenuItemFont::setFontSize(30); auto menu = Menu::create( MenuItemFont::create("Left", CC_CALLBACK_1(LabelLayoutBaseTest::setAlignmentLeft, this)), MenuItemFont::create("Center", CC_CALLBACK_1(LabelLayoutBaseTest::setAlignmentCenter, this)), - MenuItemFont::create("Right", CC_CALLBACK_1(LabelLayoutBaseTest::setAlignmentRight, this)), - nullptr); + MenuItemFont::create("Right", CC_CALLBACK_1(LabelLayoutBaseTest::setAlignmentRight, this)), nullptr); menu->alignItemsVerticallyWithPadding(4); menu->setPosition(Vec2(50.0f, size.height / 2 - 20)); this->addChild(menu); - menu = Menu::create( - MenuItemFont::create("Top", CC_CALLBACK_1(LabelLayoutBaseTest::setAlignmentTop, this)), - MenuItemFont::create("Middle", CC_CALLBACK_1(LabelLayoutBaseTest::setAlignmentMiddle, this)), - MenuItemFont::create("Bottom", CC_CALLBACK_1(LabelLayoutBaseTest::setAlignmentBottom, this)), - nullptr); + menu = Menu::create(MenuItemFont::create("Top", CC_CALLBACK_1(LabelLayoutBaseTest::setAlignmentTop, this)), + MenuItemFont::create("Middle", CC_CALLBACK_1(LabelLayoutBaseTest::setAlignmentMiddle, this)), + MenuItemFont::create("Bottom", CC_CALLBACK_1(LabelLayoutBaseTest::setAlignmentBottom, this)), + nullptr); menu->alignItemsVerticallyWithPadding(4); menu->setPosition(Vec2(size.width - 50, size.height / 2 - 20)); this->addChild(menu); @@ -2429,22 +2392,24 @@ void LabelLayoutBaseTest::initSliders(const cocos2d::Size& size) addChild(slider2); auto winSize = Director::getInstance()->getVisibleSize(); - slider->addEventListener([=](Ref* ref, Slider::EventType event){ - float percent = slider->getPercent(); - auto labelSize = _label->getContentSize(); + slider->addEventListener([=](Ref* ref, Slider::EventType event) { + float percent = slider->getPercent(); + auto labelSize = _label->getContentSize(); auto drawNodeSize = Size(percent / 100.0 * winSize.width, labelSize.height); - if(drawNodeSize.width <=0){ + if (drawNodeSize.width <= 0) + { drawNodeSize.width = 0.1f; } _label->setDimensions(drawNodeSize.width, drawNodeSize.height); this->updateDrawNodeSize(drawNodeSize); }); - slider2->addEventListener([=](Ref* ref, Slider::EventType event){ - float percent = slider2->getPercent(); - auto labelSize = _label->getContentSize(); - auto drawNodeSize = Size( labelSize.width, percent / 100.0 * winSize.height); - if(drawNodeSize.height <= 0){ + slider2->addEventListener([=](Ref* ref, Slider::EventType event) { + float percent = slider2->getPercent(); + auto labelSize = _label->getContentSize(); + auto drawNodeSize = Size(labelSize.width, percent / 100.0 * winSize.height); + if (drawNodeSize.height <= 0) + { drawNodeSize.height = 0.1f; } _label->setDimensions(drawNodeSize.width, drawNodeSize.height); @@ -2456,7 +2421,7 @@ void LabelLayoutBaseTest::initTestLabel(const cocos2d::Size& size) { auto center = VisibleRect::center(); _label = Label::createWithTTF("五六七八This is a very long sentence一二三四.", "fonts/HKYuanMini.ttf", 20); - _label->setDimensions(size.width/2, size.height/2); + _label->setDimensions(size.width / 2, size.height / 2); _label->setPosition(center); _label->setName("Label"); _label->setString("五六七八This is a very long sentence一二三."); @@ -2473,7 +2438,6 @@ void LabelLayoutBaseTest::initDrawNode(const cocos2d::Size& size) this->updateDrawNodeSize(_label->getContentSize()); } - void LabelLayoutBaseTest::setAlignmentLeft(Ref* sender) { _label->setHorizontalAlignment(TextHAlignment::LEFT); @@ -2504,56 +2468,55 @@ void LabelLayoutBaseTest::setAlignmentBottom(Ref* sender) _label->setVerticalAlignment(TextVAlignment::BOTTOM); } - -void LabelLayoutBaseTest::valueChanged(cocos2d::Ref *sender, cocos2d::extension::Control::EventType controlEvent) +void LabelLayoutBaseTest::valueChanged(cocos2d::Ref* sender, cocos2d::extension::Control::EventType controlEvent) { ControlStepper* pControl = (ControlStepper*)sender; // Change value of label. auto fontSizeLabel = (Label*)this->getChildByName("fontSize"); - float fontSize = (float)pControl->getValue(); + float fontSize = (float)pControl->getValue(); fontSizeLabel->setString(StringUtils::format("font size:%d", (int)fontSize)); - - if (_labelType == 0) { - auto ttfConfig = _label->getTTFConfig(); + + if (_labelType == 0) + { + auto ttfConfig = _label->getTTFConfig(); ttfConfig.fontSize = fontSize; _label->setTTFConfig(ttfConfig); - }else if(_labelType == 1){ + } + else if (_labelType == 1) + { _label->setBMFontSize(fontSize); - }else if (_labelType == 2) { + } + else if (_labelType == 2) + { _label->setSystemFontSize(fontSize); } this->updateDrawNodeSize(_label->getContentSize()); - - //FIXME::When calling getLetter, the label Overflow feature will be invalid. -// auto letterSprite = _label->getLetter(1); -// auto moveBy = ScaleBy::create(1.0,2.0); -// letterSprite->stopAllActions(); -// letterSprite->runAction(Sequence::create(moveBy, moveBy->clone()->reverse(), nullptr )); -// -// CCLOG("label line height = %f", _label->getLineHeight()); + + // FIXME::When calling getLetter, the label Overflow feature will be invalid. + // auto letterSprite = _label->getLetter(1); + // auto moveBy = ScaleBy::create(1.0,2.0); + // letterSprite->stopAllActions(); + // letterSprite->runAction(Sequence::create(moveBy, moveBy->clone()->reverse(), nullptr )); + // + // CCLOG("label line height = %f", _label->getLineHeight()); } -void LabelLayoutBaseTest::updateDrawNodeSize(const cocos2d::Size &drawNodeSize) +void LabelLayoutBaseTest::updateDrawNodeSize(const cocos2d::Size& drawNodeSize) { auto origin = Director::getInstance()->getWinSize(); auto labelSize = _label->getContentSize(); - origin.width = origin.width / 2 - (labelSize.width / 2); + origin.width = origin.width / 2 - (labelSize.width / 2); origin.height = origin.height / 2 - (labelSize.height / 2); - Vec2 vertices[4]= - { - Vec2(origin.width, origin.height), - Vec2(drawNodeSize.width + origin.width, origin.height), - Vec2(drawNodeSize.width + origin.width, drawNodeSize.height + origin.height), - Vec2(origin.width, drawNodeSize.height + origin.height) - }; + Vec2 vertices[4] = {Vec2(origin.width, origin.height), Vec2(drawNodeSize.width + origin.width, origin.height), + Vec2(drawNodeSize.width + origin.width, drawNodeSize.height + origin.height), + Vec2(origin.width, drawNodeSize.height + origin.height)}; _drawNode->clear(); _drawNode->drawLine(vertices[0], vertices[1], Color4F(1.0f, 1.0f, 1.0f, 1.0f)); _drawNode->drawLine(vertices[0], vertices[3], Color4F(1.0f, 1.0f, 1.0f, 1.0f)); _drawNode->drawLine(vertices[2], vertices[3], Color4F(1.0f, 1.0f, 1.0f, 1.0f)); _drawNode->drawLine(vertices[1], vertices[2], Color4F(1.0f, 1.0f, 1.0f, 1.0f)); - } LabelWrapByWordTest::LabelWrapByWordTest() @@ -2562,7 +2525,6 @@ LabelWrapByWordTest::LabelWrapByWordTest() _label->setAdditionalKerning(2); _label->setVerticalAlignment(TextVAlignment::CENTER); _label->setOverflow(Label::Overflow::CLAMP); - } std::string LabelWrapByWordTest::title() const @@ -2577,13 +2539,12 @@ std::string LabelWrapByWordTest::subtitle() const LabelWrapByCharTest::LabelWrapByCharTest() { - _label->setLineBreakWithoutSpace(true); + _label->setLineBreakWithoutSpace(true); _label->setString("五六七八This \nis a very long sentence一二三四."); _label->setLineSpacing(5); _label->setAdditionalKerning(2); _label->setVerticalAlignment(TextVAlignment::TOP); _label->setOverflow(Label::Overflow::CLAMP); - } std::string LabelWrapByCharTest::title() const @@ -2601,8 +2562,9 @@ std::string LabelWrapByCharTest::subtitle() const LabelWrapNoBreakSpaceTest::LabelWrapNoBreakSpaceTest() { _label->setLineBreakWithoutSpace(false); - const char* no_break_space_utf8 = "\xC2\xA0"; // 0xA0 - no-break space - auto str = StringUtils::format("The price is $%s1.25. \n\nthe space between \"$\" and \"1.25\" is a no break space.", no_break_space_utf8); + const char* no_break_space_utf8 = "\xC2\xA0"; // 0xA0 - no-break space + auto str = StringUtils::format( + "The price is $%s1.25. \n\nthe space between \"$\" and \"1.25\" is a no break space.", no_break_space_utf8); _label->setString(str); _label->setVerticalAlignment(TextVAlignment::TOP); _label->setOverflow(Label::Overflow::CLAMP); @@ -2666,19 +2628,19 @@ LabelResizeTest::LabelResizeTest() _label->setVerticalAlignment(TextVAlignment::TOP); _label->setOverflow(Label::Overflow::RESIZE_HEIGHT); - this->updateDrawNodeSize(_label->getContentSize()); auto slider1 = (ui::Slider*)this->getChildByTag(1); - auto slider2 = (ui::Slider*)this->getChildByTag(2); - slider2->setVisible(false); - + auto slider2 = (ui::Slider*)this->getChildByTag(2); + slider2->setVisible(false); + auto winSize = Director::getInstance()->getVisibleSize(); - slider1->addEventListener([=](Ref* ref, Slider::EventType event){ - float percent = slider1->getPercent(); - auto drawNodeSize = Size(percent / 100.0 * winSize.width,_label->getContentSize().height); - if(drawNodeSize.height <= 0){ + slider1->addEventListener([=](Ref* ref, Slider::EventType event) { + float percent = slider1->getPercent(); + auto drawNodeSize = Size(percent / 100.0 * winSize.width, _label->getContentSize().height); + if (drawNodeSize.height <= 0) + { drawNodeSize.height = 0.1f; } _label->setDimensions(drawNodeSize.width, drawNodeSize.height); @@ -2687,32 +2649,32 @@ LabelResizeTest::LabelResizeTest() auto stepper = (ControlStepper*)this->getChildByName("stepper"); stepper->setValue(12); - + auto label = Label::createWithSystemFont("Char Line break:", "Arial", 10); label->setColor(Color3B::WHITE); label->setPosition(Vec2(winSize.width * 0.1f, winSize.height * 0.8f)); this->addChild(label); - - CheckBox* checkBox = CheckBox::create("cocosui/check_box_normal.png", - "cocosui/check_box_normal_press.png", - "cocosui/check_box_active.png", - "cocosui/check_box_normal_disable.png", + + CheckBox* checkBox = CheckBox::create("cocosui/check_box_normal.png", "cocosui/check_box_normal_press.png", + "cocosui/check_box_active.png", "cocosui/check_box_normal_disable.png", "cocosui/check_box_active_disable.png"); - checkBox->setPosition(Vec2(winSize.width * 0.2f , winSize.height * 0.8f)); + checkBox->setPosition(Vec2(winSize.width * 0.2f, winSize.height * 0.8f)); checkBox->setScale(0.5); checkBox->setSelected(false); checkBox->setName("LineBreak"); - - checkBox->addEventListener([=](Ref* ref, CheckBox::EventType event){ - if (event == CheckBox::EventType::SELECTED) { + + checkBox->addEventListener([=](Ref* ref, CheckBox::EventType event) { + if (event == CheckBox::EventType::SELECTED) + { _label->setLineBreakWithoutSpace(true); - }else{ + } + else + { _label->setLineBreakWithoutSpace(false); } this->updateDrawNodeSize(_label->getContentSize()); }); this->addChild(checkBox); - } std::string LabelResizeTest::title() const @@ -2732,19 +2694,19 @@ LabelToggleTypeTest::LabelToggleTypeTest() _label->setVerticalAlignment(TextVAlignment::CENTER); _label->setOverflow(Label::Overflow::NONE); - this->updateDrawNodeSize(_label->getContentSize()); auto slider1 = (ui::Slider*)this->getChildByTag(1); - auto slider2 = (ui::Slider*)this->getChildByTag(2); - slider2->setVisible(false); + auto slider2 = (ui::Slider*)this->getChildByTag(2); + slider2->setVisible(false); auto winSize = Director::getInstance()->getVisibleSize(); - slider1->addEventListener([=](Ref* ref, Slider::EventType event){ - float percent = slider1->getPercent(); - auto drawNodeSize = Size(percent / 100.0 * winSize.width,_label->getContentSize().height); - if(drawNodeSize.height <= 0){ + slider1->addEventListener([=](Ref* ref, Slider::EventType event) { + float percent = slider1->getPercent(); + auto drawNodeSize = Size(percent / 100.0 * winSize.width, _label->getContentSize().height); + if (drawNodeSize.height <= 0) + { drawNodeSize.height = 0.1f; } _label->setDimensions(drawNodeSize.width, drawNodeSize.height); @@ -2759,20 +2721,21 @@ LabelToggleTypeTest::LabelToggleTypeTest() label->setPosition(Vec2(winSize.width * 0.1f, winSize.height * 0.8f)); this->addChild(label); - CheckBox* checkBox = CheckBox::create("cocosui/check_box_normal.png", - "cocosui/check_box_normal_press.png", - "cocosui/check_box_active.png", - "cocosui/check_box_normal_disable.png", + CheckBox* checkBox = CheckBox::create("cocosui/check_box_normal.png", "cocosui/check_box_normal_press.png", + "cocosui/check_box_active.png", "cocosui/check_box_normal_disable.png", "cocosui/check_box_active_disable.png"); - checkBox->setPosition(Vec2(winSize.width * 0.2f , winSize.height * 0.8f)); + checkBox->setPosition(Vec2(winSize.width * 0.2f, winSize.height * 0.8f)); checkBox->setScale(0.5); checkBox->setSelected(false); checkBox->setName("LineBreak"); - checkBox->addEventListener([=](Ref* ref, CheckBox::EventType event){ - if (event == CheckBox::EventType::SELECTED) { + checkBox->addEventListener([=](Ref* ref, CheckBox::EventType event) { + if (event == CheckBox::EventType::SELECTED) + { _label->setLineBreakWithoutSpace(true); - }else{ + } + else + { _label->setLineBreakWithoutSpace(false); } this->updateDrawNodeSize(_label->getContentSize()); @@ -2785,32 +2748,32 @@ LabelToggleTypeTest::LabelToggleTypeTest() void LabelToggleTypeTest::initToggleCheckboxes() { const float BUTTON_WIDTH = 100; - float startPosX = 0; - Size winSize = Director::getInstance()->getVisibleSize(); + float startPosX = 0; + Size winSize = Director::getInstance()->getVisibleSize(); // Create a radio button group auto radioButtonGroup = RadioButtonGroup::create(); this->addChild(radioButtonGroup); // Create the radio buttons - static const int NUMBER_OF_BUTTONS = 4; - startPosX = winSize.width / 2.0f - (NUMBER_OF_BUTTONS - 1 ) * 0.5 * BUTTON_WIDTH - 30; + static const int NUMBER_OF_BUTTONS = 4; + startPosX = winSize.width / 2.0f - (NUMBER_OF_BUTTONS - 1) * 0.5 * BUTTON_WIDTH - 30; std::vector labelTypes = {"Normal", "Clamp", "Shrink", "RESIZE"}; - - for(int i = 0; i < NUMBER_OF_BUTTONS; ++i) + + for (int i = 0; i < NUMBER_OF_BUTTONS; ++i) { RadioButton* radioButton = RadioButton::create("cocosui/radio_button_off.png", "cocosui/radio_button_on.png"); - float posX = startPosX + BUTTON_WIDTH * i; + float posX = startPosX + BUTTON_WIDTH * i; radioButton->setPosition(Vec2(posX, winSize.height / 2.0f + 70)); radioButton->setScale(1.2f); radioButton->addEventListener(CC_CALLBACK_2(LabelToggleTypeTest::onChangedRadioButtonSelect, this)); radioButton->setTag(i); radioButtonGroup->addRadioButton(radioButton); this->addChild(radioButton); - + auto label = Label::createWithSystemFont(labelTypes.at(i), "Arial", 20); - label->setPosition(radioButton->getPosition() + Vec2(50.0f,0.0f)); + label->setPosition(radioButton->getPosition() + Vec2(50.0f, 0.0f)); this->addChild(label); } } @@ -2825,33 +2788,33 @@ std::string LabelToggleTypeTest::subtitle() const return ""; } - void LabelToggleTypeTest::onChangedRadioButtonSelect(RadioButton* radioButton, RadioButton::EventType type) { - if(radioButton == nullptr) + if (radioButton == nullptr) { return; } - + switch (type) { case RadioButton::EventType::SELECTED: { - switch (radioButton->getTag()) { - case 0: - _label->setOverflow(Label::Overflow::NONE); - break; - case 1: - _label->setOverflow(Label::Overflow::CLAMP); - break; - case 2: - _label->setOverflow(Label::Overflow::SHRINK); - break; - case 3: - _label->setOverflow(Label::Overflow::RESIZE_HEIGHT); - break; - default: - break; + switch (radioButton->getTag()) + { + case 0: + _label->setOverflow(Label::Overflow::NONE); + break; + case 1: + _label->setOverflow(Label::Overflow::CLAMP); + break; + case 2: + _label->setOverflow(Label::Overflow::SHRINK); + break; + case 3: + _label->setOverflow(Label::Overflow::RESIZE_HEIGHT); + break; + default: + break; } break; } @@ -2873,10 +2836,10 @@ LabelSystemFontTest::LabelSystemFontTest() _label->enableOutline(Color4B::RED, 1.0); _label->setString("This is a very\n 我爱你中国\n long sentence"); _labelType = 2; - + auto stepper = (ControlStepper*)this->getChildByName("stepper"); stepper->setEnabled(true); - + auto checkbox = (CheckBox*)(this->getChildByName("toggleType")); checkbox->setEnabled(false); @@ -2885,36 +2848,37 @@ LabelSystemFontTest::LabelSystemFontTest() auto slider1 = (ui::Slider*)this->getChildByTag(1); auto winSize = Director::getInstance()->getVisibleSize(); - slider1->addEventListener([=](Ref* ref, Slider::EventType event){ - float percent = slider1->getPercent(); - auto drawNodeSize = Size(percent / 100.0 * winSize.width,_label->getContentSize().height); - if(drawNodeSize.height <= 0){ + slider1->addEventListener([=](Ref* ref, Slider::EventType event) { + float percent = slider1->getPercent(); + auto drawNodeSize = Size(percent / 100.0 * winSize.width, _label->getContentSize().height); + if (drawNodeSize.height <= 0) + { drawNodeSize.height = 0.1f; } _label->setDimensions(drawNodeSize.width, drawNodeSize.height); this->updateDrawNodeSize(drawNodeSize); }); - auto label = Label::createWithSystemFont("char Line break:", "Arial", 10); label->setColor(Color3B::WHITE); label->setPosition(Vec2(winSize.width * 0.1f, winSize.height * 0.8f)); this->addChild(label); - CheckBox* checkBox = CheckBox::create("cocosui/check_box_normal.png", - "cocosui/check_box_normal_press.png", - "cocosui/check_box_active.png", - "cocosui/check_box_normal_disable.png", + CheckBox* checkBox = CheckBox::create("cocosui/check_box_normal.png", "cocosui/check_box_normal_press.png", + "cocosui/check_box_active.png", "cocosui/check_box_normal_disable.png", "cocosui/check_box_active_disable.png"); - checkBox->setPosition(Vec2(winSize.width * 0.2f , winSize.height * 0.8f)); + checkBox->setPosition(Vec2(winSize.width * 0.2f, winSize.height * 0.8f)); checkBox->setScale(0.5); checkBox->setSelected(false); checkBox->setName("LineBreak"); - checkBox->addEventListener([=](Ref* ref, CheckBox::EventType event){ - if (event == CheckBox::EventType::SELECTED) { + checkBox->addEventListener([=](Ref* ref, CheckBox::EventType event) { + if (event == CheckBox::EventType::SELECTED) + { _label->setLineBreakWithoutSpace(true); - }else{ + } + else + { _label->setLineBreakWithoutSpace(false); } this->updateDrawNodeSize(_label->getContentSize()); @@ -2930,23 +2894,23 @@ LabelSystemFontTest::LabelSystemFontTest() void LabelSystemFontTest::initToggleCheckboxes() { const float BUTTON_WIDTH = 100; - float startPosX = 0; - Size winSize = Director::getInstance()->getVisibleSize(); + float startPosX = 0; + Size winSize = Director::getInstance()->getVisibleSize(); // Create a radio button group auto radioButtonGroup = RadioButtonGroup::create(); this->addChild(radioButtonGroup); // Create the radio buttons - static const int NUMBER_OF_BUTTONS = 4; - startPosX = winSize.width / 2.0f - (NUMBER_OF_BUTTONS - 1 ) * 0.5 * BUTTON_WIDTH - 30; + static const int NUMBER_OF_BUTTONS = 4; + startPosX = winSize.width / 2.0f - (NUMBER_OF_BUTTONS - 1) * 0.5 * BUTTON_WIDTH - 30; std::vector labelTypes = {"Normal", "Clamp", "Shrink", "RESIZE"}; - for(int i = 0; i < NUMBER_OF_BUTTONS; ++i) + for (int i = 0; i < NUMBER_OF_BUTTONS; ++i) { RadioButton* radioButton = RadioButton::create("cocosui/radio_button_off.png", "cocosui/radio_button_on.png"); - float posX = startPosX + BUTTON_WIDTH * i; + float posX = startPosX + BUTTON_WIDTH * i; radioButton->setPosition(Vec2(posX, winSize.height / 2.0f + 70)); radioButton->setScale(1.2f); radioButton->addEventListener(CC_CALLBACK_2(LabelSystemFontTest::onChangedRadioButtonSelect, this)); @@ -2955,7 +2919,7 @@ void LabelSystemFontTest::initToggleCheckboxes() this->addChild(radioButton); auto label = Label::createWithSystemFont(labelTypes.at(i), "Arial", 20); - label->setPosition(radioButton->getPosition() + Vec2(50.0f,0.0f)); + label->setPosition(radioButton->getPosition() + Vec2(50.0f, 0.0f)); this->addChild(label); } } @@ -2970,10 +2934,9 @@ std::string LabelSystemFontTest::subtitle() const return ""; } - void LabelSystemFontTest::onChangedRadioButtonSelect(RadioButton* radioButton, RadioButton::EventType type) { - if(radioButton == nullptr) + if (radioButton == nullptr) { return; } @@ -2982,21 +2945,22 @@ void LabelSystemFontTest::onChangedRadioButtonSelect(RadioButton* radioButton, R { case RadioButton::EventType::SELECTED: { - switch (radioButton->getTag()) { - case 0: - _label->setOverflow(Label::Overflow::NONE); - break; - case 1: - _label->setOverflow(Label::Overflow::CLAMP); - break; - case 2: - _label->setOverflow(Label::Overflow::SHRINK); - break; - case 3: - _label->setOverflow(Label::Overflow::RESIZE_HEIGHT); - break; - default: - break; + switch (radioButton->getTag()) + { + case 0: + _label->setOverflow(Label::Overflow::NONE); + break; + case 1: + _label->setOverflow(Label::Overflow::CLAMP); + break; + case 2: + _label->setOverflow(Label::Overflow::SHRINK); + break; + case 3: + _label->setOverflow(Label::Overflow::RESIZE_HEIGHT); + break; + default: + break; } break; } @@ -3022,10 +2986,8 @@ LabelCharMapFontTest::LabelCharMapFontTest() checkbox->setEnabled(false); this->updateDrawNodeSize(_label->getContentSize()); - } - std::string LabelCharMapFontTest::title() const { return "CharMap Font Test"; @@ -3039,11 +3001,11 @@ std::string LabelCharMapFontTest::subtitle() const LabelIssue13846Test::LabelIssue13846Test() { auto center = VisibleRect::center(); - + auto label = Label::createWithTTF("12345", "fonts/arial.ttf", 26); label->setPosition(center); addChild(label); - + label->getLetter(2)->setVisible(false); } @@ -3064,7 +3026,8 @@ LabelRichText::LabelRichText() { auto center = VisibleRect::center(); - auto richText2 = RichText::createWithXML("Mixing UIRichText with non UIWidget code. For more samples, see the UIRichTextTest.cpp file"); + auto richText2 = RichText::createWithXML( + "Mixing UIRichText with non UIWidget code. For more samples, see the UIRichTextTest.cpp file"); if (richText2) { richText2->ignoreContentAdaptWithSize(false); @@ -3090,29 +3053,29 @@ LabelItalics::LabelItalics() auto s = Director::getInstance()->getWinSize(); // LabelBMFont - auto label1 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "hello non-italics", TextHAlignment::CENTER, s.width); + auto label1 = + Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "hello non-italics", TextHAlignment::CENTER, s.width); addChild(label1, 0, kTagBitmapAtlas1); - label1->setPosition(Vec2(s.width/2, s.height*4/6)); + label1->setPosition(Vec2(s.width / 2, s.height * 4 / 6)); // you can enable italics by calling this method _label1a = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "hello italics", TextHAlignment::CENTER, s.width); addChild(_label1a, 0, kTagBitmapAtlas1); - _label1a->setPosition(Vec2(s.width/2, s.height*3/6)); + _label1a->setPosition(Vec2(s.width / 2, s.height * 3 / 6)); // you can enable italics by calling this method _label1a->enableItalics(); - // LabelTTF - TTFConfig ttfConfig("fonts/arial.ttf",24); - auto label2 = Label::createWithTTF(ttfConfig, "hello non-italics", TextHAlignment::CENTER,s.width); + TTFConfig ttfConfig("fonts/arial.ttf", 24); + auto label2 = Label::createWithTTF(ttfConfig, "hello non-italics", TextHAlignment::CENTER, s.width); addChild(label2, 0, kTagBitmapAtlas2); - label2->setPosition(Vec2(s.width/2, s.height*2/6)); + label2->setPosition(Vec2(s.width / 2, s.height * 2 / 6)); // or by setting the italics parameter on TTFConfig ttfConfig.italics = true; - _label2a = Label::createWithTTF(ttfConfig, "hello italics", TextHAlignment::CENTER,s.width); + _label2a = Label::createWithTTF(ttfConfig, "hello italics", TextHAlignment::CENTER, s.width); addChild(_label2a, 0, kTagBitmapAtlas2); - _label2a->setPosition(Vec2(s.width/2, s.height*1/6)); + _label2a->setPosition(Vec2(s.width / 2, s.height * 1 / 6)); auto menuItem = MenuItemFont::create("disable italics", [&](cocos2d::Ref* sender) { _label2a->disableEffect(LabelEffect::ITALICS); @@ -3142,29 +3105,29 @@ LabelBold::LabelBold() auto s = Director::getInstance()->getWinSize(); // LabelBMFont - auto label1 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "hello non-bold", TextHAlignment::CENTER, s.width); + auto label1 = + Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "hello non-bold", TextHAlignment::CENTER, s.width); addChild(label1, 0, kTagBitmapAtlas1); - label1->setPosition(Vec2(s.width/2, s.height*4/6)); + label1->setPosition(Vec2(s.width / 2, s.height * 4 / 6)); // you can enable italics by calling this method _label1a = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "hello bold", TextHAlignment::CENTER, s.width); addChild(_label1a, 0, kTagBitmapAtlas1); - _label1a->setPosition(Vec2(s.width/2, s.height*3/6)); + _label1a->setPosition(Vec2(s.width / 2, s.height * 3 / 6)); // you can enable italics by calling this method _label1a->enableBold(); - // LabelTTF - TTFConfig ttfConfig("fonts/arial.ttf",24); - auto label2 = Label::createWithTTF(ttfConfig, "hello non-bold", TextHAlignment::CENTER,s.width); + TTFConfig ttfConfig("fonts/arial.ttf", 24); + auto label2 = Label::createWithTTF(ttfConfig, "hello non-bold", TextHAlignment::CENTER, s.width); addChild(label2, 0, kTagBitmapAtlas2); - label2->setPosition(Vec2(s.width/2, s.height*2/6)); + label2->setPosition(Vec2(s.width / 2, s.height * 2 / 6)); // or by setting the italics parameter on TTFConfig ttfConfig.bold = true; - _label2a = Label::createWithTTF(ttfConfig, "hello bold", TextHAlignment::CENTER,s.width); + _label2a = Label::createWithTTF(ttfConfig, "hello bold", TextHAlignment::CENTER, s.width); addChild(_label2a, 0, kTagBitmapAtlas2); - _label2a->setPosition(Vec2(s.width/2, s.height*1/6)); + _label2a->setPosition(Vec2(s.width / 2, s.height * 1 / 6)); auto menuItem = MenuItemFont::create("disable bold", [&](cocos2d::Ref* sender) { _label2a->disableEffect(LabelEffect::BOLD); @@ -3194,29 +3157,29 @@ LabelUnderline::LabelUnderline() auto s = Director::getInstance()->getWinSize(); // LabelBMFont - auto label1 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "hello non-underline", TextHAlignment::CENTER, s.width); + auto label1 = + Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "hello non-underline", TextHAlignment::CENTER, s.width); addChild(label1, 0, kTagBitmapAtlas1); - label1->setPosition(Vec2(s.width/2, s.height*4/6)); + label1->setPosition(Vec2(s.width / 2, s.height * 4 / 6)); // you can enable italics by calling this method _label1a = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "hello underline", TextHAlignment::CENTER, s.width); addChild(_label1a, 0, kTagBitmapAtlas1); - _label1a->setPosition(Vec2(s.width/2, s.height*3/6)); + _label1a->setPosition(Vec2(s.width / 2, s.height * 3 / 6)); // you can enable underline by calling this method _label1a->enableUnderline(); - // LabelTTF - TTFConfig ttfConfig("fonts/arial.ttf",24); - auto label2 = Label::createWithTTF(ttfConfig, "hello non-underline", TextHAlignment::CENTER,s.width); + TTFConfig ttfConfig("fonts/arial.ttf", 24); + auto label2 = Label::createWithTTF(ttfConfig, "hello non-underline", TextHAlignment::CENTER, s.width); addChild(label2, 0, kTagBitmapAtlas2); - label2->setPosition(Vec2(s.width/2, s.height*2/6)); + label2->setPosition(Vec2(s.width / 2, s.height * 2 / 6)); // or by setting the italics parameter on TTFConfig ttfConfig.underline = true; - _label2a = Label::createWithTTF(ttfConfig, "hello underline", TextHAlignment::CENTER,s.width); + _label2a = Label::createWithTTF(ttfConfig, "hello underline", TextHAlignment::CENTER, s.width); addChild(_label2a, 0, kTagBitmapAtlas2); - _label2a->setPosition(Vec2(s.width/2, s.height*1/6)); + _label2a->setPosition(Vec2(s.width / 2, s.height * 1 / 6)); auto menuItem = MenuItemFont::create("disable underline", [&](cocos2d::Ref* sender) { _label2a->disableEffect(LabelEffect::UNDERLINE); @@ -3246,18 +3209,19 @@ LabelUnderlineMultiline::LabelUnderlineMultiline() auto s = Director::getInstance()->getWinSize(); // bmfont - _label1a = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "hello underline\nand multiline", TextHAlignment::CENTER, s.width); + _label1a = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "hello underline\nand multiline", + TextHAlignment::CENTER, s.width); addChild(_label1a, 0, kTagBitmapAtlas1); - _label1a->setPosition(Vec2(s.width/2, s.height*2/3)); + _label1a->setPosition(Vec2(s.width / 2, s.height * 2 / 3)); // you can enable underline by calling this method _label1a->enableUnderline(); // ttf - TTFConfig ttfConfig("fonts/arial.ttf",24); + TTFConfig ttfConfig("fonts/arial.ttf", 24); ttfConfig.underline = true; _label2a = Label::createWithTTF(ttfConfig, "hello\nunderline\nwith multiline", TextHAlignment::LEFT, s.width); addChild(_label2a, 0, kTagBitmapAtlas2); - _label2a->setPosition(Vec2(s.width/2, s.height*1/3)); + _label2a->setPosition(Vec2(s.width / 2, s.height * 1 / 3)); auto menuItem = MenuItemFont::create("disable underline", [&](cocos2d::Ref* sender) { _label2a->disableEffect(LabelEffect::UNDERLINE); @@ -3287,18 +3251,19 @@ LabelStrikethrough::LabelStrikethrough() auto s = Director::getInstance()->getWinSize(); // bmfont - _label1a = Label::createWithBMFont("fonts/bitmapFontTest4.fnt", "hello strikethrough\nand multiline", TextHAlignment::LEFT, s.width); + _label1a = Label::createWithBMFont("fonts/bitmapFontTest4.fnt", "hello strikethrough\nand multiline", + TextHAlignment::LEFT, s.width); addChild(_label1a, 0, kTagBitmapAtlas1); - _label1a->setPosition(Vec2(s.width/2, s.height*2/3)); + _label1a->setPosition(Vec2(s.width / 2, s.height * 2 / 3)); // you can enable underline by calling this method _label1a->enableStrikethrough(); // ttf - TTFConfig ttfConfig("fonts/arial.ttf",24); + TTFConfig ttfConfig("fonts/arial.ttf", 24); ttfConfig.strikethrough = true; _label2a = Label::createWithTTF(ttfConfig, "hello\nstrikethrough\nwith multiline", TextHAlignment::RIGHT, s.width); addChild(_label2a, 0, kTagBitmapAtlas2); - _label2a->setPosition(Vec2(s.width/2, s.height*1/3)); + _label2a->setPosition(Vec2(s.width / 2, s.height * 1 / 3)); auto menuItem = MenuItemFont::create("disable underline", [&](cocos2d::Ref* sender) { _label2a->disableEffect(LabelEffect::STRIKETHROUGH); @@ -3330,22 +3295,22 @@ LabelLocalizationTest::LabelLocalizationTest() _localizationBin->initLanguageData("configs/ENGLISH.lang.csb"); const float BUTTON_WIDTH = 100; - float startPosX = 0; - Size winSize = Director::getInstance()->getVisibleSize(); + float startPosX = 0; + Size winSize = Director::getInstance()->getVisibleSize(); // Create a radio button group auto radioButtonGroup = RadioButtonGroup::create(); this->addChild(radioButtonGroup); // Create the radio buttons - const int NUMBER_OF_BUTTONS = 3; - startPosX = winSize.width / 2.0f - (NUMBER_OF_BUTTONS - 1) * 0.5 * BUTTON_WIDTH - 30; - std::vector labelTypes = { "English", "Chinese", "Japanese" }; + const int NUMBER_OF_BUTTONS = 3; + startPosX = winSize.width / 2.0f - (NUMBER_OF_BUTTONS - 1) * 0.5 * BUTTON_WIDTH - 30; + std::vector labelTypes = {"English", "Chinese", "Japanese"}; for (int i = 0; i < NUMBER_OF_BUTTONS; ++i) { RadioButton* radioButton = RadioButton::create("cocosui/radio_button_off.png", "cocosui/radio_button_on.png"); - float posX = startPosX + BUTTON_WIDTH * i; + float posX = startPosX + BUTTON_WIDTH * i; radioButton->setPosition(Vec2(posX, winSize.height / 2.0f + 70)); radioButton->setScale(1.2f); radioButton->addEventListener(CC_CALLBACK_2(LabelLocalizationTest::onChangedRadioButtonSelect, this)); @@ -3362,7 +3327,7 @@ LabelLocalizationTest::LabelLocalizationTest() addChild(_label1, 0); _label1->setPosition(Vec2(winSize.width / 2, winSize.height * 1 / 3)); - Label * label = Label::createWithSystemFont("From json data :", "Arial", 24); + Label* label = Label::createWithSystemFont("From json data :", "Arial", 24); label->setAnchorPoint(Vec2(0.0f, 0.5f)); addChild(label, 0); label->setPosition(Vec2(20.0f, winSize.height * 1 / 3 + 24)); @@ -3387,7 +3352,6 @@ std::string LabelLocalizationTest::subtitle() const return "Change language selected and see label change"; } - void LabelLocalizationTest::onChangedRadioButtonSelect(RadioButton* radioButton, RadioButton::EventType type) { if (radioButton == nullptr) @@ -3399,7 +3363,8 @@ void LabelLocalizationTest::onChangedRadioButtonSelect(RadioButton* radioButton, { case RadioButton::EventType::SELECTED: { - switch (radioButton->getTag()) { + switch (radioButton->getTag()) + { case 0: _localizationJson->initLanguageData("configs/en-US.lang.json"); _label1->setString(_localizationJson->getLocalizationString("Text Label")); @@ -3439,28 +3404,28 @@ LabelIssue15214::LabelIssue15214() Label* label = Label::createWithTTF("TTF with setColor()", "fonts/arial.ttf", 24.0f); label->enableUnderline(); label->setColor(cocos2d::Color3B::BLUE); - label->setPosition(size.width/2, size.height/5*4); + label->setPosition(size.width / 2, size.height / 5 * 4); this->addChild(label); // 2 Label* label2 = Label::createWithSystemFont("System with setColor()", "Verdana", 24.0f); label2->enableUnderline(); label2->setColor(cocos2d::Color3B::BLUE); - label2->setPosition(size.width/2, size.height/5*3); + label2->setPosition(size.width / 2, size.height / 5 * 3); this->addChild(label2); // 3 Label* label3 = Label::createWithTTF("TTF with setTextColor()", "fonts/arial.ttf", 24.0f); label3->enableUnderline(); label3->setTextColor(Color4B::BLUE); - label3->setPosition(size.width/2, size.height/5*2); + label3->setPosition(size.width / 2, size.height / 5 * 2); this->addChild(label3); // 4 Label* label4 = Label::createWithSystemFont("System with setTextColor()", "Verdana", 24.0f); label4->enableUnderline(); label4->setTextColor(Color4B::BLUE); - label4->setPosition(size.width/2, size.height/5*1); + label4->setPosition(size.width / 2, size.height / 5 * 1); this->addChild(label4); } @@ -3479,9 +3444,11 @@ std::string LabelIssue15214::subtitle() const // LabelIssue16293::LabelIssue16293() { - auto size = Director::getInstance()->getVisibleSize(); - Label* label = Label::createWithTTF("012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789", "fonts/arial.ttf", 12); - label->setPosition(size.width/2, size.height/2); + auto size = Director::getInstance()->getVisibleSize(); + Label* label = Label::createWithTTF( + "012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789", "fonts/arial.ttf", + 12); + label->setPosition(size.width / 2, size.height / 2); this->addChild(label); } @@ -3504,7 +3471,7 @@ LabelIssue16471::LabelIssue16471() auto node = Node::create(); addChild(node, 100); - node->setPosition(size.width/2, size.height/2); + node->setPosition(size.width / 2, size.height / 2); // Used Google Translate to translate from Chinese: // Here is set to false then textLabel: TextColor valid @@ -3541,16 +3508,16 @@ LabelIssue16717::LabelIssue16717() { auto label = Label::createWithTTF("Hello World", "fonts/arial.ttf", 70); label->setPosition(VisibleRect::center() + Vec2(0.0f, 40.0f)); - label->enableOutline(Color4B(0, 255, 0, 100), 10); // Set 100 alpha for outline - label->setTextColor(Color4B(0, 0, 255, 100)); // Also set 100 alpha for text + label->enableOutline(Color4B(0, 255, 0, 100), 10); // Set 100 alpha for outline + label->setTextColor(Color4B(0, 0, 255, 100)); // Also set 100 alpha for text addChild(label); } { auto label = Label::createWithTTF("Hello World", "fonts/arial.ttf", 70); label->setPosition(VisibleRect::center() + Vec2(0.0f, -40.0f)); - label->enableOutline(Color4B(0, 255, 0, 100), 10); // Set 100 alpha for outline - label->setTextColor(Color4B(0, 255, 0, 100)); // Also set 100 alpha for text + label->enableOutline(Color4B(0, 255, 0, 100), 10); // Set 100 alpha for outline + label->setTextColor(Color4B(0, 255, 0, 100)); // Also set 100 alpha for text addChild(label); } } @@ -3570,15 +3537,15 @@ std::string LabelIssue16717::subtitle() const // LabelIssueLineGap::LabelIssueLineGap() { - + auto size = Director::getInstance()->getWinSize(); - + auto label1 = Label::createWithTTF("test \ntest", "fonts/FingerpopGap.ttf", 30); label1->setPosition(Vec2(size.width / 3, size.height / 2)); addChild(label1); - + auto label2 = Label::createWithSystemFont("test \ntest", "fonts/FingerpopGap.ttf", 30); - label2->setPosition(Vec2(size.width / 3 * 1.8 , size.height / 2)); + label2->setPosition(Vec2(size.width / 3 * 1.8, size.height / 2)); addChild(label2); } @@ -3598,13 +3565,13 @@ std::string LabelIssueLineGap::subtitle() const LabelIssue17902::LabelIssue17902() { auto center = VisibleRect::center(); - + auto label = Label::createWithTTF("abcdefg\nhijklmn", "fonts/arial.ttf", 26); label->setLineHeight(40); label->setPosition(center); addChild(label); - scheduleOnce(CC_CALLBACK_0(LabelIssue17902::purgeCachedData, this), 1.0f, "purge_cached_data"); + scheduleOnce(CC_CALLBACK_0(LabelIssue17902::purgeCachedData, this), 1.0f, "purge_cached_data"); } void LabelIssue17902::purgeCachedData() @@ -3627,19 +3594,19 @@ std::string LabelIssue17902::subtitle() const // LabelIssue20523::LabelIssue20523() { - auto size = Director::getInstance()->getWinSize(); + auto size = Director::getInstance()->getWinSize(); auto _crashingLabel = Label::createWithTTF("0", "fonts/Marker Felt.ttf", 120); _crashingLabel->setPosition(Vec2(size.width / 2, size.height / 2)); _crashingLabel->setColor(cocos2d::Color3B(200, 200, 200)); addChild(_crashingLabel, 1); //_crashingLabel->setWidth(size.width); - this->schedule([this, _crashingLabel](float) - { + this->schedule( + [this, _crashingLabel](float) { ++_i; _crashingLabel->setString(std::to_string(_i)); - }, 1, CC_REPEAT_FOREVER, 0, "repeat"); - + }, + 1, CC_REPEAT_FOREVER, 0, "repeat"); } std::string LabelIssue20523::title() const @@ -3655,7 +3622,8 @@ std::string LabelIssue20523::subtitle() const // // LabelLetterColorsTest // -LabelLetterColorsTest::LabelLetterColorsTest() { +LabelLetterColorsTest::LabelLetterColorsTest() +{ auto center = VisibleRect::center(); auto label = Label::createWithTTF("", "fonts/arial.ttf", 24); @@ -3668,17 +3636,21 @@ LabelLetterColorsTest::LabelLetterColorsTest() { label->setString("abcd\ne"); // Must not crash at here. } -std::string LabelLetterColorsTest::title() const { +std::string LabelLetterColorsTest::title() const +{ return "Test for letter colors"; } -std::string LabelLetterColorsTest::subtitle() const { +std::string LabelLetterColorsTest::subtitle() const +{ return "Should not crash!"; } -void LabelLetterColorsTest::setLetterColors(cocos2d::Label* label, const cocos2d::Color3B& color) { +void LabelLetterColorsTest::setLetterColors(cocos2d::Label* label, const cocos2d::Color3B& color) +{ int n = label->getStringLength(); - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) + { Sprite* letter = label->getLetter(i); if (letter != nullptr) letter->setColor(color); diff --git a/tests/cpp-tests/Classes/LabelTest/LabelTestNew.h b/tests/cpp-tests/Classes/LabelTest/LabelTestNew.h index 84055634411f..3e38903f785b 100644 --- a/tests/cpp-tests/Classes/LabelTest/LabelTestNew.h +++ b/tests/cpp-tests/Classes/LabelTest/LabelTestNew.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -34,12 +34,12 @@ DEFINE_TEST_SUITE(NewLabelTests); class AtlasDemoNew : public TestCase -{ -}; +{}; class LabelFNTColorAndOpacity : public AtlasDemoNew { - float _time; + float _time; + public: CREATE_FUNC(LabelFNTColorAndOpacity); @@ -53,7 +53,8 @@ class LabelFNTColorAndOpacity : public AtlasDemoNew class LabelFNTSpriteActions : public AtlasDemoNew { - float _time; + float _time; + public: CREATE_FUNC(LabelFNTSpriteActions); @@ -74,7 +75,6 @@ class LabelFNTPadding : public AtlasDemoNew virtual std::string subtitle() const override; }; - class LabelFNTOffset : public AtlasDemoNew { public: @@ -180,13 +180,13 @@ class LabelFNTMultiLineAlignment : public AtlasDemoNew virtual std::string getItemString(cocos2d::MenuItemFont* item); protected: - cocos2d::Label* _label = nullptr; + cocos2d::Label* _label = nullptr; cocos2d::Sprite* _arrowsBar = nullptr; - cocos2d::Sprite* _arrows = nullptr; + cocos2d::Sprite* _arrows = nullptr; std::vector _menuItems; - cocos2d::MenuItemFont *_lastSentenceItem = nullptr; - cocos2d::MenuItemFont *_lastAlignmentItem = nullptr; - bool _drag = false; + cocos2d::MenuItemFont* _lastSentenceItem = nullptr; + cocos2d::MenuItemFont* _lastAlignmentItem = nullptr; + bool _drag = false; }; class LabelFNTMultiLineAlignmentUNICODE : public LabelFNTMultiLineAlignment @@ -218,7 +218,7 @@ class LabelFNTBounds : public AtlasDemoNew CREATE_FUNC(LabelFNTBounds); LabelFNTBounds(); - + virtual std::string title() const override; virtual std::string subtitle() const override; }; @@ -233,7 +233,6 @@ class LabelFNTMultiFontAtlasNoRotation : public AtlasDemoNew virtual std::string subtitle() const override; }; - class LabelFNTMultiFontAtlasWithRotation : public AtlasDemoNew { public: @@ -272,7 +271,7 @@ class LabelTTFUnicodeNew : public AtlasDemoNew CREATE_FUNC(LabelTTFUnicodeNew); LabelTTFUnicodeNew(); - + virtual std::string title() const override; virtual std::string subtitle() const override; }; @@ -285,24 +284,22 @@ class LabelTTFDynamicAlignment : public AtlasDemoNew LabelTTFDynamicAlignment(); virtual std::string title() const override; virtual std::string subtitle() const override; - + private: - void setAlignmentLeft(cocos2d::Ref* sender); void setAlignmentCenter(cocos2d::Ref* sender); void setAlignmentRight(cocos2d::Ref* sender); void updateAlignment(); - + cocos2d::Label* _label; - cocos2d::TextHAlignment _horizAlign; - + cocos2d::TextHAlignment _horizAlign; }; class LabelTTFEmoji : public AtlasDemoNew { public: CREATE_FUNC(LabelTTFEmoji); - + LabelTTFEmoji(); virtual std::string title() const override; virtual std::string subtitle() const override; @@ -378,6 +375,7 @@ class LabelShadowTest : public AtlasDemoNew virtual std::string subtitle() const override; void sliderEvent(cocos2d::Ref* sender, cocos2d::ui::Slider::EventType type); + private: cocos2d::Label* shadowLabelOutline; cocos2d::Label* shadowLabelTTF; @@ -398,7 +396,7 @@ class LabelCharMapTest : public AtlasDemoNew void step(float dt); private: - float _time; + float _time; }; class LabelCharMapColorTest : public AtlasDemoNew @@ -415,7 +413,7 @@ class LabelCharMapColorTest : public AtlasDemoNew void actionFinishCallback(); private: - float _time; + float _time; }; class LabelCrashTest : public AtlasDemoNew @@ -459,13 +457,14 @@ class LabelAlignmentTest : public AtlasDemoNew LabelAlignmentTest(); virtual std::string title() const override; virtual std::string subtitle() const override; + private: - void setAlignmentLeft(cocos2d::Ref* sender); - void setAlignmentCenter(cocos2d::Ref* sender); - void setAlignmentRight(cocos2d::Ref* sender); - void setAlignmentTop(cocos2d::Ref* sender); - void setAlignmentMiddle(cocos2d::Ref* sender); - void setAlignmentBottom(cocos2d::Ref* sender); + void setAlignmentLeft(cocos2d::Ref* sender); + void setAlignmentCenter(cocos2d::Ref* sender); + void setAlignmentRight(cocos2d::Ref* sender); + void setAlignmentTop(cocos2d::Ref* sender); + void setAlignmentMiddle(cocos2d::Ref* sender); + void setAlignmentBottom(cocos2d::Ref* sender); cocos2d::Label* _label; }; @@ -503,6 +502,7 @@ class LabelLineHeightTest : public AtlasDemoNew virtual std::string subtitle() const override; void sliderEvent(cocos2d::Ref* sender, cocos2d::ui::Slider::EventType type); + private: cocos2d::Label* label; }; @@ -518,6 +518,7 @@ class LabelAdditionalKerningTest : public AtlasDemoNew virtual std::string subtitle() const override; void sliderEvent(cocos2d::Ref* sender, cocos2d::ui::Slider::EventType type); + private: cocos2d::Label* label; }; @@ -703,18 +704,18 @@ class LabelLayoutBaseTest : public AtlasDemoNew { public: LabelLayoutBaseTest(); - void updateDrawNodeSize(const cocos2d::Size &drawNodeSize); + void updateDrawNodeSize(const cocos2d::Size& drawNodeSize); cocos2d::extension::ControlStepper* makeControlStepper(); void valueChanged(cocos2d::Ref* sender, cocos2d::extension::Control::EventType controlEvent); protected: - void setAlignmentLeft(cocos2d::Ref* sender); - void setAlignmentCenter(cocos2d::Ref* sender); - void setAlignmentRight(cocos2d::Ref* sender); - void setAlignmentTop(cocos2d::Ref* sender); - void setAlignmentMiddle(cocos2d::Ref* sender); - void setAlignmentBottom(cocos2d::Ref* sender); - + void setAlignmentLeft(cocos2d::Ref* sender); + void setAlignmentCenter(cocos2d::Ref* sender); + void setAlignmentRight(cocos2d::Ref* sender); + void setAlignmentTop(cocos2d::Ref* sender); + void setAlignmentMiddle(cocos2d::Ref* sender); + void setAlignmentBottom(cocos2d::Ref* sender); + void initWrapOption(const cocos2d::Size& size); void initToggleLabelTypeOption(const cocos2d::Size& size); void initAlignmentOption(const cocos2d::Size& size); @@ -800,7 +801,7 @@ class LabelToggleTypeTest : public LabelLayoutBaseTest LabelToggleTypeTest(); void initToggleCheckboxes(); - void onChangedRadioButtonSelect(cocos2d::ui::RadioButton* radioButton,cocos2d::ui::RadioButton::EventType type); + void onChangedRadioButtonSelect(cocos2d::ui::RadioButton* radioButton, cocos2d::ui::RadioButton::EventType type); virtual std::string title() const override; virtual std::string subtitle() const override; @@ -813,7 +814,7 @@ class LabelSystemFontTest : public LabelLayoutBaseTest LabelSystemFontTest(); void initToggleCheckboxes(); - void onChangedRadioButtonSelect(cocos2d::ui::RadioButton* radioButton,cocos2d::ui::RadioButton::EventType type); + void onChangedRadioButtonSelect(cocos2d::ui::RadioButton* radioButton, cocos2d::ui::RadioButton::EventType type); virtual std::string title() const override; virtual std::string subtitle() const override; @@ -834,9 +835,9 @@ class LabelIssue13846Test : public AtlasDemoNew { public: CREATE_FUNC(LabelIssue13846Test); - + LabelIssue13846Test(); - + virtual std::string title() const override; virtual std::string subtitle() const override; }; @@ -981,9 +982,9 @@ class LabelIssueLineGap : public AtlasDemoNew { public: CREATE_FUNC(LabelIssueLineGap); - + LabelIssueLineGap(); - + virtual std::string title() const override; virtual std::string subtitle() const override; }; @@ -992,11 +993,11 @@ class LabelIssue17902 : public AtlasDemoNew { public: CREATE_FUNC(LabelIssue17902); - + LabelIssue17902(); virtual void purgeCachedData(); - + virtual std::string title() const override; virtual std::string subtitle() const override; }; @@ -1015,7 +1016,8 @@ class LabelIssue20523 : public AtlasDemoNew int _i = 0; }; -class LabelLetterColorsTest : public AtlasDemoNew { +class LabelLetterColorsTest : public AtlasDemoNew +{ public: CREATE_FUNC(LabelLetterColorsTest); diff --git a/tests/cpp-tests/Classes/LayerTest/LayerTest.cpp b/tests/cpp-tests/Classes/LayerTest/LayerTest.cpp index 1bc88b56b681..26d26a6e4c4b 100644 --- a/tests/cpp-tests/Classes/LayerTest/LayerTest.cpp +++ b/tests/cpp-tests/Classes/LayerTest/LayerTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -28,7 +28,7 @@ USING_NS_CC; -enum +enum { kTagLayer = 1, }; @@ -62,9 +62,10 @@ static void setEnableRecursiveCascading(Node* node, bool enable) { node->setCascadeColorEnabled(enable); node->setCascadeOpacityEnabled(enable); - + auto& children = node->getChildren(); - for(const auto &child : children) { + for (const auto& child : children) + { setEnableRecursiveCascading(child, enable); } } @@ -78,41 +79,30 @@ std::string LayerTest::title() const void LayerTestCascadingOpacityA::onEnter() { LayerTest::onEnter(); - - auto s = Director::getInstance()->getWinSize(); + + auto s = Director::getInstance()->getWinSize(); auto layer1 = Layer::create(); - + auto sister1 = Sprite::create("Images/grossinis_sister1.png"); auto sister2 = Sprite::create("Images/grossinis_sister2.png"); - auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); - + auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); + layer1->addChild(sister1); layer1->addChild(sister2); layer1->addChild(label); - this->addChild( layer1, 0, kTagLayer); - - sister1->setPosition( Vec2( s.width*1/3, s.height/2)); - sister2->setPosition( Vec2( s.width*2/3, s.height/2)); - label->setPosition( Vec2( s.width/2, s.height/2)); - - layer1->runAction( - RepeatForever::create( - Sequence::create( - FadeTo::create(4, 0), - FadeTo::create(4, 255), - DelayTime::create(1), - nullptr))); + this->addChild(layer1, 0, kTagLayer); + + sister1->setPosition(Vec2(s.width * 1 / 3, s.height / 2)); + sister2->setPosition(Vec2(s.width * 2 / 3, s.height / 2)); + label->setPosition(Vec2(s.width / 2, s.height / 2)); + + layer1->runAction(RepeatForever::create( + Sequence::create(FadeTo::create(4, 0), FadeTo::create(4, 255), DelayTime::create(1), nullptr))); sister1->runAction( - RepeatForever::create( - Sequence::create( - FadeTo::create(2, 0), - FadeTo::create(2, 255), - FadeTo::create(2, 0), - FadeTo::create(2, 255), - DelayTime::create(1), - nullptr))); - + RepeatForever::create(Sequence::create(FadeTo::create(2, 0), FadeTo::create(2, 255), FadeTo::create(2, 0), + FadeTo::create(2, 255), DelayTime::create(1), nullptr))); + // Enable cascading in scene setEnableRecursiveCascading(this, true); } @@ -122,49 +112,37 @@ std::string LayerTestCascadingOpacityA::subtitle() const return "Layer: cascading opacity"; } - // LayerTestCascadingOpacityB void LayerTestCascadingOpacityB::onEnter() { LayerTest::onEnter(); - - auto s = Director::getInstance()->getWinSize(); - auto layer1 = LayerColor::create(Color4B(192, 0, 0, 255), s.width, s.height/2); + + auto s = Director::getInstance()->getWinSize(); + auto layer1 = LayerColor::create(Color4B(192, 0, 0, 255), s.width, s.height / 2); layer1->setCascadeColorEnabled(false); - - layer1->setPosition( Vec2(0.0f, s.height/2)); - + + layer1->setPosition(Vec2(0.0f, s.height / 2)); + auto sister1 = Sprite::create("Images/grossinis_sister1.png"); auto sister2 = Sprite::create("Images/grossinis_sister2.png"); - auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); - + auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); + layer1->addChild(sister1); layer1->addChild(sister2); layer1->addChild(label); - this->addChild( layer1, 0, kTagLayer); - - sister1->setPosition( Vec2( s.width*1/3, 0.0f)); - sister2->setPosition( Vec2( s.width*2/3, 0.0f)); - label->setPosition( Vec2( s.width/2, 0.0f)); - - layer1->runAction( - RepeatForever::create( - Sequence::create( - FadeTo::create(4, 0), - FadeTo::create(4, 255), - DelayTime::create(1), - nullptr))); - + this->addChild(layer1, 0, kTagLayer); + + sister1->setPosition(Vec2(s.width * 1 / 3, 0.0f)); + sister2->setPosition(Vec2(s.width * 2 / 3, 0.0f)); + label->setPosition(Vec2(s.width / 2, 0.0f)); + + layer1->runAction(RepeatForever::create( + Sequence::create(FadeTo::create(4, 0), FadeTo::create(4, 255), DelayTime::create(1), nullptr))); + sister1->runAction( - RepeatForever::create( - Sequence::create( - FadeTo::create(2, 0), - FadeTo::create(2, 255), - FadeTo::create(2, 0), - FadeTo::create(2, 255), - DelayTime::create(1), - nullptr))); - + RepeatForever::create(Sequence::create(FadeTo::create(2, 0), FadeTo::create(2, 255), FadeTo::create(2, 0), + FadeTo::create(2, 255), DelayTime::create(1), nullptr))); + // Enable cascading in scene setEnableRecursiveCascading(this, true); } @@ -174,49 +152,37 @@ std::string LayerTestCascadingOpacityB::subtitle() const return "CCLayerColor: cascading opacity"; } - // LayerTestCascadingOpacityC void LayerTestCascadingOpacityC::onEnter() { LayerTest::onEnter(); - - auto s = Director::getInstance()->getWinSize(); - auto layer1 = LayerColor::create(Color4B(192, 0, 0, 255), s.width, s.height/2); + + auto s = Director::getInstance()->getWinSize(); + auto layer1 = LayerColor::create(Color4B(192, 0, 0, 255), s.width, s.height / 2); layer1->setCascadeColorEnabled(false); layer1->setCascadeOpacityEnabled(false); - - layer1->setPosition( Vec2(0.0f, s.height/2)); - + + layer1->setPosition(Vec2(0.0f, s.height / 2)); + auto sister1 = Sprite::create("Images/grossinis_sister1.png"); auto sister2 = Sprite::create("Images/grossinis_sister2.png"); - auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); - + auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); + layer1->addChild(sister1); layer1->addChild(sister2); layer1->addChild(label); - this->addChild( layer1, 0, kTagLayer); - - sister1->setPosition( Vec2( s.width*1/3, 0.0f)); - sister2->setPosition( Vec2( s.width*2/3, 0.0f)); - label->setPosition( Vec2( s.width/2, 0.0f)); - - layer1->runAction( - RepeatForever::create( - Sequence::create( - FadeTo::create(4, 0), - FadeTo::create(4, 255), - DelayTime::create(1), - nullptr))); - + this->addChild(layer1, 0, kTagLayer); + + sister1->setPosition(Vec2(s.width * 1 / 3, 0.0f)); + sister2->setPosition(Vec2(s.width * 2 / 3, 0.0f)); + label->setPosition(Vec2(s.width / 2, 0.0f)); + + layer1->runAction(RepeatForever::create( + Sequence::create(FadeTo::create(4, 0), FadeTo::create(4, 255), DelayTime::create(1), nullptr))); + sister1->runAction( - RepeatForever::create( - Sequence::create( - FadeTo::create(2, 0), - FadeTo::create(2, 255), - FadeTo::create(2, 0), - FadeTo::create(2, 255), - DelayTime::create(1), - nullptr))); + RepeatForever::create(Sequence::create(FadeTo::create(2, 0), FadeTo::create(2, 255), FadeTo::create(2, 0), + FadeTo::create(2, 255), DelayTime::create(1), nullptr))); } std::string LayerTestCascadingOpacityC::subtitle() const @@ -224,53 +190,39 @@ std::string LayerTestCascadingOpacityC::subtitle() const return "CCLayerColor: non-cascading opacity"; } - //// Example LayerTestCascadingColor // LayerTestCascadingColorA void LayerTestCascadingColorA::onEnter() { LayerTest::onEnter(); - - auto s = Director::getInstance()->getWinSize(); + + auto s = Director::getInstance()->getWinSize(); auto layer1 = Layer::create(); - + auto sister1 = Sprite::create("Images/grossinis_sister1.png"); auto sister2 = Sprite::create("Images/grossinis_sister2.png"); - auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); - + auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); + layer1->addChild(sister1); layer1->addChild(sister2); layer1->addChild(label); - this->addChild( layer1, 0, kTagLayer); - - sister1->setPosition( Vec2( s.width*1/3, s.height/2)); - sister2->setPosition( Vec2( s.width*2/3, s.height/2)); - label->setPosition( Vec2( s.width/2, s.height/2)); - - layer1->runAction( - RepeatForever::create( - Sequence::create( - TintTo::create(6, 255, 0, 255), - TintTo::create(6, 255, 255, 255), - DelayTime::create(1), - nullptr))); - - sister1->runAction( - RepeatForever::create( - Sequence::create( - TintTo::create(2, 255, 255, 0), - TintTo::create(2, 255, 255, 255), - TintTo::create(2, 0, 255, 255), - TintTo::create(2, 255, 255, 255), - TintTo::create(2, 255, 0, 255), - TintTo::create(2, 255, 255, 255), - DelayTime::create(1), - nullptr))); - + this->addChild(layer1, 0, kTagLayer); + + sister1->setPosition(Vec2(s.width * 1 / 3, s.height / 2)); + sister2->setPosition(Vec2(s.width * 2 / 3, s.height / 2)); + label->setPosition(Vec2(s.width / 2, s.height / 2)); + + layer1->runAction(RepeatForever::create(Sequence::create( + TintTo::create(6, 255, 0, 255), TintTo::create(6, 255, 255, 255), DelayTime::create(1), nullptr))); + + sister1->runAction(RepeatForever::create(Sequence::create( + TintTo::create(2, 255, 255, 0), TintTo::create(2, 255, 255, 255), TintTo::create(2, 0, 255, 255), + TintTo::create(2, 255, 255, 255), TintTo::create(2, 255, 0, 255), TintTo::create(2, 255, 255, 255), + DelayTime::create(1), nullptr))); + // Enable cascading in scene setEnableRecursiveCascading(this, true); - } std::string LayerTestCascadingColorA::subtitle() const @@ -278,49 +230,36 @@ std::string LayerTestCascadingColorA::subtitle() const return "Layer: cascading color"; } - // LayerTestCascadingColorB void LayerTestCascadingColorB::onEnter() { LayerTest::onEnter(); - auto s = Director::getInstance()->getWinSize(); - auto layer1 = LayerColor::create(Color4B(255, 255, 255, 255), s.width, s.height/2); - - layer1->setPosition( Vec2(0.0f, s.height/2)); - + auto s = Director::getInstance()->getWinSize(); + auto layer1 = LayerColor::create(Color4B(255, 255, 255, 255), s.width, s.height / 2); + + layer1->setPosition(Vec2(0.0f, s.height / 2)); + auto sister1 = Sprite::create("Images/grossinis_sister1.png"); auto sister2 = Sprite::create("Images/grossinis_sister2.png"); - auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); - + auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); + layer1->addChild(sister1); layer1->addChild(sister2); layer1->addChild(label); - this->addChild( layer1, 0, kTagLayer); - - sister1->setPosition( Vec2( s.width*1/3, 0.0f)); - sister2->setPosition( Vec2( s.width*2/3, 0.0f)); - label->setPosition( Vec2( s.width/2, 0.0f)); - - layer1->runAction( - RepeatForever::create( - Sequence::create( - TintTo::create(6, 255, 0, 255), - TintTo::create(6, 255, 255, 255), - DelayTime::create(1), - nullptr))); - - sister1->runAction( - RepeatForever::create( - Sequence::create( - TintTo::create(2, 255, 255, 0), - TintTo::create(2, 255, 255, 255), - TintTo::create(2, 0, 255, 255), - TintTo::create(2, 255, 255, 255), - TintTo::create(2, 255, 0, 255), - TintTo::create(2, 255, 255, 255), - DelayTime::create(1), - nullptr))); - + this->addChild(layer1, 0, kTagLayer); + + sister1->setPosition(Vec2(s.width * 1 / 3, 0.0f)); + sister2->setPosition(Vec2(s.width * 2 / 3, 0.0f)); + label->setPosition(Vec2(s.width / 2, 0.0f)); + + layer1->runAction(RepeatForever::create(Sequence::create( + TintTo::create(6, 255, 0, 255), TintTo::create(6, 255, 255, 255), DelayTime::create(1), nullptr))); + + sister1->runAction(RepeatForever::create(Sequence::create( + TintTo::create(2, 255, 255, 0), TintTo::create(2, 255, 255, 255), TintTo::create(2, 0, 255, 255), + TintTo::create(2, 255, 255, 255), TintTo::create(2, 255, 0, 255), TintTo::create(2, 255, 255, 255), + DelayTime::create(1), nullptr))); + // Enable cascading in scene setEnableRecursiveCascading(this, true); } @@ -330,48 +269,35 @@ std::string LayerTestCascadingColorB::subtitle() const return "CCLayerColor: cascading color"; } - // LayerTestCascadingColorC void LayerTestCascadingColorC::onEnter() { LayerTest::onEnter(); - auto s = Director::getInstance()->getWinSize(); - auto layer1 = LayerColor::create(Color4B(255, 255, 255, 255), s.width, s.height/2); + auto s = Director::getInstance()->getWinSize(); + auto layer1 = LayerColor::create(Color4B(255, 255, 255, 255), s.width, s.height / 2); layer1->setCascadeColorEnabled(false); - layer1->setPosition( Vec2(0.0f, s.height/2)); - + layer1->setPosition(Vec2(0.0f, s.height / 2)); + auto sister1 = Sprite::create("Images/grossinis_sister1.png"); auto sister2 = Sprite::create("Images/grossinis_sister2.png"); - auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); - + auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Test"); + layer1->addChild(sister1); layer1->addChild(sister2); layer1->addChild(label); - this->addChild( layer1, 0, kTagLayer); - - sister1->setPosition( Vec2( s.width*1/3, 0.0f)); - sister2->setPosition( Vec2( s.width*2/3, 0.0f)); - label->setPosition( Vec2( s.width/2, 0.0f)); - - layer1->runAction( - RepeatForever::create( - Sequence::create( - TintTo::create(6, 255, 0, 255), - TintTo::create(6, 255, 255, 255), - DelayTime::create(1), - nullptr))); - - sister1->runAction( - RepeatForever::create( - Sequence::create( - TintTo::create(2, 255, 255, 0), - TintTo::create(2, 255, 255, 255), - TintTo::create(2, 0, 255, 255), - TintTo::create(2, 255, 255, 255), - TintTo::create(2, 255, 0, 255), - TintTo::create(2, 255, 255, 255), - DelayTime::create(1), - nullptr))); + this->addChild(layer1, 0, kTagLayer); + + sister1->setPosition(Vec2(s.width * 1 / 3, 0.0f)); + sister2->setPosition(Vec2(s.width * 2 / 3, 0.0f)); + label->setPosition(Vec2(s.width / 2, 0.0f)); + + layer1->runAction(RepeatForever::create(Sequence::create( + TintTo::create(6, 255, 0, 255), TintTo::create(6, 255, 255, 255), DelayTime::create(1), nullptr))); + + sister1->runAction(RepeatForever::create(Sequence::create( + TintTo::create(2, 255, 255, 0), TintTo::create(2, 255, 255, 255), TintTo::create(2, 0, 255, 255), + TintTo::create(2, 255, 255, 255), TintTo::create(2, 255, 0, 255), TintTo::create(2, 255, 255, 255), + DelayTime::create(1), nullptr))); } std::string LayerTestCascadingColorC::subtitle() const @@ -388,45 +314,45 @@ void LayerTest1::onEnter() { LayerTest::onEnter(); - auto listener = EventListenerTouchAllAtOnce::create(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(LayerTest1::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(LayerTest1::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(LayerTest1::onTouchesEnded, this); - + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - - auto s = Director::getInstance()->getWinSize(); - auto layer = LayerColor::create( Color4B(0xFF, 0x00, 0x00, 0x80), 200, 200); - + + auto s = Director::getInstance()->getWinSize(); + auto layer = LayerColor::create(Color4B(0xFF, 0x00, 0x00, 0x80), 200, 200); + layer->setIgnoreAnchorPointForPosition(false); - layer->setPosition( Vec2(s.width/2, s.height/2) ); + layer->setPosition(Vec2(s.width / 2, s.height / 2)); addChild(layer, 1, kTagLayer); } -void LayerTest1::updateSize(Vec2 &touchLocation) -{ +void LayerTest1::updateSize(Vec2& touchLocation) +{ auto s = Director::getInstance()->getWinSize(); - - auto newSize = Size( fabs(touchLocation.x - s.width/2)*2, fabs(touchLocation.y - s.height/2)*2); - - auto l = (LayerColor*) getChildByTag(kTagLayer); - l->setContentSize( newSize ); + auto newSize = Size(fabs(touchLocation.x - s.width / 2) * 2, fabs(touchLocation.y - s.height / 2) * 2); + + auto l = (LayerColor*)getChildByTag(kTagLayer); + + l->setContentSize(newSize); } -void LayerTest1::onTouchesBegan(const std::vector& touches, Event *event) +void LayerTest1::onTouchesBegan(const std::vector& touches, Event* event) { onTouchesMoved(touches, event); } -void LayerTest1::onTouchesMoved(const std::vector& touches, Event *event) +void LayerTest1::onTouchesMoved(const std::vector& touches, Event* event) { auto touchLocation = touches[0]->getLocation(); updateSize(touchLocation); } -void LayerTest1::onTouchesEnded(const std::vector& touches, Event *event) +void LayerTest1::onTouchesEnded(const std::vector& touches, Event* event) { onTouchesMoved(touches, event); } @@ -445,25 +371,25 @@ void LayerTest2::onEnter() { LayerTest::onEnter(); - auto s = Director::getInstance()->getWinSize(); - auto layer1 = LayerColor::create( Color4B(255, 255, 0, 80), 100, 300); - layer1->setPosition(Vec2(s.width/3, s.height/2)); + auto s = Director::getInstance()->getWinSize(); + auto layer1 = LayerColor::create(Color4B(255, 255, 0, 80), 100, 300); + layer1->setPosition(Vec2(s.width / 3, s.height / 2)); layer1->setIgnoreAnchorPointForPosition(false); addChild(layer1, 1); - - auto layer2 = LayerColor::create( Color4B(0, 0, 255, 255), 100, 300); - layer2->setPosition(Vec2((s.width/3)*2, s.height/2)); + + auto layer2 = LayerColor::create(Color4B(0, 0, 255, 255), 100, 300); + layer2->setPosition(Vec2((s.width / 3) * 2, s.height / 2)); layer2->setIgnoreAnchorPointForPosition(false); addChild(layer2, 1); - - auto actionTint = TintBy::create(2, -255, -127, 0); + + auto actionTint = TintBy::create(2, -255, -127, 0); auto actionTintBack = actionTint->reverse(); - auto seq1 = Sequence::create( actionTint, actionTintBack, nullptr); + auto seq1 = Sequence::create(actionTint, actionTintBack, nullptr); layer1->runAction(seq1); - auto actionFade = FadeOut::create(2.0f); + auto actionFade = FadeOut::create(2.0f); auto actionFadeBack = actionFade->reverse(); - auto seq2 = Sequence::create(actionFade, actionFadeBack, nullptr); + auto seq2 = Sequence::create(actionFade, actionFadeBack, nullptr); layer2->runAction(seq2); } @@ -480,30 +406,30 @@ std::string LayerTest2::subtitle() const LayerTestBlend::LayerTestBlend() { - auto s = Director::getInstance()->getWinSize(); - auto layer1 = LayerColor::create( Color4B(255, 255, 255, 80) ); - + auto s = Director::getInstance()->getWinSize(); + auto layer1 = LayerColor::create(Color4B(255, 255, 255, 80)); + auto sister1 = Sprite::create(s_pathSister1); auto sister2 = Sprite::create(s_pathSister2); - + addChild(sister1); addChild(sister2); addChild(layer1, 100, kTagLayer); - - sister1->setPosition( Vec2( s.width*1/3, s.height/2) ); - sister2->setPosition( Vec2( s.width*2/3, s.height/2) ); - schedule( CC_SCHEDULE_SELECTOR(LayerTestBlend::newBlend), 1.0f); + sister1->setPosition(Vec2(s.width * 1 / 3, s.height / 2)); + sister2->setPosition(Vec2(s.width * 2 / 3, s.height / 2)); + + schedule(CC_SCHEDULE_SELECTOR(LayerTestBlend::newBlend), 1.0f); } void LayerTestBlend::newBlend(float dt) { - auto layer = (LayerColor*)getChildByTag(kTagLayer); + auto layer = (LayerColor*)getChildByTag(kTagLayer); - backend::BlendFactor src; - backend::BlendFactor dst; + backend::BlendFactor src; + backend::BlendFactor dst; - if( layer->getBlendFunc().dst == backend::BlendFactor::ZERO ) + if (layer->getBlendFunc().dst == backend::BlendFactor::ZERO) { src = backend::BlendFactor::SRC_ALPHA; dst = backend::BlendFactor::ONE_MINUS_SRC_ALPHA; @@ -515,10 +441,9 @@ void LayerTestBlend::newBlend(float dt) } BlendFunc bf = {src, dst}; - layer->setBlendFunc( bf ); + layer->setBlendFunc(bf); } - std::string LayerTestBlend::subtitle() const { return "ColorLayer: blend"; @@ -531,18 +456,19 @@ std::string LayerTestBlend::subtitle() const //------------------------------------------------------------------ LayerGradientTest::LayerGradientTest() { - auto layer1 = LayerGradient::create(Color4B(255,0,0,255), Color4B(0,255,0,255), Vec2(0.9f, 0.9f)); + auto layer1 = LayerGradient::create(Color4B(255, 0, 0, 255), Color4B(0, 255, 0, 255), Vec2(0.9f, 0.9f)); addChild(layer1, 0, kTagLayer); - auto listener = EventListenerTouchAllAtOnce::create(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesMoved = CC_CALLBACK_2(LayerGradientTest::onTouchesMoved, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); auto label1 = Label::createWithTTF("Compressed Interpolation: Enabled", "fonts/Marker Felt.ttf", 26); auto label2 = Label::createWithTTF("Compressed Interpolation: Disabled", "fonts/Marker Felt.ttf", 26); - auto item1 = MenuItemLabel::create(label1); - auto item2 = MenuItemLabel::create(label2); - auto item = MenuItemToggle::createWithCallback( CC_CALLBACK_1(LayerGradientTest::toggleItem, this), item1, item2, nullptr); + auto item1 = MenuItemLabel::create(label1); + auto item2 = MenuItemLabel::create(label2); + auto item = + MenuItemToggle::createWithCallback(CC_CALLBACK_1(LayerGradientTest::toggleItem, this), item1, item2, nullptr); auto menu = Menu::create(item, nullptr); addChild(menu); @@ -550,23 +476,23 @@ LayerGradientTest::LayerGradientTest() menu->setPosition(Vec2(s.width / 2, 100.0f)); } -void LayerGradientTest::toggleItem(Ref *sender) +void LayerGradientTest::toggleItem(Ref* sender) { - auto gradient = static_cast( getChildByTag(kTagLayer) ); - gradient->setCompressedInterpolation(! gradient->isCompressedInterpolation()); + auto gradient = static_cast(getChildByTag(kTagLayer)); + gradient->setCompressedInterpolation(!gradient->isCompressedInterpolation()); } -void LayerGradientTest::onTouchesMoved(const std::vector& touches, Event *event) +void LayerGradientTest::onTouchesMoved(const std::vector& touches, Event* event) { auto s = Director::getInstance()->getWinSize(); auto touch = touches[0]; - auto start = touch->getLocation(); + auto start = touch->getLocation(); - auto diff = Vec2(s.width/2,s.height/2) - start; - diff = diff.getNormalized(); + auto diff = Vec2(s.width / 2, s.height / 2) - start; + diff = diff.getNormalized(); - auto gradient = static_cast( getChildByTag(1) ); + auto gradient = static_cast(getChildByTag(1)); gradient->setVector(diff); } @@ -587,7 +513,7 @@ std::string LayerGradientTest::subtitle() const //------------------------------------------------------------------ LayerGradientTest2::LayerGradientTest2() { - auto layer = LayerGradient::create(Color4B(255,0,0,255), Color4B(255,255,0,255)); + auto layer = LayerGradient::create(Color4B(255, 0, 0, 255), Color4B(255, 255, 0, 255)); addChild(layer); } @@ -603,7 +529,7 @@ std::string LayerGradientTest2::subtitle() const // LayerIgnoreAnchorPointPos -#define kLayerIgnoreAnchorPoint 1000 +#define kLayerIgnoreAnchorPoint 1000 void LayerIgnoreAnchorPointPos::onEnter() { @@ -614,32 +540,33 @@ void LayerIgnoreAnchorPointPos::onEnter() auto l = LayerColor::create(Color4B(255, 0, 0, 255), 150, 150); l->setAnchorPoint(Vec2(0.5f, 0.5f)); - l->setPosition(Vec2( s.width/2, s.height/2)); + l->setPosition(Vec2(s.width / 2, s.height / 2)); - auto move = MoveBy::create(2, Vec2(100,2)); - auto back = (MoveBy *)move->reverse(); - auto seq = Sequence::create(move, back, nullptr); + auto move = MoveBy::create(2, Vec2(100, 2)); + auto back = (MoveBy*)move->reverse(); + auto seq = Sequence::create(move, back, nullptr); l->runAction(RepeatForever::create(seq)); this->addChild(l, 0, kLayerIgnoreAnchorPoint); auto child = Sprite::create("Images/grossini.png"); l->addChild(child); auto lsize = l->getContentSize(); - child->setPosition(Vec2(lsize.width/2, lsize.height/2)); + child->setPosition(Vec2(lsize.width / 2, lsize.height / 2)); - auto item = MenuItemFont::create("Toggle ignore anchor point", CC_CALLBACK_1(LayerIgnoreAnchorPointPos::onToggle, this)); + auto item = + MenuItemFont::create("Toggle ignore anchor point", CC_CALLBACK_1(LayerIgnoreAnchorPointPos::onToggle, this)); auto menu = Menu::create(item, nullptr); this->addChild(menu); - menu->setPosition(Vec2(s.width/2, s.height/2)); + menu->setPosition(Vec2(s.width / 2, s.height / 2)); } void LayerIgnoreAnchorPointPos::onToggle(Ref* pObject) { - auto layer = this->getChildByTag(kLayerIgnoreAnchorPoint); + auto layer = this->getChildByTag(kLayerIgnoreAnchorPoint); bool ignore = layer->isIgnoreAnchorPointForPosition(); - layer->setIgnoreAnchorPointForPosition(! ignore); + layer->setIgnoreAnchorPointForPosition(!ignore); } std::string LayerIgnoreAnchorPointPos::title() const @@ -662,32 +589,32 @@ void LayerIgnoreAnchorPointRot::onEnter() auto l = LayerColor::create(Color4B(255, 0, 0, 255), 200, 200); l->setAnchorPoint(Vec2(0.5f, 0.5f)); - l->setPosition(Vec2( s.width/2, s.height/2)); + l->setPosition(Vec2(s.width / 2, s.height / 2)); this->addChild(l, 0, kLayerIgnoreAnchorPoint); auto rot = RotateBy::create(2, 360); l->runAction(RepeatForever::create(rot)); - auto child = Sprite::create("Images/grossini.png"); l->addChild(child); auto lsize = l->getContentSize(); - child->setPosition(Vec2(lsize.width/2, lsize.height/2)); + child->setPosition(Vec2(lsize.width / 2, lsize.height / 2)); - auto item = MenuItemFont::create("Toggle ignore anchor point", CC_CALLBACK_1(LayerIgnoreAnchorPointRot::onToggle, this)); + auto item = + MenuItemFont::create("Toggle ignore anchor point", CC_CALLBACK_1(LayerIgnoreAnchorPointRot::onToggle, this)); auto menu = Menu::create(item, nullptr); this->addChild(menu); - menu->setPosition(Vec2(s.width/2, s.height/2)); + menu->setPosition(Vec2(s.width / 2, s.height / 2)); } void LayerIgnoreAnchorPointRot::onToggle(Ref* pObject) { - auto layer = this->getChildByTag(kLayerIgnoreAnchorPoint); + auto layer = this->getChildByTag(kLayerIgnoreAnchorPoint); bool ignore = layer->isIgnoreAnchorPointForPosition(); - layer->setIgnoreAnchorPointForPosition(! ignore); + layer->setIgnoreAnchorPointForPosition(!ignore); } std::string LayerIgnoreAnchorPointRot::title() const @@ -704,18 +631,17 @@ std::string LayerIgnoreAnchorPointRot::subtitle() const void LayerIgnoreAnchorPointScale::onEnter() { LayerTest::onEnter(); - + auto s = Director::getInstance()->getWinSize(); auto l = LayerColor::create(Color4B(255, 0, 0, 255), 200, 200); l->setAnchorPoint(Vec2(0.5f, 1.0f)); - l->setPosition(Vec2( s.width/2, s.height/2)); - + l->setPosition(Vec2(s.width / 2, s.height / 2)); auto scale = ScaleBy::create(2, 2); - auto back = (ScaleBy*)scale->reverse(); - auto seq = Sequence::create(scale, back, nullptr); + auto back = (ScaleBy*)scale->reverse(); + auto seq = Sequence::create(scale, back, nullptr); l->runAction(RepeatForever::create(seq)); @@ -724,21 +650,22 @@ void LayerIgnoreAnchorPointScale::onEnter() auto child = Sprite::create("Images/grossini.png"); l->addChild(child); auto lsize = l->getContentSize(); - child->setPosition(Vec2(lsize.width/2, lsize.height/2)); + child->setPosition(Vec2(lsize.width / 2, lsize.height / 2)); - auto item = MenuItemFont::create("Toggle ignore anchor point", CC_CALLBACK_1(LayerIgnoreAnchorPointScale::onToggle, this)); + auto item = + MenuItemFont::create("Toggle ignore anchor point", CC_CALLBACK_1(LayerIgnoreAnchorPointScale::onToggle, this)); auto menu = Menu::create(item, nullptr); this->addChild(menu); - menu->setPosition(Vec2(s.width/2, s.height/2)); + menu->setPosition(Vec2(s.width / 2, s.height / 2)); } void LayerIgnoreAnchorPointScale::onToggle(Ref* pObject) { - auto layer = this->getChildByTag(kLayerIgnoreAnchorPoint); + auto layer = this->getChildByTag(kLayerIgnoreAnchorPoint); bool ignore = layer->isIgnoreAnchorPointForPosition(); - layer->setIgnoreAnchorPointForPosition(! ignore); + layer->setIgnoreAnchorPointForPosition(!ignore); } std::string LayerIgnoreAnchorPointScale::title() const @@ -755,22 +682,22 @@ LayerExtendedBlendOpacityTest::LayerExtendedBlendOpacityTest() { auto layer1 = LayerGradient::create(Color4B(255, 0, 0, 255), Color4B(255, 0, 255, 255)); layer1->setContentSize(Size(80.0f, 80.0f)); - layer1->setPosition(Vec2(50.0f,50.0f)); + layer1->setPosition(Vec2(50.0f, 50.0f)); addChild(layer1); - + auto layer2 = LayerGradient::create(Color4B(0, 0, 0, 127), Color4B(255, 255, 255, 127)); layer2->setContentSize(Size(80.0f, 80.0f)); - layer2->setPosition(Vec2(100.0f,90.0f)); + layer2->setPosition(Vec2(100.0f, 90.0f)); addChild(layer2); - + auto layer3 = LayerGradient::create(); layer3->setContentSize(Size(80.0f, 80.0f)); - layer3->setPosition(Vec2(150.0f,140.0f)); + layer3->setPosition(Vec2(150.0f, 140.0f)); layer3->setStartColor(Color3B(255, 0, 0)); layer3->setEndColor(Color3B(255, 0, 255)); layer3->setStartOpacity(255); layer3->setEndOpacity(255); - layer3->setBlendFunc( BlendFunc::ALPHA_NON_PREMULTIPLIED ); + layer3->setBlendFunc(BlendFunc::ALPHA_NON_PREMULTIPLIED); addChild(layer3); } @@ -788,27 +715,27 @@ std::string LayerExtendedBlendOpacityTest::subtitle() const void LayerBug3162A::onEnter() { LayerTest::onEnter(); - - Size size = VisibleRect::getVisibleRect().size; - size.width = size.width / 2; - size.height = size.height / 3; + + Size size = VisibleRect::getVisibleRect().size; + size.width = size.width / 2; + size.height = size.height / 3; Color4B color[3] = {Color4B(255, 0, 0, 255), Color4B(0, 255, 0, 255), Color4B(0, 0, 255, 255)}; - + for (int i = 0; i < 3; ++i) { _layer[i] = LayerColor::create(color[i]); _layer[i]->setContentSize(size); - _layer[i]->setPosition(Vec2(size.width/2, size.height/2) - Vec2(20.0f, 20.0f)); + _layer[i]->setPosition(Vec2(size.width / 2, size.height / 2) - Vec2(20.0f, 20.0f)); _layer[i]->setOpacity(150); _layer[i]->setCascadeOpacityEnabled(true); if (i > 0) { - _layer[i-1]->addChild(_layer[i]); + _layer[i - 1]->addChild(_layer[i]); } } - + this->addChild(_layer[0]); - + schedule(CC_SCHEDULE_SELECTOR(LayerBug3162A::step), 0.5, CC_REPEAT_FOREVER, 0); } @@ -831,30 +758,30 @@ std::string LayerBug3162A::subtitle() const void LayerBug3162B::onEnter() { LayerTest::onEnter(); - - Size size = VisibleRect::getVisibleRect().size; - size.width = size.width / 2; - size.height = size.height / 3; + + Size size = VisibleRect::getVisibleRect().size; + size.width = size.width / 2; + size.height = size.height / 3; Color4B color[3] = {Color4B(200, 0, 0, 255), Color4B(150, 0, 0, 255), Color4B(100, 0, 0, 255)}; - + for (int i = 0; i < 3; ++i) { _layer[i] = LayerColor::create(color[i]); _layer[i]->setContentSize(size); - _layer[i]->setPosition(Vec2(size.width/2, size.height/2) - Vec2(20.0f, 20.0f)); + _layer[i]->setPosition(Vec2(size.width / 2, size.height / 2) - Vec2(20.0f, 20.0f)); //_layer[i]->setOpacity(150); if (i > 0) { - _layer[i-1]->addChild(_layer[i]); + _layer[i - 1]->addChild(_layer[i]); } } - + this->addChild(_layer[0]); - + _layer[0]->setCascadeColorEnabled(true); _layer[1]->setCascadeColorEnabled(true); _layer[2]->setCascadeColorEnabled(true); - + schedule(CC_SCHEDULE_SELECTOR(LayerBug3162B::step), 0.5, CC_REPEAT_FOREVER, 0); } @@ -880,7 +807,7 @@ std::string LayerColorOccludeBug::title() const std::string LayerColorOccludeBug::subtitle() const { - return "Layer Color Should not occlude titles and any sprites"; + return "Layer Color Should not occlude titles and any sprites"; } void LayerColorOccludeBug::onEnter() @@ -907,22 +834,22 @@ std::string LayerRadialGradientTest::title() const void LayerRadialGradientTest::onEnter() { LayerTest::onEnter(); - + _currentSeletedItemIndex = 0; - + auto director = Director::getInstance(); director->setClearColor(Color4F(0, 0, 0, 0)); auto origin = director->getVisibleOrigin(); - auto size = director->getVisibleSize(); - Vec2 center(origin.x + size.width/2 + 50, origin.y + size.height/2); + auto size = director->getVisibleSize(); + Vec2 center(origin.x + size.width / 2 + 50, origin.y + size.height / 2); float radius = (size.height - 50) / 2; - _layer = LayerRadialGradient::create(Color4B(145, 106, 209, 140), Color4B(0, 0, 0, 0), radius, center, 1.0f); + _layer = LayerRadialGradient::create(Color4B(145, 106, 209, 140), Color4B(0, 0, 0, 0), radius, center, 1.0f); addChild(_layer); - + auto scaleSlider = LayerRadialGradientTest::createSlider(); scaleSlider->setPosition(Vec2(50.0f, 130.0f)); addChild(scaleSlider); - + auto listview = createListView(); listview->setPosition(Vec2(100.0f, 150.0f)); addChild(listview); @@ -939,7 +866,7 @@ cocos2d::ui::Slider* LayerRadialGradientTest::createSlider() slider->setRotation(90); slider->setTag(101); slider->setPercent(50); - + return slider; } @@ -947,113 +874,114 @@ void LayerRadialGradientTest::listviewCallback(cocos2d::Ref* sender, cocos2d::ui { // clear all text to white auto listview = static_cast(sender); - for (auto &item : listview->getItems()) + for (auto& item : listview->getItems()) static_cast(item)->setColor(cocos2d::Color3B::WHITE); - + _currentSeletedItemIndex = (int)listview->getCurSelectedIndex(); listview->getItem(_currentSeletedItemIndex)->setColor(cocos2d::Color3B::RED); - + int percent = 100; auto slider = static_cast(getChildByTag(101)); switch (_currentSeletedItemIndex) { - case 0: - // scale - slider->setPercent(_layer->getScaleX() / 2 * percent); - break; - case 1: - // skewx - slider->setPercent(_layer->getSkewX() / 90 * percent); - break; - case 2: - // skewy - slider->setPercent(_layer->getSkewY() / 90 * percent); - break; - case 3: - // expand - slider->setPercent(_layer->getExpand() * percent); - break; - case 4: - // radius - slider->setPercent(_layer->getRadius() / 300 * percent); - break; - - default: - break; + case 0: + // scale + slider->setPercent(_layer->getScaleX() / 2 * percent); + break; + case 1: + // skewx + slider->setPercent(_layer->getSkewX() / 90 * percent); + break; + case 2: + // skewy + slider->setPercent(_layer->getSkewY() / 90 * percent); + break; + case 3: + // expand + slider->setPercent(_layer->getExpand() * percent); + break; + case 4: + // radius + slider->setPercent(_layer->getRadius() / 300 * percent); + break; + + default: + break; } } void LayerRadialGradientTest::sliderCallback(cocos2d::Ref* sender, cocos2d::ui::Slider::EventType type) { - auto slider = static_cast(sender); + auto slider = static_cast(sender); float percent = slider->getPercent() / 100.f; switch (_currentSeletedItemIndex) { - case 0: - // scale - _layer->setScale(percent * 2); - CCLOG("scale is %f", percent * 2); - break; - case 1: - // skewx - _layer->setSkewX(90 * percent); - CCLOG("SkewX is %f", 90 * percent); - break; - case 2: - // skewy - _layer->setSkewY(90 * percent); - CCLOG("SkewY is %f", 90 * percent); - break; - case 3: - // expand - _layer->setExpand(percent); - CCLOG("expand is %f", percent); - break; - case 4: - // radius - _layer->setRadius(300 * percent); - CCLOG("radius is %f", 300 * percent); - break; - default: - break; + case 0: + // scale + _layer->setScale(percent * 2); + CCLOG("scale is %f", percent * 2); + break; + case 1: + // skewx + _layer->setSkewX(90 * percent); + CCLOG("SkewX is %f", 90 * percent); + break; + case 2: + // skewy + _layer->setSkewY(90 * percent); + CCLOG("SkewY is %f", 90 * percent); + break; + case 3: + // expand + _layer->setExpand(percent); + CCLOG("expand is %f", percent); + break; + case 4: + // radius + _layer->setRadius(300 * percent); + CCLOG("radius is %f", 300 * percent); + break; + default: + break; } } cocos2d::ui::ListView* LayerRadialGradientTest::createListView() { auto listview = cocos2d::ui::ListView::create(); - + auto scale = cocos2d::ui::Text::create(); scale->setString("scale[0-2]"); - scale->setColor(cocos2d::Color3B::RED); // default seleted item + scale->setColor(cocos2d::Color3B::RED); // default seleted item scale->setTouchEnabled(true); listview->pushBackCustomItem(scale); - + auto skewx = cocos2d::ui::Text::create(); skewx->setString("skewx[0-90]"); skewx->setTouchEnabled(true); listview->pushBackCustomItem(skewx); - + auto skewy = cocos2d::ui::Text::create(); skewy->setString("skewy[0-90]"); skewy->setTouchEnabled(true); listview->pushBackCustomItem(skewy); - + auto expand = cocos2d::ui::Text::create(); expand->setString("expand[0-1]"); expand->setTouchEnabled(true); listview->pushBackCustomItem(expand); - + auto radius = cocos2d::ui::Text::create(); radius->setString("radius[0-300]"); radius->setTouchEnabled(true); listview->pushBackCustomItem(radius); - + listview->setContentSize(scale->getContentSize() * 5); listview->setCurSelectedIndex(0); listview->setTouchEnabled(true); - listview->addEventListener((ui::ListView::ccListViewCallback)CC_CALLBACK_2(LayerRadialGradientTest::listviewCallback, this)); + listview->addEventListener( + (ui::ListView::ccListViewCallback)CC_CALLBACK_2(LayerRadialGradientTest::listviewCallback, this)); listview->setTag(100); - + return listview; } diff --git a/tests/cpp-tests/Classes/LayerTest/LayerTest.h b/tests/cpp-tests/Classes/LayerTest/LayerTest.h index 9ef5155f0987..96817d751b83 100644 --- a/tests/cpp-tests/Classes/LayerTest/LayerTest.h +++ b/tests/cpp-tests/Classes/LayerTest/LayerTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -35,8 +35,9 @@ class LayerTest : public TestCase { public: virtual std::string title() const override; + protected: - std::string _title; + std::string _title; }; class LayerTestCascadingOpacityA : public LayerTest @@ -87,7 +88,6 @@ class LayerTestCascadingColorC : public LayerTest virtual std::string subtitle() const override; }; - class LayerTest1 : public LayerTest { public: @@ -96,7 +96,7 @@ class LayerTest1 : public LayerTest virtual void onEnter() override; virtual std::string subtitle() const override; - void updateSize(cocos2d::Vec2 &touchLocation); + void updateSize(cocos2d::Vec2& touchLocation); void onTouchesBegan(const std::vector& touches, cocos2d::Event* event); void onTouchesMoved(const std::vector& touches, cocos2d::Event* event); @@ -111,7 +111,6 @@ class LayerTest2 : public LayerTest virtual std::string subtitle() const override; }; - class LayerTestBlend : public LayerTest { public: @@ -130,7 +129,7 @@ class LayerGradientTest : public LayerTest void onTouchesMoved(const std::vector& touches, cocos2d::Event* event); virtual std::string title() const override; virtual std::string subtitle() const override; - void toggleItem(cocos2d::Ref *sender); + void toggleItem(cocos2d::Ref* sender); }; class LayerGradientTest2 : public LayerTest @@ -188,9 +187,9 @@ class LayerBug3162A : public LayerTest virtual void onEnter() override; virtual std::string title() const override; virtual std::string subtitle() const override; - + void step(float dt); - + private: cocos2d::LayerColor* _layer[3]; }; @@ -202,9 +201,9 @@ class LayerBug3162B : public LayerTest virtual void onEnter() override; virtual std::string title() const override; virtual std::string subtitle() const override; - + void step(float dt); - + private: cocos2d::LayerColor* _layer[3]; }; @@ -217,7 +216,7 @@ class LayerColorOccludeBug : public LayerTest virtual void onExit() override; virtual std::string title() const override; virtual std::string subtitle() const override; - + private: cocos2d::LayerColor* _layer; }; @@ -228,16 +227,16 @@ class LayerRadialGradientTest : public LayerTest CREATE_FUNC(LayerRadialGradientTest); virtual void onEnter() override; virtual std::string title() const override; - + void sliderCallback(cocos2d::Ref* sender, cocos2d::ui::Slider::EventType type); void listviewCallback(cocos2d::Ref* sender, cocos2d::ui::ListView::EventType type); + private: cocos2d::ui::Slider* createSlider(); cocos2d::ui::ListView* createListView(); - + cocos2d::LayerRadialGradient* _layer; int _currentSeletedItemIndex; }; - #endif diff --git a/tests/cpp-tests/Classes/LightTest/LightTest.cpp b/tests/cpp-tests/Classes/LightTest/LightTest.cpp index 26c449459df4..77d67012eadb 100644 --- a/tests/cpp-tests/Classes/LightTest/LightTest.cpp +++ b/tests/cpp-tests/Classes/LightTest/LightTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -31,49 +31,49 @@ LightTests::LightTests() ADD_TEST_CASE(LightTest); } -LightTest::LightTest() - : _directionalLight(nullptr) - , _pointLight(nullptr) - , _spotLight(nullptr) +LightTest::LightTest() : _directionalLight(nullptr), _pointLight(nullptr), _spotLight(nullptr) { addSprite(); addLights(); scheduleUpdate(); - auto s = Director::getInstance()->getWinSize(); - auto camera = Camera::createPerspective(60, (float)s.width/s.height, 1.0f, 1000.0f); + auto s = Director::getInstance()->getWinSize(); + auto camera = Camera::createPerspective(60, (float)s.width / s.height, 1.0f, 1000.0f); camera->setCameraFlag(CameraFlag::USER1); camera->setPosition3D(Vec3(0.0f, 100.0f, 100.0f)); camera->lookAt(Vec3(0.0f, 0.0f, 0.0f), Vec3(0.0f, 1.0f, 0.0f)); addChild(camera); TTFConfig ttfConfig("fonts/arial.ttf", 15); - _ambientLightLabel = Label::createWithTTF(ttfConfig,"Ambient Light ON"); + _ambientLightLabel = Label::createWithTTF(ttfConfig, "Ambient Light ON"); _ambientLightLabel->retain(); - auto menuItem0 = MenuItemLabel::create(_ambientLightLabel, CC_CALLBACK_1(LightTest::SwitchLight,this,LightType::AMBIENT)); - _directionalLightLabel = Label::createWithTTF(ttfConfig,"Directional Light OFF"); + auto menuItem0 = + MenuItemLabel::create(_ambientLightLabel, CC_CALLBACK_1(LightTest::SwitchLight, this, LightType::AMBIENT)); + _directionalLightLabel = Label::createWithTTF(ttfConfig, "Directional Light OFF"); _directionalLightLabel->retain(); - auto menuItem1 = MenuItemLabel::create(_directionalLightLabel, CC_CALLBACK_1(LightTest::SwitchLight,this,LightType::DIRECTIONAL)); - _pointLightLabel = Label::createWithTTF(ttfConfig,"Point Light OFF"); + auto menuItem1 = MenuItemLabel::create(_directionalLightLabel, + CC_CALLBACK_1(LightTest::SwitchLight, this, LightType::DIRECTIONAL)); + _pointLightLabel = Label::createWithTTF(ttfConfig, "Point Light OFF"); _pointLightLabel->retain(); - auto menuItem2 = MenuItemLabel::create(_pointLightLabel, CC_CALLBACK_1(LightTest::SwitchLight,this,LightType::POINT)); - _spotLightLabel = Label::createWithTTF(ttfConfig,"Spot Light OFF"); + auto menuItem2 = + MenuItemLabel::create(_pointLightLabel, CC_CALLBACK_1(LightTest::SwitchLight, this, LightType::POINT)); + _spotLightLabel = Label::createWithTTF(ttfConfig, "Spot Light OFF"); _spotLightLabel->retain(); - auto menuItem3 = MenuItemLabel::create(_spotLightLabel, CC_CALLBACK_1(LightTest::SwitchLight,this,LightType::SPOT)); + auto menuItem3 = + MenuItemLabel::create(_spotLightLabel, CC_CALLBACK_1(LightTest::SwitchLight, this, LightType::SPOT)); auto menu = Menu::create(menuItem0, menuItem1, menuItem2, menuItem3, nullptr); menu->setPosition(Vec2::ZERO); menuItem0->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT); - menuItem0->setPosition( Vec2(VisibleRect::left().x, VisibleRect::top().y-50) ); + menuItem0->setPosition(Vec2(VisibleRect::left().x, VisibleRect::top().y - 50)); menuItem1->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT); - menuItem1->setPosition( Vec2(VisibleRect::left().x, VisibleRect::top().y-100) ); + menuItem1->setPosition(Vec2(VisibleRect::left().x, VisibleRect::top().y - 100)); menuItem2->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT); - menuItem2->setPosition( Vec2(VisibleRect::left().x, VisibleRect::top().y -150)); + menuItem2->setPosition(Vec2(VisibleRect::left().x, VisibleRect::top().y - 150)); menuItem3->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT); - menuItem3->setPosition( Vec2(VisibleRect::left().x, VisibleRect::top().y -200)); + menuItem3->setPosition(Vec2(VisibleRect::left().x, VisibleRect::top().y - 200)); addChild(menu); } - LightTest::~LightTest() { if (_spotLightLabel) @@ -119,7 +119,7 @@ void LightTest::addSprite() { std::string fileName = "Sprite3DTest/orc.c3b"; - auto sprite = Sprite3D::create(fileName); + auto sprite = Sprite3D::create(fileName); sprite->setRotation3D(Vec3(0.0f, 180.0f, 0.0f)); sprite->setPosition(Vec2(0.0f, 0.0f)); sprite->setScale(2.0); @@ -138,7 +138,7 @@ void LightTest::addSprite() { std::string fileName = "Sprite3DTest/sphere.c3b"; - auto sprite = Sprite3D::create(fileName); + auto sprite = Sprite3D::create(fileName); sprite->setPosition(Vec2(30.0f, 0.0f)); addChild(sprite); sprite->setCameraMask(2); @@ -146,7 +146,7 @@ void LightTest::addSprite() { std::string fileName = "Sprite3DTest/sphere.c3b"; - auto sprite = Sprite3D::create(fileName); + auto sprite = Sprite3D::create(fileName); sprite->setScale(0.5f); sprite->setPosition(Vec2(-50.0f, 0.0f)); addChild(sprite); @@ -155,7 +155,7 @@ void LightTest::addSprite() { std::string fileName = "Sprite3DTest/sphere.c3b"; - auto sprite = Sprite3D::create(fileName); + auto sprite = Sprite3D::create(fileName); sprite->setScale(0.5f); sprite->setPosition(Vec2(-30.0f, 10.0f)); addChild(sprite); @@ -165,7 +165,7 @@ void LightTest::addSprite() void LightTest::addLights() { - auto s = Director::getInstance()->getWinSize(); + auto s = Director::getInstance()->getWinSize(); _ambientLight = AmbientLight::create(Color3B(200, 200, 200)); _ambientLight->retain(); _ambientLight->setEnabled(true); @@ -184,7 +184,8 @@ void LightTest::addLights() addChild(_pointLight); _pointLight->setCameraMask(2); - _spotLight = SpotLight::create(Vec3(-1.0f, -1.0f, 0.0f), Vec3(0.0f, 0.0f, 0.0f), Color3B(200, 200, 200), 0.0, 0.5, 10000.0f); + _spotLight = + SpotLight::create(Vec3(-1.0f, -1.0f, 0.0f), Vec3(0.0f, 0.0f, 0.0f), Color3B(200, 200, 200), 0.0, 0.5, 10000.0f); _spotLight->retain(); _spotLight->setEnabled(false); addChild(_spotLight); @@ -195,7 +196,7 @@ void LightTest::addLights() auto tintto2 = TintTo::create(4, 0, 255, 0); auto tintto3 = TintTo::create(4, 255, 0, 0); auto tintto4 = TintTo::create(4, 255, 255, 255); - auto seq = Sequence::create(tintto1,tintto2, tintto3, tintto4, nullptr); + auto seq = Sequence::create(tintto1, tintto2, tintto3, tintto4, nullptr); _ambientLight->runAction(RepeatForever::create(seq)); } @@ -204,7 +205,7 @@ void LightTest::addLights() auto tintto2 = TintTo::create(4, 0, 255, 0); auto tintto3 = TintTo::create(4, 0, 0, 255); auto tintto4 = TintTo::create(4, 255, 255, 255); - auto seq = Sequence::create(tintto1,tintto2, tintto3, tintto4, nullptr); + auto seq = Sequence::create(tintto1, tintto2, tintto3, tintto4, nullptr); _directionalLight->runAction(RepeatForever::create(seq)); } @@ -213,7 +214,7 @@ void LightTest::addLights() auto tintto2 = TintTo::create(4, 0, 255, 0); auto tintto3 = TintTo::create(4, 0, 0, 255); auto tintto4 = TintTo::create(4, 255, 255, 255); - auto seq = Sequence::create(tintto2, tintto1, tintto3, tintto4, nullptr); + auto seq = Sequence::create(tintto2, tintto1, tintto3, tintto4, nullptr); _pointLight->runAction(RepeatForever::create(seq)); } @@ -222,12 +223,12 @@ void LightTest::addLights() auto tintto2 = TintTo::create(4, 0, 255, 0); auto tintto3 = TintTo::create(4, 0, 0, 255); auto tintto4 = TintTo::create(4, 255, 255, 255); - auto seq = Sequence::create(tintto3, tintto2, tintto1, tintto4, nullptr); + auto seq = Sequence::create(tintto3, tintto2, tintto1, tintto4, nullptr); _spotLight->runAction(RepeatForever::create(seq)); } } -void LightTest::update( float delta ) +void LightTest::update(float delta) { static float angleDelta = 0.0; @@ -256,49 +257,49 @@ void LightTest::update( float delta ) TestCase::update(delta); } -void LightTest::SwitchLight( Ref* sender, LightType lightType ) +void LightTest::SwitchLight(Ref* sender, LightType lightType) { switch (lightType) { case LightType::AMBIENT: - { - char str[32]; - bool isON = !_ambientLight->isEnabled(); - sprintf(str, "Ambient Light %s", isON == true? "ON":"OFF"); - _ambientLight->setEnabled(isON); - _ambientLightLabel->setString(str); - } - break; + { + char str[32]; + bool isON = !_ambientLight->isEnabled(); + sprintf(str, "Ambient Light %s", isON == true ? "ON" : "OFF"); + _ambientLight->setEnabled(isON); + _ambientLightLabel->setString(str); + } + break; case LightType::DIRECTIONAL: - { - char str[32]; - bool isON = !_directionalLight->isEnabled(); - sprintf(str, "Directional Light %s", isON == true? "ON":"OFF"); - _directionalLight->setEnabled(isON); - _directionalLightLabel->setString(str); - } - break; + { + char str[32]; + bool isON = !_directionalLight->isEnabled(); + sprintf(str, "Directional Light %s", isON == true ? "ON" : "OFF"); + _directionalLight->setEnabled(isON); + _directionalLightLabel->setString(str); + } + break; case LightType::POINT: - { - char str[32]; - bool isON = !_pointLight->isEnabled(); - sprintf(str, "Point Light %s", isON == true? "ON":"OFF"); - _pointLight->setEnabled(isON); - _pointLightLabel->setString(str); - } - break; + { + char str[32]; + bool isON = !_pointLight->isEnabled(); + sprintf(str, "Point Light %s", isON == true ? "ON" : "OFF"); + _pointLight->setEnabled(isON); + _pointLightLabel->setString(str); + } + break; case LightType::SPOT: - { - char str[32]; - bool isON = !_spotLight->isEnabled(); - sprintf(str, "Spot Light %s", isON == true? "ON":"OFF"); - _spotLight->setEnabled(isON); - _spotLightLabel->setString(str); - } - break; + { + char str[32]; + bool isON = !_spotLight->isEnabled(); + sprintf(str, "Spot Light %s", isON == true ? "ON" : "OFF"); + _spotLight->setEnabled(isON); + _spotLightLabel->setString(str); + } + break; default: break; diff --git a/tests/cpp-tests/Classes/LightTest/LightTest.h b/tests/cpp-tests/Classes/LightTest/LightTest.h index 2112f1ce2010..e7b32fb9a790 100644 --- a/tests/cpp-tests/Classes/LightTest/LightTest.h +++ b/tests/cpp-tests/Classes/LightTest/LightTest.h @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2013 cocos2d-x.org Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -44,12 +44,10 @@ class LightTest : public TestCase void SwitchLight(cocos2d::Ref* sender, cocos2d::LightType lightType); private: - void addSprite(); void addLights(); private: - cocos2d::AmbientLight* _ambientLight; cocos2d::DirectionLight* _directionalLight; cocos2d::PointLight* _pointLight; @@ -62,4 +60,3 @@ class LightTest : public TestCase }; #endif - diff --git a/tests/cpp-tests/Classes/MaterialSystemTest/MaterialSystemTest.cpp b/tests/cpp-tests/Classes/MaterialSystemTest/MaterialSystemTest.cpp index de0539305eed..54ecfbb0296c 100644 --- a/tests/cpp-tests/Classes/MaterialSystemTest/MaterialSystemTest.cpp +++ b/tests/cpp-tests/Classes/MaterialSystemTest/MaterialSystemTest.cpp @@ -37,7 +37,6 @@ USING_NS_CC; static void printProperties(Properties* properties, int indent); - // MARK: Tests MaterialSystemTest::MaterialSystemTest() @@ -66,7 +65,7 @@ void Material_Sprite3DTest::onEnter() sprite->setScale(8.f); sprite->setTexture("Sprite3DTest/boss.png"); this->addChild(sprite); - sprite->setPositionNormalized(Vec2(0.5f,0.5f)); + sprite->setPositionNormalized(Vec2(0.5f, 0.5f)); } std::string Material_Sprite3DTest::subtitle() const @@ -79,25 +78,20 @@ void Material_MultipleSprite3D::onEnter() MaterialSystemBaseTest::onEnter(); const char* names[] = { - "Sprite3DTest/ReskinGirl.c3b", - "Sprite3DTest/ReskinGirl.c3b", - "Sprite3DTest/ReskinGirl.c3b", - "Sprite3DTest/ReskinGirl.c3b", - "Sprite3DTest/ReskinGirl.c3b", - "Sprite3DTest/ReskinGirl.c3b", - "Sprite3DTest/ReskinGirl.c3b", - "Sprite3DTest/ReskinGirl.c3b", + "Sprite3DTest/ReskinGirl.c3b", "Sprite3DTest/ReskinGirl.c3b", "Sprite3DTest/ReskinGirl.c3b", + "Sprite3DTest/ReskinGirl.c3b", "Sprite3DTest/ReskinGirl.c3b", "Sprite3DTest/ReskinGirl.c3b", + "Sprite3DTest/ReskinGirl.c3b", "Sprite3DTest/ReskinGirl.c3b", }; const int totalNames = sizeof(names) / sizeof(names[0]); auto size = Director::getInstance()->getWinSize(); - for(int i=0;iaddChild(sprite); - sprite->setPosition(Vec2((size.width/(totalNames+1))*(i+1), size.height/4)); + sprite->setPosition(Vec2((size.width / (totalNames + 1)) * (i + 1), size.height / 4)); sprite->setScale(3); } } @@ -119,7 +113,7 @@ void Material_2DEffects::onEnter() // Print the properties of every namespace within this one. printProperties(properties, 0); - Material *mat1 = Material::createWithProperties(properties); + Material* mat1 = Material::createWithProperties(properties); auto spriteBlur = Sprite::create("Images/grossini.png"); spriteBlur->setPositionNormalized(Vec2(0.2f, 0.5f)); @@ -143,11 +137,13 @@ void Material_2DEffects::onEnter() timeUniforms.clear(); -#define FETCH_CCTIME_LOCATION(sprite) do { \ - auto programState = sprite->getProgramState(); \ - auto location = programState->getUniformLocation("u_Time"); \ - timeUniforms.emplace_back(programState, location); \ - }while(0) +#define FETCH_CCTIME_LOCATION(sprite) \ + do \ + { \ + auto programState = sprite->getProgramState(); \ + auto location = programState->getUniformLocation("u_Time"); \ + timeUniforms.emplace_back(programState, location); \ + } while (0) FETCH_CCTIME_LOCATION(spriteBlur); FETCH_CCTIME_LOCATION(spriteOutline); @@ -169,7 +165,7 @@ void Material_2DEffects::updateCCTimeUniforms(float) { float time = Director::getInstance()->getTotalFrames() * Director::getInstance()->getAnimationInterval(); Vec4 random(time / 10.0f, time, time * 2.0f, time * 4.0f); - for (auto &loc : timeUniforms) + for (auto& loc : timeUniforms) { loc.programState->setUniform(loc.location, &random, sizeof(random)); } @@ -184,21 +180,25 @@ void Material_2DEffects::updateCCTimeUniforms(float) */ class EffectAutoBindingResolver : public backend::ProgramState::AutoBindingResolver { - virtual bool resolveAutoBinding(backend::ProgramState* programState,/* Node* node,*/ const std::string& uniform, const std::string& autoBinding) override; + virtual bool resolveAutoBinding(backend::ProgramState* programState, + /* Node* node,*/ std::string_view uniform, + std::string_view autoBinding) override; void callbackRadius(backend::ProgramState* programState, backend::UniformLocation uniform); void callbackColor(backend::ProgramState* programState, backend::UniformLocation uniform); }; -bool EffectAutoBindingResolver::resolveAutoBinding(backend::ProgramState* programState, /*Node* node,*/ const std::string& uniform, const std::string& autoBinding) +bool EffectAutoBindingResolver::resolveAutoBinding(backend::ProgramState* programState, + /*Node* node,*/ std::string_view uniform, + std::string_view autoBinding) { - if (autoBinding.compare("DYNAMIC_RADIUS")==0) + if (autoBinding.compare("DYNAMIC_RADIUS") == 0) { auto loc = programState->getUniformLocation(uniform); programState->setCallbackUniform(loc, CC_CALLBACK_2(EffectAutoBindingResolver::callbackRadius, this)); return true; } - else if (autoBinding.compare("OUTLINE_COLOR")==0) + else if (autoBinding.compare("OUTLINE_COLOR") == 0) { auto loc = programState->getUniformLocation(uniform); programState->setCallbackUniform(loc, CC_CALLBACK_2(EffectAutoBindingResolver::callbackColor, this)); @@ -207,13 +207,13 @@ bool EffectAutoBindingResolver::resolveAutoBinding(backend::ProgramState* progra return false; } -void EffectAutoBindingResolver::callbackRadius(backend::ProgramState *programState, backend::UniformLocation uniform) +void EffectAutoBindingResolver::callbackRadius(backend::ProgramState* programState, backend::UniformLocation uniform) { float f = CCRANDOM_0_1() * 10; programState->setUniform(uniform, &f, sizeof(f)); } -void EffectAutoBindingResolver::callbackColor(backend::ProgramState *programState, backend::UniformLocation uniform) +void EffectAutoBindingResolver::callbackColor(backend::ProgramState* programState, backend::UniformLocation uniform) { float r = CCRANDOM_0_1(); float g = CCRANDOM_0_1(); @@ -233,18 +233,17 @@ Material_AutoBindings::~Material_AutoBindings() delete _resolver; } - void Material_AutoBindings::onEnter() { MaterialSystemBaseTest::onEnter(); -// auto properties = Properties::createNonRefCounted("Materials/2d_effects.material#sample"); + // auto properties = Properties::createNonRefCounted("Materials/2d_effects.material#sample"); auto properties = Properties::createNonRefCounted("Materials/auto_binding_test.material#sample"); // Print the properties of every namespace within this one. printProperties(properties, 0); - Material *mat1 = Material::createWithProperties(properties); + Material* mat1 = Material::createWithProperties(properties); auto spriteBlur = Sprite::create("Images/grossini.png"); spriteBlur->setPositionNormalized(Vec2(0.2f, 0.5f)); @@ -267,8 +266,8 @@ void Material_AutoBindings::onEnter() spriteEdgeDetect->setProgramState(mat1->getTechniqueByName("edge_detect")->getPassByIndex(0)->getProgramState()); _noiseProgramState = spriteNoise->getProgramState(); - _locationTime = _noiseProgramState->getUniformLocation("u_Time"); - + _locationTime = _noiseProgramState->getUniformLocation("u_Time"); + schedule(CC_SCHEDULE_SELECTOR(Material_AutoBindings::updateUniformTime)); // properties is not a "Ref" object CC_SAFE_DELETE(properties); @@ -296,24 +295,23 @@ void Material_setTechnique::onEnter() auto sprite = Sprite3D::create("Sprite3DTest/boss1.obj"); sprite->setScale(6); this->addChild(sprite); - sprite->setPositionNormalized(Vec2(0.5f,0.5f)); + sprite->setPositionNormalized(Vec2(0.5f, 0.5f)); _sprite = sprite; - - Material *mat = Material::createWithFilename("Materials/3d_effects.material"); + Material* mat = Material::createWithFilename("Materials/3d_effects.material"); sprite->setMaterial(mat); // lights auto light1 = AmbientLight::create(Color3B::RED); addChild(light1); - auto light2 = DirectionLight::create(Vec3(-1,1,0), Color3B::GREEN); + auto light2 = DirectionLight::create(Vec3(-1, 1, 0), Color3B::GREEN); addChild(light2); - this->schedule(CC_CALLBACK_1(Material_setTechnique::changeMaterial, this), 1, "cookie"); + this->schedule(CC_CALLBACK_1(Material_setTechnique::changeMaterial, this), 1, "cookie"); _techniqueState = 0; - auto rot = RotateBy::create(5, Vec3(30.0f,60.0f,270.0f)); + auto rot = RotateBy::create(5, Vec3(30.0f, 60.0f, 270.0f)); auto repeat = RepeatForever::create(rot); sprite->runAction(repeat); } @@ -328,17 +326,17 @@ void Material_setTechnique::changeMaterial(float dt) // get it from Mesh 0 switch (_techniqueState) { - case 0: - _sprite->getMaterial(0)->setTechnique("lit"); - break; - case 1: - _sprite->getMaterial(0)->setTechnique("normal"); - break; - case 2: - _sprite->getMaterial(0)->setTechnique("outline"); - break; - default: - break; + case 0: + _sprite->getMaterial(0)->setTechnique("lit"); + break; + case 1: + _sprite->getMaterial(0)->setTechnique("normal"); + break; + case 2: + _sprite->getMaterial(0)->setTechnique("outline"); + break; + default: + break; } _techniqueState = (_techniqueState + 1) % 3; @@ -356,10 +354,10 @@ void Material_clone::onEnter() this->addChild(sprite); sprite->setPositionNormalized(Vec2(0.25f, 0.5f)); - Material *mat = Material::createWithFilename("Materials/3d_effects.material"); + Material* mat = Material::createWithFilename("Materials/3d_effects.material"); sprite->setMaterial(mat); - auto rot = RotateBy::create(5, Vec3(360.0f,240.0f,120.0f)); + auto rot = RotateBy::create(5, Vec3(360.0f, 240.0f, 120.0f)); auto repeat = RepeatForever::create(rot); sprite->runAction(repeat); @@ -385,8 +383,7 @@ void Material_clone::onEnter() mat->setTechnique("outline"); // should affect only sprite 3 -// mat2->setTechnique("normal"); - + // mat2->setTechnique("normal"); } std::string Material_clone::subtitle() const @@ -402,76 +399,74 @@ const int SHOW_LEBAL_TAG = 114; void Material_parsePerformance::onEnter() { MaterialSystemBaseTest::onEnter(); - + _maxParsingCoumt = 5e3; - + auto screenSize = Director::getInstance()->getWinSize(); - + ui::Slider* slider = ui::Slider::create(); slider->loadBarTexture("cocosui/sliderTrack.png"); slider->loadSlidBallTextures("cocosui/sliderThumb.png", "cocosui/sliderThumb.png", ""); slider->loadProgressBarTexture("cocosui/sliderProgress.png"); slider->setPercent(50); - + slider->setPosition(Vec2(screenSize.width / 2.0f, screenSize.height / 3.0f)); slider->addEventListener([&](Ref* sender, ui::Slider::EventType type) { - if (type == ui::Slider::EventType::ON_SLIDEBALL_UP) { ui::Slider* slider = dynamic_cast(sender); - float p = slider->getPercent() / 100.0f; + float p = slider->getPercent() / 100.0f; slider->setTouchEnabled(false); CCLOG("Will parsing material %d times", (int)(p * _maxParsingCoumt)); Label* label = dynamic_cast(this->getChildByTag(SHOW_LEBAL_TAG)); - if(label) + if (label) { label->setString("Testing start!"); } this->scheduleOnce( - [this, p, slider](float) - { - this->parsingTesting(p * _maxParsingCoumt); - slider->setTouchEnabled(true); - }, - 1.0, "schedule test parsing"); - + [this, p, slider](float) { + this->parsingTesting(p * _maxParsingCoumt); + slider->setTouchEnabled(true); + }, + 1.0, "schedule test parsing"); } }); - + addChild(slider); - - auto label = Label::createWithSystemFont("Max parsing count is 10000, which may crash because of high memory consumption.", "Helvetica", 10); + + auto label = Label::createWithSystemFont( + "Max parsing count is 10000, which may crash because of high memory consumption.", "Helvetica", 10); label->setPosition(Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f - 20)); addChild(label); label = Label::createWithSystemFont("Slide to test parsing performance", "Helvetica", 10); label->setPosition(Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f)); addChild(label); - + label = Label::createWithSystemFont("", "Helvetica", 10); label->setPosition(Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f + 20)); label->setTag(SHOW_LEBAL_TAG); addChild(label); - } void Material_parsePerformance::parsingTesting(unsigned int count) { std::clock_t begin = std::clock(); - + for (unsigned int i = 0; i < count; i++) { Material::createWithFilename("Materials/2d_effects.material"); Material::createWithFilename("Materials/3d_effects.material"); } - - std::clock_t end = std::clock(); + + std::clock_t end = std::clock(); double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; - Label* label = dynamic_cast(this->getChildByTag(SHOW_LEBAL_TAG)); - if(label) + Label* label = dynamic_cast(this->getChildByTag(SHOW_LEBAL_TAG)); + if (label) { - std::string str = StringUtils::format("Testing completed! Took: %.3f seconds for parsing material %d times.", elapsed_secs, count); + std::string str = StringUtils::format("Testing completed! Took: %.3f seconds for parsing material %d times.", + elapsed_secs, count); label->setString(str); - + CCLOG("Took: %.3f seconds for parsing material %d times.", elapsed_secs, count); } } @@ -487,17 +482,17 @@ static void printProperties(Properties* properties, int indent) { // Print the name and ID of the current namespace. const char* spacename = properties->getNamespace(); - const char* id = properties->getId(); + const char* id = properties->getId(); char chindent[64]; - int i=0; - for(i=0; igetNextProperty(); + const char* name = properties->getNextProperty(); const char* value = NULL; while (name != NULL) { @@ -509,9 +504,9 @@ static void printProperties(Properties* properties, int indent) Properties* space = properties->getNextNamespace(); while (space != NULL) { - printProperties(space, indent+1); + printProperties(space, indent + 1); space = properties->getNextNamespace(); } - log("%s}\n",chindent); + log("%s}\n", chindent); } diff --git a/tests/cpp-tests/Classes/MaterialSystemTest/MaterialSystemTest.h b/tests/cpp-tests/Classes/MaterialSystemTest/MaterialSystemTest.h index 5262858f9e33..518cfef70813 100644 --- a/tests/cpp-tests/Classes/MaterialSystemTest/MaterialSystemTest.h +++ b/tests/cpp-tests/Classes/MaterialSystemTest/MaterialSystemTest.h @@ -46,7 +46,6 @@ class Material_Sprite3DTest : public MaterialSystemBaseTest virtual void onEnter() override; virtual std::string subtitle() const override; - }; class Material_MultipleSprite3D : public MaterialSystemBaseTest @@ -66,13 +65,15 @@ class Material_2DEffects : public MaterialSystemBaseTest virtual void onEnter() override; virtual std::string subtitle() const override; void updateCCTimeUniforms(float); - + private: - struct Locations { - Locations(cocos2d::backend::ProgramState *ps, cocos2d::backend::UniformLocation loc) - : programState(ps), location(loc) {} - - cocos2d::backend::ProgramState *programState = nullptr; + struct Locations + { + Locations(cocos2d::backend::ProgramState* ps, cocos2d::backend::UniformLocation loc) + : programState(ps), location(loc) + {} + + cocos2d::backend::ProgramState* programState = nullptr; cocos2d::backend::UniformLocation location; }; std::vector timeUniforms; @@ -94,8 +95,8 @@ class Material_AutoBindings : public MaterialSystemBaseTest private: cocos2d::backend::UniformLocation _locationTime; - EffectAutoBindingResolver *_resolver = nullptr; - cocos2d::backend::ProgramState *_noiseProgramState = nullptr; + EffectAutoBindingResolver* _resolver = nullptr; + cocos2d::backend::ProgramState* _noiseProgramState = nullptr; }; class Material_setTechnique : public MaterialSystemBaseTest @@ -130,9 +131,7 @@ class Material_parsePerformance : public MaterialSystemBaseTest virtual void onEnter() override; virtual std::string subtitle() const override; void parsingTesting(unsigned int count); + protected: unsigned int _maxParsingCoumt; }; - - - diff --git a/tests/cpp-tests/Classes/MenuTest/MenuTest.cpp b/tests/cpp-tests/Classes/MenuTest/MenuTest.cpp index 9c2e36b0ba51..9a71dc99bcb1 100644 --- a/tests/cpp-tests/Classes/MenuTest/MenuTest.cpp +++ b/tests/cpp-tests/Classes/MenuTest/MenuTest.cpp @@ -29,21 +29,22 @@ USING_NS_CC; -enum { - kTagMenu = 1, - kTagMenu0 = 0, +enum +{ + kTagMenu = 1, + kTagMenu0 = 0, kTagMenu1 = 1, }; -#define MID_CALLBACK 1000 -#define MID_CALLBACK2 1001 -#define MID_DISABLED 1002 -#define MID_ENABLE 1003 -#define MID_CONFIG 1004 -#define MID_QUIT 1005 -#define MID_OPACITY 1006 -#define MID_ALIGN 1007 -#define MID_CALLBACK3 1008 +#define MID_CALLBACK 1000 +#define MID_CALLBACK2 1001 +#define MID_DISABLED 1002 +#define MID_ENABLE 1003 +#define MID_CONFIG 1004 +#define MID_QUIT 1005 +#define MID_OPACITY 1006 +#define MID_ALIGN 1007 +#define MID_CALLBACK3 1008 #define MID_BACKCALLBACK 1009 MenuTests::MenuTests() @@ -59,42 +60,43 @@ MenuLayerMainMenu::MenuLayerMainMenu() { _touchListener = EventListenerTouchOneByOne::create(); _touchListener->setSwallowTouches(true); - _touchListener->onTouchBegan = CC_CALLBACK_2(MenuLayerMainMenu::touchBegan, this); - _touchListener->onTouchMoved = CC_CALLBACK_2(MenuLayerMainMenu::touchMoved, this); - _touchListener->onTouchEnded = CC_CALLBACK_2(MenuLayerMainMenu::touchEnded, this); + _touchListener->onTouchBegan = CC_CALLBACK_2(MenuLayerMainMenu::touchBegan, this); + _touchListener->onTouchMoved = CC_CALLBACK_2(MenuLayerMainMenu::touchMoved, this); + _touchListener->onTouchEnded = CC_CALLBACK_2(MenuLayerMainMenu::touchEnded, this); _touchListener->onTouchCancelled = CC_CALLBACK_2(MenuLayerMainMenu::touchCancelled, this); _eventDispatcher->addEventListenerWithFixedPriority(_touchListener, 1); - - // Font Item - auto spriteNormal = Sprite::create(s_MenuItem, Rect(0,23*2,115,23)); - auto spriteSelected = Sprite::create(s_MenuItem, Rect(0,23*1,115,23)); - auto spriteDisabled = Sprite::create(s_MenuItem, Rect(0,23*0,115,23)); - - auto item1 = MenuItemSprite::create(spriteNormal, spriteSelected, spriteDisabled, CC_CALLBACK_1(MenuLayerMainMenu::menuCallback, this) ); - + + // Font Item + auto spriteNormal = Sprite::create(s_MenuItem, Rect(0, 23 * 2, 115, 23)); + auto spriteSelected = Sprite::create(s_MenuItem, Rect(0, 23 * 1, 115, 23)); + auto spriteDisabled = Sprite::create(s_MenuItem, Rect(0, 23 * 0, 115, 23)); + + auto item1 = MenuItemSprite::create(spriteNormal, spriteSelected, spriteDisabled, + CC_CALLBACK_1(MenuLayerMainMenu::menuCallback, this)); + // Image Item - auto item2 = MenuItemImage::create(s_SendScore, s_PressSendScore, CC_CALLBACK_1(MenuLayerMainMenu::menuCallback2, this) ); + auto item2 = + MenuItemImage::create(s_SendScore, s_PressSendScore, CC_CALLBACK_1(MenuLayerMainMenu::menuCallback2, this)); // Label Item (LabelAtlas) auto labelAtlas = LabelAtlas::create("0123456789", "fonts/labelatlas.png", 16, 24, '.'); - auto item3 = MenuItemLabel::create(labelAtlas, CC_CALLBACK_1(MenuLayerMainMenu::menuCallbackDisabled, this) ); - item3->setDisabledColor( Color3B(32,32,64) ); - item3->setColor( Color3B(200,200,255) ); - CCLOG("test MenuItem Label getString: %s", item3->getString().c_str()); + auto item3 = MenuItemLabel::create(labelAtlas, CC_CALLBACK_1(MenuLayerMainMenu::menuCallbackDisabled, this)); + item3->setDisabledColor(Color3B(32, 32, 64)); + item3->setColor(Color3B(200, 200, 255)); + CCLOG("test MenuItem Label getString: %s", item3->getString().data()); // Font Item - auto item4 = MenuItemFont::create("I toggle enable items", [&](Ref *sender) { - _disabledItem->setEnabled(! _disabledItem->isEnabled() ); - }); + auto item4 = MenuItemFont::create("I toggle enable items", + [&](Ref* sender) { _disabledItem->setEnabled(!_disabledItem->isEnabled()); }); item4->setFontSizeObj(20); item4->setFontName("fonts/Marker Felt.ttf"); - + // Label Item (LabelBMFont) auto label = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", "configuration"); auto item5 = MenuItemLabel::create(label, CC_CALLBACK_1(MenuLayerMainMenu::menuCallbackConfig, this)); // Testing issue #500 - item5->setScale( 0.8f ); + item5->setScale(0.8f); // Events MenuItemFont::setFontName("fonts/Marker Felt.ttf"); @@ -102,62 +104,56 @@ MenuLayerMainMenu::MenuLayerMainMenu() auto item6 = MenuItemFont::create("Bugs", CC_CALLBACK_1(MenuLayerMainMenu::menuCallbackBugsTest, this)); // Font Item - auto item7= MenuItemFont::create("Quit", CC_CALLBACK_1(MenuLayerMainMenu::onQuit, this)); - - auto item8 = MenuItemFont::create("Remove menu item when moving", CC_CALLBACK_1(MenuLayerMainMenu::menuMovingCallback, this)); - + auto item7 = MenuItemFont::create("Quit", CC_CALLBACK_1(MenuLayerMainMenu::onQuit, this)); + + auto item8 = MenuItemFont::create("Remove menu item when moving", + CC_CALLBACK_1(MenuLayerMainMenu::menuMovingCallback, this)); + auto color_action = TintBy::create(0.5f, 0, -255, -255); - auto color_back = color_action->reverse(); - auto seq = Sequence::create(color_action, color_back, nullptr); + auto color_back = color_action->reverse(); + auto seq = Sequence::create(color_action, color_back, nullptr); item7->runAction(RepeatForever::create(seq)); - auto menu = Menu::create( item1, item2, item3, item4, item5, item6, item7, item8, nullptr); + auto menu = Menu::create(item1, item2, item3, item4, item5, item6, item7, item8, nullptr); menu->alignItemsVertically(); - - + // elastic effect auto s = Director::getInstance()->getWinSize(); - - int i=0; - for(const auto &child : menu->getChildren()) { + + int i = 0; + for (const auto& child : menu->getChildren()) + { auto dstPoint = child->getPosition(); - int offset = (int) (s.width/2 + 50); - if( i % 2 == 0) + int offset = (int)(s.width / 2 + 50); + if (i % 2 == 0) offset = -offset; - - child->setPosition( Vec2( dstPoint.x + offset, dstPoint.y) ); - child->runAction( - EaseElasticOut::create(MoveBy::create(2, Vec2(dstPoint.x - offset,0.0f)), 0.35f) - ); + + child->setPosition(Vec2(dstPoint.x + offset, dstPoint.y)); + child->runAction(EaseElasticOut::create(MoveBy::create(2, Vec2(dstPoint.x - offset, 0.0f)), 0.35f)); i++; } - _disabledItem = item3; item3->retain(); - _disabledItem->setEnabled( false ); + _disabledItem = item3; + item3->retain(); + _disabledItem->setEnabled(false); addChild(menu); menu->setTag(100); - menu->setPosition(Vec2(s.width/2, s.height/2)); + menu->setPosition(Vec2(s.width / 2, s.height / 2)); menu->setScale(0); - menu->runAction(ScaleTo::create(1,1)); + menu->runAction(ScaleTo::create(1, 1)); } -bool MenuLayerMainMenu::touchBegan(Touch *touch, Event * event) +bool MenuLayerMainMenu::touchBegan(Touch* touch, Event* event) { return true; } -void MenuLayerMainMenu::touchEnded(Touch *touch, Event * event) -{ -} +void MenuLayerMainMenu::touchEnded(Touch* touch, Event* event) {} -void MenuLayerMainMenu::touchCancelled(Touch *touch, Event * event) -{ -} +void MenuLayerMainMenu::touchCancelled(Touch* touch, Event* event) {} -void MenuLayerMainMenu::touchMoved(Touch *touch, Event * event) -{ -} +void MenuLayerMainMenu::touchMoved(Touch* touch, Event* event) {} MenuLayerMainMenu::~MenuLayerMainMenu() { @@ -182,7 +178,7 @@ void MenuLayerMainMenu::allowTouches(float dt) log("TOUCHES ALLOWED AGAIN"); } -void MenuLayerMainMenu::menuCallbackDisabled(Ref* sender) +void MenuLayerMainMenu::menuCallbackDisabled(Ref* sender) { // hijack all touch events for 5 seconds _eventDispatcher->setPriority(_touchListener, -1); @@ -195,7 +191,7 @@ void MenuLayerMainMenu::menuCallback2(Ref* sender) static_cast(_parent)->switchTo(2, false); } -void MenuLayerMainMenu::menuCallbackBugsTest(Ref *pSender) +void MenuLayerMainMenu::menuCallbackBugsTest(Ref* pSender) { static_cast(_parent)->switchTo(4, false); } @@ -203,10 +199,10 @@ void MenuLayerMainMenu::menuCallbackBugsTest(Ref *pSender) void MenuLayerMainMenu::onQuit(Ref* sender) { //[[Director sharedDirector] end]; - //getCocosApp()->exit(); + // getCocosApp()->exit(); } -void MenuLayerMainMenu::menuMovingCallback(Ref *pSender) +void MenuLayerMainMenu::menuMovingCallback(Ref* pSender) { static_cast(_parent)->switchTo(5, false); } @@ -218,24 +214,26 @@ void MenuLayerMainMenu::menuMovingCallback(Ref *pSender) //------------------------------------------------------------------ MenuLayer2::MenuLayer2() { - for( int i=0;i < 2;i++ ) + for (int i = 0; i < 2; i++) { auto item1 = MenuItemImage::create(s_PlayNormal, s_PlaySelect, CC_CALLBACK_1(MenuLayer2::menuCallback, this)); - auto item2 = MenuItemImage::create(s_HighNormal, s_HighSelect, CC_CALLBACK_1(MenuLayer2::menuCallbackOpacity, this)); - auto item3 = MenuItemImage::create(s_AboutNormal, s_AboutSelect, CC_CALLBACK_1(MenuLayer2::menuCallbackAlign, this)); - - item1->setScaleX( 1.5f ); - item2->setScaleX( 0.5f ); - item3->setScaleX( 0.5f ); - + auto item2 = + MenuItemImage::create(s_HighNormal, s_HighSelect, CC_CALLBACK_1(MenuLayer2::menuCallbackOpacity, this)); + auto item3 = + MenuItemImage::create(s_AboutNormal, s_AboutSelect, CC_CALLBACK_1(MenuLayer2::menuCallbackAlign, this)); + + item1->setScaleX(1.5f); + item2->setScaleX(0.5f); + item3->setScaleX(0.5f); + auto menu = Menu::create(item1, item2, item3, nullptr); - + auto s = Director::getInstance()->getWinSize(); - menu->setPosition(Vec2(s.width/2, s.height/2)); + menu->setPosition(Vec2(s.width / 2, s.height / 2)); + + menu->setTag(kTagMenu); - menu->setTag( kTagMenu ); - - addChild(menu, 0, 100+i); + addChild(menu, 0, 100 + i); _centeredMenu = menu->getPosition(); } @@ -244,54 +242,51 @@ MenuLayer2::MenuLayer2() alignMenusH(); } -MenuLayer2::~MenuLayer2() -{ -} +MenuLayer2::~MenuLayer2() {} void MenuLayer2::alignMenusH() { - for(int i=0;i<2;i++) + for (int i = 0; i < 2; i++) { - auto menu = static_cast( getChildByTag(100+i) ); - menu->setPosition( _centeredMenu ); - if(i==0) + auto menu = static_cast(getChildByTag(100 + i)); + menu->setPosition(_centeredMenu); + if (i == 0) { // TIP: if no padding, padding = 5 - menu->alignItemsHorizontally(); + menu->alignItemsHorizontally(); auto p = menu->getPosition(); - menu->setPosition(p + Vec2(0.0f,30.0f)); - - } - else + menu->setPosition(p + Vec2(0.0f, 30.0f)); + } + else { // TIP: but padding is configurable menu->alignItemsHorizontallyWithPadding(40); auto p = menu->getPosition(); - menu->setPosition(p - Vec2(0.0f,30.0f)); - } + menu->setPosition(p - Vec2(0.0f, 30.0f)); + } } } void MenuLayer2::alignMenusV() { - for(int i=0;i<2;i++) + for (int i = 0; i < 2; i++) { - auto menu = static_cast( getChildByTag(100+i) ); - menu->setPosition( _centeredMenu ); - if(i==0) + auto menu = static_cast(getChildByTag(100 + i)); + menu->setPosition(_centeredMenu); + if (i == 0) { // TIP: if no padding, padding = 5 - menu->alignItemsVertically(); + menu->alignItemsVertically(); auto p = menu->getPosition(); - menu->setPosition(p + Vec2(100.0f,0.0f)); - } - else + menu->setPosition(p + Vec2(100.0f, 0.0f)); + } + else { // TIP: but padding is configurable - menu->alignItemsVerticallyWithPadding(40); + menu->alignItemsVerticallyWithPadding(40); auto p = menu->getPosition(); - menu->setPosition(p - Vec2(100.0f,0.0f)); - } + menu->setPosition(p - Vec2(100.0f, 0.0f)); + } } } @@ -302,22 +297,22 @@ void MenuLayer2::menuCallback(Ref* sender) void MenuLayer2::menuCallbackOpacity(Ref* sender) { - auto menu = static_cast( static_cast(sender)->getParent() ); + auto menu = static_cast(static_cast(sender)->getParent()); uint8_t opacity = menu->getOpacity(); - if( opacity == 128 ) + if (opacity == 128) menu->setOpacity(255); else - menu->setOpacity(128); + menu->setOpacity(128); } void MenuLayer2::menuCallbackAlign(Ref* sender) { - _alignedH = ! _alignedH; - - if( _alignedH ) + _alignedH = !_alignedH; + + if (_alignedH) alignMenusH(); else - alignMenusV(); + alignMenusV(); } //------------------------------------------------------------------ @@ -331,49 +326,47 @@ MenuLayer3::MenuLayer3() MenuItemFont::setFontSize(28); auto label = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", "Enable AtlasItem"); - auto item1 = MenuItemLabel::create(label, [&](Ref *sender) { - //CCLOG("Label clicked. Toggling AtlasSprite"); - _disabledItem->setEnabled( ! _disabledItem->isEnabled() ); - _disabledItem->stopAllActions(); - }); - auto item2 = MenuItemFont::create("--- Go Back ---", [&](Ref *sender) { - static_cast(_parent)->switchTo(0, false); - }); - - auto spriteNormal = Sprite::create(s_MenuItem, Rect(0,23*2,115,23)); - auto spriteSelected = Sprite::create(s_MenuItem, Rect(0,23*1,115,23)); - auto spriteDisabled = Sprite::create(s_MenuItem, Rect(0,23*0,115,23)); - - - auto item3 = MenuItemSprite::create(spriteNormal, spriteSelected, spriteDisabled, [](Ref *sender) { - log("sprite clicked!"); - }); - _disabledItem = item3; item3->retain(); - _disabledItem->setEnabled( false ); - - auto menu = Menu::create( item1, item2, item3, nullptr); - menu->setPosition( Vec2(0,0) ); + auto item1 = MenuItemLabel::create(label, [&](Ref* sender) { + // CCLOG("Label clicked. Toggling AtlasSprite"); + _disabledItem->setEnabled(!_disabledItem->isEnabled()); + _disabledItem->stopAllActions(); + }); + auto item2 = MenuItemFont::create("--- Go Back ---", + [&](Ref* sender) { static_cast(_parent)->switchTo(0, false); }); + + auto spriteNormal = Sprite::create(s_MenuItem, Rect(0, 23 * 2, 115, 23)); + auto spriteSelected = Sprite::create(s_MenuItem, Rect(0, 23 * 1, 115, 23)); + auto spriteDisabled = Sprite::create(s_MenuItem, Rect(0, 23 * 0, 115, 23)); + + auto item3 = MenuItemSprite::create(spriteNormal, spriteSelected, spriteDisabled, + [](Ref* sender) { log("sprite clicked!"); }); + _disabledItem = item3; + item3->retain(); + _disabledItem->setEnabled(false); + + auto menu = Menu::create(item1, item2, item3, nullptr); + menu->setPosition(Vec2(0, 0)); auto s = Director::getInstance()->getWinSize(); - - item1->setPosition( Vec2(s.width/2 - 150, s.height/2) ); - item2->setPosition( Vec2(s.width/2 - 200, s.height/2) ); - item3->setPosition( Vec2(s.width/2, s.height/2 - 100) ); - - auto jump = JumpBy::create(3, Vec2(400,0), 50, 4); - item2->runAction( RepeatForever::create(Sequence::create( jump, jump->reverse(), nullptr))); + + item1->setPosition(Vec2(s.width / 2 - 150, s.height / 2)); + item2->setPosition(Vec2(s.width / 2 - 200, s.height / 2)); + item3->setPosition(Vec2(s.width / 2, s.height / 2 - 100)); + + auto jump = JumpBy::create(3, Vec2(400, 0), 50, 4); + item2->runAction(RepeatForever::create(Sequence::create(jump, jump->reverse(), nullptr))); auto spin1 = RotateBy::create(3, 360); auto spin2 = spin1->clone(); auto spin3 = spin1->clone(); - - item1->runAction( RepeatForever::create(spin1) ); - item2->runAction( RepeatForever::create(spin2) ); - item3->runAction( RepeatForever::create(spin3) ); - - addChild( menu ); - menu->setPosition(Vec2(0,0)); + item1->runAction(RepeatForever::create(spin1)); + item2->runAction(RepeatForever::create(spin2)); + item3->runAction(RepeatForever::create(spin3)); + + addChild(menu); + + menu->setPosition(Vec2(0, 0)); } MenuLayer3::~MenuLayer3() @@ -392,81 +385,68 @@ MenuLayer4::MenuLayer4() MenuItemFont::setFontSize(18); auto title1 = MenuItemFont::create("Sound"); title1->setEnabled(false); - MenuItemFont::setFontName( "fonts/Marker Felt.ttf" ); + MenuItemFont::setFontName("fonts/Marker Felt.ttf"); MenuItemFont::setFontSize(34); - auto item1 = MenuItemToggle::createWithCallback( CC_CALLBACK_1(MenuLayer4::menuCallback, this), - MenuItemFont::create( "On" ), - MenuItemFont::create( "Off"), - nullptr ); - - MenuItemFont::setFontName( "American Typewriter" ); + auto item1 = MenuItemToggle::createWithCallback(CC_CALLBACK_1(MenuLayer4::menuCallback, this), + MenuItemFont::create("On"), MenuItemFont::create("Off"), nullptr); + + MenuItemFont::setFontName("American Typewriter"); MenuItemFont::setFontSize(18); - auto title2 = MenuItemFont::create( "Music" ); + auto title2 = MenuItemFont::create("Music"); title2->setEnabled(false); - MenuItemFont::setFontName( "fonts/Marker Felt.ttf" ); + MenuItemFont::setFontName("fonts/Marker Felt.ttf"); MenuItemFont::setFontSize(34); auto item2 = MenuItemToggle::createWithCallback(CC_CALLBACK_1(MenuLayer4::menuCallback, this), - MenuItemFont::create( "On" ), - MenuItemFont::create( "Off"), - nullptr ); - - MenuItemFont::setFontName( "American Typewriter" ); + MenuItemFont::create("On"), MenuItemFont::create("Off"), nullptr); + + MenuItemFont::setFontName("American Typewriter"); MenuItemFont::setFontSize(18); - auto title3 = MenuItemFont::create( "Quality" ); - title3->setEnabled( false ); - MenuItemFont::setFontName( "fonts/Marker Felt.ttf" ); + auto title3 = MenuItemFont::create("Quality"); + title3->setEnabled(false); + MenuItemFont::setFontName("fonts/Marker Felt.ttf"); MenuItemFont::setFontSize(34); auto item3 = MenuItemToggle::createWithCallback(CC_CALLBACK_1(MenuLayer4::menuCallback, this), - MenuItemFont::create( "High" ), - MenuItemFont::create( "Low" ), - nullptr ); - - MenuItemFont::setFontName( "American Typewriter" ); + MenuItemFont::create("High"), MenuItemFont::create("Low"), nullptr); + + MenuItemFont::setFontName("American Typewriter"); MenuItemFont::setFontSize(18); - auto title4 = MenuItemFont::create( "Orientation" ); + auto title4 = MenuItemFont::create("Orientation"); title4->setEnabled(false); - MenuItemFont::setFontName( "fonts/Marker Felt.ttf" ); + MenuItemFont::setFontName("fonts/Marker Felt.ttf"); MenuItemFont::setFontSize(34); auto item4 = MenuItemToggle::createWithCallback(CC_CALLBACK_1(MenuLayer4::menuCallback, this), - MenuItemFont::create( "Off" ), - nullptr ); - + MenuItemFont::create("Off"), nullptr); + // TIP: you can manipulate the items like any other MutableArray - item4->getSubItems().pushBack( MenuItemFont::create( "33%" ) ); - item4->getSubItems().pushBack( MenuItemFont::create( "66%" ) ); - item4->getSubItems().pushBack( MenuItemFont::create( "100%" ) ); - + item4->getSubItems().pushBack(MenuItemFont::create("33%")); + item4->getSubItems().pushBack(MenuItemFont::create("66%")); + item4->getSubItems().pushBack(MenuItemFont::create("100%")); + // you can change the one of the items by doing this - item4->setSelectedIndex( 2 ); - - MenuItemFont::setFontName( "fonts/Marker Felt.ttf" ); - MenuItemFont::setFontSize( 34 ); - - auto label = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", "go back"); - auto back = MenuItemLabel::create(label, CC_CALLBACK_1(MenuLayer4::backCallback, this) ); - - auto menu = Menu::create( - title1, title2, - item1, item2, - title3, title4, - item3, item4, - back, nullptr ); // 9 items. - + item4->setSelectedIndex(2); + + MenuItemFont::setFontName("fonts/Marker Felt.ttf"); + MenuItemFont::setFontSize(34); + + auto label = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", "go back"); + auto back = MenuItemLabel::create(label, CC_CALLBACK_1(MenuLayer4::backCallback, this)); + + auto menu = Menu::create(title1, title2, item1, item2, title3, title4, item3, item4, back, nullptr); // 9 items. + menu->alignItemsInColumns(2, 2, 2, 2, 1, NULL); - - addChild( menu ); + + addChild(menu); auto s = Director::getInstance()->getWinSize(); - menu->setPosition(Vec2(s.width/2, s.height/2)); + menu->setPosition(Vec2(s.width / 2, s.height / 2)); } -MenuLayer4::~MenuLayer4() -{ -} +MenuLayer4::~MenuLayer4() {} void MenuLayer4::menuCallback(Ref* sender) { - //CCLOG("selected item: %x index:%d", dynamic_cast(sender)->selectedItem(), dynamic_cast(sender)->selectedIndex() ); + // CCLOG("selected item: %x index:%d", dynamic_cast(sender)->selectedItem(), + // dynamic_cast(sender)->selectedIndex() ); } void MenuLayer4::backCallback(Ref* sender) @@ -477,37 +457,37 @@ void MenuLayer4::backCallback(Ref* sender) // BugsTest BugsTest::BugsTest() { - auto issue1410 = MenuItemFont::create("Issue 1410", CC_CALLBACK_1(BugsTest::issue1410MenuCallback, this)); + auto issue1410 = MenuItemFont::create("Issue 1410", CC_CALLBACK_1(BugsTest::issue1410MenuCallback, this)); auto issue1410_2 = MenuItemFont::create("Issue 1410 #2", CC_CALLBACK_1(BugsTest::issue1410v2MenuCallback, this)); - auto back = MenuItemFont::create("Back", CC_CALLBACK_1(BugsTest::backMenuCallback, this)); - + auto back = MenuItemFont::create("Back", CC_CALLBACK_1(BugsTest::backMenuCallback, this)); + auto menu = Menu::create(issue1410, issue1410_2, back, nullptr); addChild(menu); menu->alignItemsVertically(); - + auto s = Director::getInstance()->getWinSize(); - menu->setPosition(Vec2(s.width/2, s.height/2)); + menu->setPosition(Vec2(s.width / 2, s.height / 2)); } -void BugsTest::issue1410MenuCallback(Ref *sender) +void BugsTest::issue1410MenuCallback(Ref* sender) { - auto menu = static_cast( static_cast(sender)->getParent() ); + auto menu = static_cast(static_cast(sender)->getParent()); menu->setEnabled(false); menu->setEnabled(true); - + log("NO CRASHES"); } -void BugsTest::issue1410v2MenuCallback(cocos2d::Ref *pSender) +void BugsTest::issue1410v2MenuCallback(cocos2d::Ref* pSender) { - auto menu = static_cast( static_cast(pSender)->getParent() ); + auto menu = static_cast(static_cast(pSender)->getParent()); menu->setEnabled(true); menu->setEnabled(false); - + log("NO CRASHES. AND MENU SHOULD STOP WORKING"); } -void BugsTest::backMenuCallback(cocos2d::Ref *pSender) +void BugsTest::backMenuCallback(cocos2d::Ref* pSender) { static_cast(_parent)->switchTo(0, false); } @@ -515,34 +495,33 @@ void BugsTest::backMenuCallback(cocos2d::Ref *pSender) RemoveMenuItemWhenMove::RemoveMenuItemWhenMove() { auto s = Director::getInstance()->getWinSize(); - + auto label = Label::createWithTTF("click item and move, should not crash", "fonts/arial.ttf", 20); - label->setPosition(Vec2(s.width/2, s.height - 30)); + label->setPosition(Vec2(s.width / 2, s.height - 30)); addChild(label); - + item = MenuItemFont::create("item 1"); item->retain(); - + auto back = MenuItemFont::create("go back", CC_CALLBACK_1(RemoveMenuItemWhenMove::goBack, this)); - + auto menu = Menu::create(item, back, nullptr); addChild(menu); menu->alignItemsVertically(); - - menu->setPosition(Vec2(s.width/2, s.height/2)); - + + menu->setPosition(Vec2(s.width / 2, s.height / 2)); + // Register Touch Event _touchListener = EventListenerTouchOneByOne::create(); _touchListener->setSwallowTouches(false); - + _touchListener->onTouchBegan = CC_CALLBACK_2(RemoveMenuItemWhenMove::onTouchBegan, this); _touchListener->onTouchMoved = CC_CALLBACK_2(RemoveMenuItemWhenMove::onTouchMoved, this); - + _eventDispatcher->addEventListenerWithFixedPriority(_touchListener, -129); - } -void RemoveMenuItemWhenMove::goBack(Ref *pSender) +void RemoveMenuItemWhenMove::goBack(Ref* pSender) { static_cast(_parent)->switchTo(0, false); } @@ -553,12 +532,12 @@ RemoveMenuItemWhenMove::~RemoveMenuItemWhenMove() CC_SAFE_RELEASE(item); } -bool RemoveMenuItemWhenMove::onTouchBegan(Touch *touch, Event *event) +bool RemoveMenuItemWhenMove::onTouchBegan(Touch* touch, Event* event) { return true; } -void RemoveMenuItemWhenMove::onTouchMoved(Touch *touch, Event *event) +void RemoveMenuItemWhenMove::onTouchMoved(Touch* touch, Event* event) { if (item) { diff --git a/tests/cpp-tests/Classes/MenuTest/MenuTest.h b/tests/cpp-tests/Classes/MenuTest/MenuTest.h index 7c6f82c517da..cd505ef4be99 100644 --- a/tests/cpp-tests/Classes/MenuTest/MenuTest.h +++ b/tests/cpp-tests/Classes/MenuTest/MenuTest.h @@ -43,7 +43,7 @@ class MenuTest : public TestCase class MenuLayerMainMenu : public cocos2d::Layer { protected: - cocos2d::MenuItem* _disabledItem; + cocos2d::MenuItem* _disabledItem; cocos2d::EventListenerTouchOneByOne* _touchListener; public: @@ -66,14 +66,14 @@ class MenuLayerMainMenu : public cocos2d::Layer void onQuit(cocos2d::Ref* sender); void menuMovingCallback(cocos2d::Ref* pSender); - //CREATE_NODE(MenuLayer1); + // CREATE_NODE(MenuLayer1); }; class MenuLayer2 : public cocos2d::Layer { protected: - cocos2d::Vec2 _centeredMenu; - bool _alignedH; + cocos2d::Vec2 _centeredMenu; + bool _alignedH; void alignMenusH(); void alignMenusV(); @@ -86,13 +86,13 @@ class MenuLayer2 : public cocos2d::Layer void menuCallbackOpacity(cocos2d::Ref* sender); void menuCallbackAlign(cocos2d::Ref* sender); - //CREATE_NODE(MenuLayer2); + // CREATE_NODE(MenuLayer2); }; class MenuLayer3 : public cocos2d::Layer { protected: - cocos2d::MenuItem* _disabledItem; + cocos2d::MenuItem* _disabledItem; public: MenuLayer3(); @@ -113,7 +113,7 @@ class BugsTest : public cocos2d::Layer { public: BugsTest(); - + void issue1410MenuCallback(cocos2d::Ref* pSender); void issue1410v2MenuCallback(cocos2d::Ref* pSender); void backMenuCallback(cocos2d::Ref* pSender); @@ -126,11 +126,11 @@ class RemoveMenuItemWhenMove : public cocos2d::Layer ~RemoveMenuItemWhenMove(); bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event); void onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event); - + void goBack(cocos2d::Ref* pSender); - + private: - cocos2d::MenuItemFont *item; + cocos2d::MenuItemFont* item; cocos2d::EventListenerTouchOneByOne* _touchListener; }; diff --git a/tests/cpp-tests/Classes/MotionStreakTest/MotionStreakTest.cpp b/tests/cpp-tests/Classes/MotionStreakTest/MotionStreakTest.cpp index b016c17898ac..24e21b1f66bf 100644 --- a/tests/cpp-tests/Classes/MotionStreakTest/MotionStreakTest.cpp +++ b/tests/cpp-tests/Classes/MotionStreakTest/MotionStreakTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,10 +27,11 @@ USING_NS_CC; -enum { - kTagLabel = 1, - kTagSprite1 = 2, - kTagSprite2 = 3, +enum +{ + kTagLabel = 1, + kTagSprite1 = 2, + kTagSprite2 = 3, }; MotionStreakTests::MotionStreakTests() @@ -52,46 +53,41 @@ void MotionStreakTest1::onEnter() MotionStreakTest::onEnter(); auto s = Director::getInstance()->getWinSize(); - + // the root object just rotates around _root = Sprite::create(s_pathR1); addChild(_root, 1); - _root->setPosition(Vec2(s.width/2, s.height/2)); - + _root->setPosition(Vec2(s.width / 2, s.height / 2)); + // the target object is offset from root, and the streak is moved to follow it _target = Sprite::create(s_pathR1); _root->addChild(_target); - _target->setPosition(Vec2(s.width/4, 0.0f)); + _target->setPosition(Vec2(s.width / 4, 0.0f)); // create the streak object and add it to the scene _streak = MotionStreak::create(2, 3, 32, Color3B::GREEN, s_streak); addChild(_streak); // schedule an update on each frame so we can synchronize the streak with the target schedule(CC_SCHEDULE_SELECTOR(MotionStreakTest1::onUpdate)); - + auto a1 = RotateBy::create(2, 360); auto action1 = RepeatForever::create(a1); - auto motion = MoveBy::create(2, Vec2(100,0) ); - _root->runAction( RepeatForever::create(Sequence::create(motion, motion->reverse(), nullptr) ) ); - _root->runAction( action1 ); + auto motion = MoveBy::create(2, Vec2(100, 0)); + _root->runAction(RepeatForever::create(Sequence::create(motion, motion->reverse(), nullptr))); + _root->runAction(action1); auto colorAction = RepeatForever::create(Sequence::create( - TintTo::create(0.2f, 255, 0, 0), - TintTo::create(0.2f, 0, 255, 0), - TintTo::create(0.2f, 0, 0, 255), - TintTo::create(0.2f, 0, 255, 255), - TintTo::create(0.2f, 255, 255, 0), - TintTo::create(0.2f, 255, 0, 255), - TintTo::create(0.2f, 255, 255, 255), - nullptr)); + TintTo::create(0.2f, 255, 0, 0), TintTo::create(0.2f, 0, 255, 0), TintTo::create(0.2f, 0, 0, 255), + TintTo::create(0.2f, 0, 255, 255), TintTo::create(0.2f, 255, 255, 0), TintTo::create(0.2f, 255, 0, 255), + TintTo::create(0.2f, 255, 255, 255), nullptr)); _streak->runAction(colorAction); } void MotionStreakTest1::onUpdate(float delta) { - _streak->setPosition( _target->convertToWorldSpace(Vec2::ZERO) ); + _streak->setPosition(_target->convertToWorldSpace(Vec2::ZERO)); } std::string MotionStreakTest1::title() const @@ -109,24 +105,24 @@ void MotionStreakTest2::onEnter() { MotionStreakTest::onEnter(); - auto listener = EventListenerTouchAllAtOnce::create(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesMoved = CC_CALLBACK_2(MotionStreakTest2::onTouchesMoved, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - + auto s = Director::getInstance()->getWinSize(); - + // create the streak object and add it to the scene - _streak = MotionStreak::create(3, 3, 64, Color3B::WHITE, s_streak ); + _streak = MotionStreak::create(3, 3, 64, Color3B::WHITE, s_streak); addChild(_streak); - - _streak->setPosition( Vec2(s.width/2, s.height/2) ); + + _streak->setPosition(Vec2(s.width / 2, s.height / 2)); } void MotionStreakTest2::onTouchesMoved(const std::vector& touches, Event* event) { auto touchLocation = touches[0]->getLocation(); - - _streak->setPosition( touchLocation ); + + _streak->setPosition(touchLocation); } std::string MotionStreakTest2::title() const @@ -148,26 +144,25 @@ std::string MotionStreakTest2::subtitle() const void Issue1358::onEnter() { MotionStreakTest::onEnter(); - + // ask director the the window size auto size = Director::getInstance()->getWinSize(); - + _streak = MotionStreak::create(2.0f, 1.0f, 50.0f, Color3B(255, 255, 0), "Images/Icon.png"); addChild(_streak); - - - _center = Vec2(size.width/2, size.height/2); - _radius = size.width/3; - _angle = 0.0f; - + + _center = Vec2(size.width / 2, size.height / 2); + _radius = size.width / 3; + _angle = 0.0f; + schedule(CC_SCHEDULE_SELECTOR(Issue1358::update), 0); } void Issue1358::update(float dt) { _angle += 1.0f; - _streak->setPosition(Vec2(_center.x + cosf(_angle/180 * M_PI)*_radius, - _center.y + sinf(_angle/ 180 * M_PI)*_radius)); + _streak->setPosition( + Vec2(_center.x + cosf(_angle / 180 * M_PI) * _radius, _center.y + sinf(_angle / 180 * M_PI) * _radius)); } std::string Issue1358::title() const @@ -193,15 +188,14 @@ void Issue12226::onEnter() // ask director the the window size auto size = Director::getInstance()->getWinSize(); - auto radius = size.width/3; + auto radius = size.width / 3; auto outer = Sprite::create("Images/grossini.png"); - outer->setPosition(size/2); + outer->setPosition(size / 2); addChild(outer); - _streak = MotionStreak::create(1.0f, 3, radius * 1.5f, Color3B(0xA0, 0xA0, 0xA0), "ccb/particle-smoke.png"); -// motionStreak->setOpacity(0x70); + // motionStreak->setOpacity(0x70); _streak->setPosition(outer->getPosition()); this->addChild(_streak, outer->getLocalZOrder() - 1); @@ -211,19 +205,18 @@ void Issue12226::onEnter() const uint32_t length = (radius * 0.95); std::function updateMotionStreak = [=](float dt) { - - Vec2 position = Vec2(outer->getPositionX() + length * cosf(-1 * CC_DEGREES_TO_RADIANS(outer->getRotation() + 90.0f)), - outer->getPositionY() + length * sinf(-1 * CC_DEGREES_TO_RADIANS(outer->getRotation() + 90.0f))); + Vec2 position = + Vec2(outer->getPositionX() + length * cosf(-1 * CC_DEGREES_TO_RADIANS(outer->getRotation() + 90.0f)), + outer->getPositionY() + length * sinf(-1 * CC_DEGREES_TO_RADIANS(outer->getRotation() + 90.0f))); _streak->setPosition(position); }; outer->schedule(updateMotionStreak, 1 / 240.0f, CC_REPEAT_FOREVER, 0, "motion1scheduler"); - auto rot = RotateBy::create(2, 360); + auto rot = RotateBy::create(2, 360); auto forever = RepeatForever::create(rot); outer->runAction(forever); - } std::string Issue12226::title() const @@ -242,13 +235,9 @@ std::string Issue12226::subtitle() const // //------------------------------------------------------------------ -MotionStreakTest::MotionStreakTest() -{ -} +MotionStreakTest::MotionStreakTest() {} -MotionStreakTest::~MotionStreakTest() -{ -} +MotionStreakTest::~MotionStreakTest() {} std::string MotionStreakTest::title() const { @@ -266,19 +255,18 @@ void MotionStreakTest::onEnter() auto s = Director::getInstance()->getWinSize(); - auto itemMode = MenuItemToggle::createWithCallback( CC_CALLBACK_1(MotionStreakTest::modeCallback, this), - MenuItemFont::create("Use High Quality Mode"), - MenuItemFont::create("Use Fast Mode"), - nullptr); + auto itemMode = MenuItemToggle::createWithCallback(CC_CALLBACK_1(MotionStreakTest::modeCallback, this), + MenuItemFont::create("Use High Quality Mode"), + MenuItemFont::create("Use Fast Mode"), nullptr); auto menuMode = Menu::create(itemMode, nullptr); addChild(menuMode); - menuMode->setPosition(Vec2(s.width/2, s.height/4)); + menuMode->setPosition(Vec2(s.width / 2, s.height / 4)); } -void MotionStreakTest::modeCallback(Ref *pSender) +void MotionStreakTest::modeCallback(Ref* pSender) { bool fastMode = _streak->isFastMode(); - _streak->setFastMode(! fastMode); + _streak->setFastMode(!fastMode); } diff --git a/tests/cpp-tests/Classes/MotionStreakTest/MotionStreakTest.h b/tests/cpp-tests/Classes/MotionStreakTest/MotionStreakTest.h index aa6210bfd6fe..ae0683a68256 100644 --- a/tests/cpp-tests/Classes/MotionStreakTest/MotionStreakTest.h +++ b/tests/cpp-tests/Classes/MotionStreakTest/MotionStreakTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,7 +27,6 @@ #include "../BaseTest.h" - DEFINE_TEST_SUITE(MotionStreakTests); class MotionStreakTest : public TestCase @@ -41,6 +40,7 @@ class MotionStreakTest : public TestCase virtual void onEnter() override; void modeCallback(cocos2d::Ref* sender); + protected: cocos2d::MotionStreak* _streak; }; @@ -48,8 +48,8 @@ class MotionStreakTest : public TestCase class MotionStreakTest1 : public MotionStreakTest { protected: - cocos2d::Node* _root; - cocos2d::Node* _target; + cocos2d::Node* _root; + cocos2d::Node* _target; public: CREATE_FUNC(MotionStreakTest1); @@ -61,8 +61,8 @@ class MotionStreakTest1 : public MotionStreakTest class MotionStreakTest2 : public MotionStreakTest { protected: - cocos2d::Node* _root; - cocos2d::Node* _target; + cocos2d::Node* _root; + cocos2d::Node* _target; public: CREATE_FUNC(MotionStreakTest2); @@ -81,6 +81,7 @@ class Issue1358 : public MotionStreakTest virtual std::string subtitle() const override; virtual void onEnter() override; virtual void update(float dt) override; + private: cocos2d::Vec2 _center; float _radius; @@ -97,5 +98,4 @@ class Issue12226 : public MotionStreakTest virtual void onEnter() override; }; - #endif diff --git a/tests/cpp-tests/Classes/MultiTouchTest/MultiTouchTest.cpp b/tests/cpp-tests/Classes/MultiTouchTest/MultiTouchTest.cpp index 087ffe8f07a8..d3c6c4273bc3 100644 --- a/tests/cpp-tests/Classes/MultiTouchTest/MultiTouchTest.cpp +++ b/tests/cpp-tests/Classes/MultiTouchTest/MultiTouchTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -31,29 +31,24 @@ MultiTouchTests::MultiTouchTests() ADD_TEST_CASE(MultiTouchTest); } -static const Color3B* s_TouchColors[5] = { - &Color3B::YELLOW, - &Color3B::BLUE, - &Color3B::GREEN, - &Color3B::RED, - &Color3B::MAGENTA -}; +static const Color3B* s_TouchColors[5] = {&Color3B::YELLOW, &Color3B::BLUE, &Color3B::GREEN, &Color3B::RED, + &Color3B::MAGENTA}; class TouchPoint : public Node { public: - TouchPoint(const Vec2 &touchPoint, const Color3B &touchColor) + TouchPoint(const Vec2& touchPoint, const Color3B& touchColor) { DrawNode* drawNode = DrawNode::create(); - auto s = Director::getInstance()->getWinSize(); - Color4F color(touchColor.r/255.0f, touchColor.g/255.0f, touchColor.b/255.0f, 1.0f); + auto s = Director::getInstance()->getWinSize(); + Color4F color(touchColor.r / 255.0f, touchColor.g / 255.0f, touchColor.b / 255.0f, 1.0f); drawNode->drawLine(Vec2(0.0f, touchPoint.y), Vec2(s.width, touchPoint.y), color); drawNode->drawLine(Vec2(touchPoint.x, 0.0f), Vec2(touchPoint.x, s.height), color); drawNode->drawDot(touchPoint, 3, color); addChild(drawNode); } - static TouchPoint* touchPointWithParent(Node* pParent, const Vec2 &touchPoint, const Color3B &touchColor) + static TouchPoint* touchPointWithParent(Node* pParent, const Vec2& touchPoint, const Color3B& touchColor) { auto pRet = new TouchPoint(touchPoint, touchColor); pRet->setContentSize(pParent->getContentSize()); @@ -67,16 +62,16 @@ bool MultiTouchTest::init() { if (TestCase::init()) { - auto listener = EventListenerTouchAllAtOnce::create(); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(MultiTouchTest::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(MultiTouchTest::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(MultiTouchTest::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - + auto title = Label::createWithSystemFont("Please touch the screen!", "", 24); - title->setPosition(VisibleRect::top()+Vec2(0.0f, -40.0f)); + title->setPosition(VisibleRect::top() + Vec2(0.0f, -40.0f)); addChild(title); - + return true; } return false; @@ -84,48 +79,48 @@ bool MultiTouchTest::init() static Map s_map; -void MultiTouchTest::onTouchesBegan(const std::vector& touches, Event *event) +void MultiTouchTest::onTouchesBegan(const std::vector& touches, Event* event) { - for ( auto &item: touches ) + for (auto& item : touches) { - auto touch = item; - auto location = touch->getLocation(); - auto touchPoint = TouchPoint::touchPointWithParent(this, location, *s_TouchColors[touch->getID()%5]); + auto touch = item; + auto location = touch->getLocation(); + auto touchPoint = TouchPoint::touchPointWithParent(this, location, *s_TouchColors[touch->getID() % 5]); addChild(touchPoint); s_map.insert(touch->getID(), touchPoint); } } -void MultiTouchTest::onTouchesMoved(const std::vector& touches, Event *event) +void MultiTouchTest::onTouchesMoved(const std::vector& touches, Event* event) { - for( auto &item: touches) + for (auto& item : touches) { - auto touch = item; - auto pTP = s_map.at(touch->getID()); + auto touch = item; + auto pTP = s_map.at(touch->getID()); auto location = touch->getLocation(); - + removeChild(pTP, true); s_map.erase(touch->getID()); - - auto touchPointNew = TouchPoint::touchPointWithParent(this, location, *s_TouchColors[touch->getID()%5]); + + auto touchPointNew = TouchPoint::touchPointWithParent(this, location, *s_TouchColors[touch->getID() % 5]); addChild(touchPointNew); s_map.insert(touch->getID(), touchPointNew); } } -void MultiTouchTest::onTouchesEnded(const std::vector& touches, Event *event) +void MultiTouchTest::onTouchesEnded(const std::vector& touches, Event* event) { - for ( auto &item: touches ) + for (auto& item : touches) { auto touch = item; - auto pTP = s_map.at(touch->getID()); + auto pTP = s_map.at(touch->getID()); removeChild(pTP, true); s_map.erase(touch->getID()); } } -void MultiTouchTest::onTouchesCancelled(const std::vector& touches, Event *event) +void MultiTouchTest::onTouchesCancelled(const std::vector& touches, Event* event) { onTouchesEnded(touches, event); } diff --git a/tests/cpp-tests/Classes/MultiTouchTest/MultiTouchTest.h b/tests/cpp-tests/Classes/MultiTouchTest/MultiTouchTest.h index 94f6c65bd50a..f16ec67e5a7f 100644 --- a/tests/cpp-tests/Classes/MultiTouchTest/MultiTouchTest.h +++ b/tests/cpp-tests/Classes/MultiTouchTest/MultiTouchTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -36,10 +36,10 @@ class MultiTouchTest : public TestCase virtual bool init() override; - void onTouchesBegan(const std::vector& touches, cocos2d::Event *event); - void onTouchesMoved(const std::vector& touches, cocos2d::Event *event); - void onTouchesEnded(const std::vector& touches, cocos2d::Event *event); - void onTouchesCancelled(const std::vector& touches, cocos2d::Event *event); + void onTouchesBegan(const std::vector& touches, cocos2d::Event* event); + void onTouchesMoved(const std::vector& touches, cocos2d::Event* event); + void onTouchesEnded(const std::vector& touches, cocos2d::Event* event); + void onTouchesCancelled(const std::vector& touches, cocos2d::Event* event); }; #endif /* __MULTITOUCHTEST_H__ */ diff --git a/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.cpp b/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.cpp index 6e9fa8c7f39b..7bce80fd971d 100644 --- a/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.cpp +++ b/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.cpp @@ -2,19 +2,19 @@ Copyright (c) 2012 cocos2d-x.org Copyright (c) 2015-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -40,7 +40,7 @@ struct AgentUserData NavMeshTests::NavMeshTests() { -#if ( CC_USE_NAVMESH == 0 ) || ( CC_USE_PHYSICS == 0 ) +#if (CC_USE_NAVMESH == 0) || (CC_USE_PHYSICS == 0) ADD_TEST_CASE(NavMeshDisabled); #else ADD_TEST_CASE(NavMeshBasicTestDemo); @@ -48,12 +48,13 @@ NavMeshTests::NavMeshTests() #endif }; -#if ( CC_USE_NAVMESH == 0 ) || ( CC_USE_PHYSICS == 0 ) +#if (CC_USE_NAVMESH == 0) || (CC_USE_PHYSICS == 0) void NavMeshDisabled::onEnter() { TTFConfig ttfConfig("fonts/arial.ttf", 16); - auto label = Label::createWithTTF(ttfConfig, "Should define CC_USE_NAVMESH & CC_USE_PHYSICS\n to run this test case"); - + auto label = + Label::createWithTTF(ttfConfig, "Should define CC_USE_NAVMESH & CC_USE_PHYSICS\n to run this test case"); + auto size = Director::getInstance()->getWinSize(); label->setPosition(Vec2(size.width / 2, size.height / 2)); @@ -63,26 +64,24 @@ void NavMeshDisabled::onEnter() } #else -NavMeshBaseTestDemo::NavMeshBaseTestDemo() - : _camera(nullptr) - , _needMoveAgents(false) -{ - -} +NavMeshBaseTestDemo::NavMeshBaseTestDemo() : _camera(nullptr), _needMoveAgents(false) {} NavMeshBaseTestDemo::~NavMeshBaseTestDemo() { - for (auto iter : _agents){ - AgentUserData *data = static_cast(iter.first->getUserData()); + for (auto iter : _agents) + { + AgentUserData* data = static_cast(iter.first->getUserData()); delete data; } } -bool NavMeshBaseTestDemo::init() +bool NavMeshBaseTestDemo::init() { - if (!TestCase::init()) return false; + if (!TestCase::init()) + return false; - if (initPhysicsWorld()) { + if (initPhysicsWorld()) + { _angle = 0.0f; @@ -103,17 +102,16 @@ bool NavMeshBaseTestDemo::init() scheduleUpdate(); } - return true; } -void NavMeshBaseTestDemo::onTouchesBegan(const std::vector& touches, cocos2d::Event *event) +void NavMeshBaseTestDemo::onTouchesBegan(const std::vector& touches, cocos2d::Event* event) { _needMoveAgents = true; touchesBegan(touches, event); } -void NavMeshBaseTestDemo::onTouchesMoved(const std::vector& touches, cocos2d::Event *event) +void NavMeshBaseTestDemo::onTouchesMoved(const std::vector& touches, cocos2d::Event* event) { if (touches.size() && _camera) { @@ -132,7 +130,7 @@ void NavMeshBaseTestDemo::onTouchesMoved(const std::vector& tou touchesMoved(touches, event); } -void NavMeshBaseTestDemo::onTouchesEnded(const std::vector& touches, cocos2d::Event *event) +void NavMeshBaseTestDemo::onTouchesEnded(const std::vector& touches, cocos2d::Event* event) { touchesEnded(touches, event); } @@ -140,7 +138,7 @@ void NavMeshBaseTestDemo::onTouchesEnded(const std::vector& tou void NavMeshBaseTestDemo::initScene() { getPhysics3DWorld()->setDebugDrawEnable(false); - //create mesh + // create mesh std::vector trianglesList = Bundle3D::getTrianglesList("NavMesh/scene.obj"); Physics3DRigidBodyDes rbDes; @@ -159,7 +157,6 @@ void NavMeshBaseTestDemo::initScene() setNavMesh(navMesh); setNavMeshDebugCamera(_camera); - auto ambientLight = AmbientLight::create(Color3B(64, 64, 64)); ambientLight->setCameraMask((unsigned short)CameraFlag::USER1); this->addChild(ambientLight); @@ -169,7 +166,7 @@ void NavMeshBaseTestDemo::initScene() this->addChild(dirLight); } -void NavMeshBaseTestDemo::createAgent(const Vec3 &pos) +void NavMeshBaseTestDemo::createAgent(const Vec3& pos) { std::string filePath = "Sprite3DTest/girl.c3b"; NavMeshAgentParam param; @@ -179,7 +176,7 @@ void NavMeshBaseTestDemo::createAgent(const Vec3 &pos) auto agent = NavMeshAgent::create(param); auto agentNode = Sprite3D::create(filePath); agent->setOrientationRefAxes(Vec3(-1.0f, 0.0f, 1.0f)); - AgentUserData *data = new AgentUserData{ 0.0f }; + AgentUserData* data = new AgentUserData{0.0f}; agent->setUserData(data); agentNode->setScale(0.05f); agentNode->addComponent(agent); @@ -190,10 +187,10 @@ void NavMeshBaseTestDemo::createAgent(const Vec3 &pos) node->setCameraMask((unsigned short)CameraFlag::USER1); this->addChild(node); - auto animation = Animation3D::create(filePath); auto animate = Animate3D::create(animation); - if (animate){ + if (animate) + { agentNode->runAction(RepeatForever::create(animate)); animate->setSpeed(0); } @@ -201,7 +198,7 @@ void NavMeshBaseTestDemo::createAgent(const Vec3 &pos) _agents.push_back(std::make_pair(agent, animate)); } -void NavMeshBaseTestDemo::createObstacle(const Vec3 &pos) +void NavMeshBaseTestDemo::createObstacle(const Vec3& pos) { auto obstacle = NavMeshObstacle::create(2.0f, 8.0f); auto obstacleNode = Sprite3D::create("Sprite3DTest/cylinder.c3b"); @@ -223,17 +220,20 @@ Vec3 jump(const Vec3* pV1, const Vec3* pV2, float height, float t) return pOut; } -void NavMeshBaseTestDemo::moveAgents(const cocos2d::Vec3 &des) +void NavMeshBaseTestDemo::moveAgents(const cocos2d::Vec3& des) { - for (auto iter : _agents){ - NavMeshAgent::MoveCallback callback = [](NavMeshAgent *agent, float totalTimeAfterMove){ - AgentUserData *data = static_cast(agent->getUserData()); - if (agent->isOnOffMeshLink()){ + for (auto iter : _agents) + { + NavMeshAgent::MoveCallback callback = [](NavMeshAgent* agent, float totalTimeAfterMove) { + AgentUserData* data = static_cast(agent->getUserData()); + if (agent->isOnOffMeshLink()) + { agent->setAutoTraverseOffMeshLink(false); agent->setAutoOrientation(false); OffMeshLinkData linkdata = agent->getCurrentOffMeshLinkData(); - agent->getOwner()->setPosition3D(jump(&linkdata.startPosition, &linkdata.endPosition, 10.0f, data->time)); + agent->getOwner()->setPosition3D( + jump(&linkdata.startPosition, &linkdata.endPosition, 10.0f, data->time)); Vec3 dir = linkdata.endPosition - linkdata.startPosition; dir.y = 0.0f; dir.normalize(); @@ -244,7 +244,8 @@ void NavMeshBaseTestDemo::moveAgents(const cocos2d::Vec3 &des) float angle = Vec3::dot(refAxes, dir); agent->getOwner()->setRotationQuat(Quaternion(axes, acosf(angle))); data->time += 0.01f; - if (1.0f < data->time){ + if (1.0f < data->time) + { agent->completeOffMeshLink(); agent->setAutoOrientation(true); data->time = 0.0f; @@ -257,20 +258,16 @@ void NavMeshBaseTestDemo::moveAgents(const cocos2d::Vec3 &des) void NavMeshBaseTestDemo::update(float delta) { - for (auto iter : _agents){ + for (auto iter : _agents) + { float speed = iter.first->getCurrentVelocity().length() * 0.2f; iter.second->setSpeed(0.0f < speed ? speed : 0.0f); } } -NavMeshBasicTestDemo::NavMeshBasicTestDemo() -{ - -} +NavMeshBasicTestDemo::NavMeshBasicTestDemo() {} -NavMeshBasicTestDemo::~NavMeshBasicTestDemo() -{ -} +NavMeshBasicTestDemo::~NavMeshBasicTestDemo() {} std::string NavMeshBasicTestDemo::title() const { @@ -282,10 +279,12 @@ std::string NavMeshBasicTestDemo::subtitle() const return "Basic Test"; } -void NavMeshBasicTestDemo::touchesEnded(const std::vector& touches, cocos2d::Event *event) +void NavMeshBasicTestDemo::touchesEnded(const std::vector& touches, cocos2d::Event* event) { - if (!_needMoveAgents) return; - if (!touches.empty()){ + if (!_needMoveAgents) + return; + if (!touches.empty()) + { auto touch = touches[0]; auto location = touch->getLocationInView(); Vec3 nearP(location.x, location.y, 0.0f), farP(location.x, location.y, 1.0f); @@ -302,18 +301,21 @@ void NavMeshBasicTestDemo::touchesEnded(const std::vector& touc bool NavMeshBasicTestDemo::init() { - if (!NavMeshBaseTestDemo::init()) return false; + if (!NavMeshBaseTestDemo::init()) + return false; TTFConfig ttfConfig("fonts/arial.ttf", 15); _debugLabel = Label::createWithTTF(ttfConfig, "Debug Draw ON"); _debugLabel->retain(); - auto menuItem1 = MenuItemLabel::create(_debugLabel, [=](Ref*){ + auto menuItem1 = MenuItemLabel::create(_debugLabel, [=](Ref*) { bool enabledDebug = !getNavMesh()->isDebugDrawEnabled(); getNavMesh()->setDebugDrawEnable(enabledDebug); - if (enabledDebug){ + if (enabledDebug) + { _debugLabel->setString("Debug Draw ON"); } - else{ + else + { _debugLabel->setString("Debug Draw OFF"); } }); @@ -329,25 +331,20 @@ bool NavMeshBasicTestDemo::init() void NavMeshBasicTestDemo::onEnter() { NavMeshBaseTestDemo::onEnter(); - + Physics3DWorld::HitResult result; getPhysics3DWorld()->rayCast(Vec3(0.0f, 50.0f, 0.0f), Vec3(0.0f, -50.0f, 0.0f), &result); createAgent(result.hitPosition); } -NavMeshAdvanceTestDemo::NavMeshAdvanceTestDemo() -{ - -} - -NavMeshAdvanceTestDemo::~NavMeshAdvanceTestDemo() -{ +NavMeshAdvanceTestDemo::NavMeshAdvanceTestDemo() {} -} +NavMeshAdvanceTestDemo::~NavMeshAdvanceTestDemo() {} bool NavMeshAdvanceTestDemo::init() { - if (!NavMeshBaseTestDemo::init()) return false; + if (!NavMeshBaseTestDemo::init()) + return false; TTFConfig ttfConfig("fonts/arial.ttf", 15); _obstacleLabel = Label::createWithTTF(ttfConfig, "Create Obstacle"); @@ -357,7 +354,7 @@ bool NavMeshAdvanceTestDemo::init() _debugLabel = Label::createWithTTF(ttfConfig, "Debug Draw ON"); _debugLabel->retain(); - auto menuItem0 = MenuItemLabel::create(_obstacleLabel, [=](Ref*){ + auto menuItem0 = MenuItemLabel::create(_obstacleLabel, [=](Ref*) { float x = cocos2d::random(-50.0f, 50.0f); float z = cocos2d::random(-50.0f, 50.0f); Physics3DWorld::HitResult result; @@ -367,7 +364,7 @@ bool NavMeshAdvanceTestDemo::init() menuItem0->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT); menuItem0->setPosition(Vec2(VisibleRect::left().x, VisibleRect::top().y - 50)); - auto menuItem1 = MenuItemLabel::create(_agentLabel, [=](Ref*){ + auto menuItem1 = MenuItemLabel::create(_agentLabel, [=](Ref*) { float x = cocos2d::random(-50.0f, 50.0f); float z = cocos2d::random(-50.0f, 50.0f); Physics3DWorld::HitResult result; @@ -377,13 +374,15 @@ bool NavMeshAdvanceTestDemo::init() menuItem1->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT); menuItem1->setPosition(Vec2(VisibleRect::left().x, VisibleRect::top().y - 100)); - auto menuItem2 = MenuItemLabel::create(_debugLabel, [=](Ref*){ + auto menuItem2 = MenuItemLabel::create(_debugLabel, [=](Ref*) { bool enabledDebug = !getNavMesh()->isDebugDrawEnabled(); getNavMesh()->setDebugDrawEnable(enabledDebug); - if (enabledDebug){ + if (enabledDebug) + { _debugLabel->setString("Debug Draw ON"); } - else{ + else + { _debugLabel->setString("Debug Draw OFF"); } }); @@ -393,14 +392,14 @@ bool NavMeshAdvanceTestDemo::init() auto menu = Menu::create(menuItem0, menuItem1, menuItem2, nullptr); menu->setPosition(Vec2::ZERO); addChild(menu); - + return true; } void NavMeshAdvanceTestDemo::onEnter() { NavMeshBaseTestDemo::onEnter(); - + Physics3DWorld::HitResult result; getPhysics3DWorld()->rayCast(Vec3(0.0f, 50.0f, 0.0f), Vec3(0.0f, -50.0f, 0.0f), &result); createAgent(result.hitPosition); @@ -416,10 +415,12 @@ std::string NavMeshAdvanceTestDemo::subtitle() const return "Advance Test"; } -void NavMeshAdvanceTestDemo::touchesEnded(const std::vector& touches, cocos2d::Event *event) +void NavMeshAdvanceTestDemo::touchesEnded(const std::vector& touches, cocos2d::Event* event) { - if (!_needMoveAgents) return; - if (!touches.empty()){ + if (!_needMoveAgents) + return; + if (!touches.empty()) + { auto touch = touches[0]; auto location = touch->getLocationInView(); Vec3 nearP(location.x, location.y, 0.0f), farP(location.x, location.y, 1.0f); diff --git a/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.h b/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.h index fc2d1a58ebe6..63e07ee041a7 100644 --- a/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.h +++ b/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.h @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2013 cocos2d-x.org Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -32,7 +32,7 @@ DEFINE_TEST_SUITE(NavMeshTests); -#if ( CC_USE_NAVMESH == 0 ) || ( CC_USE_PHYSICS == 0 ) +#if (CC_USE_NAVMESH == 0) || (CC_USE_PHYSICS == 0) class NavMeshDisabled : public TestCase { public: @@ -52,24 +52,23 @@ class NavMeshBaseTestDemo : public TestCase // overrides virtual bool init() override; virtual void update(float delta) override; - virtual void onTouchesBegan(const std::vector& touches, cocos2d::Event *event); - virtual void onTouchesMoved(const std::vector& touches, cocos2d::Event *event); - virtual void onTouchesEnded(const std::vector& touches, cocos2d::Event *event); + virtual void onTouchesBegan(const std::vector& touches, cocos2d::Event* event); + virtual void onTouchesMoved(const std::vector& touches, cocos2d::Event* event); + virtual void onTouchesEnded(const std::vector& touches, cocos2d::Event* event); protected: - void initScene(); - void createAgent(const cocos2d::Vec3 &pos); - void createObstacle(const cocos2d::Vec3 &pos); - void moveAgents(const cocos2d::Vec3 &des); - virtual void touchesBegan(const std::vector& touches, cocos2d::Event *event){}; - virtual void touchesMoved(const std::vector& touches, cocos2d::Event *event){}; - virtual void touchesEnded(const std::vector& touches, cocos2d::Event *event){}; + void createAgent(const cocos2d::Vec3& pos); + void createObstacle(const cocos2d::Vec3& pos); + void moveAgents(const cocos2d::Vec3& des); + virtual void touchesBegan(const std::vector& touches, cocos2d::Event* event){}; + virtual void touchesMoved(const std::vector& touches, cocos2d::Event* event){}; + virtual void touchesEnded(const std::vector& touches, cocos2d::Event* event){}; protected: - cocos2d::Camera *_camera; + cocos2d::Camera* _camera; float _angle; - std::vector > _agents; + std::vector> _agents; bool _needMoveAgents; }; @@ -79,22 +78,21 @@ class NavMeshBasicTestDemo : public NavMeshBaseTestDemo CREATE_FUNC(NavMeshBasicTestDemo); NavMeshBasicTestDemo(); virtual ~NavMeshBasicTestDemo(); - + // overrides virtual bool init() override; virtual std::string title() const override; virtual std::string subtitle() const override; - + virtual void onEnter() override; - -protected: - virtual void touchesBegan(const std::vector& touches, cocos2d::Event *event)override{}; - virtual void touchesMoved(const std::vector& touches, cocos2d::Event *event)override{}; - virtual void touchesEnded(const std::vector& touches, cocos2d::Event *event)override; +protected: + virtual void touchesBegan(const std::vector& touches, cocos2d::Event* event) override{}; + virtual void touchesMoved(const std::vector& touches, cocos2d::Event* event) override{}; + virtual void touchesEnded(const std::vector& touches, cocos2d::Event* event) override; protected: - cocos2d::Label *_debugLabel; + cocos2d::Label* _debugLabel; }; class NavMeshAdvanceTestDemo : public NavMeshBaseTestDemo @@ -108,19 +106,18 @@ class NavMeshAdvanceTestDemo : public NavMeshBaseTestDemo virtual bool init() override; virtual std::string title() const override; virtual std::string subtitle() const override; - + virtual void onEnter() override; protected: - - virtual void touchesBegan(const std::vector& touches, cocos2d::Event *event)override{}; - virtual void touchesMoved(const std::vector& touches, cocos2d::Event *event)override{}; - virtual void touchesEnded(const std::vector& touches, cocos2d::Event *event)override; + virtual void touchesBegan(const std::vector& touches, cocos2d::Event* event) override{}; + virtual void touchesMoved(const std::vector& touches, cocos2d::Event* event) override{}; + virtual void touchesEnded(const std::vector& touches, cocos2d::Event* event) override; protected: - cocos2d::Label *_obstacleLabel; - cocos2d::Label *_agentLabel; - cocos2d::Label *_debugLabel; + cocos2d::Label* _obstacleLabel; + cocos2d::Label* _agentLabel; + cocos2d::Label* _debugLabel; }; #endif diff --git a/tests/cpp-tests/Classes/NetworkTest/DownloaderTest/DownloaderTest.cpp b/tests/cpp-tests/Classes/NetworkTest/DownloaderTest/DownloaderTest.cpp index 46376391538b..8b63a52711ea 100644 --- a/tests/cpp-tests/Classes/NetworkTest/DownloaderTest/DownloaderTest.cpp +++ b/tests/cpp-tests/Classes/NetworkTest/DownloaderTest/DownloaderTest.cpp @@ -34,16 +34,13 @@ USING_NS_CC; -static const char* sURLList[] = -{ - "https://www.cocos2d-x.org/attachments/802/cocos2dx_landscape.png", - "https://cocos2d-x.org/images/logo.png", +static const char* sURLList[] = { + "https://www.cocos2d-x.org/attachments/802/cocos2dx_landscape.png", "https://cocos2d-x.org/images/logo.png", "https://www.cocos2d-x.org/attachments/1503/no_exist.txt", // try to download no exist file - "https://cdn-fastly.obsproject.com/downloads/OBS-Studio-27.0.1-Full-Installer-x64.exe" // "https://github.com/openssl/openssl/archive/OpenSSL_1_1_1a.zip", + "https://cdn-fastly.obsproject.com/downloads/OBS-Studio-27.0.1-Full-Installer-x64.exe" // "https://github.com/openssl/openssl/archive/OpenSSL_1_1_1a.zip", }; -const static int sListSize = (sizeof(sURLList)/sizeof(sURLList[0])); -static const char* sNameList[sListSize] = -{ +const static int sListSize = (sizeof(sURLList) / sizeof(sURLList[0])); +static const char* sNameList[sListSize] = { "cocos2dx_landscape.png", "logo.png", "inexist file", @@ -53,50 +50,47 @@ static const char* sNameList[sListSize] = struct DownloaderTest : public TestCase { CREATE_FUNC(DownloaderTest); - + virtual std::string title() const override { return "Downloader Test"; } - + std::unique_ptr downloader; - - DownloaderTest() + + DownloaderTest() { downloader.reset(new network::Downloader()); } + + enum { - downloader.reset(new network::Downloader()); - } - - enum { TAG_TITLE = 1, TAG_BUTTON, TAG_PROGRESS_BAR, TAG_STATUS, TAG_SPRITE, }; - - Node* createDownloadView(const char *name, const cocos2d::ui::Button::ccWidgetClickCallback &callback) + + Node* createDownloadView(const char* name, const cocos2d::ui::Button::ccWidgetClickCallback& callback) { Size viewSize(220, 120); float margin = 5; - + // create background auto bg = ui::Scale9Sprite::createWithSpriteFrameName("button_actived.png"); bg->setContentSize(viewSize); - + // add a title on the top - auto title = Label::createWithTTF(name,"fonts/arial.ttf",16); + auto title = Label::createWithTTF(name, "fonts/arial.ttf", 16); title->setTag(TAG_TITLE); title->setAnchorPoint(Vec2(0.5f, 1.0f)); title->setPosition(viewSize.width / 2, viewSize.height - margin); bg->addChild(title, 10); - + // add a button on the bottom - auto btn = ui::Button::create("cocosui/animationbuttonnormal.png", - "cocosui/animationbuttonpressed.png"); + auto btn = ui::Button::create("cocosui/animationbuttonnormal.png", "cocosui/animationbuttonpressed.png"); btn->setTag(TAG_BUTTON); btn->setTitleText("Download"); btn->setAnchorPoint(Vec2(0.5f, 0.0f)); btn->setPosition(Vec2(viewSize.width / 2, margin)); btn->addClickEventListener(callback); bg->addChild(btn, 10); - + // add a progress bar auto bar = ui::LoadingBar::create("ccs-res/cocosui/sliderProgress.png"); bar->setTag(TAG_PROGRESS_BAR); @@ -108,7 +102,7 @@ struct DownloaderTest : public TestCase bg->addChild(bar, 10); // add a status label - auto label = Label::createWithTTF("","fonts/arial.ttf",14); + auto label = Label::createWithTTF("", "fonts/arial.ttf", 14); label->setTag(TAG_STATUS); label->setAnchorPoint(Vec2(0.5f, 0.5f)); label->setPosition(Vec2(viewSize.width / 2, viewSize.height / 2)); @@ -116,21 +110,20 @@ struct DownloaderTest : public TestCase label->setAlignment(TextHAlignment::CENTER, TextVAlignment::CENTER); label->setDimensions(viewSize.width, viewSize.height); bg->addChild(label, 20); - + return bg; } - + virtual void onEnter() override { TestCase::onEnter(); _restartTestItem->setVisible(true); - + SpriteFrameCache::getInstance()->addSpriteFramesWithFile(s_s9s_ui_plist); // add four download view in test case - Node* topRightView = createDownloadView(sNameList[0], [this](Ref*) - { - auto view = this->getChildByName(sNameList[0]); + Node* topRightView = createDownloadView(sNameList[0], [this](Ref*) { + auto view = this->getChildByName(sNameList[0]); auto sprite = view->getChildByTag(TAG_SPRITE); if (sprite) { @@ -149,9 +142,8 @@ struct DownloaderTest : public TestCase topRightView->setPosition(VisibleRect::center()); this->addChild(topRightView); - Node* topLeftView = createDownloadView(sNameList[1], [this](Ref*) - { - auto view = this->getChildByName(sNameList[1]); + Node* topLeftView = createDownloadView(sNameList[1], [this](Ref*) { + auto view = this->getChildByName(sNameList[1]); auto sprite = view->getChildByTag(TAG_SPRITE); if (sprite) { @@ -171,9 +163,8 @@ struct DownloaderTest : public TestCase topLeftView->setPosition(VisibleRect::center()); this->addChild(topLeftView); - Node* bottomLeftView = createDownloadView(sNameList[2], [this](Ref*) - { - auto view = this->getChildByName(sNameList[2]); + Node* bottomLeftView = createDownloadView(sNameList[2], [this](Ref*) { + auto view = this->getChildByName(sNameList[2]); auto sprite = view->getChildByTag(TAG_SPRITE); if (sprite) { @@ -194,10 +185,9 @@ struct DownloaderTest : public TestCase bottomLeftView->setPosition(VisibleRect::center()); this->addChild(bottomLeftView); - Node* bottomRightView = createDownloadView(sNameList[3], [this](Ref*) - { + Node* bottomRightView = createDownloadView(sNameList[3], [this](Ref*) { auto view = this->getChildByName(sNameList[3]); - auto btn = (ui::Button*)view->getChildByTag(TAG_BUTTON); + auto btn = (ui::Button*)view->getChildByTag(TAG_BUTTON); btn->setEnabled(false); btn->setVisible(false); auto bar = (ui::LoadingBar*)view->getChildByTag(TAG_PROGRESS_BAR); @@ -205,7 +195,8 @@ struct DownloaderTest : public TestCase bar->setVisible(true); bar->setEnabled(true); auto path = FileUtils::getInstance()->getWritablePath() + "CppTests/DownloaderTest/" + sNameList[3]; - auto task = this->downloader->createDownloadFileTask(sURLList[3], path, sNameList[3], "730cfe31b344ba77d87d0a896af710d4", false); + auto task = this->downloader->createDownloadFileTask(sURLList[3], path, sNameList[3], + "730cfe31b344ba77d87d0a896af710d4", false); task->progressInfo.totalBytesExpected = 89945032; }); bottomRightView->setName(sNameList[3]); @@ -214,22 +205,20 @@ struct DownloaderTest : public TestCase this->addChild(bottomRightView); // define progress callback - downloader->onTaskProgress = [this](const network::DownloadTask& task) - { - Node* view = this->getChildByName(task.identifier); - auto bar = (ui::LoadingBar*)view->getChildByTag(TAG_PROGRESS_BAR); + downloader->onTaskProgress = [this](const network::DownloadTask& task) { + Node* view = this->getChildByName(task.identifier); + auto bar = (ui::LoadingBar*)view->getChildByTag(TAG_PROGRESS_BAR); float percent = float(task.progressInfo.totalBytesReceived * 100) / task.progressInfo.totalBytesExpected; bar->setPercent(percent); char buf[128]; - sprintf(buf, "%.1f%%[total %d KB]", percent, int(task.progressInfo.totalBytesExpected/1024)); + sprintf(buf, "%.1f%%[total %d KB]", percent, int(task.progressInfo.totalBytesExpected / 1024)); auto status = (Label*)view->getChildByTag(TAG_STATUS); status->setString(buf); }; - + // define success callback downloader->onDataTaskSuccess = [this](const cocos2d::network::DownloadTask& task, - std::vector& data) - { + std::vector& data) { // create texture from data Texture2D* texture = nullptr; do @@ -239,21 +228,21 @@ struct DownloaderTest : public TestCase { break; } - + texture = new Texture2D(); if (false == texture->initWithImage(&img)) { break; } - auto sprite = Sprite::createWithTexture(texture); - auto view = this->getChildByName(task.identifier); + auto sprite = Sprite::createWithTexture(texture); + auto view = this->getChildByName(task.identifier); auto viewSize = view->getContentSize(); sprite->setPosition(viewSize.width / 2, viewSize.height / 2); auto spriteSize = sprite->getContentSize(); float scale = MIN((viewSize.height - 20) / spriteSize.height, (viewSize.width - 20) / spriteSize.width); sprite->setScale(scale); view->addChild(sprite, 5, TAG_SPRITE); - + auto btn = (ui::Button*)view->getChildByTag(TAG_BUTTON); btn->setEnabled(true); btn->setVisible(true); @@ -262,14 +251,14 @@ struct DownloaderTest : public TestCase } while (0); CC_SAFE_RELEASE(texture); }; - - downloader->onFileTaskSuccess = [this](const cocos2d::network::DownloadTask& task) - { + + downloader->onFileTaskSuccess = [this](const cocos2d::network::DownloadTask& task) { Texture2D* texture = nullptr; do { auto view = this->getChildByName(task.identifier); - if (task.storagePath.find(".png") != std::string::npos) { + if (task.storagePath.find(".png") != std::string::npos) + { // create sprite from file auto sprite = Sprite::create(task.storagePath); auto viewSize = view->getContentSize(); @@ -280,10 +269,12 @@ struct DownloaderTest : public TestCase sprite->setScale(scale); view->addChild(sprite, 5, TAG_SPRITE); CC_SAFE_RELEASE(texture); - } else { + } + else + { // download big file success - auto msg = StringUtils::format("Download [%s] success.", task.identifier.c_str()); - auto status = (Label*) view->getChildByTag(TAG_STATUS); + auto msg = StringUtils::format("Download [%s] success.", task.identifier.c_str()); + auto status = (Label*)view->getChildByTag(TAG_STATUS); status->setString(msg); } auto btn = (ui::Button*)view->getChildByTag(TAG_BUTTON); @@ -293,23 +284,16 @@ struct DownloaderTest : public TestCase bar->setVisible(false); } while (0); }; - + // define failed callback - downloader->onTaskError = [this](const cocos2d::network::DownloadTask& task, - int errorCode, - int errorCodeInternal, - const std::string& errorStr) - { - log("Failed to download : %s, identifier(%s) error code(%d), internal error code(%d) desc(%s)" - , task.requestURL.c_str() - , task.identifier.c_str() - , errorCode - , errorCodeInternal - , errorStr.c_str()); - auto view = this->getChildByName(task.identifier); + downloader->onTaskError = [this](const cocos2d::network::DownloadTask& task, int errorCode, + int errorCodeInternal, std::string_view errorStr) { + log("Failed to download : %s, identifier(%s) error code(%d), internal error code(%d) desc(%s)", + task.requestURL.c_str(), task.identifier.c_str(), errorCode, errorCodeInternal, errorStr.data()); + auto view = this->getChildByName(task.identifier); auto status = (Label*)view->getChildByTag(TAG_STATUS); status->setString(errorStr.length() ? errorStr : "Download failed."); - + auto btn = (ui::Button*)view->getChildByTag(TAG_BUTTON); btn->setEnabled(true); btn->setVisible(true); @@ -339,25 +323,22 @@ struct DownloaderMultiTask : public TestCase char path[256]; char name[64]; // add 64 download task at same time. - for(int i=0; i< 64;i++){ + for (int i = 0; i < 64; i++) + { sprintf(name, "%d_%s", i, sNameList[0]); sprintf(path, "%sCppTests/DownloaderTest/%s", FileUtils::getInstance()->getWritablePath().c_str(), name); log("downloader task create: %s", name); this->downloader->createDownloadFileTask(sURLList[0], path, name); } - downloader->onFileTaskSuccess = ([] (const network::DownloadTask& task) { - log("downloader task success: %s", task.identifier.c_str()); - }); + downloader->onFileTaskSuccess = + ([](const network::DownloadTask& task) { log("downloader task success: %s", task.identifier.c_str()); }); - downloader->onTaskError = ([] (const network::DownloadTask& task, int errorCode, int errorCodeInternal, const std::string& errorStr) { - log("downloader task failed : %s, identifier(%s) error code(%d), internal error code(%d) desc(%s)" - , task.requestURL.c_str() - , task.identifier.c_str() - , errorCode - , errorCodeInternal - , errorStr.c_str()); - }); + downloader->onTaskError = + ([](const network::DownloadTask& task, int errorCode, int errorCodeInternal, std::string_view errorStr) { + log("downloader task failed : %s, identifier(%s) error code(%d), internal error code(%d) desc(%s)", + task.requestURL.c_str(), task.identifier.c_str(), errorCode, errorCodeInternal, errorStr.data()); + }); } }; diff --git a/tests/cpp-tests/Classes/NetworkTest/HttpClientTest/HttpClientTest.cpp b/tests/cpp-tests/Classes/NetworkTest/HttpClientTest/HttpClientTest.cpp index d77782ff1eb2..5c2c8a52bbeb 100644 --- a/tests/cpp-tests/Classes/NetworkTest/HttpClientTest/HttpClientTest.cpp +++ b/tests/cpp-tests/Classes/NetworkTest/HttpClientTest/HttpClientTest.cpp @@ -3,17 +3,17 @@ Copyright (c) Bytedance Inc. https://adxe.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 @@ -29,7 +29,9 @@ USING_NS_CC; using namespace cocos2d::network; -#define CHROME_UA "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" +#define CHROME_UA \ + "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 " \ + "Safari/537.36" HttpClientTests::HttpClientTests() { @@ -37,8 +39,7 @@ HttpClientTests::HttpClientTests() ADD_TEST_CASE(HttpClientClearRequestsTest); } -HttpClientTest::HttpClientTest() -: _labelStatusCode(nullptr) +HttpClientTest::HttpClientTest() : _labelStatusCode(nullptr) { auto winSize = Director::getInstance()->getWinSize(); @@ -47,51 +48,52 @@ HttpClientTest::HttpClientTest() auto cafile = FileUtils::getInstance()->fullPathForFilename("cacert.pem"); httpClient->setSSLVerification(cafile); httpClient->enableCookies(nullptr); - CCLOG("The http cookie will store to: %s", httpClient->getCookieFilename().c_str()); + CCLOG("The http cookie will store to: %s", httpClient->getCookieFilename().data()); const int MARGIN = 40; - const int SPACE = 35; + const int SPACE = 35; - const int LEFT = winSize.width / 2; + const int LEFT = winSize.width / 2; const int RIGHT = winSize.width / 4 * 3; - + auto menuRequest = Menu::create(); menuRequest->setPosition(Vec2::ZERO); addChild(menuRequest); - - // Get + + // Get auto labelGet = Label::createWithTTF("Test Get", "fonts/arial.ttf", 22); - auto itemGet = MenuItemLabel::create(labelGet, CC_CALLBACK_1(HttpClientTest::onMenuGetTestClicked, this)); + auto itemGet = MenuItemLabel::create(labelGet, CC_CALLBACK_1(HttpClientTest::onMenuGetTestClicked, this)); itemGet->setPosition(LEFT, winSize.height - MARGIN - SPACE); menuRequest->addChild(itemGet); - + // Post auto labelPost = Label::createWithTTF("Test Post", "fonts/arial.ttf", 22); - auto itemPost = MenuItemLabel::create(labelPost, CC_CALLBACK_1(HttpClientTest::onMenuPostTestClicked, this)); + auto itemPost = MenuItemLabel::create(labelPost, CC_CALLBACK_1(HttpClientTest::onMenuPostTestClicked, this)); itemPost->setPosition(LEFT, winSize.height - MARGIN - 2 * SPACE); menuRequest->addChild(itemPost); - + // Post Binary auto labelPostBinary = Label::createWithTTF("Test Post Binary", "fonts/arial.ttf", 22); - auto itemPostBinary = MenuItemLabel::create(labelPostBinary, CC_CALLBACK_1(HttpClientTest::onMenuPostBinaryTestClicked, this)); + auto itemPostBinary = + MenuItemLabel::create(labelPostBinary, CC_CALLBACK_1(HttpClientTest::onMenuPostBinaryTestClicked, this)); itemPostBinary->setPosition(LEFT, winSize.height - MARGIN - 3 * SPACE); menuRequest->addChild(itemPostBinary); // Put auto labelPut = Label::createWithTTF("Test Put", "fonts/arial.ttf", 22); - auto itemPut = MenuItemLabel::create(labelPut, CC_CALLBACK_1(HttpClientTest::onMenuPutTestClicked, this)); + auto itemPut = MenuItemLabel::create(labelPut, CC_CALLBACK_1(HttpClientTest::onMenuPutTestClicked, this)); itemPut->setPosition(LEFT, winSize.height - MARGIN - 4 * SPACE); menuRequest->addChild(itemPut); // Delete auto labelDelete = Label::createWithTTF("Test Delete", "fonts/arial.ttf", 22); - auto itemDelete = MenuItemLabel::create(labelDelete, CC_CALLBACK_1(HttpClientTest::onMenuDeleteTestClicked, this)); + auto itemDelete = MenuItemLabel::create(labelDelete, CC_CALLBACK_1(HttpClientTest::onMenuDeleteTestClicked, this)); itemDelete->setPosition(LEFT, winSize.height - MARGIN - 5 * SPACE); menuRequest->addChild(itemDelete); - + // Response Code Label _labelStatusCode = Label::createWithTTF("HTTP Status Code", "fonts/arial.ttf", 18); - _labelStatusCode->setPosition(winSize.width / 2, winSize.height - MARGIN - 6 * SPACE); + _labelStatusCode->setPosition(winSize.width / 2, winSize.height - MARGIN - 6 * SPACE); addChild(_labelStatusCode); } @@ -100,8 +102,8 @@ HttpClientTest::~HttpClientTest() HttpClient::destroyInstance(); } -void HttpClientTest::onMenuGetTestClicked(cocos2d::Ref *sender) -{ +void HttpClientTest::onMenuGetTestClicked(cocos2d::Ref* sender) +{ // test 1(sync request test) { HttpRequest* request = new HttpRequest(); @@ -111,7 +113,8 @@ void HttpClientTest::onMenuGetTestClicked(cocos2d::Ref *sender) // request->setResponseCallback(CC_CALLBACK_2(HttpClientTest::onHttpRequestCompleted, this)); request->setTag("GET test1"); HttpResponse* response = HttpClient::getInstance()->sendSync(request); - if (response) { + if (response) + { onHttpRequestCompleted(HttpClient::getInstance(), response); response->release(); } @@ -129,7 +132,7 @@ void HttpClientTest::onMenuGetTestClicked(cocos2d::Ref *sender) HttpClient::getInstance()->send(request); request->release(); } - + // test 3 { HttpRequest* request = new HttpRequest(); @@ -143,8 +146,8 @@ void HttpClientTest::onMenuGetTestClicked(cocos2d::Ref *sender) // don't forget to release it, pair to new request->release(); } - - // test 4 + + // test 4 { HttpRequest* request = new HttpRequest(); request->setUrl("https://httpbin.org/get"); @@ -167,13 +170,12 @@ void HttpClientTest::onMenuGetTestClicked(cocos2d::Ref *sender) HttpClient::getInstance()->send(request); request->release(); } - + // waiting _labelStatusCode->setString("waiting..."); - } -void HttpClientTest::onMenuPostTestClicked(cocos2d::Ref *sender) +void HttpClientTest::onMenuPostTestClicked(cocos2d::Ref* sender) { // test 1 { @@ -182,7 +184,7 @@ void HttpClientTest::onMenuPostTestClicked(cocos2d::Ref *sender) request->setRequestType(HttpRequest::Type::POST); request->setHeaders(std::vector{CHROME_UA}); request->setResponseCallback(CC_CALLBACK_2(HttpClientTest::onHttpRequestCompleted, this)); - + // write the post data const char* postData = "visitor=cocos2d&TestSuite=Extensions Test/NetworkTest"; request->setRequestData(postData, strlen(postData)); @@ -190,7 +192,7 @@ void HttpClientTest::onMenuPostTestClicked(cocos2d::Ref *sender) HttpClient::getInstance()->send(request); request->release(); } - + // test 2: set Content-Type { HttpRequest* request = new HttpRequest(); @@ -198,7 +200,7 @@ void HttpClientTest::onMenuPostTestClicked(cocos2d::Ref *sender) request->setRequestType(HttpRequest::Type::POST); request->setHeaders(std::vector{CHROME_UA, "Content-Type: application/json; charset=utf-8"}); request->setResponseCallback(CC_CALLBACK_2(HttpClientTest::onHttpRequestCompleted, this)); - + // write the post data const char* postData = "visitor=cocos2d&TestSuite=Extensions Test/NetworkTest"; request->setRequestData(postData, strlen(postData)); @@ -206,32 +208,30 @@ void HttpClientTest::onMenuPostTestClicked(cocos2d::Ref *sender) HttpClient::getInstance()->send(request); request->release(); } - + // waiting _labelStatusCode->setString("waiting..."); } -void HttpClientTest::onMenuPostBinaryTestClicked(cocos2d::Ref *sender) +void HttpClientTest::onMenuPostBinaryTestClicked(cocos2d::Ref* sender) { HttpRequest* request = new HttpRequest(); request->setUrl("https://httpbin.org/post"); request->setRequestType(HttpRequest::Type::POST); request->setResponseCallback(CC_CALLBACK_2(HttpClientTest::onHttpRequestCompleted, this)); - + // write the post data char postData[22] = "binary=hello\0\0cocos2d"; // including \0, the strings after \0 should not be cut in response - request->setRequestData(postData, 22); + request->setRequestData(postData, 22); request->setTag("POST Binary test"); HttpClient::getInstance()->send(request); request->release(); - + // waiting _labelStatusCode->setString("waiting..."); } - - -void HttpClientTest::onMenuPutTestClicked(Ref *sender) +void HttpClientTest::onMenuPutTestClicked(Ref* sender) { // test 1 { @@ -270,7 +270,7 @@ void HttpClientTest::onMenuPutTestClicked(Ref *sender) _labelStatusCode->setString("waiting..."); } -void HttpClientTest::onMenuDeleteTestClicked(Ref *sender) +void HttpClientTest::onMenuDeleteTestClicked(Ref* sender) { // test 1 { @@ -298,35 +298,35 @@ void HttpClientTest::onMenuDeleteTestClicked(Ref *sender) _labelStatusCode->setString("waiting..."); } -void HttpClientTest::onHttpRequestCompleted(HttpClient *sender, HttpResponse *response) +void HttpClientTest::onHttpRequestCompleted(HttpClient* sender, HttpResponse* response) { if (!response) { return; } - + // You can get original request type from: response->request->reqType - if (0 != strlen(response->getHttpRequest()->getTag())) + if (0 != strlen(response->getHttpRequest()->getTag())) { log("%s completed", response->getHttpRequest()->getTag()); } - - int32_t statusCode = response->getResponseCode(); + + int32_t statusCode = response->getResponseCode(); char statusString[64] = {}; sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag()); _labelStatusCode->setString(statusString); log("response code: %d", statusCode); - - if (response->getResponseCode() != 200) + + if (response->getResponseCode() != 200) { log("response failed"); // log("error buffer: %s", response->getErrorBuffer()); return; } - + // dump data auto buffer = response->getResponseData(); - buffer->push_back('\0'); // to c_str + buffer->push_back('\0'); // to c_str log("Http Test, dump data: %s", buffer->data()); log("\n"); if (response->getHttpRequest()->getReferenceCount() != 2) @@ -335,43 +335,44 @@ void HttpClientTest::onHttpRequestCompleted(HttpClient *sender, HttpResponse *re } } -HttpClientClearRequestsTest::HttpClientClearRequestsTest() -: _labelStatusCode(nullptr) +HttpClientClearRequestsTest::HttpClientClearRequestsTest() : _labelStatusCode(nullptr) { auto winSize = Director::getInstance()->getWinSize(); - + const int MARGIN = 40; - const int SPACE = 35; - + const int SPACE = 35; + const int CENTER = winSize.width / 2; - + auto menuRequest = Menu::create(); menuRequest->setPosition(Vec2::ZERO); addChild(menuRequest); - + // Get auto labelGet = Label::createWithTTF("Test Clear all Get", "fonts/arial.ttf", 22); - auto itemGet = MenuItemLabel::create(labelGet, CC_CALLBACK_1(HttpClientClearRequestsTest::onMenuCancelAllClicked, this)); + auto itemGet = + MenuItemLabel::create(labelGet, CC_CALLBACK_1(HttpClientClearRequestsTest::onMenuCancelAllClicked, this)); itemGet->setPosition(CENTER, winSize.height - MARGIN - SPACE); menuRequest->addChild(itemGet); - + // Post auto labelPost = Label::createWithTTF("Test Clear but only with the tag DELETE", "fonts/arial.ttf", 22); - auto itemPost = MenuItemLabel::create(labelPost, CC_CALLBACK_1(HttpClientClearRequestsTest::onMenuCancelSomeClicked, this)); + auto itemPost = + MenuItemLabel::create(labelPost, CC_CALLBACK_1(HttpClientClearRequestsTest::onMenuCancelSomeClicked, this)); itemPost->setPosition(CENTER, winSize.height - MARGIN - 2 * SPACE); menuRequest->addChild(itemPost); - + // Response Code Label _labelStatusCode = Label::createWithTTF("HTTP Status Code", "fonts/arial.ttf", 18); - _labelStatusCode->setPosition(winSize.width / 2, winSize.height - MARGIN - 6 * SPACE); + _labelStatusCode->setPosition(winSize.width / 2, winSize.height - MARGIN - 6 * SPACE); addChild(_labelStatusCode); - + // Tracking Data Label _labelTrakingData = Label::createWithTTF("Got 0 of 0 expected http requests", "fonts/arial.ttf", 16); - _labelTrakingData->setPosition(CENTER, winSize.height - MARGIN - 5 * SPACE); + _labelTrakingData->setPosition(CENTER, winSize.height - MARGIN - 5 * SPACE); addChild(_labelTrakingData); - - _totalExpectedRequests = 0; + + _totalExpectedRequests = 0; _totalProcessedRequests = 0; } @@ -380,9 +381,9 @@ HttpClientClearRequestsTest::~HttpClientClearRequestsTest() HttpClient::destroyInstance(); } -void HttpClientClearRequestsTest::onMenuCancelAllClicked(cocos2d::Ref *sender) +void HttpClientClearRequestsTest::onMenuCancelAllClicked(cocos2d::Ref* sender) { - for (int i=0; i < 10; i++) + for (int i = 0; i < 10; i++) { HttpRequest* request = new HttpRequest(); std::stringstream url; @@ -390,28 +391,28 @@ void HttpClientClearRequestsTest::onMenuCancelAllClicked(cocos2d::Ref *sender) request->setUrl(url.str()); request->setRequestType(HttpRequest::Type::GET); request->setResponseCallback(CC_CALLBACK_2(HttpClientClearRequestsTest::onHttpRequestCompleted, this)); - + url.str(""); url << "TEST_" << std::to_string(i); request->setTag(url.str()); HttpClient::getInstance()->send(request); request->release(); } - + _totalProcessedRequests = 0; - _totalExpectedRequests = 1; - + _totalExpectedRequests = 1; + HttpClient::getInstance()->setClearResponsePredicate(nullptr); HttpClient::getInstance()->clearResponseQueue(); - + // waiting _labelStatusCode->setString("waiting..."); } -void HttpClientClearRequestsTest::onMenuCancelSomeClicked(cocos2d::Ref *sender) +void HttpClientClearRequestsTest::onMenuCancelSomeClicked(cocos2d::Ref* sender) { // test 1 - for (int i=0; i < 10; i++) + for (int i = 0; i < 10; i++) { HttpRequest* request = new HttpRequest(); std::stringstream url; @@ -419,57 +420,57 @@ void HttpClientClearRequestsTest::onMenuCancelSomeClicked(cocos2d::Ref *sender) request->setUrl(url.str()); request->setRequestType(HttpRequest::Type::GET); request->setResponseCallback(CC_CALLBACK_2(HttpClientClearRequestsTest::onHttpRequestCompleted, this)); - + url.str(""); - if (i < 5) { + if (i < 5) + { url << "TEST_" << std::to_string(i); _totalExpectedRequests++; } - else { + else + { url << "DELETE_" << std::to_string(i); } request->setTag(url.str()); HttpClient::getInstance()->send(request); request->release(); } - - /* HttpClient::getInstance()->setClearRequestPredicate([&](HttpRequest* req) - { - auto r = !!strstr(req->getTag(), "DELETE_"); - return r; - });*/ + + /* HttpClient::getInstance()->setClearRequestPredicate([&](HttpRequest* req) + { + auto r = !!strstr(req->getTag(), "DELETE_"); + return r; + });*/ HttpClient::getInstance()->setClearResponsePredicate(nullptr); HttpClient::getInstance()->clearResponseQueue(); - - + // waiting _labelStatusCode->setString("waiting..."); - } -void HttpClientClearRequestsTest::onHttpRequestCompleted(HttpClient *sender, HttpResponse *response) +void HttpClientClearRequestsTest::onHttpRequestCompleted(HttpClient* sender, HttpResponse* response) { if (!response) { return; } - + // You can get original request type from: response->request->reqType if (0 != strlen(response->getHttpRequest()->getTag())) { log("%s completed", response->getHttpRequest()->getTag()); } - - int32_t statusCode = response->getResponseCode(); + + int32_t statusCode = response->getResponseCode(); char statusString[64] = {}; sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag()); _labelStatusCode->setString(statusString); log("response code: %d", statusCode); - + _totalProcessedRequests++; sprintf(statusString, "Got %d of %d expected http requests", _totalProcessedRequests, _totalExpectedRequests); _labelTrakingData->setString(statusString); - + if (!response->isSucceed()) { log("response failed"); diff --git a/tests/cpp-tests/Classes/NetworkTest/HttpClientTest/HttpClientTest.h b/tests/cpp-tests/Classes/NetworkTest/HttpClientTest/HttpClientTest.h index 80c85ff28666..e188007e1c16 100644 --- a/tests/cpp-tests/Classes/NetworkTest/HttpClientTest/HttpClientTest.h +++ b/tests/cpp-tests/Classes/NetworkTest/HttpClientTest/HttpClientTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -39,16 +39,16 @@ class HttpClientTest : public TestCase HttpClientTest(); virtual ~HttpClientTest(); - - //Menu Callbacks - void onMenuGetTestClicked(cocos2d::Ref *sender); - void onMenuPostTestClicked(cocos2d::Ref *sender); - void onMenuPostBinaryTestClicked(cocos2d::Ref *sender); - void onMenuPutTestClicked(cocos2d::Ref *sender); - void onMenuDeleteTestClicked(cocos2d::Ref *sender); - - //Http Response Callback - void onHttpRequestCompleted(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response); + + // Menu Callbacks + void onMenuGetTestClicked(cocos2d::Ref* sender); + void onMenuPostTestClicked(cocos2d::Ref* sender); + void onMenuPostBinaryTestClicked(cocos2d::Ref* sender); + void onMenuPutTestClicked(cocos2d::Ref* sender); + void onMenuDeleteTestClicked(cocos2d::Ref* sender); + + // Http Response Callback + void onHttpRequestCompleted(cocos2d::network::HttpClient* sender, cocos2d::network::HttpResponse* response); virtual std::string title() const override { return "Http Request Test"; } @@ -60,19 +60,19 @@ class HttpClientClearRequestsTest : public TestCase { public: CREATE_FUNC(HttpClientClearRequestsTest); - + HttpClientClearRequestsTest(); virtual ~HttpClientClearRequestsTest(); - - //Menu Callbacks - void onMenuCancelAllClicked(cocos2d::Ref *sender); - void onMenuCancelSomeClicked(cocos2d::Ref *sender); - - //Http Response Callback - void onHttpRequestCompleted(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response); - + + // Menu Callbacks + void onMenuCancelAllClicked(cocos2d::Ref* sender); + void onMenuCancelSomeClicked(cocos2d::Ref* sender); + + // Http Response Callback + void onHttpRequestCompleted(cocos2d::network::HttpClient* sender, cocos2d::network::HttpResponse* response); + virtual std::string title() const override { return "Http Request Test"; } - + private: int _totalExpectedRequests; int _totalProcessedRequests; @@ -80,4 +80,4 @@ class HttpClientClearRequestsTest : public TestCase cocos2d::Label* _labelStatusCode; }; -#endif //__HTTPREQUESTHTTP_H +#endif //__HTTPREQUESTHTTP_H diff --git a/tests/cpp-tests/Classes/NetworkTest/NetworkTest.cpp b/tests/cpp-tests/Classes/NetworkTest/NetworkTest.cpp index 4e320a70ffd7..1f518130f2f3 100644 --- a/tests/cpp-tests/Classes/NetworkTest/NetworkTest.cpp +++ b/tests/cpp-tests/Classes/NetworkTest/NetworkTest.cpp @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 @@ -27,7 +27,8 @@ #include "HttpClientTest/HttpClientTest.h" #include "DownloaderTest/DownloaderTest.h" -NetworkTests::NetworkTests() { +NetworkTests::NetworkTests() +{ addTest("HttpClientTest", []() { return new HttpClientTests; }); addTest("DownloaderTest", []() { return new DownloaderTests; }); } diff --git a/tests/cpp-tests/Classes/NetworkTest/NetworkTest.h b/tests/cpp-tests/Classes/NetworkTest/NetworkTest.h index 917e95d037a3..e0574e76c225 100644 --- a/tests/cpp-tests/Classes/NetworkTest/NetworkTest.h +++ b/tests/cpp-tests/Classes/NetworkTest/NetworkTest.h @@ -1,18 +1,18 @@ /**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + 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 diff --git a/tests/cpp-tests/Classes/NewAudioEngineTest/NewAudioEngineTest.cpp b/tests/cpp-tests/Classes/NewAudioEngineTest/NewAudioEngineTest.cpp index 90e304dece67..81dc4aea801e 100644 --- a/tests/cpp-tests/Classes/NewAudioEngineTest/NewAudioEngineTest.cpp +++ b/tests/cpp-tests/Classes/NewAudioEngineTest/NewAudioEngineTest.cpp @@ -53,151 +53,153 @@ AudioEngineTests::AudioEngineTests() ADD_TEST_CASE(AudioIssue18597Test); ADD_TEST_CASE(AudioIssue11143Test); - - //FIXME: Please keep AudioSwitchStateTest to the last position since this test case doesn't work well on each platforms. + + // FIXME: Please keep AudioSwitchStateTest to the last position since this test case doesn't work well on each + // platforms. ADD_TEST_CASE(AudioSwitchStateTest); } -namespace { - - class TextButton : public cocos2d::Label +namespace +{ + +class TextButton : public cocos2d::Label +{ +public: + static TextButton* create(std::string_view text, const std::function& onTriggered) { - public: - - static TextButton *create(const std::string& text, const std::function &onTriggered) + auto ret = new TextButton(); + + TTFConfig ttfconfig("fonts/arial.ttf", 25); + if (ret->setTTFConfig(ttfconfig)) { - auto ret = new TextButton(); - - TTFConfig ttfconfig("fonts/arial.ttf",25); - if (ret->setTTFConfig(ttfconfig)) { - ret->setString(text); - ret->_onTriggered = onTriggered; - - ret->autorelease(); - - return ret; - } - - delete ret; - return nullptr; + ret->setString(text); + ret->_onTriggered = onTriggered; + + ret->autorelease(); + + return ret; } - - void setEnabled(bool enabled) + + delete ret; + return nullptr; + } + + void setEnabled(bool enabled) + { + _enabled = enabled; + if (_enabled) { - _enabled = enabled; - if(_enabled){ - this->setColor(Color3B::WHITE); - } - else { - this->setColor(Color3B::GRAY); - } + this->setColor(Color3B::WHITE); } - - private: - TextButton() - : _onTriggered(nullptr) - , _enabled(true) + else { - auto listener = EventListenerTouchOneByOne::create(); - listener->setSwallowTouches(true); - - listener->onTouchBegan = CC_CALLBACK_2(TextButton::onTouchBegan, this); - listener->onTouchEnded = CC_CALLBACK_2(TextButton::onTouchEnded, this); - listener->onTouchCancelled = CC_CALLBACK_2(TextButton::onTouchCancelled, this); - - _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - + this->setColor(Color3B::GRAY); } - - bool touchHits(Touch *touch) + } + +private: + TextButton() : _onTriggered(nullptr), _enabled(true) + { + auto listener = EventListenerTouchOneByOne::create(); + listener->setSwallowTouches(true); + + listener->onTouchBegan = CC_CALLBACK_2(TextButton::onTouchBegan, this); + listener->onTouchEnded = CC_CALLBACK_2(TextButton::onTouchEnded, this); + listener->onTouchCancelled = CC_CALLBACK_2(TextButton::onTouchCancelled, this); + + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); + } + + bool touchHits(Touch* touch) + { + auto hitPos = this->convertToNodeSpace(touch->getLocation()); + if (hitPos.x >= 0 && hitPos.y >= 0 && hitPos.x <= _contentSize.width && hitPos.y <= _contentSize.height) { - auto hitPos = this->convertToNodeSpace(touch->getLocation()); - if (hitPos.x >= 0 && hitPos.y >= 0 && hitPos.x <= _contentSize.width && hitPos.y <= _contentSize.height) { - return true; - } - return false; + return true; } - - bool onTouchBegan(Touch *touch, Event *event) + return false; + } + + bool onTouchBegan(Touch* touch, Event* event) + { + auto hits = touchHits(touch); + if (hits) { - auto hits = touchHits(touch); - if (hits){ - scaleButtonTo(0.95f); - } - return hits; + scaleButtonTo(0.95f); } - - void onTouchEnded(Touch *touch, Event *event) + return hits; + } + + void onTouchEnded(Touch* touch, Event* event) + { + if (_enabled) { - if(_enabled) { - auto hits = touchHits(touch); - if (hits && _onTriggered){ - _onTriggered(this); - } + auto hits = touchHits(touch); + if (hits && _onTriggered) + { + _onTriggered(this); } - - scaleButtonTo(1); } - - void onTouchCancelled(Touch *touch, Event *event) - { - scaleButtonTo(1); - } - - void scaleButtonTo(float scale) - { - auto action = ScaleTo::create(0.05f, scale); - action->setTag(10000); - stopActionByTag(10000); - runAction(action); - } - - std::function _onTriggered; - - bool _enabled; - }; - - class SliderEx : public Slider + + scaleButtonTo(1); + } + + void onTouchCancelled(Touch* touch, Event* event) { scaleButtonTo(1); } + + void scaleButtonTo(float scale) { - public: - static SliderEx* create(){ - auto ret = new SliderEx(); - if (ret->init()) - { - ret->loadBarTexture("cocosui/sliderTrack.png"); - ret->loadSlidBallTextures("cocosui/sliderThumb.png", "cocosui/sliderThumb.png", ""); - ret->loadProgressBarTexture("cocosui/sliderProgress.png"); - ret->setTouchEnabled(true); - - ret->autorelease(); - - return ret; - } - CC_SAFE_DELETE(ret); + auto action = ScaleTo::create(0.05f, scale); + action->setTag(10000); + stopActionByTag(10000); + runAction(action); + } + + std::function _onTriggered; + + bool _enabled; +}; + +class SliderEx : public Slider +{ +public: + static SliderEx* create() + { + auto ret = new SliderEx(); + if (ret->init()) + { + ret->loadBarTexture("cocosui/sliderTrack.png"); + ret->loadSlidBallTextures("cocosui/sliderThumb.png", "cocosui/sliderThumb.png", ""); + ret->loadProgressBarTexture("cocosui/sliderProgress.png"); + ret->setTouchEnabled(true); + + ret->autorelease(); + return ret; } - - void setRatio(float ratio) { - ratio = clampf(ratio, 0.0f, 1.0f); - - _ratio = ratio; - setPercent(100 * _ratio); - } - - float getRatio () { - _ratio = 1.0f * _percent / _maxPercent; - return _ratio; - } - - private: - float _ratio; - }; -} + CC_SAFE_DELETE(ret); + return ret; + } -AudioEngineTestDemo::AudioEngineTestDemo() -: _isDestroyed(std::make_shared(false)) -{ -} + void setRatio(float ratio) + { + ratio = clampf(ratio, 0.0f, 1.0f); + + _ratio = ratio; + setPercent(100 * _ratio); + } + + float getRatio() + { + _ratio = 1.0f * _percent / _maxPercent; + return _ratio; + } + +private: + float _ratio; +}; +} // namespace + +AudioEngineTestDemo::AudioEngineTestDemo() : _isDestroyed(std::make_shared(false)) {} void AudioEngineTestDemo::onExit() { @@ -220,173 +222,184 @@ void AudioEngineTestDemo::onBackCallback(cocos2d::Ref* sender) // AudioControlTest bool AudioControlTest::init() { - auto ret = AudioEngineTestDemo::init(); - _audioID = AudioEngine::INVALID_AUDIO_ID; - _loopEnabled = false; - _volume = 1.0f; - _duration = AudioEngine::TIME_UNKNOWN; - _timeRatio = 0.0f; + auto ret = AudioEngineTestDemo::init(); + _audioID = AudioEngine::INVALID_AUDIO_ID; + _loopEnabled = false; + _volume = 1.0f; + _duration = AudioEngine::TIME_UNKNOWN; + _timeRatio = 0.0f; _updateTimeSlider = true; - _isStopped = false; - + _isStopped = false; + std::string fontFilePath = "fonts/arial.ttf"; - + auto& layerSize = this->getContentSize(); - + _playOverLabel = Label::createWithSystemFont("Play Over", "", 30); - _playOverLabel->setPosition(Vec2(layerSize/2) + Vec2(0, 30)); + _playOverLabel->setPosition(Vec2(layerSize / 2) + Vec2(0, 30)); _playOverLabel->setVisible(false); addChild(_playOverLabel, 99999); - auto playItem = TextButton::create("play", [&](TextButton* button){ - if (_audioID == AudioEngine::INVALID_AUDIO_ID) { + auto playItem = TextButton::create("play", [&](TextButton* button) { + if (_audioID == AudioEngine::INVALID_AUDIO_ID) + { _audioID = AudioEngine::play2d("background.mp3", _loopEnabled, _volume); - - if(_audioID != AudioEngine::INVALID_AUDIO_ID) { + + if (_audioID != AudioEngine::INVALID_AUDIO_ID) + { _isStopped = false; - + button->setEnabled(false); - AudioEngine::setFinishCallback(_audioID, [&](int id, const std::string& filePath){ + AudioEngine::setFinishCallback(_audioID, [&](int id, std::string_view filePath) { log("_audioID(%d), _isStopped:(%d), played over!!!", _audioID, _isStopped); - + _playOverLabel->setVisible(true); - - scheduleOnce([&](float dt){ - _playOverLabel->setVisible(false); - }, 2.0f, "hide_play_over_label"); - - assert(!_isStopped); // Stop audio should not trigger finished callback + + scheduleOnce([&](float dt) { _playOverLabel->setVisible(false); }, 2.0f, "hide_play_over_label"); + + assert(!_isStopped); // Stop audio should not trigger finished callback _audioID = AudioEngine::INVALID_AUDIO_ID; ((TextButton*)_playItem)->setEnabled(true); - + _timeRatio = 0.0f; ((SliderEx*)_timeSlider)->setRatio(_timeRatio); }); } } }); - _playItem = playItem; - playItem->setPosition(layerSize.width * 0.3f,layerSize.height * 0.8f); + _playItem = playItem; + playItem->setPosition(layerSize.width * 0.3f, layerSize.height * 0.8f); addChild(playItem); - - auto stopItem = TextButton::create("stop", [&](TextButton* button){ - if (_audioID != AudioEngine::INVALID_AUDIO_ID ) { + + auto stopItem = TextButton::create("stop", [&](TextButton* button) { + if (_audioID != AudioEngine::INVALID_AUDIO_ID) + { _isStopped = true; AudioEngine::stop(_audioID); - + _audioID = AudioEngine::INVALID_AUDIO_ID; ((TextButton*)_playItem)->setEnabled(true); } }); - stopItem->setPosition(layerSize.width * 0.7f,layerSize.height * 0.8f); + stopItem->setPosition(layerSize.width * 0.7f, layerSize.height * 0.8f); addChild(stopItem); - - auto pauseItem = TextButton::create("pause", [&](TextButton* button){ - if (_audioID != AudioEngine::INVALID_AUDIO_ID ) { + + auto pauseItem = TextButton::create("pause", [&](TextButton* button) { + if (_audioID != AudioEngine::INVALID_AUDIO_ID) + { AudioEngine::pause(_audioID); } }); - pauseItem->setPosition(layerSize.width * 0.3f,layerSize.height * 0.7f); + pauseItem->setPosition(layerSize.width * 0.3f, layerSize.height * 0.7f); addChild(pauseItem); - - auto resumeItem = TextButton::create("resume", [&](TextButton* button){ - if (_audioID != AudioEngine::INVALID_AUDIO_ID ) { + + auto resumeItem = TextButton::create("resume", [&](TextButton* button) { + if (_audioID != AudioEngine::INVALID_AUDIO_ID) + { AudioEngine::resume(_audioID); } }); - resumeItem->setPosition(layerSize.width * 0.7f,layerSize.height * 0.7f); + resumeItem->setPosition(layerSize.width * 0.7f, layerSize.height * 0.7f); addChild(resumeItem); - - auto loopItem = TextButton::create("enable-loop", [&](TextButton* button){ + + auto loopItem = TextButton::create("enable-loop", [&](TextButton* button) { _loopEnabled = !_loopEnabled; - if (_audioID != AudioEngine::INVALID_AUDIO_ID) { + if (_audioID != AudioEngine::INVALID_AUDIO_ID) + { AudioEngine::setLoop(_audioID, _loopEnabled); } - if (_loopEnabled){ + if (_loopEnabled) + { button->setString("disable-loop"); } - else { + else + { button->setString("enable-loop"); } }); loopItem->setPosition(layerSize.width * 0.5f, layerSize.height * 0.5f); addChild(loopItem); - + auto volumeSlider = SliderEx::create(); volumeSlider->setPercent(100); - volumeSlider->addEventListener([&](Ref* sender, Slider::EventType event){ - SliderEx *slider = dynamic_cast(sender); - _volume = slider->getRatio(); - if (_audioID != AudioEngine::INVALID_AUDIO_ID ) { + volumeSlider->addEventListener([&](Ref* sender, Slider::EventType event) { + SliderEx* slider = dynamic_cast(sender); + _volume = slider->getRatio(); + if (_audioID != AudioEngine::INVALID_AUDIO_ID) + { AudioEngine::setVolume(_audioID, _volume); } }); - volumeSlider->setPosition(Vec2(layerSize.width * 0.5f,layerSize.height * 0.35f)); + volumeSlider->setPosition(Vec2(layerSize.width * 0.5f, layerSize.height * 0.35f)); addChild(volumeSlider); - + auto timeSlider = SliderEx::create(); - timeSlider->addEventListener([&](Ref* sender, Slider::EventType event){ - SliderEx *slider = dynamic_cast(sender); - switch(event){ - case Slider::EventType::ON_SLIDEBALL_DOWN: - _updateTimeSlider = false; - break; - case Slider::EventType::ON_SLIDEBALL_UP: - if (_audioID != AudioEngine::INVALID_AUDIO_ID && _duration != AudioEngine::TIME_UNKNOWN) { - float ratio = (float)slider->getPercent() / 100; - ratio = clampf(ratio, 0.0f, 1.0f); - AudioEngine::setCurrentTime(_audioID, _duration * ratio); - } - case Slider::EventType::ON_SLIDEBALL_CANCEL: - _updateTimeSlider = true; - case Slider::EventType::ON_PERCENTAGE_CHANGED: - default: - //ignore - break; + timeSlider->addEventListener([&](Ref* sender, Slider::EventType event) { + SliderEx* slider = dynamic_cast(sender); + switch (event) + { + case Slider::EventType::ON_SLIDEBALL_DOWN: + _updateTimeSlider = false; + break; + case Slider::EventType::ON_SLIDEBALL_UP: + if (_audioID != AudioEngine::INVALID_AUDIO_ID && _duration != AudioEngine::TIME_UNKNOWN) + { + float ratio = (float)slider->getPercent() / 100; + ratio = clampf(ratio, 0.0f, 1.0f); + AudioEngine::setCurrentTime(_audioID, _duration * ratio); + } + case Slider::EventType::ON_SLIDEBALL_CANCEL: + _updateTimeSlider = true; + case Slider::EventType::ON_PERCENTAGE_CHANGED: + default: + // ignore + break; } }); - timeSlider->setPosition(Vec2(layerSize.width * 0.5f,layerSize.height * 0.25f)); + timeSlider->setPosition(Vec2(layerSize.width * 0.5f, layerSize.height * 0.25f)); addChild(timeSlider); _timeSlider = timeSlider; - + auto& volumeSliderPos = volumeSlider->getPosition(); - auto& sliderSize = volumeSlider->getContentSize(); - auto volumeLabel = Label::createWithTTF("volume: ", fontFilePath, 20); + auto& sliderSize = volumeSlider->getContentSize(); + auto volumeLabel = Label::createWithTTF("volume: ", fontFilePath, 20); volumeLabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE_RIGHT); volumeLabel->setPosition(volumeSliderPos.x - sliderSize.width / 2, volumeSliderPos.y); addChild(volumeLabel); - + auto& timeSliderPos = timeSlider->getPosition(); - auto timeLabel = Label::createWithTTF("time: ", fontFilePath, 20); + auto timeLabel = Label::createWithTTF("time: ", fontFilePath, 20); timeLabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE_RIGHT); timeLabel->setPosition(timeSliderPos.x - sliderSize.width / 2, timeSliderPos.y); addChild(timeLabel); - + this->schedule(CC_CALLBACK_1(AudioControlTest::update, this), 0.1f, "update_key"); - + return ret; } void AudioControlTest::update(float dt) { - if (_audioID != AudioEngine::INVALID_AUDIO_ID ) { - if(_duration == AudioEngine::TIME_UNKNOWN){ + if (_audioID != AudioEngine::INVALID_AUDIO_ID) + { + if (_duration == AudioEngine::TIME_UNKNOWN) + { _duration = AudioEngine::getDuration(_audioID); } - if(_duration != AudioEngine::TIME_UNKNOWN){ - auto time = AudioEngine::getCurrentTime(_audioID); + if (_duration != AudioEngine::TIME_UNKNOWN) + { + auto time = AudioEngine::getCurrentTime(_audioID); _timeRatio = time / _duration; - if(_updateTimeSlider){ + if (_updateTimeSlider) + { ((SliderEx*)_timeSlider)->setRatio(_timeRatio); } } } } -AudioControlTest::~AudioControlTest() -{ -} +AudioControlTest::~AudioControlTest() {} std::string AudioControlTest::title() const { @@ -403,16 +416,16 @@ bool AudioLoadTest::init() stateLabel->setPosition(layerSize.width / 2, layerSize.height * 0.7f); addChild(stateLabel); - auto preloadItem = TextButton::create("preload", [&, stateLabel](TextButton* button){ + auto preloadItem = TextButton::create("preload", [&, stateLabel](TextButton* button) { stateLabel->setString("status:loading..."); auto isDestroyed = _isDestroyed; - AudioEngine::preload("audio/SoundEffectsFX009/FX082.mp3", [isDestroyed, stateLabel](bool isSuccess){ + AudioEngine::preload("audio/SoundEffectsFX009/FX082.mp3", [isDestroyed, stateLabel](bool isSuccess) { if (*isDestroyed) { CCLOG("AudioLoadTest scene was destroyed, no need to set the label text."); return; } - + if (isSuccess) { stateLabel->setString("status:load success"); @@ -426,13 +439,13 @@ bool AudioLoadTest::init() preloadItem->setPosition(layerSize.width * 0.35f, layerSize.height * 0.5f); addChild(preloadItem); - auto uncacheItem = TextButton::create("uncache", [&, stateLabel](TextButton* button){ + auto uncacheItem = TextButton::create("uncache", [&, stateLabel](TextButton* button) { stateLabel->setString("status:uncache"); AudioEngine::uncache("audio/SoundEffectsFX009/FX082.mp3"); }); uncacheItem->setPosition(layerSize.width * 0.65f, layerSize.height * 0.5f); addChild(uncacheItem); - + return true; } @@ -445,9 +458,7 @@ std::string AudioLoadTest::title() const } // AudioWavTest -AudioWavTest::~AudioWavTest() -{ -} +AudioWavTest::~AudioWavTest() {} std::string AudioWavTest::title() const { @@ -468,22 +479,26 @@ bool AudioWavTest::init() addChild(_stateLabel); auto playPrev = TextButton::create("Play Prev", [=](TextButton* button) { - if (_curIndex > 0) { + if (_curIndex > 0) + { AudioEngine::stop(_audioID); _audioID = AudioEngine::play2d(_wavFiles[--_curIndex]); - _stateLabel->setString(StringUtils::format("[index: %d] %s", _curIndex, FileUtils::getFileShortName(_wavFiles[_curIndex]).c_str())); + _stateLabel->setString(StringUtils::format("[index: %d] %s", _curIndex, + FileUtils::getFileShortName(_wavFiles[_curIndex]).c_str())); } - }); + }); playPrev->setPosition(layerSize.width * 0.35f, layerSize.height * 0.5f); addChild(playPrev); auto playNext = TextButton::create("Play Next", [=](TextButton* button) { - if (_curIndex != -1 && _curIndex < (_wavFiles.size() - 1)) { + if (_curIndex != -1 && _curIndex < (_wavFiles.size() - 1)) + { AudioEngine::stop(_audioID); _audioID = AudioEngine::play2d(_wavFiles[++_curIndex]); - _stateLabel->setString(StringUtils::format("[index: %d] %s", _curIndex, FileUtils::getFileShortName(_wavFiles[_curIndex]).c_str())); + _stateLabel->setString(StringUtils::format("[index: %d] %s", _curIndex, + FileUtils::getFileShortName(_wavFiles[_curIndex]).c_str())); } - }); + }); playNext->setPosition(layerSize.width * 0.65f, layerSize.height * 0.5f); addChild(playNext); @@ -497,10 +512,12 @@ void AudioWavTest::onEnter() { AudioEngineTestDemo::onEnter(); - if (!_wavFiles.empty()) { + if (!_wavFiles.empty()) + { _curIndex = 0; - _audioID = AudioEngine::play2d(_wavFiles[_curIndex]); - _stateLabel->setString(StringUtils::format("[index: %d] %s", _curIndex, FileUtils::getFileShortName(_wavFiles[_curIndex]).c_str())); + _audioID = AudioEngine::play2d(_wavFiles[_curIndex]); + _stateLabel->setString(StringUtils::format("[index: %d] %s", _curIndex, + FileUtils::getFileShortName(_wavFiles[_curIndex]).c_str())); } } @@ -508,48 +525,51 @@ void AudioWavTest::onEnter() bool PlaySimultaneouslyTest::init() { auto ret = AudioEngineTestDemo::init(); - + char text[36]; int tmp = 81; - for(int index = 0; index < TEST_COUNT; ++index){ - sprintf(text,"audio/SoundEffectsFX009/FX0%d.mp3",tmp + index); + for (int index = 0; index < TEST_COUNT; ++index) + { + sprintf(text, "audio/SoundEffectsFX009/FX0%d.mp3", tmp + index); _files[index] = text; } _playingcount = 0; - - auto playItem = TextButton::create("play-simultaneously", [&](TextButton* button){ + + auto playItem = TextButton::create("play-simultaneously", [&](TextButton* button) { int audioId; _playingcount = 0; button->setEnabled(false); auto startTime = utils::gettime(); - for(int index = 0; index < TEST_COUNT; ++index){ + for (int index = 0; index < TEST_COUNT; ++index) + { audioId = AudioEngine::play2d(_files[index]); - if(audioId != AudioEngine::INVALID_AUDIO_ID){ + if (audioId != AudioEngine::INVALID_AUDIO_ID) + { _playingcount += 1; - - AudioEngine::setFinishCallback(audioId, [&](int id, const std::string& filePath){ + + AudioEngine::setFinishCallback(audioId, [&](int id, std::string_view filePath) { _playingcount -= 1; - if(_playingcount <= 0){ + if (_playingcount <= 0) + { ((TextButton*)_playItem)->setEnabled(true); } }); } - else { - log("%s,%d,Fail to play file:%s",__FILE__,__LINE__ ,_files[index].c_str()); + else + { + log("%s,%d,Fail to play file:%s", __FILE__, __LINE__, _files[index].c_str()); } } - log("diff time:%lf",utils::gettime() - startTime); + log("diff time:%lf", utils::gettime() - startTime); }); - playItem->setPositionNormalized(Vec2(0.5f,0.5f)); + playItem->setPositionNormalized(Vec2(0.5f, 0.5f)); this->addChild(playItem); _playItem = playItem; - + return ret; } -PlaySimultaneouslyTest::~PlaySimultaneouslyTest() -{ -} +PlaySimultaneouslyTest::~PlaySimultaneouslyTest() {} std::string PlaySimultaneouslyTest::title() const { @@ -560,7 +580,7 @@ std::string PlaySimultaneouslyTest::title() const bool AudioProfileTest::init() { auto ret = AudioEngineTestDemo::init(); - + char text[30]; _files[0] = "background.mp3"; #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC @@ -568,82 +588,81 @@ bool AudioProfileTest::init() #else _files[1] = "background.ogg"; #endif - + std::string fontFilePath = "fonts/arial.ttf"; - _minDelay = 1.0f; - _time = 0.0f; + _minDelay = 1.0f; + _time = 0.0f; - _audioProfile.name = "AudioProfileTest"; + _audioProfile.name = "AudioProfileTest"; _audioProfile.maxInstances = 3; - _audioProfile.minDelay = 1.0; - - Vec2 pos(0.5f,0.7f); - for(int index = 0; index < FILE_COUNT; ++index){ - sprintf(text,"play %s",_files[index].c_str()); - - auto playItem = TextButton::create(text, [&](TextButton* button){ + _audioProfile.minDelay = 1.0; + + Vec2 pos(0.5f, 0.7f); + for (int index = 0; index < FILE_COUNT; ++index) + { + sprintf(text, "play %s", _files[index].c_str()); + + auto playItem = TextButton::create(text, [&](TextButton* button) { int index = button->getTag(); - auto id = AudioEngine::play2d(_files[index], false, 1.0f, &_audioProfile); - if(id != AudioEngine::INVALID_AUDIO_ID){ + auto id = AudioEngine::play2d(_files[index], false, 1.0f, &_audioProfile); + if (id != AudioEngine::INVALID_AUDIO_ID) + { _time = _minDelay; _audioCount += 1; char show[30]; - sprintf(show,"audio count:%d",_audioCount); + sprintf(show, "audio count:%d", _audioCount); _showLabel->setString(show); - - AudioEngine::setFinishCallback(id, [&](int id, const std::string& filePath){ + + AudioEngine::setFinishCallback(id, [&](int id, std::string_view filePath) { _audioCount -= 1; char show[30]; - sprintf(show,"audio count:%d",_audioCount); + sprintf(show, "audio count:%d", _audioCount); _showLabel->setString(show); }); } - }); playItem->setTag(index); playItem->setPositionNormalized(pos); this->addChild(playItem); pos.y -= 0.15f; - } - + Vec2 origin = Director::getInstance()->getVisibleOrigin(); - Size size = Director::getInstance()->getVisibleSize(); - - auto profileInfoLabel = Label::createWithTTF("AudioProfile Info:\n max instance:3 \n minimum delay:1.0", fontFilePath, 12); + Size size = Director::getInstance()->getVisibleSize(); + + auto profileInfoLabel = + Label::createWithTTF("AudioProfile Info:\n max instance:3 \n minimum delay:1.0", fontFilePath, 12); profileInfoLabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT); profileInfoLabel->setPosition(Vec2(origin.x, origin.y + size.height * 0.65f)); addChild(profileInfoLabel); - + _audioCount = 0; - _showLabel = Label::createWithTTF("audio count:0", fontFilePath, 12); + _showLabel = Label::createWithTTF("audio count:0", fontFilePath, 12); _showLabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT); _showLabel->setPosition(Vec2(origin.x, origin.y + size.height * 0.5f)); addChild(_showLabel); - + auto timeSlider = SliderEx::create(); timeSlider->setEnabled(false); timeSlider->setPositionNormalized(pos); addChild(timeSlider); _timeSlider = timeSlider; - + this->schedule(CC_CALLBACK_1(AudioProfileTest::update, this), 0.05f, "update_key"); - + return ret; } void AudioProfileTest::update(float dt) { - if(_time > 0.0f) + if (_time > 0.0f) { _time -= dt; ((SliderEx*)_timeSlider)->setRatio(_time / _minDelay); } } -AudioProfileTest::~AudioProfileTest() -{ -} +AudioProfileTest::~AudioProfileTest() {} std::string AudioProfileTest::title() const { @@ -659,29 +678,26 @@ std::string AudioProfileTest::subtitle() const bool InvalidAudioFileTest::init() { auto ret = AudioEngineTestDemo::init(); - - auto playItem = TextButton::create("play unsupported media type", [&](TextButton* button){ + + auto playItem = TextButton::create("play unsupported media type", [&](TextButton* button) { #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC AudioEngine::play2d("background.ogg"); #elif CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 - AudioEngine::play2d("background.caf"); + AudioEngine::play2d("background.caf"); #endif }); playItem->setPositionNormalized(Vec2(0.5f, 0.6f)); this->addChild(playItem); - - auto playItem2 = TextButton::create("play not-existent file", [&](TextButton* button){ - AudioEngine::play2d("not-existent file.mp3"); - }); + + auto playItem2 = TextButton::create("play not-existent file", + [&](TextButton* button) { AudioEngine::play2d("not-existent file.mp3"); }); playItem2->setPositionNormalized(Vec2(0.5f, 0.4f)); this->addChild(playItem2); - + return ret; } -InvalidAudioFileTest::~InvalidAudioFileTest() -{ -} +InvalidAudioFileTest::~InvalidAudioFileTest() {} std::string InvalidAudioFileTest::title() const { @@ -697,19 +713,16 @@ std::string InvalidAudioFileTest::subtitle() const bool LargeAudioFileTest::init() { auto ret = AudioEngineTestDemo::init(); - - auto playItem = TextButton::create("play large audio file", [&](TextButton* button){ - AudioEngine::play2d("audio/LuckyDay.mp3"); - }); + + auto playItem = TextButton::create("play large audio file", + [&](TextButton* button) { AudioEngine::play2d("audio/LuckyDay.mp3"); }); playItem->setPositionNormalized(Vec2::ANCHOR_MIDDLE); this->addChild(playItem); - + return ret; } -LargeAudioFileTest::~LargeAudioFileTest() -{ -} +LargeAudioFileTest::~LargeAudioFileTest() {} std::string LargeAudioFileTest::title() const { @@ -722,36 +735,33 @@ bool AudioIssue18597Test::init() { auto& layerSize = this->getContentSize(); - //test case for https://github.com/cocos2d/cocos2d-x/issues/18597 - this->schedule([=](float dt) - { - CCLOG("issues 18597 audio crash test"); - for (int i = 0; i< 2;++i) - { - auto id = AudioEngine::play2d("audio/MUS_BGM_Battle_Round1_v1.caf", true, 1.0f); - this->runAction(Sequence::create( - DelayTime::create(8.0f), - CallFunc::create([=]() - { - AudioEngine::stop(id); - }), - nullptr - )); - } - }, 2.0, 10000, 0.0, "audio test"); + // test case for https://github.com/cocos2d/cocos2d-x/issues/18597 + this->schedule( + [=](float dt) { + CCLOG("issues 18597 audio crash test"); + for (int i = 0; i < 2; ++i) + { + auto id = AudioEngine::play2d("audio/MUS_BGM_Battle_Round1_v1.caf", true, 1.0f); + this->runAction(Sequence::create(DelayTime::create(8.0f), + CallFunc::create([=]() { AudioEngine::stop(id); }), nullptr)); + } + }, + 2.0, 10000, 0.0, "audio test"); // add label to show the side effect of "UnqueueBuffers Before alSourceStop" - _time = 0.0; + _time = 0.0; auto labelTime = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "time: "); labelTime->setPosition(layerSize.width * 0.5f, layerSize.height * 0.5f); labelTime->setTag(999); this->addChild(labelTime); // update label quickly - this->schedule([=](float dt){ - _time += dt; - char timeString[20] = {0}; - sprintf(timeString, "Time %2.2f", _time); - dynamic_cast