Merge branch 'v3' of https://github.com/cocos2d/cocos2d-x into autoExtend

This commit is contained in:
pandamicro 2015-07-23 15:25:33 +08:00
commit 6110700615
374 changed files with 9259 additions and 6200 deletions

1
.gitignore vendored
View File

@ -146,3 +146,4 @@ tests/cpp-tests/Resources/audio
/*/*/prebuilt-mk/Android.mk
/*/*/*/prebuilt-mk/Android.mk
/*/*/*/*/prebuilt-mk/Android.mk
*.xcscmblueprint

View File

@ -37,5 +37,5 @@ before_install:
# whitelist
branches:
only:
- v3.7-release
- v3.7.1
- v3

View File

@ -4,6 +4,46 @@ cocos2d-x-3.8 ??
[FIX] renderer: UI component can't click correctly by moving UI and camera far away of origin.
[FIX] JS: Fixed issue of iOS/JS reflection `callStaticMethod` with bool arg
cocos2d-x-3.7final July.21 2015
[REFINE] JS: Improve manual binding code for `retain`, `release`, `onEnter`, `onExit`, `onEnterTransitionDidFinish` and `onExitTransitionDidStart`
[REFINE] web: Add compatible Uint16Array defintion
[FIX] Scale9Sprite: Fixed Scale9Sprite gray state issue while `setCapInsets` called
[FIX] studio: Fixed parser issue by checking texture existance
[FIX] studio: Fixed Armature parser issue
[FIX] JS: Fixed cleanup overriding issue in JS that it will cause `too much recursion` error
[FIX] web: Fixed url check regular expression not supporting localhost issue
[FIX] web: Fixed issue that sprite doesn't update texture rect correctly in some condition
cocos2d-x-3.7rc1 July.14 2015
[REFINE] framework: Used msbuild to generating engine prebuilt libs on win32.
[REFINE] 3d: Used shader with normal while creating mesh with normals
[REFINE] 3d: Set default 3d animation quality to low
[REFINE] web: Improved localStorage warning when disabled
[FIX] studio: Fixed percentage setting won't take effect when UISlider's background resource set to null
[FIX] studio: Fixed a bug that SingleNode's color isn't set
[FIX] studio: Fixed child nodes can't be rendered when particle and TiledMap as parent and their resource have been removed from disk
[FIX] studio: Fixed a bug of JSON parser that texture address is wrong
[FIX] studio: Fixed a bug that drawLine & drawPoints don't apply blend function in parser
[FIX] studio: Fixed a bug that check box front cross texture will expand to normal size when change status between normal and disable frequently
[FIX] studio: Fixed a bug that normal texture won't show when slider set to disable mode then clean slider ball disable texture
[FIX] 3d: Fixed obj loading failed on windows
[FIX] 3d: Fixed clipping node does not work for Sprite3D
[FIX] platform: Fixed js template run error on linux
[FIX] Tilemap: Fixed CCTMXXMLParser code negligence
[FIX] JS: Fixed constant value error for ccui.Layout.BACKGROUND_IMAGE_ZORDER
[FIX] JS: Fixed XMLHttpRequest can't be retain in JSB
[FIX] JS: Added cc.path.mainFileName
[FIX] JS: Fixed issue that override cleanup function in JS can't get invoked during node detaching
[FIX] JS: Fixed cc.loader notification issue with image asynchonous loading
[FIX] web: Fixed MenuItems' color/opacity setter issue with child nodes
[FIX] web: Fixed page view's layout issue for JSON parser
[FIX] web: Add ttc loader and prevent the pure digital fonts is invalid
[FIX] web: Fixed Float32Array initialization
[FIX] web: Fixed a bug that layout background is missing
[FIX] web: Fixed a bug that ObjectExtensionData miss setCustomProperty and getCustomProperty function
cocos2d-x-3.7rc0 July.1 2015
[HIGHLIGHT] core: Added Material system (JS/Lua ready)
[HIGHLIGHT] 3d: Added Physics3d support (JS/Lua ready)

View File

@ -13,7 +13,7 @@ cocos2d-x
[cocos2d-x][1] is a multi-platform framework for building 2d games, interactive books, demos and other graphical applications.
It is based on [cocos2d-iphone][2], but instead of using Objective-C, it uses C++.
It works on iOS, Android, Windows Phone and Store Apps, OS X, Windows and Linux.
It works on iOS, Android, Windows Phone and Store Apps, OS X, Windows, Linux and Web platforms.
cocos2d-x is:
@ -38,6 +38,12 @@ Git user attention
cocos2d-x $ git submodule update --init
Download stable versions
-----------------------
* [Cocos2d-x stable versions](http://www.cocos2d-x.org/download)
* [Cocos2d-JS Lite version](http://www.cocos2d-x.org/filecenter/jsbuilder)
How to start a new game
-----------------------
@ -53,6 +59,8 @@ Example:
$ cocos new MyGame -p com.your_company.mygame -l cpp -d NEW_PROJECTS_DIR
$ cd NEW_PROJECTS_DIR/MyGame
You can also create a JS project or Lua project with `-l js` or `-l lua`.
### Build and run a new project for Android ###
$ cocos run -p android -j 4
@ -67,7 +75,7 @@ Example:
### Build and run a new project for Linux ###
if you never run cocos2d-x on Linux, you need to install all dependencies by the
If you never run cocos2d-x on Linux, you need to install all dependencies by the
script in **cocos2d/build/install-deps-linux.sh**
$ cd cocos2d-x/build
@ -100,6 +108,29 @@ Starting with Cocos2d-x v3.6 there will no longer be support for Windows Phone 8
See more info on How to install and Create games on Windows RT (Windows and Windows Phone 8.1) at http://msopentech.github.io/cocos2d-x/
### Build and run new project for web ###
Only JS project can be published to web platforms, so you will need to create a JS project first:
$ cocos new -l js WebGame
Then you can run your game in a web browser:
$ cocos run -p web
Or you can publish your game to `publish/html5/` folder:
$ cocos run -p web -m release [--advanced]
Documentations and samples
-------------
* [Online API Reference](http://cocos2d-x.org/wiki/Reference) _Note that Cocos2d-x and Cocos2d-JS have different API set_
* [Programmers Guide](http://cocos2d-x.org/programmersguide/)
* [Temporary Cocos2d-JS documents](http://cocos2d-x.org/docs/manual/framework/html5/en)
* [Latest Release Note](https://github.com/cocos2d/cocos2d-x/blob/v3/docs/RELEASE_NOTES.md)
* [Changelog](https://github.com/cocos2d/cocos2d-x/blob/v3/CHANGELOG)
* [Cocos2d sample games](https://github.com/cocos2d/cocos2d-x-samples) _More samples will be added in v3.8_
Main features
-------------
@ -141,9 +172,8 @@ Build Requirements
* or Windows 7+, VS 2013+
* Python 2.7.5
* NDK r10c+ is required to build Android games
* Windows Phone/Store 8.0 VS 2013+
* Windows Phone/Store 8.1 VS 2013 Update 3+
* Windows Phone/Store 8.1 VS 2013 Update 4+
* JRE or JDK 1.6+ is required for web publishing
Runtime Requirements
--------------------
@ -153,13 +183,28 @@ Runtime Requirements
* Windows 10.0 for Windows Phone/Store 10.0 games
* OS X v10.6+ for Mac games
* Windows 7+ for Win games
* Modern browsers and IE 9+ for web games
Running Tests
--------------------
Select the test you want from Xcode Scheme chooser.
* Cocos Console
```
// Enter cpp test folder
cd tests/cpp-tests
// Or enter js test folder
cd tests/js-tests
// Or enter lua test folder
cd tests/lua-tests
// Compile or run test case
cocos compile -p ios|mac|android|win32|win8_1|metro|web -m debug|release
cocos run -p ios|mac|android|win32|win8_1|metro|web -m debug|release
```
* For OS X / iOS
```

View File

@ -2009,6 +2009,10 @@
B29A7E3F19EE1B7700872B35 /* AnimationState.h in Headers */ = {isa = PBXBuildFile; fileRef = B29A7DC619EE1B7700872B35 /* AnimationState.h */; };
B29A7E4019EE1B7700872B35 /* AnimationState.h in Headers */ = {isa = PBXBuildFile; fileRef = B29A7DC619EE1B7700872B35 /* AnimationState.h */; };
B2CC507C19776DD10041958E /* CCPhysicsJoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 46A170721807CE7A005B8026 /* CCPhysicsJoint.cpp */; };
B5668D7D1B3838E4003CBD5E /* UIScrollViewBar.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B5668D7B1B3838E4003CBD5E /* UIScrollViewBar.cpp */; };
B5668D7E1B3838E4003CBD5E /* UIScrollViewBar.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B5668D7B1B3838E4003CBD5E /* UIScrollViewBar.cpp */; };
B5668D7F1B3838E4003CBD5E /* UIScrollViewBar.h in Headers */ = {isa = PBXBuildFile; fileRef = B5668D7C1B3838E4003CBD5E /* UIScrollViewBar.h */; };
B5668D801B3838E4003CBD5E /* UIScrollViewBar.h in Headers */ = {isa = PBXBuildFile; fileRef = B5668D7C1B3838E4003CBD5E /* UIScrollViewBar.h */; };
B5CE6DBE1B3BF2B1002B0419 /* UIAbstractCheckButton.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B5CE6DBC1B3BF2B1002B0419 /* UIAbstractCheckButton.cpp */; };
B5CE6DBF1B3BF2B1002B0419 /* UIAbstractCheckButton.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B5CE6DBC1B3BF2B1002B0419 /* UIAbstractCheckButton.cpp */; };
B5CE6DC01B3BF2B1002B0419 /* UIAbstractCheckButton.h in Headers */ = {isa = PBXBuildFile; fileRef = B5CE6DBD1B3BF2B1002B0419 /* UIAbstractCheckButton.h */; };
@ -2017,10 +2021,6 @@
B5CE6DC91B3C05BA002B0419 /* UIRadioButton.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B5CE6DC61B3C05BA002B0419 /* UIRadioButton.cpp */; };
B5CE6DCA1B3C05BA002B0419 /* UIRadioButton.h in Headers */ = {isa = PBXBuildFile; fileRef = B5CE6DC71B3C05BA002B0419 /* UIRadioButton.h */; };
B5CE6DCB1B3C05BA002B0419 /* UIRadioButton.h in Headers */ = {isa = PBXBuildFile; fileRef = B5CE6DC71B3C05BA002B0419 /* UIRadioButton.h */; };
B5668D7D1B3838E4003CBD5E /* UIScrollViewBar.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B5668D7B1B3838E4003CBD5E /* UIScrollViewBar.cpp */; };
B5668D7E1B3838E4003CBD5E /* UIScrollViewBar.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B5668D7B1B3838E4003CBD5E /* UIScrollViewBar.cpp */; };
B5668D7F1B3838E4003CBD5E /* UIScrollViewBar.h in Headers */ = {isa = PBXBuildFile; fileRef = B5668D7C1B3838E4003CBD5E /* UIScrollViewBar.h */; };
B5668D801B3838E4003CBD5E /* UIScrollViewBar.h in Headers */ = {isa = PBXBuildFile; fileRef = B5668D7C1B3838E4003CBD5E /* UIScrollViewBar.h */; };
B603F1A81AC8EA0900A9579C /* CCTerrain.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B603F1A61AC8EA0900A9579C /* CCTerrain.cpp */; };
B603F1A91AC8EA0900A9579C /* CCTerrain.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B603F1A61AC8EA0900A9579C /* CCTerrain.cpp */; };
B603F1AA1AC8EA0900A9579C /* CCTerrain.h in Headers */ = {isa = PBXBuildFile; fileRef = B603F1A71AC8EA0900A9579C /* CCTerrain.h */; };
@ -4704,12 +4704,12 @@
B29A7DC619EE1B7700872B35 /* AnimationState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AnimationState.h; sourceTree = "<group>"; };
B3AF019E1842FBA400A98B85 /* b2MotorJoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = b2MotorJoint.cpp; sourceTree = "<group>"; };
B3AF019F1842FBA400A98B85 /* b2MotorJoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = b2MotorJoint.h; sourceTree = "<group>"; };
B5668D7B1B3838E4003CBD5E /* UIScrollViewBar.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = UIScrollViewBar.cpp; sourceTree = "<group>"; };
B5668D7C1B3838E4003CBD5E /* UIScrollViewBar.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UIScrollViewBar.h; sourceTree = "<group>"; };
B5CE6DBC1B3BF2B1002B0419 /* UIAbstractCheckButton.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = UIAbstractCheckButton.cpp; sourceTree = "<group>"; };
B5CE6DBD1B3BF2B1002B0419 /* UIAbstractCheckButton.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UIAbstractCheckButton.h; sourceTree = "<group>"; };
B5CE6DC61B3C05BA002B0419 /* UIRadioButton.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = UIRadioButton.cpp; sourceTree = "<group>"; };
B5CE6DC71B3C05BA002B0419 /* UIRadioButton.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UIRadioButton.h; sourceTree = "<group>"; };
B5668D7B1B3838E4003CBD5E /* UIScrollViewBar.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = UIScrollViewBar.cpp; sourceTree = "<group>"; };
B5668D7C1B3838E4003CBD5E /* UIScrollViewBar.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UIScrollViewBar.h; sourceTree = "<group>"; };
B603F1A61AC8EA0900A9579C /* CCTerrain.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCTerrain.cpp; sourceTree = "<group>"; };
B603F1A71AC8EA0900A9579C /* CCTerrain.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTerrain.h; sourceTree = "<group>"; };
B603F1B11AC8F1FD00A9579C /* ccShader_3D_Terrain.frag */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.glsl; path = ccShader_3D_Terrain.frag; sourceTree = "<group>"; };
@ -12521,7 +12521,6 @@
"COCOS2D_DEBUG=1",
USE_FILE32API,
"CC_ENABLE_CHIPMUNK_INTEGRATION=1",
"CC_ENABLE_BULLET_INTEGRATION=1",
);
GCC_SYMBOLS_PRIVATE_EXTERN = YES;
GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES;
@ -12556,7 +12555,6 @@
"CC_ENABLE_CHIPMUNK_INTEGRATION=1",
NDEBUG,
USE_FILE32API,
"CC_ENABLE_BULLET_INTEGRATION=1",
);
GCC_SYMBOLS_PRIVATE_EXTERN = YES;
GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES;

View File

@ -883,6 +883,12 @@
688669711AE8E8B500C2CFD9 /* SpritePolygonTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6886696F1AE8E8B500C2CFD9 /* SpritePolygonTest.cpp */; };
688669721AE8E8B500C2CFD9 /* SpritePolygonTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6886696F1AE8E8B500C2CFD9 /* SpritePolygonTest.cpp */; };
826294431AAF071500CB7CF7 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 826294421AAF071500CB7CF7 /* Security.framework */; };
850F8A241B5F3A4F00780603 /* Bug-12847.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 850F8A221B5F3A4F00780603 /* Bug-12847.cpp */; };
850F8A251B5F3A4F00780603 /* Bug-12847.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 850F8A221B5F3A4F00780603 /* Bug-12847.cpp */; };
94D793D91B4B7A3600F60F10 /* Bug-CCDrawNode.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 94D793D51B4B7A3600F60F10 /* Bug-CCDrawNode.cpp */; };
94D793DA1B4B7A3600F60F10 /* Bug-CCDrawNode.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 94D793D51B4B7A3600F60F10 /* Bug-CCDrawNode.cpp */; };
94D793DB1B4B7A3600F60F10 /* Bug-PageViewLayout.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 94D793D71B4B7A3600F60F10 /* Bug-PageViewLayout.cpp */; };
94D793DC1B4B7A3600F60F10 /* Bug-PageViewLayout.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 94D793D71B4B7A3600F60F10 /* Bug-PageViewLayout.cpp */; };
A05FCACA177C124500BE600E /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 15C64822165F391E007D4F18 /* Cocoa.framework */; };
A07A521E1783A1D20073F6A7 /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 15C6482E165F399D007D4F18 /* libz.dylib */; };
A07A521F1783A1D20073F6A7 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 15C64832165F3AFD007D4F18 /* Foundation.framework */; };
@ -1945,6 +1951,12 @@
70A7F72D191D3E4900F0F206 /* shaderTest.psh.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = shaderTest.psh.h; sourceTree = "<group>"; };
70A7F730191D421B00F0F206 /* ShaderTest.vsh.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ShaderTest.vsh.h; sourceTree = "<group>"; };
826294421AAF071500CB7CF7 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; };
850F8A221B5F3A4F00780603 /* Bug-12847.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = "Bug-12847.cpp"; sourceTree = "<group>"; };
850F8A231B5F3A4F00780603 /* Bug-12847.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "Bug-12847.h"; sourceTree = "<group>"; };
94D793D51B4B7A3600F60F10 /* Bug-CCDrawNode.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = "Bug-CCDrawNode.cpp"; sourceTree = "<group>"; };
94D793D61B4B7A3600F60F10 /* Bug-CCDrawNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "Bug-CCDrawNode.h"; sourceTree = "<group>"; };
94D793D71B4B7A3600F60F10 /* Bug-PageViewLayout.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = "Bug-PageViewLayout.cpp"; sourceTree = "<group>"; };
94D793D81B4B7A3600F60F10 /* Bug-PageViewLayout.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "Bug-PageViewLayout.h"; sourceTree = "<group>"; };
A035A71117822E9E00987F6C /* libsqlite3.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsqlite3.dylib; path = usr/lib/libsqlite3.dylib; sourceTree = SDKROOT; };
A07A52291783A1D20073F6A7 /* cpp-tests iOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "cpp-tests iOS.app"; sourceTree = BUILT_PRODUCTS_DIR; };
A07A52B71783AE6D0073F6A7 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; };
@ -2733,6 +2745,10 @@
1AC3597618CECF0B00F37B72 /* BugsTest */ = {
isa = PBXGroup;
children = (
94D793D51B4B7A3600F60F10 /* Bug-CCDrawNode.cpp */,
94D793D61B4B7A3600F60F10 /* Bug-CCDrawNode.h */,
94D793D71B4B7A3600F60F10 /* Bug-PageViewLayout.cpp */,
94D793D81B4B7A3600F60F10 /* Bug-PageViewLayout.h */,
1AC3597718CECF0B00F37B72 /* Bug-1159.cpp */,
1AC3597818CECF0B00F37B72 /* Bug-1159.h */,
1AC3597918CECF0B00F37B72 /* Bug-1174.cpp */,
@ -2754,6 +2770,8 @@
1AC3598D18CECF0B00F37B72 /* BugsTest.h */,
59620E8D1921E5CF002021B6 /* Bug-Child.cpp */,
59620E8E1921E5CF002021B6 /* Bug-Child.h */,
850F8A221B5F3A4F00780603 /* Bug-12847.cpp */,
850F8A231B5F3A4F00780603 /* Bug-12847.h */,
);
path = BugsTest;
sourceTree = "<group>";
@ -5388,6 +5406,7 @@
1AC35BEB18CECF0C00F37B72 /* CCControlSliderTest.cpp in Sources */,
1AC35C4D18CECF0C00F37B72 /* SpineTest.cpp in Sources */,
3E92EA821921A1400094CD21 /* Sprite3DTest.cpp in Sources */,
94D793DB1B4B7A3600F60F10 /* Bug-PageViewLayout.cpp in Sources */,
1AC35C1D18CECF0C00F37B72 /* NewRendererTest.cpp in Sources */,
1AC35B6718CECF0C00F37B72 /* AnimationsTestLayer.cpp in Sources */,
29080DB7191B595E0066F8DF /* UIListViewTest_Editor.cpp in Sources */,
@ -5402,6 +5421,7 @@
1AC35B2918CECF0C00F37B72 /* AppDelegate.cpp in Sources */,
29080DA1191B595E0066F8DF /* GUIEditorTest.cpp in Sources */,
1AC35B3718CECF0C00F37B72 /* Bug-1159.cpp in Sources */,
850F8A241B5F3A4F00780603 /* Bug-12847.cpp in Sources */,
A5030C3519D059DA000E78E7 /* OpenURLTest.cpp in Sources */,
29080D1C191B574B0066F8DF /* UITest.cpp in Sources */,
1AC35C3118CECF0C00F37B72 /* PerformanceRendererTest.cpp in Sources */,
@ -5533,6 +5553,7 @@
1AC35B2518CECF0C00F37B72 /* ActionsProgressTest.cpp in Sources */,
1AC35B6518CECF0C00F37B72 /* EffectsTest.cpp in Sources */,
1AC35B7118CECF0C00F37B72 /* TestHeaderLayer.cpp in Sources */,
94D793D91B4B7A3600F60F10 /* Bug-CCDrawNode.cpp in Sources */,
29080D93191B595E0066F8DF /* CustomImageTest.cpp in Sources */,
1AC35B2118CECF0C00F37B72 /* ActionManagerTest.cpp in Sources */,
1AC35C3D18CECF0C00F37B72 /* PhysicsTest.cpp in Sources */,
@ -5673,6 +5694,7 @@
1AC35B2818CECF0C00F37B72 /* ActionsTest.cpp in Sources */,
1AC35C4A18CECF0C00F37B72 /* ShaderTest.cpp in Sources */,
B609E67419C18DAD003D0074 /* BillBoardTest.cpp in Sources */,
94D793DC1B4B7A3600F60F10 /* Bug-PageViewLayout.cpp in Sources */,
C04F935B1941B05400E9FEAB /* TileMapTest2.cpp in Sources */,
1AC35B4418CECF0C00F37B72 /* Bug-624.cpp in Sources */,
1AC35BF818CECF0C00F37B72 /* SocketIOTest.cpp in Sources */,
@ -5753,6 +5775,7 @@
1AC35B3018CECF0C00F37B72 /* Box2dView.cpp in Sources */,
29080DAE191B595E0066F8DF /* UIImageViewTest.cpp in Sources */,
1AC35C1018CECF0C00F37B72 /* LabelTest.cpp in Sources */,
850F8A251B5F3A4F00780603 /* Bug-12847.cpp in Sources */,
59620E901921E5CF002021B6 /* Bug-Child.cpp in Sources */,
29080DC8191B595E0066F8DF /* UISceneManager.cpp in Sources */,
1AC35C6A18CECF0C00F37B72 /* VisibleRect.cpp in Sources */,
@ -5781,6 +5804,7 @@
1AC35BEA18CECF0C00F37B72 /* CCControlSceneManager.cpp in Sources */,
182C5CBB1A95B30500C30D34 /* CocosStudio3DTest.cpp in Sources */,
1AC35B7418CECF0C00F37B72 /* TimelineCallbackTestLayer.cpp in Sources */,
94D793DA1B4B7A3600F60F10 /* Bug-CCDrawNode.cpp in Sources */,
29080D9E191B595E0066F8DF /* CustomParticleWidgetReader.cpp in Sources */,
1AC35BFC18CECF0C00F37B72 /* NotificationCenterTest.cpp in Sources */,
29FBBBFF196A9ECD00E65826 /* CocostudioParserJsonTest.cpp in Sources */,
@ -6662,7 +6686,6 @@
"COCOS2D_DEBUG=1",
USE_FILE32API,
"CC_ENABLE_CHIPMUNK_INTEGRATION=1",
"CC_ENABLE_BULLET_INTEGRATION=1",
);
GCC_SYMBOLS_PRIVATE_EXTERN = YES;
GCC_TREAT_WARNINGS_AS_ERRORS = YES;
@ -6691,7 +6714,6 @@
NDEBUG,
USE_FILE32API,
"CC_ENABLE_CHIPMUNK_INTEGRATION=1",
"CC_ENABLE_BULLET_INTEGRATION=1",
);
GCC_SYMBOLS_PRIVATE_EXTERN = YES;
GCC_TREAT_WARNINGS_AS_ERRORS = YES;

View File

@ -40,6 +40,7 @@ Action::Action()
:_originalTarget(nullptr)
,_target(nullptr)
,_tag(Action::INVALID_TAG)
,_flags(0)
{
}

View File

@ -143,6 +143,16 @@ public:
* @param tag Used to identify the action easily.
*/
inline void setTag(int tag) { _tag = tag; }
/** Returns a flag field that is used to group the actions easily.
*
* @return A tag.
*/
inline unsigned int getFlags() const { return _flags; }
/** Changes the flag field that is used to group the actions easily.
*
* @param tag Used to identify the action easily.
*/
inline void setFlags(unsigned int flags) { _flags = flags; }
CC_CONSTRUCTOR_ACCESS:
Action();
@ -159,6 +169,8 @@ protected:
Node *_target;
/** The action tag. An identifier of the action. */
int _tag;
/** The action flag field. To categorize action into certain groups.*/
unsigned int _flags;
private:
CC_DISALLOW_COPY_AND_ASSIGN(Action);

View File

@ -46,7 +46,7 @@ NS_CC_BEGIN
bool ActionEase::initWithAction(ActionInterval *action)
{
CCASSERT(action != nullptr, "");
CCASSERT(action != nullptr, "action couldn't be nullptr!");
if (ActionInterval::initWithDuration(action->getDuration()))
{

View File

@ -57,13 +57,13 @@ void GridAction::startWithTarget(Node *target)
if (targetGrid && targetGrid->getReuseGrid() > 0)
{
if (targetGrid->isActive() && targetGrid->getGridSize().width == _gridSize.width
&& targetGrid->getGridSize().height == _gridSize.height /*&& dynamic_cast<GridBase*>(targetGrid) != nullptr*/)
&& targetGrid->getGridSize().height == _gridSize.height)
{
targetGrid->reuse();
}
else
{
CCASSERT(0, "");
CCASSERT(0, "Invalid grid parameters!");
}
}
else
@ -93,7 +93,7 @@ GridAction* GridAction::reverse() const
GridBase* GridAction::getGrid()
{
// Abstract class needs implementation
CCASSERT(0, "");
CCASSERT(0, "Subclass should implement this method!");
return nullptr;
}

View File

@ -134,13 +134,13 @@ void ActionInterval::setAmplitudeRate(float amp)
{
CC_UNUSED_PARAM(amp);
// Abstract class needs implementation
CCASSERT(0, "");
CCASSERT(0, "Subclass should implement this method!");
}
float ActionInterval::getAmplitudeRate()
{
// Abstract class needs implementation
CCASSERT(0, "");
CCASSERT(0, "Subclass should implement this method!");
return 0;
}
@ -248,8 +248,8 @@ Sequence* Sequence::create(const Vector<FiniteTimeAction*>& arrayOfActions)
bool Sequence::initWithTwoActions(FiniteTimeAction *actionOne, FiniteTimeAction *actionTwo)
{
CCASSERT(actionOne != nullptr, "");
CCASSERT(actionTwo != nullptr, "");
CCASSERT(actionOne != nullptr, "actionOne can't be nullptr!");
CCASSERT(actionTwo != nullptr, "actionTwo can't be nullptr!");
float d = actionOne->getDuration() + actionTwo->getDuration();
ActionInterval::initWithDuration(d);
@ -504,7 +504,7 @@ RepeatForever *RepeatForever::create(ActionInterval *action)
bool RepeatForever::initWithAction(ActionInterval *action)
{
CCASSERT(action != nullptr, "");
CCASSERT(action != nullptr, "action can't be nullptr!");
action->retain();
_innerAction = action;
return true;
@ -645,8 +645,8 @@ Spawn* Spawn::createWithTwoActions(FiniteTimeAction *action1, FiniteTimeAction *
bool Spawn::initWithTwoActions(FiniteTimeAction *action1, FiniteTimeAction *action2)
{
CCASSERT(action1 != nullptr, "");
CCASSERT(action2 != nullptr, "");
CCASSERT(action1 != nullptr, "action1 can't be nullptr!");
CCASSERT(action2 != nullptr, "action2 can't be nullptr!");
bool ret = false;
@ -2189,8 +2189,8 @@ ReverseTime* ReverseTime::create(FiniteTimeAction *action)
bool ReverseTime::initWithAction(FiniteTimeAction *action)
{
CCASSERT(action != nullptr, "");
CCASSERT(action != _other, "");
CCASSERT(action != nullptr, "action can't be nullptr!");
CCASSERT(action != _other, "action doesn't equal to _other!");
if (ActionInterval::initWithDuration(action->getDuration()))
{
@ -2270,6 +2270,7 @@ Animate::Animate()
, _executedLoops(0)
, _animation(nullptr)
, _frameDisplayedEvent(nullptr)
, _currFrameIndex(0)
{
}
@ -2383,7 +2384,8 @@ void Animate::update(float t)
float splitTime = _splitTimes->at(i);
if( splitTime <= t ) {
AnimationFrame* frame = frames.at(i);
_currFrameIndex = i;
AnimationFrame* frame = frames.at(_currFrameIndex);
frameToDisplay = frame->getSpriteFrame();
static_cast<Sprite*>(_target)->setSpriteFrame(frameToDisplay);

View File

@ -1439,6 +1439,11 @@ public:
Animation* getAnimation() { return _animation; }
const Animation* getAnimation() const { return _animation; }
/**
* Gets the index of sprite frame currently displayed.
* @return int the index of sprite frame currently displayed.
*/
int getCurrentFrameIndex() { return _currFrameIndex; }
//
// Overrides
//
@ -1462,6 +1467,7 @@ protected:
std::vector<float>* _splitTimes;
int _nextFrame;
SpriteFrame* _origFrame;
int _currFrameIndex;
unsigned int _executedLoops;
Animation* _animation;

View File

@ -168,8 +168,8 @@ void ActionManager::resumeTargets(const Vector<Node*>& targetsToResume)
void ActionManager::addAction(Action *action, Node *target, bool paused)
{
CCASSERT(action != nullptr, "");
CCASSERT(target != nullptr, "");
CCASSERT(action != nullptr, "action can't be nullptr!");
CCASSERT(target != nullptr, "target can't be nullptr!");
tHashElement *element = nullptr;
// we should convert it to Ref*, because we save it as Ref*
@ -186,7 +186,7 @@ void ActionManager::addAction(Action *action, Node *target, bool paused)
actionAllocWithHashElement(element);
CCASSERT(! ccArrayContainsObject(element->actions, action), "");
CCASSERT(! ccArrayContainsObject(element->actions, action), "action already be added!");
ccArrayAppendObject(element->actions, action);
action->startWithTarget(target);
@ -265,8 +265,8 @@ void ActionManager::removeAction(Action *action)
void ActionManager::removeActionByTag(int tag, Node *target)
{
CCASSERT(tag != Action::INVALID_TAG, "");
CCASSERT(target != nullptr, "");
CCASSERT(tag != Action::INVALID_TAG, "Invalid tag value!");
CCASSERT(target != nullptr, "target can't be nullptr!");
tHashElement *element = nullptr;
HASH_FIND_PTR(_targets, &target, element);
@ -289,8 +289,8 @@ void ActionManager::removeActionByTag(int tag, Node *target)
void ActionManager::removeAllActionsByTag(int tag, Node *target)
{
CCASSERT(tag != Action::INVALID_TAG, "");
CCASSERT(target != nullptr, "");
CCASSERT(tag != Action::INVALID_TAG, "Invalid tag value!");
CCASSERT(target != nullptr, "target can't be nullptr!");
tHashElement *element = nullptr;
HASH_FIND_PTR(_targets, &target, element);
@ -315,13 +315,44 @@ void ActionManager::removeAllActionsByTag(int tag, Node *target)
}
}
void ActionManager::removeActionsByFlags(unsigned int flags, Node *target)
{
if (flags == 0)
{
return;
}
CCASSERT(target != nullptr, "target can't be nullptr!");
tHashElement *element = nullptr;
HASH_FIND_PTR(_targets, &target, element);
if (element)
{
auto limit = element->actions->num;
for (int i = 0; i < limit;)
{
Action *action = (Action*)element->actions->arr[i];
if ((action->getFlags() & flags) != 0 && action->getOriginalTarget() == target)
{
removeActionAtIndex(i, element);
--limit;
}
else
{
++i;
}
}
}
}
// get
// FIXME: Passing "const O *" instead of "const O&" because HASH_FIND_IT requries the address of a pointer
// and, it is not possible to get the address of a reference
Action* ActionManager::getActionByTag(int tag, const Node *target) const
{
CCASSERT(tag != Action::INVALID_TAG, "");
CCASSERT(tag != Action::INVALID_TAG, "Invalid tag value!");
tHashElement *element = nullptr;
HASH_FIND_PTR(_targets, &target, element);

View File

@ -114,6 +114,14 @@ public:
*/
void removeAllActionsByTag(int tag, Node *target);
/** Removes all actions matching at least one bit in flags and the target.
*
* @param flags The flag field to match the actions' flags based on bitwise AND.
* @param target A certain target.
* @js NA
*/
void removeActionsByFlags(unsigned int flags, Node *target);
/** Gets an action given its tag an a target.
*
* @param tag The action's tag.

View File

@ -238,7 +238,7 @@ Vec2 Camera::project(const Vec3& src) const
Vec4 clipPos;
getViewProjectionMatrix().transformVector(Vec4(src.x, src.y, src.z, 1.0f), &clipPos);
CCASSERT(clipPos.w != 0.0f, "");
CCASSERT(clipPos.w != 0.0f, "clipPos.w can't be 0.0f!");
float ndcX = clipPos.x / clipPos.w;
float ndcY = clipPos.y / clipPos.w;
@ -255,7 +255,7 @@ Vec2 Camera::projectGL(const Vec3& src) const
Vec4 clipPos;
getViewProjectionMatrix().transformVector(Vec4(src.x, src.y, src.z, 1.0f), &clipPos);
CCASSERT(clipPos.w != 0.0f, "");
CCASSERT(clipPos.w != 0.0f, "clipPos.w can't be 0.0f!");
float ndcX = clipPos.x / clipPos.w;
float ndcY = clipPos.y / clipPos.w;

View File

@ -375,6 +375,8 @@ void DrawNode::onDrawGLLine(const Mat4 &transform, uint32_t flags)
glProgram->use();
glProgram->setUniformsForBuiltins(transform);
GL::blendFunc(_blendFunc.src, _blendFunc.dst);
if (_dirtyGLLine)
{
glBindBuffer(GL_ARRAY_BUFFER, _vboGLLine);
@ -416,6 +418,8 @@ void DrawNode::onDrawGLPoint(const Mat4 &transform, uint32_t flags)
glProgram->use();
glProgram->setUniformsForBuiltins(transform);
GL::blendFunc(_blendFunc.src, _blendFunc.dst);
if (_dirtyGLPoint)
{
glBindBuffer(GL_ARRAY_BUFFER, _vboGLPoint);

View File

@ -70,32 +70,6 @@ static Color4F s_color(1.0f,1.0f,1.0f,1.0f);
static int s_pointSizeLocation = -1;
static GLfloat s_pointSize = 1.0f;
#ifdef EMSCRIPTEN
static GLuint s_bufferObject = 0;
static GLuint s_bufferSize = 0;
static void setGLBufferData(void *buf, GLuint bufSize)
{
if(s_bufferSize < bufSize)
{
if(s_bufferObject)
{
glDeleteBuffers(1, &s_bufferObject);
}
glGenBuffers(1, &s_bufferObject);
s_bufferSize = bufSize;
glBindBuffer(GL_ARRAY_BUFFER, s_bufferObject);
glBufferData(GL_ARRAY_BUFFER, bufSize, buf, GL_DYNAMIC_DRAW);
}
else
{
glBindBuffer(GL_ARRAY_BUFFER, s_bufferObject);
glBufferSubData(GL_ARRAY_BUFFER, 0, bufSize, buf);
}
}
#endif // EMSCRIPTEN
static void lazy_init()
{
@ -143,12 +117,7 @@ void drawPoint(const Vec2& point)
s_shader->setUniformLocationWith4fv(s_colorLocation, (GLfloat*) &s_color.r, 1);
s_shader->setUniformLocationWith1f(s_pointSizeLocation, s_pointSize);
#ifdef EMSCRIPTEN
setGLBufferData(&p, 8);
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, &p);
#endif // EMSCRIPTEN
glDrawArrays(GL_POINTS, 0, 1);
@ -171,12 +140,7 @@ void drawPoints( const Vec2 *points, unsigned int numberOfPoints )
// iPhone and 32-bit machines optimization
if( sizeof(Vec2) == sizeof(Vec2) )
{
#ifdef EMSCRIPTEN
setGLBufferData((void*) points, numberOfPoints * sizeof(Vec2));
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, points);
#endif // EMSCRIPTEN
}
else
{
@ -185,14 +149,7 @@ void drawPoints( const Vec2 *points, unsigned int numberOfPoints )
newPoints[i].x = points[i].x;
newPoints[i].y = points[i].y;
}
#ifdef EMSCRIPTEN
// Suspect Emscripten won't be emitting 64-bit code for a while yet,
// but want to make sure this continues to work even if they do.
setGLBufferData(newPoints, numberOfPoints * sizeof(Vec2));
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, newPoints);
#endif // EMSCRIPTEN
}
glDrawArrays(GL_POINTS, 0, (GLsizei) numberOfPoints);
@ -217,12 +174,7 @@ void drawLine(const Vec2& origin, const Vec2& destination)
s_shader->setUniformLocationWith4fv(s_colorLocation, (GLfloat*) &s_color.r, 1);
GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION );
#ifdef EMSCRIPTEN
setGLBufferData(vertices, 16);
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, vertices);
#endif // EMSCRIPTEN
glDrawArrays(GL_LINES, 0, 2);
CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1,2);
@ -261,12 +213,7 @@ void drawPoly(const Vec2 *poli, unsigned int numberOfPoints, bool closePolygon)
// iPhone and 32-bit machines optimization
if( sizeof(Vec2) == sizeof(Vec2) )
{
#ifdef EMSCRIPTEN
setGLBufferData((void*) poli, numberOfPoints * sizeof(Vec2));
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, poli);
#endif // EMSCRIPTEN
if( closePolygon )
glDrawArrays(GL_LINE_LOOP, 0, (GLsizei) numberOfPoints);
@ -282,12 +229,7 @@ void drawPoly(const Vec2 *poli, unsigned int numberOfPoints, bool closePolygon)
newPoli[i].x = poli[i].x;
newPoli[i].y = poli[i].y;
}
#ifdef EMSCRIPTEN
setGLBufferData(newPoli, numberOfPoints * sizeof(Vec2));
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, newPoli);
#endif // EMSCRIPTEN
if( closePolygon )
glDrawArrays(GL_LINE_LOOP, 0, (GLsizei) numberOfPoints);
@ -316,12 +258,7 @@ void drawSolidPoly(const Vec2 *poli, unsigned int numberOfPoints, Color4F color)
// iPhone and 32-bit machines optimization
if (sizeof(Vec2) == sizeof(Vec2))
{
#ifdef EMSCRIPTEN
setGLBufferData((void*) poli, numberOfPoints * sizeof(Vec2));
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, poli);
#endif // EMSCRIPTEN
}
else
{
@ -330,12 +267,7 @@ void drawSolidPoly(const Vec2 *poli, unsigned int numberOfPoints, Color4F color)
{
newPoli[i].set(poli[i].x, poli[i].y);
}
#ifdef EMSCRIPTEN
setGLBufferData(newPoli, numberOfPoints * sizeof(Vec2));
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, newPoli);
#endif // EMSCRIPTEN
}
glDrawArrays(GL_TRIANGLE_FAN, 0, (GLsizei) numberOfPoints);
@ -375,12 +307,7 @@ void drawCircle( const Vec2& center, float radius, float angle, unsigned int seg
GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION );
#ifdef EMSCRIPTEN
setGLBufferData(vertices, sizeof(GLfloat)*2*(segments+2));
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, vertices);
#endif // EMSCRIPTEN
glDrawArrays(GL_LINE_STRIP, 0, (GLsizei) segments+additionalSegment);
::free( vertices );
@ -420,12 +347,7 @@ void drawSolidCircle( const Vec2& center, float radius, float angle, unsigned in
GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION );
#ifdef EMSCRIPTEN
setGLBufferData(vertices, sizeof(GLfloat)*2*(segments+2));
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, vertices);
#endif // EMSCRIPTEN
glDrawArrays(GL_TRIANGLE_FAN, 0, (GLsizei) segments+1);
@ -461,12 +383,7 @@ void drawQuadBezier(const Vec2& origin, const Vec2& control, const Vec2& destina
GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION );
#ifdef EMSCRIPTEN
setGLBufferData(vertices, (segments + 1) * sizeof(Vec2));
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, vertices);
#endif // EMSCRIPTEN
glDrawArrays(GL_LINE_STRIP, 0, (GLsizei) segments + 1);
CC_SAFE_DELETE_ARRAY(vertices);
@ -518,12 +435,7 @@ void drawCardinalSpline( PointArray *config, float tension, unsigned int segmen
GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION );
#ifdef EMSCRIPTEN
setGLBufferData(vertices, (segments + 1) * sizeof(Vec2));
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, vertices);
#endif // EMSCRIPTEN
glDrawArrays(GL_LINE_STRIP, 0, (GLsizei) segments + 1);
CC_SAFE_DELETE_ARRAY(vertices);
@ -552,12 +464,7 @@ void drawCubicBezier(const Vec2& origin, const Vec2& control1, const Vec2& contr
GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION );
#ifdef EMSCRIPTEN
setGLBufferData(vertices, (segments + 1) * sizeof(Vec2));
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, vertices);
#endif // EMSCRIPTEN
glDrawArrays(GL_LINE_STRIP, 0, (GLsizei) segments + 1);
CC_SAFE_DELETE_ARRAY(vertices);

View File

@ -204,7 +204,7 @@ bool FontAtlas::prepareLetterDefinitions(const std::u16string& utf16String)
if (bitmapHeight > _currLineHeight)
{
_currLineHeight = bitmapHeight + 1;
_currLineHeight = static_cast<int>(bitmapHeight) + 1;
}
if (_currentPageOrigX + tempDef.width > CacheTextureWidth)
{

View File

@ -137,9 +137,28 @@ bool FontFreeType::createFontObject(const std::string &fontName, int fontSize)
if (FT_New_Memory_Face(getFTLibrary(), s_cacheFontData[fontName].data.getBytes(), s_cacheFontData[fontName].data.getSize(), 0, &face ))
return false;
//we want to use unicode
if (FT_Select_Charmap(face, FT_ENCODING_UNICODE))
{
int foundIndex = -1;
for (int charmapIndex = 0; charmapIndex < face->num_charmaps; charmapIndex++)
{
if (face->charmaps[charmapIndex]->encoding != FT_ENCODING_NONE)
{
foundIndex = charmapIndex;
break;
}
}
if (foundIndex == -1)
{
return false;
}
if (FT_Select_Charmap(face, face->charmaps[foundIndex]->encoding))
{
return false;
}
}
// set the requested font size
int dpi = 72;

View File

@ -245,17 +245,17 @@ void GridBase::afterDraw(cocos2d::Node *target)
void GridBase::blit(void)
{
CCASSERT(0, "");
CCASSERT(0, "Subclass should implement it.");
}
void GridBase::reuse(void)
{
CCASSERT(0, "");
CCASSERT(0, "Subclass should implement it!");
}
void GridBase::calculateVertexPoints(void)
{
CCASSERT(0, "");
CCASSERT(0, "Subclass should implement it.");
}
// implementation of Grid3D

View File

@ -162,7 +162,7 @@ Label* Label::create(const std::string& text, const std::string& font, float fon
Label* Label::createWithSystemFont(const std::string& text, const std::string& font, float fontSize, const Size& dimensions /* = Size::ZERO */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */, TextVAlignment vAlignment /* = TextVAlignment::TOP */)
{
auto ret = new (std::nothrow) Label(nullptr,hAlignment,vAlignment);
auto ret = new (std::nothrow) Label(hAlignment,vAlignment);
if (ret)
{
@ -182,7 +182,7 @@ Label* Label::createWithSystemFont(const std::string& text, const std::string& f
Label* Label::createWithTTF(const std::string& text, const std::string& fontFile, float fontSize, const Size& dimensions /* = Size::ZERO */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */, TextVAlignment vAlignment /* = TextVAlignment::TOP */)
{
auto ret = new (std::nothrow) Label(nullptr,hAlignment,vAlignment);
auto ret = new (std::nothrow) Label(hAlignment,vAlignment);
if (ret && FileUtils::getInstance()->isFileExist(fontFile))
{
@ -202,9 +202,9 @@ Label* Label::createWithTTF(const std::string& text, const std::string& fontFile
return nullptr;
}
Label* Label::createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment alignment /* = TextHAlignment::CENTER */, int maxLineWidth /* = 0 */)
Label* Label::createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment hAlignment /* = TextHAlignment::CENTER */, int maxLineWidth /* = 0 */)
{
auto ret = new (std::nothrow) Label(nullptr,alignment);
auto ret = new (std::nothrow) Label(hAlignment);
if (ret && FileUtils::getInstance()->isFileExist(ttfConfig.fontFilePath) && ret->setTTFConfig(ttfConfig))
{
@ -219,9 +219,9 @@ Label* Label::createWithTTF(const TTFConfig& ttfConfig, const std::string& text,
return nullptr;
}
Label* Label::createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& alignment /* = TextHAlignment::LEFT */, int maxLineWidth /* = 0 */, const Vec2& imageOffset /* = Vec2::ZERO */)
Label* Label::createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& hAlignment /* = TextHAlignment::LEFT */, int maxLineWidth /* = 0 */, const Vec2& imageOffset /* = Vec2::ZERO */)
{
auto ret = new (std::nothrow) Label(nullptr,alignment);
auto ret = new (std::nothrow) Label(hAlignment);
if (ret && ret->setBMFontFilePath(bmfontFilePath,imageOffset))
{
@ -326,41 +326,23 @@ bool Label::setCharMap(const std::string& charMapFile, int itemWidth, int itemHe
return true;
}
Label::Label(FontAtlas *atlas /* = nullptr */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */,
TextVAlignment vAlignment /* = TextVAlignment::TOP */,bool useDistanceField /* = false */,bool useA8Shader /* = false */)
: _isOpacityModifyRGB(false)
, _contentDirty(false)
, _fontAtlas(atlas)
, _textSprite(nullptr)
, _compatibleMode(false)
Label::Label(TextHAlignment hAlignment /* = TextHAlignment::LEFT */,
TextVAlignment vAlignment /* = TextVAlignment::TOP */)
: _textSprite(nullptr)
, _shadowNode(nullptr)
, _fontAtlas(nullptr)
, _reusedLetter(nullptr)
, _additionalKerning(0.0f)
, _commonLineHeight(0.0f)
, _lineBreakWithoutSpaces(false)
, _horizontalKernings(nullptr)
, _maxLineWidth(0.0f)
, _labelDimensions(Size::ZERO)
, _labelWidth(0.0f)
, _labelHeight(0.0f)
, _hAlignment(hAlignment)
, _vAlignment(vAlignment)
, _currNumLines(-1)
, _fontScale(1.0f)
, _useDistanceField(useDistanceField)
, _useA8Shader(useA8Shader)
, _effectColorF(Color4F::BLACK)
, _uniformEffectColor(0)
, _shadowDirty(false)
, _blendFunc(BlendFunc::ALPHA_PREMULTIPLIED)
, _insideBounds(true)
{
setAnchorPoint(Vec2::ANCHOR_MIDDLE);
reset();
_hAlignment = hAlignment;
_vAlignment = vAlignment;
_purgeTextureListener = EventListenerCustom::create(FontAtlas::CMD_PURGE_FONTATLAS, [this](EventCustom* event){
if (_fontAtlas && _currentLabelType == LabelType::TTF && event->getUserData() == _fontAtlas)
{
for (auto it : _letters)
for (auto&& it : _letters)
{
it.second->setTexture(nullptr);
}
@ -379,7 +361,7 @@ Label::Label(FontAtlas *atlas /* = nullptr */, TextHAlignment hAlignment /* = Te
{
_fontAtlas = nullptr;
this->setTTFConfig(_fontConfig);
for (auto it : _letters)
for (auto&& it : _letters)
{
getLetter(it.first);
}
@ -394,27 +376,27 @@ Label::~Label()
if (_fontAtlas)
{
Node::removeAllChildrenWithCleanup(true);
CC_SAFE_RELEASE_NULL(_reusedLetter);
_batchNodes.clear();
FontAtlasCache::releaseFontAtlas(_fontAtlas);
}
_eventDispatcher->removeEventListener(_purgeTextureListener);
_eventDispatcher->removeEventListener(_resetTextureListener);
CC_SAFE_RELEASE_NULL(_reusedLetter);
CC_SAFE_RELEASE_NULL(_textSprite);
CC_SAFE_RELEASE_NULL(_shadowNode);
}
void Label::reset()
{
TTFConfig temp;
_fontConfig = temp;
_systemFontDirty = false;
_systemFont = "Helvetica";
_systemFontSize = 12;
CC_SAFE_RELEASE_NULL(_textSprite);
CC_SAFE_RELEASE_NULL(_shadowNode);
Node::removeAllChildrenWithCleanup(true);
CC_SAFE_RELEASE_NULL(_reusedLetter);
_letters.clear();
_batchNodes.clear();
_lettersInfo.clear();
if (_fontAtlas)
{
FontAtlasCache::releaseFontAtlas(_fontAtlas);
@ -423,21 +405,53 @@ void Label::reset()
_currentLabelType = LabelType::STRING_TEXTURE;
_currLabelEffect = LabelEffect::NORMAL;
_shadowBlurRadius = 0;
_contentDirty = false;
_currNumLines = 0;
_limitShowCount = 0;
_currentUTF16String.clear();
_originalUTF8String.clear();
Node::removeAllChildrenWithCleanup(true);
_textSprite = nullptr;
_shadowNode = nullptr;
TTFConfig temp;
_fontConfig = temp;
_outlineSize = 0.f;
_bmFontPath = "";
_systemFontDirty = false;
_systemFont = "Helvetica";
_systemFontSize = 12;
CC_SAFE_RELEASE_NULL(_reusedLetter);
if (_horizontalKernings)
{
delete[] _horizontalKernings;
_horizontalKernings = nullptr;
}
_additionalKerning = 0.f;
_commonLineHeight = 0.f;
_maxLineWidth = 0.f;
_labelDimensions.width = 0.f;
_labelDimensions.height = 0.f;
_labelWidth = 0.f;
_labelHeight = 0.f;
_lineBreakWithoutSpaces = false;
_hAlignment = TextHAlignment::LEFT;
_vAlignment = TextVAlignment::TOP;
_effectColorF = Color4F::BLACK;
_textColor = Color4B::WHITE;
_textColorF = Color4F::WHITE;
setColor(Color3B::WHITE);
_shadowDirty = false;
_shadowEnabled = false;
_shadowBlurRadius = 0.f;
_correctionScale = 1.f;
_useDistanceField = false;
_useA8Shader = false;
_clipEnabled = false;
_blendFuncDirty = false;
_blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;
_isOpacityModifyRGB = false;
_insideBounds = true;
}
void Label::updateShaderProgram()
@ -481,6 +495,7 @@ void Label::setFontAtlas(FontAtlas* atlas,bool distanceFieldEnabled /* = false *
if (_fontAtlas)
{
_batchNodes.clear();
FontAtlasCache::releaseFontAtlas(_fontAtlas);
_fontAtlas = nullptr;
}
@ -538,7 +553,7 @@ bool Label::setTTFConfig(const TTFConfig& ttfConfig)
updateShaderProgram();
if(ttfConfig.distanceFieldEnabled)
{
this->setFontScale(1.0f * ttfConfig.fontSize / DistanceFieldFontSize);
this->setCorrectionScale(1.0f * ttfConfig.fontSize / DistanceFieldFontSize);
}
}
@ -623,7 +638,7 @@ void Label::setScale(float scale)
{
if (_useDistanceField)
{
scale *= _fontScale;
scale *= _correctionScale;
}
Node::setScale(scale);
}
@ -632,7 +647,7 @@ void Label::setScaleX(float scaleX)
{
if (_useDistanceField)
{
scaleX *= _fontScale;
scaleX *= _correctionScale;
}
Node::setScaleX(scaleX);
}
@ -641,7 +656,7 @@ void Label::setScaleY(float scaleY)
{
if (_useDistanceField)
{
scaleY *= _fontScale;
scaleY *= _correctionScale;
}
Node::setScaleY(scaleY);
}
@ -650,7 +665,7 @@ float Label::getScaleY() const
{
if (_useDistanceField)
{
return _scaleY / _fontScale;
return _scaleY / _correctionScale;
}
else
{
@ -662,7 +677,7 @@ float Label::getScaleX() const
{
if (_useDistanceField)
{
return _scaleX / _fontScale;
return _scaleX / _correctionScale;
}
else
{
@ -687,6 +702,7 @@ void Label::alignText()
auto batchNode = SpriteBatchNode::createWithTexture(textures.at(index));
if (batchNode)
{
_isOpacityModifyRGB = batchNode->getTexture()->hasPremultipliedAlpha();
_blendFunc = batchNode->getBlendFunc();
batchNode->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT);
batchNode->setPosition(Vec2::ZERO);
@ -741,7 +757,7 @@ void Label::alignText()
}
}
for (const auto& batchNode : _batchNodes)
for (auto&& batchNode : _batchNodes)
{
batchNode->getTextureAtlas()->removeAllQuads();
}
@ -781,19 +797,7 @@ void Label::updateQuads()
_reusedRect.size.width = letterDef.width;
_reusedRect.origin.x = letterDef.U;
_reusedRect.origin.y = letterDef.V;
if (_labelHeight > 0.f)
{
if (_lettersInfo[ctr].position.y > _contentSize.height)
{
auto clipTop = _lettersInfo[ctr].position.y - _contentSize.height;
_reusedRect.origin.y += clipTop;
_lettersInfo[ctr].position.y -= clipTop;
}
if (_lettersInfo[ctr].position.y - letterDef.height < 0.f)
{
_reusedRect.size.height = _lettersInfo[ctr].position.y < 0.f ? 0.f : _lettersInfo[ctr].position.y;
}
}
_reusedLetter->setTextureRect(_reusedRect,false,_reusedRect.size);
_reusedLetter->setPosition(_lettersInfo[ctr].position);
@ -848,11 +852,10 @@ void Label::enableGlow(const Color4B& glowColor)
_contentDirty = true;
}
_currLabelEffect = LabelEffect::GLOW;
_effectColor = glowColor;
_effectColorF.r = _effectColor.r / 255.0f;
_effectColorF.g = _effectColor.g / 255.0f;
_effectColorF.b = _effectColor.b / 255.0f;
_effectColorF.a = _effectColor.a / 255.0f;
_effectColorF.r = glowColor.r / 255.0f;
_effectColorF.g = glowColor.g / 255.0f;
_effectColorF.b = glowColor.b / 255.0f;
_effectColorF.a = glowColor.a / 255.0f;
updateShaderProgram();
}
}
@ -876,9 +879,12 @@ void Label::enableOutline(const Color4B& outlineColor,int outlineSize /* = -1 */
setTTFConfig(_fontConfig);
}
}
else if (_effectColor != outlineColor || _outlineSize != outlineSize)
else if (_effectColorF != outlineColor || _outlineSize != outlineSize)
{
_effectColor = outlineColor;
_effectColorF.r = outlineColor.r / 255.f;
_effectColorF.g = outlineColor.g / 255.f;
_effectColorF.b = outlineColor.b / 255.f;
_effectColorF.a = outlineColor.a / 255.f;
_outlineSize = outlineSize;
_currLabelEffect = LabelEffect::OUTLINE;
_contentDirty = true;
@ -895,7 +901,6 @@ void Label::enableShadow(const Color4B& shadowColor /* = Color4B::BLACK */,const
_shadowOffset.width = offset.width * contentScaleFactor;
_shadowOffset.height = offset.height * contentScaleFactor;
//TODO: support blur for shadow
_shadowBlurRadius = 0;
_shadowColor3B.r = shadowColor.r;
_shadowColor3B.g = shadowColor.g;
@ -904,13 +909,14 @@ void Label::enableShadow(const Color4B& shadowColor /* = Color4B::BLACK */,const
if (!_systemFontDirty && !_contentDirty && _textSprite)
{
auto fontDef = _getFontDefinition();
if (_shadowNode)
{
if (shadowColor != _shadowColor4F)
{
_shadowNode->release();
_shadowNode = nullptr;
createShadowSpriteForSystemFont();
createShadowSpriteForSystemFont(fontDef);
}
else
{
@ -919,7 +925,7 @@ void Label::enableShadow(const Color4B& shadowColor /* = Color4B::BLACK */,const
}
else
{
createShadowSpriteForSystemFont();
createShadowSpriteForSystemFont(fontDef);
}
}
@ -981,59 +987,18 @@ void Label::disableEffect(LabelEffect effect)
}
}
void Label::setFontScale(float fontScale)
void Label::setCorrectionScale(float correctionScale)
{
_fontScale = fontScale * CC_CONTENT_SCALE_FACTOR();
Node::setScale(_fontScale);
_correctionScale = correctionScale * CC_CONTENT_SCALE_FACTOR();
Node::setScale(_correctionScale);
}
void Label::createSpriteForSystemFont()
void Label::createSpriteForSystemFont(const FontDefinition& fontDef)
{
_currentLabelType = LabelType::STRING_TEXTURE;
if (!_compatibleMode)
{
_fontDefinition._fontName = _systemFont;
_fontDefinition._fontSize = _systemFontSize;
_fontDefinition._alignment = _hAlignment;
_fontDefinition._vertAlignment = _vAlignment;
_fontDefinition._dimensions.width = _labelWidth;
_fontDefinition._dimensions.height = _labelHeight;
_fontDefinition._fontFillColor.r = _textColor.r;
_fontDefinition._fontFillColor.g = _textColor.g;
_fontDefinition._fontFillColor.b = _textColor.b;
_fontDefinition._fontAlpha = _textColor.a;
_fontDefinition._shadow._shadowEnabled = false;
if (_currLabelEffect == LabelEffect::OUTLINE && _outlineSize > 0)
{
_fontDefinition._stroke._strokeEnabled = true;
_fontDefinition._stroke._strokeSize = _outlineSize;
_fontDefinition._stroke._strokeColor.r = _effectColor.r;
_fontDefinition._stroke._strokeColor.g = _effectColor.g;
_fontDefinition._stroke._strokeColor.b = _effectColor.b;
_fontDefinition._stroke._strokeAlpha = _effectColor.a;
}
else
{
_fontDefinition._stroke._strokeEnabled = false;
}
#if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) && (CC_TARGET_PLATFORM != CC_PLATFORM_IOS)
if (_fontDefinition._stroke._strokeEnabled)
{
CCLOGERROR("Currently only supported on iOS and Android!");
}
_fontDefinition._stroke._strokeEnabled = false;
#endif
}
auto texture = new (std::nothrow) Texture2D;
texture->initWithString(_originalUTF8String.c_str(), _fontDefinition);
texture->initWithString(_originalUTF8String.c_str(), fontDef);
_textSprite = Sprite::createWithTexture(texture);
//set camera mask using label's camera mask, because _textSprite may be null when setting camera mask to label
@ -1051,16 +1016,16 @@ void Label::createSpriteForSystemFont()
_textSprite->updateDisplayedOpacity(_displayedOpacity);
}
void Label::createShadowSpriteForSystemFont()
void Label::createShadowSpriteForSystemFont(const FontDefinition& fontDef)
{
if (!_fontDefinition._stroke._strokeEnabled && _fontDefinition._fontFillColor == _shadowColor3B
&& (_fontDefinition._fontAlpha == _shadowOpacity))
if (!fontDef._stroke._strokeEnabled && fontDef._fontFillColor == _shadowColor3B
&& (fontDef._fontAlpha == _shadowOpacity))
{
_shadowNode = Sprite::createWithTexture(_textSprite->getTexture());
}
else
{
auto shadowFontDefinition = _fontDefinition;
FontDefinition shadowFontDefinition = fontDef;
shadowFontDefinition._fontFillColor.r = _shadowColor3B.r;
shadowFontDefinition._fontFillColor.g = _shadowColor3B.g;
shadowFontDefinition._fontFillColor.b = _shadowColor3B.b;
@ -1107,20 +1072,35 @@ void Label::setCameraMask(unsigned short mask, bool applyChildren)
void Label::setFontDefinition(const FontDefinition& textDefinition)
{
_fontDefinition = textDefinition;
_systemFont = textDefinition._fontName;
_systemFontSize = textDefinition._fontSize;
_hAlignment = textDefinition._alignment;
_vAlignment = textDefinition._vertAlignment;
setDimensions(textDefinition._dimensions.width, textDefinition._dimensions.height);
Color4B textColor = Color4B(textDefinition._fontFillColor);
textColor.a = textDefinition._fontAlpha;
setTextColor(textColor);
#if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) && (CC_TARGET_PLATFORM != CC_PLATFORM_IOS)
if (_fontDefinition._stroke._strokeEnabled)
if (textDefinition._stroke._strokeEnabled)
{
CCLOGERROR("Currently only supported on iOS and Android!");
}
_fontDefinition._stroke._strokeEnabled = false;
#endif
if (_fontDefinition._shadow._shadowEnabled)
_outlineSize = 0.f;
#else
if (textDefinition._stroke._strokeEnabled && textDefinition._stroke._strokeSize > 0.f)
{
_fontDefinition._shadow._shadowEnabled = false;
enableShadow(Color4B(0,0,0,255 * _fontDefinition._shadow._shadowOpacity),_fontDefinition._shadow._shadowOffset,_fontDefinition._shadow._shadowBlur);
Color4B outlineColor = Color4B(textDefinition._stroke._strokeColor);
outlineColor.a = textDefinition._stroke._strokeAlpha;
enableOutline(outlineColor, textDefinition._stroke._strokeSize);
}
#endif
if (textDefinition._shadow._shadowEnabled)
{
enableShadow(Color4B(0, 0, 0, 255 * textDefinition._shadow._shadowOpacity),
textDefinition._shadow._shadowOffset, textDefinition._shadow._shadowBlur);
}
_compatibleMode = true;
}
void Label::updateContent()
@ -1155,10 +1135,11 @@ void Label::updateContent()
}
else
{
createSpriteForSystemFont();
auto fontDef = _getFontDefinition();
createSpriteForSystemFont(fontDef);
if (_shadowEnabled)
{
createShadowSpriteForSystemFont();
createShadowSpriteForSystemFont(fontDef);
}
}
_contentDirty = false;
@ -1177,11 +1158,11 @@ void Label::onDrawShadow(GLProgram* glProgram)
}
glProgram->setUniformsForBuiltins(_shadowTransform);
for (auto it : _letters)
for (auto&& it : _letters)
{
it.second->updateTransform();
}
for (const auto& batchNode : _batchNodes)
for (auto&& batchNode : _batchNodes)
{
batchNode->getTextureAtlas()->drawQuads();
}
@ -1194,11 +1175,11 @@ void Label::onDrawShadow(GLProgram* glProgram)
setColor(_shadowColor3B);
glProgram->setUniformsForBuiltins(_shadowTransform);
for (auto it : _letters)
for (auto&& it : _letters)
{
it.second->updateTransform();
}
for (const auto& batchNode : _batchNodes)
for (auto&& batchNode : _batchNodes)
{
batchNode->getTextureAtlas()->drawQuads();
}
@ -1220,7 +1201,7 @@ void Label::onDraw(const Mat4& transform, bool transformUpdated)
}
glprogram->setUniformsForBuiltins(transform);
for (auto it : _letters)
for (auto&& it : _letters)
{
it.second->updateTransform();
}
@ -1234,7 +1215,7 @@ void Label::onDraw(const Mat4& transform, bool transformUpdated)
_textColorF.r, _textColorF.g, _textColorF.b, _textColorF.a);
glprogram->setUniformLocationWith4f(_uniformEffectColor,
_effectColorF.r, _effectColorF.g, _effectColorF.b, _effectColorF.a);
for (const auto& batchNode : _batchNodes)
for (auto&& batchNode : _batchNodes)
{
batchNode->getTextureAtlas()->drawQuads();
}
@ -1255,7 +1236,7 @@ void Label::onDraw(const Mat4& transform, bool transformUpdated)
}
}
for (const auto& batchNode : _batchNodes)
for (auto&& batchNode : _batchNodes)
{
batchNode->getTextureAtlas()->drawQuads();
}
@ -1296,8 +1277,7 @@ void Label::visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t pare
uint32_t flags = processParentFlags(parentTransform, parentFlags);
if (!_originalUTF8String.empty() && _shadowEnabled && _shadowBlurRadius <= 0
&& (_shadowDirty || (flags & FLAGS_DIRTY_MASK)))
if (!_originalUTF8String.empty() && _shadowEnabled && (_shadowDirty || (flags & FLAGS_DIRTY_MASK)))
{
_position.x += _shadowOffset.width;
_position.y += _shadowOffset.height;
@ -1339,9 +1319,8 @@ void Label::visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t pare
else
break;
}
// self draw
if (visibleByCamera)
this->drawSelf(renderer, flags);
this->drawSelf(visibleByCamera, renderer, flags);
for (auto it = _children.cbegin() + i; it != _children.cend(); ++it)
{
@ -1349,15 +1328,15 @@ void Label::visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t pare
}
}
else if (visibleByCamera)
else
{
this->drawSelf(renderer, flags);
this->drawSelf(visibleByCamera, renderer, flags);
}
_director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
}
void Label::drawSelf(Renderer* renderer, uint32_t flags)
void Label::drawSelf(bool visibleByCamera, Renderer* renderer, uint32_t flags)
{
if (_textSprite)
{
@ -1367,7 +1346,7 @@ void Label::drawSelf(Renderer* renderer, uint32_t flags)
}
_textSprite->visit(renderer, _modelViewTransform, flags);
}
else
else if (visibleByCamera)
{
draw(renderer, _modelViewTransform, flags);
}
@ -1525,11 +1504,6 @@ int Label::getStringLength() const
}
// RGBA protocol
bool Label::isOpacityModifyRGB() const
{
return _isOpacityModifyRGB;
}
void Label::setOpacityModifyRGB(bool isOpacityModifyRGB)
{
if (isOpacityModifyRGB != _isOpacityModifyRGB)
@ -1551,6 +1525,11 @@ void Label::updateDisplayedColor(const Color3B& parentColor)
_shadowNode->updateDisplayedColor(_displayedColor);
}
}
for (auto&& it : _letters)
{
it.second->updateDisplayedColor(_displayedColor);;
}
}
void Label::updateDisplayedOpacity(GLubyte parentOpacity)
@ -1565,26 +1544,27 @@ void Label::updateDisplayedOpacity(GLubyte parentOpacity)
_shadowNode->updateDisplayedOpacity(_displayedOpacity);
}
}
for (auto&& it : _letters)
{
it.second->updateDisplayedOpacity(_displayedOpacity);;
}
}
void Label::setTextColor(const Color4B &color)
{
CCASSERT(_currentLabelType == LabelType::TTF || _currentLabelType == LabelType::STRING_TEXTURE, "Only supported system font and ttf!");
if (_currentLabelType == LabelType::STRING_TEXTURE && _textColor != color)
{
_contentDirty = true;
}
_textColor = color;
_textColorF.r = _textColor.r / 255.0f;
_textColorF.g = _textColor.g / 255.0f;
_textColorF.b = _textColor.b / 255.0f;
_textColorF.a = _textColor.a / 255.0f;
if (_currentLabelType == LabelType::STRING_TEXTURE)
{
if (_fontDefinition._fontFillColor.r != _textColor.r || _fontDefinition._fontFillColor.g != _textColor.g
|| _fontDefinition._fontFillColor.b != _textColor.b || _fontDefinition._fontAlpha != _textColor.a)
{
_contentDirty = true;
}
}
}
void Label::updateColor()
@ -1606,7 +1586,7 @@ void Label::updateColor()
cocos2d::TextureAtlas* textureAtlas;
V3F_C4B_T2F_Quad *quads;
for (const auto& batchNode:_batchNodes)
for (auto&& batchNode:_batchNodes)
{
textureAtlas = batchNode->getTextureAtlas();
quads = textureAtlas->getQuads();
@ -1669,7 +1649,7 @@ void Label::removeAllChildrenWithCleanup(bool cleanup)
void Label::removeChild(Node* child, bool cleanup /* = true */)
{
Node::removeChild(child, cleanup);
for (auto it : _letters)
for (auto&& it : _letters)
{
if (it.second == child)
{
@ -1679,4 +1659,44 @@ void Label::removeChild(Node* child, bool cleanup /* = true */)
}
}
FontDefinition Label::_getFontDefinition() const
{
FontDefinition systemFontDef;
systemFontDef._fontName = _systemFont;
systemFontDef._fontSize = _systemFontSize;
systemFontDef._alignment = _hAlignment;
systemFontDef._vertAlignment = _vAlignment;
systemFontDef._dimensions.width = _labelWidth;
systemFontDef._dimensions.height = _labelHeight;
systemFontDef._fontFillColor.r = _textColor.r;
systemFontDef._fontFillColor.g = _textColor.g;
systemFontDef._fontFillColor.b = _textColor.b;
systemFontDef._fontAlpha = _textColor.a;
systemFontDef._shadow._shadowEnabled = false;
if (_currLabelEffect == LabelEffect::OUTLINE && _outlineSize > 0.f)
{
systemFontDef._stroke._strokeEnabled = true;
systemFontDef._stroke._strokeSize = _outlineSize;
systemFontDef._stroke._strokeColor.r = _effectColorF.r * 255;
systemFontDef._stroke._strokeColor.g = _effectColorF.g * 255;
systemFontDef._stroke._strokeColor.b = _effectColorF.b * 255;
systemFontDef._stroke._strokeAlpha = _effectColorF.a * 255;
}
else
{
systemFontDef._stroke._strokeEnabled = false;
}
#if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) && (CC_TARGET_PLATFORM != CC_PLATFORM_IOS)
if (systemFontDef._stroke._strokeEnabled)
{
CCLOGERROR("Currently only supported on iOS and Android!");
}
systemFontDef._stroke._strokeEnabled = false;
#endif
return systemFontDef;
}
NS_CC_END

View File

@ -162,7 +162,8 @@ public:
* @return An automatically released Label object.
* @see TTFConfig setTTFConfig setMaxLineWidth
*/
static Label* createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment hAlignment = TextHAlignment::LEFT, int maxLineWidth = 0);
static Label* createWithTTF(const TTFConfig& ttfConfig, const std::string& text,
TextHAlignment hAlignment = TextHAlignment::LEFT, int maxLineWidth = 0);
/**
* Allocates and initializes a Label, with a bitmap font file.
@ -441,7 +442,7 @@ public:
virtual const BlendFunc& getBlendFunc() const override { return _blendFunc; }
virtual void setBlendFunc(const BlendFunc &blendFunc) override;
virtual bool isOpacityModifyRGB() const override;
virtual bool isOpacityModifyRGB() const override { return _isOpacityModifyRGB; }
virtual void setOpacityModifyRGB(bool isOpacityModifyRGB) override;
virtual void updateDisplayedColor(const Color3B& parentColor) override;
virtual void updateDisplayedOpacity(GLubyte parentOpacity) override;
@ -455,7 +456,6 @@ public:
virtual std::string getDescription() const override;
virtual const Size& getContentSize() const override;
virtual Rect getBoundingBox() const override;
virtual void visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags) override;
@ -469,13 +469,8 @@ public:
CC_DEPRECATED_ATTRIBUTE static Label* create(const std::string& text, const std::string& font, float fontSize,
const Size& dimensions = Size::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT,
TextVAlignment vAlignment = TextVAlignment::TOP);
CC_DEPRECATED_ATTRIBUTE virtual void setFontDefinition(const FontDefinition& textDefinition);
CC_DEPRECATED_ATTRIBUTE const FontDefinition& getFontDefinition() const { return _fontDefinition; }
/**
* @deprecated Use `getLineHeight` instead.
*/
CC_DEPRECATED_ATTRIBUTE FontDefinition getFontDefinition() const { return _getFontDefinition(); }
CC_DEPRECATED_ATTRIBUTE int getCommonLineHeight() const { return (int)getLineHeight();}
CC_CONSTRUCTOR_ACCESS:
@ -483,8 +478,8 @@ CC_CONSTRUCTOR_ACCESS:
* Constructor of Label.
* @js NA
*/
Label(FontAtlas *atlas = nullptr, TextHAlignment hAlignment = TextHAlignment::LEFT,
TextVAlignment vAlignment = TextVAlignment::TOP,bool useDistanceField = false,bool useA8Shader = false);
Label(TextHAlignment hAlignment = TextHAlignment::LEFT,
TextVAlignment vAlignment = TextVAlignment::TOP);
/**
* Destructor of Label.
@ -494,85 +489,79 @@ CC_CONSTRUCTOR_ACCESS:
virtual ~Label();
protected:
void onDraw(const Mat4& transform, bool transformUpdated);
void onDrawShadow(GLProgram* glProgram);
struct LetterInfo
{
FontLetterDefinition def;
Vec2 position;
Size contentSize;
int atlasIndex;
};
enum class LabelType {
enum class LabelType {
TTF,
BMFONT,
CHARMAP,
STRING_TEXTURE
};
virtual void setFontAtlas(FontAtlas* atlas,bool distanceFieldEnabled = false, bool useA8Shader = false);
virtual void setFontAtlas(FontAtlas* atlas, bool distanceFieldEnabled = false, bool useA8Shader = false);
bool recordLetterInfo(const cocos2d::Vec2& point,const FontLetterDefinition& letterDef, int spriteIndex);
bool recordPlaceholderInfo(int spriteIndex);
void setFontScale(float fontScale);
virtual void alignText();
bool computeHorizontalKernings(const std::u16string& stringToRender);
void setCorrectionScale(float fontScale);
void computeStringNumLines();
void onDraw(const Mat4& transform, bool transformUpdated);
void onDrawShadow(GLProgram* glProgram);
void drawSelf(bool visibleByCamera, Renderer* renderer, uint32_t flags);
virtual void alignText();
bool computeHorizontalKernings(const std::u16string& stringToRender);
bool recordLetterInfo(const cocos2d::Vec2& point,const FontLetterDefinition& letterDef, int spriteIndex);
bool recordPlaceholderInfo(int spriteIndex);
void updateQuads();
virtual void updateColor() override;
void createSpriteForSystemFont(const FontDefinition& fontDef);
void createShadowSpriteForSystemFont(const FontDefinition& fontDef);
virtual void updateShaderProgram();
void createSpriteForSystemFont();
void createShadowSpriteForSystemFont();
void reset();
void drawSelf(Renderer* renderer, uint32_t flags);
FontDefinition _getFontDefinition() const;
virtual void updateColor() override;
LabelType _currentLabelType;
bool _contentDirty;
std::u16string _currentUTF16String;
std::string _originalUTF8String;
int _currNumLines;
std::string _bmFontPath;
bool _isOpacityModifyRGB;
bool _contentDirty;
TTFConfig _fontConfig;
float _outlineSize;
bool _systemFontDirty;
std::string _systemFont;
float _systemFontSize;
LabelType _currentLabelType;
Vector<SpriteBatchNode*> _batchNodes;
FontAtlas * _fontAtlas;
std::vector<LetterInfo> _lettersInfo;
EventListenerCustom* _purgeTextureListener;
EventListenerCustom* _resetTextureListener;
TTFConfig _fontConfig;
//compatibility with older LabelTTF
Sprite* _textSprite;
FontDefinition _fontDefinition;
bool _compatibleMode;
Sprite* _shadowNode;
FontAtlas* _fontAtlas;
Vector<SpriteBatchNode*> _batchNodes;
std::vector<LetterInfo> _lettersInfo;
//! used for optimization
Sprite *_reusedLetter;
Rect _reusedRect;
int _limitShowCount;
float _additionalKerning;
//layout relevant properties.
float _commonLineHeight;
float _additionalKerning;
int* _horizontalKernings;
bool _lineBreakWithoutSpaces;
int * _horizontalKernings;
float _maxLineWidth;
Size _labelDimensions;
float _labelWidth;
@ -580,46 +569,44 @@ protected:
TextHAlignment _hAlignment;
TextVAlignment _vAlignment;
int _currNumLines;
std::u16string _currentUTF16String;
std::string _originalUTF8String;
float _fontScale;
bool _useDistanceField;
bool _useA8Shader;
//the correction scale for distance field.
float _correctionScale;
LabelEffect _currLabelEffect;
Color4B _effectColor;
Color4F _effectColorF;
Color4B _textColor;
Color4F _textColorF;
CustomCommand _customCommand;
Mat4 _shadowTransform;
GLuint _uniformEffectColor;
GLuint _uniformTextColor;
CustomCommand _customCommand;
bool _useDistanceField;
bool _useA8Shader;
bool _shadowDirty;
bool _shadowEnabled;
Size _shadowOffset;
int _shadowBlurRadius;
Mat4 _shadowTransform;
Color4F _shadowColor4F;
Color3B _shadowColor3B;
GLubyte _shadowOpacity;
Sprite* _shadowNode;
int _outlineSize;
Color4B _textColor;
Color4F _textColorF;
float _shadowBlurRadius;
bool _clipEnabled;
bool _blendFuncDirty;
BlendFunc _blendFunc;
/// whether or not the sprite was inside bounds the previous frame
/// whether or not the label was inside bounds the previous frame
bool _insideBounds;
bool _isOpacityModifyRGB;
std::unordered_map<int, Sprite*> _letters;
EventListenerCustom* _purgeTextureListener;
EventListenerCustom* _resetTextureListener;
private:
CC_DISALLOW_COPY_AND_ASSIGN(Label);

View File

@ -223,9 +223,11 @@ void LabelTTF::setTextDefinition(const FontDefinition& theDefinition)
_contentDirty = true;
}
const FontDefinition& LabelTTF::getTextDefinition() const
const FontDefinition& LabelTTF::getTextDefinition()
{
return _renderLabel->getFontDefinition();
auto fontDef = _renderLabel->getFontDefinition();
memcpy(&_fontDef, &fontDef, sizeof(FontDefinition));
return _fontDef;
}
void LabelTTF::setBlendFunc(const BlendFunc &blendFunc)

View File

@ -100,7 +100,7 @@ public:
void setTextDefinition(const FontDefinition& theDefinition);
/** get the text definition used by this label */
const FontDefinition& getTextDefinition() const;
const FontDefinition& getTextDefinition();
@ -163,6 +163,7 @@ public:
protected:
Label* _renderLabel;
bool _contentDirty;
FontDefinition _fontDef;
};

View File

@ -316,7 +316,7 @@ bool LabelTextFormatter::createStringSprites(Label *theLabel)
auto labelHeightPixel = theLabel->_labelHeight * contentScaleFactor;
if (totalHeight > labelHeightPixel)
{
int numLines = MIN(ceil(labelHeightPixel / theLabel->_commonLineHeight), theLabel->_currNumLines);
int numLines = labelHeightPixel / theLabel->_commonLineHeight;
totalHeight = numLines * theLabel->_commonLineHeight;
}
switch (theLabel->_vAlignment)
@ -379,7 +379,7 @@ bool LabelTextFormatter::createStringSprites(Label *theLabel)
nextFontPositionY -= theLabel->_commonLineHeight;
theLabel->recordPlaceholderInfo(i);
if(nextFontPositionY < 0.f)
if (nextFontPositionY < theLabel->_commonLineHeight)
break;
lineStart = true;

View File

@ -600,17 +600,9 @@ void LayerColor::onDraw(const Mat4& transform, uint32_t flags)
//
// Attributes
//
#ifdef EMSCRIPTEN
setGLBufferData(_noMVPVertices, 4 * sizeof(Vec3), 0);
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, 0, 0);
setGLBufferData(_squareColors, 4 * sizeof(Color4F), 1);
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_FLOAT, GL_FALSE, 0, 0);
#else
glBindBuffer(GL_ARRAY_BUFFER, 0);
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, 0, _noMVPVertices);
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_FLOAT, GL_FALSE, 0, _squareColors);
#endif // EMSCRIPTEN
GL::blendFunc( _blendFunc.src, _blendFunc.dst );

View File

@ -376,11 +376,11 @@ void Menu::alignItemsInColumnsWithArray(const ValueVector& rows)
int rowColumns = 0;
for(const auto &child : _children) {
CCASSERT(row < rows.size(), "");
CCASSERT(row < rows.size(), "row should less than rows.size()!");
rowColumns = rows[row].asInt();
// can not have zero columns on a row
CCASSERT(rowColumns, "");
CCASSERT(rowColumns, "rowColumns can't be 0.");
float tmp = child->getContentSize().height;
rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp);
@ -397,7 +397,7 @@ void Menu::alignItemsInColumnsWithArray(const ValueVector& rows)
}
// check if too many rows/columns for available menu items
CCASSERT(! columnsOccupied, "");
CCASSERT(! columnsOccupied, "columnsOccupied should be 0.");
Size winSize = Director::getInstance()->getWinSize();
@ -472,11 +472,11 @@ void Menu::alignItemsInRowsWithArray(const ValueVector& columns)
for(const auto &child : _children) {
// check if too many menu items for the amount of rows/columns
CCASSERT(column < columns.size(), "");
CCASSERT(column < columns.size(), "column should be less than columns.size().");
columnRows = columns[column].asInt();
// can't have zero rows on a column
CCASSERT(columnRows, "");
CCASSERT(columnRows, "columnRows can't be 0.");
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = child->getContentSize().width;
@ -499,7 +499,7 @@ void Menu::alignItemsInRowsWithArray(const ValueVector& columns)
}
// check if too many rows/columns for available menu items.
CCASSERT(! rowsOccupied, "");
CCASSERT(! rowsOccupied, "rowsOccupied should be 0.");
Size winSize = Director::getInstance()->getWinSize();

View File

@ -386,21 +386,9 @@ void MotionStreak::onDraw(const Mat4 &transform, uint32_t flags)
GL::bindTexture2D( _texture->getName() );
#ifdef EMSCRIPTEN
// Size calculations from ::initWithFade
setGLBufferData(_vertices, (sizeof(Vec2) * _maxPoints * 2), 0);
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
setGLBufferData(_texCoords, (sizeof(Tex2F) * _maxPoints * 2), 1);
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORD, 2, GL_FLOAT, GL_FALSE, 0, 0);
setGLBufferData(_colorPointer, (sizeof(GLubyte) * _maxPoints * 2 * 4), 2);
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0);
#else
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, _vertices);
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORD, 2, GL_FLOAT, GL_FALSE, 0, _texCoords);
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, _colorPointer);
#endif // EMSCRIPTEN
glDrawArrays(GL_TRIANGLE_STRIP, 0, (GLsizei)_nuPoints*2);
CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1, _nuPoints*2);

View File

@ -221,20 +221,22 @@ bool Node::init()
void Node::cleanup()
{
#if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeJavascript)
{
if (ScriptEngineManager::sendNodeEventToJS(this, kNodeOnCleanup))
return;
}
else if (_scriptType == kScriptTypeLua)
{
ScriptEngineManager::sendNodeEventToLua(this, kNodeOnCleanup);
}
#endif // #if CC_ENABLE_SCRIPT_BINDING
// actions
this->stopAllActions();
this->unscheduleAllCallbacks();
#if CC_ENABLE_SCRIPT_BINDING
if ( _scriptType != kScriptTypeNone)
{
int action = kNodeOnCleanup;
BasicScriptData data(this,(void*)&action);
ScriptEvent scriptEvent(kNodeEvent,(void*)&data);
ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent);
}
#endif // #if CC_ENABLE_SCRIPT_BINDING
// timers
for( const auto &child: _children)
child->cleanup();
@ -1576,6 +1578,14 @@ void Node::stopAllActionsByTag(int tag)
_actionManager->removeAllActionsByTag(tag, this);
}
void Node::stopActionsByFlags(unsigned int flags)
{
if (flags > 0)
{
_actionManager->removeActionsByFlags(flags, this);
}
}
Action * Node::getActionByTag(int tag)
{
CCASSERT( tag != Action::INVALID_TAG, "Invalid tag");

View File

@ -1228,6 +1228,13 @@ public:
*/
void stopAllActionsByTag(int tag);
/**
* Removes all actions from the running action list by its flags.
*
* @param flags A flag field that removes actions based on bitwise AND.
*/
void stopActionsByFlags(unsigned int flags);
/**
* Gets an action from the running action list by its tag.
*

View File

@ -384,7 +384,7 @@ bool ParticleSystem::initWithDictionary(ValueMap& dictionary, const std::string&
else if( dictionary.find("textureImageData") != dictionary.end() )
{
std::string textureData = dictionary.at("textureImageData").asString();
CCASSERT(!textureData.empty(), "");
CCASSERT(!textureData.empty(), "textureData can't be empty!");
auto dataLen = textureData.size();
if (dataLen != 0)

View File

@ -63,6 +63,14 @@ ProtectedNode * ProtectedNode::create(void)
void ProtectedNode::cleanup()
{
#if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeJavascript)
{
if (ScriptEngineManager::sendNodeEventToJS(this, kNodeOnCleanup))
return;
}
#endif // #if CC_ENABLE_SCRIPT_BINDING
Node::cleanup();
// timers
for( const auto &child: _protectedChildren)

View File

@ -35,6 +35,7 @@ THE SOFTWARE.
#include "base/CCEventDispatcher.h"
#include "renderer/CCRenderer.h"
#include "2d/CCCamera.h"
#include "renderer/CCTextureCache.h"
NS_CC_BEGIN
@ -87,7 +88,6 @@ void RenderTexture::listenToBackground(EventCustom *event)
{
// We have not found a way to dispatch the enter background message before the texture data are destroyed.
// So we disable this pair of message handler at present.
#if 0
#if CC_ENABLE_CACHE_TEXTURE_DATA
CC_SAFE_DELETE(_UITextureImage);
@ -112,12 +112,10 @@ void RenderTexture::listenToBackground(EventCustom *event)
glDeleteFramebuffers(1, &_FBO);
_FBO = 0;
#endif
#endif
}
void RenderTexture::listenToForeground(EventCustom *event)
{
#if 0
#if CC_ENABLE_CACHE_TEXTURE_DATA
// -- regenerate frame buffer object and attach the texture
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_oldFBO);
@ -135,7 +133,6 @@ void RenderTexture::listenToForeground(EventCustom *event)
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _texture->getName(), 0);
glBindFramebuffer(GL_FRAMEBUFFER, _oldFBO);
#endif
#endif
}
RenderTexture * RenderTexture::create(int w, int h, Texture2D::PixelFormat eFormat)

View File

@ -205,7 +205,7 @@ bool Sprite::initWithSpriteFrameName(const std::string& spriteFrameName)
bool Sprite::initWithSpriteFrame(SpriteFrame *spriteFrame)
{
CCASSERT(spriteFrame != nullptr, "");
CCASSERT(spriteFrame != nullptr, "spriteFrame can't be nullptr!");
bool bRet = initWithTexture(spriteFrame->getTexture(), spriteFrame->getRect());
setSpriteFrame(spriteFrame);
@ -265,7 +265,6 @@ bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect, bool rotated)
setTexture(texture);
setTextureRect(rect, rotated, rect.size);
_polyInfo.setQuad(&_quad);
// by default use "Self Render".
// if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render"
setBatchNode(nullptr);
@ -288,7 +287,7 @@ Sprite::Sprite(void)
, _insideBounds(true)
{
#if CC_SPRITE_DEBUG_DRAW
debugDraw(true)
debugDraw(true);
#endif //CC_SPRITE_DEBUG_DRAW
}
@ -424,6 +423,8 @@ void Sprite::setTextureRect(const Rect& rect, bool rotated, const Size& untrimme
_quad.tl.vertices.set(x1, y2, 0.0f);
_quad.tr.vertices.set(x2, y2, 0.0f);
}
_polyInfo.setQuad(&_quad);
}
void Sprite::debugDraw(bool on)
@ -673,7 +674,7 @@ void Sprite::addChild(Node *child, int zOrder, int tag)
{
Sprite* childSprite = dynamic_cast<Sprite*>(child);
CCASSERT( childSprite, "CCSprite only supports Sprites as children when using SpriteBatchNode");
CCASSERT(childSprite->getTexture()->getName() == _textureAtlas->getTexture()->getName(), "");
CCASSERT(childSprite->getTexture()->getName() == _textureAtlas->getTexture()->getName(), "childSprite's texture name should be equal to _textureAtlas's texture name!");
//put it in descendants array of batch node
_batchNode->appendChild(childSprite);
@ -694,7 +695,8 @@ void Sprite::addChild(Node *child, int zOrder, const std::string &name)
{
Sprite* childSprite = dynamic_cast<Sprite*>(child);
CCASSERT( childSprite, "CCSprite only supports Sprites as children when using SpriteBatchNode");
CCASSERT(childSprite->getTexture()->getName() == _textureAtlas->getTexture()->getName(), "");
CCASSERT(childSprite->getTexture()->getName() == _textureAtlas->getTexture()->getName(),
"childSprite's texture name should be equal to _textureAtlas's texture name.");
//put it in descendants array of batch node
_batchNode->appendChild(childSprite);
@ -942,10 +944,9 @@ void Sprite::updateColor(void)
color4.b *= _displayedOpacity/255.0f;
}
_quad.bl.colors = color4;
_quad.br.colors = color4;
_quad.tl.colors = color4;
_quad.tr.colors = color4;
for (ssize_t i = 0; i < _polyInfo.triangles.vertCount; i++) {
_polyInfo.triangles.verts[i].colors = color4;
}
// renders using batch node
if (_batchNode)

View File

@ -88,8 +88,13 @@ Rect TMXTilesetInfo::getRectForGID(uint32_t gid)
rect.size = _tileSize;
gid &= kTMXFlippedMask;
gid = gid - _firstGid;
int max_x = (int)((_imageSize.width - _margin*2 + _spacing) / (_tileSize.width + _spacing));
// int max_y = (imageSize.height - margin*2 + spacing) / (tileSize.height + spacing);
// max_x means the colum count in tile map
// in the origin:
// max_x = (int)((_imageSize.width - _margin*2 + _spacing) / (_tileSize.width + _spacing));
// but in editor "Tield", _margin variable only effect the left side
// for compatible with "Tield", change the max_x calculation
int max_x = (int)((_imageSize.width - _margin + _spacing) / (_tileSize.width + _spacing));
rect.origin.x = (gid % max_x) * (_tileSize.width + _spacing) + _margin;
rect.origin.y = (gid / max_x) * (_tileSize.height + _spacing) + _margin;
return rect;
@ -454,7 +459,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
// Y
int y = attributeDict["y"].asInt();
Vec2 p(x + objectGroup->getPositionOffset().x, _mapSize.height * _tileSize.height - y - objectGroup->getPositionOffset().x - attributeDict["height"].asInt());
Vec2 p(x + objectGroup->getPositionOffset().x, _mapSize.height * _tileSize.height - y - objectGroup->getPositionOffset().y - attributeDict["height"].asInt());
p = CC_POINT_PIXELS_TO_POINTS(p);
dict["x"] = Value(p.x);
dict["y"] = Value(p.y);
@ -643,7 +648,7 @@ void TMXMapInfo::endElement(void *ctx, const char *name)
ssize_t sizeHint = s.width * s.height * sizeof(unsigned int);
ssize_t CC_UNUSED inflatedLen = ZipUtils::inflateMemoryWithHint(buffer, len, &deflated, sizeHint);
CCASSERT(inflatedLen == sizeHint, "");
CCASSERT(inflatedLen == sizeHint, "inflatedLen should be equal to sizeHint!");
free(buffer);
buffer = nullptr;

View File

@ -191,6 +191,14 @@ void TransitionScene::onExit()
// custom cleanup
void TransitionScene::cleanup()
{
#if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeJavascript)
{
if (ScriptEngineManager::sendNodeEventToJS(this, kNodeOnCleanup))
return;
}
#endif // #if CC_ENABLE_SCRIPT_BINDING
Scene::cleanup();
if( _isSendCleanupToScene )

View File

@ -7,7 +7,7 @@
</PropertyGroup>
<ItemDefinitionGroup>
<Link>
<AdditionalDependencies>opengl32.lib;glew32.lib;libzlib.lib;libwebp.lib;libiconv.lib;freetype250.lib;winmm.lib;ws2_32.lib;libbox2d.lib;libSpine.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalDependencies>opengl32.lib;glew32.lib;libzlib.lib;libwebp.lib;libiconv.lib;freetype.lib;winmm.lib;ws2_32.lib;libbox2d.lib;libSpine.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>$(OutDir);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
</Link>

View File

@ -76,7 +76,7 @@
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(EngineRoot)external\box2d;$(EngineRoot)external\sqlite3\include;$(EngineRoot)external\unzip;$(EngineRoot)external\edtaa3func;$(EngineRoot)external\tinyxml2;$(EngineRoot)external\png\include\win32;$(EngineRoot)external\jpeg\include\win32;$(EngineRoot)external\tiff\include\win32;$(EngineRoot)external\webp\include\win32;$(EngineRoot)external\freetype2\include\win32;$(EngineRoot)external\win32-specific\OpenalSoft\include;$(EngineRoot)external\win32-specific\MP3Decoder\include;$(EngineRoot)external\win32-specific\OggDecoder\include;$(EngineRoot)external\win32-specific\icon\include;$(EngineRoot)external\win32-specific\zlib\include;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)external\xxhash;$(EngineRoot)external\ConvertUTF;$(EngineRoot)external\curl\include\win32;$(EngineRoot)external\websockets\include\win32;$(EngineRoot)external\poly2tri\common;$(EngineRoot)external\poly2tri\sweep;$(EngineRoot)external\poly2tri;$(EngineRoot)external;$(EngineRoot)cocos;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\audio\include;$(EngineRoot)extensions;$(EngineRoot);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_USRDLL;_DEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_ENABLE_BULLET_INTEGRATION=1;PROTOBUF_USE_DLLS;LIBPROTOBUF_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>WIN32;_USRDLL;_DEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;PROTOBUF_USE_DLLS;LIBPROTOBUF_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
@ -131,7 +131,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\chipmunk\prebuilt\win32\debug-lib\*.*"
</PreBuildEvent>
<ClCompile>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(EngineRoot)external\sqlite3\include;$(EngineRoot)external\unzip;$(EngineRoot)external\edtaa3func;$(EngineRoot)external\tinyxml2;$(EngineRoot)external\png\include\win32;$(EngineRoot)external\jpeg\include\win32;$(EngineRoot)external\tiff\include\win32;$(EngineRoot)external\webp\include\win32;$(EngineRoot)external\freetype2\include\win32;$(EngineRoot)external\win32-specific\MP3Decoder\include;$(EngineRoot)external\win32-specific\OggDecoder\include;$(EngineRoot)external\win32-specific\OpenalSoft\include;$(EngineRoot)external\win32-specific\icon\include;$(EngineRoot)external\win32-specific\zlib\include;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)external\xxhash;$(EngineRoot)external\ConvertUTF;$(EngineRoot)external\Box2d;$(EngineRoot)external\curl\include\win32;$(EngineRoot)external\websockets\include\win32\;$(EngineRoot)external\poly2tri\common;$(EngineRoot)external\poly2tri\sweep;$(EngineRoot)external\poly2tri;$(EngineRoot)external;$(EngineRoot)cocos;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\audio\include;$(EngineRoot)extensions;$(EngineRoot);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_USRDLL;NDEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_ENABLE_BULLET_INTEGRATION=1;PROTOBUF_USE_DLLS;LIBPROTOBUF_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>WIN32;_USRDLL;NDEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;PROTOBUF_USE_DLLS;LIBPROTOBUF_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>

View File

@ -163,7 +163,7 @@
<AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles>
<AdditionalIncludeDirectories>$(EngineRoot)external\winrt_8.1-specific\OggDecoder\include;$(EngineRoot)external\winrt_8.1-specific\zlib\include;$(EngineRoot)external\freetype2\include\winrt_8.1\freetype2;$(EngineRoot)external\websockets\include\winrt_8.1;$(EngineRoot)external\curl\include\winrt_8.1;$(EngineRoot)external\tiff\include\winrt_8.1;$(EngineRoot)external\jpeg\include\winrt_8.1;$(EngineRoot)external\png\include\winrt_8.1;$(EngineRoot)external\protobuf-lite\src;$(EngineRoot)external\protobuf-lite\win32;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_ENABLE_BULLET_INTEGRATION=1;_DEBUG;COCOS2D_DEBUG=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_DEBUG;COCOS2D_DEBUG=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings>
</ClCompile>
@ -184,7 +184,7 @@
<AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles>
<AdditionalIncludeDirectories>$(EngineRoot)external\winrt_8.1-specific\OggDecoder\include;$(EngineRoot)external\winrt_8.1-specific\OggDecoder\include;$(EngineRoot)external\winrt_8.1-specific\zlib\include;$(EngineRoot)external\freetype2\include\winrt_8.1\freetype2;$(EngineRoot)external\websockets\include\winrt_8.1;$(EngineRoot)external\curl\include\winrt_8.1;$(EngineRoot)external\tiff\include\winrt_8.1;$(EngineRoot)external\jpeg\include\winrt_8.1;$(EngineRoot)external\png\include\winrt_8.1;$(EngineRoot)external\protobuf-lite\src;$(EngineRoot)external\protobuf-lite\win32;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_ENABLE_BULLET_INTEGRATION=1;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings>
</ClCompile>
@ -204,7 +204,7 @@
<AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles>
<AdditionalIncludeDirectories>$(EngineRoot)external\winrt_8.1-specific\OggDecoder\include;$(EngineRoot)external\winrt_8.1-specific\OggDecoder\include;$(EngineRoot)external\winrt_8.1-specific\zlib\include;$(EngineRoot)external\freetype2\include\winrt_8.1\freetype2;$(EngineRoot)external\websockets\include\winrt_8.1;$(EngineRoot)external\curl\include\winrt_8.1;$(EngineRoot)external\tiff\include\winrt_8.1;$(EngineRoot)external\jpeg\include\winrt_8.1;$(EngineRoot)external\png\include\winrt_8.1;$(EngineRoot)external\protobuf-lite\src;$(EngineRoot)external\protobuf-lite\win32;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_ENABLE_BULLET_INTEGRATION=1;_DEBUG;COCOS2D_DEBUG=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_DEBUG;COCOS2D_DEBUG=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings>
</ClCompile>
@ -225,7 +225,7 @@
<AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles>
<AdditionalIncludeDirectories>$(EngineRoot)external\winrt_8.1-specific\OggDecoder\include;$(EngineRoot)external\winrt_8.1-specific\OggDecoder\include;$(EngineRoot)external\winrt_8.1-specific\zlib\include;$(EngineRoot)external\freetype2\include\winrt_8.1\freetype2;$(EngineRoot)external\websockets\include\winrt_8.1;$(EngineRoot)external\curl\include\winrt_8.1;$(EngineRoot)external\tiff\include\winrt_8.1;$(EngineRoot)external\jpeg\include\winrt_8.1;$(EngineRoot)external\png\include\winrt_8.1;$(EngineRoot)external\protobuf-lite\src;$(EngineRoot)external\protobuf-lite\win32;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_ENABLE_BULLET_INTEGRATION=1;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings>
</ClCompile>
@ -245,7 +245,7 @@
<AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles>
<AdditionalIncludeDirectories>$(EngineRoot)external\winrt_8.1-specific\zlib\include;$(EngineRoot)external\freetype2\include\winrt_8.1\freetype2;$(EngineRoot)external\websockets\include\winrt_8.1;$(EngineRoot)external\curl\include\winrt_8.1;$(EngineRoot)external\tiff\include\winrt_8.1;$(EngineRoot)external\jpeg\include\winrt_8.1;$(EngineRoot)external\png\include\winrt_8.1;$(EngineRoot)external\protobuf-lite\src;$(EngineRoot)external\protobuf-lite\win32;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_ENABLE_BULLET_INTEGRATION=1;_DEBUG;COCOS2D_DEBUG=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_DEBUG;COCOS2D_DEBUG=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings>
</ClCompile>
@ -266,7 +266,7 @@
<AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles>
<AdditionalIncludeDirectories>$(EngineRoot)external\winrt_8.1-specific\zlib\include;$(EngineRoot)external\freetype2\include\winrt_8.1\freetype2;$(EngineRoot)external\websockets\include\winrt_8.1;$(EngineRoot)external\curl\include\winrt_8.1;$(EngineRoot)external\tiff\include\winrt_8.1;$(EngineRoot)external\jpeg\include\winrt_8.1;$(EngineRoot)external\png\include\winrt_8.1;$(EngineRoot)external\protobuf-lite\src;$(EngineRoot)external\protobuf-lite\win32;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_ENABLE_BULLET_INTEGRATION=1;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings>
</ClCompile>

View File

@ -117,7 +117,7 @@
<AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles>
<AdditionalIncludeDirectories>$(EngineRoot)external\wp_8.1-specific\OggDecoder\include;$(EngineRoot)external\wp_8.1-specific\zlib\include;$(EngineRoot)external\freetype2\include\wp_8.1\freetype2;$(EngineRoot)external\websockets\include\wp_8.1;$(EngineRoot)external\curl\include\wp_8.1;$(EngineRoot)external\tiff\include\wp_8.1;$(EngineRoot)external\jpeg\include\wp_8.1;$(EngineRoot)external\png\include\wp_8.1;$(EngineRoot)external\protobuf-lite\src;$(EngineRoot)external\protobuf-lite\win32;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>CC_WINDOWS_PHONE_8_1;_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_ENABLE_BULLET_INTEGRATION=1;_DEBUG;COCOS2D_DEBUG=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>CC_WINDOWS_PHONE_8_1;_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_DEBUG;COCOS2D_DEBUG=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings>
</ClCompile>
@ -138,7 +138,7 @@
<AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles>
<AdditionalIncludeDirectories>$(EngineRoot)external\wp_8.1-specific\OggDecoder\include;$(EngineRoot)external\wp_8.1-specific\zlib\include;$(EngineRoot)external\freetype2\include\wp_8.1\freetype2;$(EngineRoot)external\websockets\include\wp_8.1;$(EngineRoot)external\curl\include\wp_8.1;$(EngineRoot)external\tiff\include\wp_8.1;$(EngineRoot)external\jpeg\include\wp_8.1;$(EngineRoot)external\png\include\wp_8.1;$(EngineRoot)external\protobuf-lite\src;$(EngineRoot)external\protobuf-lite\win32;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>CC_WINDOWS_PHONE_8_1;_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_ENABLE_BULLET_INTEGRATION=1;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>CC_WINDOWS_PHONE_8_1;_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings>
</ClCompile>
@ -158,7 +158,7 @@
<AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles>
<AdditionalIncludeDirectories>$(EngineRoot)external\wp_8.1-specific\OggDecoder\include;$(EngineRoot)external\wp_8.1-specific\zlib\include;$(EngineRoot)external\freetype2\include\wp_8.1\freetype2;$(EngineRoot)external\websockets\include\wp_8.1;$(EngineRoot)external\curl\include\wp_8.1;$(EngineRoot)external\tiff\include\wp_8.1;$(EngineRoot)external\jpeg\include\wp_8.1;$(EngineRoot)external\png\include\wp_8.1;$(EngineRoot)external\protobuf-lite\src;$(EngineRoot)external\protobuf-lite\win32;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>CC_WINDOWS_PHONE_8_1;_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_ENABLE_BULLET_INTEGRATION=1;_DEBUG;COCOS2D_DEBUG=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>CC_WINDOWS_PHONE_8_1;_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_DEBUG;COCOS2D_DEBUG=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings>
</ClCompile>
@ -179,7 +179,7 @@
<AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles>
<AdditionalIncludeDirectories>$(EngineRoot)external\wp_8.1-specific\OggDecoder\include;$(EngineRoot)external\wp_8.1-specific\zlib\include;$(EngineRoot)external\freetype2\include\wp_8.1\freetype2;$(EngineRoot)external\websockets\include\wp_8.1;$(EngineRoot)external\curl\include\wp_8.1;$(EngineRoot)external\tiff\include\wp_8.1;$(EngineRoot)external\jpeg\include\wp_8.1;$(EngineRoot)external\png\include\wp_8.1;$(EngineRoot)external\protobuf-lite\src;$(EngineRoot)external\protobuf-lite\win32;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>CC_WINDOWS_PHONE_8_1;_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_ENABLE_BULLET_INTEGRATION=1;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>CC_WINDOWS_PHONE_8_1;_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings>
</ClCompile>

View File

@ -1525,7 +1525,7 @@
<PrecompiledHeader>Use</PrecompiledHeader>
<CompileAsWinRT>true</CompileAsWinRT>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_ENABLE_BULLET_INTEGRATION=1;_DEBUG;COCOS2D_DEBUG=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_DEBUG;COCOS2D_DEBUG=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>4458;4459;%(DisableSpecificWarnings)</DisableSpecificWarnings>
<AdditionalIncludeDirectories>$(EngineRoot)external\win10-specific\zlib\include;$(EngineRoot)external\freetype2\include\win10\freetype2;$(EngineRoot)external\protobuf-lite\src;$(EngineRoot)external\protobuf-lite\win32;$(EngineRoot)external\win10-specific\OggDecoder\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
@ -1544,7 +1544,7 @@
<PrecompiledHeader>Use</PrecompiledHeader>
<CompileAsWinRT>true</CompileAsWinRT>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_ENABLE_BULLET_INTEGRATION=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>4458;4459;%(DisableSpecificWarnings)</DisableSpecificWarnings>
<AdditionalIncludeDirectories>$(EngineRoot)external\win10-specific\zlib\include;$(EngineRoot)external\freetype2\include\win10\freetype2;$(EngineRoot)external\protobuf-lite\src;$(EngineRoot)external\protobuf-lite\win32;$(EngineRoot)external\win10-specific\OggDecoder\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
@ -1563,7 +1563,7 @@
<PrecompiledHeader>Use</PrecompiledHeader>
<CompileAsWinRT>true</CompileAsWinRT>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_ENABLE_BULLET_INTEGRATION=1;_DEBUG;COCOS2D_DEBUG=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_DEBUG;COCOS2D_DEBUG=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>4458;4459;%(DisableSpecificWarnings)</DisableSpecificWarnings>
<AdditionalIncludeDirectories>$(EngineRoot)external\win10-specific\zlib\include;$(EngineRoot)external\freetype2\include\win10\freetype2;$(EngineRoot)external\protobuf-lite\src;$(EngineRoot)external\protobuf-lite\win32;$(EngineRoot)external\win10-specific\OggDecoder\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
@ -1582,7 +1582,7 @@
<PrecompiledHeader>Use</PrecompiledHeader>
<CompileAsWinRT>true</CompileAsWinRT>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_ENABLE_BULLET_INTEGRATION=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>4458;4459;%(DisableSpecificWarnings)</DisableSpecificWarnings>
<AdditionalIncludeDirectories>$(EngineRoot)external\win10-specific\zlib\include;$(EngineRoot)external\freetype2\include\win10\freetype2;$(EngineRoot)external\protobuf-lite\src;$(EngineRoot)external\protobuf-lite\win32;$(EngineRoot)external\win10-specific\OggDecoder\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
@ -1602,7 +1602,7 @@
<PrecompiledHeader>Use</PrecompiledHeader>
<CompileAsWinRT>true</CompileAsWinRT>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_ENABLE_BULLET_INTEGRATION=1;_DEBUG;COCOS2D_DEBUG=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_DEBUG;COCOS2D_DEBUG=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>4458;4459;%(DisableSpecificWarnings)</DisableSpecificWarnings>
<AdditionalIncludeDirectories>$(EngineRoot)external\win10-specific\zlib\include;$(EngineRoot)external\freetype2\include\win10\freetype2;$(EngineRoot)external\protobuf-lite\src;$(EngineRoot)external\protobuf-lite\win32;$(EngineRoot)external\win10-specific\OggDecoder\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
@ -1621,7 +1621,7 @@
<PrecompiledHeader>Use</PrecompiledHeader>
<CompileAsWinRT>true</CompileAsWinRT>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_ENABLE_BULLET_INTEGRATION=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>_USRDLL;_LIB;COCOS2DXWIN32_EXPORTS;_USE3DDLL;_EXPORT_DLL_;_USRSTUDIODLL;_USREXDLL;_USEGUIDLL;CC_ENABLE_CHIPMUNK_INTEGRATION=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>4458;4459;%(DisableSpecificWarnings)</DisableSpecificWarnings>
<AdditionalIncludeDirectories>$(EngineRoot)external\win10-specific\zlib\include;$(EngineRoot)external\freetype2\include\win10\freetype2;$(EngineRoot)external\protobuf-lite\src;$(EngineRoot)external\protobuf-lite\win32;$(EngineRoot)external\win10-specific\OggDecoder\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

View File

@ -216,73 +216,24 @@ bool Bundle3D::loadObj(MeshDatas& meshdatas, MaterialDatas& materialdatas, NodeD
else
mtlPath = fullPath.substr(0, fullPath.find_last_of("\\/") + 1).c_str();
ObjLoader::shapes_t shapes;
auto ret = ObjLoader::LoadObj(shapes, fullPath.c_str(), mtlPath.c_str());
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
auto ret = tinyobj::LoadObj(shapes, materials, fullPath.c_str(), mtlPath.c_str());
if (ret.empty())
{
//fill data
MeshData* meshdata = new (std::nothrow) MeshData();
MeshVertexAttrib attrib;
attrib.size = 3;
attrib.type = GL_FLOAT;
if (shapes.positions.size())
{
attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_POSITION;
attrib.attribSizeBytes = attrib.size * sizeof(float);
meshdata->attribs.push_back(attrib);
}
bool hasnormal = false, hastex = false;
if (shapes.normals.size())
{
hasnormal = true;
attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_NORMAL;
attrib.attribSizeBytes = attrib.size * sizeof(float);;
meshdata->attribs.push_back(attrib);
}
if (shapes.texcoords.size())
{
hastex = true;
attrib.size = 2;
attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_TEX_COORD;
attrib.attribSizeBytes = attrib.size * sizeof(float);
meshdata->attribs.push_back(attrib);
}
auto vertexNum = shapes.positions.size() / 3;
for(unsigned int i = 0; i < vertexNum; i++)
{
meshdata->vertex.push_back(shapes.positions[i * 3]);
meshdata->vertex.push_back(shapes.positions[i * 3 + 1]);
meshdata->vertex.push_back(shapes.positions[i * 3 + 2]);
if (hasnormal)
{
meshdata->vertex.push_back(shapes.normals[i * 3]);
meshdata->vertex.push_back(shapes.normals[i * 3 + 1]);
meshdata->vertex.push_back(shapes.normals[i * 3 + 2]);
}
if (hastex)
{
meshdata->vertex.push_back(shapes.texcoords[i * 2]);
meshdata->vertex.push_back(shapes.texcoords[i * 2 + 1]);
}
}
meshdatas.meshDatas.push_back(meshdata);
//convert material
int i = 0;
char str[20];
std::string dir = "";
auto last = fullPath.rfind("/");
if (last != -1)
dir = fullPath.substr(0, last + 1);
for (const auto& it : shapes.shapes)
{
for (auto& material : materials) {
NMaterialData materialdata;
NTextureData tex;
tex.filename = it.material.diffuse_texname.empty() ? it.material.diffuse_texname : dir + it.material.diffuse_texname;
tex.filename = material.diffuse_texname.empty() ? material.diffuse_texname : dir + material.diffuse_texname;
tex.type = NTextureData::Usage::Diffuse;
tex.wrapS = GL_CLAMP_TO_EDGE;
tex.wrapT = GL_CLAMP_TO_EDGE;
@ -290,19 +241,91 @@ bool Bundle3D::loadObj(MeshDatas& meshdatas, MaterialDatas& materialdatas, NodeD
sprintf(str, "%d", i++);
materialdata.textures.push_back(tex);
materialdata.id = str;
material.name = str;
materialdatas.materials.push_back(materialdata);
meshdata->subMeshIndices.push_back(it.mesh.indices);
meshdata->subMeshAABB.push_back(calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), it.mesh.indices));
meshdata->subMeshIds.push_back(str);
auto node = new (std::nothrow) NodeData();
auto modelnode = new (std::nothrow) ModelData();
modelnode->matrialId = str;
modelnode->subMeshId = str;
node->id = it.name;
node->modelNodeDatas.push_back(modelnode);
nodedatas.nodes.push_back(node);
}
//convert mesh
i = 0;
for (auto& shape : shapes) {
auto mesh = shape.mesh;
MeshData* meshdata = new (std::nothrow) MeshData();
MeshVertexAttrib attrib;
attrib.size = 3;
attrib.type = GL_FLOAT;
if (mesh.positions.size())
{
attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_POSITION;
attrib.attribSizeBytes = attrib.size * sizeof(float);
meshdata->attribs.push_back(attrib);
}
bool hasnormal = false, hastex = false;
if (mesh.normals.size())
{
hasnormal = true;
attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_NORMAL;
attrib.attribSizeBytes = attrib.size * sizeof(float);;
meshdata->attribs.push_back(attrib);
}
if (mesh.texcoords.size())
{
hastex = true;
attrib.size = 2;
attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_TEX_COORD;
attrib.attribSizeBytes = attrib.size * sizeof(float);
meshdata->attribs.push_back(attrib);
}
auto vertexNum = mesh.positions.size() / 3;
for(unsigned int k = 0; k < vertexNum; k++)
{
meshdata->vertex.push_back(mesh.positions[k * 3]);
meshdata->vertex.push_back(mesh.positions[k * 3 + 1]);
meshdata->vertex.push_back(mesh.positions[k * 3 + 2]);
if (hasnormal)
{
meshdata->vertex.push_back(mesh.normals[k * 3]);
meshdata->vertex.push_back(mesh.normals[k * 3 + 1]);
meshdata->vertex.push_back(mesh.normals[k * 3 + 2]);
}
if (hastex)
{
meshdata->vertex.push_back(mesh.texcoords[k * 2]);
meshdata->vertex.push_back(mesh.texcoords[k * 2 + 1]);
}
}
//split into submesh according to material
std::map<int, std::vector<unsigned short> > subMeshMap;
for (size_t k = 0; k < mesh.material_ids.size(); k++) {
int id = mesh.material_ids[k];
size_t idx = k * 3;
subMeshMap[id].push_back(mesh.indices[idx]);
subMeshMap[id].push_back(mesh.indices[idx + 1]);
subMeshMap[id].push_back(mesh.indices[idx + 2]);
}
auto node = new (std::nothrow) NodeData();
node->id = shape.name;
for (auto& submesh : subMeshMap) {
meshdata->subMeshIndices.push_back(submesh.second);
meshdata->subMeshAABB.push_back(calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), submesh.second));
sprintf(str, "%d", i++);
meshdata->subMeshIds.push_back(str);
auto modelnode = new (std::nothrow) ModelData();
modelnode->matrialId = submesh.first == -1 ? "" : materials[submesh.first].name;
modelnode->subMeshId = str;
node->modelNodeDatas.push_back(modelnode);
}
nodedatas.nodes.push_back(node);
meshdatas.meshDatas.push_back(meshdata);
}
return true;
}
CCLOG("warning: load %s file error: %s", fullPath.c_str(), ret.c_str());

View File

@ -273,6 +273,9 @@ void Mesh::setTexture(Texture2D* tex)
// Texture must be saved for future use
// it doesn't matter if the material is already set or not
// This functionality is added for compatibility issues
if (tex == nullptr)
tex = getDummyTexture();
if (tex != _texture)
{
CC_SAFE_RETAIN(tex);

File diff suppressed because it is too large Load Diff

View File

@ -1,40 +1,19 @@
//
// Copyright 2012-2013, Syoyo Fujita.
// Copyright 2012-2015, Syoyo Fujita.
//
// Licensed under 2-clause BSD liecense.
//
// copied from Syoyo Fujita
// https://github.com/syoyo/tinyobjloader
#ifndef __CCOBJLOADER_H__
#define __CCOBJLOADER_H__
//https://github.com/syoyo/tinyobjloader
#ifndef _TINY_OBJ_LOADER_H
#define _TINY_OBJ_LOADER_H
#include <string>
#include <vector>
#include <map>
#include "base/ccTypes.h"
NS_CC_BEGIN
namespace tinyobj {
/**
* @addtogroup _3d
* @{
*/
/**
* @brief .obj file Loader
* @js NA
* @lua NA
**/
class ObjLoader
{
public:
/**
* model's material struct
**/
typedef struct
{
typedef struct {
std::string name;
float ambient[3];
@ -55,61 +34,62 @@ public:
std::map<std::string, std::string> unknown_parameter;
} material_t;
/**
* model's indices struct
**/
typedef struct
{
std::vector<unsigned short> indices;
} mesh_t;
/**
* model's shape struct
**/
typedef struct
{
std::string name;
material_t material;
mesh_t mesh;
} shape_t;
/**
* model's shapes struct
**/
typedef struct
{
typedef struct {
std::vector<float> positions;
std::vector<float> normals;
std::vector<float> texcoords;
std::vector<unsigned short> indices;
std::vector<int> material_ids; // per-mesh material ID
} mesh_t;
std::vector<shape_t> shapes;
typedef struct {
std::string name;
mesh_t mesh;
} shape_t;
void reset()
{
positions.clear();
normals.clear();
texcoords.clear();
shapes.clear();
}
}shapes_t;
class MaterialReader {
public:
MaterialReader() {}
virtual ~MaterialReader() {}
/**
* Loads .obj from a file.
* @param shapes will be filled with parsed shape data
* @param filename the .obj file path .
* @param mtl_basepath It's optional, and used for base path for .mtl file
* @return The function returns error string, return empty string when loading .obj success.
*/
static std::string LoadObj(
shapes_t& shapes, // [output]
const char* filename,
const char* mtl_basepath = NULL);
virtual std::string operator()(const std::string &matId,
std::vector<material_t> &materials,
std::map<std::string, int> &matMap) = 0;
};
};
class MaterialFileReader : public MaterialReader {
public:
MaterialFileReader(const std::string &mtl_basepath)
: m_mtlBasePath(mtl_basepath) {}
virtual ~MaterialFileReader() {}
virtual std::string operator()(const std::string &matId,
std::vector<material_t> &materials,
std::map<std::string, int> &matMap);
// end of 3d group
/// @}
private:
std::string m_mtlBasePath;
};
NS_CC_END
/// Loads .obj from a file.
/// 'shapes' will be filled with parsed shape data
/// The function returns error string.
/// Returns empty string when loading .obj success.
/// 'mtl_basepath' is optional, and used for base path for .mtl file.
std::string LoadObj(std::vector<shape_t> &shapes, // [output]
std::vector<material_t> &materials, // [output]
const char *filename, const char *mtl_basepath = NULL);
/// Loads object from a std::istream, uses GetMtlIStreamFn to retrieve
/// std::istream for materials.
/// Returns empty string when loading .obj success.
std::string LoadObj(std::vector<shape_t> &shapes, // [output]
std::vector<material_t> &materials, // [output]
std::istream &inStream, MaterialReader &readMatFn);
/// Loads materials into std::map
/// Returns an empty string if successful
std::string LoadMtl(std::map<std::string, int> &material_map,
std::vector<material_t> &materials, std::istream &inStream);
}
#endif // _TINY_OBJ_LOADER_H

View File

@ -352,7 +352,6 @@ Sprite3D* Sprite3D::createSprite3DNode(NodeData* nodedata,ModelData* modeldata,c
if (modeldata->matrialId == "" && materialdatas.materials.size())
{
const NTextureData* textureData = materialdatas.materials[0].getTextureData(NTextureData::Usage::Diffuse);
if (!textureData->filename.empty())
mesh->setTexture(textureData->filename);
}
else
@ -361,9 +360,10 @@ Sprite3D* Sprite3D::createSprite3DNode(NodeData* nodedata,ModelData* modeldata,c
if(materialData)
{
const NTextureData* textureData = materialData->getTextureData(NTextureData::Usage::Diffuse);
if(textureData && !textureData->filename.empty())
if(textureData)
{
auto tex = Director::getInstance()->getTextureCache()->addImage(textureData->filename);
mesh->setTexture(textureData->filename);
auto tex = mesh->getTexture();
if(tex)
{
Texture2D::TexParams texParams;
@ -372,10 +372,8 @@ Sprite3D* Sprite3D::createSprite3DNode(NodeData* nodedata,ModelData* modeldata,c
texParams.wrapS = textureData->wrapS;
texParams.wrapT = textureData->wrapT;
tex->setTexParameters(texParams);
mesh->setTexture(tex);
mesh->_isTransparent = (materialData->getTextureData(NTextureData::Usage::Transparency) != nullptr);
}
}
}
}
@ -506,9 +504,10 @@ void Sprite3D::createNode(NodeData* nodedata, Node* root, const MaterialDatas& m
if(materialData)
{
const NTextureData* textureData = materialData->getTextureData(NTextureData::Usage::Diffuse);
if(textureData && !textureData->filename.empty())
if(textureData)
{
auto tex = Director::getInstance()->getTextureCache()->addImage(textureData->filename);
mesh->setTexture(textureData->filename);
auto tex = mesh->getTexture();
if(tex)
{
Texture2D::TexParams texParams;
@ -517,10 +516,8 @@ void Sprite3D::createNode(NodeData* nodedata, Node* root, const MaterialDatas& m
texParams.wrapS = textureData->wrapS;
texParams.wrapT = textureData->wrapT;
tex->setTexParameters(texParams);
mesh->setTexture(tex);
mesh->_isTransparent = (materialData->getTextureData(NTextureData::Usage::Transparency) != nullptr);
}
}
}
}
@ -982,6 +979,9 @@ static GLProgramState* getGLProgramStateForAttribs(MeshVertexData* meshVertexDat
}
else
{
if (hasNormal && usesLight)
shader = GLProgram::SHADER_3D_POSITION_NORMAL;
else
shader = GLProgram::SHADER_3D_POSITION;
}

View File

@ -23,6 +23,7 @@
****************************************************************************/
#include "platform/CCPlatformConfig.h"
#include <condition_variable>
#if CC_TARGET_PLATFORM == CC_PLATFORM_WINRT || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
@ -61,8 +62,110 @@ AudioEngine::ProfileHelper* AudioEngine::_defaultProfileHelper = nullptr;
std::unordered_map<int, AudioEngine::AudioInfo> AudioEngine::_audioIDInfoMap;
AudioEngineImpl* AudioEngine::_audioEngineImpl = nullptr;
AudioEngine::AudioEngineThreadPool* AudioEngine::s_threadPool = nullptr;
class AudioEngine::AudioEngineThreadPool
{
public:
AudioEngineThreadPool(bool detach)
: _numThread(6)
, _detach(detach)
{
s_threadPool = this;
_threads.reserve(_numThread);
_tasks.reserve(_numThread);
for (int index = 0; index < _numThread; ++index) {
_tasks.push_back(nullptr);
_threads.push_back(std::thread(std::bind(&AudioEngineThreadPool::threadFunc, this, index)));
if (_detach)
{
_threads[index].detach();
}
}
}
void addTask(const std::function<void()> &task){
_taskMutex.lock();
int targetIndex = -1;
for (int index = 0; index < _numThread; ++index) {
if (_tasks[index] == nullptr) {
targetIndex = index;
_tasks[index] = task;
break;
}
}
if (targetIndex == -1) {
_tasks.push_back(task);
_threads.push_back(std::thread(std::bind(&AudioEngineThreadPool::threadFunc, this, _numThread)));
if (_detach)
{
_threads[_numThread].detach();
}
_numThread++;
}
_taskMutex.unlock();
_sleepCondition.notify_all();
}
void destroy()
{
std::unique_lock<std::mutex> lk(_sleepMutex);
_sleepCondition.notify_all();
if (!_detach)
{
for (int index = 0; index < _numThread; ++index) {
_threads[index].join();
}
}
}
private:
std::vector<std::thread> _threads;
std::vector< std::function<void()> > _tasks;
void threadFunc(int index)
{
while (s_threadPool == this) {
std::function<void()> task = nullptr;
_taskMutex.lock();
task = _tasks[index];
_taskMutex.unlock();
if (nullptr == task)
{
std::unique_lock<std::mutex> lk(_sleepMutex);
_sleepCondition.wait(lk);
continue;
}
task();
_taskMutex.lock();
_tasks[index] = nullptr;
_taskMutex.unlock();
}
}
int _numThread;
std::mutex _taskMutex;
std::mutex _sleepMutex;
std::condition_variable _sleepCondition;
bool _detach;
};
void AudioEngine::end()
{
if (s_threadPool)
{
s_threadPool->destroy();
delete s_threadPool;
s_threadPool = nullptr;
}
delete _audioEngineImpl;
_audioEngineImpl = nullptr;
@ -82,6 +185,18 @@ bool AudioEngine::lazyInit()
}
}
#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
if (_audioEngineImpl && s_threadPool == nullptr)
{
s_threadPool = new (std::nothrow) AudioEngineThreadPool(true);
}
#elif CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID
if (_audioEngineImpl && s_threadPool == nullptr)
{
s_threadPool = new (std::nothrow) AudioEngineThreadPool(false);
}
#endif
return true;
}
@ -415,4 +530,28 @@ AudioProfile* AudioEngine::getProfile(const std::string &name)
}
}
void AudioEngine::preload(const std::string& filePath)
{
lazyInit();
if (_audioEngineImpl)
{
if (!FileUtils::getInstance()->isFileExist(filePath)){
return;
}
_audioEngineImpl->preload(filePath);
}
}
void AudioEngine::addTask(const std::function<void()> &task)
{
lazyInit();
if (_audioEngineImpl && s_threadPool)
{
s_threadPool->addTask(task);
}
}
#endif

View File

@ -1,5 +1,5 @@
/****************************************************************************
Copyright (c) 2014 Chukong Technologies Inc.
Copyright (c) 2014-2015 Chukong Technologies Inc.
http://www.cocos2d-x.org
@ -432,4 +432,9 @@ void AudioEngineImpl::setFinishCallback(int audioID, const std::function<void (i
_audioPlayers[audioID]._finishCallback = callback;
}
void AudioEngineImpl::preload(const std::string& filePath)
{
CCLOG("Preload not support on Anroid");
}
#endif

View File

@ -1,5 +1,5 @@
/****************************************************************************
Copyright (c) 2014 Chukong Technologies Inc.
Copyright (c) 2014-2015 Chukong Technologies Inc.
http://www.cocos2d-x.org
@ -88,6 +88,7 @@ public:
void uncache(const std::string& filePath){}
void uncacheAll(){}
void preload(const std::string& filePath);
void update(float dt);
private:

View File

@ -38,8 +38,6 @@ NS_CC_BEGIN
namespace experimental{
#define MAX_AUDIOINSTANCES 24
class AudioEngineThreadPool;
class AudioEngineImpl : public cocos2d::Ref
{
public:
@ -61,14 +59,12 @@ public:
void uncache(const std::string& filePath);
void uncacheAll();
AudioCache* preload(const std::string& filePath);
void update(float dt);
private:
void _play2d(AudioCache *cache, int audioID);
AudioEngineThreadPool* _threadPool;
ALuint _alSources[MAX_AUDIOINSTANCES];
//source,used

View File

@ -42,93 +42,6 @@ using namespace cocos2d::experimental;
static ALCdevice *s_ALDevice = nullptr;
static ALCcontext *s_ALContext = nullptr;
namespace cocos2d {
namespace experimental {
class AudioEngineThreadPool
{
public:
AudioEngineThreadPool()
: _running(true)
, _numThread(6)
{
_threads.reserve(_numThread);
_tasks.reserve(_numThread);
for (int index = 0; index < _numThread; ++index) {
_tasks.push_back(nullptr);
_threads.push_back( std::thread( std::bind(&AudioEngineThreadPool::threadFunc,this,index) ) );
}
}
void addTask(const std::function<void()> &task){
_taskMutex.lock();
int targetIndex = -1;
for (int index = 0; index < _numThread; ++index) {
if (_tasks[index] == nullptr) {
targetIndex = index;
_tasks[index] = task;
break;
}
}
if (targetIndex == -1) {
_tasks.push_back(task);
_threads.push_back( std::thread( std::bind(&AudioEngineThreadPool::threadFunc,this,_numThread) ) );
_numThread++;
}
_taskMutex.unlock();
_sleepCondition.notify_all();
}
void destroy()
{
_running = false;
_sleepCondition.notify_all();
for (int index = 0; index < _numThread; ++index) {
_threads[index].join();
}
}
private:
bool _running;
std::vector<std::thread> _threads;
std::vector< std::function<void ()> > _tasks;
void threadFunc(int index)
{
while (_running) {
std::function<void ()> task = nullptr;
_taskMutex.lock();
task = _tasks[index];
_taskMutex.unlock();
if (nullptr == task)
{
std::unique_lock<std::mutex> lk(_sleepMutex);
_sleepCondition.wait(lk);
continue;
}
task();
_taskMutex.lock();
_tasks[index] = nullptr;
_taskMutex.unlock();
}
}
int _numThread;
std::mutex _taskMutex;
std::mutex _sleepMutex;
std::condition_variable _sleepCondition;
};
}
}
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
@interface AudioEngineSessionHandler : NSObject
{
@ -220,8 +133,7 @@ static id s_AudioEngineSessionHandler = nullptr;
#endif
AudioEngineImpl::AudioEngineImpl()
: _threadPool(nullptr)
, _lazyInitLoop(true)
: _lazyInitLoop(true)
, _currentAudioID(0)
{
@ -240,10 +152,7 @@ AudioEngineImpl::~AudioEngineImpl()
if (s_ALDevice) {
alcCloseDevice(s_ALDevice);
}
if (_threadPool) {
_threadPool->destroy();
delete _threadPool;
}
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
[s_AudioEngineSessionHandler release];
#endif
@ -275,7 +184,6 @@ bool AudioEngineImpl::init()
_alSourceUsed[_alSources[i]] = false;
}
_threadPool = new (std::nothrow) AudioEngineThreadPool();
ret = true;
}
}while (false);
@ -283,6 +191,24 @@ bool AudioEngineImpl::init()
return ret;
}
AudioCache* AudioEngineImpl::preload(const std::string& filePath)
{
AudioCache* audioCache = nullptr;
auto it = _audioCaches.find(filePath);
if (it == _audioCaches.end()) {
audioCache = &_audioCaches[filePath];
audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
AudioEngine::addTask(std::bind(&AudioCache::readDataTask, audioCache));
}
else {
audioCache = &it->second;
}
return audioCache;
}
int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume)
{
if (s_ALDevice == nullptr) {
@ -303,16 +229,9 @@ int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume
return AudioEngine::INVALID_AUDIO_ID;
}
AudioCache* audioCache = nullptr;
auto it = _audioCaches.find(filePath);
if (it == _audioCaches.end()) {
audioCache = &_audioCaches[filePath];
audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
_threadPool->addTask(std::bind(&AudioCache::readDataTask, audioCache));
}
else {
audioCache = &it->second;
AudioCache* audioCache = preload(filePath);
if (audioCache == nullptr) {
return AudioEngine::INVALID_AUDIO_ID;
}
auto player = &_audioPlayers[_currentAudioID];

View File

@ -281,8 +281,14 @@ public:
*/
static AudioProfile* getProfile(const std::string &profileName);
protected:
/**
* Preload audio file.
* @param filePath The file path of an audio.
*/
static void preload(const std::string& filePath);
protected:
static void addTask(const std::function<void()> &task);
static void remove(int audioID);
struct ProfileHelper
@ -336,6 +342,9 @@ protected:
static AudioEngineImpl* _audioEngineImpl;
class AudioEngineThreadPool;
static AudioEngineThreadPool* s_threadPool;
friend class AudioEngineImpl;
};

View File

@ -26,7 +26,7 @@
#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
#include "AudioEngine-win32.h"
#include <condition_variable>
#ifdef OPENAL_PLAIN_INCLUDES
#include "alc.h"
#include "alext.h"
@ -47,95 +47,9 @@ static ALCdevice *s_ALDevice = nullptr;
static ALCcontext *s_ALContext = nullptr;
static bool MPG123_LAZYINIT = true;
namespace cocos2d {
namespace experimental {
class AudioEngineThreadPool
{
public:
AudioEngineThreadPool()
: _running(true)
, _numThread(6)
{
_threads.reserve(_numThread);
_tasks.reserve(_numThread);
for (int index = 0; index < _numThread; ++index) {
_tasks.push_back(nullptr);
_threads.push_back( std::thread( std::bind(&AudioEngineThreadPool::threadFunc,this,index) ) );
_threads[index].detach();
}
}
void addTask(const std::function<void()> &task){
_taskMutex.lock();
int targetIndex = -1;
for (int index = 0; index < _numThread; ++index) {
if (_tasks[index] == nullptr) {
targetIndex = index;
_tasks[index] = task;
break;
}
}
if (targetIndex == -1) {
_tasks.push_back(task);
_threads.push_back( std::thread( std::bind(&AudioEngineThreadPool::threadFunc,this,_numThread) ) );
_threads[_numThread].detach();
_numThread++;
}
_taskMutex.unlock();
_sleepCondition.notify_all();
}
void destroy()
{
_running = false;
_sleepCondition.notify_all();
for (int index = 0; index < _numThread; ++index) {
_threads[index].join();
}
}
private:
bool _running;
std::vector<std::thread> _threads;
std::vector< std::function<void ()> > _tasks;
void threadFunc(int index)
{
while (_running) {
std::function<void ()> task = nullptr;
_taskMutex.lock();
task = _tasks[index];
_taskMutex.unlock();
if (nullptr == task)
{
std::unique_lock<std::mutex> lk(_sleepMutex);
_sleepCondition.wait(lk);
continue;
}
task();
_taskMutex.lock();
_tasks[index] = nullptr;
_taskMutex.unlock();
}
}
int _numThread;
std::mutex _taskMutex;
std::mutex _sleepMutex;
std::condition_variable _sleepCondition;
};
}
}
AudioEngineImpl::AudioEngineImpl()
: _lazyInitLoop(true)
, _currentAudioID(0)
, _threadPool(nullptr)
{
}
@ -155,10 +69,6 @@ AudioEngineImpl::~AudioEngineImpl()
alcCloseDevice(s_ALDevice);
s_ALDevice = nullptr;
}
if (_threadPool) {
_threadPool->destroy();
delete _threadPool;
}
mpg123_exit();
MPG123_LAZYINIT = true;
@ -186,7 +96,6 @@ bool AudioEngineImpl::init()
_alSourceUsed[_alSources[i]] = false;
}
_threadPool = new (std::nothrow) AudioEngineThreadPool();
ret = true;
}
}while (false);
@ -194,6 +103,54 @@ bool AudioEngineImpl::init()
return ret;
}
AudioCache* AudioEngineImpl::preload(const std::string& filePath)
{
AudioCache* audioCache = nullptr;
do
{
auto it = _audioCaches.find(filePath);
if (it != _audioCaches.end())
{
audioCache = &it->second;
break;
}
auto ext = strchr(filePath.c_str(), '.');
AudioCache::FileFormat fileFormat = AudioCache::FileFormat::UNKNOWN;
if (_stricmp(ext, ".ogg") == 0){
fileFormat = AudioCache::FileFormat::OGG;
}
else if (_stricmp(ext, ".mp3") == 0){
fileFormat = AudioCache::FileFormat::MP3;
if (MPG123_LAZYINIT){
auto error = mpg123_init();
if (error == MPG123_OK){
MPG123_LAZYINIT = false;
}
else{
log("Basic setup goes wrong: %s", mpg123_plain_strerror(error));
break;
}
}
}
else{
log("unsupported media type:%s\n", ext);
break;
}
audioCache = &_audioCaches[filePath];
audioCache->_fileFormat = fileFormat;
audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
AudioEngine::addTask(std::bind(&AudioCache::readDataTask, audioCache));
} while (false);
return audioCache;
}
int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume)
{
bool availableSourceExist = false;
@ -209,50 +166,12 @@ int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume
return AudioEngine::INVALID_AUDIO_ID;
}
AudioCache* audioCache = nullptr;
auto it = _audioCaches.find(filePath);
if (it == _audioCaches.end()) {
audioCache = &_audioCaches[filePath];
auto ext = strchr(filePath.c_str(), '.');
bool eraseCache = true;
if (_stricmp(ext, ".ogg") == 0){
audioCache->_fileFormat = AudioCache::FileFormat::OGG;
eraseCache = false;
}
else if (_stricmp(ext, ".mp3") == 0){
audioCache->_fileFormat = AudioCache::FileFormat::MP3;
if (MPG123_LAZYINIT){
auto error = mpg123_init();
if(error == MPG123_OK){
MPG123_LAZYINIT = false;
eraseCache = false;
}
else{
log("Basic setup goes wrong: %s", mpg123_plain_strerror(error));
}
}
else{
eraseCache = false;
}
}
else{
log("unsupported media type:%s\n", ext);
}
if (eraseCache){
_audioCaches.erase(filePath);
AudioCache* audioCache = preload(filePath);
if (audioCache == nullptr)
{
return AudioEngine::INVALID_AUDIO_ID;
}
audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
_threadPool->addTask(std::bind(&AudioCache::readDataTask, audioCache));
}
else {
audioCache = &it->second;
}
auto player = &_audioPlayers[_currentAudioID];
player->_alSource = alSource;
player->_loop = loop;

View File

@ -38,8 +38,6 @@ NS_CC_BEGIN
namespace experimental{
#define MAX_AUDIOINSTANCES 32
class AudioEngineThreadPool;
class CC_DLL AudioEngineImpl : public cocos2d::Ref
{
public:
@ -61,14 +59,13 @@ public:
void uncache(const std::string& filePath);
void uncacheAll();
AudioCache* preload(const std::string& filePath);
void update(float dt);
private:
void _play2d(AudioCache *cache, int audioID);
AudioEngineThreadPool* _threadPool;
ALuint _alSources[MAX_AUDIOINSTANCES];
//source,used

View File

@ -21,101 +21,13 @@
#if CC_TARGET_PLATFORM == CC_PLATFORM_WINRT
#include "AudioEngine-winrt.h"
#include <condition_variable>
using namespace cocos2d;
using namespace cocos2d::experimental;
namespace cocos2d {
namespace experimental {
class AudioEngineThreadPool
{
public:
AudioEngineThreadPool()
: _running(true)
, _numThread(6)
{
_threads.reserve(_numThread);
_tasks.reserve(_numThread);
for (int index = 0; index < _numThread; ++index) {
_tasks.push_back(nullptr);
_threads.push_back(std::thread(std::bind(&AudioEngineThreadPool::threadFunc, this, index)));
}
}
void addTask(const std::function<void()> &task){
_taskMutex.lock();
int targetIndex = -1;
for (int index = 0; index < _numThread; ++index) {
if (_tasks[index] == nullptr) {
targetIndex = index;
_tasks[index] = task;
break;
}
}
if (targetIndex == -1) {
_tasks.push_back(task);
_threads.push_back(std::thread(std::bind(&AudioEngineThreadPool::threadFunc, this, _numThread)));
_numThread++;
}
_taskMutex.unlock();
_sleepCondition.notify_all();
}
void destroy()
{
_running = false;
_sleepCondition.notify_all();
for (int index = 0; index < _numThread; ++index) {
_threads[index].join();
}
}
private:
bool _running;
std::vector<std::thread> _threads;
std::vector< std::function<void()> > _tasks;
void threadFunc(int index)
{
while (_running) {
std::function<void()> task = nullptr;
_taskMutex.lock();
task = _tasks[index];
_taskMutex.unlock();
if (nullptr == task)
{
std::unique_lock<std::mutex> lk(_sleepMutex);
_sleepCondition.wait(lk);
continue;
}
task();
_taskMutex.lock();
_tasks[index] = nullptr;
_taskMutex.unlock();
}
}
int _numThread;
std::mutex _taskMutex;
std::mutex _sleepMutex;
std::condition_variable _sleepCondition;
};
}
}
AudioEngineImpl::AudioEngineImpl()
: _lazyInitLoop(true)
, _currentAudioID(0)
, _threadPool(nullptr)
{
}
@ -123,65 +35,64 @@ AudioEngineImpl::AudioEngineImpl()
AudioEngineImpl::~AudioEngineImpl()
{
_audioCaches.clear();
if (_threadPool) {
_threadPool->destroy();
delete _threadPool;
}
}
bool AudioEngineImpl::init()
{
bool ret = false;
if (nullptr == _threadPool) {
_threadPool = new (std::nothrow) AudioEngineThreadPool();
}
ret = true;
return ret;
}
int AudioEngineImpl::play2d(const std::string &filePath, bool loop, float volume)
AudioCache* AudioEngineImpl::preload(const std::string& filePath)
{
AudioCache* audioCache = nullptr;
do
{
auto it = _audioCaches.find(filePath);
if (it == _audioCaches.end()) {
audioCache = &_audioCaches[filePath];
FileFormat fileFormat = FileFormat::UNKNOWN;
auto ext = filePath.substr(filePath.rfind('.'));
transform(ext.begin(), ext.end(), ext.begin(), tolower);
bool eraseCache = true;
if (ext.compare(".wav") == 0){
audioCache->_fileFormat = FileFormat::WAV;
eraseCache = false;
fileFormat = FileFormat::WAV;
}
else if (ext.compare(".ogg") == 0){
audioCache->_fileFormat = FileFormat::OGG;
eraseCache = false;
fileFormat = FileFormat::OGG;
}
else if (ext.compare(".mp3") == 0){
audioCache->_fileFormat = FileFormat::MP3;
eraseCache = false;
fileFormat = FileFormat::MP3;
}
else{
log("unsupported media type:%s\n", ext.c_str());
break;
}
if (eraseCache){
_audioCaches.erase(filePath);
return AudioEngine::INVALID_AUDIO_ID;
}
audioCache = &_audioCaches[filePath];
audioCache->_fileFormat = fileFormat;
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
audioCache->_fileFullPath = fullPath;
_threadPool->addTask(std::bind(&AudioCache::readDataTask, audioCache));
AudioEngine::addTask(std::bind(&AudioCache::readDataTask, audioCache));
}
else {
audioCache = &it->second;
}
} while (false);
return audioCache;
}
int AudioEngineImpl::play2d(const std::string &filePath, bool loop, float volume)
{
auto audioCache = preload(filePath);
if (audioCache == nullptr)
{
return AudioEngine::INVALID_AUDIO_ID;
}
auto player = &_audioPlayers[_currentAudioID];
player->_loop = loop;

View File

@ -35,9 +35,6 @@ NS_CC_BEGIN
namespace experimental{
#define MAX_AUDIOINSTANCES 32
class AudioEngineThreadPool;
class CC_DLL AudioEngineImpl : public cocos2d::Ref
{
public:
@ -58,6 +55,7 @@ NS_CC_BEGIN
void setFinishCallback(int audioID, const std::function<void(int, const std::string &)> &callback);
void uncache(const std::string& filePath);
void uncacheAll();
AudioCache* preload(const std::string& filePath);
void update(float dt);
private:
@ -72,7 +70,6 @@ NS_CC_BEGIN
std::vector<int> _toRemoveAudioIDs;
bool _lazyInitLoop;
int _currentAudioID;
AudioEngineThreadPool* _threadPool;
};
}

View File

@ -50,7 +50,7 @@ Configuration::Configuration()
, _maxDirLightInShader(1)
, _maxPointLightInShader(1)
, _maxSpotLightInShader(1)
, _animate3DQuality(Animate3DQuality::QUALITY_HIGH)
, _animate3DQuality(Animate3DQuality::QUALITY_LOW)
{
}

View File

@ -235,20 +235,53 @@ void SendLogToWindow(const char *log)
static void _log(const char *format, va_list args)
{
char buf[MAX_LOG_LENGTH];
int bufferSize = MAX_LOG_LENGTH;
char* buf = nullptr;
do
{
buf = new (std::nothrow) char[bufferSize];
if (buf == nullptr)
return; // not enough memory
int ret = vsnprintf(buf, bufferSize - 3, format, args);
if (ret < 0)
{
bufferSize *= 2;
delete [] buf;
}
else
break;
} while (true);
vsnprintf(buf, MAX_LOG_LENGTH-3, format, args);
strcat(buf, "\n");
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
__android_log_print(ANDROID_LOG_DEBUG, "cocos2d-x debug info", "%s", buf);
#elif CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT
WCHAR wszBuf[MAX_LOG_LENGTH] = {0};
MultiByteToWideChar(CP_UTF8, 0, buf, -1, wszBuf, sizeof(wszBuf));
int pos = 0;
int len = strlen(buf);
char tempBuf[MAX_LOG_LENGTH + 1] = { 0 };
WCHAR wszBuf[MAX_LOG_LENGTH + 1] = { 0 };
do
{
std::copy(buf + pos, buf + pos + MAX_LOG_LENGTH, tempBuf);
tempBuf[MAX_LOG_LENGTH] = 0;
MultiByteToWideChar(CP_UTF8, 0, tempBuf, -1, wszBuf, sizeof(wszBuf));
OutputDebugStringW(wszBuf);
WideCharToMultiByte(CP_ACP, 0, wszBuf, -1, buf, sizeof(buf), nullptr, FALSE);
printf("%s", buf);
WideCharToMultiByte(CP_ACP, 0, wszBuf, -1, tempBuf, sizeof(tempBuf), nullptr, FALSE);
printf("%s", tempBuf);
pos += MAX_LOG_LENGTH;
} while (pos < len);
SendLogToWindow(buf);
fflush(stdout);
#else
@ -258,7 +291,7 @@ static void _log(const char *format, va_list args)
#endif
Director::getInstance()->getConsole()->log(buf);
delete [] buf;
}
// FIXME: Deprecated

View File

@ -410,11 +410,7 @@ TextureCache* Director::getTextureCache() const
void Director::initTextureCache()
{
#ifdef EMSCRIPTEN
_textureCache = new (std::nothrow) TextureCacheEmscripten();
#else
_textureCache = new (std::nothrow) TextureCache();
#endif // EMSCRIPTEN
}
void Director::destroyTextureCache()

View File

@ -1027,7 +1027,8 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event)
return true;
}
CCASSERT((*touchesIter)->getID() == (*mutableTouchesIter)->getID(), "");
CCASSERT((*touchesIter)->getID() == (*mutableTouchesIter)->getID(),
"touchesIter ID should be equal to mutableTouchesIter's ID.");
if (isClaimed && listener->_isRegistered && listener->_needSwallow)
{

View File

@ -89,7 +89,7 @@ EventListenerAcceleration* EventListenerAcceleration::clone()
bool EventListenerAcceleration::checkAvailable()
{
CCASSERT(onAccelerationEvent, "");
CCASSERT(onAccelerationEvent, "onAccelerationEvent can't be nullptr!");
return true;
}

View File

@ -300,7 +300,7 @@ void Scheduler::schedule(const ccSchedulerFunc& callback, void *target, float in
}
else
{
CCASSERT(element->paused == paused, "");
CCASSERT(element->paused == paused, "element's paused should be paused!");
}
if (element->timers == nullptr)
@ -694,7 +694,7 @@ void Scheduler::unscheduleScriptEntry(unsigned int scheduleScriptEntryID)
void Scheduler::resumeTarget(void *target)
{
CCASSERT(target != nullptr, "");
CCASSERT(target != nullptr, "target can't be nullptr!");
// custom selectors
tHashTimerEntry *element = nullptr;
@ -709,14 +709,14 @@ void Scheduler::resumeTarget(void *target)
HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate);
if (elementUpdate)
{
CCASSERT(elementUpdate->entry != nullptr, "");
CCASSERT(elementUpdate->entry != nullptr, "elementUpdate's entry can't be nullptr!");
elementUpdate->entry->paused = false;
}
}
void Scheduler::pauseTarget(void *target)
{
CCASSERT(target != nullptr, "");
CCASSERT(target != nullptr, "target can't be nullptr!");
// custom selectors
tHashTimerEntry *element = nullptr;
@ -731,7 +731,7 @@ void Scheduler::pauseTarget(void *target)
HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate);
if (elementUpdate)
{
CCASSERT(elementUpdate->entry != nullptr, "");
CCASSERT(elementUpdate->entry != nullptr, "elementUpdate's entry can't be nullptr!");
elementUpdate->entry->paused = true;
}
}
@ -1001,7 +1001,7 @@ void Scheduler::schedule(SEL_SCHEDULE selector, Ref *target, float interval, uns
}
else
{
CCASSERT(element->paused == paused, "");
CCASSERT(element->paused == paused, "element's paused should be paused.");
}
if (element->timers == nullptr)

View File

@ -252,8 +252,8 @@ int ZipUtils::inflateGZipFile(const char *path, unsigned char **out)
int len;
unsigned int offset = 0;
CCASSERT(out, "");
CCASSERT(&*out, "");
CCASSERT(out, "out can't be nullptr.");
CCASSERT(&*out, "&*out can't be nullptr.");
gzFile inFile = gzopen(path, "rb");
if( inFile == nullptr ) {

View File

@ -256,7 +256,13 @@ THE SOFTWARE.
#ifndef CC_USE_3D_PHYSICS
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_LINUX || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
#define CC_USE_3D_PHYSICS 1
#define CC_USE_3D_PHYSICS 1
#endif
#endif
#if (CC_USE_3D_PHYSICS)
/** Use bullet physics engine. */
#ifndef CC_ENABLE_BULLET_INTEGRATION
#define CC_ENABLE_BULLET_INTEGRATION 1
#endif
#endif

View File

@ -28,6 +28,8 @@ THE SOFTWARE.
#include <stdlib.h>
#include "base/CCDirector.h"
#include "base/CCAsyncTaskPool.h"
#include "base/CCEventDispatcher.h"
#include "renderer/CCCustomCommand.h"
#include "renderer/CCRenderer.h"
#include "platform/CCImage.h"
@ -49,10 +51,27 @@ int ccNextPOT(int x)
namespace utils
{
/**
* Capture screen implementation, don't use it directly.
*/
* Capture screen implementation, don't use it directly.
*/
void onCaptureScreen(const std::function<void(bool, const std::string&)>& afterCaptured, const std::string& filename)
{
static bool startedCapture = false;
if (startedCapture)
{
CCLOG("Screen capture is already working");
if (afterCaptured)
{
afterCaptured(false, filename);
}
return;
}
else
{
startedCapture = true;
}
auto glView = Director::getInstance()->getOpenGLView();
auto frameSize = glView->getFrameSize();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
@ -87,7 +106,7 @@ void onCaptureScreen(const std::function<void(bool, const std::string&)>& afterC
memcpy(flippedBuffer.get() + (height - row - 1) * width * 4, buffer.get() + row * width * 4, width * 4);
}
std::shared_ptr<Image> image(new Image);
Image* image = new (std::nothrow) Image;
if (image)
{
image->initWithRawData(flippedBuffer.get(), width * height * 4, width, height, 8);
@ -100,24 +119,57 @@ void onCaptureScreen(const std::function<void(bool, const std::string&)>& afterC
CCASSERT(filename.find("/") == std::string::npos, "The existence of a relative path is not guaranteed!");
outputFile = FileUtils::getInstance()->getWritablePath() + filename;
}
succeed = image->saveToFile(outputFile);
}
}while(0);
// Save image in AsyncTaskPool::TaskType::TASK_IO thread, and call afterCaptured in mainThread
static bool succeedSaveToFile = false;
std::function<void(void*)> mainThread = [afterCaptured, outputFile](void* param)
{
if (afterCaptured)
{
afterCaptured(succeedSaveToFile, outputFile);
}
startedCapture = false;
};
AsyncTaskPool::getInstance()->enqueue(AsyncTaskPool::TaskType::TASK_IO, mainThread, (void*)NULL, [image, outputFile]()
{
succeedSaveToFile = image->saveToFile(outputFile);
delete image;
});
}
else
{
CCLOG("Malloc Image memory failed!");
if (afterCaptured)
{
afterCaptured(succeed, outputFile);
}
startedCapture = false;
}
} while (0);
}
/*
* Capture screen interface
*/
static EventListenerCustom* s_captureScreenListener;
static CustomCommand s_captureScreenCommand;
void captureScreen(const std::function<void(bool, const std::string&)>& afterCaptured, const std::string& filename)
{
static CustomCommand captureScreenCommand;
captureScreenCommand.init(std::numeric_limits<float>::max());
captureScreenCommand.func = std::bind(onCaptureScreen, afterCaptured, filename);
Director::getInstance()->getRenderer()->addCommand(&captureScreenCommand);
if (s_captureScreenListener)
{
CCLOG("Warning: CaptureScreen has been caled yet, don't call more than once in one frame.");
return;
}
s_captureScreenCommand.init(std::numeric_limits<float>::max());
s_captureScreenCommand.func = std::bind(onCaptureScreen, afterCaptured, filename);
s_captureScreenListener = Director::getInstance()->getEventDispatcher()->addCustomEventListener(Director::EVENT_AFTER_DRAW, [](EventCustom *event) {
auto director = Director::getInstance();
director->getEventDispatcher()->removeEventListener((EventListener*)(s_captureScreenListener));
s_captureScreenListener = nullptr;
director->getRenderer()->addCommand(&s_captureScreenCommand);
director->getRenderer()->render();
});
}
std::vector<Node*> findChildren(const Node &node, const std::string &name)

View File

@ -31,7 +31,7 @@ NS_CC_BEGIN
CC_DLL const char* cocos2dVersion()
{
return "cocos2d-x-3.7rc0";
return "cocos2d-x-3.7";
}
NS_CC_END

View File

@ -128,7 +128,7 @@ CCBReader::~CCBReader()
void CCBReader::setCCBRootPath(const char* ccbRootPath)
{
CCASSERT(ccbRootPath != nullptr, "");
CCASSERT(ccbRootPath != nullptr, "ccbRootPath can't be nullptr!");
_CCBRootPath = ccbRootPath;
}

View File

@ -99,11 +99,11 @@ void NodeLoader::parseProperties(Node * pNode, Node * pParent, CCBReader * ccbRe
__Array *extraPropsNames = static_cast<__Array*>(pNode->getUserObject());
if (! extraPropsNames)
{
extraPropsNames = Array::create();
extraPropsNames = __Array::create();
pNode->setUserObject(extraPropsNames);
}
extraPropsNames->addObject(String::create(propertyName));
extraPropsNames->addObject(__String::create(propertyName));
}
switch(type)
@ -968,7 +968,8 @@ Node * NodeLoader::parsePropTypeCCBFile(Node * pNode, Node * pParent, CCBReader
auto& ownerCallbackNodes = reader->getOwnerCallbackNodes();
if (!ownerCallbackNames.empty() && !ownerCallbackNodes.empty())
{
CCASSERT(ownerCallbackNames.size() == ownerCallbackNodes.size(), "");
CCASSERT(ownerCallbackNames.size() == ownerCallbackNodes.size(),
"ownerCallbackNames size should equal to ownerCallbackNodes size.");
ssize_t nCount = ownerCallbackNames.size();
for (ssize_t i = 0 ; i < nCount; i++)
@ -982,7 +983,8 @@ Node * NodeLoader::parsePropTypeCCBFile(Node * pNode, Node * pParent, CCBReader
auto ownerOutletNodes = reader->getOwnerOutletNodes();
if (!ownerOutletNames.empty() && !ownerOutletNodes.empty())
{
CCASSERT(ownerOutletNames.size() == ownerOutletNodes.size(), "");
CCASSERT(ownerOutletNames.size() == ownerOutletNodes.size(),
"ownerOutletNames size should be equal to ownerOutletNodes's size.");
ssize_t nCount = ownerOutletNames.size();
for (ssize_t i = 0 ; i < nCount; i++)

View File

@ -611,7 +611,7 @@ Node* CSLoader::loadSprite(const rapidjson::Value& json)
if(!sprite)
{
sprite = CCSprite::create();
sprite = Sprite::create();
CCLOG("filePath is empty. Create a sprite with no texture");
}
}
@ -844,7 +844,7 @@ Node* CSLoader::nodeWithFlatBuffersFile(const std::string &fileName, const ccNod
if (csBuildId)
{
CCASSERT(strcmp(_csBuildID.c_str(), csBuildId->c_str()) == 0,
String::createWithFormat("%s%s%s%s%s%s%s%s%s%s",
StringUtils::format("%s%s%s%s%s%s%s%s%s%s",
"The reader build id of your Cocos exported file(",
csBuildId->c_str(),
") and the reader build id in your Cocos2d-x(",
@ -854,7 +854,7 @@ Node* CSLoader::nodeWithFlatBuffersFile(const std::string &fileName, const ccNod
csBuildId->c_str(),
")from ",
"http://www.cocos2d-x.org/filedown/cocos-reader",
" and replace it in your Cocos2d-x")->getCString());
" and replace it in your Cocos2d-x").c_str());
}
// decode plist

View File

@ -137,7 +137,7 @@ bool Armature::init(const std::string& name)
ArmatureData *armatureData = armatureDataManager->getArmatureData(name);
CCASSERT(armatureData, "");
CCASSERT(armatureData, "armatureData doesn't exists!");
_armatureData = armatureData;

View File

@ -246,7 +246,7 @@ void DisplayManager::changeDisplayWithIndex(int index, bool force)
setCurrentDecorativeDisplay(decoDisplay);
}
void CCDisplayManager::changeDisplayWithName(const std::string& name, bool force)
void DisplayManager::changeDisplayWithName(const std::string& name, bool force)
{
for (int i = 0; i<_decoDisplayList.size(); i++)
{

View File

@ -493,7 +493,7 @@ Widget* WidgetPropertiesReader0250::createWidget(const rapidjson::Value& data, c
const char* file = DICTOOL->getStringValueFromArray_json(data, "textures", i);
std::string tp = fullPath;
tp.append(file);
CCSpriteFrameCache::getInstance()->addSpriteFramesWithFile(tp.c_str());
SpriteFrameCache::getInstance()->addSpriteFramesWithFile(tp.c_str());
}
float fileDesignWidth = DICTOOL->getFloatValue_json(data, "designWidth");
float fileDesignHeight = DICTOOL->getFloatValue_json(data, "designHeight");
@ -713,7 +713,7 @@ void WidgetPropertiesReader0250::setPropsForButtonFromJsonDictionary(Widget*widg
if (useMergedTexture)
{
button->loadTextures(normalFileName, pressedFileName, disabledFileName,TextureResType::PLIST);
button->loadTextures(normalFileName, pressedFileName, disabledFileName,Widget::TextureResType::PLIST);
}
else
{
@ -733,7 +733,7 @@ void WidgetPropertiesReader0250::setPropsForButtonFromJsonDictionary(Widget*widg
{
if (useMergedTexture)
{
button->loadTextures(normalFileName, pressedFileName, disabledFileName,TextureResType::PLIST);
button->loadTextures(normalFileName, pressedFileName, disabledFileName,Widget::TextureResType::PLIST);
}
else
{
@ -794,7 +794,7 @@ void WidgetPropertiesReader0250::setPropsForCheckBoxFromJsonDictionary(Widget*wi
if (useMergedTexture)
{
checkBox->loadTextures(backGroundFileName, backGroundSelectedFileName, frontCrossFileName,backGroundDisabledFileName,frontCrossDisabledFileName,TextureResType::PLIST);
checkBox->loadTextures(backGroundFileName, backGroundSelectedFileName, frontCrossFileName,backGroundDisabledFileName,frontCrossDisabledFileName,Widget::TextureResType::PLIST);
}
else
{
@ -829,7 +829,7 @@ void WidgetPropertiesReader0250::setPropsForImageViewFromJsonDictionary(Widget*w
{
if (useMergedTexture)
{
imageView->loadTexture(imageFileName,TextureResType::PLIST);
imageView->loadTexture(imageFileName,Widget::TextureResType::PLIST);
}
else
{
@ -856,7 +856,7 @@ void WidgetPropertiesReader0250::setPropsForImageViewFromJsonDictionary(Widget*w
{
if (useMergedTexture)
{
imageView->loadTexture(imageFileName,TextureResType::PLIST);
imageView->loadTexture(imageFileName,Widget::TextureResType::PLIST);
}
else
{
@ -974,7 +974,7 @@ void WidgetPropertiesReader0250::setPropsForLayoutFromJsonDictionary(Widget*widg
float ch = DICTOOL->getFloatValue_json(options, "capInsetsHeight");
if (useMergedTexture)
{
panel->setBackGroundImage(imageFileName,TextureResType::PLIST);
panel->setBackGroundImage(imageFileName,Widget::TextureResType::PLIST);
}
else
{
@ -987,7 +987,7 @@ void WidgetPropertiesReader0250::setPropsForLayoutFromJsonDictionary(Widget*widg
if (useMergedTexture)
{
panel->setBackGroundImage(imageFileName,TextureResType::PLIST);
panel->setBackGroundImage(imageFileName,Widget::TextureResType::PLIST);
}
else
{
@ -1029,7 +1029,7 @@ void WidgetPropertiesReader0250::setPropsForSliderFromJsonDictionary(Widget*widg
const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():nullptr;
if (useMergedTexture)
{
slider->loadBarTexture(imageFileName,TextureResType::PLIST);
slider->loadBarTexture(imageFileName,Widget::TextureResType::PLIST);
}
else
{
@ -1044,7 +1044,7 @@ void WidgetPropertiesReader0250::setPropsForSliderFromJsonDictionary(Widget*widg
const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():nullptr;
if (useMergedTexture)
{
slider->loadBarTexture(imageFileName,TextureResType::PLIST);
slider->loadBarTexture(imageFileName,Widget::TextureResType::PLIST);
}
else
{
@ -1065,7 +1065,7 @@ void WidgetPropertiesReader0250::setPropsForSliderFromJsonDictionary(Widget*widg
const char* disabledFileName_tp = (disabledFileName && (strcmp(disabledFileName, "") != 0))?tp_d.append(disabledFileName).c_str():nullptr;
if (useMergedTexture)
{
slider->loadSlidBallTextures(normalFileName,pressedFileName,disabledFileName,TextureResType::PLIST);
slider->loadSlidBallTextures(normalFileName,pressedFileName,disabledFileName,Widget::TextureResType::PLIST);
}
else
{
@ -1078,7 +1078,7 @@ void WidgetPropertiesReader0250::setPropsForSliderFromJsonDictionary(Widget*widg
const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():nullptr;
if (useMergedTexture)
{
slider->loadProgressBarTexture(imageFileName, TextureResType::PLIST);
slider->loadProgressBarTexture(imageFileName, Widget::TextureResType::PLIST);
}
else
{
@ -1147,7 +1147,7 @@ void WidgetPropertiesReader0250::setPropsForLoadingBarFromJsonDictionary(Widget
const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():nullptr;
if (useMergedTexture)
{
loadingBar->loadTexture(imageFileName,TextureResType::PLIST);
loadingBar->loadTexture(imageFileName,Widget::TextureResType::PLIST);
}
else
{

View File

@ -79,7 +79,7 @@ cocos2d::Node* SceneReader::createNodeWithSceneFile(const std::string &fileName,
else if(file_extension == ".CSB")
{
do {
std::string binaryFilePath = CCFileUtils::getInstance()->fullPathForFilename(fileName);
std::string binaryFilePath = FileUtils::getInstance()->fullPathForFilename(fileName);
auto fileData = FileUtils::getInstance()->getDataFromFile(binaryFilePath);
auto fileDataBytes = fileData.getBytes();
CC_BREAK_IF(fileData.isNull());
@ -429,7 +429,7 @@ cocos2d::Node* SceneReader::createObject(CocoLoader *cocoLoader, stExpCocoNode *
{
if (pRender == nullptr || attachComponent == AttachComponentType::EMPTY_NODE)
{
gb = CCNode::create();
gb = Node::create();
if (pRender != nullptr)
{
_vecComs.push_back(pRender);

View File

@ -185,10 +185,10 @@ void TriggerObj::serialize(const rapidjson::Value &val)
if(con == nullptr)
{
CCLOG("class %s can not be implemented!", classname);
CCASSERT(con != nullptr, "");
CCASSERT(con != nullptr, "con can't be nullptr!");
}
CCASSERT(con != nullptr, "");
CCASSERT(con != nullptr, "con can't be nullptr!");
con->serialize(subDict);
con->init();
_cons.pushBack(con);
@ -207,7 +207,7 @@ void TriggerObj::serialize(const rapidjson::Value &val)
if(act == nullptr)
{
CCLOG("class %s can not be implemented!", classname);
CCASSERT(act != nullptr, "");
CCASSERT(act != nullptr, "act can't be nullptr!");
}
act->serialize(subDict);
act->init();

View File

@ -238,15 +238,12 @@ namespace cocostudio
setPropsWithFlatBuffers(tmx, (Table*)gameMapOptions);
}
}
//else
//{
// Node* node = Node::create();
// setPropsWithFlatBuffers(node, (Table*)gameMapOptions);
// auto label = Label::create();
// label->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString());
// node->addChild(label);
// return node;
//}
else
{
Node* node = Node::create();
setPropsWithFlatBuffers(node, (Table*)gameMapOptions);
return node;
}
return tmx;
}

View File

@ -153,11 +153,11 @@ namespace cocostudio
void ParticleReader::setPropsWithFlatBuffers(cocos2d::Node *node,
const flatbuffers::Table *particleOptions)
{
auto particle = static_cast<ParticleSystemQuad*>(node);
auto particle = dynamic_cast<ParticleSystemQuad*>(node);
auto options = (ParticleSystemOptions*)particleOptions;
auto f_blendFunc = options->blendFunc();
if (f_blendFunc)
if (particle && f_blendFunc)
{
cocos2d::BlendFunc blendFunc = cocos2d::BlendFunc::ALPHA_PREMULTIPLIED;
blendFunc.src = f_blendFunc->src();
@ -208,15 +208,12 @@ namespace cocostudio
particle->setPositionType(ParticleSystem::PositionType::GROUPED);
}
}
//else
//{
// Node* node = Node::create();
// setPropsWithFlatBuffers(node, (Table*)particleOptions);
// auto label = Label::create();
// label->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString());
// node->addChild(label);
// return node;
//}
else
{
Node* node = Node::create();
setPropsWithFlatBuffers(node, (Table*)particleOptions);
return node;
}
return particle;
}

View File

@ -466,7 +466,7 @@ namespace cocostudio
auto options = (SliderOptions*)sliderOptions;
int percent = options->percent();
slider->setPercent(percent);
//slider->setPercent(percent);
bool imageFileExist = false;
std::string imageErrorFilePath = "";
@ -798,7 +798,7 @@ namespace cocostudio
auto widgetReader = WidgetReader::getInstance();
widgetReader->setPropsWithFlatBuffers(node, (Table*)options->widgetOptions());
slider->setPercent(percent);
}
Node* SliderReader::createNodeWithFlatBuffers(const flatbuffers::Table *sliderOptions)

View File

@ -125,6 +125,7 @@ namespace cocostudio
else if(value == "USER1") cameraFlag = 1 << 1;
else if(value == "USER2") cameraFlag = 1 << 2;
else if(value == "USER3") cameraFlag = 1 << 3;
else if(value == "USER4") cameraFlag = 1 << 4;
}
attribute = attribute->Next();

View File

@ -91,10 +91,10 @@ public:
bool setAttachment (const std::string& slotName, const char* attachmentName);
// --- BlendProtocol
virtual void setBlendFunc (const cocos2d::BlendFunc& blendFunc);
virtual const cocos2d::BlendFunc& getBlendFunc () const;
virtual void setOpacityModifyRGB (bool value);
virtual bool isOpacityModifyRGB () const;
virtual void setBlendFunc (const cocos2d::BlendFunc& blendFunc)override;
virtual const cocos2d::BlendFunc& getBlendFunc () const override;
virtual void setOpacityModifyRGB (bool value)override;
virtual bool isOpacityModifyRGB () const override;
CC_CONSTRUCTOR_ACCESS:
SkeletonRenderer ();

View File

@ -49,8 +49,8 @@ public:
NavMeshDebugDraw();
virtual ~NavMeshDebugDraw();
virtual void depthMask(bool state);
virtual void texture(bool state){};
virtual void depthMask(bool state)override;
virtual void texture(bool state)override{};
virtual void begin(duDebugDrawPrimitives prim, float size = 1.0f) override;
virtual void vertex(const float* pos, unsigned int color) override;

View File

@ -61,7 +61,10 @@
- (void) startRequest:(NSURLRequest *)request
{
#ifdef COCOS2D_DEBUG
NSLog(@"Starting to load %@", srcURL);
#endif
finish = false;
self.responseData = [NSMutableData data];
@ -90,7 +93,9 @@
**/
- (void) connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response {
#ifdef COCOS2D_DEBUG
NSLog(@"Received response from request to url %@", srcURL);
#endif
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
//NSLog(@"All headers = %@", [httpResponse allHeaderFields]);

View File

@ -936,9 +936,12 @@ void PhysicsDebugDraw::drawShape(PhysicsShape& shape)
{
case CP_CIRCLE_SHAPE:
{
float radius = PhysicsHelper::cpfloat2float(cpCircleShapeGetRadius(subShape));
Vec2 centre = PhysicsHelper::cpv2point(cpBodyGetPos(cpShapeGetBody(subShape)))
+ PhysicsHelper::cpv2point(cpCircleShapeGetOffset(subShape));
Vec2 centre = PhysicsHelper::cpv2point(cpBodyGetPos(cpShapeGetBody(subShape)));
Vec2 offset = PhysicsHelper::cpv2point(cpCircleShapeGetOffset(subShape));
Vec2 rotation(PhysicsHelper::cpv2point(cpBodyGetRot(cpShapeGetBody(subShape))));
centre += offset.rotate(rotation);
static const int CIRCLE_SEG_NUM = 12;
Vec2 seg[CIRCLE_SEG_NUM] = {};

View File

@ -41,24 +41,12 @@ THE SOFTWARE.
#endif
#include <sys/stat.h>
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
#include <regex>
#endif
NS_CC_BEGIN
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
#include <ftw.h>
#endif
#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) && (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT)
#include <sys/types.h>
#include <errno.h>
#include <dirent.h>
#endif
// Implement DictMaker
#if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) && (CC_TARGET_PLATFORM != CC_PLATFORM_MAC)
NS_CC_BEGIN
typedef enum
{
SAX_NONE = 0,
@ -370,8 +358,12 @@ static tinyxml2::XMLElement* generateElementForDict(const ValueMap& dict, tinyxm
*/
bool FileUtils::writeToFile(ValueMap& dict, const std::string &fullPath)
{
//CCLOG("tinyxml2 Dictionary %d writeToFile %s", dict->_ID, fullPath.c_str());
tinyxml2::XMLDocument *doc = new tinyxml2::XMLDocument();
return writeValueMapToFile(dict, fullPath);
}
bool FileUtils::writeValueMapToFile(ValueMap& dict, const std::string& fullPath)
{
tinyxml2::XMLDocument *doc = new (std::nothrow)tinyxml2::XMLDocument();
if (nullptr == doc)
return false;
@ -396,7 +388,47 @@ bool FileUtils::writeToFile(ValueMap& dict, const std::string &fullPath)
doc->LinkEndChild(rootEle);
tinyxml2::XMLElement *innerDict = generateElementForDict(dict, doc);
if (nullptr == innerDict )
if (nullptr == innerDict)
{
delete doc;
return false;
}
rootEle->LinkEndChild(innerDict);
bool ret = tinyxml2::XML_SUCCESS == doc->SaveFile(getSuitableFOpen(fullPath).c_str());
delete doc;
return ret;
}
bool FileUtils::writeValueVectorToFile(ValueVector vecData, const std::string& fullPath)
{
tinyxml2::XMLDocument *doc = new (std::nothrow)tinyxml2::XMLDocument();
if (nullptr == doc)
return false;
tinyxml2::XMLDeclaration *declaration = doc->NewDeclaration("xml version=\"1.0\" encoding=\"UTF-8\"");
if (nullptr == declaration)
{
delete doc;
return false;
}
doc->LinkEndChild(declaration);
tinyxml2::XMLElement *docType = doc->NewElement("!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"");
doc->LinkEndChild(docType);
tinyxml2::XMLElement *rootEle = doc->NewElement("plist");
rootEle->SetAttribute("version", "1.0");
if (nullptr == rootEle)
{
delete doc;
return false;
}
doc->LinkEndChild(rootEle);
tinyxml2::XMLElement *innerDict = generateElementForArray(vecData, doc);
if (nullptr == innerDict)
{
delete doc;
return false;
@ -496,7 +528,6 @@ static tinyxml2::XMLElement* generateElementForArray(const ValueVector& array, t
}
#else
NS_CC_BEGIN
/* The subclass FileUtilsApple should override these two method. */
ValueMap FileUtils::getValueMapFromFile(const std::string& filename) {return ValueMap();}
@ -506,6 +537,7 @@ bool FileUtils::writeToFile(ValueMap& dict, const std::string &fullPath) {return
#endif /* (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) && (CC_TARGET_PLATFORM != CC_PLATFORM_MAC) */
// Implement FileUtils
FileUtils* FileUtils::s_sharedFileUtils = nullptr;
void FileUtils::destroyInstance()
@ -530,7 +562,38 @@ FileUtils::~FileUtils()
{
}
bool FileUtils::writeStringToFile(std::string dataStr, const std::string& fullPath)
{
Data retData;
retData.copy((unsigned char*)dataStr.c_str(), dataStr.size());
return writeDataToFile(retData, fullPath);
}
bool FileUtils::writeDataToFile(Data retData, const std::string& fullPath)
{
size_t size = 0;
const char* mode = "wb";
CCASSERT(!fullPath.empty() && retData.getSize() != 0, "Invalid parameters.");
auto fileutils = FileUtils::getInstance();
do
{
// Read the file from hardware
FILE *fp = fopen(fileutils->getSuitableFOpen(fullPath).c_str(), mode);
CC_BREAK_IF(!fp);
size = retData.getSize();
fwrite(retData.getBytes(), size, 1, fp);
fclose(fp);
return true;
} while (0);
return false;
}
bool FileUtils::init()
{
@ -962,36 +1025,6 @@ bool FileUtils::isAbsolutePath(const std::string& path) const
return (path[0] == '/');
}
bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
WIN32_FILE_ATTRIBUTE_DATA wfad;
std::wstring wdirPath(dirPath.begin(), dirPath.end());
if (GetFileAttributesEx(wdirPath.c_str(), GetFileExInfoStandard, &wfad))
{
return true;
}
return false;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
unsigned long fAttrib = GetFileAttributesA(dirPath.c_str());
if (fAttrib != INVALID_FILE_ATTRIBUTES &&
(fAttrib & FILE_ATTRIBUTE_DIRECTORY))
{
return true;
}
return false;
#else
struct stat st;
if (stat(dirPath.c_str(), &st) == 0)
{
return S_ISDIR(st.st_mode);
}
return false;
#endif
}
bool FileUtils::isDirectoryExist(const std::string& dirPath) const
{
CCASSERT(!dirPath.empty(), "Invalid path");
@ -1022,7 +1055,60 @@ bool FileUtils::isDirectoryExist(const std::string& dirPath) const
}
}
}
return false;
}
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
// windows os implement should override in platform specific FileUtiles class
bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const
{
CCASSERT(false, "FileUtils not support isDirectoryExistInternal");
return false;
}
bool FileUtils::createDirectory(const std::string& path)
{
CCASSERT(false, "FileUtils not support createDirectory");
return false;
}
bool FileUtils::removeDirectory(const std::string& path)
{
CCASSERT(false, "FileUtils not support removeDirectory");
return false;
}
bool FileUtils::removeFile(const std::string &path)
{
CCASSERT(false, "FileUtils not support removeFile");
return false;
}
bool FileUtils::renameFile(const std::string &path, const std::string &oldname, const std::string &name)
{
CCASSERT(false, "FileUtils not support renameFile");
return false;
}
std::string FileUtils::getSuitableFOpen(const std::string& filenameUtf8) const
{
CCASSERT(false, "getSuitableFOpen should be override by platform FileUtils");
return filenameUtf8;
}
#else
// default implements for unix like os
#include <sys/types.h>
#include <errno.h>
#include <dirent.h>
bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const
{
struct stat st;
if (stat(dirPath.c_str(), &st) == 0)
{
return S_ISDIR(st.st_mode);
}
return false;
}
@ -1059,47 +1145,6 @@ bool FileUtils::createDirectory(const std::string& path)
}
}
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
WIN32_FILE_ATTRIBUTE_DATA wfad;
std::wstring wpath(path.begin(), path.end());
if (!(GetFileAttributesEx(wpath.c_str(), GetFileExInfoStandard, &wfad)))
{
subpath = "";
for(unsigned int i = 0 ; i < dirs.size() ; ++i)
{
subpath += dirs[i];
if (i > 0 && !isDirectoryExist(subpath))
{
std::wstring wsubpath(subpath.begin(), subpath.end());
BOOL ret = CreateDirectory(wsubpath.c_str(), NULL);
if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
{
return false;
}
}
}
}
return true;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
if ((GetFileAttributesA(path.c_str())) == INVALID_FILE_ATTRIBUTES)
{
subpath = "";
for (unsigned int i = 0; i < dirs.size(); ++i)
{
subpath += dirs[i];
if (!isDirectoryExist(subpath))
{
BOOL ret = CreateDirectoryA(subpath.c_str(), NULL);
if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
{
return false;
}
}
}
}
return true;
#else
DIR *dir = NULL;
// Create path recursively
@ -1128,22 +1173,8 @@ bool FileUtils::createDirectory(const std::string& path)
}
}
return true;
#endif
}
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
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);
}
return ret;
}
#endif
bool FileUtils::removeDirectory(const std::string& path)
{
if (path.size() > 0 && path[path.size() - 1] != '/')
@ -1152,58 +1183,6 @@ bool FileUtils::removeDirectory(const std::string& path)
return false;
}
// Remove downloaded files
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
std::wstring wpath = std::wstring(path.begin(), path.end());
std::wstring files = wpath + L"*.*";
WIN32_FIND_DATA wfd;
HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0);
bool ret=true;
if (search!=INVALID_HANDLE_VALUE)
{
BOOL find=true;
while (find)
{
//. ..
if(wfd.cFileName[0]!='.')
{
std::wstring temp = wpath + wfd.cFileName;
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
temp += '/';
ret = ret && this->removeDirectory(std::string(temp.begin(), temp.end()));
}
else
{
SetFileAttributes(temp.c_str(), FILE_ATTRIBUTE_NORMAL);
ret = ret && DeleteFile(temp.c_str());
}
}
find = FindNextFile(search, &wfd);
}
FindClose(search);
}
if (ret && RemoveDirectory(wpath.c_str()))
{
return true;
}
return false;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
std::string command = "cmd /c rd /s /q ";
// Path may include space.
command += "\"" + path + "\"";
if (WinExec(command.c_str(), SW_HIDE) > 31)
return true;
else
return false;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
if (nftw(path.c_str(),unlink_cb, 64, FTW_DEPTH | FTW_PHYS))
return false;
else
return true;
#else
std::string command = "rm -r ";
// Path may include space.
command += "\"" + path + "\"";
@ -1211,44 +1190,15 @@ bool FileUtils::removeDirectory(const std::string& path)
return true;
else
return false;
#endif
}
bool FileUtils::removeFile(const std::string &path)
{
// Remove downloaded file
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
std::wstring wpath(path.begin(), path.end());
if (DeleteFile(wpath.c_str()))
{
return true;
}
return false;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
std::string command = "cmd /c del /q ";
std::string win32path = path;
int len = win32path.length();
for (int i = 0; i < len; ++i)
{
if (win32path[i] == '/')
{
win32path[i] = '\\';
}
}
command += win32path;
if (WinExec(command.c_str(), SW_HIDE) > 31)
return true;
else
return false;
#else
if (remove(path.c_str())) {
return false;
} else {
return true;
}
#endif
}
bool FileUtils::renameFile(const std::string &path, const std::string &oldname, const std::string &name)
@ -1257,41 +1207,6 @@ bool FileUtils::renameFile(const std::string &path, const std::string &oldname,
std::string oldPath = path + oldname;
std::string newPath = path + name;
// Rename a file
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
std::regex pat("\\/");
std::string _old = std::regex_replace(oldPath, pat, "\\");
std::string _new = std::regex_replace(newPath, pat, "\\");
if (MoveFileEx(std::wstring(_old.begin(), _old.end()).c_str(),
std::wstring(_new.begin(), _new.end()).c_str(),
MOVEFILE_REPLACE_EXISTING & MOVEFILE_WRITE_THROUGH))
{
return true;
}
return false;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
std::regex pat("\\/");
std::string _old = std::regex_replace(oldPath, pat, "\\");
std::string _new = std::regex_replace(newPath, pat, "\\");
if(FileUtils::getInstance()->isFileExist(_new))
{
if (!DeleteFileA(_new.c_str()))
{
CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newPath.c_str(), GetLastError());
}
}
if (MoveFileA(_old.c_str(), _new.c_str()))
{
return true;
}
else
{
CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldPath.c_str(), newPath.c_str(), GetLastError());
return false;
}
#else
int errorCode = rename(oldPath.c_str(), newPath.c_str());
if (0 != errorCode)
@ -1300,9 +1215,15 @@ bool FileUtils::renameFile(const std::string &path, const std::string &oldname,
return false;
}
return true;
#endif
}
std::string FileUtils::getSuitableFOpen(const std::string& filenameUtf8) const
{
return filenameUtf8;
}
#endif
long FileUtils::getFileSize(const std::string &filepath)
{
CCASSERT(!filepath.empty(), "Invalid path");
@ -1346,67 +1267,5 @@ bool FileUtils::isPopupNotify() const
return s_popupNotify;
}
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
static std::wstring StringUtf8ToWideChar(const std::string& strUtf8)
{
std::wstring ret;
if (!strUtf8.empty())
{
int nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, nullptr, 0);
if (nNum)
{
WCHAR* wideCharString = new WCHAR[nNum + 1];
wideCharString[0] = 0;
nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, wideCharString, nNum + 1);
ret = wideCharString;
delete[] wideCharString;
}
else
{
CCLOG("Wrong convert to WideChar code:0x%x", GetLastError());
}
}
return ret;
}
static std::string UTF8StringToMultiByte(const std::string& strUtf8)
{
std::string ret;
if (!strUtf8.empty())
{
std::wstring strWideChar = StringUtf8ToWideChar(strUtf8);
int nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE);
if (nNum)
{
char* ansiString = new char[nNum + 1];
ansiString[0] = 0;
nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, ansiString, nNum + 1, nullptr, FALSE);
ret = ansiString;
delete[] ansiString;
}
else
{
CCLOG("Wrong convert to Ansi code:0x%x", GetLastError());
}
}
return ret;
}
std::string FileUtils::getSuitableFOpen(const std::string& filenameUtf8) const
{
return UTF8StringToMultiByte(filenameUtf8);
}
#else
std::string FileUtils::getSuitableFOpen(const std::string& filenameUtf8) const
{
return filenameUtf8;
}
#endif
NS_CC_END

View File

@ -321,15 +321,58 @@ public:
*/
virtual ValueMap getValueMapFromFile(const std::string& filename);
// Converts the contents of a file to a ValueMap.
// This method is used internally.
/** Converts the contents of a file to a ValueMap.
* This method is used internally.
*/
virtual ValueMap getValueMapFromData(const char* filedata, int filesize);
// Write a ValueMap to a plist file.
// This method is used internally.
/**
* write a ValueMap into a plist file
*
*@param dict the ValueMap want to save
*@param fullPath The full path to the file you want to save a string
*@return bool
*/
virtual bool writeToFile(ValueMap& dict, const std::string& fullPath);
/**
* write a string into a file
*
* @param dataStr the string want to save
* @param fullPath The full path to the file you want to save a string
* @return bool True if write success
*/
virtual bool writeStringToFile(std::string dataStr, const std::string& fullPath);
/**
* write Data into a file
*
*@param retData the data want to save
*@param fullPath The full path to the file you want to save a string
*@return bool
*/
virtual bool writeDataToFile(Data retData, const std::string& fullPath);
/**
* write ValueMap into a plist file
*
*@param dict the ValueMap want to save
*@param fullPath The full path to the file you want to save a string
*@return bool
*/
virtual bool writeValueMapToFile(ValueMap& dict, const std::string& fullPath);
/**
* write ValueVector into a plist file
*
*@param vecData the ValueVector want to save
*@param fullPath The full path to the file you want to save a string
*@return bool
*/
virtual bool writeValueVectorToFile(ValueVector vecData, const std::string& fullPath);
/**
* Windows fopen can't support UTF-8 filename
* Need convert all parameters fopen and other 3rd-party libs

View File

@ -486,33 +486,12 @@ bool Image::initWithImageFile(const std::string& path)
bool ret = false;
_filePath = FileUtils::getInstance()->fullPathForFilename(path);
#ifdef EMSCRIPTEN
// Emscripten includes a re-implementation of SDL that uses HTML5 canvas
// operations underneath. Consequently, loading images via IMG_Load (an SDL
// API) will be a lot faster than running libpng et al as compiled with
// Emscripten.
SDL_Surface *iSurf = IMG_Load(fullPath.c_str());
int size = 4 * (iSurf->w * iSurf->h);
ret = initWithRawData((const unsigned char*)iSurf->pixels, size, iSurf->w, iSurf->h, 8, true);
unsigned int *tmp = (unsigned int *)_data;
int nrPixels = iSurf->w * iSurf->h;
for(int i = 0; i < nrPixels; i++)
{
unsigned char *p = _data + i * 4;
tmp[i] = CC_RGB_PREMULTIPLY_ALPHA( p[0], p[1], p[2], p[3] );
}
SDL_FreeSurface(iSurf);
#else
Data data = FileUtils::getInstance()->getDataFromFile(_filePath);
if (!data.isNull())
{
ret = initWithImageData(data.getBytes(), data.getSize());
}
#endif // EMSCRIPTEN
return ret;
}

View File

@ -77,7 +77,7 @@ void Application::setAnimationInterval(float interval)
{
JniMethodInfo methodInfo;
if (! JniHelper::getStaticMethodInfo(methodInfo, "org/cocos2dx/lib/Cocos2dxRenderer", "setAnimationInterval",
"(D)V"))
"(F)V"))
{
CCLOG("%s %d: error to get methodInfo", __FILE__, __LINE__);
}

View File

@ -33,6 +33,7 @@ THE SOFTWARE.
#include "android/asset_manager_jni.h"
#include "jni/CocosPlayClient.h"
#include <stdlib.h>
#include <sys/stat.h>
#define LOG_TAG "CCFileUtils-android.cpp"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
@ -187,6 +188,59 @@ bool FileUtilsAndroid::isFileExistInternal(const std::string& strFilePath) const
return bFound;
}
bool FileUtilsAndroid::isDirectoryExistInternal(const std::string& dirPath) const
{
if (dirPath.empty())
{
return false;
}
const char* s = dirPath.c_str();
bool startWithAssets = (dirPath.find("assets/") == 0);
int lenOfAssets = 7;
std::string tmpStr;
if (cocosplay::isEnabled() && !cocosplay::isDemo())
{
// redirect assets/*** path to cocosplay resource dir
tmpStr.append(_defaultResRootPath);
if ('/' != tmpStr[tmpStr.length() - 1])
{
tmpStr += '/';
}
tmpStr.append(s + lenOfAssets);
}
// find absolute path in flash memory
if (s[0] == '/')
{
CCLOG("find in flash memory dirPath(%s)", s);
struct stat st;
if (stat(s, &st) == 0)
{
return S_ISDIR(st.st_mode);
}
}
// find it in apk's assets dir
// Found "assets/" at the beginning of the path and we don't want it
CCLOG("find in apk dirPath(%s)", s);
if (startWithAssets)
{
s += lenOfAssets;
}
if (FileUtilsAndroid::assetmanager)
{
AAssetDir* aa = AAssetManager_openDir(FileUtilsAndroid::assetmanager, s);
if (aa && AAssetDir_getNextFileName(aa))
{
AAssetDir_close(aa);
return true;
}
}
return false;
}
bool FileUtilsAndroid::isAbsolutePath(const std::string& strPath) const
{
// On Android, there are two situations for full path.

View File

@ -81,7 +81,8 @@ public:
virtual bool isAbsolutePath(const std::string& strPath) const;
private:
virtual bool isFileExistInternal(const std::string& strFilePath) const;
virtual bool isFileExistInternal(const std::string& strFilePath) const override;
virtual bool isDirectoryExistInternal(const std::string& dirPath) const override;
Data getData(const std::string& filename, bool forString);
static AAssetManager* assetmanager;

View File

@ -62,7 +62,7 @@ OnSimpleStickListener, OnAccListener, OnGyroListener, OnStateListener, GameContr
public void onCreate(Context context) {
mContext = context;
mControllerService = Controller.getControllerService();
mControllerService = Controller.getControllerService(context);
if (mControllerService != null) {
mControllerService.setControllerServiceListener(this);
mControllerService.setStateListener(this);
@ -70,7 +70,7 @@ OnSimpleStickListener, OnAccListener, OnGyroListener, OnStateListener, GameContr
mControllerService.setSimpleStickListener(this);
//mControllerService.setAccListener(this);
//mControllerService.setGyroListener(this);
mControllerService.setEnableLR2(true);
mControllerService.setEnableL2R2(true);
mControllerService.setAutoKeyUpMode(false);
mControllerService.checkNibiruInstall(mContext, false);
@ -114,11 +114,11 @@ OnSimpleStickListener, OnAccListener, OnGyroListener, OnStateListener, GameContr
if( !mControllerService.hasDeviceConnected() ){
Bundle bun = new Bundle();
bun.putBoolean(ControllerService.FLAG_IS_SHOW_GAMEPAD_TIP, false);
try {
/*try {
mControllerService.showDeviceManagerUI(mContext, bun);
} catch (ControllerServiceException e) {
e.printStackTrace();
}
}*/
}
}
}

View File

@ -35,14 +35,6 @@ public class GameControllerOuya implements GameControllerDelegate{
public void onCreate(Context context) {
OuyaController.init(context);
/*GameControllerAdapter.addRunnableToFrameStartList(new Runnable() {
@Override
public void run() {
OuyaController.startOfFrame();
}
});*/
}
private float mOldLeftThumbstickX = 0.0f;

View File

@ -44,7 +44,9 @@ import android.preference.PreferenceManager.OnActivityResultListener;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.opengl.GLSurfaceView;
import java.util.Arrays;
import java.util.Comparator;
public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelperListener {
// ===========================================================
@ -76,31 +78,6 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
configAttribs = attribs;
}
public EGLConfig selectConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs, int[] attribs)
{
for (EGLConfig config : configs) {
int d = findConfigAttrib(egl, display, config,
EGL10.EGL_DEPTH_SIZE, 0);
int s = findConfigAttrib(egl, display, config,
EGL10.EGL_STENCIL_SIZE, 0);
if ((d >= attribs[4]) && (s >= attribs[5])) {
int r = findConfigAttrib(egl, display, config,
EGL10.EGL_RED_SIZE, 0);
int g = findConfigAttrib(egl, display, config,
EGL10.EGL_GREEN_SIZE, 0);
int b = findConfigAttrib(egl, display, config,
EGL10.EGL_BLUE_SIZE, 0);
int a = findConfigAttrib(egl, display, config,
EGL10.EGL_ALPHA_SIZE, 0);
if ((r >= attribs[0]) && (g >= attribs[1])
&& (b >= attribs[2]) && (a >= attribs[3])) {
return config;
}
}
}
return null;
}
private int findConfigAttrib(EGL10 egl, EGLDisplay display,
EGLConfig config, int attribute, int defaultValue) {
int[] value = new int[1];
@ -110,13 +87,76 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
return defaultValue;
}
class ConfigValue implements Comparable<ConfigValue> {
public EGLConfig config = null;
public int[] configAttribs = null;
public int value = 0;
private void calcValue() {
// depth factor 29bit and [6,12)bit
if (configAttribs[4] > 0) {
value = value + (1 << 29) + ((configAttribs[4]%64) << 6);
}
// stencil factor 28bit and [0, 6)bit
if (configAttribs[5] > 0) {
value = value + (1 << 28) + ((configAttribs[5]%64));
}
// alpha factor 30bit and [24, 28)bit
if (configAttribs[3] > 0) {
value = value + (1 << 30) + ((configAttribs[3]%16) << 24);
}
// green factor [20, 24)bit
if (configAttribs[1] > 0) {
value = value + ((configAttribs[1]%16) << 20);
}
// blue factor [16, 20)bit
if (configAttribs[2] > 0) {
value = value + ((configAttribs[2]%16) << 16);
}
// red factor [12, 16)bit
if (configAttribs[0] > 0) {
value = value + ((configAttribs[0]%16) << 12);
}
}
public ConfigValue(int[] attribs) {
configAttribs = attribs;
calcValue();
}
public ConfigValue(EGL10 egl, EGLDisplay display, EGLConfig config) {
this.config = config;
configAttribs = new int[6];
configAttribs[0] = findConfigAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0);
configAttribs[1] = findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0);
configAttribs[2] = findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0);
configAttribs[3] = findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0);
configAttribs[4] = findConfigAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0);
configAttribs[5] = findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0);
calcValue();
}
@Override
public int compareTo(ConfigValue another) {
if (value < another.value) {
return -1;
} else if (value > another.value) {
return 1;
} else {
return 0;
}
}
@Override
public String toString() {
return "{ color: " + configAttribs[3] + configAttribs[2] + configAttribs[1] + configAttribs[0] +
"; depth: " + configAttribs[4] + "; stencil: " + configAttribs[5] + ";}";
}
}
@Override
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display)
{
int[] numConfigs = new int[1];
if(egl.eglGetConfigs(display, null, 0, numConfigs))
{
EGLConfig[] configs = new EGLConfig[numConfigs[0]];
int[] EGLattribs = {
EGL10.EGL_RED_SIZE, configAttribs[0],
EGL10.EGL_GREEN_SIZE, configAttribs[1],
@ -127,58 +167,50 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
EGL10.EGL_RENDERABLE_TYPE, 4, //EGL_OPENGL_ES2_BIT
EGL10.EGL_NONE
};
int[] choosedConfigNum = new int[1];
EGLConfig[] configs = new EGLConfig[1];
int[] numConfigs = new int[1];
egl.eglChooseConfig(display, EGLattribs, configs, numConfigs[0], choosedConfigNum);
if(choosedConfigNum[0]>0)
{
return selectConfig(egl, display, configs, configAttribs);
if (egl.eglChooseConfig(display, EGLattribs, configs, 1, numConfigs)) {
return configs[0];
}
else
{
int[] defaultEGLattribs = {
EGL10.EGL_RED_SIZE, 5,
EGL10.EGL_GREEN_SIZE, 6,
EGL10.EGL_BLUE_SIZE, 5,
EGL10.EGL_ALPHA_SIZE, 0,
EGL10.EGL_DEPTH_SIZE, 0,
EGL10.EGL_STENCIL_SIZE,0,
// there's no config match the specific configAttribs, we should choose a closest one
int[] EGLV2attribs = {
EGL10.EGL_RENDERABLE_TYPE, 4, //EGL_OPENGL_ES2_BIT
EGL10.EGL_NONE
};
int[] defaultEGLattribsAlpha = {
EGL10.EGL_RED_SIZE, 4,
EGL10.EGL_GREEN_SIZE, 4,
EGL10.EGL_BLUE_SIZE, 4,
EGL10.EGL_ALPHA_SIZE, 4,
EGL10.EGL_DEPTH_SIZE, 0,
EGL10.EGL_STENCIL_SIZE,0,
EGL10.EGL_RENDERABLE_TYPE, 4, //EGL_OPENGL_ES2_BIT
EGL10.EGL_NONE
};
int[] attribs = null;
//choose one can use
if(this.configAttribs[3] == 0)
{
egl.eglChooseConfig(display, defaultEGLattribs, configs, numConfigs[0], choosedConfigNum);
attribs = new int[]{5,6,5,0,0,0};
if(egl.eglChooseConfig(display, EGLV2attribs, null, 0, numConfigs)) {
int num = numConfigs[0];
ConfigValue[] cfgVals = new ConfigValue[num];
// convert all config to ConfigValue
configs = new EGLConfig[num];
egl.eglChooseConfig(display, EGLV2attribs, configs, num, numConfigs);
for (int i = 0; i < num; ++i) {
cfgVals[i] = new ConfigValue(egl, display, configs[i]);
}
else
{
egl.eglChooseConfig(display, defaultEGLattribsAlpha, configs, numConfigs[0], choosedConfigNum);
attribs = new int[]{4,4,4,4,0,0};
}
if(choosedConfigNum[0] > 0)
{
return selectConfig(egl, display, configs, attribs);
}
else
{
Log.e(DEVICE_POLICY_SERVICE, "Can not select an EGLConfig for rendering.");
return null;
ConfigValue e = new ConfigValue(configAttribs);
// bin search
int lo = 0;
int hi = num;
int mi;
while (lo < hi - 1) {
mi = (lo + hi) / 2;
if (e.compareTo(cfgVals[mi]) < 0) {
hi = mi;
} else {
lo = mi;
}
}
if (lo != num - 1) {
lo = lo + 1;
}
Log.w("cocos2d", "Can't find EGLConfig match: " + e + ", instead of closest one:" + cfgVals[lo]);
return cfgVals[lo].config;
}
Log.e(DEVICE_POLICY_SERVICE, "Can not select an EGLConfig for rendering.");
return null;
}
@ -252,17 +284,23 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
@Override
protected void onResume() {
super.onResume();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
Cocos2dxHelper.onResume();
this.mGLSurfaceView.onResume();
mGLSurfaceView.onResume();
}
}
@Override
protected void onPause() {
super.onPause();
Cocos2dxHelper.onPause();
this.mGLSurfaceView.onPause();
mGLSurfaceView.onPause();
}
@Override

View File

@ -91,11 +91,11 @@ public class Cocos2dxHelper {
private static boolean sInited = false;
public static void init(final Activity activity) {
sActivity = activity;
Cocos2dxHelper.sCocos2dxHelperListener = (Cocos2dxHelperListener)activity;
if (!sInited) {
final ApplicationInfo applicationInfo = activity.getApplicationInfo();
Cocos2dxHelper.sCocos2dxHelperListener = (Cocos2dxHelperListener)activity;
Cocos2dxHelper.sPackageName = applicationInfo.packageName;
if (CocosPlayClient.isEnabled() && !CocosPlayClient.isDemo()) {
Cocos2dxHelper.sFileDirectory = CocosPlayClient.getGameRoot();
@ -113,7 +113,6 @@ public class Cocos2dxHelper {
Cocos2dxHelper.nativeSetContext((Context)activity, Cocos2dxHelper.sAssetManager);
Cocos2dxBitmap.setContext(activity);
sActivity = activity;
Cocos2dxHelper.sVibrateService = (Vibrator)activity.getSystemService(Context.VIBRATOR_SERVICE);

View File

@ -50,13 +50,15 @@ public:
virtual std::string getFullPathForDirectoryAndFilename(const std::string& directory, const std::string& filename) const override;
virtual ValueMap getValueMapFromFile(const std::string& filename) override;
virtual ValueMap getValueMapFromData(const char* filedata, int filesize);
virtual ValueMap getValueMapFromData(const char* filedata, int filesize)override;
virtual bool writeToFile(ValueMap& dict, const std::string& fullPath) override;
virtual ValueVector getValueVectorFromFile(const std::string& filename) override;
void setBundle(NSBundle* bundle);
private:
virtual bool isFileExistInternal(const std::string& filePath) const override;
virtual bool removeDirectory(const std::string& dirPath) override;
NSBundle* getBundle() const;
NSBundle* _bundle;
};

View File

@ -27,6 +27,8 @@ THE SOFTWARE.
#include "CCFileUtils-apple.h"
#include <ftw.h>
#include <string>
#include <stack>
@ -392,6 +394,31 @@ bool FileUtilsApple::isFileExistInternal(const std::string& filePath) const
return ret;
}
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);
}
return ret;
}
bool FileUtilsApple::removeDirectory(const std::string& path)
{
if (path.size() > 0 && path[path.size() - 1] != '/')
{
CCLOGERROR("Fail to remove directory, path must termniate with '/': %s", path.c_str());
return false;
}
if (nftw(path.c_str(),unlink_cb, 64, FTW_DEPTH | FTW_PHYS))
return false;
else
return true;
}
std::string FileUtilsApple::getFullPathForDirectoryAndFilename(const std::string& directory, const std::string& filename) const
{
if (directory[0] != '/')
@ -455,6 +482,12 @@ ValueMap FileUtilsApple::getValueMapFromData(const char* filedata, int filesize)
bool FileUtilsApple::writeToFile(ValueMap& dict, const std::string &fullPath)
{
return writeValueMapToFile(dict, fullPath);
}
bool FileUtils::writeValueMapToFile(ValueMap& dict, const std::string& fullPath)
{
//CCLOG("iOS||Mac Dictionary %d write to file %s", dict->_ID, fullPath.c_str());
NSMutableDictionary *nsDict = [NSMutableDictionary dictionary];
@ -470,6 +503,20 @@ bool FileUtilsApple::writeToFile(ValueMap& dict, const std::string &fullPath)
return true;
}
bool FileUtils::writeValueVectorToFile(ValueVector vecData, const std::string& fullPath)
{
NSString* path = [NSString stringWithUTF8String:fullPath.c_str()];
NSMutableArray* array = [NSMutableArray array];
for (const auto &e : vecData)
{
addObjectToNSArray(e, array);
}
[array writeToFile:path atomically:YES];
return true;
}
ValueVector FileUtilsApple::getValueVectorFromFile(const std::string& filename)
{
// NSString* pPath = [NSString stringWithUTF8String:pFileName];

View File

@ -35,6 +35,7 @@ THE SOFTWARE.
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#ifndef CC_RESOURCE_FOLDER_LINUX
#define CC_RESOURCE_FOLDER_LINUX ("/Resources/")

View File

@ -52,7 +52,7 @@ public:
bool init();
virtual std::string getWritablePath() const;
private:
virtual bool isFileExistInternal(const std::string& strFilePath) const;
virtual bool isFileExistInternal(const std::string& strFilePath) const override;
};
// end of platform group

View File

@ -30,6 +30,7 @@ THE SOFTWARE.
#include "platform/CCCommon.h"
#include <Shlobj.h>
#include <cstdlib>
#include <regex>
using namespace std;
@ -56,6 +57,81 @@ static inline std::string convertPathFormatToUnixStyle(const std::string& path)
return ret;
}
static std::wstring StringUtf8ToWideChar(const std::string& strUtf8)
{
std::wstring ret;
if (!strUtf8.empty())
{
int nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, nullptr, 0);
if (nNum)
{
WCHAR* wideCharString = new WCHAR[nNum + 1];
wideCharString[0] = 0;
nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, wideCharString, nNum + 1);
ret = wideCharString;
delete[] wideCharString;
}
else
{
CCLOG("Wrong convert to WideChar code:0x%x", GetLastError());
}
}
return ret;
}
static std::string StringWideCharToUtf8(const std::wstring& strWideChar)
{
std::string ret;
if (!strWideChar.empty())
{
int nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE);
if (nNum)
{
char* utf8String = new char[nNum + 1];
utf8String[0] = 0;
nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, utf8String, nNum + 1, nullptr, FALSE);
ret = utf8String;
delete[] utf8String;
}
else
{
CCLOG("Wrong convert to Utf8 code:0x%x", GetLastError());
}
}
return ret;
}
static std::string UTF8StringToMultiByte(const std::string& strUtf8)
{
std::string ret;
if (!strUtf8.empty())
{
std::wstring strWideChar = StringUtf8ToWideChar(strUtf8);
int nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE);
if (nNum)
{
char* ansiString = new char[nNum + 1];
ansiString[0] = 0;
nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, ansiString, nNum + 1, nullptr, FALSE);
ret = ansiString;
delete[] ansiString;
}
else
{
CCLOG("Wrong convert to Ansi code:0x%x", GetLastError());
}
}
return ret;
}
static void _checkPath()
{
if (0 == s_resourcePath.length())
@ -99,6 +175,22 @@ bool FileUtilsWin32::init()
return FileUtils::init();
}
bool FileUtilsWin32::isDirectoryExistInternal(const std::string& dirPath) const
{
unsigned long fAttrib = GetFileAttributes(StringUtf8ToWideChar(dirPath).c_str());
if (fAttrib != INVALID_FILE_ATTRIBUTES &&
(fAttrib & FILE_ATTRIBUTE_DIRECTORY))
{
return true;
}
return false;
}
std::string FileUtilsWin32::getSuitableFOpen(const std::string& filenameUtf8) const
{
return UTF8StringToMultiByte(filenameUtf8);
}
bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const
{
if (0 == strFilePath.length())
@ -112,10 +204,7 @@ bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const
strPath.insert(0, _defaultResRootPath);
}
WCHAR utf16Buf[CC_MAX_PATH] = {0};
MultiByteToWideChar(CP_UTF8, 0, strPath.c_str(), -1, utf16Buf, sizeof(utf16Buf)/sizeof(utf16Buf[0]));
DWORD attr = GetFileAttributesW(utf16Buf);
DWORD attr = GetFileAttributesW(StringUtf8ToWideChar(strPath).c_str());
if(attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY))
return false; // not a file
return true;
@ -162,7 +251,6 @@ static bool checkFileName(const std::string& fullPath, const std::string& filena
CCLOG("%s", msg.c_str());
return false;
}
}
else
{
@ -193,12 +281,9 @@ static Data getData(const std::string& filename, bool forString)
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename);
// check if the filename uses correct case characters
CC_BREAK_IF(!checkFileName(fullPath, filename));
checkFileName(fullPath, filename);
WCHAR wszBuf[CC_MAX_PATH] = {0};
MultiByteToWideChar(CP_UTF8, 0, fullPath.c_str(), -1, wszBuf, sizeof(wszBuf)/sizeof(wszBuf[0]));
HANDLE fileHandle = ::CreateFileW(wszBuf, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr);
HANDLE fileHandle = ::CreateFile(StringUtf8ToWideChar(fullPath).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr);
CC_BREAK_IF(fileHandle == INVALID_HANDLE_VALUE);
size = ::GetFileSize(fileHandle, nullptr);
@ -278,12 +363,9 @@ unsigned char* FileUtilsWin32::getFileData(const std::string& filename, const ch
std::string fullPath = fullPathForFilename(filename);
// check if the filename uses correct case characters
CC_BREAK_IF(!checkFileName(fullPath, filename));
checkFileName(fullPath, filename);
WCHAR wszBuf[CC_MAX_PATH] = {0};
MultiByteToWideChar(CP_UTF8, 0, fullPath.c_str(), -1, wszBuf, sizeof(wszBuf)/sizeof(wszBuf[0]));
HANDLE fileHandle = ::CreateFileW(wszBuf, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr);
HANDLE fileHandle = ::CreateFile(StringUtf8ToWideChar(fullPath).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr);
CC_BREAK_IF(fileHandle == INVALID_HANDLE_VALUE);
*size = ::GetFileSize(fileHandle, nullptr);
@ -340,49 +422,191 @@ string FileUtilsWin32::getWritablePath() const
}
// Get full path of executable, e.g. c:\Program Files (x86)\My Game Folder\MyGame.exe
char full_path[CC_MAX_PATH + 1];
::GetModuleFileNameA(nullptr, full_path, CC_MAX_PATH + 1);
WCHAR full_path[CC_MAX_PATH + 1] = { 0 };
::GetModuleFileName(nullptr, full_path, CC_MAX_PATH + 1);
// Debug app uses executable directory; Non-debug app uses local app data directory
//#ifndef _DEBUG
// Get filename of executable only, e.g. MyGame.exe
char *base_name = strrchr(full_path, '\\');
WCHAR *base_name = wcsrchr(full_path, '\\');
wstring retPath;
if(base_name)
{
char app_data_path[CC_MAX_PATH + 1];
WCHAR app_data_path[CC_MAX_PATH + 1];
// Get local app data directory, e.g. C:\Documents and Settings\username\Local Settings\Application Data
if (SUCCEEDED(SHGetFolderPathA(nullptr, CSIDL_LOCAL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, app_data_path)))
if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_LOCAL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, app_data_path)))
{
string ret((char*)app_data_path);
wstring ret(app_data_path);
// Adding executable filename, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame.exe
ret += base_name;
// Remove ".exe" extension, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame
ret = ret.substr(0, ret.rfind("."));
ret = ret.substr(0, ret.rfind(L"."));
ret += "\\";
ret += L"\\";
// Create directory
if (SUCCEEDED(SHCreateDirectoryExA(nullptr, ret.c_str(), nullptr)))
if (SUCCEEDED(SHCreateDirectoryEx(nullptr, ret.c_str(), nullptr)))
{
return convertPathFormatToUnixStyle(ret);
retPath = ret;
}
}
}
if (retPath.empty())
//#endif // not defined _DEBUG
{
// If fetching of local app data directory fails, use the executable one
string ret((char*)full_path);
retPath = full_path;
// remove xxx.exe
ret = ret.substr(0, ret.rfind("\\") + 1);
retPath = retPath.substr(0, retPath.rfind(L"\\") + 1);
}
ret = convertPathFormatToUnixStyle(ret);
return convertPathFormatToUnixStyle(StringWideCharToUtf8(retPath));
}
return ret;
bool FileUtilsWin32::renameFile(const std::string &path, const std::string &oldname, const std::string &name)
{
CCASSERT(!path.empty(), "Invalid path");
std::string oldPath = path + oldname;
std::string newPath = path + name;
std::regex pat("\\/");
std::string _old = std::regex_replace(oldPath, pat, "\\");
std::string _new = std::regex_replace(newPath, pat, "\\");
std::wstring _wNew = StringUtf8ToWideChar(_new);
if (FileUtils::getInstance()->isFileExist(_new))
{
if (!DeleteFile(_wNew.c_str()))
{
CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newPath.c_str(), GetLastError());
}
}
if (MoveFile(StringUtf8ToWideChar(_old).c_str(), _wNew.c_str()))
{
return true;
}
else
{
CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldPath.c_str(), newPath.c_str(), GetLastError());
return false;
}
}
bool FileUtilsWin32::createDirectory(const std::string& dirPath)
{
CCASSERT(!dirPath.empty(), "Invalid path");
if (isDirectoryExist(dirPath))
return true;
std::wstring path = StringUtf8ToWideChar(dirPath);
// Split the path
size_t start = 0;
size_t found = path.find_first_of(L"/\\", start);
std::wstring subpath;
std::vector<std::wstring> dirs;
if (found != std::wstring::npos)
{
while (true)
{
subpath = path.substr(start, found - start + 1);
if (!subpath.empty())
dirs.push_back(subpath);
start = found + 1;
found = path.find_first_of(L"/\\", start);
if (found == std::wstring::npos)
{
if (start < path.length())
{
dirs.push_back(path.substr(start));
}
break;
}
}
}
if ((GetFileAttributes(path.c_str())) == INVALID_FILE_ATTRIBUTES)
{
subpath = L"";
for (unsigned int i = 0; i < dirs.size(); ++i)
{
subpath += dirs[i];
std::string utf8Path = StringWideCharToUtf8(subpath);
if (!isDirectoryExist(utf8Path))
{
BOOL ret = CreateDirectory(subpath.c_str(), NULL);
if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
{
CCLOGERROR("Fail create directory %s !Error code is 0x%x", utf8Path.c_str(), GetLastError());
return false;
}
}
}
}
return true;
}
bool FileUtilsWin32::removeFile(const std::string &filepath)
{
std::regex pat("\\/");
std::string win32path = std::regex_replace(filepath, pat, "\\");
if (DeleteFile(StringUtf8ToWideChar(win32path).c_str()))
{
return true;
}
else
{
CCLOGERROR("Fail remove file %s !Error code is 0x%x", filepath.c_str(), GetLastError());
return false;
}
}
bool FileUtilsWin32::removeDirectory(const std::string& dirPath)
{
std::wstring wpath = StringUtf8ToWideChar(dirPath);
std::wstring files = wpath + L"*.*";
WIN32_FIND_DATA wfd;
HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0);
bool ret = true;
if (search != INVALID_HANDLE_VALUE)
{
BOOL find = true;
while (find)
{
//. ..
if (wfd.cFileName[0] != '.')
{
std::wstring temp = wpath + wfd.cFileName;
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
temp += '/';
ret = ret && this->removeDirectory(StringWideCharToUtf8(temp));
}
else
{
SetFileAttributes(temp.c_str(), FILE_ATTRIBUTE_NORMAL);
ret = ret && DeleteFile(temp.c_str());
}
}
find = FindNextFile(search, &wfd);
}
FindClose(search);
}
if (ret && RemoveDirectory(wpath.c_str()))
{
return true;
}
return false;
}
NS_CC_END

View File

@ -49,11 +49,53 @@ class CC_DLL FileUtilsWin32 : public FileUtils
public:
/* override funtions */
bool init();
virtual std::string getWritablePath() const;
virtual bool isAbsolutePath(const std::string& strPath) const;
virtual std::string getWritablePath() const override;
virtual bool isAbsolutePath(const std::string& strPath) const override;
virtual std::string getSuitableFOpen(const std::string& filenameUtf8) const override;
protected:
virtual bool isFileExistInternal(const std::string& strFilePath) const;
virtual bool isFileExistInternal(const std::string& strFilePath) const override;
/**
* Renames a file under the given directory.
*
* @param path The parent directory path of the file, it must be an absolute path.
* @param oldname The current name of the file.
* @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) 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;
/**
* Removes a file.
*
* @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) override;
/**
* Creates a directory.
*
* @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) override;
/**
* Removes a directory.
*
* @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) override;
/**
* Gets resource file data
@ -64,7 +106,7 @@ protected:
* @return Upon success, a pointer to the data is returned, otherwise NULL.
* @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned.
*/
virtual unsigned char* getFileData(const std::string& filename, const char* mode, ssize_t * size) override;
CC_DEPRECATED_ATTRIBUTE virtual unsigned char* getFileData(const std::string& filename, const char* mode, ssize_t * size) override;
/**
* Gets string from a file.

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