Merge branch 'v3' into v3FrameBufferObject

# Conflicts:
#	cocos/2d/CCCamera.h
This commit is contained in:
Huabing.Xu 2015-06-10 10:16:42 +08:00
commit 10352c40b2
246 changed files with 17164 additions and 2671 deletions

View File

@ -1,6 +1,6 @@
cocos2d-x authors & contributors cocos2d-x authors & contributors
(ordered by the join in time) (ordered by join time)
Core Developers: Core Developers:
Ricardo Quesada Ricardo Quesada
@ -69,6 +69,9 @@ Developers:
silverscania silverscania
Pass correct parameter to glPixelStorei when creating a texture Pass correct parameter to glPixelStorei when creating a texture
stari4ek
Fix VideoPlayer on Android ignore search paths
FlagellumDei FlagellumDei
Center the window correctly on windows Center the window correctly on windows

View File

@ -1,4 +1,5 @@
cocos2d-x-3.7 ?? cocos2d-x-3.7 ??
[NEW] android: Add Samsung API for cocos, please refer to the release note for more details.
[NEW] 3rd: updated rapidjson to v1.0.2 [NEW] 3rd: updated rapidjson to v1.0.2
[NEW] 3d: added physics3d support [NEW] 3d: added physics3d support
[NEW] console: support build & run Android Studio project [NEW] console: support build & run Android Studio project
@ -12,12 +13,19 @@ cocos2d-x-3.7 ??
[NEW] Scale9Sprite: added Android 9-patch image support [NEW] Scale9Sprite: added Android 9-patch image support
[NEW] Sprite: used triangle command [NEW] Sprite: used triangle command
[NEW] 3d: add `getFarPlane` and `getNearPlane` in `Camera` class [NEW] 3d: add `getFarPlane` and `getNearPlane` in `Camera` class
[NEW] 3d: add opengl version project/unproject function in camera.
[NEW] ui: button add BMFont title support [NEW] ui: button add BMFont title support
[NEW] ui: TextField add `getTextColor`, `getTextHorizontalAlignment` and `getTextVerticalAlignment` API [NEW] ui: TextField add `getTextColor`, `getTextHorizontalAlignment` and `getTextVerticalAlignment` API
[NEW] audio: Added MP3 support to winrt audio [NEW] audio: Added MP3 support to winrt audio
[NEW] win10: Added Windows 10.0 Universal App(UWP) support.
[FIX] network: Fix memory leak of HttpClient on iOS and Mac platform.
[FIX] android: Improve UserDefault's robustness, now the converting behavior is the same as iOS platform.
[FIX] android: Fix VideoPlayer on Android ignore search paths.
[FIX] audio: Fixed program may freeze if `AudioEngine::stop` or `AudioEngine::stopAll()` is invoked frequently on Android [FIX] audio: Fixed program may freeze if `AudioEngine::stop` or `AudioEngine::stopAll()` is invoked frequently on Android
[FIX] ui: TextField scale factor is wrong with multiline text. [FIX] audio: Fixed audio can't resume if it is interrupted by an incoming phone call.
[FIX] audio: Fixed SimpleAudioEngine::playEffect() lagged on Android 5.0.x
[FIX] ui: Text scale factor is wrong with multiline text.
[FIX] 3d: skybox can't move to other position except origin point in world space [FIX] 3d: skybox can't move to other position except origin point in world space
[FIX] 3d: terrain can't move to other position except origin point in world space [FIX] 3d: terrain can't move to other position except origin point in world space
[FIX] 3rd: fix PIE link error on iOS caused by libpng and libtiff [FIX] 3rd: fix PIE link error on iOS caused by libpng and libtiff
@ -28,6 +36,7 @@ cocos2d-x-3.7 ??
[FIX] Label: position is wrong if label content is changed after invoking `getLetter(letterIndex)` [FIX] Label: position is wrong if label content is changed after invoking `getLetter(letterIndex)`
[FIX] Label: shadow effect cause OpenGL error on iOS [FIX] Label: shadow effect cause OpenGL error on iOS
[FIX] Label: outline effect doesn't match characters well [FIX] Label: outline effect doesn't match characters well
[FIX] Label: Fixed system font label line height calculation is wrong on Android.
[FIX] ProgressTimer: `setSprite()` doesn't take effect [FIX] ProgressTimer: `setSprite()` doesn't take effect
[FIX] Sprite3D: setGLProgram() does not work [FIX] Sprite3D: setGLProgram() does not work
[FIX] Sprite3D: transition breaks when there is a Sprite3D in the scene [FIX] Sprite3D: transition breaks when there is a Sprite3D in the scene

View File

@ -25,9 +25,9 @@ cocos2d-x is:
Git user attention Git user attention
----------------------- -----------------------
1. clone the repo from GitHub. 1. Clone the repo from GitHub.
$ git clone git@github.com:cocos2d/cocos2d-x.git $ git clone https://github.com/cocos2d/cocos2d-x.git
2. After cloning the repo, please execute `download-deps.py` to download and install dependencies. 2. After cloning the repo, please execute `download-deps.py` to download and install dependencies.

123
build/cocos2d-win10.sln Normal file
View File

@ -0,0 +1,123 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.22823.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "External", "External", "{17093B03-00CA-402F-981A-D8C84B2922B5}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libSpine", "..\cocos\editor-support\spine\proj.win10\libSpine.vcxproj", "{4B3BA10A-941F-4E08-8A50-8A7FCB822BB8}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libbox2d", "..\external\Box2D\proj-win10\libbox2d.vcxproj", "{0C32D479-46D5-46C3-9AA9-0A8FF8320516}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d", "..\cocos\2d\libcocos2d_win10\libcocos2d.vcxproj", "{07C2895D-720C-487D-B7B4-12C293EA533F}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cpp-empty-test", "..\tests\cpp-empty-test\proj.win10\cpp-empty-test.vcxproj", "{87ED86E7-A850-433F-88D5-D5F65CFF7BF5}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cpp-tests", "..\tests\cpp-tests\proj.win10\cpp-tests.vcxproj", "{C1307B42-D00A-4B88-BCDD-0A16A81FF4C1}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libbullet", "..\external\bullet\proj.win10\libbullet.vcxproj", "{ECEE1119-CE2E-4F7E-83A8-1932EA48E893}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|ARM = Debug|ARM
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|ARM = Release|ARM
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B3BA10A-941F-4E08-8A50-8A7FCB822BB8}.Debug|ARM.ActiveCfg = Debug|ARM
{4B3BA10A-941F-4E08-8A50-8A7FCB822BB8}.Debug|ARM.Build.0 = Debug|ARM
{4B3BA10A-941F-4E08-8A50-8A7FCB822BB8}.Debug|x64.ActiveCfg = Debug|x64
{4B3BA10A-941F-4E08-8A50-8A7FCB822BB8}.Debug|x64.Build.0 = Debug|x64
{4B3BA10A-941F-4E08-8A50-8A7FCB822BB8}.Debug|x86.ActiveCfg = Debug|Win32
{4B3BA10A-941F-4E08-8A50-8A7FCB822BB8}.Debug|x86.Build.0 = Debug|Win32
{4B3BA10A-941F-4E08-8A50-8A7FCB822BB8}.Release|ARM.ActiveCfg = Release|ARM
{4B3BA10A-941F-4E08-8A50-8A7FCB822BB8}.Release|ARM.Build.0 = Release|ARM
{4B3BA10A-941F-4E08-8A50-8A7FCB822BB8}.Release|x64.ActiveCfg = Release|x64
{4B3BA10A-941F-4E08-8A50-8A7FCB822BB8}.Release|x64.Build.0 = Release|x64
{4B3BA10A-941F-4E08-8A50-8A7FCB822BB8}.Release|x86.ActiveCfg = Release|Win32
{4B3BA10A-941F-4E08-8A50-8A7FCB822BB8}.Release|x86.Build.0 = Release|Win32
{0C32D479-46D5-46C3-9AA9-0A8FF8320516}.Debug|ARM.ActiveCfg = Debug|ARM
{0C32D479-46D5-46C3-9AA9-0A8FF8320516}.Debug|ARM.Build.0 = Debug|ARM
{0C32D479-46D5-46C3-9AA9-0A8FF8320516}.Debug|x64.ActiveCfg = Debug|x64
{0C32D479-46D5-46C3-9AA9-0A8FF8320516}.Debug|x64.Build.0 = Debug|x64
{0C32D479-46D5-46C3-9AA9-0A8FF8320516}.Debug|x86.ActiveCfg = Debug|Win32
{0C32D479-46D5-46C3-9AA9-0A8FF8320516}.Debug|x86.Build.0 = Debug|Win32
{0C32D479-46D5-46C3-9AA9-0A8FF8320516}.Release|ARM.ActiveCfg = Release|ARM
{0C32D479-46D5-46C3-9AA9-0A8FF8320516}.Release|ARM.Build.0 = Release|ARM
{0C32D479-46D5-46C3-9AA9-0A8FF8320516}.Release|x64.ActiveCfg = Release|x64
{0C32D479-46D5-46C3-9AA9-0A8FF8320516}.Release|x64.Build.0 = Release|x64
{0C32D479-46D5-46C3-9AA9-0A8FF8320516}.Release|x86.ActiveCfg = Release|Win32
{0C32D479-46D5-46C3-9AA9-0A8FF8320516}.Release|x86.Build.0 = Release|Win32
{07C2895D-720C-487D-B7B4-12C293EA533F}.Debug|ARM.ActiveCfg = Debug|ARM
{07C2895D-720C-487D-B7B4-12C293EA533F}.Debug|ARM.Build.0 = Debug|ARM
{07C2895D-720C-487D-B7B4-12C293EA533F}.Debug|x64.ActiveCfg = Debug|x64
{07C2895D-720C-487D-B7B4-12C293EA533F}.Debug|x64.Build.0 = Debug|x64
{07C2895D-720C-487D-B7B4-12C293EA533F}.Debug|x86.ActiveCfg = Debug|Win32
{07C2895D-720C-487D-B7B4-12C293EA533F}.Debug|x86.Build.0 = Debug|Win32
{07C2895D-720C-487D-B7B4-12C293EA533F}.Release|ARM.ActiveCfg = Release|ARM
{07C2895D-720C-487D-B7B4-12C293EA533F}.Release|ARM.Build.0 = Release|ARM
{07C2895D-720C-487D-B7B4-12C293EA533F}.Release|x64.ActiveCfg = Release|x64
{07C2895D-720C-487D-B7B4-12C293EA533F}.Release|x64.Build.0 = Release|x64
{07C2895D-720C-487D-B7B4-12C293EA533F}.Release|x86.ActiveCfg = Release|Win32
{07C2895D-720C-487D-B7B4-12C293EA533F}.Release|x86.Build.0 = Release|Win32
{87ED86E7-A850-433F-88D5-D5F65CFF7BF5}.Debug|ARM.ActiveCfg = Debug|ARM
{87ED86E7-A850-433F-88D5-D5F65CFF7BF5}.Debug|ARM.Build.0 = Debug|ARM
{87ED86E7-A850-433F-88D5-D5F65CFF7BF5}.Debug|ARM.Deploy.0 = Debug|ARM
{87ED86E7-A850-433F-88D5-D5F65CFF7BF5}.Debug|x64.ActiveCfg = Debug|x64
{87ED86E7-A850-433F-88D5-D5F65CFF7BF5}.Debug|x64.Build.0 = Debug|x64
{87ED86E7-A850-433F-88D5-D5F65CFF7BF5}.Debug|x64.Deploy.0 = Debug|x64
{87ED86E7-A850-433F-88D5-D5F65CFF7BF5}.Debug|x86.ActiveCfg = Debug|Win32
{87ED86E7-A850-433F-88D5-D5F65CFF7BF5}.Debug|x86.Build.0 = Debug|Win32
{87ED86E7-A850-433F-88D5-D5F65CFF7BF5}.Debug|x86.Deploy.0 = Debug|Win32
{87ED86E7-A850-433F-88D5-D5F65CFF7BF5}.Release|ARM.ActiveCfg = Release|ARM
{87ED86E7-A850-433F-88D5-D5F65CFF7BF5}.Release|ARM.Build.0 = Release|ARM
{87ED86E7-A850-433F-88D5-D5F65CFF7BF5}.Release|ARM.Deploy.0 = Release|ARM
{87ED86E7-A850-433F-88D5-D5F65CFF7BF5}.Release|x64.ActiveCfg = Release|x64
{87ED86E7-A850-433F-88D5-D5F65CFF7BF5}.Release|x64.Build.0 = Release|x64
{87ED86E7-A850-433F-88D5-D5F65CFF7BF5}.Release|x64.Deploy.0 = Release|x64
{87ED86E7-A850-433F-88D5-D5F65CFF7BF5}.Release|x86.ActiveCfg = Release|Win32
{87ED86E7-A850-433F-88D5-D5F65CFF7BF5}.Release|x86.Build.0 = Release|Win32
{87ED86E7-A850-433F-88D5-D5F65CFF7BF5}.Release|x86.Deploy.0 = Release|Win32
{C1307B42-D00A-4B88-BCDD-0A16A81FF4C1}.Debug|ARM.ActiveCfg = Debug|ARM
{C1307B42-D00A-4B88-BCDD-0A16A81FF4C1}.Debug|ARM.Build.0 = Debug|ARM
{C1307B42-D00A-4B88-BCDD-0A16A81FF4C1}.Debug|ARM.Deploy.0 = Debug|ARM
{C1307B42-D00A-4B88-BCDD-0A16A81FF4C1}.Debug|x64.ActiveCfg = Debug|x64
{C1307B42-D00A-4B88-BCDD-0A16A81FF4C1}.Debug|x64.Build.0 = Debug|x64
{C1307B42-D00A-4B88-BCDD-0A16A81FF4C1}.Debug|x64.Deploy.0 = Debug|x64
{C1307B42-D00A-4B88-BCDD-0A16A81FF4C1}.Debug|x86.ActiveCfg = Debug|Win32
{C1307B42-D00A-4B88-BCDD-0A16A81FF4C1}.Debug|x86.Build.0 = Debug|Win32
{C1307B42-D00A-4B88-BCDD-0A16A81FF4C1}.Debug|x86.Deploy.0 = Debug|Win32
{C1307B42-D00A-4B88-BCDD-0A16A81FF4C1}.Release|ARM.ActiveCfg = Release|ARM
{C1307B42-D00A-4B88-BCDD-0A16A81FF4C1}.Release|ARM.Build.0 = Release|ARM
{C1307B42-D00A-4B88-BCDD-0A16A81FF4C1}.Release|ARM.Deploy.0 = Release|ARM
{C1307B42-D00A-4B88-BCDD-0A16A81FF4C1}.Release|x64.ActiveCfg = Release|x64
{C1307B42-D00A-4B88-BCDD-0A16A81FF4C1}.Release|x64.Build.0 = Release|x64
{C1307B42-D00A-4B88-BCDD-0A16A81FF4C1}.Release|x64.Deploy.0 = Release|x64
{C1307B42-D00A-4B88-BCDD-0A16A81FF4C1}.Release|x86.ActiveCfg = Release|Win32
{C1307B42-D00A-4B88-BCDD-0A16A81FF4C1}.Release|x86.Build.0 = Release|Win32
{C1307B42-D00A-4B88-BCDD-0A16A81FF4C1}.Release|x86.Deploy.0 = Release|Win32
{ECEE1119-CE2E-4F7E-83A8-1932EA48E893}.Debug|ARM.ActiveCfg = Debug|ARM
{ECEE1119-CE2E-4F7E-83A8-1932EA48E893}.Debug|ARM.Build.0 = Debug|ARM
{ECEE1119-CE2E-4F7E-83A8-1932EA48E893}.Debug|x64.ActiveCfg = Debug|x64
{ECEE1119-CE2E-4F7E-83A8-1932EA48E893}.Debug|x64.Build.0 = Debug|x64
{ECEE1119-CE2E-4F7E-83A8-1932EA48E893}.Debug|x86.ActiveCfg = Debug|Win32
{ECEE1119-CE2E-4F7E-83A8-1932EA48E893}.Debug|x86.Build.0 = Debug|Win32
{ECEE1119-CE2E-4F7E-83A8-1932EA48E893}.Release|ARM.ActiveCfg = Release|ARM
{ECEE1119-CE2E-4F7E-83A8-1932EA48E893}.Release|ARM.Build.0 = Release|ARM
{ECEE1119-CE2E-4F7E-83A8-1932EA48E893}.Release|x64.ActiveCfg = Release|x64
{ECEE1119-CE2E-4F7E-83A8-1932EA48E893}.Release|x64.Build.0 = Release|x64
{ECEE1119-CE2E-4F7E-83A8-1932EA48E893}.Release|x86.ActiveCfg = Release|Win32
{ECEE1119-CE2E-4F7E-83A8-1932EA48E893}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{4B3BA10A-941F-4E08-8A50-8A7FCB822BB8} = {17093B03-00CA-402F-981A-D8C84B2922B5}
{0C32D479-46D5-46C3-9AA9-0A8FF8320516} = {17093B03-00CA-402F-981A-D8C84B2922B5}
{ECEE1119-CE2E-4F7E-83A8-1932EA48E893} = {17093B03-00CA-402F-981A-D8C84B2922B5}
EndGlobalSection
EndGlobal

View File

@ -2106,7 +2106,7 @@ TintBy* TintBy::clone() const
{ {
// no copy constructor // no copy constructor
auto a = new (std::nothrow) TintBy(); auto a = new (std::nothrow) TintBy();
a->initWithDuration(_duration, (GLubyte)_deltaR, (GLubyte)_deltaG, (GLubyte)_deltaB); a->initWithDuration(_duration, _deltaR, _deltaG, _deltaB);
a->autorelease(); a->autorelease();
return a; return a;
} }

View File

@ -20,6 +20,9 @@
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
Code based GamePlay3D's Camera: http://gameplay3d.org
****************************************************************************/ ****************************************************************************/
#include "2d/CCCamera.h" #include "2d/CCCamera.h"
#include "base/CCDirector.h" #include "base/CCDirector.h"

View File

@ -20,7 +20,10 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/
Code based GamePlay3D's Camera: http://gameplay3d.org
****************************************************************************/
#ifndef _CCCAMERA_H__ #ifndef _CCCAMERA_H__
#define _CCCAMERA_H__ #define _CCCAMERA_H__
@ -61,6 +64,7 @@ enum class CameraFlag
class CC_DLL Camera :public Node class CC_DLL Camera :public Node
{ {
friend class Scene; friend class Scene;
friend class Director;
friend class EventDispatcher; friend class EventDispatcher;
public: public:
/** /**
@ -286,7 +290,6 @@ protected:
int8_t _depth; //camera depth, the depth of camera with CameraFlag::DEFAULT flag is 0 by default, a camera with larger depth is drawn on top of camera with smaller detph int8_t _depth; //camera depth, the depth of camera with CameraFlag::DEFAULT flag is 0 by default, a camera with larger depth is drawn on top of camera with smaller detph
static Camera* _visitingCamera; static Camera* _visitingCamera;
friend class Director;
experimental::Viewport _viewport; experimental::Viewport _viewport;
experimental::FrameBuffer* _fbo; experimental::FrameBuffer* _fbo;

View File

@ -74,8 +74,7 @@ void Component::onEnter()
#if CC_ENABLE_SCRIPT_BINDING #if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeJavascript) if (_scriptType == kScriptTypeJavascript)
{ {
if (sendComponentEventToJS(this, kComponentOnEnter)) sendComponentEventToJS(this, kComponentOnEnter);
return;
} }
#endif #endif
} }
@ -85,8 +84,27 @@ void Component::onExit()
#if CC_ENABLE_SCRIPT_BINDING #if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeJavascript) if (_scriptType == kScriptTypeJavascript)
{ {
if (sendComponentEventToJS(this, kComponentOnExit)) sendComponentEventToJS(this, kComponentOnExit);
return; }
#endif
}
void Component::onAdd()
{
#if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeJavascript)
{
sendComponentEventToJS(this, kComponentOnAdd);
}
#endif
}
void Component::onRemove()
{
#if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeJavascript)
{
sendComponentEventToJS(this, kComponentOnRemove);
} }
#endif #endif
} }
@ -96,8 +114,7 @@ void Component::update(float delta)
#if CC_ENABLE_SCRIPT_BINDING #if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeJavascript) if (_scriptType == kScriptTypeJavascript)
{ {
if (sendComponentEventToJS(this, kComponentOnUpdate)) sendComponentEventToJS(this, kComponentOnUpdate);
return;
} }
#endif #endif
} }

View File

@ -38,6 +38,8 @@ class Node;
enum { enum {
kComponentOnEnter, kComponentOnEnter,
kComponentOnExit, kComponentOnExit,
kComponentOnAdd,
kComponentOnRemove,
kComponentOnUpdate kComponentOnUpdate
}; };
@ -58,6 +60,8 @@ public:
virtual void onEnter(); virtual void onEnter();
virtual void onExit(); virtual void onExit();
virtual void onAdd();
virtual void onRemove();
virtual void update(float delta); virtual void update(float delta);
virtual bool serialize(void* r); virtual bool serialize(void* r);
virtual bool isEnabled() const; virtual bool isEnabled() const;

View File

@ -68,7 +68,7 @@ bool ComponentContainer::add(Component *com)
CC_BREAK_IF(component); CC_BREAK_IF(component);
com->setOwner(_owner); com->setOwner(_owner);
_components->insert(com->getName(), com); _components->insert(com->getName(), com);
com->onEnter(); com->onAdd();
ret = true; ret = true;
} while(0); } while(0);
return ret; return ret;
@ -85,7 +85,7 @@ bool ComponentContainer::remove(const std::string& name)
CC_BREAK_IF(iter == _components->end()); CC_BREAK_IF(iter == _components->end());
auto com = iter->second; auto com = iter->second;
com->onExit(); com->onRemove();
com->setOwner(nullptr); com->setOwner(nullptr);
_components->erase(iter); _components->erase(iter);
@ -105,7 +105,7 @@ bool ComponentContainer::remove(Component *com)
{ {
if (iter->second == com) if (iter->second == com)
{ {
com->onExit(); com->onRemove();
com->setOwner(nullptr); com->setOwner(nullptr);
_components->erase(iter); _components->erase(iter);
break; break;
@ -122,7 +122,7 @@ void ComponentContainer::removeAll()
{ {
for (auto iter = _components->begin(); iter != _components->end(); ++iter) for (auto iter = _components->begin(); iter != _components->end(); ++iter)
{ {
iter->second->onExit(); iter->second->onRemove();
iter->second->setOwner(nullptr); iter->second->setOwner(nullptr);
} }

View File

@ -407,7 +407,7 @@ bool LabelTextFormatter::createStringSprites(Label *theLabel)
} }
} }
letterPosition.x = (nextFontPositionX + charXOffset + kernings[i]) / contentScaleFactor; letterPosition.x = (nextFontPositionX + charXOffset) / contentScaleFactor;
letterPosition.y = (nextFontPositionY - charYOffset) / contentScaleFactor; letterPosition.y = (nextFontPositionY - charYOffset) / contentScaleFactor;
if( theLabel->recordLetterInfo(letterPosition, tempDefinition, i) == false) if( theLabel->recordLetterInfo(letterPosition, tempDefinition, i) == false)
@ -417,6 +417,10 @@ bool LabelTextFormatter::createStringSprites(Label *theLabel)
} }
nextFontPositionX += charAdvance + theLabel->_additionalKerning; nextFontPositionX += charAdvance + theLabel->_additionalKerning;
if (i < stringLen - 1)
{
nextFontPositionX += kernings[i + 1];
}
auto letterRight = letterPosition.x + tempDefinition.width; auto letterRight = letterPosition.x + tempDefinition.width;
if (longestLine < letterRight) if (longestLine < letterRight)

View File

@ -710,14 +710,6 @@ const Vec2& Node::getAnchorPoint() const
void Node::setAnchorPoint(const Vec2& point) void Node::setAnchorPoint(const Vec2& point)
{ {
#if CC_USE_PHYSICS
if (_physicsBody != nullptr && !point.equals(Vec2::ANCHOR_MIDDLE))
{
CCLOG("Node warning: This node has a physics body, the anchor must be in the middle, you cann't change this to other value.");
return;
}
#endif
if (! point.equals(_anchorPoint)) if (! point.equals(_anchorPoint))
{ {
_anchorPoint = point; _anchorPoint = point;
@ -812,7 +804,7 @@ void Node::setOrderOfArrival(int orderOfArrival)
_orderOfArrival = orderOfArrival; _orderOfArrival = orderOfArrival;
} }
void Node::setUserObject(Ref *userObject) void Node::setUserObject(Ref* userObject)
{ {
CC_SAFE_RETAIN(userObject); CC_SAFE_RETAIN(userObject);
CC_SAFE_RELEASE(_userObject); CC_SAFE_RELEASE(_userObject);
@ -824,24 +816,29 @@ GLProgramState* Node::getGLProgramState() const
return _glProgramState; return _glProgramState;
} }
void Node::setGLProgramState(cocos2d::GLProgramState *glProgramState) void Node::setGLProgramState(cocos2d::GLProgramState* glProgramState)
{ {
if (glProgramState != _glProgramState) if (glProgramState != _glProgramState)
{ {
CC_SAFE_RELEASE(_glProgramState); CC_SAFE_RELEASE(_glProgramState);
_glProgramState = glProgramState; _glProgramState = glProgramState;
CC_SAFE_RETAIN(_glProgramState); CC_SAFE_RETAIN(_glProgramState);
if (_glProgramState)
_glProgramState->setNodeBinding(this);
} }
} }
void Node::setGLProgram(GLProgram *glProgram) void Node::setGLProgram(GLProgram* glProgram)
{ {
if (_glProgramState == nullptr || (_glProgramState && _glProgramState->getGLProgram() != glProgram)) if (_glProgramState == nullptr || (_glProgramState && _glProgramState->getGLProgram() != glProgram))
{ {
CC_SAFE_RELEASE(_glProgramState); CC_SAFE_RELEASE(_glProgramState);
_glProgramState = GLProgramState::getOrCreateWithGLProgram(glProgram); _glProgramState = GLProgramState::getOrCreateWithGLProgram(glProgram);
_glProgramState->retain(); _glProgramState->retain();
_glProgramState->setNodeBinding(this);
} }
} }
@ -880,9 +877,9 @@ void Node::childrenAlloc()
Node* Node::getChildByTag(int tag) const Node* Node::getChildByTag(int tag) const
{ {
CCASSERT( tag != Node::INVALID_TAG, "Invalid tag"); CCASSERT(tag != Node::INVALID_TAG, "Invalid tag");
for (const auto& child : _children) for (const auto child : _children)
{ {
if(child && child->_tag == tag) if(child && child->_tag == tag)
return child; return child;
@ -1414,6 +1411,11 @@ void Node::onEnter()
if (_onEnterCallback) if (_onEnterCallback)
_onEnterCallback(); _onEnterCallback();
if (_componentContainer && !_componentContainer->isEmpty())
{
_componentContainer->onEnter();
}
#if CC_ENABLE_SCRIPT_BINDING #if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeJavascript) if (_scriptType == kScriptTypeJavascript)
{ {
@ -1493,6 +1495,11 @@ void Node::onExit()
if (_onExitCallback) if (_onExitCallback)
_onExitCallback(); _onExitCallback();
if (_componentContainer && !_componentContainer->isEmpty())
{
_componentContainer->onExit();
}
#if CC_ENABLE_SCRIPT_BINDING #if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeJavascript) if (_scriptType == kScriptTypeJavascript)
{ {
@ -2072,14 +2079,6 @@ void Node::setPhysicsBody(PhysicsBody* body)
body->_node = this; body->_node = this;
body->retain(); body->retain();
// physics rotation based on body position, but node rotation based on node anthor point
// it cann't support both of them, so I clear the anthor point to default.
if (!getAnchorPoint().equals(Vec2::ANCHOR_MIDDLE))
{
CCLOG("Node warning: setPhysicsBody sets anchor point to Vec2::ANCHOR_MIDDLE.");
setAnchorPoint(Vec2::ANCHOR_MIDDLE);
}
_physicsBody = body; _physicsBody = body;
_physicsScaleStartX = _scaleX; _physicsScaleStartX = _scaleX;
@ -2118,10 +2117,16 @@ void Node::updatePhysicsBodyTransform(const Mat4& parentTransform, uint32_t pare
if (_physicsBody && ((flags & FLAGS_DIRTY_MASK) || _physicsTransformDirty)) if (_physicsBody && ((flags & FLAGS_DIRTY_MASK) || _physicsTransformDirty))
{ {
_physicsTransformDirty = false; _physicsTransformDirty = false;
Vec3 vec3(_position.x, _position.y, 0);
Vec3 vec3(_contentSize.width * 0.5f, _contentSize.height * 0.5f, 0);
Vec3 ret; Vec3 ret;
parentTransform.transformPoint(vec3, &ret); _modelViewTransform.transformPoint(vec3, &ret);
_physicsBody->setPosition(Vec2(ret.x, ret.y)); _physicsBody->setPosition(Vec2(ret.x, ret.y));
parentTransform.getInversed().transformPoint(&ret);
_offsetX = ret.x - _position.x;
_offsetY = ret.y - _position.y;
_physicsBody->setScale(scaleX / _physicsScaleStartX, scaleY / _physicsScaleStartY); _physicsBody->setScale(scaleX / _physicsScaleStartX, scaleY / _physicsScaleStartY);
_physicsBody->setRotation(_physicsRotation - _physicsRotationOffset); _physicsBody->setRotation(_physicsRotation - _physicsRotationOffset);
} }
@ -2143,7 +2148,7 @@ void Node::updateTransformFromPhysics(const Mat4& parentTransform, uint32_t pare
Vec3 vec3(newPosition.x, newPosition.y, 0); Vec3 vec3(newPosition.x, newPosition.y, 0);
Vec3 ret; Vec3 ret;
parentTransform.getInversed().transformPoint(vec3, &ret); parentTransform.getInversed().transformPoint(vec3, &ret);
setPosition(ret.x, ret.y); setPosition(ret.x - _offsetX, ret.y - _offsetY);
} }
_physicsRotation = _physicsBody->getRotation(); _physicsRotation = _physicsBody->getRotation();
setRotation(_physicsRotation - _parent->_physicsRotation + _physicsRotationOffset); setRotation(_physicsRotation - _parent->_physicsRotation + _physicsRotationOffset);

View File

@ -1844,6 +1844,9 @@ protected:
PhysicsWorld* _physicsWorld; /** The PhysicsWorld associated with the node.*/ PhysicsWorld* _physicsWorld; /** The PhysicsWorld associated with the node.*/
int _physicsBodyAssociatedWith; /** The count of PhysicsBody associated with the node and children.*/ int _physicsBodyAssociatedWith; /** The count of PhysicsBody associated with the node and children.*/
float _physicsRotationOffset; /** Record the rotation value when invoke Node::setPhysicsBody.*/ float _physicsRotationOffset; /** Record the rotation value when invoke Node::setPhysicsBody.*/
float _offsetX;
float _offsetY;
#endif #endif
// opacity controls // opacity controls

View File

@ -217,13 +217,17 @@ void Scene::setPhysics3DDebugCamera(Camera* camera)
void Scene::addChild(Node* child, int zOrder, int tag) void Scene::addChild(Node* child, int zOrder, int tag)
{ {
Node::addChild(child, zOrder, tag); Node::addChild(child, zOrder, tag);
#if CC_USE_PHYSICS
addChildToPhysicsWorld(child); addChildToPhysicsWorld(child);
#endif
} }
void Scene::addChild(Node* child, int zOrder, const std::string &name) void Scene::addChild(Node* child, int zOrder, const std::string &name)
{ {
Node::addChild(child, zOrder, name); Node::addChild(child, zOrder, name);
#if CC_USE_PHYSICS
addChildToPhysicsWorld(child); addChildToPhysicsWorld(child);
#endif
} }
Scene* Scene::createWithPhysics() Scene* Scene::createWithPhysics()
@ -256,8 +260,6 @@ bool Scene::initWithPhysics()
#if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION #if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION
Physics3DWorldDes info; Physics3DWorldDes info;
//TODO: FIX ME
//info.isDebugDrawEnabled = true;
CC_BREAK_IF(! (_physics3DWorld = Physics3DWorld::create(&info))); CC_BREAK_IF(! (_physics3DWorld = Physics3DWorld::create(&info)));
_physics3DWorld->retain(); _physics3DWorld->retain();
#endif #endif
@ -292,29 +294,6 @@ void Scene::addChildToPhysicsWorld(Node* child)
addToPhysicsWorldFunc(child); addToPhysicsWorldFunc(child);
} }
#endif #endif
#if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION
if (_physics3DWorld)
{
std::function<void(Node*)> addToPhysicsWorldFunc = nullptr;
addToPhysicsWorldFunc = [this, &addToPhysicsWorldFunc](Node* node) -> void
{
static std::string comName = Physics3DComponent::getPhysics3DComponentName();
auto com = static_cast<Physics3DComponent*>(node->getComponent(comName));
if (com)
{
com->addToPhysicsWorld(_physics3DWorld);
}
auto& children = node->getChildren();
for( const auto &n : children) {
addToPhysicsWorldFunc(n);
}
};
addToPhysicsWorldFunc(child);
}
#endif
} }
#endif #endif

View File

@ -257,8 +257,8 @@ void MarchingSquare::marchSquare(int startx, int starty)
{ {
//TODO: we triangulation cannot work collineer points, so we need to modify same point a little //TODO: we triangulation cannot work collineer points, so we need to modify same point a little
//TODO: maybe we can detect if we go into a hole and coming back the hole, we should extract those points and remove them //TODO: maybe we can detect if we go into a hole and coming back the hole, we should extract those points and remove them
points.back().x -= 0.00001; points.back().x -= 0.00001f;
points.back().y -= 0.00001; points.back().y -= 0.00001f;
points.push_back(Vec2((float)curx, (float)height-cury)/ scaleFactor); points.push_back(Vec2((float)curx, (float)height-cury)/ scaleFactor);
} }
else{ else{

View File

@ -159,7 +159,7 @@
<CompileAsWinRT>true</CompileAsWinRT> <CompileAsWinRT>true</CompileAsWinRT>
<AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions> <AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles> <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> <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;CC_ENABLE_BULLET_INTEGRATION=1;_DEBUG;COCOS2D_DEBUG=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck> <SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings> <DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings>
@ -171,6 +171,7 @@
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies> <AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<ModuleDefinitionFile>..\..\..\cocos2d.def</ModuleDefinitionFile> <ModuleDefinitionFile>..\..\..\cocos2d.def</ModuleDefinitionFile>
<IgnoreSpecificDefaultLibraries>MSVCRT;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
</Link> </Link>
</ItemDefinitionGroup> </ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
@ -179,7 +180,7 @@
<CompileAsWinRT>true</CompileAsWinRT> <CompileAsWinRT>true</CompileAsWinRT>
<AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions> <AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles> <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> <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;CC_ENABLE_BULLET_INTEGRATION=1;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck> <SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings> <DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings>
@ -199,7 +200,7 @@
<CompileAsWinRT>true</CompileAsWinRT> <CompileAsWinRT>true</CompileAsWinRT>
<AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions> <AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles> <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> <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;CC_ENABLE_BULLET_INTEGRATION=1;_DEBUG;COCOS2D_DEBUG=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck> <SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings> <DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings>
@ -211,6 +212,7 @@
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies> <AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<ModuleDefinitionFile>..\..\..\cocos2d.def</ModuleDefinitionFile> <ModuleDefinitionFile>..\..\..\cocos2d.def</ModuleDefinitionFile>
<IgnoreSpecificDefaultLibraries>MSVCRT;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
</Link> </Link>
</ItemDefinitionGroup> </ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|arm'"> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|arm'">
@ -219,7 +221,7 @@
<CompileAsWinRT>true</CompileAsWinRT> <CompileAsWinRT>true</CompileAsWinRT>
<AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions> <AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles> <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> <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;CC_ENABLE_BULLET_INTEGRATION=1;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck> <SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings> <DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings>
@ -251,6 +253,7 @@
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies> <AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<ModuleDefinitionFile>..\..\..\cocos2d.def</ModuleDefinitionFile> <ModuleDefinitionFile>..\..\..\cocos2d.def</ModuleDefinitionFile>
<IgnoreSpecificDefaultLibraries>MSVCRT;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
</Link> </Link>
</ItemDefinitionGroup> </ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">

View File

@ -113,7 +113,7 @@
<CompileAsWinRT>true</CompileAsWinRT> <CompileAsWinRT>true</CompileAsWinRT>
<AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions> <AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles> <ForcedIncludeFiles>pch.h</ForcedIncludeFiles>
<AdditionalIncludeDirectories>$(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> <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;CC_ENABLE_BULLET_INTEGRATION=1;_DEBUG;COCOS2D_DEBUG=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck> <SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings> <DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings>
@ -125,6 +125,7 @@
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies> <AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<ModuleDefinitionFile>..\..\..\cocos2d.def</ModuleDefinitionFile> <ModuleDefinitionFile>..\..\..\cocos2d.def</ModuleDefinitionFile>
<IgnoreSpecificDefaultLibraries>MSVCRT;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
</Link> </Link>
</ItemDefinitionGroup> </ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
@ -133,7 +134,7 @@
<CompileAsWinRT>true</CompileAsWinRT> <CompileAsWinRT>true</CompileAsWinRT>
<AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions> <AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles> <ForcedIncludeFiles>pch.h</ForcedIncludeFiles>
<AdditionalIncludeDirectories>$(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> <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;CC_ENABLE_BULLET_INTEGRATION=1;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck> <SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings> <DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings>
@ -153,7 +154,7 @@
<CompileAsWinRT>true</CompileAsWinRT> <CompileAsWinRT>true</CompileAsWinRT>
<AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions> <AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles> <ForcedIncludeFiles>pch.h</ForcedIncludeFiles>
<AdditionalIncludeDirectories>$(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> <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;CC_ENABLE_BULLET_INTEGRATION=1;_DEBUG;COCOS2D_DEBUG=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck> <SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings> <DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings>
@ -165,6 +166,7 @@
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies> <AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<ModuleDefinitionFile>..\..\..\cocos2d.def</ModuleDefinitionFile> <ModuleDefinitionFile>..\..\..\cocos2d.def</ModuleDefinitionFile>
<IgnoreSpecificDefaultLibraries>MSVCRT;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
</Link> </Link>
</ItemDefinitionGroup> </ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|arm'"> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|arm'">
@ -173,7 +175,7 @@
<CompileAsWinRT>true</CompileAsWinRT> <CompileAsWinRT>true</CompileAsWinRT>
<AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions> <AdditionalOptions>/Zm384 /bigobj %(AdditionalOptions)</AdditionalOptions>
<ForcedIncludeFiles>pch.h</ForcedIncludeFiles> <ForcedIncludeFiles>pch.h</ForcedIncludeFiles>
<AdditionalIncludeDirectories>$(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> <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;CC_ENABLE_BULLET_INTEGRATION=1;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>false</SDLCheck> <SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings> <DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="PropertySheets" />
<PropertyGroup Label="UserMacros">
<EngineRoot>$(MSBuildThisFileDirectory)..\..\..\</EngineRoot>
</PropertyGroup>
<PropertyGroup />
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>$(EngineRoot)external\$(COCOS2D_PLATFORM)-specific\angle\include;$(EngineRoot)external\freetype2\include\$(COCOS2D_PLATFORM)\freetype2;$(EngineRoot)external\websockets\include\$(COCOS2D_PLATFORM);$(EngineRoot)cocos\platform\winrt;$(EngineRoot)cocos\platform;$(EngineRoot)cocos\editor-support;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)external\sqlite3\include;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos;$(EngineRoot)extensions;$(EngineRoot)external;$(EngineRoot)external\edtaa3func;$(EngineRoot)external\unzip;$(EngineRoot)external\tinyxml2;$(EngineRoot);$(EngineRoot)external\ConvertUTF;$(EngineRoot)external\xxhash;$(EngineRoot)external\poly2tri;$(EngineRoot)external\poly2tri\common;$(EngineRoot)external\poly2tri\sweep;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<ClCompile>
<PreprocessorDefinitions>WINRT;_VARIADIC_MAX=10;NOMINMAX;GL_GLEXT_PROTOTYPES;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;_UNICODE;UNICODE;RAPIDJSON_ENDIAN=RAPIDJSON_LITTLEENDIAN;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<CompileAsWinRT>true</CompileAsWinRT>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<MinimalRebuild>false</MinimalRebuild>
<DebugInformationFormat>OldStyle</DebugInformationFormat>
<DisableSpecificWarnings>4056;4244;4251;4756;4453;28204;4099;</DisableSpecificWarnings>
</ClCompile>
<Link>
<AdditionalDependencies>libogg.lib;libvorbis.lib;libvorbisfile.lib;libGLESv2.lib;libEGL.lib;ws2_32.lib;libwebsockets.lib;chipmunk.lib;zlib.lib;freetype.lib;sqlite3.lib;d2d1.lib;d3d11.lib;dxgi.lib;windowscodecs.lib;dwrite.lib;dxguid.lib;xaudio2.lib;mfcore.lib;mfplat.lib;mfreadwrite.lib;mfuuid.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>$(EngineRoot)external\$(COCOS2D_PLATFORM)-specific\OggDecoder\prebuilt\$(Platform);$(EngineRoot)external\$(COCOS2D_PLATFORM)-specific\angle\prebuilt\$(Platform);$(EngineRoot)external\websockets\prebuilt\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\chipmunk\prebuilt\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\$(COCOS2D_PLATFORM)-specific\zlib\prebuilt\$(Platform);$(EngineRoot)external\sqlite3\libraries\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\freetype2\prebuilt\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\poly2tri;$(EngineRoot)external\poly2tri\common;$(EngineRoot)external\poly2tri\sweep;%(AdditionalLibraryDirectories);</AdditionalLibraryDirectories>
<AdditionalOptions>/IGNORE:4264 %(AdditionalOptions)</AdditionalOptions>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<BuildMacro Include="EngineRoot">
<Value>$(EngineRoot)</Value>
<EnvironmentVariable>true</EnvironmentVariable>
</BuildMacro>
</ItemGroup>
</Project>

View File

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="PropertySheets" />
<PropertyGroup Label="APP_DLLS">
<AngleBinPath Condition=" '$(AngleBinPath)' == '' ">$(EngineRoot)external\$(COCOS2D_PLATFORM)-specific\angle\prebuilt\$(Platform)\</AngleBinPath>
<ZLibBinPath Condition=" '$(ZLibBinPath)' == '' ">$(EngineRoot)external\$(COCOS2D_PLATFORM)-specific\zlib\prebuilt\$(Platform)\</ZLibBinPath>
<WebsocketsBinPath Condition=" '$(WebsocketsBinPath)' == '' ">$(EngineRoot)external\websockets\prebuilt\$(COCOS2D_PLATFORM)\$(Platform)\</WebsocketsBinPath>
<SQLiteBinPath Condition=" '$(SQLiteBinPath)' == '' ">$(EngineRoot)external\sqlite3\libraries\$(COCOS2D_PLATFORM)\$(Platform)\</SQLiteBinPath>
<OggBinPath Condition=" '$(OggBinPath)' == '' ">$(EngineRoot)external\$(COCOS2D_PLATFORM)-specific\OggDecoder\prebuilt\$(Platform)\</OggBinPath>
</PropertyGroup>
<ItemGroup Label="ANGLE">
<None Include="$(AngleBinPath)libEGL.dll">
<DeploymentContent>true</DeploymentContent>
</None>
<None Include="$(AngleBinPath)libGLESv2.dll">
<DeploymentContent>true</DeploymentContent>
</None>
<None Include="$(ZLibBinPath)zlib.dll">
<DeploymentContent>true</DeploymentContent>
</None>
<None Include="$(WebsocketsBinPath)libwebsockets.dll">
<DeploymentContent>true</DeploymentContent>
</None>
<None Include="$(SQLiteBinPath)sqlite3.dll">
<DeploymentContent>true</DeploymentContent>
</None>
<None Include="$(OggBinPath)libogg.dll">
<DeploymentContent>true</DeploymentContent>
</None>
<None Include="$(OggBinPath)libvorbis.dll">
<DeploymentContent>true</DeploymentContent>
</None>
<None Include="$(OggBinPath)libvorbisfile.dll">
<DeploymentContent>true</DeploymentContent>
</None>
</ItemGroup>
</Project>

View File

@ -2,6 +2,11 @@
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="PropertySheets" /> <ImportGroup Label="PropertySheets" />
<PropertyGroup Label="COCOS2"> <PropertyGroup Label="COCOS2">
<COCOS2D_PLATFORM Condition=" '$(COCOS2_PLATFORM)' == '' ">winrt_8.1</COCOS2D_PLATFORM> <COCOS2D_PLATFORM Condition=" '$(COCOS2_PLATFORM)' == '' ">win10</COCOS2D_PLATFORM>
</PropertyGroup> </PropertyGroup>
<ItemDefinitionGroup>
<Link>
<AdditionalDependencies>msxml6.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
</Project> </Project>

View File

@ -18,8 +18,8 @@
<DisableSpecificWarnings>4056;4244;4251;4756;4453;28204;4099;</DisableSpecificWarnings> <DisableSpecificWarnings>4056;4244;4251;4756;4453;28204;4099;</DisableSpecificWarnings>
</ClCompile> </ClCompile>
<Link> <Link>
<AdditionalDependencies>libGLESv2.lib;libEGL.lib;ws2_32.lib;libwebsockets.lib;libcurl.lib;chipmunk.lib;zlib.lib;freetype.lib;sqlite3.lib;d2d1.lib;d3d11.lib;dxgi.lib;windowscodecs.lib;dwrite.lib;dxguid.lib;xaudio2.lib;mfcore.lib;mfplat.lib;mfreadwrite.lib;mfuuid.lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalDependencies>libogg.lib;libvorbis.lib;libvorbisfile.lib;libGLESv2.lib;libEGL.lib;ws2_32.lib;libwebsockets.lib;libcurl.lib;chipmunk.lib;zlib.lib;freetype.lib;sqlite3.lib;d2d1.lib;d3d11.lib;dxgi.lib;windowscodecs.lib;dwrite.lib;dxguid.lib;xaudio2.lib;mfcore.lib;mfplat.lib;mfreadwrite.lib;mfuuid.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>$(EngineRoot)external\$(COCOS2D_PLATFORM)-specific\angle\prebuilt\$(Platform);$(EngineRoot)external\curl\prebuilt\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\websockets\prebuilt\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\chipmunk\prebuilt\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\$(COCOS2D_PLATFORM)-specific\zlib\prebuilt\$(Platform);$(EngineRoot)external\sqlite3\libraries\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\freetype2\prebuilt\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\poly2tri;$(EngineRoot)external\poly2tri\common;$(EngineRoot)external\poly2tri\sweep;%(AdditionalLibraryDirectories);</AdditionalLibraryDirectories> <AdditionalLibraryDirectories>$(EngineRoot)external\$(COCOS2D_PLATFORM)-specific\OggDecoder\prebuilt\$(Platform);$(EngineRoot)external\$(COCOS2D_PLATFORM)-specific\angle\prebuilt\$(Platform);$(EngineRoot)external\curl\prebuilt\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\websockets\prebuilt\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\chipmunk\prebuilt\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\$(COCOS2D_PLATFORM)-specific\zlib\prebuilt\$(Platform);$(EngineRoot)external\sqlite3\libraries\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\freetype2\prebuilt\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\poly2tri;$(EngineRoot)external\poly2tri\common;$(EngineRoot)external\poly2tri\sweep;%(AdditionalLibraryDirectories);</AdditionalLibraryDirectories>
<AdditionalOptions>/IGNORE:4264 %(AdditionalOptions)</AdditionalOptions> <AdditionalOptions>/IGNORE:4264 %(AdditionalOptions)</AdditionalOptions>
</Link> </Link>
</ItemDefinitionGroup> </ItemDefinitionGroup>

View File

@ -6,6 +6,7 @@
<CurlBinPath Condition=" '$(CurlBinPath)' == '' ">$(EngineRoot)external\curl\prebuilt\$(COCOS2D_PLATFORM)\$(Platform)\</CurlBinPath> <CurlBinPath Condition=" '$(CurlBinPath)' == '' ">$(EngineRoot)external\curl\prebuilt\$(COCOS2D_PLATFORM)\$(Platform)\</CurlBinPath>
<WebsocketsBinPath Condition=" '$(WebsocketsBinPath)' == '' ">$(EngineRoot)external\websockets\prebuilt\$(COCOS2D_PLATFORM)\$(Platform)\</WebsocketsBinPath> <WebsocketsBinPath Condition=" '$(WebsocketsBinPath)' == '' ">$(EngineRoot)external\websockets\prebuilt\$(COCOS2D_PLATFORM)\$(Platform)\</WebsocketsBinPath>
<SQLiteBinPath Condition=" '$(SQLiteBinPath)' == '' ">$(EngineRoot)external\sqlite3\libraries\$(COCOS2D_PLATFORM)\$(Platform)\</SQLiteBinPath> <SQLiteBinPath Condition=" '$(SQLiteBinPath)' == '' ">$(EngineRoot)external\sqlite3\libraries\$(COCOS2D_PLATFORM)\$(Platform)\</SQLiteBinPath>
<OggBinPath Condition=" '$(OggBinPath)' == '' ">$(EngineRoot)external\$(COCOS2D_PLATFORM)-specific\OggDecoder\prebuilt\$(Platform)\</OggBinPath>
</PropertyGroup> </PropertyGroup>
<ItemGroup Label="ANGLE"> <ItemGroup Label="ANGLE">
<None Include="$(AngleBinPath)libEGL.dll"> <None Include="$(AngleBinPath)libEGL.dll">
@ -29,5 +30,14 @@
<None Include="$(CurlBinPath)ssleay32.dll"> <None Include="$(CurlBinPath)ssleay32.dll">
<DeploymentContent>true</DeploymentContent> <DeploymentContent>true</DeploymentContent>
</None> </None>
<None Include="$(OggBinPath)libogg.dll">
<DeploymentContent>true</DeploymentContent>
</None>
<None Include="$(OggBinPath)libvorbis.dll">
<DeploymentContent>true</DeploymentContent>
</None>
<None Include="$(OggBinPath)libvorbisfile.dll">
<DeploymentContent>true</DeploymentContent>
</None>
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -1,32 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="PropertySheets" />
<PropertyGroup Label="UserMacros">
<EngineRoot>$(MSBuildThisFileDirectory)..\..\..\</EngineRoot>
</PropertyGroup>
<PropertyGroup />
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>$(EngineRoot)external\winrt-specific\angle\include;$(EngineRoot)external\freetype2\include\$(COCOS2D_PLATFORM);$(EngineRoot)external\curl\include\$(COCOS2D_PLATFORM);$(EngineRoot)external\websockets\include\$(COCOS2D_PLATFORM);$(EngineRoot)cocos\platform\winrt;$(EngineRoot)cocos\platform;$(EngineRoot)cocos\editor-support;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)external\sqlite3\include;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos;$(EngineRoot)extensions;$(EngineRoot)external;$(EngineRoot)external\edtaa3func;$(EngineRoot)external\unzip;$(EngineRoot)external\tinyxml2;$(EngineRoot);$(EngineRoot)external\ConvertUTF;$(EngineRoot)external\xxhash;$(EngineRoot)external\poly2tri;$(EngineRoot)external\poly2tri\common;$(EngineRoot)external\poly2tri\sweep;%(AdditionalIncludeDirectories);</AdditionalIncludeDirectories>
</ClCompile>
<ClCompile>
<PreprocessorDefinitions>WINRT;_VARIADIC_MAX=10;NOMINMAX;GL_GLEXT_PROTOTYPES;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<CompileAsWinRT>true</CompileAsWinRT>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<MinimalRebuild>false</MinimalRebuild>
<DebugInformationFormat>OldStyle</DebugInformationFormat>
<DisableSpecificWarnings>4056;4996;4244;4251;</DisableSpecificWarnings>
</ClCompile>
<Link>
<AdditionalDependencies>libGLESv2.lib;libEGL.lib;ws2_32.lib;libwebsockets.lib;libcurl.lib;libchipmunk.lib;zlib.lib;libpng.lib;libjpeg.lib;libtiff.lib;freetype250.lib;sqlite3.lib;d2d1.lib;d3d11.lib;dxgi.lib;windowscodecs.lib;dwrite.lib;dxguid.lib;xaudio2.lib;mfcore.lib;mfplat.lib;mfreadwrite.lib;mfuuid.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>$(EngineRoot)external\winrt-specific\angle\prebuilt\$(Platform);$(EngineRoot)external\curl\prebuilt\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\websockets\prebuilt\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\chipmunk\prebuilt\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\$(COCOS2D_PLATFORM)-specific\zlib\prebuilt\$(Platform);$(EngineRoot)external\png\prebuilt\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\tiff\prebuilt\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\jpeg\prebuilt\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\sqlite3\libraries\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\freetype2\prebuilt\$(COCOS2D_PLATFORM)\$(Platform);$(EngineRoot)external\poly2tri;$(EngineRoot)external\poly2tri\common;$(EngineRoot)external\poly2tri\sweep;%(AdditionalLibraryDirectories);</AdditionalLibraryDirectories>
<AdditionalOptions>/IGNORE:4264 %(AdditionalOptions)</AdditionalOptions>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<BuildMacro Include="EngineRoot">
<Value>$(EngineRoot)</Value>
<EnvironmentVariable>true</EnvironmentVariable>
</BuildMacro>
</ItemGroup>
</Project>

View File

@ -1,15 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="PropertySheets" />
<PropertyGroup Label="APP_DLLS">
<AngleBinPath Condition=" '$(AngleBinPath)' == '' ">$(EngineRoot)external\winrt-specific\angle\prebuilt\$(Platform)\</AngleBinPath>
</PropertyGroup>
<ItemGroup Label="ANGLE">
<None Include="$(AngleBinPath)libEGL.dll">
<DeploymentContent>true</DeploymentContent>
</None>
<None Include="$(AngleBinPath)libGLESv2.dll">
<DeploymentContent>true</DeploymentContent>
</None>
</ItemGroup>
</Project>

View File

@ -283,6 +283,9 @@ void Mesh::setTexture(Texture2D* tex)
auto technique = _material->_currentTechnique; auto technique = _material->_currentTechnique;
for(auto& pass: technique->_passes) for(auto& pass: technique->_passes)
{ {
// FIXME: Ideally it should use glProgramState->setUniformTexture()
// and set CC_Texture0 that way. But trying to it, will trigger
// another bug
pass->setTexture(tex); pass->setTexture(tex);
} }
} }
@ -350,6 +353,7 @@ void Mesh::draw(Renderer* renderer, float globalZOrder, const Mat4& transform, u
_meshCommand.setSkipBatching(isTransparent); _meshCommand.setSkipBatching(isTransparent);
_meshCommand.setTransparent(isTransparent);
// set default uniforms for Mesh // set default uniforms for Mesh
// 'u_color' and others // 'u_color' and others

View File

@ -418,7 +418,7 @@ void Sprite3D::createAttachSprite3DNode(NodeData* nodedata, const MaterialDatas&
void Sprite3D::setMaterial(Material *material) void Sprite3D::setMaterial(Material *material)
{ {
setMaterial(material, -1); setMaterial(material, -1);
} }
void Sprite3D::setMaterial(Material *material, int meshIndex) void Sprite3D::setMaterial(Material *material, int meshIndex)
@ -606,8 +606,8 @@ void Sprite3D::setTexture(const std::string& texFile)
void Sprite3D::setTexture(Texture2D* texture) void Sprite3D::setTexture(Texture2D* texture)
{ {
for (auto& state : _meshes) { for (auto mesh: _meshes) {
state->setTexture(texture); mesh->setTexture(texture);
} }
} }
AttachNode* Sprite3D::getAttachNode(const std::string& boneName) AttachNode* Sprite3D::getAttachNode(const std::string& boneName)
@ -730,7 +730,7 @@ void Sprite3D::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
} }
} }
for (auto mesh : _meshes) for (auto mesh: _meshes)
{ {
mesh->draw(renderer, mesh->draw(renderer,
_globalZOrder, _globalZOrder,
@ -743,25 +743,25 @@ void Sprite3D::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
} }
} }
void Sprite3D::setGLProgramState(GLProgramState *glProgramState) void Sprite3D::setGLProgramState(GLProgramState* glProgramState)
{ {
Node::setGLProgramState(glProgramState); Node::setGLProgramState(glProgramState);
for (auto& state : _meshes) { for (auto state : _meshes) {
state->setGLProgramState(glProgramState); state->setGLProgramState(glProgramState);
} }
} }
void Sprite3D::setGLProgram(GLProgram *glprogram) void Sprite3D::setGLProgram(GLProgram* glprogram)
{ {
auto glProgramState = GLProgramState::create(glprogram); auto glProgramState = GLProgramState::create(glprogram);
setGLProgramState(glProgramState); setGLProgramState(glProgramState);
} }
void Sprite3D::setBlendFunc(const BlendFunc &blendFunc) void Sprite3D::setBlendFunc(const BlendFunc& blendFunc)
{ {
if(_blend.src != blendFunc.src || _blend.dst != blendFunc.dst) if(_blend.src != blendFunc.src || _blend.dst != blendFunc.dst)
{ {
_blend = blendFunc; _blend = blendFunc;
for(auto& mesh : _meshes) for(auto mesh: _meshes)
{ {
mesh->setBlendFunc(blendFunc); mesh->setBlendFunc(blendFunc);
} }
@ -776,8 +776,8 @@ const BlendFunc& Sprite3D::getBlendFunc() const
AABB Sprite3D::getAABBRecursively() AABB Sprite3D::getAABBRecursively()
{ {
AABB aabb; AABB aabb;
const Vector<Node*>& children = getChildren(); const auto children = getChildren();
for (const auto& iter : children) for (const auto iter: children)
{ {
Sprite3D* child = dynamic_cast<Sprite3D*>(iter); Sprite3D* child = dynamic_cast<Sprite3D*>(iter);
if(child) if(child)

View File

@ -278,7 +278,7 @@ void Terrain::setChunksLOD(Vec3 cameraPos)
} }
} }
float Terrain::getHeight(float x, float z, Vec3 * normal) float Terrain::getHeight(float x, float z, Vec3 * normal) const
{ {
Vec2 pos(x,z); Vec2 pos(x,z);
@ -307,6 +307,10 @@ float Terrain::getHeight(float x, float z, Vec3 * normal)
if(image_x>=_imageWidth-1 || image_y >=_imageHeight-1 || image_x<0 || image_y<0) if(image_x>=_imageWidth-1 || image_y >=_imageHeight-1 || image_x<0 || image_y<0)
{ {
if (normal)
{
normal->setZero();
}
return 0; return 0;
}else }else
{ {
@ -327,12 +331,12 @@ float Terrain::getHeight(float x, float z, Vec3 * normal)
} }
} }
float Terrain::getHeight(Vec2 pos, Vec3*Normal) float Terrain::getHeight(Vec2 pos, Vec3*Normal) const
{ {
return getHeight(pos.x,pos.y,Normal); return getHeight(pos.x,pos.y,Normal);
} }
float Terrain::getImageHeight(int pixel_x,int pixel_y) float Terrain::getImageHeight(int pixel_x,int pixel_y) const
{ {
int byte_stride =1; int byte_stride =1;
switch (_heightMapImage->getRenderFormat()) switch (_heightMapImage->getRenderFormat())
@ -472,7 +476,7 @@ Terrain::~Terrain()
#endif #endif
} }
cocos2d::Vec3 Terrain::getNormal(int pixel_x, int pixel_y) cocos2d::Vec3 Terrain::getNormal(int pixel_x, int pixel_y) const
{ {
float a = getImageHeight(pixel_x,pixel_y)*getScaleY(); float a = getImageHeight(pixel_x,pixel_y)*getScaleY();
float b = getImageHeight(pixel_x,pixel_y+1)*getScaleY(); float b = getImageHeight(pixel_x,pixel_y+1)*getScaleY();
@ -486,7 +490,7 @@ cocos2d::Vec3 Terrain::getNormal(int pixel_x, int pixel_y)
return normal; return normal;
} }
cocos2d::Vec3 Terrain::getIntersectionPoint(const Ray & ray) cocos2d::Vec3 Terrain::getIntersectionPoint(const Ray & ray) const
{ {
Vec3 dir = ray._direction; Vec3 dir = ray._direction;
dir.normalize(); dir.normalize();
@ -496,12 +500,14 @@ cocos2d::Vec3 Terrain::getIntersectionPoint(const Ray & ray)
Vec3 lastRayPosition =rayPos; Vec3 lastRayPosition =rayPos;
rayPos += rayStep; rayPos += rayStep;
// Linear search - Loop until find a point inside and outside the terrain Vector3 // Linear search - Loop until find a point inside and outside the terrain Vector3
float height = getHeight(rayPos.x,rayPos.z); Vec3 normal;
float height = getHeight(rayPos.x, rayPos.z, &normal);
while (rayPos.y > height) while (rayPos.y > height)
{ {
lastRayPosition = rayPos; lastRayPosition = rayPos;
rayPos += rayStep; rayPos += rayStep;
if (normal.isZero())
return Vec3(0, 0, 0);
height = getHeight(rayPos.x,rayPos.z); height = getHeight(rayPos.x,rayPos.z);
} }
@ -521,6 +527,47 @@ cocos2d::Vec3 Terrain::getIntersectionPoint(const Ray & ray)
return collisionPoint; return collisionPoint;
} }
bool Terrain::getIntersectionPoint(const Ray & ray, Vec3 & intersectionPoint) const
{
Vec3 dir = ray._direction;
dir.normalize();
Vec3 rayStep = _terrainData._chunkSize.width*0.25*dir;
Vec3 rayPos = ray._origin;
Vec3 rayStartPosition = ray._origin;
Vec3 lastRayPosition = rayPos;
rayPos += rayStep;
// Linear search - Loop until find a point inside and outside the terrain Vector3
Vec3 normal;
float height = getHeight(rayPos.x, rayPos.z, &normal);
while (rayPos.y > height)
{
lastRayPosition = rayPos;
rayPos += rayStep;
if (normal.isZero())
{
intersectionPoint = Vec3(0, 0, 0);
return false;
}
height = getHeight(rayPos.x, rayPos.z);
}
Vec3 startPosition = lastRayPosition;
Vec3 endPosition = rayPos;
for (int i = 0; i < 32; i++)
{
// Binary search pass
Vec3 middlePoint = (startPosition + endPosition) * 0.5f;
if (middlePoint.y < height)
endPosition = middlePoint;
else
startPosition = middlePoint;
}
Vec3 collisionPoint = (startPosition + endPosition) * 0.5f;
intersectionPoint = collisionPoint;
return true;
}
void Terrain::setMaxDetailMapAmount(int max_value) void Terrain::setMaxDetailMapAmount(int max_value)
{ {
_maxDetailMapValue = max_value; _maxDetailMapValue = max_value;

View File

@ -302,22 +302,22 @@ public:
* @param normal the specified position's normal vector in terrain . if this argument is NULL or nullptr,Normal calculation shall be skip. * @param normal the specified position's normal vector in terrain . if this argument is NULL or nullptr,Normal calculation shall be skip.
* @return the height value of the specified position of the terrain, if the (X,Z) position is out of the terrain bounds,it shall return 0; * @return the height value of the specified position of the terrain, if the (X,Z) position is out of the terrain bounds,it shall return 0;
**/ **/
float getHeight(float x, float z, Vec3 * normal= nullptr); float getHeight(float x, float z, Vec3 * normal= nullptr) const;
/**get specified position's height mapping to the terrain,use bi-linear interpolation method /**get specified position's height mapping to the terrain,use bi-linear interpolation method
* @param pos the position (X,Z) * @param pos the position (X,Z)
* @param normal the specified position's normal vector in terrain . if this argument is NULL or nullptr,Normal calculation shall be skip. * @param normal the specified position's normal vector in terrain . if this argument is NULL or nullptr,Normal calculation shall be skip.
* @return the height value of the specified position of the terrain, if the (X,Z) position is out of the terrain bounds,it shall return 0; * @return the height value of the specified position of the terrain, if the (X,Z) position is out of the terrain bounds,it shall return 0;
**/ **/
float getHeight(Vec2 pos, Vec3*Normal = nullptr); float getHeight(Vec2 pos, Vec3*Normal = nullptr) const;
/**get the normal of the specified pistion in terrain /**get the normal of the specified pistion in terrain
* @return the normal vector of the specified position of the terrain. * @return the normal vector of the specified position of the terrain.
* @note the fast normal calculation may not get precise normal vector. * @note the fast normal calculation may not get precise normal vector.
**/ **/
Vec3 getNormal(int pixelX, int pixelY); Vec3 getNormal(int pixelX, int pixelY) const;
/**get height from the raw height filed*/ /**get height from the raw height filed*/
float getImageHeight(int pixelX, int pixelY); float getImageHeight(int pixelX, int pixelY) const;
/**show the wireline instead of the surface,Debug Use only. /**show the wireline instead of the surface,Debug Use only.
* @Note only support desktop platform * @Note only support desktop platform
**/ **/
@ -344,7 +344,15 @@ public:
* Ray-Terrain intersection. * Ray-Terrain intersection.
* @return the intersection point * @return the intersection point
*/ */
Vec3 getIntersectionPoint(const Ray & ray); Vec3 getIntersectionPoint(const Ray & ray) const;
/**
* Ray-Terrain intersection.
* @param ray to hit the terrain
* @param intersectionPoint hit point if hitted
* @return true if hit, false otherwise
*/
bool getIntersectionPoint(const Ray & ray, Vec3 & intersectionPoint) const;
/** /**
* set the MaxDetailAmount. * set the MaxDetailAmount.

View File

@ -1,23 +1,6 @@
LOCAL_PATH := $(call my-dir) LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := cocosdenshion_static #New AudioEngine
LOCAL_MODULE_FILENAME := libcocosdenshion
LOCAL_SRC_FILES := cddSimpleAudioEngine.cpp \
ccdandroidUtils.cpp \
jni/cddandroidAndroidJavaEngine.cpp
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../include
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../include \
$(LOCAL_PATH)/../.. \
$(LOCAL_PATH)/../../platform/android
include $(BUILD_STATIC_LIBRARY)
#new audio engine
include $(CLEAR_VARS) include $(CLEAR_VARS)
LOCAL_MODULE := audioengine_static LOCAL_MODULE := audioengine_static
@ -36,3 +19,23 @@ LOCAL_C_INCLUDES := $(LOCAL_PATH)/../include \
$(LOCAL_PATH)/../../platform/android $(LOCAL_PATH)/../../platform/android
include $(BUILD_STATIC_LIBRARY) include $(BUILD_STATIC_LIBRARY)
#SimpleAudioEngine
include $(CLEAR_VARS)
LOCAL_MODULE := cocosdenshion_static
LOCAL_MODULE_FILENAME := libcocosdenshion
LOCAL_SRC_FILES := cddSimpleAudioEngine.cpp \
ccdandroidUtils.cpp \
jni/cddandroidAndroidJavaEngine.cpp
LOCAL_STATIC_LIBRARIES := audioengine_static
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../include
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../include \
$(LOCAL_PATH)/../.. \
$(LOCAL_PATH)/../../platform/android
include $(BUILD_STATIC_LIBRARY)

View File

@ -1,6 +1,6 @@
/**************************************************************************** /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc. Copyright (c) 2013-2015 Chukong Technologies Inc.
http://www.cocos2d-x.org http://www.cocos2d-x.org
@ -24,10 +24,13 @@ THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "cddandroidAndroidJavaEngine.h" #include "cddandroidAndroidJavaEngine.h"
#include "platform/android/jni/JniHelper.h" #include <stdlib.h>
#include "ccdandroidUtils.h"
#include <android/log.h> #include <android/log.h>
#include <jni.h> #include <jni.h>
#include <sys/system_properties.h>
#include "platform/android/jni/JniHelper.h"
#include "ccdandroidUtils.h"
#include "audio/include/AudioEngine.h"
// logging // logging
#define LOG_TAG "cocosdenshion::android::AndroidJavaEngine" #define LOG_TAG "cocosdenshion::android::AndroidJavaEngine"
@ -36,282 +39,463 @@ THE SOFTWARE.
// Java class // Java class
#define CLASS_NAME "org/cocos2dx/lib/Cocos2dxHelper" #define CLASS_NAME "org/cocos2dx/lib/Cocos2dxHelper"
namespace CocosDenshion { using namespace cocos2d::experimental;
namespace android { using namespace CocosDenshion::android;
bool AndroidJavaEngine::getJNIStaticMethodInfo(cocos2d::JniMethodInfo &methodinfo, static inline bool getJNIStaticMethodInfo(cocos2d::JniMethodInfo &methodinfo,
const char *methodName, const char *methodName,
const char *paramCode) { const char *paramCode) {
return cocos2d::JniHelper::getStaticMethodInfo(methodinfo, return cocos2d::JniHelper::getStaticMethodInfo(methodinfo,
CLASS_NAME, CLASS_NAME,
methodName, methodName,
paramCode); paramCode);
} }
AndroidJavaEngine::~AndroidJavaEngine() { AndroidJavaEngine::AndroidJavaEngine()
cocos2d::JniMethodInfo methodInfo; : _implementBaseOnAudioEngine(false)
, _effectVolume(1.f)
if (!getJNIStaticMethodInfo(methodInfo, "end", "()V")) { {
return ; char sdk_ver_str[PROP_VALUE_MAX] = "0";
} auto len = __system_property_get("ro.build.version.sdk", sdk_ver_str);
if (len > 0)
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID); {
methodInfo.env->DeleteLocalRef(methodInfo.classID); auto sdk_ver = atoi(sdk_ver_str);
} __android_log_print(ANDROID_LOG_DEBUG, "cocos2d", "android build version:%d", sdk_ver);
if (sdk_ver == 21)
void AndroidJavaEngine::preloadBackgroundMusic(const char* pszFilePath) { {
std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(pszFilePath); _implementBaseOnAudioEngine = true;
// void playBackgroundMusic(String,boolean)
cocos2d::JniMethodInfo methodInfo;
if (! getJNIStaticMethodInfo(methodInfo, "preloadBackgroundMusic", "(Ljava/lang/String;)V")) {
return;
}
jstring stringArg = methodInfo.env->NewStringUTF(fullPath.c_str());
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, stringArg);
methodInfo.env->DeleteLocalRef(stringArg);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::playBackgroundMusic(const char* pszFilePath, bool bLoop) {
std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(pszFilePath);
cocos2d::JniMethodInfo methodInfo;
if (! getJNIStaticMethodInfo(methodInfo, "playBackgroundMusic", "(Ljava/lang/String;Z)V")) {
return;
}
jstring stringArg = methodInfo.env->NewStringUTF(fullPath.c_str());
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, stringArg, bLoop);
methodInfo.env->DeleteLocalRef(stringArg);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::stopBackgroundMusic(bool bReleaseData) {
cocos2d::JniMethodInfo methodInfo;
if (! getJNIStaticMethodInfo(methodInfo, "stopBackgroundMusic", "()V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::pauseBackgroundMusic() {
cocos2d::JniMethodInfo methodInfo;
if (! getJNIStaticMethodInfo(methodInfo, "pauseBackgroundMusic", "()V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::resumeBackgroundMusic() {
cocos2d::JniMethodInfo methodInfo;
if (! getJNIStaticMethodInfo(methodInfo, "resumeBackgroundMusic", "()V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::rewindBackgroundMusic() {
cocos2d::JniMethodInfo methodInfo;
if (! getJNIStaticMethodInfo(methodInfo, "rewindBackgroundMusic", "()V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
bool AndroidJavaEngine::willPlayBackgroundMusic() {
return true;
}
bool AndroidJavaEngine::isBackgroundMusicPlaying() {
cocos2d::JniMethodInfo methodInfo;
jboolean ret = false;
if (! getJNIStaticMethodInfo(methodInfo, "isBackgroundMusicPlaying", "()Z")) {
return ret;
}
ret = methodInfo.env->CallStaticBooleanMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
return ret;
}
float AndroidJavaEngine::getBackgroundMusicVolume() {
cocos2d::JniMethodInfo methodInfo;
jfloat ret = -1.0;
if (! getJNIStaticMethodInfo(methodInfo, "getBackgroundMusicVolume", "()F")) {
return ret;
}
ret = methodInfo.env->CallStaticFloatMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
return ret;
}
void AndroidJavaEngine::setBackgroundMusicVolume(float volume) {
cocos2d::JniMethodInfo methodInfo;
if (! getJNIStaticMethodInfo(methodInfo, "setBackgroundMusicVolume", "(F)V")) {
return ;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, volume);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
float AndroidJavaEngine::getEffectsVolume() {
cocos2d::JniMethodInfo methodInfo;
jfloat ret = -1.0;
if (! getJNIStaticMethodInfo(methodInfo, "getEffectsVolume", "()F")) {
return ret;
}
ret = methodInfo.env->CallStaticFloatMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
return ret;
}
void AndroidJavaEngine::setEffectsVolume(float volume) {
cocos2d::JniMethodInfo methodInfo;
if (! getJNIStaticMethodInfo(methodInfo, "setEffectsVolume", "(F)V")) {
return ;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, volume);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
unsigned int AndroidJavaEngine::playEffect(const char* pszFilePath, bool bLoop,
float pitch, float pan, float gain) {
cocos2d::JniMethodInfo methodInfo;
int ret = 0;
std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(pszFilePath);
if (! getJNIStaticMethodInfo(methodInfo, "playEffect", "(Ljava/lang/String;ZFFF)I")) {
return ret;
}
jstring stringArg = methodInfo.env->NewStringUTF(fullPath.c_str());
ret = methodInfo.env->CallStaticIntMethod(methodInfo.classID,
methodInfo.methodID,
stringArg,
bLoop,
pitch, pan, gain);
methodInfo.env->DeleteLocalRef(stringArg);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
return (unsigned int)ret;
}
void AndroidJavaEngine::pauseEffect(unsigned int nSoundId) {
cocos2d::JniMethodInfo methodInfo;
if (! getJNIStaticMethodInfo(methodInfo, "pauseEffect", "(I)V")) {
return ;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, (int)nSoundId);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::pauseAllEffects() {
cocos2d::JniMethodInfo methodInfo;
if (! getJNIStaticMethodInfo(methodInfo, "pauseAllEffects", "()V")) {
return ;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::resumeEffect(unsigned int nSoundId) {
cocos2d::JniMethodInfo methodInfo;
if (! getJNIStaticMethodInfo(methodInfo, "resumeEffect", "(I)V")) {
return ;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, (int)nSoundId);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::resumeAllEffects() {
cocos2d::JniMethodInfo methodInfo;
if (! getJNIStaticMethodInfo(methodInfo, "resumeAllEffects", "()V")) {
return ;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::stopEffect(unsigned int nSoundId) {
cocos2d::JniMethodInfo methodInfo;
if (! getJNIStaticMethodInfo(methodInfo, "stopEffect", "(I)V")) {
return ;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, (int)nSoundId);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::stopAllEffects() {
cocos2d::JniMethodInfo methodInfo;
if (! getJNIStaticMethodInfo(methodInfo, "stopAllEffects", "()V")) {
return ;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
static void loadEffect(const char* pszFilePath, char* loadEffectName) {
cocos2d::JniMethodInfo methodInfo;
std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(pszFilePath);
if (! cocos2d::JniHelper::getStaticMethodInfo(methodInfo, CLASS_NAME, loadEffectName, "(Ljava/lang/String;)V")) {
return ;
}
jstring stringArg = methodInfo.env->NewStringUTF(fullPath.c_str());
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, stringArg);
methodInfo.env->DeleteLocalRef(stringArg);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::preloadEffect(const char* pszFilePath) {
loadEffect(pszFilePath, "preloadEffect");
}
void AndroidJavaEngine::unloadEffect(const char* pszFilePath) {
loadEffect(pszFilePath, "unloadEffect");
} }
} }
} else
{
__android_log_print(ANDROID_LOG_DEBUG, "cocos2d", "%s", "Fail to get android build version.");
}
}
AndroidJavaEngine::~AndroidJavaEngine() {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "end", "()V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::preloadBackgroundMusic(const char* filePath) {
std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(filePath);
// void playBackgroundMusic(String,boolean)
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "preloadBackgroundMusic", "(Ljava/lang/String;)V")) {
return;
}
jstring stringArg = methodInfo.env->NewStringUTF(fullPath.c_str());
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, stringArg);
methodInfo.env->DeleteLocalRef(stringArg);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::playBackgroundMusic(const char* filePath, bool loop) {
std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(filePath);
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "playBackgroundMusic", "(Ljava/lang/String;Z)V")) {
return;
}
jstring stringArg = methodInfo.env->NewStringUTF(fullPath.c_str());
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, stringArg, loop);
methodInfo.env->DeleteLocalRef(stringArg);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::stopBackgroundMusic(bool releaseData) {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "stopBackgroundMusic", "()V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::pauseBackgroundMusic() {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "pauseBackgroundMusic", "()V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::resumeBackgroundMusic() {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "resumeBackgroundMusic", "()V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
void AndroidJavaEngine::rewindBackgroundMusic() {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "rewindBackgroundMusic", "()V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
bool AndroidJavaEngine::willPlayBackgroundMusic() {
return true;
}
bool AndroidJavaEngine::isBackgroundMusicPlaying() {
cocos2d::JniMethodInfo methodInfo;
jboolean ret = false;
if (!getJNIStaticMethodInfo(methodInfo, "isBackgroundMusicPlaying", "()Z")) {
return ret;
}
ret = methodInfo.env->CallStaticBooleanMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
return ret;
}
float AndroidJavaEngine::getBackgroundMusicVolume() {
cocos2d::JniMethodInfo methodInfo;
jfloat ret = -1.0;
if (!getJNIStaticMethodInfo(methodInfo, "getBackgroundMusicVolume", "()F")) {
return ret;
}
ret = methodInfo.env->CallStaticFloatMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
return ret;
}
void AndroidJavaEngine::setBackgroundMusicVolume(float volume) {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "setBackgroundMusicVolume", "(F)V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, volume);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
static float _jni_getEffectsVolume() {
cocos2d::JniMethodInfo methodInfo;
jfloat ret = -1.0;
if (!getJNIStaticMethodInfo(methodInfo, "getEffectsVolume", "()F")) {
return ret;
}
ret = methodInfo.env->CallStaticFloatMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
return ret;
}
static void _jni_setEffectsVolume(float volume) {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "setEffectsVolume", "(F)V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, volume);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
static unsigned int _jni_playEffect(const char* filePath, bool loop, float pitch, float pan, float gain)
{
cocos2d::JniMethodInfo methodInfo;
int ret = 0;
std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(filePath);
if (!getJNIStaticMethodInfo(methodInfo, "playEffect", "(Ljava/lang/String;ZFFF)I")) {
return ret;
}
jstring stringArg = methodInfo.env->NewStringUTF(fullPath.c_str());
ret = methodInfo.env->CallStaticIntMethod(methodInfo.classID,
methodInfo.methodID,
stringArg,
loop,
pitch, pan, gain);
methodInfo.env->DeleteLocalRef(stringArg);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
return (unsigned int)ret;
}
static void _jni_pauseEffect(unsigned int soundId) {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "pauseEffect", "(I)V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, (int)soundId);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
static void _jni_pauseAllEffects() {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "pauseAllEffects", "()V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
static void _jni_resumeEffect(unsigned int soundId) {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "resumeEffect", "(I)V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, (int)soundId);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
static void _jni_resumeAllEffects() {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "resumeAllEffects", "()V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
static void _jni_stopEffect(unsigned int soundId) {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "stopEffect", "(I)V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, (int)soundId);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
static void _jni_stopAllEffects() {
cocos2d::JniMethodInfo methodInfo;
if (!getJNIStaticMethodInfo(methodInfo, "stopAllEffects", "()V")) {
return;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
static void loadEffect(const char* filePath, char* loadEffectName) {
cocos2d::JniMethodInfo methodInfo;
std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(filePath);
if (!cocos2d::JniHelper::getStaticMethodInfo(methodInfo, CLASS_NAME, loadEffectName, "(Ljava/lang/String;)V")) {
return;
}
jstring stringArg = methodInfo.env->NewStringUTF(fullPath.c_str());
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, stringArg);
methodInfo.env->DeleteLocalRef(stringArg);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
static void _jni_preloadEffect(const char* filePath) {
loadEffect(filePath, "preloadEffect");
}
static void _jni_unloadEffect(const char* filePath) {
loadEffect(filePath, "unloadEffect");
}
float AndroidJavaEngine::getEffectsVolume()
{
if (_implementBaseOnAudioEngine)
{
return _effectVolume;
}
else
{
return _jni_getEffectsVolume();
}
}
void AndroidJavaEngine::setEffectsVolume(float volume)
{
if (_implementBaseOnAudioEngine)
{
if (volume > 1.f)
{
volume = 1.f;
}
else if (volume < 0.f)
{
volume = 0.f;
}
if (_effectVolume != volume)
{
_effectVolume = volume;
for (auto& it : _soundIDs)
{
AudioEngine::setVolume(it.first, volume);
}
}
}
else
{
_jni_setEffectsVolume(volume);
}
}
unsigned int AndroidJavaEngine::playEffect(const char* filePath, bool loop,
float pitch, float pan, float gain)
{
if (_implementBaseOnAudioEngine)
{
auto soundID = AudioEngine::play2d(filePath, loop, _effectVolume);
if (soundID != AudioEngine::INVALID_AUDIO_ID)
{
_soundIDs[soundID] = soundID;
AudioEngine::setFinishCallback(soundID, [this](int id, const std::string& filePath){
_soundIDs.erase(id);
});
}
return soundID;
}
else
{
return _jni_playEffect(filePath, loop, pitch, pan, gain);
}
}
void AndroidJavaEngine::pauseEffect(unsigned int soundID)
{
if (_implementBaseOnAudioEngine)
{
AudioEngine::pause(soundID);
}
else
{
_jni_pauseEffect(soundID);
}
}
void AndroidJavaEngine::resumeEffect(unsigned int soundID)
{
if (_implementBaseOnAudioEngine)
{
AudioEngine::resume(soundID);
}
else
{
_jni_resumeEffect(soundID);
}
}
void AndroidJavaEngine::stopEffect(unsigned int soundID)
{
if (_implementBaseOnAudioEngine)
{
AudioEngine::stop(soundID);
_soundIDs.erase(soundID);
}
else
{
_jni_stopEffect(soundID);
}
}
void AndroidJavaEngine::pauseAllEffects()
{
if (_implementBaseOnAudioEngine)
{
for (auto& it : _soundIDs)
{
AudioEngine::pause(it.first);
}
}
else
{
_jni_pauseAllEffects();
}
}
void AndroidJavaEngine::resumeAllEffects()
{
if (_implementBaseOnAudioEngine)
{
for (auto& it : _soundIDs)
{
AudioEngine::resume(it.first);
}
}
else
{
_jni_resumeAllEffects();
}
}
void AndroidJavaEngine::stopAllEffects()
{
if (_implementBaseOnAudioEngine)
{
for (auto& it : _soundIDs)
{
AudioEngine::stop(it.first);
}
_soundIDs.clear();
}
else
{
_jni_stopAllEffects();
}
}
void AndroidJavaEngine::preloadEffect(const char* filePath)
{
if (!_implementBaseOnAudioEngine)
{
_jni_preloadEffect(filePath);
}
}
void AndroidJavaEngine::unloadEffect(const char* filePath)
{
if (!_implementBaseOnAudioEngine)
{
_jni_unloadEffect(filePath);
}
}

View File

@ -1,6 +1,6 @@
/**************************************************************************** /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc. Copyright (c) 2013-2015 Chukong Technologies Inc.
http://www.cocos2d-x.org http://www.cocos2d-x.org
@ -27,39 +27,42 @@ THE SOFTWARE.
#include "SimpleAudioEngine.h" #include "SimpleAudioEngine.h"
#include "platform/android/jni/JniHelper.h" #include "platform/android/jni/JniHelper.h"
#include <unordered_map>
namespace CocosDenshion { namespace CocosDenshion {
namespace android { namespace android {
class AndroidJavaEngine : public SimpleAudioEngine { class AndroidJavaEngine : public SimpleAudioEngine {
public:
AndroidJavaEngine();
~AndroidJavaEngine(); ~AndroidJavaEngine();
void preloadBackgroundMusic(const char* pszFilePath); virtual void preloadBackgroundMusic(const char* filePath);
void playBackgroundMusic(const char* pszFilePath, bool bLoop); virtual void playBackgroundMusic(const char* filePath, bool loop);
void stopBackgroundMusic(bool bReleaseData); virtual void stopBackgroundMusic(bool releaseData);
void pauseBackgroundMusic(); virtual void pauseBackgroundMusic();
void resumeBackgroundMusic(); virtual void resumeBackgroundMusic();
void rewindBackgroundMusic(); virtual void rewindBackgroundMusic();
bool willPlayBackgroundMusic(); virtual bool willPlayBackgroundMusic();
bool isBackgroundMusicPlaying(); virtual bool isBackgroundMusicPlaying();
float getBackgroundMusicVolume(); virtual float getBackgroundMusicVolume();
void setBackgroundMusicVolume(float volume); virtual void setBackgroundMusicVolume(float volume);
float getEffectsVolume(); virtual float getEffectsVolume();
void setEffectsVolume(float volume); virtual void setEffectsVolume(float volume);
unsigned int playEffect(const char* pszFilePath, bool bLoop = false, virtual unsigned int playEffect(const char* filePath, bool loop = false,
float pitch = 1.0f, float pan = 0.0f, float gain = 1.0f); float pitch = 1.0f, float pan = 0.0f, float gain = 1.0f);
void pauseEffect(unsigned int nSoundId); virtual void pauseEffect(unsigned int soundId);
void pauseAllEffects(); virtual void pauseAllEffects();
void resumeEffect(unsigned int nSoundId); virtual void resumeEffect(unsigned int soundId);
void resumeAllEffects(); virtual void resumeAllEffects();
void stopEffect(unsigned int nSoundId); virtual void stopEffect(unsigned int soundId);
void stopAllEffects(); virtual void stopAllEffects();
void preloadEffect(const char* pszFilePath); virtual void preloadEffect(const char* filePath);
void unloadEffect(const char* pszFilePath); virtual void unloadEffect(const char* filePath);
private : private :
static bool getJNIStaticMethodInfo(cocos2d::JniMethodInfo &methodinfo, bool _implementBaseOnAudioEngine;
const char *methodName, float _effectVolume;
const char *paramCode); std::unordered_map<int, int> _soundIDs;
}; };
} }
} }

View File

@ -162,6 +162,7 @@ void AudioEngineInterruptionListenerCallback(void* user_data, UInt32 interruptio
{ {
if ([[[UIDevice currentDevice] systemVersion] intValue] > 5) { if ([[[UIDevice currentDevice] systemVersion] intValue] > 5) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:UIApplicationDidBecomeActiveNotification object:[AVAudioSession sharedInstance]];
} }
else { else {
AudioSessionInitialize(NULL, NULL, AudioEngineInterruptionListenerCallback, self); AudioSessionInitialize(NULL, NULL, AudioEngineInterruptionListenerCallback, self);
@ -172,6 +173,8 @@ void AudioEngineInterruptionListenerCallback(void* user_data, UInt32 interruptio
-(void)handleInterruption:(NSNotification*)notification -(void)handleInterruption:(NSNotification*)notification
{ {
static bool resumeOnBecomingActive = false;
if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification]) { if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification]) {
NSInteger reason = [[[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey] integerValue]; NSInteger reason = [[[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey] integerValue];
if (reason == AVAudioSessionInterruptionTypeBegan) { if (reason == AVAudioSessionInterruptionTypeBegan) {
@ -179,17 +182,35 @@ void AudioEngineInterruptionListenerCallback(void* user_data, UInt32 interruptio
} }
if (reason == AVAudioSessionInterruptionTypeEnded) { if (reason == AVAudioSessionInterruptionTypeEnded) {
OSStatus result = AudioSessionSetActive(true); if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
if (result) NSLog(@"Error setting audio session active! %d\n", result); NSError *error = nil;
[[AVAudioSession sharedInstance] setActive:YES error:&error];
alcMakeContextCurrent(s_ALContext); alcMakeContextCurrent(s_ALContext);
} else {
resumeOnBecomingActive = true;
}
} }
} }
if ([notification.name isEqualToString:UIApplicationDidBecomeActiveNotification] && resumeOnBecomingActive) {
resumeOnBecomingActive = false;
NSError *error = nil;
BOOL success = [[AVAudioSession sharedInstance]
setCategory: AVAudioSessionCategoryAmbient
error: &error];
if (!success) {
printf("Fail to set audio session.\n");
return;
}
[[AVAudioSession sharedInstance] setActive:YES error:&error];
alcMakeContextCurrent(s_ALContext);
}
} }
-(void) dealloc -(void) dealloc
{ {
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionInterruptionNotification object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionInterruptionNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
[super dealloc]; [super dealloc];
} }

View File

@ -37,6 +37,7 @@ inline void ThrowIfFailed(HRESULT hr)
// AudioCache // AudioCache
AudioCache::AudioCache() AudioCache::AudioCache()
: _isReady(false) : _isReady(false)
, _retry(false)
, _fileFullPath("") , _fileFullPath("")
, _srcReader(nullptr) , _srcReader(nullptr)
, _fileFormat(FileFormat::UNKNOWN) , _fileFormat(FileFormat::UNKNOWN)
@ -57,6 +58,10 @@ AudioCache::~AudioCache()
void AudioCache::readDataTask() void AudioCache::readDataTask()
{ {
if (_isReady) {
return;
}
std::wstring path(_fileFullPath.begin(), _fileFullPath.end()); std::wstring path(_fileFullPath.begin(), _fileFullPath.end());
if (nullptr != _srcReader) { if (nullptr != _srcReader) {
@ -68,31 +73,34 @@ void AudioCache::readDataTask()
{ {
case FileFormat::WAV: case FileFormat::WAV:
_srcReader = new (std::nothrow) WAVReader(); _srcReader = new (std::nothrow) WAVReader();
if (_srcReader && _srcReader->initialize(_fileFullPath)) {
_audInfo._totalAudioBytes = _srcReader->getTotalAudioBytes();
_audInfo._wfx = _srcReader->getWaveFormatInfo();
_isReady = true;
invokeCallbacks();
}
break; break;
case FileFormat::OGG: case FileFormat::OGG:
_srcReader = new (std::nothrow) OGGReader();
break; break;
case FileFormat::MP3: case FileFormat::MP3:
_srcReader = new (std::nothrow) MP3Reader(); _srcReader = new (std::nothrow) MP3Reader();
if (_srcReader && _srcReader->initialize(_fileFullPath)) {
_audInfo._totalAudioBytes = _srcReader->getTotalAudioBytes();
_audInfo._wfx = _srcReader->getWaveFormatInfo();
_isReady = true;
invokeCallbacks();
}
break; break;
case FileFormat::UNKNOWN: case FileFormat::UNKNOWN:
default: default:
break; break;
} }
if (_srcReader && _srcReader->initialize(_fileFullPath)) {
_audInfo._totalAudioBytes = _srcReader->getTotalAudioBytes();
_audInfo._wfx = _srcReader->getWaveFormatInfo();
_isReady = true;
_retry = false;
invokeCallbacks();
}
if (!_isReady) {
_retry = true;
log("Failed to read input file: %s.\n", _fileFullPath.c_str());
}
} }
void AudioCache::addCallback(const std::function<void()> &callback) void AudioCache::addCallback(const std::function<void()> &callback)
@ -105,6 +113,10 @@ void AudioCache::addCallback(const std::function<void()> &callback)
_callbacks.push_back(callback); _callbacks.push_back(callback);
} }
_cbMutex.unlock(); _cbMutex.unlock();
if (_retry) {
readDataTask();
}
} }
void AudioCache::invokeCallbacks() void AudioCache::invokeCallbacks()
@ -290,6 +302,9 @@ void AudioPlayer::setVolume(float volume)
if (FAILED(_xaMasterVoice->SetVolume(volume))) { if (FAILED(_xaMasterVoice->SetVolume(volume))) {
error(); error();
} }
else {
_volume = volume;
}
} }
} }
@ -371,7 +386,7 @@ bool AudioPlayer::_play(bool resume)
if (_state == AudioPlayerState::PAUSED && !resume || nullptr == _xaSourceVoice) break; if (_state == AudioPlayerState::PAUSED && !resume || nullptr == _xaSourceVoice) break;
if (FAILED(_xaSourceVoice->Start())) { if (FAILED(_xaMasterVoice->SetVolume(_volume)) || FAILED(_xaSourceVoice->Start())) {
error(); error();
} }
else { else {

View File

@ -65,6 +65,7 @@ private:
AudioCache& operator=(const AudioCache&); AudioCache& operator=(const AudioCache&);
private: private:
bool _retry;
bool _isReady; bool _isReady;
AudioInfo _audInfo; AudioInfo _audInfo;
std::mutex _cbMutex; std::mutex _cbMutex;

View File

@ -160,7 +160,7 @@ int AudioEngineImpl::play2d(const std::string &filePath, bool loop, float volume
} }
else if (ext.compare(".ogg") == 0){ else if (ext.compare(".ogg") == 0){
audioCache->_fileFormat = FileFormat::OGG; audioCache->_fileFormat = FileFormat::OGG;
//eraseCache = false; //TODO add support for OGG eraseCache = false;
} }
else if (ext.compare(".mp3") == 0){ else if (ext.compare(".mp3") == 0){
audioCache->_fileFormat = FileFormat::MP3; audioCache->_fileFormat = FileFormat::MP3;
@ -168,7 +168,6 @@ int AudioEngineImpl::play2d(const std::string &filePath, bool loop, float volume
} }
else{ else{
log("unsupported media type:%s\n", ext.c_str()); log("unsupported media type:%s\n", ext.c_str());
eraseCache = false;
} }
if (eraseCache){ if (eraseCache){

View File

@ -53,6 +53,24 @@ void AudioSourceReader::flushChunks()
_rwMutex.unlock(); _rwMutex.unlock();
} }
void AudioSourceReader::seekTo(const float ratio)
{
if (_isStreaming) {
auto newPos = ratio * _audioSize;
if (!newPos && !_isDirty && _chnkQ.size()) // already in 0.0 position
return;
_bytesRead = newPos;
flushChunks();
auto alignment = _wfx.nChannels * _wfx.nBlockAlign;
_bytesRead = _bytesRead >= _audioSize ? (_audioSize - alignment) : _bytesRead - (_bytesRead % alignment);
for (int i = 0; i < QUEUEBUFFER_NUM; i++) {
produceChunk();
}
}
}
// WAVFileReader // WAVFileReader
WAVReader::WAVReader() : WAVReader::WAVReader() :
@ -78,10 +96,8 @@ bool WAVReader::initialize(const std::string& filePath)
flushChunks(); flushChunks();
_rwMutex.lock();
_streamer = ref new MediaStreamer; _streamer = ref new MediaStreamer;
_streamer->Initialize(std::wstring(_filePath.begin(), _filePath.end()).c_str(), true); _streamer->Initialize(std::wstring(_filePath.begin(), _filePath.end()).c_str(), true);
_rwMutex.unlock();
_wfx = _streamer->GetOutputWaveFormatEx(); _wfx = _streamer->GetOutputWaveFormatEx();
UINT32 dataSize = _streamer->GetMaxStreamLengthInBytes(); UINT32 dataSize = _streamer->GetMaxStreamLengthInBytes();
@ -162,31 +178,7 @@ void WAVReader::produceChunk()
void WAVReader::seekTo(const float ratio) void WAVReader::seekTo(const float ratio)
{ {
if (_isStreaming) { AudioSourceReader::seekTo(ratio);
auto newPos = ratio * _audioSize;
if (!newPos && !_isDirty && _chnkQ.size()) // already in 0.0 position
return;
_bytesRead = newPos;
flushChunks();
switch (_wfx.wFormatTag)
{
case WAVE_FORMAT_PCM:
case WAVE_FORMAT_ADPCM: {
auto alignment = _wfx.nChannels * _wfx.nBlockAlign;
_bytesRead = _bytesRead >= _audioSize ? (_audioSize - alignment) : _bytesRead - (_bytesRead % alignment);
} break;
default:
break;
}
for (int i = 0; i < QUEUEBUFFER_NUM; i++) {
produceChunk();
}
}
} }
@ -299,21 +291,7 @@ void MP3Reader::produceChunk()
void MP3Reader::seekTo(const float ratio) void MP3Reader::seekTo(const float ratio)
{ {
if (_isStreaming) { AudioSourceReader::seekTo(ratio);
auto newPos = ratio * _audioSize;
if (!newPos && !_isDirty && _chnkQ.size()) // already in 0.0 position
return;
_bytesRead = newPos;
flushChunks();
auto alignment = _wfx.nChannels * _wfx.nBlockAlign;
_bytesRead = _bytesRead >= _audioSize ? (_audioSize - alignment) : _bytesRead - (_bytesRead % alignment);
for (int i = 0; i < QUEUEBUFFER_NUM; i++) {
produceChunk();
}
}
} }
HRESULT MP3Reader::configureSourceReader(IMFSourceReader* pReader, IMFMediaType** ppDecomprsdAudioType) HRESULT MP3Reader::configureSourceReader(IMFSourceReader* pReader, IMFMediaType** ppDecomprsdAudioType)
@ -520,4 +498,137 @@ Wrappers::FileHandle MP3Reader::openFile(const std::string& path, bool append)
return Microsoft::WRL::Wrappers::FileHandle(CreateFile2(std::wstring(path.begin(), path.end()).c_str(), access, FILE_SHARE_READ, creation, &extParams)); return Microsoft::WRL::Wrappers::FileHandle(CreateFile2(std::wstring(path.begin(), path.end()).c_str(), access, FILE_SHARE_READ, creation, &extParams));
} }
// OGGReader
OGGReader::OGGReader()
{
}
OGGReader::~OGGReader()
{
if (_vorbisFd) {
ov_clear(_vorbisFd.get());
}
}
bool OGGReader::initialize(const std::string& filePath)
{
bool ret = false;
_filePath = filePath;
do {
_vorbisFd = std::make_unique<OggVorbis_File>();
if (ov_fopen(FileUtils::getInstance()->getSuitableFOpen(_filePath).c_str(), _vorbisFd.get())){
break;
}
auto vi = ov_info(_vorbisFd.get(), -1);
if (!vi) {
break;
}
auto totalFrames = ov_pcm_total(_vorbisFd.get(), -1);
auto bytesPerFrame = vi->channels * 2;
_audioSize = totalFrames * bytesPerFrame;
_wfx.wFormatTag = WAVE_FORMAT_PCM;
_wfx.nChannels = vi->channels;
_wfx.nSamplesPerSec = vi->rate;
_wfx.nAvgBytesPerSec = vi->rate * bytesPerFrame;
_wfx.nBlockAlign = bytesPerFrame;
_wfx.wBitsPerSample = (bytesPerFrame / vi->channels) * 8;
_wfx.cbSize = 0;
if (_audioSize <= PCMDATA_CACHEMAXSIZE) {
produceChunk();
}
else {
_isStreaming = true;
for (int i = 0; i < QUEUEBUFFER_NUM; i++) {
produceChunk();
}
}
ret = true;
} while (false);
return ret;
}
bool OGGReader::consumeChunk(AudioDataChunk& chunk)
{
bool ret = false;
_isDirty = true;
_rwMutex.lock();
if (_chnkQ.size() > 0) {
chunk = _chnkQ.front();
if (_isStreaming) {
_chnkQ.pop();
}
ret = true;
}
_rwMutex.unlock();
return ret;
}
void OGGReader::produceChunk()
{
_rwMutex.lock();
int chunkSize = _audioSize;
do {
if (!_isStreaming && _chnkQ.size() || _chnkQ.size() >= QUEUEBUFFER_NUM) {
break;
}
if (_isStreaming) {
chunkSize = std::min(CHUNK_SIZE_MAX, _audioSize - _bytesRead);
}
if (!chunkSize && !_chnkQ.size()) {
auto alignment = _wfx.nChannels * _wfx.nBlockAlign;
_bytesRead -= alignment;
chunkSize = alignment;
}
if (!chunkSize) {
break;
}
int retSize = 0;
AudioDataChunk chunk = { 0 };
chunk._data = std::make_shared<PCMBuffer>(chunkSize);
auto newPos = (1.0f * _bytesRead / _audioSize) * ov_time_total(_vorbisFd.get(), -1);
if (ov_time_seek(_vorbisFd.get(), newPos)){
break;
}
do
{
long br = 0;
int current_section = 0;
if ((br = ov_read(_vorbisFd.get(), (char*)chunk._data->data() + retSize, chunkSize - retSize, 0, 2, 1, &current_section)) == 0) {
break;
}
retSize += br;
} while (retSize < chunkSize);
_bytesRead += retSize;
chunk._dataSize = retSize;
chunk._seqNo = ((float)_bytesRead / _audioSize) * ((float)_audioSize / CHUNK_SIZE_MAX);
chunk._endOfStream = (_bytesRead >= _audioSize);
_chnkQ.push(chunk);
} while (false);
_rwMutex.unlock();
}
void OGGReader::seekTo(const float ratio)
{
AudioSourceReader::seekTo(ratio);
}
#endif #endif

View File

@ -30,6 +30,8 @@
#include <queue> #include <queue>
#include <mutex> #include <mutex>
#include "MediaStreamer.h" #include "MediaStreamer.h"
#include "ogg/ogg.h"
#include "vorbis/vorbisfile.h"
NS_CC_BEGIN NS_CC_BEGIN
namespace experimental{ namespace experimental{
@ -132,6 +134,22 @@ class MP3Reader : public AudioSourceReader
std::string _mappedWavFile; std::string _mappedWavFile;
}; };
class OGGReader : public AudioSourceReader
{
public:
OGGReader();
virtual ~OGGReader();
virtual bool initialize(const std::string& filePath) override;
virtual FileFormat getFileFormat() override { return FileFormat::WAV; }
virtual bool consumeChunk(AudioDataChunk& chunk) override;
virtual void produceChunk() override;
virtual void seekTo(const float ratio) override;
private:
std::unique_ptr<OggVorbis_File> _vorbisFd;
};
} }
NS_CC_END NS_CC_END
#endif // __AUDIO_SOURCE_READER_H_ #endif // __AUDIO_SOURCE_READER_H_

View File

@ -24,6 +24,7 @@
****************************************************************************/ ****************************************************************************/
#include "base/CCData.h" #include "base/CCData.h"
#include "base/CCConsole.h"
NS_CC_BEGIN NS_CC_BEGIN

View File

@ -23,6 +23,7 @@
****************************************************************************/ ****************************************************************************/
#include "base/CCEventListener.h" #include "base/CCEventListener.h"
#include "base/CCConsole.h"
NS_CC_BEGIN NS_CC_BEGIN

View File

@ -24,6 +24,7 @@
#include "base/CCEventListenerAcceleration.h" #include "base/CCEventListenerAcceleration.h"
#include "base/CCEventAcceleration.h" #include "base/CCEventAcceleration.h"
#include "base/CCConsole.h"
NS_CC_BEGIN NS_CC_BEGIN

View File

@ -60,6 +60,7 @@ ActionNode::~ActionNode()
else else
{ {
CC_SAFE_RELEASE_NULL(_action); CC_SAFE_RELEASE_NULL(_action);
CC_SAFE_RELEASE_NULL(_actionSpawn);
} }
for (auto object : _frameArray) for (auto object : _frameArray)
@ -464,6 +465,7 @@ Spawn * ActionNode::refreshActionProperty()
else else
{ {
CC_SAFE_RELEASE_NULL(_action); CC_SAFE_RELEASE_NULL(_action);
CC_SAFE_RELEASE_NULL(_actionSpawn);
} }
_actionSpawn = Spawn::create(cSpawnArray); _actionSpawn = Spawn::create(cSpawnArray);

View File

@ -56,6 +56,16 @@ void ComAudio::onExit()
stopAllEffects(); stopAllEffects();
} }
void ComAudio::onAdd()
{
}
void ComAudio::onRemove()
{
stopBackgroundMusic(true);
stopAllEffects();
}
bool ComAudio::isEnabled() const bool ComAudio::isEnabled() const
{ {
return _enabled; return _enabled;

View File

@ -59,6 +59,16 @@ public:
* @lua NA * @lua NA
*/ */
virtual void onExit() override; virtual void onExit() override;
/**
* @js NA
* @lua NA
*/
virtual void onAdd() override;
/**
* @js NA
* @lua NA
*/
virtual void onRemove() override;
virtual bool isEnabled() const override; virtual bool isEnabled() const override;
virtual void setEnabled(bool b) override; virtual void setEnabled(bool b) override;
virtual bool serialize(void* r) override; virtual bool serialize(void* r) override;

View File

@ -54,6 +54,18 @@ void ComController::onExit()
{ {
} }
void ComController::onAdd()
{
if (_owner != nullptr)
{
_owner->scheduleUpdate();
}
}
void ComController::onRemove()
{
}
void ComController::update(float delta) void ComController::update(float delta)
{ {
} }

View File

@ -59,6 +59,16 @@ public:
* @lua NA * @lua NA
*/ */
virtual void onExit() override; virtual void onExit() override;
/**
* @js NA
* @lua NA
*/
virtual void onAdd() override;
/**
* @js NA
* @lua NA
*/
virtual void onRemove() override;
virtual void update(float delta) override; virtual void update(float delta) override;
virtual bool isEnabled() const override; virtual bool isEnabled() const override;
virtual void setEnabled(bool b) override; virtual void setEnabled(bool b) override;

View File

@ -68,6 +68,22 @@ void ComRender::onExit()
} }
} }
void ComRender::onAdd()
{
if (_owner != nullptr)
{
_owner->addChild(_render);
}
}
void ComRender::onRemove()
{
if (_owner != nullptr)
{
_owner->removeChild(_render, true);
}
}
cocos2d::Node* ComRender::getNode() cocos2d::Node* ComRender::getNode()
{ {
return _render; return _render;

View File

@ -57,6 +57,16 @@ public:
* @lua NA * @lua NA
*/ */
virtual void onExit() override; virtual void onExit() override;
/**
* @js NA
* @lua NA
*/
virtual void onAdd() override;
/**
* @js NA
* @lua NA
*/
virtual void onRemove() override;
virtual bool serialize(void* r) override; virtual bool serialize(void* r) override;
virtual cocos2d::Node* getNode(); virtual cocos2d::Node* getNode();
virtual void setNode(cocos2d::Node *node); virtual void setNode(cocos2d::Node *node);

View File

@ -177,14 +177,18 @@ bool CocoLoader::ReadCocoBinBuff(char* pBinBuff)
pTempBuff += sizeof(stCocoFileHeader); pTempBuff += sizeof(stCocoFileHeader);
char* pStartAddr = m_pMemoryBuff = pTempBuff; char* pStartAddr = m_pMemoryBuff = pTempBuff;
if( m_pFileHeader->m_nCompressSize > 0 ) char* pDestBuff = new char[m_pFileHeader->m_nDataSize];
if (m_pFileHeader->m_nCompressSize > 0)
{ {
char* pDestBuff = new char[m_pFileHeader->m_nDataSize];
uLongf dwSrcSize = m_pFileHeader->m_nCompressSize; uLongf dwSrcSize = m_pFileHeader->m_nCompressSize;
uLongf dwDestSize = m_pFileHeader->m_nDataSize; uLongf dwDestSize = m_pFileHeader->m_nDataSize;
uncompress((Bytef*)pDestBuff,&dwDestSize,(Bytef*)m_pMemoryBuff,dwSrcSize); uncompress((Bytef*)pDestBuff,&dwDestSize,(Bytef*)m_pMemoryBuff,dwSrcSize);
pStartAddr = m_pMemoryBuff = pDestBuff;
} }
else
{
memcpy(pDestBuff, m_pMemoryBuff, m_pFileHeader->m_nDataSize);
}
pStartAddr = m_pMemoryBuff = pDestBuff;
m_pObjectDescArray = (stExpCocoObjectDesc*)pStartAddr; m_pObjectDescArray = (stExpCocoObjectDesc*)pStartAddr;

View File

@ -0,0 +1,489 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|ARM">
<Configuration>Debug</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM">
<Configuration>Release</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\Animation.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\AnimationState.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\AnimationStateData.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\Atlas.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\AtlasAttachmentLoader.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\Attachment.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\AttachmentLoader.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\Bone.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\BoneData.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\BoundingBoxAttachment.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\Event.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\EventData.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\extension.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\IkConstraint.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\IkConstraintData.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\Json.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\MeshAttachment.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\PolygonBatch.cpp" />
<ClCompile Include="..\RegionAttachment.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\Skeleton.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\SkeletonAnimation.cpp" />
<ClCompile Include="..\SkeletonBounds.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\SkeletonData.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\SkeletonJson.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\SkeletonRenderer.cpp" />
<ClCompile Include="..\Skin.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\SkinnedMeshAttachment.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\Slot.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\SlotData.c">
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsWinRT>
<CompileAsWinRT Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsWinRT>
</ClCompile>
<ClCompile Include="..\spine-cocos2dx.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\Animation.h" />
<ClInclude Include="..\AnimationState.h" />
<ClInclude Include="..\AnimationStateData.h" />
<ClInclude Include="..\Atlas.h" />
<ClInclude Include="..\AtlasAttachmentLoader.h" />
<ClInclude Include="..\Attachment.h" />
<ClInclude Include="..\AttachmentLoader.h" />
<ClInclude Include="..\Bone.h" />
<ClInclude Include="..\BoneData.h" />
<ClInclude Include="..\BoundingBoxAttachment.h" />
<ClInclude Include="..\Event.h" />
<ClInclude Include="..\EventData.h" />
<ClInclude Include="..\extension.h" />
<ClInclude Include="..\IkConstraint.h" />
<ClInclude Include="..\IkConstraintData.h" />
<ClInclude Include="..\Json.h" />
<ClInclude Include="..\MeshAttachment.h" />
<ClInclude Include="..\PolygonBatch.h" />
<ClInclude Include="..\RegionAttachment.h" />
<ClInclude Include="..\Skeleton.h" />
<ClInclude Include="..\SkeletonAnimation.h" />
<ClInclude Include="..\SkeletonBounds.h" />
<ClInclude Include="..\SkeletonData.h" />
<ClInclude Include="..\SkeletonJson.h" />
<ClInclude Include="..\SkeletonRenderer.h" />
<ClInclude Include="..\Skin.h" />
<ClInclude Include="..\SkinnedMeshAttachment.h" />
<ClInclude Include="..\Slot.h" />
<ClInclude Include="..\SlotData.h" />
<ClInclude Include="..\spine-cocos2dx.h" />
<ClInclude Include="..\spine.h" />
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{4b3ba10a-941f-4e08-8a50-8a7fcb822bb8}</ProjectGuid>
<Keyword>StaticLibrary</Keyword>
<ProjectName>libSpine</ProjectName>
<RootNamespace>libSpine</RootNamespace>
<DefaultLanguage>en-US</DefaultLanguage>
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
<AppContainerApplication>true</AppContainerApplication>
<ApplicationType>Windows Store</ApplicationType>
<ApplicationTypeRevision>8.2</ApplicationTypeRevision>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\..\..\2d\win10_props\cocos2d_win10.props" />
<Import Project="..\..\..\2d\win10_props\cocos2d_win10_platform.props" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\..\..\2d\win10_props\cocos2d_win10.props" />
<Import Project="..\..\..\2d\win10_props\cocos2d_win10_platform.props" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\..\..\2d\win10_props\cocos2d_win10.props" />
<Import Project="..\..\..\2d\win10_props\cocos2d_win10_platform.props" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\..\..\2d\win10_props\cocos2d_win10.props" />
<Import Project="..\..\..\2d\win10_props\cocos2d_win10_platform.props" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\..\..\2d\win10_props\cocos2d_win10.props" />
<Import Project="..\..\..\2d\win10_props\cocos2d_win10_platform.props" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\..\..\2d\win10_props\cocos2d_win10.props" />
<Import Project="..\..\..\2d\win10_props\cocos2d_win10_platform.props" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<CompileAsWinRT>true</CompileAsWinRT>
<SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>4458;4456;4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
<AdditionalIncludeDirectories>$(EngineRoot)external\win10-specific\angle\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
</Link>
<Lib>
<AdditionalOptions>/IGNORE:4264 %(AdditionalOptions)</AdditionalOptions>
</Lib>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<CompileAsWinRT>true</CompileAsWinRT>
<SDLCheck>false</SDLCheck>
<WholeProgramOptimization>false</WholeProgramOptimization>
<DisableSpecificWarnings>4458;4456;4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
<AdditionalIncludeDirectories>$(EngineRoot)external\win10-specific\angle\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
</Link>
<Lib>
<LinkTimeCodeGeneration>false</LinkTimeCodeGeneration>
<AdditionalOptions>/IGNORE:4264 %(AdditionalOptions)</AdditionalOptions>
</Lib>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|arm'">
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<CompileAsWinRT>true</CompileAsWinRT>
<SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>4458;4456;4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
<AdditionalIncludeDirectories>$(EngineRoot)external\win10-specific\angle\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
</Link>
<Lib>
<AdditionalOptions>/IGNORE:4264 %(AdditionalOptions)</AdditionalOptions>
</Lib>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|arm'">
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<CompileAsWinRT>true</CompileAsWinRT>
<SDLCheck>false</SDLCheck>
<WholeProgramOptimization>false</WholeProgramOptimization>
<DisableSpecificWarnings>4458;4456;4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
<AdditionalIncludeDirectories>$(EngineRoot)external\win10-specific\angle\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
</Link>
<Lib>
<LinkTimeCodeGeneration>false</LinkTimeCodeGeneration>
<AdditionalOptions>/IGNORE:4264 %(AdditionalOptions)</AdditionalOptions>
</Lib>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<CompileAsWinRT>true</CompileAsWinRT>
<SDLCheck>false</SDLCheck>
<DisableSpecificWarnings>4458;4456;4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
<AdditionalIncludeDirectories>$(EngineRoot)external\win10-specific\angle\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
</Link>
<Lib>
<AdditionalOptions>/IGNORE:4264 %(AdditionalOptions)</AdditionalOptions>
</Lib>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<CompileAsWinRT>true</CompileAsWinRT>
<SDLCheck>false</SDLCheck>
<WholeProgramOptimization>false</WholeProgramOptimization>
<DisableSpecificWarnings>4458;4456;4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
<AdditionalIncludeDirectories>$(EngineRoot)external\win10-specific\angle\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
</Link>
<Lib>
<LinkTimeCodeGeneration>false</LinkTimeCodeGeneration>
<AdditionalOptions>/IGNORE:4264 %(AdditionalOptions)</AdditionalOptions>
</Lib>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -51,10 +51,10 @@
[sslFile release]; [sslFile release];
[responseHeader release]; [responseHeader release];
[responseData release]; [responseData release];
[statusString release];
[responseError release]; [responseError release];
[conn release]; [conn release];
[runLoop release]; [runLoop release];
[connError release];
[super dealloc]; [super dealloc];
} }
@ -178,10 +178,12 @@
{ {
CFDataRef errDataRef = SecTrustCopyExceptions(serverTrust); CFDataRef errDataRef = SecTrustCopyExceptions(serverTrust);
SecTrustSetExceptions(serverTrust, errDataRef); SecTrustSetExceptions(serverTrust, errDataRef);
SecTrustEvaluate(serverTrust, &trustResult); SecTrustEvaluate(serverTrust, &trustResult);
[(id)errDataRef release];
} }
[certData release];
[(id)certArrayRef release];
[(id)certArrayRef release];
//Did our custom trust chain evaluate successfully? //Did our custom trust chain evaluate successfully?
return trustResult = kSecTrustResultUnspecified || trustResult == kSecTrustResultProceed; return trustResult = kSecTrustResultUnspecified || trustResult == kSecTrustResultProceed;
} }

View File

@ -217,7 +217,7 @@ static int processTask(HttpClient* client, HttpRequest* request, NSString* reque
long len = sslCaFileName.length(); long len = sslCaFileName.length();
long pos = sslCaFileName.rfind('.', len-1); long pos = sslCaFileName.rfind('.', len-1);
httpAsynConn.sslFile = [NSString stringWithUTF8String:sslCaFileName.substr(0, pos-1).c_str()]; httpAsynConn.sslFile = [NSString stringWithUTF8String:sslCaFileName.substr(0, pos).c_str()];
} }
[httpAsynConn startRequest:nsrequest]; [httpAsynConn startRequest:nsrequest];

View File

@ -0,0 +1,366 @@
/****************************************************************************
Copyright (c) 2012 greathqy
Copyright (c) 2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "HttpClient.h"
#include <thread>
#include <queue>
#include <condition_variable>
#include <errno.h>
#include "base/CCVector.h"
#include "base/CCDirector.h"
#include "base/CCScheduler.h"
#include "platform/CCFileUtils.h"
#include "HttpConnection-winrt.h"
NS_CC_BEGIN
namespace network {
static std::mutex s_requestQueueMutex;
static std::mutex s_responseQueueMutex;
static std::condition_variable_any s_SleepCondition;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
typedef int int32_t;
#endif
static Vector<HttpRequest*>* s_requestQueue = nullptr;
static Vector<HttpResponse*>* s_responseQueue = nullptr;
static HttpClient *s_pHttpClient = nullptr; // pointer to singleton
static std::string s_errorBuffer ="";
static std::string s_cookieFilename = "";
static std::string s_sslCaFilename = "";
// function used to collect response/header data
static void writeData(std::vector<char> *pFromBuffer, std::vector<char> *pToBuffer)
{
if(nullptr == pFromBuffer || nullptr == pToBuffer)
return;
pToBuffer->insert(pToBuffer->end(), pFromBuffer->begin(), pFromBuffer->end());
}
static void processHttpResponse(HttpResponse* response, std::string& errorStr);
static HttpRequest *s_requestSentinel = new HttpRequest;
// Worker thread
void HttpClient::networkThread()
{
auto scheduler = Director::getInstance()->getScheduler();
while (true)
{
HttpRequest *request;
// step 1: send http request if the requestQueue isn't empty
{
std::lock_guard<std::mutex> lock(s_requestQueueMutex);
while (s_requestQueue->empty()) {
s_SleepCondition.wait(s_requestQueueMutex);
}
request = s_requestQueue->at(0);
s_requestQueue->erase(0);
}
if (request == s_requestSentinel) {
break;
}
// step 2: libcurl sync access
// Create a HttpResponse object, the default setting is http access failed
HttpResponse *response = new (std::nothrow) HttpResponse(request);
processHttpResponse(response, s_errorBuffer);
// add response packet into queue
s_responseQueueMutex.lock();
s_responseQueue->pushBack(response);
s_responseQueueMutex.unlock();
if (nullptr != s_pHttpClient) {
scheduler->performFunctionInCocosThread(CC_CALLBACK_0(HttpClient::dispatchResponseCallbacks, this));
}
}
// cleanup: if worker thread received quit signal, clean up un-completed request queue
s_requestQueueMutex.lock();
s_requestQueue->clear();
s_requestQueueMutex.unlock();
if (s_requestQueue != nullptr) {
delete s_requestQueue;
s_requestQueue = nullptr;
delete s_responseQueue;
s_responseQueue = nullptr;
}
}
// Worker thread
void HttpClient::networkThreadAlone(HttpRequest* request, HttpResponse* response)
{
std::string errorStr;
processHttpResponse(response, errorStr);
auto scheduler = Director::getInstance()->getScheduler();
scheduler->performFunctionInCocosThread([response, request]{
const ccHttpRequestCallback& callback = request->getCallback();
Ref* pTarget = request->getTarget();
SEL_HttpResponse pSelector = request->getSelector();
if (callback != nullptr)
{
callback(s_pHttpClient, response);
}
else if (pTarget && pSelector)
{
(pTarget->*pSelector)(s_pHttpClient, response);
}
response->release();
// do not release in other thread
request->release();
});
}
// Process Response
static void processHttpResponse(HttpResponse* response, std::string& errorStr)
{
auto request = response->getHttpRequest();
long responseCode = -1;
int retValue = 0;
HttpConnection xhr;
bool ok = false;
bool manualAuthReqd = false;
// Process the request -> get response packet
switch (request->getRequestType())
{
case HttpRequest::Type::GET: // HTTP GET
ok = (xhr.init(request) && xhr.open("GET", manualAuthReqd, s_cookieFilename) && xhr.send());
break;
case HttpRequest::Type::POST: // HTTP POST
ok = (xhr.init(request) && xhr.open("POST", manualAuthReqd, s_cookieFilename) && xhr.send());
break;
case HttpRequest::Type::PUT: // HTTP PUT
ok = (xhr.init(request) && xhr.open("PUT", manualAuthReqd, s_cookieFilename) && xhr.send());
break;
case HttpRequest::Type::DELETE: // HTTP DELETE
ok = (xhr.init(request) && xhr.open("DELETE", manualAuthReqd, s_cookieFilename) && xhr.send());
break;
default:
CCASSERT(true, "CCHttpClient: unknown request type, only GET and POST are supported");
break;
}
writeData(xhr.getResponseHeader(), response->getResponseHeader());
writeData(xhr.getResponseData(), response->getResponseData());
retValue = ok ? 0 : 1;
errorStr = xhr.getErrorMessage();
responseCode = xhr.getStatusCode();
// write data to HttpResponse
response->setResponseCode(responseCode);
if (retValue != 0)
{
response->setSucceed(false);
response->setErrorBuffer(errorStr.c_str());
}
else
{
response->setSucceed(true);
}
}
// HttpClient implementation
HttpClient* HttpClient::getInstance()
{
if (s_pHttpClient == nullptr) {
s_pHttpClient = new (std::nothrow) HttpClient();
}
return s_pHttpClient;
}
void HttpClient::destroyInstance()
{
CC_SAFE_DELETE(s_pHttpClient);
}
void HttpClient::enableCookies(const char* cookieFile) {
if (cookieFile) {
s_cookieFilename = std::string(cookieFile);
}
else {
s_cookieFilename = (FileUtils::getInstance()->getWritablePath() + "cookieFile.txt");
}
}
void HttpClient::setSSLVerification(const std::string& caFile)
{
s_sslCaFilename = caFile;
}
HttpClient::HttpClient()
: _timeoutForConnect(30)
, _timeoutForRead(60)
{
}
HttpClient::~HttpClient()
{
if (s_requestQueue != nullptr) {
{
std::lock_guard<std::mutex> lock(s_requestQueueMutex);
s_requestQueue->pushBack(s_requestSentinel);
}
s_SleepCondition.notify_one();
}
s_pHttpClient = nullptr;
}
//Lazy create semaphore & mutex & thread
bool HttpClient::lazyInitThreadSemphore()
{
if (s_requestQueue != nullptr) {
return true;
}
else {
s_requestQueue = new (std::nothrow) Vector<HttpRequest*>();
s_responseQueue = new (std::nothrow) Vector<HttpResponse*>();
auto t = std::thread(CC_CALLBACK_0(HttpClient::networkThread, this));
t.detach();
}
return true;
}
//Add a get task to queue
void HttpClient::send(HttpRequest* request)
{
if (false == lazyInitThreadSemphore())
{
return;
}
if (!request)
{
return;
}
request->retain();
if (nullptr != s_requestQueue) {
s_requestQueueMutex.lock();
s_requestQueue->pushBack(request);
s_requestQueueMutex.unlock();
// Notify thread start to work
s_SleepCondition.notify_one();
}
}
void HttpClient::sendImmediate(HttpRequest* request)
{
if (!request)
{
return;
}
request->retain();
// Create a HttpResponse object, the default setting is http access failed
HttpResponse *response = new (std::nothrow) HttpResponse(request);
auto t = std::thread(&HttpClient::networkThreadAlone, this, request, response);
t.detach();
}
// Poll and notify main thread if responses exists in queue
void HttpClient::dispatchResponseCallbacks()
{
// log("CCHttpClient::dispatchResponseCallbacks is running");
//occurs when cocos thread fires but the network thread has already quited
if (nullptr == s_responseQueue) {
return;
}
HttpResponse* response = nullptr;
s_responseQueueMutex.lock();
if (!s_responseQueue->empty())
{
response = s_responseQueue->at(0);
s_responseQueue->erase(0);
}
s_responseQueueMutex.unlock();
if (response)
{
HttpRequest *request = response->getHttpRequest();
const ccHttpRequestCallback& callback = request->getCallback();
Ref* pTarget = request->getTarget();
SEL_HttpResponse pSelector = request->getSelector();
if (callback != nullptr)
{
callback(this, response);
}
else if (pTarget && pSelector)
{
(pTarget->*pSelector)(this, response);
}
response->release();
// do not release in other thread
request->release();
}
}
}
NS_CC_END

View File

@ -202,6 +202,8 @@ static bool configureCURL(HttpClient* client, CURL* handle, char* errorBuffer)
// Document is here: http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTNOSIGNAL // Document is here: http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTNOSIGNAL
curl_easy_setopt(handle, CURLOPT_NOSIGNAL, 1L); curl_easy_setopt(handle, CURLOPT_NOSIGNAL, 1L);
curl_easy_setopt(handle, CURLOPT_ACCEPT_ENCODING, "");
return true; return true;
} }

View File

@ -0,0 +1,741 @@
/****************************************************************************
Copyright (c) 2012 greathqy
Copyright (c) 2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "network/HttpCookie.h"
#include "HttpConnection-winrt.h"
NS_CC_BEGIN
namespace network {
// Format and add default headers (Platform specific approach)
static void formatHeaders(std::vector<std::string>& headers)
{
#if defined(_XBOX_ONE)
for(auto iter = headers.begin(); iter != headers.end(); ++iter)
{
(*iter) += "\r\n";
}
// append default headers
headers.emplace_back("User-Agent: XB1_IXHR2_HTTP\r\n");
headers.emplace_back("x-xbl-device-type: XboxOne\r\n");
headers.emplace_back("x-xbl-client-type: Console\r\n");
headers.emplace_back("x-xbl-client-version: 1.0\r\n");
headers.emplace_back("x-xbl-contract-version: 1\r\n");
#endif
}
// Get user authentication token (Platform specific approach)
static bool getAuthenticationToken(std::string verb, std::string url, std::string headersXST, std::string bodyXST, std::string& token, std::string& signature)
{
#if defined(_XBOX_ONE)
using namespace Windows::Xbox::System;
token = "";
signature = "";
User^ loggedInUser = nullptr;
int ind = 0;
while(ind < User::Users->Size)
{
loggedInUser = User::Users->GetAt(ind++);
if(loggedInUser->IsSignedIn)
break;
loggedInUser = nullptr;
}
if(nullptr == loggedInUser)
return false;
Platform::Array<unsigned char>^ body;
if(!bodyXST.empty()) {
body = ref new Platform::Array<unsigned char>((unsigned char*)bodyXST.c_str(), bodyXST.size());
}
else {
body = ref new Platform::Array<unsigned char>(1);
body[0] = 0;
}
// this method will crash if TitleId & PrimaryServiceConfigId not specified in Package.appxmanifest.
auto asynOp = loggedInUser->GetTokenAndSignatureAsync(
ref new Platform::String(std::wstring(verb.begin(), verb.end()).c_str()),
ref new Platform::String(std::wstring(url.begin(), url.end()).c_str()),
ref new Platform::String(std::wstring(headersXST.begin(), headersXST.end()).c_str()), body);
bool bRet = false;
HRESULT hr = S_OK;
asynOp->Completed = ref new Windows::Foundation::AsyncOperationCompletedHandler<GetTokenAndSignatureResult^>(
[&token, &signature, &bRet, &hr](Windows::Foundation::IAsyncOperation<GetTokenAndSignatureResult^>^ operation, Windows::Foundation::AsyncStatus status)
{
if(status == Windows::Foundation::AsyncStatus::Completed) {
try
{
auto result = operation->GetResults();
std::wstring tok = result->Token->Data();
std::wstring sig = result->Signature->Data();
token = std::string(tok.begin(), tok.end());
signature = std::string(sig.begin(), sig.end());
bRet = true;
}
catch(Platform::Exception^ e)
{
bRet = false;
}
}
else {
hr = operation->ErrorCode.Value;
if(hr == 0x87dd0021) //AM_E_NO_TOKEN_REQUIRED
bRet = true;
}
});
while(asynOp->Status == Windows::Foundation::AsyncStatus::Started)
{
::Sleep(1);
}
return bRet;
#else
return false;
#endif
}
// CXMLHTTPRequest2Callback
CXHR2Callback::CXHR2Callback() :
_statusCode(0),
_hWfC(nullptr),
_errorMsg("")
{
}
CXHR2Callback::~CXHR2Callback()
{
if (nullptr != _hWfC)
{
CloseHandle(_hWfC);
_hWfC = nullptr;
}
}
HRESULT CXHR2Callback::RuntimeClassInitialize()
{
_hWfC = CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, EVENT_ALL_ACCESS);
return HRESULT_FROM_WIN32(GetLastError());
}
HRESULT CXHR2Callback::OnRedirect(IXMLHTTPRequest2 *pXHR, const WCHAR *pwszRedirectUrl)
{
UNREFERENCED_PARAMETER(pXHR);
UNREFERENCED_PARAMETER(pwszRedirectUrl);
return S_OK;
}
HRESULT CXHR2Callback::OnHeadersAvailable(IXMLHTTPRequest2 *pXHR, DWORD dwStatus, const WCHAR *pwszStatus)
{
_statusCode = dwStatus;
if(nullptr == pXHR) {
return E_INVALIDARG;
}
WCHAR *headers = nullptr;
HRESULT hr = pXHR->GetAllResponseHeaders(&headers);
if(SUCCEEDED(hr)) {
std::wstring hdr = headers;
_headers.insert(_headers.end(), hdr.begin(), hdr.end());
}
if(headers != nullptr) {
CoTaskMemFree(headers);
headers = nullptr;
}
return hr;
}
HRESULT CXHR2Callback::OnDataAvailable(IXMLHTTPRequest2 *pXHR, ISequentialStream *pResponseStream)
{
UNREFERENCED_PARAMETER(pXHR);
return ReadStreamData(pResponseStream);
}
HRESULT CXHR2Callback::OnResponseReceived(IXMLHTTPRequest2 *pXHR, ISequentialStream *pResponseStream)
{
UNREFERENCED_PARAMETER(pXHR);
HRESULT hr = ReadStreamData(pResponseStream);
CompleteRequest(hr);
return hr;
}
HRESULT CXHR2Callback::OnError(IXMLHTTPRequest2 *pXHR, HRESULT hrError)
{
CompleteRequest(hrError);
return hrError;
}
HRESULT CXHR2Callback::WaitForComplete(PDWORD pdwStatus)
{
HRESULT hr = E_FAIL;
if (NULL != _hWfC)
{
hr = S_OK;
DWORD error;
error = WaitForSingleObjectEx(_hWfC, INFINITE, FALSE);
if (error == WAIT_FAILED) {
hr = HRESULT_FROM_WIN32(GetLastError());
}
if (error != WAIT_OBJECT_0) {
hr = E_ABORT;
}
}
if (SUCCEEDED(hr)) {
*pdwStatus = _statusCode;
}
return hr;
}
HRESULT CXHR2Callback::ReadStreamData(ISequentialStream* pResponseStream)
{
if(pResponseStream == NULL) {
return E_INVALIDARG;
}
CCHAR buff[READ_BUFFER_MAX];
DWORD totalBytes = 0;
DWORD bytesRead = 0;
HRESULT hr = S_OK;
do
{
hr = pResponseStream->Read(buff, READ_BUFFER_MAX, &bytesRead);
if(FAILED(hr)) {
break;
}
_data.insert(_data.end(), &buff[0], buff + bytesRead);
totalBytes += bytesRead;
}
while(hr == S_OK);
if(SUCCEEDED(hr)) {
hr = S_OK;
}
return hr;
}
void CXHR2Callback::CompleteRequest(HRESULT hrError)
{
if (NULL != _hWfC) {
SetEvent(_hWfC);
}
switch (hrError)
{
case S_OK:
case S_FALSE:
_statusCode = 200;
break;
case INET_E_AUTHENTICATION_REQUIRED:
_statusCode = 401;
_errorMsg = ERR_MSG_401;
break;
case INET_E_DOWNLOAD_FAILURE:
_statusCode = 500;
_errorMsg = ERR_MSG_DL_FLD;
break;
case INET_E_FORBIDFRAMING:
_statusCode = 403;
_errorMsg = ERR_MSG_403;
break;
case INET_E_RESOURCE_NOT_FOUND:
_statusCode = 404;
_errorMsg = ERR_MSG_404;
break;
case RPC_S_PROXY_ACCESS_DENIED:
_statusCode = 407;
_errorMsg = ERR_MSG_407;
break;
case ERROR_RESOURCE_CALL_TIMED_OUT:
_statusCode = 408;
_errorMsg = ERR_MSG_408;
break;
case INET_E_INVALID_REQUEST:
_statusCode = 400;
_errorMsg = ERR_MSG_400;
break;
case E_ABORT:
_statusCode = 412;
_errorMsg = ERR_MSG_412;
break;
default:
_statusCode = 500;
_errorMsg = ERR_MSG_500;
break;
}
}
//CXHR2DataStream
CXHR2DataStream::CXHR2DataStream() :
_pData(nullptr),
_dataSize(0),
_seekIndex(0),
_refCnt(1)
{
}
CXHR2DataStream::~CXHR2DataStream()
{
if(nullptr != _pData)
delete[] _pData;
}
ULONG CXHR2DataStream::Length()
{
return _dataSize;
}
HRESULT CXHR2DataStream::Init(const void *psBuffer, ULONG cbBufferSize)
{
HRESULT hr = S_OK;
if(psBuffer == nullptr || cbBufferSize > REQUEST_BUFFER_MAX) {
hr = E_INVALIDARG;
}
if(SUCCEEDED(hr)) {
_dataSize = cbBufferSize;
_seekIndex = 0;
_pData = new (std::nothrow) BYTE[_dataSize];
if(_pData == nullptr)
hr = E_OUTOFMEMORY;
}
if(SUCCEEDED(hr)) {
memcpy_s(_pData, _dataSize, psBuffer, cbBufferSize);
}
return hr;
}
HRESULT CXHR2DataStream::Read(void *pv, ULONG cb, ULONG *pcbRead)
{
HRESULT hr = S_OK;
if(pv == nullptr) {
hr = E_INVALIDARG;
}
if(SUCCEEDED(hr)) {
BYTE* pOutput = (BYTE*)pv;
BYTE* _pInput = _pData;
for(*pcbRead = 0; *pcbRead < cb; (*pcbRead)++)
{
if(_seekIndex == _dataSize) {
hr = S_FALSE;
break;
}
pOutput[*pcbRead] = _pInput[*pcbRead];
_seekIndex++;
}
}
return hr;
}
HRESULT CXHR2DataStream::Write(const void *pv, ULONG cb, ULONG *pcbWritten)
{
HRESULT hr = E_NOTIMPL;
UNREFERENCED_PARAMETER(pv);
UNREFERENCED_PARAMETER(cb);
UNREFERENCED_PARAMETER(pcbWritten);
return hr;
}
ULONG CXHR2DataStream::AddRef()
{
return ::InterlockedIncrement(&_refCnt);
}
ULONG CXHR2DataStream::Release()
{
ULONG refCnt = ::InterlockedDecrement(&_refCnt);
if(0 == refCnt) {
delete this;
}
return refCnt;
}
HRESULT CXHR2DataStream::QueryInterface(REFIID riid, void **ppvObject)
{
HRESULT hr = S_OK;
if(ppvObject == nullptr) {
hr = E_INVALIDARG;
}
void *pObject = nullptr;
if(SUCCEEDED(hr)) {
if(riid == IID_IUnknown) {
pObject = static_cast<IUnknown*>((IDispatch*)this);
}
else if(riid == IID_IDispatch) {
pObject = static_cast<IDispatch*>(this);
}
else if(riid == IID_ISequentialStream) {
pObject = static_cast<ISequentialStream*>(this);
}
else {
hr = E_NOINTERFACE;
}
}
if(SUCCEEDED(hr)) {
AddRef();
*ppvObject = pObject;
pObject = nullptr;
}
return hr;
}
HRESULT CXHR2DataStream::GetTypeInfoCount(unsigned int FAR* pctinfo)
{
HRESULT hr = E_NOTIMPL;
if(pctinfo)
*pctinfo = 0;
return hr;
}
HRESULT CXHR2DataStream::GetTypeInfo(unsigned int iTInfo, LCID lcid, ITypeInfo FAR* FAR* ppTInfo)
{
HRESULT hr = E_NOTIMPL;
if(ppTInfo)
*ppTInfo = 0;
UNREFERENCED_PARAMETER(iTInfo);
UNREFERENCED_PARAMETER(lcid);
return hr;
}
HRESULT CXHR2DataStream::GetIDsOfNames(REFIID riid, OLECHAR FAR* FAR* rgszNames, unsigned int cNames, LCID lcid, DISPID FAR* rgDispId)
{
HRESULT hr = DISP_E_UNKNOWNNAME;
UNREFERENCED_PARAMETER(riid);
UNREFERENCED_PARAMETER(rgszNames);
UNREFERENCED_PARAMETER(cNames);
UNREFERENCED_PARAMETER(lcid);
UNREFERENCED_PARAMETER(rgDispId);
return hr;
}
HRESULT CXHR2DataStream::Invoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS FAR* pDispParams, VARIANT FAR* pVarResult, EXCEPINFO FAR* pExcepInfo, unsigned int FAR* puArgErr)
{
HRESULT hr = S_OK;
UNREFERENCED_PARAMETER(dispIdMember);
UNREFERENCED_PARAMETER(riid);
UNREFERENCED_PARAMETER(lcid);
UNREFERENCED_PARAMETER(wFlags);
UNREFERENCED_PARAMETER(pDispParams);
UNREFERENCED_PARAMETER(pVarResult);
UNREFERENCED_PARAMETER(pExcepInfo);
UNREFERENCED_PARAMETER(puArgErr);
return hr;
}
// HttpConnection
HttpConnection::HttpConnection() :
_isInitialized(false),
_spXhr(nullptr),
_spXhrCallback(nullptr),
_spXhrRequestData(nullptr),
_pRequest(nullptr),
_timeOutInMs(0)
{
}
HttpConnection::~HttpConnection()
{
}
bool HttpConnection::init(HttpRequest *pRequest, DWORD timeOutInMs)
{
if (_isInitialized || nullptr == pRequest) {
return _isInitialized;
}
HRESULT hr = CoInitializeEx(NULL, NULL);
if (SUCCEEDED(hr)) {
hr = CoCreateInstance(CLSID_FreeThreadedXMLHTTP60, NULL, CLSCTX_SERVER, IID_PPV_ARGS(&_spXhr));
}
if (SUCCEEDED(hr)) {
hr = MakeAndInitialize<CXHR2Callback>(&_spXhrCallback);
}
if(SUCCEEDED(hr)) {
_pRequest = pRequest;
_timeOutInMs = timeOutInMs;
LONG size = _pRequest->getRequestDataSize();
if(size > 0) {
_spXhrRequestData = Make<CXHR2DataStream>();
hr = _spXhrRequestData->Init(_pRequest->getRequestData(), size);
}
}
return _isInitialized = SUCCEEDED(hr);
}
bool HttpConnection::open(std::string verb)
{
return open(verb, false, "");
}
bool HttpConnection::open(std::string verb, bool userAuthentication)
{
return open(verb, userAuthentication, "");
}
bool HttpConnection::open(std::string verb, std::string cookieFile)
{
return open(verb, false, cookieFile);
}
bool HttpConnection::open(std::string verb, bool userAuthentication, std::string cookieFile)
{
if (!_isInitialized) {
return false;
}
std::wstring method(verb.begin(), verb.end());
std::string url(_pRequest->getUrl());
std::wstring wUrl(url.begin(), url.end());
HRESULT hr = _spXhr->Open(method.c_str(), wUrl.c_str(), _spXhrCallback.Get(), NULL, NULL, NULL, NULL);
if(SUCCEEDED(hr) && _timeOutInMs != 0) {
hr = _spXhr->SetProperty(XHR_PROP_TIMEOUT, _timeOutInMs);
}
#if 0
if(SUCCEEDED(hr)) {
hr = _spXhr->SetProperty(XHR_PROP_ONDATA_THRESHOLD, READ_BUFFER_MAX);
}
#endif
auto headers = _pRequest->getHeaders();
formatHeaders(headers);
for(auto header : headers)
{
std::string key = header.substr(0, header.find_first_of(':'));
std::string value = header.substr(header.find_first_of(':') + 1, header.size() - 1);
if(SUCCEEDED(hr)) {
hr = _spXhr->SetRequestHeader(std::wstring(key.begin(), key.end()).c_str(), std::wstring(value.begin(), value.end()).c_str());
}
}
if(SUCCEEDED(hr) && userAuthentication) {
std::string authHeaders = std::accumulate(headers.begin(), headers.end(), std::string(""));
hr = authenticateUser(verb, url, authHeaders);
}
if(SUCCEEDED(hr) && !cookieFile.empty()) {
hr = processCookieFile(url, cookieFile);
}
if(FAILED(hr)) {
cancelRequest(hr);
}
return SUCCEEDED(hr);
}
HRESULT HttpConnection::authenticateUser(std::string& verb, std::string& url, std::string& headers)
{
HRESULT hr = S_OK;
std::string authToken;
std::string authSig;
std::string authBody;
if(_pRequest->getRequestDataSize() > 0)
authBody = _pRequest->getRequestData();
if(getAuthenticationToken(verb, url, headers, authBody, authToken, authSig)) {
hr = _spXhr->SetRequestHeader(L"Authorization", std::wstring(authToken.begin(), authToken.end()).c_str());
if(SUCCEEDED(hr)) {
hr = _spXhr->SetRequestHeader(L"Signature", std::wstring(authSig.begin(), authSig.end()).c_str());
}
}
else
{
hr = INET_E_AUTHENTICATION_REQUIRED;
}
return hr;
}
HRESULT HttpConnection::processCookieFile(std::string& url, std::string& cookieFile)
{
HRESULT hr = S_OK;
HttpCookie cookie;
cookie.setCookieFileName(cookieFile);
auto cookies = cookie.getCookies();
std::string cookieInfo = "";
int cCnt = 0;
for(auto iter = cookies->begin(); iter != cookies->end(); iter++)
{
if(url.find(iter->domain) != std::string::npos)
{
std::string keyVal = iter->name;
keyVal.append("=");
keyVal.append(iter->value);
if(cCnt != 0) {
cookieInfo.append(";");
}
cookieInfo.append(keyVal);
cCnt++;
}
}
if(!cookieInfo.empty() && nullptr != _spXhr) {
hr = _spXhr->SetRequestHeader(L"Cookie", std::wstring(cookieInfo.begin(), cookieInfo.end()).c_str());
}
return hr;
}
bool HttpConnection::send()
{
if (!_isInitialized) {
return false;
}
HRESULT hr = E_FAIL;
if(nullptr == _spXhrRequestData) {
hr = _spXhr->Send(NULL, 0);
}
else {
hr = _spXhr->Send(_spXhrRequestData.Get(), _spXhrRequestData->Length());
}
if(SUCCEEDED(hr)) {
DWORD status = 0;
hr = _spXhrCallback->WaitForComplete(&status);
}
else {
cancelRequest(hr);
}
return SUCCEEDED(hr);
}
DWORD HttpConnection::getStatusCode()
{
return _spXhrCallback != nullptr ? _spXhrCallback->_statusCode : 500;
}
std::string HttpConnection::getErrorMessage()
{
return _spXhrCallback != nullptr ? _spXhrCallback->_errorMsg : ERR_MSG_500;
}
std::vector<char>* HttpConnection::getResponseHeader()
{
return _spXhrCallback != nullptr ? &_spXhrCallback->_headers : nullptr;
}
std::vector<char>* HttpConnection::getResponseData()
{
return _spXhrCallback != nullptr ? &_spXhrCallback->_data : nullptr;
}
void HttpConnection::cancelRequest(HRESULT hrError)
{
if(nullptr != _spXhr) {
_spXhr->Abort();
_spXhrCallback->CompleteRequest(hrError);
}
}
}
NS_CC_END

View File

@ -0,0 +1,157 @@
/****************************************************************************
Copyright (c) 2012 greathqy
Copyright (c) 2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "network/HttpRequest.h"
#include "network/HttpClient.h"
#include <thread>
#include <queue>
#include <numeric>
#include <condition_variable>
#include <errno.h>
#include <wrl.h>
#if defined(_XBOX_ONE)
#include <ixmlhttprequest2.h>
#else
#include <Msxml6.h>
#endif
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Details;
#include "base/CCVector.h"
#include "base/CCDirector.h"
#include "base/CCScheduler.h"
#include "platform/CCFileUtils.h"
NS_CC_BEGIN
namespace network {
const int READ_BUFFER_MAX = 16 * 1024;
const int REQUEST_BUFFER_MAX = 4 * 1024 * 1024;
const char ERR_MSG_500[] = "Internal server error";
const char ERR_MSG_400[] = "Invalid request";
const char ERR_MSG_401[] = "Authentication is required to access this resource";
const char ERR_MSG_403[] = "Forbidden";
const char ERR_MSG_404[] = "Specified resource could not be found";
const char ERR_MSG_407[] = "Proxy authentication failed";
const char ERR_MSG_408[] = "Request timed out";
const char ERR_MSG_412[] = "Request aborted";
const char ERR_MSG_DL_FLD[] = "The download of the specified resource has failed";
class CXHR2Callback : public Microsoft::WRL::RuntimeClass<RuntimeClassFlags<ClassicCom>, IXMLHTTPRequest2Callback>
{
public:
CXHR2Callback();
~CXHR2Callback();
HRESULT RuntimeClassInitialize();
HRESULT ReadStreamData(ISequentialStream* pResponseStream);
STDMETHODIMP OnRedirect(IXMLHTTPRequest2 *pXHR, const WCHAR *pwszRedirectUrl);
STDMETHODIMP OnHeadersAvailable(IXMLHTTPRequest2 *pXHR, DWORD dwStatus, const WCHAR *pwszStatus);
STDMETHODIMP OnDataAvailable(IXMLHTTPRequest2 *pXHR, ISequentialStream *pResponseStream);
STDMETHODIMP OnResponseReceived(IXMLHTTPRequest2 *pXHR, ISequentialStream *pResponseStream);
STDMETHODIMP OnError(IXMLHTTPRequest2 *pXHR, HRESULT hrError);
STDMETHODIMP WaitForComplete(PDWORD pdwStatus);
protected:
void CompleteRequest(HRESULT hrError);
private:
HANDLE _hWfC;
DWORD _statusCode;
std::string _errorMsg;
std::vector<char> _headers;
std::vector<char> _data;
friend class HttpConnection;
};
class CXHR2DataStream : public Microsoft::WRL::RuntimeClass<RuntimeClassFlags<ClassicCom>, ISequentialStream, IDispatch>
{
public:
CXHR2DataStream();
~CXHR2DataStream();
STDMETHODIMP_(ULONG) Length();
STDMETHODIMP Init(const void *psBuffer, ULONG cbBufferSize);
STDMETHODIMP Read(void *pv, ULONG cb, ULONG *pcbRead);
STDMETHODIMP Write(const void *pv, ULONG cb, ULONG *pcbWritten);
STDMETHODIMP_(ULONG) AddRef();
STDMETHODIMP_(ULONG) Release();
STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject);
STDMETHODIMP GetTypeInfoCount(unsigned int FAR* pctinfo);
STDMETHODIMP GetTypeInfo(unsigned int iTInfo, LCID lcid, ITypeInfo FAR* FAR* ppTInfo);
STDMETHODIMP GetIDsOfNames(REFIID riid, OLECHAR FAR* FAR* rgszNames, unsigned int cNames, LCID lcid, DISPID FAR* rgDispId);
STDMETHODIMP Invoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS FAR* pDispParams, VARIANT FAR* pVarResult, EXCEPINFO FAR* pExcepInfo, unsigned int FAR* puArgErr);
private:
ULONG _refCnt;
BYTE* _pData;
ULONG _dataSize;
ULONG _seekIndex;
};
class HttpConnection
{
public:
HttpConnection();
~HttpConnection();
bool init(HttpRequest *pRequest, DWORD timeOutInMs = 0);
bool open(std::string verb);
bool open(std::string verb, bool userAuthentication);
bool open(std::string verb, std::string cookieFile);
bool open(std::string verb, bool userAuthentication, std::string cookieFile);
bool send();
DWORD getStatusCode();
std::string getErrorMessage();
std::vector<char>* getResponseHeader();
std::vector<char>* getResponseData();
protected:
void cancelRequest(HRESULT hrError);
HRESULT authenticateUser(std::string& verb, std::string& url, std::string& headers);
HRESULT processCookieFile(std::string& url, std::string& cookieFile);
private:
bool _isInitialized;
ComPtr<IXMLHTTPRequest2> _spXhr;
ComPtr<CXHR2Callback> _spXhrCallback;
ComPtr<CXHR2DataStream> _spXhrRequestData;
DWORD _timeOutInMs;
cocos2d::network::HttpRequest* _pRequest;
};
}
NS_CC_END

View File

@ -147,7 +147,7 @@ void Physics3DComponent::preSimulate()
{ {
if (((int)_syncFlag & (int)Physics3DComponent::PhysicsSyncFlag::NODE_TO_PHYSICS) && _physics3DObj && _owner) if (((int)_syncFlag & (int)Physics3DComponent::PhysicsSyncFlag::NODE_TO_PHYSICS) && _physics3DObj && _owner)
{ {
syncToNode(); syncNodeToPhysics();
} }
} }
@ -155,7 +155,7 @@ void Physics3DComponent::postSimulate()
{ {
if (((int)_syncFlag & (int)Physics3DComponent::PhysicsSyncFlag::PHYSICS_TO_NODE) && _physics3DObj && _owner) if (((int)_syncFlag & (int)Physics3DComponent::PhysicsSyncFlag::PHYSICS_TO_NODE) && _physics3DObj && _owner)
{ {
syncToPhysics(); syncPhysicsToNode();
} }
} }
@ -174,7 +174,7 @@ void Physics3DComponent::setSyncFlag(PhysicsSyncFlag syncFlag)
_syncFlag = syncFlag; _syncFlag = syncFlag;
} }
void Physics3DComponent::syncToPhysics() void Physics3DComponent::syncPhysicsToNode()
{ {
if (_physics3DObj->getObjType() == Physics3DObject::PhysicsObjType::RIGID_BODY) if (_physics3DObj->getObjType() == Physics3DObject::PhysicsObjType::RIGID_BODY)
{ {
@ -207,7 +207,7 @@ void Physics3DComponent::syncToPhysics()
} }
} }
void Physics3DComponent::syncToNode() void Physics3DComponent::syncNodeToPhysics()
{ {
if (_physics3DObj->getObjType() == Physics3DObject::PhysicsObjType::RIGID_BODY) if (_physics3DObj->getObjType() == Physics3DObject::PhysicsObjType::RIGID_BODY)
{ {

View File

@ -110,14 +110,14 @@ public:
void setSyncFlag(PhysicsSyncFlag syncFlag); void setSyncFlag(PhysicsSyncFlag syncFlag);
/** /**
* align node and physics according to physics object * synchronize node transformation to physics
*/ */
void syncToPhysics(); void syncNodeToPhysics();
/** /**
* align node and physics according to node * synchronize physics transformation to node
*/ */
void syncToNode(); void syncPhysicsToNode();
CC_CONSTRUCTOR_ACCESS: CC_CONSTRUCTOR_ACCESS:
Physics3DComponent(); Physics3DComponent();

View File

@ -67,6 +67,16 @@ Physics3DWorld* Physics3DWorld::create(Physics3DWorldDes* info)
return world; return world;
} }
void Physics3DWorld::setGravity(const Vec3& gravity)
{
_btPhyiscsWorld->setGravity(convertVec3TobtVector3(gravity));
}
Vec3 Physics3DWorld::getGravity() const
{
return convertbtVector3ToVec3(_btPhyiscsWorld->getGravity());
}
bool Physics3DWorld::init(Physics3DWorldDes* info) bool Physics3DWorld::init(Physics3DWorldDes* info)
{ {
///collision configuration contains default setup for memory, collision setup ///collision configuration contains default setup for memory, collision setup

View File

@ -90,6 +90,12 @@ public:
*/ */
static Physics3DWorld* create(Physics3DWorldDes* info); static Physics3DWorld* create(Physics3DWorldDes* info);
/** set gravity for the physics world */
void setGravity(const Vec3& gravity);
/** get current gravity */
Vec3 getGravity() const;
/** Add a Physics3DObject. */ /** Add a Physics3DObject. */
void addPhysics3DObject(Physics3DObject* physicsObj); void addPhysics3DObject(Physics3DObject* physicsObj);

View File

@ -57,16 +57,16 @@ void PhysicsSprite3D::setSyncFlag(Physics3DComponent::PhysicsSyncFlag syncFlag)
_physicsComponent->setSyncFlag(syncFlag); _physicsComponent->setSyncFlag(syncFlag);
} }
void PhysicsSprite3D::syncToPhysics() void PhysicsSprite3D::syncNodeToPhysics()
{ {
if (_physicsComponent) if (_physicsComponent)
_physicsComponent->syncToPhysics(); _physicsComponent->syncNodeToPhysics();
} }
void PhysicsSprite3D::syncToNode() void PhysicsSprite3D::syncPhysicsToNode()
{ {
if (_physicsComponent) if (_physicsComponent)
_physicsComponent->syncToNode(); _physicsComponent->syncPhysicsToNode();
} }
PhysicsSprite3D::PhysicsSprite3D() PhysicsSprite3D::PhysicsSprite3D()

View File

@ -56,11 +56,11 @@ public:
/** Set synchronization flag, see Physics3DComponent. */ /** Set synchronization flag, see Physics3DComponent. */
void setSyncFlag(Physics3DComponent::PhysicsSyncFlag syncFlag); void setSyncFlag(Physics3DComponent::PhysicsSyncFlag syncFlag);
/** Physics synchronize rendering. */ /** synchronize node transformation to physics. */
void syncToPhysics(); void syncNodeToPhysics();
/** Rendering synchronize physics. */ /** synchronize physics transformation to node. */
void syncToNode(); void syncPhysicsToNode();
CC_CONSTRUCTOR_ACCESS: CC_CONSTRUCTOR_ACCESS:
PhysicsSprite3D(); PhysicsSprite3D();

View File

@ -26,33 +26,30 @@ package org.cocos2dx.lib;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
import java.util.LinkedList;
import android.content.Context; import android.content.Context;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Rect; import android.graphics.Rect;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint; import android.text.TextPaint;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
public class Cocos2dxBitmap { public final class Cocos2dxBitmap {
// =========================================================== // ===========================================================
// Constants // Constants
// =========================================================== // ===========================================================
/* The values are the same as cocos2dx/platform/CCImage.h. */ /* The values are the same as cocos2dx/platform/CCImage.h. */
private static final int HORIZONTALALIGN_LEFT = 1; private static final int HORIZONTAL_ALIGN_LEFT = 1;
private static final int HORIZONTALALIGN_RIGHT = 2; private static final int HORIZONTAL_ALIGN_RIGHT = 2;
private static final int HORIZONTALALIGN_CENTER = 3; private static final int HORIZONTAL_ALIGN_CENTER = 3;
private static final int VERTICALALIGN_TOP = 1; private static final int VERTICAL_ALIGN_TOP = 1;
private static final int VERTICALALIGN_BOTTOM = 2; private static final int VERTICAL_ALIGN_BOTTOM = 2;
private static final int VERTICALALIGN_CENTER = 3; private static final int VERTICAL_ALIGN_CENTER = 3;
// =========================================================== // ===========================================================
// Fields // Fields
@ -60,10 +57,6 @@ public class Cocos2dxBitmap {
private static Context sContext; private static Context sContext;
// ===========================================================
// Constructors
// ===========================================================
// =========================================================== // ===========================================================
// Getter & Setter // Getter & Setter
// =========================================================== // ===========================================================
@ -83,129 +76,98 @@ public class Cocos2dxBitmap {
private static native void nativeInitBitmapDC(final int width, private static native void nativeInitBitmapDC(final int width,
final int height, final byte[] pixels); final int height, final byte[] pixels);
/**
* @param width
* the width to draw, it can be 0
* @param height
* the height to draw, it can be 0
*/
public static void createTextBitmap(String string, final String fontName,
final int fontSize, final int alignment, final int width,
final int height) {
createTextBitmapShadowStroke( string.getBytes(), fontName, fontSize, 255, 255, 255, 255, // text font and color
alignment, width, height, // alignment and size
false, 0.0f, 0.0f, 0.0f, 0.0f, // no shadow
false, 255, 255, 255, 255, 0.0f); // no stroke
}
public static boolean createTextBitmapShadowStroke(byte[] bytes, final String fontName, int fontSize, public static boolean createTextBitmapShadowStroke(byte[] bytes, final String fontName, int fontSize,
int fontTintR, int fontTintG, int fontTintB, int fontTintA, int fontTintR, int fontTintG, int fontTintB, int fontTintA,
int alignment, int width, int height, int alignment, int width, int height,
boolean shadow, float shadowDX, float shadowDY, float shadowBlur, float shadowOpacity, boolean shadow, float shadowDX, float shadowDY, float shadowBlur, float shadowOpacity,
boolean stroke, int strokeR, int strokeG, int strokeB, int strokeA, float strokeSize) { boolean stroke, int strokeR, int strokeG, int strokeB, int strokeA, float strokeSize) {
String string; String string;
if (bytes == null || bytes.length == 0) { if (bytes == null || bytes.length == 0) {
string = ""; return false;
} else { } else {
string = new String(bytes); string = new String(bytes);
} }
final int horizontalAlignment = alignment & 0x0F; Layout.Alignment hAlignment = Layout.Alignment.ALIGN_NORMAL;
final int verticalAlignment = (alignment >> 4) & 0x0F; int horizontalAlignment = alignment & 0x0F;
switch (horizontalAlignment) {
string = Cocos2dxBitmap.refactorString(string); case HORIZONTAL_ALIGN_CENTER:
final Paint paint = Cocos2dxBitmap.newPaint(fontName, fontSize, horizontalAlignment); hAlignment = Layout.Alignment.ALIGN_CENTER;
break;
// if the first word width less than designed width, it means no words to show case HORIZONTAL_ALIGN_RIGHT:
if(0 != width) hAlignment = Layout.Alignment.valueOf("ALIGN_RIGHT");
{ break;
final int firstWordWidth = (int) Math.ceil(paint.measureText(string, 0,1)); case HORIZONTAL_ALIGN_LEFT:
if (firstWordWidth > width) hAlignment = Layout.Alignment.valueOf("ALIGN_LEFT");
{ break;
Log.w("createTextBitmapShadowStroke warning:","the input width is less than the width of the pString's first word\n"); default:
return false; break;
}
} }
TextPaint paint = Cocos2dxBitmap.newPaint(fontName, fontSize, horizontalAlignment);
// set the paint color if (stroke) {
paint.setARGB(fontTintA, fontTintR, fontTintG, fontTintB); paint.setStyle(TextPaint.Style.STROKE);
paint.setStrokeWidth(strokeSize);
}
final TextProperty textProperty = Cocos2dxBitmap.computeTextProperty(string, width, height, paint); int maxWidth = width;
final int bitmapTotalHeight = (height == 0 ? textProperty.mTotalHeight: height); if (maxWidth <= 0) {
maxWidth = (int)Math.ceil( StaticLayout.getDesiredWidth(string, paint));
// padding needed when using shadows (not used otherwise) }
float bitmapPaddingX = 0.0f; StaticLayout staticLayout = new StaticLayout(string, paint, maxWidth , hAlignment,1.0f,0.0f,false);
float bitmapPaddingY = 0.0f; int layoutWidth = staticLayout.getWidth();
float renderTextDeltaX = 0.0f; int layoutHeight = staticLayout.getLineTop(staticLayout.getLineCount());
float renderTextDeltaY = 0.0f;
int bitmapWidth = Math.max(layoutWidth, width);
if (0 == textProperty.mMaxWidth || 0 == bitmapTotalHeight) int bitmapHeight = layoutHeight;
{ if (height > 0) {
Log.w("createTextBitmapShadowStroke warning:","textProperty MaxWidth is 0 or bitMapTotalHeight is 0\n"); bitmapHeight = height;
}
if (bitmapWidth == 0 || bitmapHeight == 0) {
return false; return false;
} }
int offsetX = 0;
final Bitmap bitmap = Bitmap.createBitmap(textProperty.mMaxWidth + (int)bitmapPaddingX, if (horizontalAlignment == HORIZONTAL_ALIGN_CENTER) {
bitmapTotalHeight + (int)bitmapPaddingY, Bitmap.Config.ARGB_8888); offsetX = (bitmapWidth - layoutWidth) / 2;
}
final Canvas canvas = new Canvas(bitmap); else if (horizontalAlignment == HORIZONTAL_ALIGN_RIGHT) {
offsetX = bitmapWidth - layoutWidth;
}
// Draw string. int offsetY = 0;
final FontMetricsInt fontMetricsInt = paint.getFontMetricsInt(); int verticalAlignment = (alignment >> 4) & 0x0F;
switch (verticalAlignment)
// draw again with stroke on if needed {
case VERTICAL_ALIGN_CENTER:
offsetY = (bitmapHeight - layoutHeight) / 2;
break;
case VERTICAL_ALIGN_BOTTOM:
offsetY = bitmapHeight - layoutHeight;
break;
}
Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.translate(offsetX, offsetY);
if ( stroke ) if ( stroke )
{ {
final Paint paintStroke = Cocos2dxBitmap.newPaint(fontName, fontSize, horizontalAlignment); paint.setARGB(strokeA, strokeR, strokeG, strokeB);
paintStroke.setStyle(Paint.Style.STROKE); staticLayout.draw(canvas);
paintStroke.setStrokeWidth(strokeSize);
paintStroke.setARGB(strokeA, strokeR, strokeG, strokeB);
int x = 0;
int y = Cocos2dxBitmap.computeY(fontMetricsInt, height, textProperty.mTotalHeight, verticalAlignment);
final String[] lines2 = textProperty.mLines;
for (final String line : lines2) {
x = Cocos2dxBitmap.computeX(line, textProperty.mMaxWidth, horizontalAlignment);
canvas.drawText(line, x + renderTextDeltaX, y + renderTextDeltaY, paintStroke);
canvas.drawText(line, x + renderTextDeltaX, y + renderTextDeltaY, paint);
y += textProperty.mHeightPerLine;
}
} }
else paint.setStyle(TextPaint.Style.FILL);
{ paint.setARGB(fontTintA, fontTintR, fontTintG, fontTintB);
int x = 0; staticLayout.draw(canvas);
int y = Cocos2dxBitmap.computeY(fontMetricsInt, height, textProperty.mTotalHeight, verticalAlignment);
final String[] lines = textProperty.mLines;
for (final String line : lines) {
x = Cocos2dxBitmap.computeX(line, textProperty.mMaxWidth, horizontalAlignment);
canvas.drawText(line, x + renderTextDeltaX, y + renderTextDeltaY, paint);
y += textProperty.mHeightPerLine;
}
}
Cocos2dxBitmap.initNativeObject(bitmap);
Cocos2dxBitmap.initNativeObject(bitmap);
return true; return true;
} }
private static Paint newPaint(final String fontName, final int fontSize, private static TextPaint newPaint(final String fontName, final int fontSize,
final int horizontalAlignment) { final int horizontalAlignment) {
final Paint paint = new Paint(); final TextPaint paint = new TextPaint();
paint.setColor(Color.WHITE); paint.setTextSize(fontSize);
paint.setTextSize(fontSize);
paint.setAntiAlias(true); paint.setAntiAlias(true);
// Set type face for paint, now it support .ttf file. // Set type face for paint, now it support .ttf file.
@ -225,227 +187,8 @@ public class Cocos2dxBitmap {
paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL)); paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL));
} }
switch (horizontalAlignment) {
case HORIZONTALALIGN_CENTER:
paint.setTextAlign(Align.CENTER);
break;
case HORIZONTALALIGN_RIGHT:
paint.setTextAlign(Align.RIGHT);
break;
case HORIZONTALALIGN_LEFT:
default:
paint.setTextAlign(Align.LEFT);
break;
}
return paint; return paint;
} }
private static TextProperty computeTextProperty(final String string,
final int width, final int height, final Paint paint) {
final FontMetricsInt fm = paint.getFontMetricsInt();
final int h = (int) Math.ceil(fm.bottom - fm.top);
int maxContentWidth = 0;
final String[] lines = Cocos2dxBitmap.splitString(string, width,
height, paint);
if (width != 0) {
maxContentWidth = width;
} else {
// Compute the max width.
int temp = 0;
for (final String line : lines) {
temp = (int) Math.ceil(paint.measureText(line, 0,
line.length()));
if (temp > maxContentWidth) {
maxContentWidth = temp;
}
}
}
return new TextProperty(maxContentWidth, h, lines);
}
private static int computeX(final String text, final int maxWidth,
final int horizontalAlignment) {
int ret = 0;
switch (horizontalAlignment) {
case HORIZONTALALIGN_CENTER:
ret = maxWidth / 2;
break;
case HORIZONTALALIGN_RIGHT:
ret = maxWidth;
break;
case HORIZONTALALIGN_LEFT:
default:
break;
}
return ret;
}
private static int computeY(final FontMetricsInt fontMetricsInt,
final int constrainHeight, final int totalHeight,
final int verticalAlignment) {
int y = -fontMetricsInt.top;
if (constrainHeight > totalHeight) {
switch (verticalAlignment) {
case VERTICALALIGN_TOP:
y = -fontMetricsInt.top;
break;
case VERTICALALIGN_CENTER:
y = -fontMetricsInt.top + (constrainHeight - totalHeight)
/ 2;
break;
case VERTICALALIGN_BOTTOM:
y = -fontMetricsInt.top + (constrainHeight - totalHeight);
break;
default:
break;
}
}
return y;
}
/*
* If maxWidth or maxHeight is not 0, split the string to fix the maxWidth
* and maxHeight.
*/
private static String[] splitString(final String string,
final int maxWidth, final int maxHeight, final Paint paint) {
final String[] lines = string.split("\\n");
String[] ret = null;
final FontMetricsInt fm = paint.getFontMetricsInt();
final int heightPerLine = (int) Math.ceil(fm.bottom - fm.top);
final int maxLines = maxHeight / heightPerLine;
if (maxWidth != 0) {
final LinkedList<String> strList = new LinkedList<String>();
for (final String line : lines) {
/*
* The width of line is exceed maxWidth, should divide it into
* two or more lines.
*/
final int lineWidth = (int) Math.ceil(paint
.measureText(line));
if (lineWidth > maxWidth) {
strList.addAll(Cocos2dxBitmap.divideStringWithMaxWidth(
line, maxWidth, paint));
} else {
strList.add(line);
}
// Should not exceed the max height.
if (maxLines > 0 && strList.size() >= maxLines) {
break;
}
}
// Remove exceeding lines.
if (maxLines > 0 && strList.size() > maxLines) {
while (strList.size() > maxLines) {
strList.removeLast();
}
}
ret = new String[strList.size()];
strList.toArray(ret);
} else if (maxHeight != 0 && lines.length > maxLines) {
/* Remove exceeding lines. */
final LinkedList<String> strList = new LinkedList<String>();
for (int i = 0; i < maxLines; i++) {
strList.add(lines[i]);
}
ret = new String[strList.size()];
strList.toArray(ret);
} else {
ret = lines;
}
return ret;
}
private static LinkedList<String> divideStringWithMaxWidth(
final String string, final int maxWidth, final Paint paint) {
final int charLength = string.length();
int start = 0;
int tempWidth = 0;
final LinkedList<String> strList = new LinkedList<String>();
// Break a String into String[] by the width & should wrap the word.
for (int i = 1; i <= charLength; ++i) {
tempWidth = (int) Math.ceil(paint.measureText(string, start,
i));
if (tempWidth >= maxWidth) {
final int lastIndexOfSpace = string.substring(0, i)
.lastIndexOf(" ");
if (lastIndexOfSpace != -1 && lastIndexOfSpace > start) {
// Should wrap the word.
strList.add(string.substring(start, lastIndexOfSpace));
i = lastIndexOfSpace + 1; // skip space
} else {
// Should not exceed the width.
if (tempWidth > maxWidth && i != start + 1) {
strList.add(string.substring(start, i - 1));
// Compute from previous char.
--i;
} else {
strList.add(string.substring(start, i));
}
}
// Remove spaces at the beginning of a new line.
while (i < charLength && string.charAt(i) == ' ') {
++i;
}
start = i;
}
}
// Add the last chars.
if (start < charLength) {
strList.add(string.substring(start));
}
return strList;
}
private static String refactorString(final String string) {
// Avoid error when content is "".
if (string.compareTo("") == 0) {
return " ";
}
/*
* If the font of "\n" is "" or "\n", insert " " in front of it. For
* example: "\nabc" -> " \nabc" "\nabc\n\n" -> " \nabc\n \n".
*/
final StringBuilder strBuilder = new StringBuilder(string);
int start = 0;
int index = strBuilder.indexOf("\n");
while (index != -1) {
if (index == 0 || strBuilder.charAt(index - 1) == '\n') {
strBuilder.insert(start, " ");
start = index + 2;
} else {
start = index + 1;
}
if (start > strBuilder.length() || index == strBuilder.length()) {
break;
}
index = strBuilder.indexOf("\n", start);
}
return strBuilder.toString();
}
private static void initNativeObject(final Bitmap bitmap) { private static void initNativeObject(final Bitmap bitmap) {
final byte[] pixels = Cocos2dxBitmap.getPixels(bitmap); final byte[] pixels = Cocos2dxBitmap.getPixels(bitmap);
@ -471,31 +214,29 @@ public class Cocos2dxBitmap {
} }
private static int getFontSizeAccordingHeight(int height) { private static int getFontSizeAccordingHeight(int height) {
Paint paint = new Paint(); TextPaint paint = new TextPaint();
Rect bounds = new Rect(); Rect bounds = new Rect();
paint.setTypeface(Typeface.DEFAULT); paint.setTypeface(Typeface.DEFAULT);
int incr_text_size = 1; int text_size = 1;
boolean found_desired_size = false; boolean found_desired_size = false;
while (!found_desired_size) { while (!found_desired_size) {
paint.setTextSize(text_size);
paint.setTextSize(incr_text_size);
String text = "SghMNy"; String text = "SghMNy";
paint.getTextBounds(text, 0, text.length(), bounds); paint.getTextBounds(text, 0, text.length(), bounds);
incr_text_size++; text_size++;
if (height - bounds.height() <= 2) { if (height - bounds.height() <= 2) {
found_desired_size = true; found_desired_size = true;
} }
Log.d("font size", "incr size:" + incr_text_size);
} }
return incr_text_size; return text_size;
} }
private static String getStringWithEllipsis(String string, float width, private static String getStringWithEllipsis(String string, float width,
float fontSize) { float fontSize) {
if (TextUtils.isEmpty(string)) { if (TextUtils.isEmpty(string)) {
return ""; return "";
} }
@ -507,25 +248,4 @@ public class Cocos2dxBitmap {
return TextUtils.ellipsize(string, paint, width, return TextUtils.ellipsize(string, paint, width,
TextUtils.TruncateAt.END).toString(); TextUtils.TruncateAt.END).toString();
} }
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
private static class TextProperty {
/** The max width of lines. */
private final int mMaxWidth;
/** The height of all lines. */
private final int mTotalHeight;
private final int mHeightPerLine;
private final String[] mLines;
TextProperty(final int maxWidth, final int heightPerLine,
final String[] lines) {
this.mMaxWidth = maxWidth;
this.mHeightPerLine = heightPerLine;
this.mTotalHeight = heightPerLine * lines.length;
this.mLines = lines;
}
}
} }

View File

@ -27,6 +27,7 @@ package org.cocos2dx.lib;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.util.Locale; import java.util.Locale;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set; import java.util.Set;
import java.lang.Runnable; import java.lang.Runnable;
@ -379,28 +380,104 @@ public class Cocos2dxHelper {
public static boolean getBoolForKey(String key, boolean defaultValue) { public static boolean getBoolForKey(String key, boolean defaultValue) {
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
return settings.getBoolean(key, defaultValue); try {
return settings.getBoolean(key, defaultValue);
}
catch (Exception ex) {
ex.printStackTrace();
Map allValues = settings.getAll();
Object value = allValues.get(key);
if ( value instanceof String)
{
return Boolean.parseBoolean(value.toString());
}
else if (value instanceof Integer)
{
int intValue = ((Integer) value).intValue();
return (intValue != 0) ;
}
else if (value instanceof Float)
{
float floatValue = ((Float) value).floatValue();
return (floatValue != 0.0f);
}
}
return false;
} }
public static int getIntegerForKey(String key, int defaultValue) { public static int getIntegerForKey(String key, int defaultValue) {
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
return settings.getInt(key, defaultValue); try {
return settings.getInt(key, defaultValue);
}
catch (Exception ex) {
ex.printStackTrace();
Map allValues = settings.getAll();
Object value = allValues.get(key);
if ( value instanceof String) {
return Integer.parseInt(value.toString());
}
else if (value instanceof Float)
{
return ((Float) value).intValue();
}
else if (value instanceof Boolean)
{
boolean booleanValue = ((Boolean) value).booleanValue();
if (booleanValue)
return 1;
}
}
return 0;
} }
public static float getFloatForKey(String key, float defaultValue) { public static float getFloatForKey(String key, float defaultValue) {
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
return settings.getFloat(key, defaultValue); try {
return settings.getFloat(key, defaultValue);
}
catch (Exception ex) {
ex.printStackTrace();;
Map allValues = settings.getAll();
Object value = allValues.get(key);
if ( value instanceof String) {
return Float.parseFloat(value.toString());
}
else if (value instanceof Integer)
{
return ((Integer) value).floatValue();
}
else if (value instanceof Boolean)
{
boolean booleanValue = ((Boolean) value).booleanValue();
if (booleanValue)
return 1.0f;
}
}
return 0.0f;
} }
public static double getDoubleForKey(String key, double defaultValue) { public static double getDoubleForKey(String key, double defaultValue) {
// SharedPreferences doesn't support saving double value // SharedPreferences doesn't support saving double value
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); return getFloatForKey(key, (float) defaultValue);
return settings.getFloat(key, (float)defaultValue);
} }
public static String getStringForKey(String key, String defaultValue) { public static String getStringForKey(String key, String defaultValue) {
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
return settings.getString(key, defaultValue); try {
return settings.getString(key, defaultValue);
}
catch (Exception ex) {
ex.printStackTrace();
return settings.getAll().get(key).toString();
}
} }
public static void setBoolForKey(String key, boolean value) { public static void setBoolForKey(String key, boolean value) {

View File

@ -28,6 +28,8 @@ import java.io.DataInputStream;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.InputStream; import java.io.InputStream;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
@ -260,11 +262,20 @@ public class Cocos2dxHttpURLConnection
} }
static byte[] getResponseContent(HttpURLConnection http) { static byte[] getResponseContent(HttpURLConnection http) {
DataInputStream in; InputStream in;
try { try {
in = new DataInputStream(http.getInputStream()); in = http.getInputStream();
String contentEncoding = http.getContentEncoding();
if (contentEncoding != null) {
if(contentEncoding.equalsIgnoreCase("gzip")){
in = new GZIPInputStream(http.getInputStream()); //reads 2 bytes to determine GZIP stream!
}
else if(contentEncoding.equalsIgnoreCase("deflate")){
in = new InflaterInputStream(http.getInputStream());
}
}
} catch (IOException e) { } catch (IOException e) {
in = new DataInputStream(http.getErrorStream()); in = http.getErrorStream();
} catch (Exception e) { } catch (Exception e) {
Log.e("Cocos2dxHttpURLConnection exception", e.toString()); Log.e("Cocos2dxHttpURLConnection exception", e.toString());
return null; return null;

View File

@ -51,10 +51,11 @@ OpenGLESPage::OpenGLESPage(OpenGLES* openGLES) :
mRenderSurface(EGL_NO_SURFACE), mRenderSurface(EGL_NO_SURFACE),
mCustomRenderSurfaceSize(0,0), mCustomRenderSurfaceSize(0,0),
mUseCustomRenderSurfaceSize(false), mUseCustomRenderSurfaceSize(false),
m_coreInput(nullptr), mCoreInput(nullptr),
m_dpi(0.0f), mDpi(0.0f),
m_deviceLost(false), mDeviceLost(false),
m_orientation(DisplayOrientations::Landscape) mVisible(false),
mOrientation(DisplayOrientations::Landscape)
{ {
InitializeComponent(); InitializeComponent();
@ -77,7 +78,7 @@ OpenGLESPage::OpenGLESPage(OpenGLES* openGLES) :
currentDisplayInformation->OrientationChanged += currentDisplayInformation->OrientationChanged +=
ref new TypedEventHandler<DisplayInformation^, Object^>(this, &OpenGLESPage::OnOrientationChanged); ref new TypedEventHandler<DisplayInformation^, Object^>(this, &OpenGLESPage::OnOrientationChanged);
m_orientation = currentDisplayInformation->CurrentOrientation; mOrientation = currentDisplayInformation->CurrentOrientation;
this->Loaded += this->Loaded +=
ref new Windows::UI::Xaml::RoutedEventHandler(this, &OpenGLESPage::OnPageLoaded); ref new Windows::UI::Xaml::RoutedEventHandler(this, &OpenGLESPage::OnPageLoaded);
@ -111,23 +112,23 @@ OpenGLESPage::OpenGLESPage(OpenGLES* openGLES) :
auto workItemHandler = ref new WorkItemHandler([this](IAsyncAction ^) auto workItemHandler = ref new WorkItemHandler([this](IAsyncAction ^)
{ {
// The CoreIndependentInputSource will raise pointer events for the specified device types on whichever thread it's created on. // The CoreIndependentInputSource will raise pointer events for the specified device types on whichever thread it's created on.
m_coreInput = swapChainPanel->CreateCoreIndependentInputSource( mCoreInput = swapChainPanel->CreateCoreIndependentInputSource(
Windows::UI::Core::CoreInputDeviceTypes::Mouse | Windows::UI::Core::CoreInputDeviceTypes::Mouse |
Windows::UI::Core::CoreInputDeviceTypes::Touch | Windows::UI::Core::CoreInputDeviceTypes::Touch |
Windows::UI::Core::CoreInputDeviceTypes::Pen Windows::UI::Core::CoreInputDeviceTypes::Pen
); );
// Register for pointer events, which will be raised on the background thread. // Register for pointer events, which will be raised on the background thread.
m_coreInput->PointerPressed += ref new TypedEventHandler<Object^, PointerEventArgs^>(this, &OpenGLESPage::OnPointerPressed); mCoreInput->PointerPressed += ref new TypedEventHandler<Object^, PointerEventArgs^>(this, &OpenGLESPage::OnPointerPressed);
m_coreInput->PointerMoved += ref new TypedEventHandler<Object^, PointerEventArgs^>(this, &OpenGLESPage::OnPointerMoved); mCoreInput->PointerMoved += ref new TypedEventHandler<Object^, PointerEventArgs^>(this, &OpenGLESPage::OnPointerMoved);
m_coreInput->PointerReleased += ref new TypedEventHandler<Object^, PointerEventArgs^>(this, &OpenGLESPage::OnPointerReleased); mCoreInput->PointerReleased += ref new TypedEventHandler<Object^, PointerEventArgs^>(this, &OpenGLESPage::OnPointerReleased);
// Begin processing input messages as they're delivered. // Begin processing input messages as they're delivered.
m_coreInput->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit); mCoreInput->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit);
}); });
// Run task on a dedicated high priority background thread. // Run task on a dedicated high priority background thread.
m_inputLoopWorker = ThreadPool::RunAsync(workItemHandler, WorkItemPriority::High, WorkItemOptions::TimeSliced); mInputLoopWorker = ThreadPool::RunAsync(workItemHandler, WorkItemPriority::High, WorkItemOptions::TimeSliced);
} }
OpenGLESPage::~OpenGLESPage() OpenGLESPage::~OpenGLESPage()
@ -141,29 +142,30 @@ void OpenGLESPage::OnPageLoaded(Platform::Object^ sender, Windows::UI::Xaml::Rou
// The SwapChainPanel has been created and arranged in the page layout, so EGL can be initialized. // The SwapChainPanel has been created and arranged in the page layout, so EGL can be initialized.
CreateRenderSurface(); CreateRenderSurface();
StartRenderLoop(); StartRenderLoop();
mVisible = true;
} }
void OpenGLESPage::OnPointerPressed(Object^ sender, PointerEventArgs^ e) void OpenGLESPage::OnPointerPressed(Object^ sender, PointerEventArgs^ e)
{ {
if (m_renderer) if (mRenderer)
{ {
m_renderer->QueuePointerEvent(PointerEventType::PointerPressed, e); mRenderer->QueuePointerEvent(PointerEventType::PointerPressed, e);
} }
} }
void OpenGLESPage::OnPointerMoved(Object^ sender, PointerEventArgs^ e) void OpenGLESPage::OnPointerMoved(Object^ sender, PointerEventArgs^ e)
{ {
if (m_renderer) if (mRenderer)
{ {
m_renderer->QueuePointerEvent(PointerEventType::PointerMoved, e); mRenderer->QueuePointerEvent(PointerEventType::PointerMoved, e);
} }
} }
void OpenGLESPage::OnPointerReleased(Object^ sender, PointerEventArgs^ e) void OpenGLESPage::OnPointerReleased(Object^ sender, PointerEventArgs^ e)
{ {
if (m_renderer) if (mRenderer)
{ {
m_renderer->QueuePointerEvent(PointerEventType::PointerReleased, e); mRenderer->QueuePointerEvent(PointerEventType::PointerReleased, e);
} }
} }
@ -172,9 +174,9 @@ void OpenGLESPage::OnKeyPressed(CoreWindow^ sender, KeyEventArgs^ e)
if (!e->KeyStatus.WasKeyDown) if (!e->KeyStatus.WasKeyDown)
{ {
//log("OpenGLESPage::OnKeyPressed %d", e->VirtualKey); //log("OpenGLESPage::OnKeyPressed %d", e->VirtualKey);
if (m_renderer) if (mRenderer)
{ {
m_renderer->QueueKeyboardEvent(WinRTKeyboardEventType::KeyPressed, e); mRenderer->QueueKeyboardEvent(WinRTKeyboardEventType::KeyPressed, e);
} }
} }
} }
@ -192,9 +194,9 @@ void OpenGLESPage::OnCharacterReceived(CoreWindow^ sender, CharacterReceivedEven
void OpenGLESPage::OnKeyReleased(CoreWindow^ sender, KeyEventArgs^ e) void OpenGLESPage::OnKeyReleased(CoreWindow^ sender, KeyEventArgs^ e)
{ {
//log("OpenGLESPage::OnKeyReleased %d", e->VirtualKey); //log("OpenGLESPage::OnKeyReleased %d", e->VirtualKey);
if (m_renderer) if (mRenderer)
{ {
m_renderer->QueueKeyboardEvent(WinRTKeyboardEventType::KeyReleased, e); mRenderer->QueueKeyboardEvent(WinRTKeyboardEventType::KeyReleased, e);
} }
} }
@ -202,18 +204,20 @@ void OpenGLESPage::OnKeyReleased(CoreWindow^ sender, KeyEventArgs^ e)
void OpenGLESPage::OnOrientationChanged(DisplayInformation^ sender, Object^ args) void OpenGLESPage::OnOrientationChanged(DisplayInformation^ sender, Object^ args)
{ {
critical_section::scoped_lock lock(mSwapChainPanelSizeCriticalSection); critical_section::scoped_lock lock(mSwapChainPanelSizeCriticalSection);
m_orientation = sender->CurrentOrientation; mOrientation = sender->CurrentOrientation;
} }
void OpenGLESPage::OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args) void OpenGLESPage::OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args)
{ {
if (args->Visible && mRenderSurface != EGL_NO_SURFACE) if (args->Visible && mRenderSurface != EGL_NO_SURFACE)
{ {
StartRenderLoop(); std::unique_lock<std::mutex> locker(mSleepMutex);
mVisible = true;
mSleepCondition.notify_one();
} }
else else
{ {
StopRenderLoop(); mVisible = false;
} }
} }
@ -230,15 +234,14 @@ void OpenGLESPage::OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Wi
*/ */
void OpenGLESPage::OnBackButtonPressed(Object^ sender, BackPressedEventArgs^ args) void OpenGLESPage::OnBackButtonPressed(Object^ sender, BackPressedEventArgs^ args)
{ {
if (m_renderer) if (mRenderer)
{ {
m_renderer->QueueBackButtonEvent(); mRenderer->QueueBackButtonEvent();
args->Handled = true; args->Handled = true;
} }
} }
#endif #endif
void OpenGLESPage::OnSwapChainPanelSizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e) void OpenGLESPage::OnSwapChainPanelSizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e)
{ {
// Size change events occur outside of the render thread. A lock is required when updating // Size change events occur outside of the render thread. A lock is required when updating
@ -291,19 +294,13 @@ void OpenGLESPage::DestroyRenderSurface()
void OpenGLESPage::RecoverFromLostDevice() void OpenGLESPage::RecoverFromLostDevice()
{ {
// Stop the render loop, reset OpenGLES, recreate the render surface critical_section::scoped_lock lock(mRenderSurfaceCriticalSection);
// and start the render loop again to recover from a lost device. DestroyRenderSurface();
mOpenGLES->Reset();
StopRenderLoop(); CreateRenderSurface();
std::unique_lock<std::mutex> locker(mSleepMutex);
{ mDeviceLost = false;
critical_section::scoped_lock lock(mRenderSurfaceCriticalSection); mSleepCondition.notify_one();
DestroyRenderSurface();
mOpenGLES->Reset();
CreateRenderSurface();
}
StartRenderLoop();
} }
void OpenGLESPage::TerminateApp() void OpenGLESPage::TerminateApp()
@ -316,7 +313,6 @@ void OpenGLESPage::TerminateApp()
mOpenGLES->DestroySurface(mRenderSurface); mOpenGLES->DestroySurface(mRenderSurface);
mOpenGLES->Cleanup(); mOpenGLES->Cleanup();
} }
} }
Windows::UI::Xaml::Application::Current->Exit(); Windows::UI::Xaml::Application::Current->Exit();
} }
@ -330,45 +326,60 @@ void OpenGLESPage::StartRenderLoop()
} }
DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView(); DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
m_dpi = currentDisplayInformation->LogicalDpi; mDpi = currentDisplayInformation->LogicalDpi;
auto dispatcher = Windows::UI::Xaml::Window::Current->CoreWindow->Dispatcher; auto dispatcher = Windows::UI::Xaml::Window::Current->CoreWindow->Dispatcher;
// Create a task for rendering that will be run on a background thread. // Create a task for rendering that will be run on a background thread.
auto workItemHandler = ref new Windows::System::Threading::WorkItemHandler([this, dispatcher](Windows::Foundation::IAsyncAction ^ action) auto workItemHandler = ref new Windows::System::Threading::WorkItemHandler([this, dispatcher](Windows::Foundation::IAsyncAction ^ action)
{ {
critical_section::scoped_lock lock(mRenderSurfaceCriticalSection);
mOpenGLES->MakeCurrent(mRenderSurface); mOpenGLES->MakeCurrent(mRenderSurface);
GLsizei panelWidth = 0; GLsizei panelWidth = 0;
GLsizei panelHeight = 0; GLsizei panelHeight = 0;
GetSwapChainPanelSize(&panelWidth, &panelHeight); GetSwapChainPanelSize(&panelWidth, &panelHeight);
if (m_renderer.get() == nullptr) if (mRenderer.get() == nullptr)
{ {
m_renderer = std::make_shared<Cocos2dRenderer>(panelWidth, panelHeight, m_dpi, m_orientation, dispatcher, swapChainPanel); mRenderer = std::make_shared<Cocos2dRenderer>(panelWidth, panelHeight, mDpi, mOrientation, dispatcher, swapChainPanel);
} }
if (m_deviceLost) mRenderer->Resume();
{
m_deviceLost = false;
m_renderer->DeviceLost();
}
else
{
m_renderer->Resume();
}
while (action->Status == Windows::Foundation::AsyncStatus::Started)
while (action->Status == Windows::Foundation::AsyncStatus::Started && !m_deviceLost)
{ {
GetSwapChainPanelSize(&panelWidth, &panelHeight); if (!mVisible)
m_renderer.get()->Draw(panelWidth, panelHeight, m_dpi, m_orientation);
// run on main UI thread
if (m_renderer->AppShouldExit())
{ {
mRenderer->Pause();
}
// wait until app is visible again or thread is cancelled
while (!mVisible)
{
std::unique_lock<std::mutex> lock(mSleepMutex);
mSleepCondition.wait(lock);
if (action->Status != Windows::Foundation::AsyncStatus::Started)
{
return; // thread was cancelled. Exit thread
}
if (mVisible)
{
mRenderer->Resume();
}
else // spurious wake up
{
continue;
}
}
GetSwapChainPanelSize(&panelWidth, &panelHeight);
mRenderer.get()->Draw(panelWidth, panelHeight, mDpi, mOrientation);
if (mRenderer->AppShouldExit())
{
// run on main UI thread
swapChainPanel->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]() swapChainPanel->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
{ {
TerminateApp(); TerminateApp();
@ -376,17 +387,19 @@ void OpenGLESPage::StartRenderLoop()
return; return;
} }
else if (mOpenGLES->SwapBuffers(mRenderSurface) != GL_TRUE)
EGLBoolean result = GL_FALSE;
{ {
// The call to eglSwapBuffers might not be successful (i.e. due to Device Lost) critical_section::scoped_lock lock(mRenderSurfaceCriticalSection);
result = mOpenGLES->SwapBuffers(mRenderSurface);
}
if (result != GL_TRUE)
{
// The call to eglSwapBuffers was not be successful (i.e. due to Device Lost)
// If the call fails, then we must reinitialize EGL and the GL resources. // If the call fails, then we must reinitialize EGL and the GL resources.
mRenderer->Pause();
m_deviceLost = true; mDeviceLost = true;
if (m_renderer)
{
m_renderer->Pause();
}
// XAML objects like the SwapChainPanel must only be manipulated on the UI thread. // XAML objects like the SwapChainPanel must only be manipulated on the UI thread.
swapChainPanel->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([=]() swapChainPanel->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([=]()
@ -394,13 +407,28 @@ void OpenGLESPage::StartRenderLoop()
RecoverFromLostDevice(); RecoverFromLostDevice();
}, CallbackContext::Any)); }, CallbackContext::Any));
return; // wait until OpenGL is reset or thread is cancelled
} while (mDeviceLost)
} {
std::unique_lock<std::mutex> lock(mSleepMutex);
mSleepCondition.wait(lock);
if (m_renderer) if (action->Status != Windows::Foundation::AsyncStatus::Started)
{ {
m_renderer->Pause(); return; // thread was cancelled. Exit thread
}
if (!mDeviceLost)
{
// restart cocos2d-x
mRenderer->DeviceLost();
}
else // spurious wake up
{
continue;
}
}
}
} }
}); });
@ -413,6 +441,8 @@ void OpenGLESPage::StopRenderLoop()
if (mRenderLoopWorker) if (mRenderLoopWorker)
{ {
mRenderLoopWorker->Cancel(); mRenderLoopWorker->Cancel();
std::unique_lock<std::mutex> locker(mSleepMutex);
mSleepCondition.notify_one();
mRenderLoopWorker = nullptr; mRenderLoopWorker = nullptr;
} }
} }

View File

@ -21,6 +21,8 @@
#include "OpenGLES.h" #include "OpenGLES.h"
#include "OpenGLESPage.g.h" #include "OpenGLESPage.g.h"
#include <memory> #include <memory>
#include <condition_variable>
#include <mutex>
#include "Cocos2dRenderer.h" #include "Cocos2dRenderer.h"
@ -51,7 +53,7 @@ namespace cocos2d
void StopRenderLoop(); void StopRenderLoop();
OpenGLES* mOpenGLES; OpenGLES* mOpenGLES;
std::shared_ptr<cocos2d::Cocos2dRenderer> m_renderer; std::shared_ptr<cocos2d::Cocos2dRenderer> mRenderer;
Windows::Foundation::Size mSwapChainPanelSize; Windows::Foundation::Size mSwapChainPanelSize;
Concurrency::critical_section mSwapChainPanelSizeCriticalSection; Concurrency::critical_section mSwapChainPanelSizeCriticalSection;
@ -64,8 +66,8 @@ namespace cocos2d
Windows::Foundation::IAsyncAction^ mRenderLoopWorker; Windows::Foundation::IAsyncAction^ mRenderLoopWorker;
// Track user input on a background worker thread. // Track user input on a background worker thread.
Windows::Foundation::IAsyncAction^ m_inputLoopWorker; Windows::Foundation::IAsyncAction^ mInputLoopWorker;
Windows::UI::Core::CoreIndependentInputSource^ m_coreInput; Windows::UI::Core::CoreIndependentInputSource^ mCoreInput;
// Independent input handling functions. // Independent input handling functions.
void OnPointerPressed(Platform::Object^ sender, Windows::UI::Core::PointerEventArgs^ e); void OnPointerPressed(Platform::Object^ sender, Windows::UI::Core::PointerEventArgs^ e);
@ -77,9 +79,12 @@ namespace cocos2d
void OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args); void OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
float m_dpi; float mDpi;
bool m_deviceLost; bool mDeviceLost;
Windows::Graphics::Display::DisplayOrientations m_orientation; bool mVisible;
Windows::Graphics::Display::DisplayOrientations mOrientation;
std::mutex mSleepMutex;
std::condition_variable mSleepCondition;
}; };
} }

View File

@ -0,0 +1,12 @@
//
// pch.h
// Header for standard system include files.
//
#pragma once
#include "mozilla\Char16.h"
#include "cocos2d.h"
#include "cocos-ext.h"

View File

@ -1,470 +0,0 @@
//-----------------------------------------------------------------------------------------------
// Copyright (c) 2012 Andrew Garrison
//-----------------------------------------------------------------------------------------------
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//-----------------------------------------------------------------------------------------------
#include "platform/CCPlatformConfig.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
#include "DirectXBase.h"
#include <windows.ui.xaml.media.dxinterop.h>
#include <math.h>
using namespace Microsoft::WRL;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::Foundation;
using namespace Windows::Graphics::Display;
using namespace D2D1;
// Constructor.
DirectXBase::DirectXBase() :
m_dpi(-1.0f)
{
}
// Initialize the DirectX resources required to run.
void DirectXBase::Initialize(CoreWindow^ window, SwapChainBackgroundPanel^ panel, float dpi)
{
m_window = window;
m_panel = panel;
CreateDeviceIndependentResources();
CreateDeviceResources();
SetDpi(dpi);
}
// These are the resources required independent of the device.
void DirectXBase::CreateDeviceIndependentResources()
{
D2D1_FACTORY_OPTIONS options;
ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
#if defined(_DEBUG)
// If the project is in a debug build, enable Direct2D debugging via SDK Layers
options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
#endif
DX::ThrowIfFailed(
D2D1CreateFactory(
D2D1_FACTORY_TYPE_SINGLE_THREADED,
__uuidof(ID2D1Factory1),
&options,
&m_d2dFactory
)
);
DX::ThrowIfFailed(
DWriteCreateFactory(
DWRITE_FACTORY_TYPE_SHARED,
__uuidof(IDWriteFactory),
&m_dwriteFactory
)
);
DX::ThrowIfFailed(
CoCreateInstance(
CLSID_WICImagingFactory,
nullptr,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&m_wicFactory)
)
);
}
// These are the resources that depend on the device.
void DirectXBase::CreateDeviceResources()
{
// This flag adds support for surfaces with a different color channel ordering than the API default.
// It is recommended usage, and is required for compatibility with Direct2D.
UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
ComPtr<IDXGIDevice> dxgiDevice;
#if defined(_DEBUG)
// If the project is in a debug build, enable debugging via SDK Layers with this flag.
creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
// This array defines the set of DirectX hardware feature levels this app will support.
// Note the ordering should be preserved.
// Don't forget to declare your application's minimum required feature level in its
// description. All applications are assumed to support 9.1 unless otherwise stated.
D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
D3D_FEATURE_LEVEL_9_3,
D3D_FEATURE_LEVEL_9_2,
D3D_FEATURE_LEVEL_9_1
};
// Create the DX11 API device object, and get a corresponding context.
ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> context;
DX::ThrowIfFailed(
D3D11CreateDevice(
nullptr, // specify null to use the default adapter
D3D_DRIVER_TYPE_HARDWARE,
0, // leave as 0 unless software device
creationFlags, // optionally set debug and Direct2D compatibility flags
featureLevels, // list of feature levels this app can support
ARRAYSIZE(featureLevels), // number of entries in above list
D3D11_SDK_VERSION, // always set this to D3D11_SDK_VERSION for Metro style apps
&device, // returns the Direct3D device created
&m_featureLevel, // returns feature level of device created
&context // returns the device immediate context
)
);
// Get the DirectX11.1 device by QI off the DirectX11 one.
DX::ThrowIfFailed(
device.As(&m_d3dDevice)
);
// And get the corresponding device context in the same way.
DX::ThrowIfFailed(
context.As(&m_d3dContext)
);
// Obtain the underlying DXGI device of the Direct3D11.1 device.
DX::ThrowIfFailed(
m_d3dDevice.As(&dxgiDevice)
);
// Obtain the Direct2D device for 2-D rendering.
DX::ThrowIfFailed(
m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
);
// And get its corresponding device context object.
DX::ThrowIfFailed(
m_d2dDevice->CreateDeviceContext(
D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
&m_d2dContext
)
);
// Release the swap chain (if it exists) as it will be incompatible with the new device.
m_swapChain = nullptr;
}
// Helps track the DPI in the helper class.
// This is called in the dpiChanged event handler in the view class.
void DirectXBase::SetDpi(float dpi)
{
if (dpi != m_dpi)
{
// Save the DPI of this display in our class.
m_dpi = dpi;
// Update Direct2D's stored DPI.
m_d2dContext->SetDpi(m_dpi, m_dpi);
// Often a DPI change implies a window size change. In some cases Windows will issues
// both a size changed event and a DPI changed event. In this case, the resulting bounds
// will not change, and the window resize code will only be executed once.
UpdateForWindowSizeChange();
}
}
// This routine is called in the event handler for the view SizeChanged event.
void DirectXBase::UpdateForWindowSizeChange()
{
// Only handle window size changed if there is no pending DPI change.
if (m_dpi != DisplayProperties::LogicalDpi)
return;
if (m_window->Bounds.Width != m_windowBounds.Width ||
m_window->Bounds.Height != m_windowBounds.Height)
{
m_d2dContext->SetTarget(nullptr);
m_d2dTargetBitmap = nullptr;
m_renderTargetView = nullptr;
m_depthStencilView = nullptr;
CreateWindowSizeDependentResources();
}
}
// Allocate all memory resources that change on a window SizeChanged event.
void DirectXBase::CreateWindowSizeDependentResources()
{
// Store the window bounds so the next time we get a SizeChanged event we can
// avoid rebuilding everything if the size is identical.
m_windowBounds = m_window->Bounds;
// Calculate the necessary swap chain and render target size in pixels.
m_renderTargetSize.Width = ConvertDipsToPixels(m_windowBounds.Width);
m_renderTargetSize.Height = ConvertDipsToPixels(m_windowBounds.Height);
// If the swap chain already exists, resize it.
if (m_swapChain != nullptr)
{
DX::ThrowIfFailed(
m_swapChain->ResizeBuffers(
2,
static_cast<UINT>(m_renderTargetSize.Width),
static_cast<UINT>(m_renderTargetSize.Height),
DXGI_FORMAT_B8G8R8A8_UNORM,
0
)
);
}
// Otherwise, create a new one.
else
{
// Allocate a descriptor.
DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
swapChainDesc.Width = static_cast<UINT>(m_renderTargetSize.Width); // Match the size of the windowm.
swapChainDesc.Height = static_cast<UINT>(m_renderTargetSize.Height);
swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // This is the most common swapchain format.
swapChainDesc.Stereo = false;
swapChainDesc.SampleDesc.Count = 1; // Don't use multi-sampling.
swapChainDesc.SampleDesc.Quality = 0;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.BufferCount = 2; // Use double buffering to enable flip.
swapChainDesc.Scaling = DXGI_SCALING_STRETCH;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Metro style apps must use this SwapEffect.
swapChainDesc.Flags = 0;
// Once the desired swap chain description is configured, it must be created on the same adapter as our D3D Device.
// First, retrieve the underlying DXGI Device from the D3D Device.
ComPtr<IDXGIDevice1> dxgiDevice;
DX::ThrowIfFailed(
m_d3dDevice.As(&dxgiDevice)
);
// Identify the physical adapter (GPU or card) this device is running on.
ComPtr<IDXGIAdapter> dxgiAdapter;
DX::ThrowIfFailed(
dxgiDevice->GetAdapter(&dxgiAdapter)
);
// And obtain the factory object that created it.
ComPtr<IDXGIFactory2> dxgiFactory;
DX::ThrowIfFailed(
dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
);
// Create the swap chain and then associate it with the SwapChainBackgroundPanel.
DX::ThrowIfFailed(
dxgiFactory->CreateSwapChainForComposition(
m_d3dDevice.Get(),
&swapChainDesc,
nullptr,
&m_swapChain
)
);
ComPtr<ISwapChainBackgroundPanelNative> panelNative;
DX::ThrowIfFailed(
reinterpret_cast<IUnknown*>(m_panel)->QueryInterface(IID_PPV_ARGS(&panelNative))
);
DX::ThrowIfFailed(
panelNative->SetSwapChain(m_swapChain.Get())
);
// Ensure that DXGI does not queue more than one frame at a time. This both reduces
// latency and ensures that the application will only render after each VSync, minimizing
// power consumption.
DX::ThrowIfFailed(
dxgiDevice->SetMaximumFrameLatency(1)
);
}
// Obtain the backbuffer for this window which will be the final 3D rendertarget.
ComPtr<ID3D11Texture2D> backBuffer;
DX::ThrowIfFailed(
m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
);
// Create a view interface on the rendertarget to use on bind.
DX::ThrowIfFailed(
m_d3dDevice->CreateRenderTargetView(
backBuffer.Get(),
nullptr,
&m_renderTargetView
)
);
// Create a descriptor for the depth/stencil buffer.
CD3D11_TEXTURE2D_DESC depthStencilDesc(
DXGI_FORMAT_D24_UNORM_S8_UINT,
static_cast<UINT>(m_renderTargetSize.Width),
static_cast<UINT>(m_renderTargetSize.Height),
1,
1,
D3D11_BIND_DEPTH_STENCIL
);
// Allocate a 2-D surface as the depth/stencil buffer.
ComPtr<ID3D11Texture2D> depthStencil;
DX::ThrowIfFailed(
m_d3dDevice->CreateTexture2D(
&depthStencilDesc,
nullptr,
&depthStencil
)
);
// Create a DepthStencil view on this surface to use on bind.
CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D);
DX::ThrowIfFailed(
m_d3dDevice->CreateDepthStencilView(
depthStencil.Get(),
&depthStencilViewDesc,
&m_depthStencilView
)
);
// Create a viewport descriptor of the full window size.
CD3D11_VIEWPORT viewport(
0.0f,
0.0f,
m_renderTargetSize.Width,
m_renderTargetSize.Height
);
// Set the current viewport using the descriptor.
m_d3dContext->RSSetViewports(1, &viewport);
// Now we set up the Direct2D render target bitmap linked to the swapchain.
// Whenever we render to this bitmap, it will be directly rendered to the
// swapchain associated with the window.
D2D1_BITMAP_PROPERTIES1 bitmapProperties =
BitmapProperties1(
D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
m_dpi,
m_dpi
);
// Direct2D needs the DXGI version of the backbuffer surface pointer.
ComPtr<IDXGISurface> dxgiBackBuffer;
DX::ThrowIfFailed(
m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
);
// Get a D2D surface from the DXGI back buffer to use as the D2D render target.
DX::ThrowIfFailed(
m_d2dContext->CreateBitmapFromDxgiSurface(
dxgiBackBuffer.Get(),
&bitmapProperties,
&m_d2dTargetBitmap
)
);
// So now we can set the Direct2D render target.
m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
// Set D2D text anti-alias mode to Grayscale to ensure proper rendering of text on intermediate surfaces.
m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
// Set the blend function.
ID3D11BlendState* g_pBlendState = NULL;
D3D11_BLEND_DESC blendDesc;
ZeroMemory(&blendDesc, sizeof(D3D11_BLEND_DESC));
blendDesc.AlphaToCoverageEnable = false;
blendDesc.IndependentBlendEnable = false;
D3D11_RENDER_TARGET_BLEND_DESC rtBlendDesc;
rtBlendDesc.BlendEnable = false;
rtBlendDesc.SrcBlend = D3D11_BLEND_SRC_ALPHA;
rtBlendDesc.DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
rtBlendDesc.BlendOp = D3D11_BLEND_OP_ADD;
rtBlendDesc.SrcBlendAlpha = D3D11_BLEND_ZERO;
rtBlendDesc.DestBlendAlpha = D3D11_BLEND_ZERO;
rtBlendDesc.BlendOpAlpha = D3D11_BLEND_OP_ADD;
rtBlendDesc.RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
blendDesc.RenderTarget[0] = rtBlendDesc;
auto hr1 = m_d3dDevice->CreateBlendState(&blendDesc, &g_pBlendState);
m_d3dContext->OMSetBlendState(g_pBlendState, 0, 0xffffffff);
D3D11_DEPTH_STENCIL_DESC dsDesc;
// Depth test parameters
dsDesc.DepthEnable = false;
dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
dsDesc.DepthFunc = D3D11_COMPARISON_LESS;
// Stencil test parameters
dsDesc.StencilEnable = true;
dsDesc.StencilReadMask = 0xFF;
dsDesc.StencilWriteMask = 0xFF;
// Stencil operations if pixel is front-facing
dsDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
dsDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
dsDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
dsDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// Stencil operations if pixel is back-facing
dsDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
dsDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
dsDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
dsDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// Create depth stencil state
ID3D11DepthStencilState * pDSState;
m_d3dDevice->CreateDepthStencilState(&dsDesc, &pDSState);
m_d3dContext->OMSetDepthStencilState(pDSState, 1);
m_d3dContext->OMSetRenderTargets(1, m_renderTargetView.GetAddressOf(), m_depthStencilView.Get());
}
// Method to deliver the final image to the display.
void DirectXBase::Present()
{
// The application may optionally specify "dirty" or "scroll" rects to improve efficiency
// in certain scenarios.
DXGI_PRESENT_PARAMETERS parameters = {0};
parameters.DirtyRectsCount = 0;
parameters.pDirtyRects = nullptr;
parameters.pScrollRect = nullptr;
parameters.pScrollOffset = nullptr;
// The first argument instructs DXGI to block until VSync, putting the application
// to sleep until the next VSync. This ensures we don't waste any cycles rendering
// frames that will never be displayed to the screen.
HRESULT hr = m_swapChain->Present1(1, 0, &parameters);
m_d3dContext->OMSetRenderTargets(1,m_renderTargetView.GetAddressOf(),m_depthStencilView.Get());
// If the device was removed either by a disconnect or a driver upgrade, we
// must completely reinitialize the renderer.
if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
{
Initialize(m_window.Get(), m_panel, m_dpi);
}
else
{
DX::ThrowIfFailed(hr);
}
}
// Method to convert a length in device-independent pixels (DIPs) to a length in physical pixels.
float DirectXBase::ConvertDipsToPixels(float dips)
{
static const float dipsPerInch = 96.0f;
return floor(dips * m_dpi / dipsPerInch + 0.5f); // Round to nearest integer.
}
#endif // (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)

View File

@ -1,83 +0,0 @@
//-----------------------------------------------------------------------------------------------
// Copyright (c) 2012 Andrew Garrison
//-----------------------------------------------------------------------------------------------
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//-----------------------------------------------------------------------------------------------
#pragma once
#include "platform/CCPlatformConfig.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
#include <wrl/client.h>
#include <d3d11_1.h>
#include <d2d1_1.h>
#include <d2d1effects.h>
#include <dwrite_1.h>
#include <wincodec.h>
#include <agile.h>
#include <DirectXMath.h>
#include "DirectXHelper.h"
#pragma warning (disable: 4449)
using namespace Windows::UI::ViewManagement;
// Helper class that initializes DirectX APIs
ref class DirectXBase abstract
{
internal:
DirectXBase();
public:
virtual void Initialize(Windows::UI::Core::CoreWindow^ window, Windows::UI::Xaml::Controls::SwapChainBackgroundPanel^ panel, float dpi);
virtual void CreateDeviceIndependentResources();
virtual void CreateDeviceResources();
virtual void SetDpi(float dpi);
virtual void CreateWindowSizeDependentResources();
virtual void UpdateForWindowSizeChange();
virtual void Present();
virtual float ConvertDipsToPixels(float dips);
protected private:
Platform::Agile<Windows::UI::Core::CoreWindow> m_window;
Windows::UI::Xaml::Controls::SwapChainBackgroundPanel^ m_panel;
// Direct2D Objects
Microsoft::WRL::ComPtr<ID2D1Factory1> m_d2dFactory;
Microsoft::WRL::ComPtr<ID2D1Device> m_d2dDevice;
Microsoft::WRL::ComPtr<ID2D1DeviceContext> m_d2dContext;
Microsoft::WRL::ComPtr<ID2D1Bitmap1> m_d2dTargetBitmap;
// DirectWrite & Windows Imaging Component Objects
Microsoft::WRL::ComPtr<IDWriteFactory1> m_dwriteFactory;
Microsoft::WRL::ComPtr<IWICImagingFactory2> m_wicFactory;
// Direct3D Objects
Microsoft::WRL::ComPtr<ID3D11Device1> m_d3dDevice;
Microsoft::WRL::ComPtr<ID3D11DeviceContext1> m_d3dContext;
Microsoft::WRL::ComPtr<IDXGISwapChain1> m_swapChain;
Microsoft::WRL::ComPtr<ID3D11RenderTargetView> m_renderTargetView;
Microsoft::WRL::ComPtr<ID3D11DepthStencilView> m_depthStencilView;
D3D_FEATURE_LEVEL m_featureLevel;
Windows::Foundation::Size m_renderTargetSize;
Windows::Foundation::Rect m_windowBounds;
float m_dpi;
};
#pragma warning (default: 4449)
#endif // (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)

View File

@ -1,38 +0,0 @@
//-----------------------------------------------------------------------------------------------
// Copyright (c) 2012 Andrew Garrison
//-----------------------------------------------------------------------------------------------
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//-----------------------------------------------------------------------------------------------
#pragma once
#include "platform/CCPlatformConfig.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
// Helper utilities to make Win32 APIs work with exceptions.
namespace DX
{
inline void ThrowIfFailed(HRESULT hr)
{
if (FAILED(hr))
{
// Set a breakpoint on this line to catch Win32 API errors.
throw Platform::Exception::CreateException(hr);
}
}
}
#endif // (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)

View File

@ -38,9 +38,14 @@ THE SOFTWARE.
#include "base/CCEventType.h" #include "base/CCEventType.h"
#include "base/CCDirector.h" #include "base/CCDirector.h"
#include "base/CCEventDispatcher.h" #include "base/CCEventDispatcher.h"
#include "2d/CCCamera.h"
#include "deprecated/CCString.h"
NS_CC_BEGIN NS_CC_BEGIN
// static vector with all the registered custom binding resolvers
std::vector<GLProgramState::AutoBindingResolver*> GLProgramState::_customAutoBindingResolvers;
// //
// //
// UniformValue // UniformValue
@ -320,7 +325,7 @@ GLProgramState* GLProgramState::create(GLProgram *glprogram)
return nullptr; return nullptr;
} }
GLProgramState* GLProgramState::getOrCreateWithGLProgramName(const std::string &glProgramName ) GLProgramState* GLProgramState::getOrCreateWithGLProgramName(const std::string& glProgramName )
{ {
GLProgram *glProgram = GLProgramCache::getInstance()->getGLProgram(glProgramName); GLProgram *glProgram = GLProgramCache::getInstance()->getGLProgram(glProgramName);
if( glProgram ) if( glProgram )
@ -354,9 +359,10 @@ GLProgramState* GLProgramState::getOrCreateWithShaders(const std::string& vertex
GLProgramState::GLProgramState() GLProgramState::GLProgramState()
: _uniformAttributeValueDirty(true) : _uniformAttributeValueDirty(true)
, _textureUnitIndex(1) , _textureUnitIndex(4) // first 4 textures unites are reserved for CC_Texture0-3
, _vertexAttribsFlags(0) , _vertexAttribsFlags(0)
, _glprogram(nullptr) , _glprogram(nullptr)
, _nodeBinding(nullptr)
{ {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
/** listen the event that renderer was recreated on Android/WP8 */ /** listen the event that renderer was recreated on Android/WP8 */
@ -401,6 +407,13 @@ GLProgramState* GLProgramState::clone() const
glprogramstate->_textureUnitIndex = this->_textureUnitIndex; glprogramstate->_textureUnitIndex = this->_textureUnitIndex;
glprogramstate->_boundTextureUnits = this->_boundTextureUnits; glprogramstate->_boundTextureUnits = this->_boundTextureUnits;
// _nodeBinding is null since a node can only have one state.
// making the null explict to avoid possible bugs in the future
glprogramstate->_nodeBinding = nullptr;
// copy autobindings... rebound them once a target is set again
glprogramstate->_autoBindings = _autoBindings;
glprogramstate->autorelease(); glprogramstate->autorelease();
return glprogramstate; return glprogramstate;
} }
@ -429,10 +442,12 @@ bool GLProgramState::init(GLProgram* glprogram)
void GLProgramState::resetGLProgram() void GLProgramState::resetGLProgram()
{ {
CC_SAFE_RELEASE(_glprogram); CC_SAFE_RELEASE(_glprogram);
_glprogram = nullptr;
_uniforms.clear(); _uniforms.clear();
_attributes.clear(); _attributes.clear();
// first texture is GL_TEXTURE1 // first texture is GL_TEXTURE1
_textureUnitIndex = 1; _textureUnitIndex = 1;
_nodeBinding = nullptr;
} }
void GLProgramState::apply(const Mat4& modelView) void GLProgramState::apply(const Mat4& modelView)
@ -530,7 +545,7 @@ UniformValue* GLProgramState::getUniformValue(GLint uniformLocation)
return nullptr; return nullptr;
} }
UniformValue* GLProgramState::getUniformValue(const std::string &name) UniformValue* GLProgramState::getUniformValue(const std::string& name)
{ {
updateUniformsAndAttributes(); updateUniformsAndAttributes();
const auto itr = _uniformsByName.find(name); const auto itr = _uniformsByName.find(name);
@ -539,7 +554,7 @@ UniformValue* GLProgramState::getUniformValue(const std::string &name)
return nullptr; return nullptr;
} }
VertexAttribValue* GLProgramState::getVertexAttribValue(const std::string &name) VertexAttribValue* GLProgramState::getVertexAttribValue(const std::string& name)
{ {
updateUniformsAndAttributes(); updateUniformsAndAttributes();
const auto itr = _attributes.find(name); const auto itr = _attributes.find(name);
@ -549,7 +564,7 @@ VertexAttribValue* GLProgramState::getVertexAttribValue(const std::string &name)
} }
// VertexAttrib Setters // VertexAttrib Setters
void GLProgramState::setVertexAttribCallback(const std::string &name, const std::function<void(VertexAttrib*)> &callback) void GLProgramState::setVertexAttribCallback(const std::string& name, const std::function<void(VertexAttrib*)> &callback)
{ {
VertexAttribValue *v = getVertexAttribValue(name); VertexAttribValue *v = getVertexAttribValue(name);
if(v) { if(v) {
@ -562,7 +577,7 @@ void GLProgramState::setVertexAttribCallback(const std::string &name, const std:
} }
} }
void GLProgramState::setVertexAttribPointer(const std::string &name, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLvoid *pointer) void GLProgramState::setVertexAttribPointer(const std::string& name, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLvoid *pointer)
{ {
auto v = getVertexAttribValue(name); auto v = getVertexAttribValue(name);
if(v) { if(v) {
@ -577,7 +592,7 @@ void GLProgramState::setVertexAttribPointer(const std::string &name, GLint size,
// Uniform Setters // Uniform Setters
void GLProgramState::setUniformCallback(const std::string &uniformName, const std::function<void(GLProgram*, Uniform*)> &callback) void GLProgramState::setUniformCallback(const std::string& uniformName, const std::function<void(GLProgram*, Uniform*)> &callback)
{ {
auto v = getUniformValue(uniformName); auto v = getUniformValue(uniformName);
if (v) if (v)
@ -595,7 +610,7 @@ void GLProgramState::setUniformCallback(GLint uniformLocation, const std::functi
CCLOG("cocos2d: warning: Uniform at location not found: %i", uniformLocation); CCLOG("cocos2d: warning: Uniform at location not found: %i", uniformLocation);
} }
void GLProgramState::setUniformFloat(const std::string &uniformName, float value) void GLProgramState::setUniformFloat(const std::string& uniformName, float value)
{ {
auto v = getUniformValue(uniformName); auto v = getUniformValue(uniformName);
if (v) if (v)
@ -613,7 +628,7 @@ void GLProgramState::setUniformFloat(GLint uniformLocation, float value)
CCLOG("cocos2d: warning: Uniform at location not found: %i", uniformLocation); CCLOG("cocos2d: warning: Uniform at location not found: %i", uniformLocation);
} }
void GLProgramState::setUniformInt(const std::string &uniformName, int value) void GLProgramState::setUniformInt(const std::string& uniformName, int value)
{ {
auto v = getUniformValue(uniformName); auto v = getUniformValue(uniformName);
if(v) if(v)
@ -632,7 +647,7 @@ void GLProgramState::setUniformInt(GLint uniformLocation, int value)
} }
void GLProgramState::setUniformFloatv(const std::string &uniformName, ssize_t size, const float* pointer) void GLProgramState::setUniformFloatv(const std::string& uniformName, ssize_t size, const float* pointer)
{ {
auto v = getUniformValue(uniformName); auto v = getUniformValue(uniformName);
if (v) if (v)
@ -650,7 +665,7 @@ void GLProgramState::setUniformFloatv(GLint uniformLocation, ssize_t size, const
CCLOG("cocos2d: warning: Uniform at location not found: %i", uniformLocation); CCLOG("cocos2d: warning: Uniform at location not found: %i", uniformLocation);
} }
void GLProgramState::setUniformVec2(const std::string &uniformName, const Vec2& value) void GLProgramState::setUniformVec2(const std::string& uniformName, const Vec2& value)
{ {
auto v = getUniformValue(uniformName); auto v = getUniformValue(uniformName);
if (v) if (v)
@ -668,7 +683,7 @@ void GLProgramState::setUniformVec2(GLint uniformLocation, const Vec2& value)
CCLOG("cocos2d: warning: Uniform at location not found: %i", uniformLocation); CCLOG("cocos2d: warning: Uniform at location not found: %i", uniformLocation);
} }
void GLProgramState::setUniformVec2v(const std::string &uniformName, ssize_t size, const Vec2* pointer) void GLProgramState::setUniformVec2v(const std::string& uniformName, ssize_t size, const Vec2* pointer)
{ {
auto v = getUniformValue(uniformName); auto v = getUniformValue(uniformName);
if (v) if (v)
@ -686,7 +701,7 @@ void GLProgramState::setUniformVec2v(GLint uniformLocation, ssize_t size, const
CCLOG("cocos2d: warning: Uniform at location not found: %i", uniformLocation); CCLOG("cocos2d: warning: Uniform at location not found: %i", uniformLocation);
} }
void GLProgramState::setUniformVec3(const std::string &uniformName, const Vec3& value) void GLProgramState::setUniformVec3(const std::string& uniformName, const Vec3& value)
{ {
auto v = getUniformValue(uniformName); auto v = getUniformValue(uniformName);
if (v) if (v)
@ -704,7 +719,7 @@ void GLProgramState::setUniformVec3(GLint uniformLocation, const Vec3& value)
CCLOG("cocos2d: warning: Uniform at location not found: %i", uniformLocation); CCLOG("cocos2d: warning: Uniform at location not found: %i", uniformLocation);
} }
void GLProgramState::setUniformVec3v(const std::string &uniformName, ssize_t size, const Vec3* pointer) void GLProgramState::setUniformVec3v(const std::string& uniformName, ssize_t size, const Vec3* pointer)
{ {
auto v = getUniformValue(uniformName); auto v = getUniformValue(uniformName);
if (v) if (v)
@ -722,7 +737,7 @@ void GLProgramState::setUniformVec3v(GLint uniformLocation, ssize_t size, const
CCLOG("cocos2d: warning: Uniform at location not found: %i", uniformLocation); CCLOG("cocos2d: warning: Uniform at location not found: %i", uniformLocation);
} }
void GLProgramState::setUniformVec4(const std::string &uniformName, const Vec4& value) void GLProgramState::setUniformVec4(const std::string& uniformName, const Vec4& value)
{ {
auto v = getUniformValue(uniformName); auto v = getUniformValue(uniformName);
if (v) if (v)
@ -740,7 +755,7 @@ void GLProgramState::setUniformVec4(GLint uniformLocation, const Vec4& value)
CCLOG("cocos2d: warning: Uniform at location not found: %i", uniformLocation); CCLOG("cocos2d: warning: Uniform at location not found: %i", uniformLocation);
} }
void GLProgramState::setUniformVec4v(const std::string &uniformName, ssize_t size, const Vec4* value) void GLProgramState::setUniformVec4v(const std::string& uniformName, ssize_t size, const Vec4* value)
{ {
auto v = getUniformValue(uniformName); auto v = getUniformValue(uniformName);
if (v) if (v)
@ -759,7 +774,7 @@ void GLProgramState::setUniformVec4v(GLint uniformLocation, ssize_t size, const
} }
void GLProgramState::setUniformMat4(const std::string &uniformName, const Mat4& value) void GLProgramState::setUniformMat4(const std::string& uniformName, const Mat4& value)
{ {
auto v = getUniformValue(uniformName); auto v = getUniformValue(uniformName);
if (v) if (v)
@ -779,7 +794,7 @@ void GLProgramState::setUniformMat4(GLint uniformLocation, const Mat4& value)
// Textures // Textures
void GLProgramState::setUniformTexture(const std::string &uniformName, Texture2D *texture) void GLProgramState::setUniformTexture(const std::string& uniformName, Texture2D *texture)
{ {
CCASSERT(texture, "Invalid texture"); CCASSERT(texture, "Invalid texture");
setUniformTexture(uniformName, texture->getName()); setUniformTexture(uniformName, texture->getName());
@ -791,7 +806,7 @@ void GLProgramState::setUniformTexture(GLint uniformLocation, Texture2D *texture
setUniformTexture(uniformLocation, texture->getName()); setUniformTexture(uniformLocation, texture->getName());
} }
void GLProgramState::setUniformTexture(const std::string &uniformName, GLuint textureId) void GLProgramState::setUniformTexture(const std::string& uniformName, GLuint textureId)
{ {
auto v = getUniformValue(uniformName); auto v = getUniformValue(uniformName);
if (v) if (v)
@ -833,4 +848,74 @@ void GLProgramState::setUniformTexture(GLint uniformLocation, GLuint textureId)
} }
} }
// Auto bindings
void GLProgramState::setParameterAutoBinding(const std::string& uniformName, const std::string& autoBinding)
{
_autoBindings[uniformName] = autoBinding;
if (_nodeBinding)
applyAutoBinding(uniformName, autoBinding);
}
void GLProgramState::applyAutoBinding(const std::string& uniformName, const std::string& autoBinding)
{
// This code tries to replace GLProgram::setUniformsForBuiltins. But it is unfinished ATM.
// The idea is that users will be able to use variables from cocos2d-x without hardcoding the
// information on GLProgram and other objects.
// Instead, the Cocos2d uniform variables will be callbacks.
// As an example of how bad the current design is, the ModelView matrix is being passed from Node, to the Commands, to the GLProgram.
// Instead, the GLProgramState should obtain it from its target.
bool resolved = false;
for (const auto resolver: _customAutoBindingResolvers)
{
resolved = resolver->resolveAutoBinding(this, _nodeBinding, uniformName, autoBinding);
if (resolved)
break;
}
if (!resolved)
{
// add cocos2d-x variables here like:
// PROJECT_MATRIX
// MODEL_MATRIX
// MODEL_VIEW
// MODEL_VIEW_PROJECTION
// etc...
//
// and remove them from GLProgram::setUniformsForBuiltins
}
}
void GLProgramState::setNodeBinding(Node* target)
{
CCASSERT(target, "must be non-null");
// weak ref
_nodeBinding = target;
for (const auto autobinding: _autoBindings)
applyAutoBinding(autobinding.first, autobinding.second);
}
Node* GLProgramState::getNodeBinding() const
{
return _nodeBinding;
}
//
// MARK: AutoBindingResolver
//
GLProgramState::AutoBindingResolver::AutoBindingResolver()
{
_customAutoBindingResolvers.push_back(this);
}
GLProgramState::AutoBindingResolver::~AutoBindingResolver()
{
std::vector<GLProgramState::AutoBindingResolver*>::iterator itr = std::find(_customAutoBindingResolvers.begin(), _customAutoBindingResolvers.end(), this);
if (itr != _customAutoBindingResolvers.end())
_customAutoBindingResolvers.erase(itr);
}
NS_CC_END NS_CC_END

View File

@ -20,6 +20,8 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
Autobinding Interface from GamePlay3D: http://www.gameplay3d.org/
****************************************************************************/ ****************************************************************************/
#ifndef __CCGLPROGRAMSTATE_H__ #ifndef __CCGLPROGRAMSTATE_H__
@ -46,6 +48,7 @@ struct Uniform;
struct VertexAttrib; struct VertexAttrib;
class EventListenerCustom; class EventListenerCustom;
class EventCustom; class EventCustom;
class Node;
/** /**
* Uniform Value, which is used to store to value send to openGL pipe line by glUniformXXX. * Uniform Value, which is used to store to value send to openGL pipe line by glUniformXXX.
@ -246,7 +249,7 @@ public:
static GLProgramState* getOrCreateWithGLProgram(GLProgram* glprogram); static GLProgramState* getOrCreateWithGLProgram(GLProgram* glprogram);
/** gets-or-creates an instance of GLProgramState for a given GLProgramName */ /** gets-or-creates an instance of GLProgramState for a given GLProgramName */
static GLProgramState* getOrCreateWithGLProgramName(const std::string &glProgramName ); static GLProgramState* getOrCreateWithGLProgramName(const std::string& glProgramName );
/** gets-or-creates an instance of GLProgramState for given shaders */ /** gets-or-creates an instance of GLProgramState for given shaders */
static GLProgramState* getOrCreateWithShaders(const std::string& vertexShader, const std::string& fragShader, const std::string& compileTimeDefines); static GLProgramState* getOrCreateWithShaders(const std::string& vertexShader, const std::string& fragShader, const std::string& compileTimeDefines);
@ -289,8 +292,8 @@ public:
/**@{ /**@{
Set the vertex attribute value. Set the vertex attribute value.
*/ */
void setVertexAttribCallback(const std::string &name, const std::function<void(VertexAttrib*)> &callback); void setVertexAttribCallback(const std::string& name, const std::function<void(VertexAttrib*)> &callback);
void setVertexAttribPointer(const std::string &name, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLvoid *pointer); void setVertexAttribPointer(const std::string& name, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLvoid *pointer);
/**@}*/ /**@}*/
/**Get the number of user defined uniform count.*/ /**Get the number of user defined uniform count.*/
@ -299,19 +302,19 @@ public:
/** @{ /** @{
Setting user defined uniforms by uniform string name in the shader. Setting user defined uniforms by uniform string name in the shader.
*/ */
void setUniformInt(const std::string &uniformName, int value); void setUniformInt(const std::string& uniformName, int value);
void setUniformFloat(const std::string &uniformName, float value); void setUniformFloat(const std::string& uniformName, float value);
void setUniformFloatv(const std::string &uniformName, ssize_t size, const float* pointer); void setUniformFloatv(const std::string& uniformName, ssize_t size, const float* pointer);
void setUniformVec2(const std::string &uniformName, const Vec2& value); void setUniformVec2(const std::string& uniformName, const Vec2& value);
void setUniformVec2v(const std::string &uniformName, ssize_t size, const Vec2* pointer); void setUniformVec2v(const std::string& uniformName, ssize_t size, const Vec2* pointer);
void setUniformVec3(const std::string &uniformName, const Vec3& value); void setUniformVec3(const std::string& uniformName, const Vec3& value);
void setUniformVec3v(const std::string &uniformName, ssize_t size, const Vec3* pointer); void setUniformVec3v(const std::string& uniformName, ssize_t size, const Vec3* pointer);
void setUniformVec4(const std::string &uniformName, const Vec4& value); void setUniformVec4(const std::string& uniformName, const Vec4& value);
void setUniformVec4v(const std::string &uniformName, ssize_t size, const Vec4* pointer); void setUniformVec4v(const std::string& uniformName, ssize_t size, const Vec4* pointer);
void setUniformMat4(const std::string &uniformName, const Mat4& value); void setUniformMat4(const std::string& uniformName, const Mat4& value);
void setUniformCallback(const std::string &uniformName, const std::function<void(GLProgram*, Uniform*)> &callback); void setUniformCallback(const std::string& uniformName, const std::function<void(GLProgram*, Uniform*)> &callback);
void setUniformTexture(const std::string &uniformName, Texture2D *texture); void setUniformTexture(const std::string& uniformName, Texture2D *texture);
void setUniformTexture(const std::string &uniformName, GLuint textureId); void setUniformTexture(const std::string& uniformName, GLuint textureId);
/**@}*/ /**@}*/
/** @{ /** @{
@ -331,17 +334,118 @@ public:
void setUniformTexture(GLint uniformLocation, Texture2D *texture); void setUniformTexture(GLint uniformLocation, Texture2D *texture);
void setUniformTexture(GLint uniformLocation, GLuint textureId); void setUniformTexture(GLint uniformLocation, GLuint textureId);
/**@}*/ /**@}*/
/**
* Returns the Node bound to the GLProgramState
*/
Node* getNodeBinding() const;
/**
* Sets the node that this render state is bound to.
*
* The specified node is used to apply auto-bindings for the render state.
* This is typically set to the node of the model that a material is
* applied to.
*
* @param node The node to use for applying auto-bindings.
*/
void setNodeBinding(Node* node);
/**
* Applies the specified custom auto-binding.
*
* @param uniformName Name of the shader uniform.
* @param autoBinding Name of the auto binding.
*/
void applyAutoBinding(const std::string& uniformName, const std::string& autoBinding);
/**
* Sets a uniform auto-binding.
*
* This method parses the passed in autoBinding string and attempts to convert it
* to an enumeration value. If it matches to one of the predefined strings, it will create a
* callback to get the correct value at runtime.
*
* @param name The name of the material parameter to store an auto-binding for.
* @param autoBinding A string matching one of the built-in AutoBinding enum constants.
*/
void setParameterAutoBinding(const std::string& uniformName, const std::string& autoBinding);
/**
* An abstract base class that can be extended to support custom material auto bindings.
*
* Implementing a custom auto binding resolver allows the set of built-in parameter auto
* bindings to be extended or overridden. Any parameter auto binding that is set on a
* material will be forwarded to any custom auto binding resolvers, in the order in which
* they are registered. If a registered resolver returns true (specifying that it handles
* the specified autoBinding), no further code will be executed for that autoBinding.
* This allows auto binding resolvers to not only implement new/custom binding strings,
* but it also lets them override existing/built-in ones. For this reason, you should
* ensure that you ONLY return true if you explicitly handle a custom auto binding; return
* false otherwise.
*
* Note that the custom resolver is called only once for a GLProgramState object when its
* node binding is initially set. This occurs when a material is initially bound to a
* Node. The resolver is NOT called each frame or each time the GLProgramState is bound.
*
* If no registered resolvers explicitly handle an auto binding, the binding will attempt
* to be resolved using the internal/built-in resolver, which is able to handle any
* auto bindings found in the GLProgramState::AutoBinding enumeration.
*
* When an instance of a class that extends AutoBindingResolver is created, it is automatically
* registered as a custom auto binding handler. Likewise, it is automatically deregistered
* on destruction.
*
* @script{ignore}
*/
class CC_DLL AutoBindingResolver
{
public:
/**
* Destructor.
*/
virtual ~AutoBindingResolver();
/**
* Called when an unrecognized uniform variable is encountered
* during material loading.
*
* Implemenations of this method should do a string comparison on the passed
* in name parameter and decide whether or not they should handle the
* parameter. If the parameter is not handled, false should be returned so
* that other auto binding resolvers get a chance to handle the parameter.
* Otherwise, the parameter should be set or bound and true should be returned.
*
* @param glProgramState The glProgramState
* @param node The node that the material is attached to.
* @param uniformName Name of the uniform
* @param autoBinding Name of the auto binding to be resolved.
*
* @return True if the auto binding is handled and the associated parmeter is
* bound, false otherwise.
*/
virtual bool resolveAutoBinding(GLProgramState* glProgramState, Node* node, const std::string& uniformName, const std::string& autoBinding) = 0;
protected:
/**
* Constructor.
*/
AutoBindingResolver();
};
protected: protected:
GLProgramState(); GLProgramState();
~GLProgramState(); ~GLProgramState();
bool init(GLProgram* program); bool init(GLProgram* program);
void resetGLProgram(); void resetGLProgram();
void updateUniformsAndAttributes(); void updateUniformsAndAttributes();
VertexAttribValue* getVertexAttribValue(const std::string &attributeName); VertexAttribValue* getVertexAttribValue(const std::string& attributeName);
UniformValue* getUniformValue(const std::string &uniformName); UniformValue* getUniformValue(const std::string& uniformName);
UniformValue* getUniformValue(GLint uniformLocation); UniformValue* getUniformValue(GLint uniformLocation);
bool _uniformAttributeValueDirty; bool _uniformAttributeValueDirty;
std::unordered_map<std::string, GLint> _uniformsByName; std::unordered_map<std::string, GLint> _uniformsByName;
std::unordered_map<GLint, UniformValue> _uniforms; std::unordered_map<GLint, UniformValue> _uniforms;
@ -350,11 +454,20 @@ protected:
int _textureUnitIndex; int _textureUnitIndex;
uint32_t _vertexAttribsFlags; uint32_t _vertexAttribsFlags;
GLProgram *_glprogram; GLProgram* _glprogram;
Node* _nodeBinding; // weak ref
// contains uniform name and variable
std::unordered_map<std::string, std::string> _autoBindings;
// Map of custom auto binding resolvers.
static std::vector<AutoBindingResolver*> _customAutoBindingResolvers;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
EventListenerCustom* _backToForegroundlistener; EventListenerCustom* _backToForegroundlistener;
#endif #endif
}; };
NS_CC_END NS_CC_END

View File

@ -198,9 +198,7 @@ bool Material::parsePass(Technique* technique, Properties* passProperties)
while (space) while (space)
{ {
const char* name = space->getNamespace(); const char* name = space->getNamespace();
if (strcmp(name, "sampler") == 0) if (strcmp(name, "shader") == 0)
parseSampler(pass, space);
else if (strcmp(name, "shader") == 0)
parseShader(pass, space); parseShader(pass, space);
else if (strcmp(name, "renderState") == 0) else if (strcmp(name, "renderState") == 0)
parseRenderState(pass, space); parseRenderState(pass, space);
@ -216,10 +214,12 @@ bool Material::parsePass(Technique* technique, Properties* passProperties)
} }
// cocos2d-x doesn't support Samplers yet. But will be added soon // cocos2d-x doesn't support Samplers yet. But will be added soon
bool Material::parseSampler(Pass* pass, Properties* textureProperties) bool Material::parseSampler(GLProgramState* glProgramState, Properties* samplerProperties)
{ {
CCASSERT(samplerProperties->getId(), "Sampler must have an id. The id is the uniform name");
// required // required
auto filename = textureProperties->getString("path"); auto filename = samplerProperties->getString("path");
auto texture = Director::getInstance()->getTextureCache()->addImage(filename); auto texture = Director::getInstance()->getTextureCache()->addImage(filename);
if (!texture) { if (!texture) {
@ -234,14 +234,14 @@ bool Material::parseSampler(Pass* pass, Properties* textureProperties)
// mipmap // mipmap
bool usemipmap = false; bool usemipmap = false;
const char* mipmap = getOptionalString(textureProperties, "mipmap", "false"); const char* mipmap = getOptionalString(samplerProperties, "mipmap", "false");
if (mipmap && strcasecmp(mipmap, "true")==0) { if (mipmap && strcasecmp(mipmap, "true")==0) {
texture->generateMipmap(); texture->generateMipmap();
usemipmap = true; usemipmap = true;
} }
// valid options: REPEAT, CLAMP // valid options: REPEAT, CLAMP
const char* wrapS = getOptionalString(textureProperties, "wrapS", "CLAMP_TO_EDGE"); const char* wrapS = getOptionalString(samplerProperties, "wrapS", "CLAMP_TO_EDGE");
if (strcasecmp(wrapS, "REPEAT")==0) if (strcasecmp(wrapS, "REPEAT")==0)
texParams.wrapS = GL_REPEAT; texParams.wrapS = GL_REPEAT;
else if(strcasecmp(wrapS, "CLAMP_TO_EDGE")==0) else if(strcasecmp(wrapS, "CLAMP_TO_EDGE")==0)
@ -251,7 +251,7 @@ bool Material::parseSampler(Pass* pass, Properties* textureProperties)
// valid options: REPEAT, CLAMP // valid options: REPEAT, CLAMP
const char* wrapT = getOptionalString(textureProperties, "wrapT", "CLAMP_TO_EDGE"); const char* wrapT = getOptionalString(samplerProperties, "wrapT", "CLAMP_TO_EDGE");
if (strcasecmp(wrapT, "REPEAT")==0) if (strcasecmp(wrapT, "REPEAT")==0)
texParams.wrapT = GL_REPEAT; texParams.wrapT = GL_REPEAT;
else if(strcasecmp(wrapT, "CLAMP_TO_EDGE")==0) else if(strcasecmp(wrapT, "CLAMP_TO_EDGE")==0)
@ -261,7 +261,7 @@ bool Material::parseSampler(Pass* pass, Properties* textureProperties)
// valid options: NEAREST, LINEAR, NEAREST_MIPMAP_NEAREST, LINEAR_MIPMAP_NEAREST, NEAREST_MIPMAP_LINEAR, LINEAR_MIPMAP_LINEAR // valid options: NEAREST, LINEAR, NEAREST_MIPMAP_NEAREST, LINEAR_MIPMAP_NEAREST, NEAREST_MIPMAP_LINEAR, LINEAR_MIPMAP_LINEAR
const char* minFilter = getOptionalString(textureProperties, "minFilter", usemipmap ? "LINEAR_MIPMAP_NEAREST" : "LINEAR"); const char* minFilter = getOptionalString(samplerProperties, "minFilter", usemipmap ? "LINEAR_MIPMAP_NEAREST" : "LINEAR");
if (strcasecmp(minFilter, "NEAREST")==0) if (strcasecmp(minFilter, "NEAREST")==0)
texParams.minFilter = GL_NEAREST; texParams.minFilter = GL_NEAREST;
else if(strcasecmp(minFilter, "LINEAR")==0) else if(strcasecmp(minFilter, "LINEAR")==0)
@ -278,7 +278,7 @@ bool Material::parseSampler(Pass* pass, Properties* textureProperties)
CCLOG("Invalid minFilter: %s", minFilter); CCLOG("Invalid minFilter: %s", minFilter);
// valid options: NEAREST, LINEAR // valid options: NEAREST, LINEAR
const char* magFilter = getOptionalString(textureProperties, "magFilter", "LINEAR"); const char* magFilter = getOptionalString(samplerProperties, "magFilter", "LINEAR");
if (strcasecmp(magFilter, "NEAREST")==0) if (strcasecmp(magFilter, "NEAREST")==0)
texParams.magFilter = GL_NEAREST; texParams.magFilter = GL_NEAREST;
else if(strcasecmp(magFilter, "LINEAR")==0) else if(strcasecmp(magFilter, "LINEAR")==0)
@ -289,7 +289,7 @@ bool Material::parseSampler(Pass* pass, Properties* textureProperties)
texture->setTexParameters(texParams); texture->setTexParameters(texParams);
} }
pass->_textures.pushBack(texture); glProgramState->setUniformTexture(samplerProperties->getId(), texture);
return true; return true;
} }
@ -321,7 +321,16 @@ bool Material::parseShader(Pass* pass, Properties* shaderProperties)
property = shaderProperties->getNextProperty(); property = shaderProperties->getNextProperty();
} }
// glProgramState->updateUniformsAndAttributes(); auto space = shaderProperties->getNextNamespace();
while (space)
{
const char* name = space->getNamespace();
if (strcmp(name, "sampler") == 0)
{
parseSampler(glProgramState, space);
}
space = shaderProperties->getNextNamespace();
}
} }
return true; return true;
@ -329,6 +338,8 @@ bool Material::parseShader(Pass* pass, Properties* shaderProperties)
bool Material::parseUniform(GLProgramState* programState, Properties* properties, const char* uniformName) bool Material::parseUniform(GLProgramState* programState, Properties* properties, const char* uniformName)
{ {
bool ret = true;
auto type = properties->getType(uniformName); auto type = properties->getType(uniformName);
switch (type) { switch (type) {
@ -339,11 +350,6 @@ bool Material::parseUniform(GLProgramState* programState, Properties* properties
break; break;
} }
case Properties::Type::STRING:
CCASSERT(false, "invalid type for a uniform");
return false;
break;
case Properties::Type::VECTOR2: case Properties::Type::VECTOR2:
{ {
Vec2 v2; Vec2 v2;
@ -376,11 +382,15 @@ bool Material::parseUniform(GLProgramState* programState, Properties* properties
break; break;
} }
case Properties::Type::STRING:
default: default:
return false; {
// Assume this is a parameter auto-binding.
programState->setParameterAutoBinding(uniformName, properties->getString());
break; break;
}
} }
return true; return ret;
} }

View File

@ -133,8 +133,8 @@ protected:
bool parseProperties(Properties* properties); bool parseProperties(Properties* properties);
bool parseTechnique(Properties* properties); bool parseTechnique(Properties* properties);
bool parsePass(Technique* technique, Properties* properties); bool parsePass(Technique* technique, Properties* properties);
bool parseSampler(Pass* pass, Properties* properties);
bool parseShader(Pass* pass, Properties* properties); bool parseShader(Pass* pass, Properties* properties);
bool parseSampler(GLProgramState* glProgramState, Properties* properties);
bool parseUniform(GLProgramState* programState, Properties* properties, const char* uniformName); bool parseUniform(GLProgramState* programState, Properties* properties, const char* uniformName);
bool parseRenderState(RenderState* renderState, Properties* properties); bool parseRenderState(RenderState* renderState, Properties* properties);

View File

@ -129,7 +129,7 @@ uint32_t Pass::getHash() const
{ {
if (_hashDirty || _state->isDirty()) { if (_hashDirty || _state->isDirty()) {
uint32_t glProgram = (uint32_t)_glProgramState->getGLProgram()->getProgram(); uint32_t glProgram = (uint32_t)_glProgramState->getGLProgram()->getProgram();
uint32_t textureid = (uint32_t)_textures.at(0)->getName(); uint32_t textureid = _texture ? _texture->getName() : -1;
uint32_t stateblockid = _state->getHash(); uint32_t stateblockid = _state->getHash();
_hash = glProgram ^ textureid ^ stateblockid; _hash = glProgram ^ textureid ^ stateblockid;

View File

@ -58,7 +58,7 @@ enum
RenderState::RenderState() RenderState::RenderState()
: _textures() : _texture(nullptr)
, _hash(0) , _hash(0)
, _hashDirty(true) , _hashDirty(true)
, _parent(nullptr) , _parent(nullptr)
@ -102,32 +102,27 @@ std::string RenderState::getName() const
} }
const Vector<Texture2D*>& RenderState::getTextures() const
{
return _textures;
}
void RenderState::setTexture(Texture2D* texture) void RenderState::setTexture(Texture2D* texture)
{ {
if (_textures.size() > 0) if (_texture != texture)
_textures.replace(0, texture); {
else CC_SAFE_RELEASE(_texture);
_textures.pushBack(texture); _texture = texture;
CC_SAFE_RETAIN(_texture);
}
} }
Texture2D* RenderState::getTexture() const Texture2D* RenderState::getTexture() const
{ {
if (_textures.size() > 0) return _texture;
return _textures.at(0);
return nullptr;
} }
void RenderState::bind(Pass* pass) void RenderState::bind(Pass* pass)
{ {
CC_ASSERT(pass); CC_ASSERT(pass);
if (_textures.size() > 0) if (_texture)
GL::bindTexture2D(_textures.at(0)->getName()); GL::bindTexture2D(_texture->getName());
// Get the combined modified state bits for our RenderState hierarchy. // Get the combined modified state bits for our RenderState hierarchy.
long stateOverrideBits = _state ? _state->_bits : 0; long stateOverrideBits = _state ? _state->_bits : 0;
@ -193,7 +188,8 @@ void RenderState::cloneInto(RenderState* renderState) const
} }
renderState->_name = _name; renderState->_name = _name;
renderState->_textures = _textures; renderState->_texture = _texture;
CC_SAFE_RETAIN(renderState->_texture);
// weak ref. don't retain // weak ref. don't retain
renderState->_parent = _parent; renderState->_parent = _parent;
} }

View File

@ -31,7 +31,6 @@
#include <functional> #include <functional>
#include <cstdint> #include <cstdint>
#include "renderer/CCTexture2D.h"
#include "platform/CCPlatformMacros.h" #include "platform/CCPlatformMacros.h"
#include "base/CCRef.h" #include "base/CCRef.h"
#include "base/ccTypes.h" #include "base/ccTypes.h"
@ -65,14 +64,12 @@ public:
std::string getName() const; std::string getName() const;
const Vector<Texture2D*>& getTextures() const; /** Texture that will use in the CC_Texture0 uniform.
Added to be backwards compatible. Use Samplers from .material instead.
/** Replaces the texture that is at the front of _textures array.
Added to be backwards compatible.
*/ */
void setTexture(Texture2D* texture); void setTexture(Texture2D* texture);
/** Returns the texture that is at the front of the _textures array. /** Returns the texture that is going to be used for CC_Texture0.
Added to be backwards compatible. Added to be backwards compatible.
*/ */
Texture2D* getTexture() const; Texture2D* getTexture() const;
@ -413,7 +410,7 @@ protected:
// name, for filtering // name, for filtering
std::string _name; std::string _name;
Vector<Texture2D*> _textures; Texture2D* _texture;
}; };
NS_CC_END NS_CC_END

View File

@ -17,7 +17,7 @@ void main()
vec4 sample = texture2D(CC_Texture0, v_texCoord); vec4 sample = texture2D(CC_Texture0, v_texCoord);
float fontAlpha = sample.a; float fontAlpha = sample.a;
float outlineAlpha = sample.r; float outlineAlpha = sample.r;
if (outlineAlpha > 0.0){ if ((fontAlpha + outlineAlpha) > 0.0){
vec4 color = u_textColor * fontAlpha + u_effectColor * (1.0 - fontAlpha); vec4 color = u_textColor * fontAlpha + u_effectColor * (1.0 - fontAlpha);
gl_FragColor = v_fragmentColor * vec4( color.rgb,max(fontAlpha,outlineAlpha)*color.a); gl_FragColor = v_fragmentColor * vec4( color.rgb,max(fontAlpha,outlineAlpha)*color.a);
} }

View File

@ -1405,14 +1405,16 @@ getTerrainSize : function (
/** /**
* @method getIntersectionPoint * @method getIntersectionPoint
* @param {cc.Ray} arg0 * @param {cc.Ray|cc.Ray} ray
* @return {vec3_object} * @param {vec3_object} vec3
*/ * @return {bool|vec3_object}
getIntersectionPoint : function ( */
ray getIntersectionPoint : function(
ray,
vec3
) )
{ {
return cc.Vec3; return false;
}, },
/** /**

View File

@ -10497,6 +10497,18 @@ getVertexAttribsFlags : function (
return 0; return 0;
}, },
/**
* @method applyAutoBinding
* @param {String} arg0
* @param {String} arg1
*/
applyAutoBinding : function (
str,
str
)
{
},
/** /**
* @method setUniformVec2 * @method setUniformVec2
* @param {int|String} int * @param {int|String} int
@ -10543,6 +10555,16 @@ mat4
{ {
}, },
/**
* @method getNodeBinding
* @return {cc.Node}
*/
getNodeBinding : function (
)
{
return cc.Node;
},
/** /**
* @method applyGLProgram * @method applyGLProgram
* @param {mat4_object} arg0 * @param {mat4_object} arg0
@ -10553,6 +10575,16 @@ mat4
{ {
}, },
/**
* @method setNodeBinding
* @param {cc.Node} arg0
*/
setNodeBinding : function (
node
)
{
},
/** /**
* @method setUniformInt * @method setUniformInt
* @param {int|String} int * @param {int|String} int
@ -10565,6 +10597,18 @@ int
{ {
}, },
/**
* @method setParameterAutoBinding
* @param {String} arg0
* @param {String} arg1
*/
setParameterAutoBinding : function (
str,
str
)
{
},
/** /**
* @method setUniformVec2v * @method setUniformVec2v
* @param {int|String} int * @param {int|String} int
@ -19871,16 +19915,6 @@ getStateBlock : function (
return cc.RenderState::StateBlock; return cc.RenderState::StateBlock;
}, },
/**
* @method getTextures
* @return {Array}
*/
getTextures : function (
)
{
return new Array();
},
/** /**
* @method initialize * @method initialize
*/ */
@ -22169,16 +22203,6 @@ isEnabled : function (
return false; return false;
}, },
/**
* @method update
* @param {float} arg0
*/
update : function (
float
)
{
},
/** /**
* @method getOwner * @method getOwner
* @return {cc.Node} * @return {cc.Node}
@ -22199,16 +22223,6 @@ init : function (
return false; return false;
}, },
/**
* @method setOwner
* @param {cc.Node} arg0
*/
setOwner : function (
node
)
{
},
/** /**
* @method getName * @method getName
* @return {String} * @return {String}
@ -22219,6 +22233,16 @@ getName : function (
return ; return ;
}, },
/**
* @method setOwner
* @param {cc.Node} arg0
*/
setOwner : function (
node
)
{
},
/** /**
* @method create * @method create
* @return {cc.Component} * @return {cc.Component}

View File

@ -0,0 +1,172 @@
/**
* @module cocos2dx_experimental_video
*/
var ccui = ccui || {};
/**
* @class VideoPlayer
*/
ccui.VideoPlayer = {
/**
* @method getFileName
* @return {String}
*/
getFileName : function (
)
{
return ;
},
/**
* @method getURL
* @return {String}
*/
getURL : function (
)
{
return ;
},
/**
* @method play
*/
play : function (
)
{
},
/**
* @method pause
*/
pause : function (
)
{
},
/**
* @method setKeepAspectRatioEnabled
* @param {bool} arg0
*/
setKeepAspectRatioEnabled : function (
bool
)
{
},
/**
* @method resume
*/
resume : function (
)
{
},
/**
* @method stop
*/
stop : function (
)
{
},
/**
* @method setFullScreenEnabled
* @param {bool} arg0
*/
setFullScreenEnabled : function (
bool
)
{
},
/**
* @method setFileName
* @param {String} arg0
*/
setFileName : function (
str
)
{
},
/**
* @method setURL
* @param {String} arg0
*/
setURL : function (
str
)
{
},
/**
* @method isKeepAspectRatioEnabled
* @return {bool}
*/
isKeepAspectRatioEnabled : function (
)
{
return false;
},
/**
* @method onPlayEvent
* @param {int} arg0
*/
onPlayEvent : function (
int
)
{
},
/**
* @method isFullScreenEnabled
* @return {bool}
*/
isFullScreenEnabled : function (
)
{
return false;
},
/**
* @method isPlaying
* @return {bool}
*/
isPlaying : function (
)
{
return false;
},
/**
* @method seekTo
* @param {float} arg0
*/
seekTo : function (
float
)
{
},
/**
* @method create
* @return {cc.experimental::ui::VideoPlayer}
*/
create : function (
)
{
return cc.experimental::ui::VideoPlayer;
},
/**
* @method VideoPlayer
* @constructor
*/
VideoPlayer : function (
)
{
},
};

View File

@ -726,6 +726,14 @@ Physics3DRigidBody : function (
*/ */
cc.Physics3DComponent = { cc.Physics3DComponent = {
/**
* @method syncNodeToPhysics
*/
syncNodeToPhysics : function (
)
{
},
/** /**
* @method addToPhysicsWorld * @method addToPhysicsWorld
* @param {cc.Physics3DWorld} arg0 * @param {cc.Physics3DWorld} arg0
@ -737,17 +745,9 @@ physics3dworld
}, },
/** /**
* @method syncToPhysics * @method syncPhysicsToNode
*/ */
syncToPhysics : function ( syncPhysicsToNode : function (
)
{
},
/**
* @method syncToNode
*/
syncToNode : function (
) )
{ {
}, },
@ -837,17 +837,17 @@ Physics3DComponent : function (
cc.PhysicsSprite3D = { cc.PhysicsSprite3D = {
/** /**
* @method syncToPhysics * @method syncNodeToPhysics
*/ */
syncToPhysics : function ( syncNodeToPhysics : function (
) )
{ {
}, },
/** /**
* @method syncToNode * @method syncPhysicsToNode
*/ */
syncToNode : function ( syncPhysicsToNode : function (
) )
{ {
}, },
@ -888,6 +888,16 @@ PhysicsSprite3D : function (
*/ */
cc.Physics3DWorld = { cc.Physics3DWorld = {
/**
* @method setGravity
* @param {vec3_object} arg0
*/
setGravity : function (
vec3
)
{
},
/** /**
* @method stepSimulate * @method stepSimulate
* @param {float} arg0 * @param {float} arg0
@ -929,11 +939,9 @@ physics3dworlddes
}, },
/** /**
* @method removePhysics3DConstraint * @method removeAllPhysics3DObjects
* @param {cc.Physics3DConstraint} arg0
*/ */
removePhysics3DConstraint : function ( removeAllPhysics3DObjects : function (
physics3dconstraint
) )
{ {
}, },
@ -973,9 +981,21 @@ hitresult
}, },
/** /**
* @method removeAllPhysics3DObjects * @method getGravity
* @return {vec3_object}
*/ */
removeAllPhysics3DObjects : function ( getGravity : function (
)
{
return cc.Vec3;
},
/**
* @method removePhysics3DConstraint
* @param {cc.Physics3DConstraint} arg0
*/
removePhysics3DConstraint : function (
physics3dconstraint
) )
{ {
}, },

View File

@ -4022,22 +4022,43 @@ bool js_cocos2dx_3d_Terrain_getIntersectionPoint(JSContext *cx, uint32_t argc, j
{ {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true; bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::Terrain* cobj = (cocos2d::Terrain *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_3d_Terrain_getIntersectionPoint : Invalid Native Object");
if (argc == 1) {
cocos2d::Ray arg0;
ok &= jsval_to_ray(cx, args.get(0), &arg0);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_3d_Terrain_getIntersectionPoint : Error processing arguments");
cocos2d::Vec3 ret = cobj->getIntersectionPoint(arg0);
jsval jsret = JSVAL_NULL;
jsret = vector3_to_jsval(cx, ret);
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_3d_Terrain_getIntersectionPoint : wrong number of arguments: %d, was expecting %d", argc, 1); JS::RootedObject obj(cx);
cocos2d::Terrain* cobj = NULL;
obj = args.thisv().toObjectOrNull();
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cobj = (cocos2d::Terrain *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_3d_Terrain_getIntersectionPoint : Invalid Native Object");
do {
if (argc == 2) {
cocos2d::Ray arg0;
ok &= jsval_to_ray(cx, args.get(0), &arg0);
if (!ok) { ok = true; break; }
cocos2d::Vec3 arg1;
ok &= jsval_to_vector3(cx, args.get(1), &arg1);
if (!ok) { ok = true; break; }
bool ret = cobj->getIntersectionPoint(arg0, arg1);
jsval jsret = JSVAL_NULL;
jsret = BOOLEAN_TO_JSVAL(ret);
args.rval().set(jsret);
return true;
}
} while(0);
do {
if (argc == 1) {
cocos2d::Ray arg0;
ok &= jsval_to_ray(cx, args.get(0), &arg0);
if (!ok) { ok = true; break; }
cocos2d::Vec3 ret = cobj->getIntersectionPoint(arg0);
jsval jsret = JSVAL_NULL;
jsret = vector3_to_jsval(cx, ret);
args.rval().set(jsret);
return true;
}
} while(0);
JS_ReportError(cx, "js_cocos2dx_3d_Terrain_getIntersectionPoint : wrong number of arguments");
return false; return false;
} }
bool js_cocos2dx_3d_Terrain_getNormal(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_3d_Terrain_getNormal(JSContext *cx, uint32_t argc, jsval *vp)

View File

@ -32979,6 +32979,28 @@ bool js_cocos2dx_GLProgramState_getVertexAttribsFlags(JSContext *cx, uint32_t ar
JS_ReportError(cx, "js_cocos2dx_GLProgramState_getVertexAttribsFlags : wrong number of arguments: %d, was expecting %d", argc, 0); JS_ReportError(cx, "js_cocos2dx_GLProgramState_getVertexAttribsFlags : wrong number of arguments: %d, was expecting %d", argc, 0);
return false; return false;
} }
bool js_cocos2dx_GLProgramState_applyAutoBinding(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::GLProgramState* cobj = (cocos2d::GLProgramState *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_GLProgramState_applyAutoBinding : Invalid Native Object");
if (argc == 2) {
std::string arg0;
std::string arg1;
ok &= jsval_to_std_string(cx, args.get(0), &arg0);
ok &= jsval_to_std_string(cx, args.get(1), &arg1);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_GLProgramState_applyAutoBinding : Error processing arguments");
cobj->applyAutoBinding(arg0, arg1);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_GLProgramState_applyAutoBinding : wrong number of arguments: %d, was expecting %d", argc, 2);
return false;
}
bool js_cocos2dx_GLProgramState_setUniformVec2(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_GLProgramState_setUniformVec2(JSContext *cx, uint32_t argc, jsval *vp)
{ {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@ -33133,6 +33155,31 @@ bool js_cocos2dx_GLProgramState_apply(JSContext *cx, uint32_t argc, jsval *vp)
JS_ReportError(cx, "js_cocos2dx_GLProgramState_apply : wrong number of arguments: %d, was expecting %d", argc, 1); JS_ReportError(cx, "js_cocos2dx_GLProgramState_apply : wrong number of arguments: %d, was expecting %d", argc, 1);
return false; return false;
} }
bool js_cocos2dx_GLProgramState_getNodeBinding(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::GLProgramState* cobj = (cocos2d::GLProgramState *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_GLProgramState_getNodeBinding : Invalid Native Object");
if (argc == 0) {
cocos2d::Node* ret = cobj->getNodeBinding();
jsval jsret = JSVAL_NULL;
do {
if (ret) {
js_proxy_t *jsProxy = js_get_or_create_proxy<cocos2d::Node>(cx, (cocos2d::Node*)ret);
jsret = OBJECT_TO_JSVAL(jsProxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_GLProgramState_getNodeBinding : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_GLProgramState_applyGLProgram(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_GLProgramState_applyGLProgram(JSContext *cx, uint32_t argc, jsval *vp)
{ {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@ -33153,6 +33200,34 @@ bool js_cocos2dx_GLProgramState_applyGLProgram(JSContext *cx, uint32_t argc, jsv
JS_ReportError(cx, "js_cocos2dx_GLProgramState_applyGLProgram : wrong number of arguments: %d, was expecting %d", argc, 1); JS_ReportError(cx, "js_cocos2dx_GLProgramState_applyGLProgram : wrong number of arguments: %d, was expecting %d", argc, 1);
return false; return false;
} }
bool js_cocos2dx_GLProgramState_setNodeBinding(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::GLProgramState* cobj = (cocos2d::GLProgramState *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_GLProgramState_setNodeBinding : Invalid Native Object");
if (argc == 1) {
cocos2d::Node* arg0;
do {
if (args.get(0).isNull()) { arg0 = nullptr; break; }
if (!args.get(0).isObject()) { ok = false; break; }
js_proxy_t *jsProxy;
JSObject *tmpObj = args.get(0).toObjectOrNull();
jsProxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocos2d::Node*)(jsProxy ? jsProxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, false, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_GLProgramState_setNodeBinding : Error processing arguments");
cobj->setNodeBinding(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_GLProgramState_setNodeBinding : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_GLProgramState_setUniformInt(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_GLProgramState_setUniformInt(JSContext *cx, uint32_t argc, jsval *vp)
{ {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@ -33195,6 +33270,28 @@ bool js_cocos2dx_GLProgramState_setUniformInt(JSContext *cx, uint32_t argc, jsva
JS_ReportError(cx, "js_cocos2dx_GLProgramState_setUniformInt : wrong number of arguments"); JS_ReportError(cx, "js_cocos2dx_GLProgramState_setUniformInt : wrong number of arguments");
return false; return false;
} }
bool js_cocos2dx_GLProgramState_setParameterAutoBinding(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::GLProgramState* cobj = (cocos2d::GLProgramState *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_GLProgramState_setParameterAutoBinding : Invalid Native Object");
if (argc == 2) {
std::string arg0;
std::string arg1;
ok &= jsval_to_std_string(cx, args.get(0), &arg0);
ok &= jsval_to_std_string(cx, args.get(1), &arg1);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_GLProgramState_setParameterAutoBinding : Error processing arguments");
cobj->setParameterAutoBinding(arg0, arg1);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_GLProgramState_setParameterAutoBinding : wrong number of arguments: %d, was expecting %d", argc, 2);
return false;
}
bool js_cocos2dx_GLProgramState_setUniformVec2v(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_GLProgramState_setUniformVec2v(JSContext *cx, uint32_t argc, jsval *vp)
{ {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@ -33845,12 +33942,16 @@ void js_register_cocos2dx_GLProgramState(JSContext *cx, JS::HandleObject global)
static JSFunctionSpec funcs[] = { static JSFunctionSpec funcs[] = {
JS_FN("setUniformCallback", js_cocos2dx_GLProgramState_setUniformCallback, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setUniformCallback", js_cocos2dx_GLProgramState_setUniformCallback, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getVertexAttribsFlags", js_cocos2dx_GLProgramState_getVertexAttribsFlags, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("getVertexAttribsFlags", js_cocos2dx_GLProgramState_getVertexAttribsFlags, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("applyAutoBinding", js_cocos2dx_GLProgramState_applyAutoBinding, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setUniformVec2", js_cocos2dx_GLProgramState_setUniformVec2, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setUniformVec2", js_cocos2dx_GLProgramState_setUniformVec2, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setUniformVec3", js_cocos2dx_GLProgramState_setUniformVec3, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setUniformVec3", js_cocos2dx_GLProgramState_setUniformVec3, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setVertexAttribCallback", js_cocos2dx_GLProgramState_setVertexAttribCallback, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setVertexAttribCallback", js_cocos2dx_GLProgramState_setVertexAttribCallback, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("apply", js_cocos2dx_GLProgramState_apply, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("apply", js_cocos2dx_GLProgramState_apply, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getNodeBinding", js_cocos2dx_GLProgramState_getNodeBinding, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("applyGLProgram", js_cocos2dx_GLProgramState_applyGLProgram, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("applyGLProgram", js_cocos2dx_GLProgramState_applyGLProgram, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setNodeBinding", js_cocos2dx_GLProgramState_setNodeBinding, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setUniformInt", js_cocos2dx_GLProgramState_setUniformInt, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setUniformInt", js_cocos2dx_GLProgramState_setUniformInt, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setParameterAutoBinding", js_cocos2dx_GLProgramState_setParameterAutoBinding, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setUniformVec2v", js_cocos2dx_GLProgramState_setUniformVec2v, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setUniformVec2v", js_cocos2dx_GLProgramState_setUniformVec2v, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getUniformCount", js_cocos2dx_GLProgramState_getUniformCount, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("getUniformCount", js_cocos2dx_GLProgramState_getUniformCount, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("applyAttributes", js_cocos2dx_GLProgramState_applyAttributes, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("applyAttributes", js_cocos2dx_GLProgramState_applyAttributes, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
@ -61341,24 +61442,6 @@ bool js_cocos2dx_RenderState_getStateBlock(JSContext *cx, uint32_t argc, jsval *
JS_ReportError(cx, "js_cocos2dx_RenderState_getStateBlock : wrong number of arguments: %d, was expecting %d", argc, 0); JS_ReportError(cx, "js_cocos2dx_RenderState_getStateBlock : wrong number of arguments: %d, was expecting %d", argc, 0);
return false; return false;
} }
bool js_cocos2dx_RenderState_getTextures(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::RenderState* cobj = (cocos2d::RenderState *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_RenderState_getTextures : Invalid Native Object");
if (argc == 0) {
const cocos2d::Vector<cocos2d::Texture2D *>& ret = cobj->getTextures();
jsval jsret = JSVAL_NULL;
jsret = ccvector_to_jsval(cx, ret);
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_RenderState_getTextures : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_RenderState_initialize(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_RenderState_initialize(JSContext *cx, uint32_t argc, jsval *vp)
{ {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@ -61414,7 +61497,6 @@ void js_register_cocos2dx_RenderState(JSContext *cx, JS::HandleObject global) {
JS_FN("bind", js_cocos2dx_RenderState_bind, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("bind", js_cocos2dx_RenderState_bind, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getName", js_cocos2dx_RenderState_getName, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("getName", js_cocos2dx_RenderState_getName, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getStateBlock", js_cocos2dx_RenderState_getStateBlock, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("getStateBlock", js_cocos2dx_RenderState_getStateBlock, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getTextures", js_cocos2dx_RenderState_getTextures, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END JS_FS_END
}; };
@ -67722,26 +67804,6 @@ bool js_cocos2dx_Component_isEnabled(JSContext *cx, uint32_t argc, jsval *vp)
JS_ReportError(cx, "js_cocos2dx_Component_isEnabled : wrong number of arguments: %d, was expecting %d", argc, 0); JS_ReportError(cx, "js_cocos2dx_Component_isEnabled : wrong number of arguments: %d, was expecting %d", argc, 0);
return false; return false;
} }
bool js_cocos2dx_Component_update(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::Component* cobj = (cocos2d::Component *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_Component_update : Invalid Native Object");
if (argc == 1) {
double arg0;
ok &= JS::ToNumber( cx, args.get(0), &arg0) && !isnan(arg0);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_Component_update : Error processing arguments");
cobj->update(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_Component_update : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_Component_getOwner(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_Component_getOwner(JSContext *cx, uint32_t argc, jsval *vp)
{ {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@ -67785,6 +67847,24 @@ bool js_cocos2dx_Component_init(JSContext *cx, uint32_t argc, jsval *vp)
JS_ReportError(cx, "js_cocos2dx_Component_init : wrong number of arguments: %d, was expecting %d", argc, 0); JS_ReportError(cx, "js_cocos2dx_Component_init : wrong number of arguments: %d, was expecting %d", argc, 0);
return false; return false;
} }
bool js_cocos2dx_Component_getName(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::Component* cobj = (cocos2d::Component *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_Component_getName : Invalid Native Object");
if (argc == 0) {
const std::string& ret = cobj->getName();
jsval jsret = JSVAL_NULL;
jsret = std_string_to_jsval(cx, ret);
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_Component_getName : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_Component_setOwner(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_Component_setOwner(JSContext *cx, uint32_t argc, jsval *vp)
{ {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@ -67813,24 +67893,6 @@ bool js_cocos2dx_Component_setOwner(JSContext *cx, uint32_t argc, jsval *vp)
JS_ReportError(cx, "js_cocos2dx_Component_setOwner : wrong number of arguments: %d, was expecting %d", argc, 1); JS_ReportError(cx, "js_cocos2dx_Component_setOwner : wrong number of arguments: %d, was expecting %d", argc, 1);
return false; return false;
} }
bool js_cocos2dx_Component_getName(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::Component* cobj = (cocos2d::Component *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_Component_getName : Invalid Native Object");
if (argc == 0) {
const std::string& ret = cobj->getName();
jsval jsret = JSVAL_NULL;
jsret = std_string_to_jsval(cx, ret);
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_Component_getName : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_Component_create(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_Component_create(JSContext *cx, uint32_t argc, jsval *vp)
{ {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@ -67925,11 +67987,10 @@ void js_register_cocos2dx_Component(JSContext *cx, JS::HandleObject global) {
JS_FN("setEnabled", js_cocos2dx_Component_setEnabled, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setEnabled", js_cocos2dx_Component_setEnabled, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setName", js_cocos2dx_Component_setName, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setName", js_cocos2dx_Component_setName, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("isEnabled", js_cocos2dx_Component_isEnabled, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("isEnabled", js_cocos2dx_Component_isEnabled, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("update", js_cocos2dx_Component_update, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getOwner", js_cocos2dx_Component_getOwner, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("getOwner", js_cocos2dx_Component_getOwner, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("init", js_cocos2dx_Component_init, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("init", js_cocos2dx_Component_init, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setOwner", js_cocos2dx_Component_setOwner, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getName", js_cocos2dx_Component_getName, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("getName", js_cocos2dx_Component_getName, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setOwner", js_cocos2dx_Component_setOwner, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("ctor", js_cocos2d_Component_ctor, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("ctor", js_cocos2d_Component_ctor, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END JS_FS_END
}; };

View File

@ -2044,12 +2044,16 @@ void js_register_cocos2dx_GLProgramState(JSContext *cx, JS::HandleObject global)
void register_all_cocos2dx(JSContext* cx, JS::HandleObject obj); void register_all_cocos2dx(JSContext* cx, JS::HandleObject obj);
bool js_cocos2dx_GLProgramState_setUniformCallback(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_GLProgramState_setUniformCallback(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_GLProgramState_getVertexAttribsFlags(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_GLProgramState_getVertexAttribsFlags(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_GLProgramState_applyAutoBinding(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_GLProgramState_setUniformVec2(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_GLProgramState_setUniformVec2(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_GLProgramState_setUniformVec3(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_GLProgramState_setUniformVec3(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_GLProgramState_setVertexAttribCallback(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_GLProgramState_setVertexAttribCallback(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_GLProgramState_apply(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_GLProgramState_apply(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_GLProgramState_getNodeBinding(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_GLProgramState_applyGLProgram(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_GLProgramState_applyGLProgram(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_GLProgramState_setNodeBinding(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_GLProgramState_setUniformInt(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_GLProgramState_setUniformInt(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_GLProgramState_setParameterAutoBinding(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_GLProgramState_setUniformVec2v(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_GLProgramState_setUniformVec2v(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_GLProgramState_getUniformCount(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_GLProgramState_getUniformCount(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_GLProgramState_applyAttributes(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_GLProgramState_applyAttributes(JSContext *cx, uint32_t argc, jsval *vp);
@ -3563,7 +3567,6 @@ bool js_cocos2dx_RenderState_getTexture(JSContext *cx, uint32_t argc, jsval *vp)
bool js_cocos2dx_RenderState_bind(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_RenderState_bind(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_RenderState_getName(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_RenderState_getName(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_RenderState_getStateBlock(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_RenderState_getStateBlock(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_RenderState_getTextures(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_RenderState_initialize(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_RenderState_initialize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_RenderState_finalize(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_RenderState_finalize(JSContext *cx, uint32_t argc, jsval *vp);
@ -3918,11 +3921,10 @@ void register_all_cocos2dx(JSContext* cx, JS::HandleObject obj);
bool js_cocos2dx_Component_setEnabled(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Component_setEnabled(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Component_setName(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Component_setName(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Component_isEnabled(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Component_isEnabled(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Component_update(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Component_getOwner(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Component_getOwner(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Component_init(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Component_init(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Component_setOwner(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Component_getName(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Component_getName(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Component_setOwner(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Component_create(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Component_create(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Component_Component(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Component_Component(JSContext *cx, uint32_t argc, jsval *vp);

View File

@ -0,0 +1,455 @@
#include "jsb_cocos2dx_experimental_video_auto.hpp"
#include "cocos2d_specifics.hpp"
#include "UIVideoPlayer.h"
template<class T>
static bool dummy_constructor(JSContext *cx, uint32_t argc, jsval *vp) {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedValue initializing(cx);
bool isNewValid = true;
JS::RootedObject global(cx, ScriptingCore::getInstance()->getGlobalObject());
isNewValid = JS_GetProperty(cx, global, "initializing", &initializing) && initializing.toBoolean();
if (isNewValid)
{
TypeTest<T> t;
js_type_class_t *typeClass = nullptr;
std::string typeName = t.s_name();
auto typeMapIter = _js_global_type_map.find(typeName);
CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!");
typeClass = typeMapIter->second;
CCASSERT(typeClass, "The value is null.");
JS::RootedObject proto(cx, typeClass->proto.get());
JS::RootedObject parent(cx, typeClass->parentProto.get());
JS::RootedObject _tmp(cx, JS_NewObject(cx, typeClass->jsclass, proto, parent));
args.rval().set(OBJECT_TO_JSVAL(_tmp));
return true;
}
JS_ReportError(cx, "Constructor for the requested class is not available, please refer to the API reference.");
return false;
}
static bool empty_constructor(JSContext *cx, uint32_t argc, jsval *vp) {
return false;
}
static bool js_is_native_obj(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
args.rval().setBoolean(true);
return true;
}
JSClass *jsb_cocos2d_experimental_ui_VideoPlayer_class;
JSObject *jsb_cocos2d_experimental_ui_VideoPlayer_prototype;
bool js_cocos2dx_experimental_video_VideoPlayer_getFileName(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::VideoPlayer* cobj = (cocos2d::experimental::ui::VideoPlayer *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_getFileName : Invalid Native Object");
if (argc == 0) {
const std::string& ret = cobj->getFileName();
jsval jsret = JSVAL_NULL;
jsret = std_string_to_jsval(cx, ret);
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_getFileName : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_video_VideoPlayer_getURL(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::VideoPlayer* cobj = (cocos2d::experimental::ui::VideoPlayer *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_getURL : Invalid Native Object");
if (argc == 0) {
const std::string& ret = cobj->getURL();
jsval jsret = JSVAL_NULL;
jsret = std_string_to_jsval(cx, ret);
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_getURL : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_video_VideoPlayer_play(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::VideoPlayer* cobj = (cocos2d::experimental::ui::VideoPlayer *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_play : Invalid Native Object");
if (argc == 0) {
cobj->play();
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_play : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_video_VideoPlayer_pause(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::VideoPlayer* cobj = (cocos2d::experimental::ui::VideoPlayer *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_pause : Invalid Native Object");
if (argc == 0) {
cobj->pause();
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_pause : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::VideoPlayer* cobj = (cocos2d::experimental::ui::VideoPlayer *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled : Invalid Native Object");
if (argc == 1) {
bool arg0;
arg0 = JS::ToBoolean(args.get(0));
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled : Error processing arguments");
cobj->setKeepAspectRatioEnabled(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_experimental_video_VideoPlayer_resume(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::VideoPlayer* cobj = (cocos2d::experimental::ui::VideoPlayer *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_resume : Invalid Native Object");
if (argc == 0) {
cobj->resume();
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_resume : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_video_VideoPlayer_stop(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::VideoPlayer* cobj = (cocos2d::experimental::ui::VideoPlayer *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_stop : Invalid Native Object");
if (argc == 0) {
cobj->stop();
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_stop : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_video_VideoPlayer_setFullScreenEnabled(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::VideoPlayer* cobj = (cocos2d::experimental::ui::VideoPlayer *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_setFullScreenEnabled : Invalid Native Object");
if (argc == 1) {
bool arg0;
arg0 = JS::ToBoolean(args.get(0));
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_setFullScreenEnabled : Error processing arguments");
cobj->setFullScreenEnabled(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_setFullScreenEnabled : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_experimental_video_VideoPlayer_setFileName(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::VideoPlayer* cobj = (cocos2d::experimental::ui::VideoPlayer *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_setFileName : Invalid Native Object");
if (argc == 1) {
std::string arg0;
ok &= jsval_to_std_string(cx, args.get(0), &arg0);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_setFileName : Error processing arguments");
cobj->setFileName(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_setFileName : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_experimental_video_VideoPlayer_setURL(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::VideoPlayer* cobj = (cocos2d::experimental::ui::VideoPlayer *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_setURL : Invalid Native Object");
if (argc == 1) {
std::string arg0;
ok &= jsval_to_std_string(cx, args.get(0), &arg0);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_setURL : Error processing arguments");
cobj->setURL(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_setURL : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_experimental_video_VideoPlayer_isKeepAspectRatioEnabled(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::VideoPlayer* cobj = (cocos2d::experimental::ui::VideoPlayer *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_isKeepAspectRatioEnabled : Invalid Native Object");
if (argc == 0) {
bool ret = cobj->isKeepAspectRatioEnabled();
jsval jsret = JSVAL_NULL;
jsret = BOOLEAN_TO_JSVAL(ret);
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_isKeepAspectRatioEnabled : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_video_VideoPlayer_onPlayEvent(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::VideoPlayer* cobj = (cocos2d::experimental::ui::VideoPlayer *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_onPlayEvent : Invalid Native Object");
if (argc == 1) {
int arg0;
ok &= jsval_to_int32(cx, args.get(0), (int32_t *)&arg0);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_onPlayEvent : Error processing arguments");
cobj->onPlayEvent(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_onPlayEvent : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_experimental_video_VideoPlayer_isFullScreenEnabled(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::VideoPlayer* cobj = (cocos2d::experimental::ui::VideoPlayer *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_isFullScreenEnabled : Invalid Native Object");
if (argc == 0) {
bool ret = cobj->isFullScreenEnabled();
jsval jsret = JSVAL_NULL;
jsret = BOOLEAN_TO_JSVAL(ret);
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_isFullScreenEnabled : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_video_VideoPlayer_isPlaying(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::VideoPlayer* cobj = (cocos2d::experimental::ui::VideoPlayer *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_isPlaying : Invalid Native Object");
if (argc == 0) {
bool ret = cobj->isPlaying();
jsval jsret = JSVAL_NULL;
jsret = BOOLEAN_TO_JSVAL(ret);
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_isPlaying : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_video_VideoPlayer_seekTo(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::VideoPlayer* cobj = (cocos2d::experimental::ui::VideoPlayer *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_seekTo : Invalid Native Object");
if (argc == 1) {
double arg0;
ok &= JS::ToNumber( cx, args.get(0), &arg0) && !isnan(arg0);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_seekTo : Error processing arguments");
cobj->seekTo(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_seekTo : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_experimental_video_VideoPlayer_create(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
if (argc == 0) {
cocos2d::experimental::ui::VideoPlayer* ret = cocos2d::experimental::ui::VideoPlayer::create();
jsval jsret = JSVAL_NULL;
do {
if (ret) {
js_proxy_t *jsProxy = js_get_or_create_proxy<cocos2d::experimental::ui::VideoPlayer>(cx, (cocos2d::experimental::ui::VideoPlayer*)ret);
jsret = OBJECT_TO_JSVAL(jsProxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_create : wrong number of arguments");
return false;
}
bool js_cocos2dx_experimental_video_VideoPlayer_constructor(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
cocos2d::experimental::ui::VideoPlayer* cobj = new (std::nothrow) cocos2d::experimental::ui::VideoPlayer();
cocos2d::Ref *_ccobj = dynamic_cast<cocos2d::Ref *>(cobj);
if (_ccobj) {
_ccobj->autorelease();
}
TypeTest<cocos2d::experimental::ui::VideoPlayer> t;
js_type_class_t *typeClass = nullptr;
std::string typeName = t.s_name();
auto typeMapIter = _js_global_type_map.find(typeName);
CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!");
typeClass = typeMapIter->second;
CCASSERT(typeClass, "The value is null.");
// JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto);
JS::RootedObject proto(cx, typeClass->proto.get());
JS::RootedObject parent(cx, typeClass->parentProto.get());
JS::RootedObject obj(cx, JS_NewObject(cx, typeClass->jsclass, proto, parent));
args.rval().set(OBJECT_TO_JSVAL(obj));
// link the native object with the javascript object
js_proxy_t* p = jsb_new_proxy(cobj, obj);
AddNamedObjectRoot(cx, &p->obj, "cocos2d::experimental::ui::VideoPlayer");
if (JS_HasProperty(cx, obj, "_ctor", &ok) && ok)
ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(obj), "_ctor", args);
return true;
}
extern JSObject *jsb_cocos2d_ui_Widget_prototype;
void js_cocos2d_experimental_ui_VideoPlayer_finalize(JSFreeOp *fop, JSObject *obj) {
CCLOGINFO("jsbindings: finalizing JS object %p (VideoPlayer)", obj);
}
void js_register_cocos2dx_experimental_video_VideoPlayer(JSContext *cx, JS::HandleObject global) {
jsb_cocos2d_experimental_ui_VideoPlayer_class = (JSClass *)calloc(1, sizeof(JSClass));
jsb_cocos2d_experimental_ui_VideoPlayer_class->name = "VideoPlayer";
jsb_cocos2d_experimental_ui_VideoPlayer_class->addProperty = JS_PropertyStub;
jsb_cocos2d_experimental_ui_VideoPlayer_class->delProperty = JS_DeletePropertyStub;
jsb_cocos2d_experimental_ui_VideoPlayer_class->getProperty = JS_PropertyStub;
jsb_cocos2d_experimental_ui_VideoPlayer_class->setProperty = JS_StrictPropertyStub;
jsb_cocos2d_experimental_ui_VideoPlayer_class->enumerate = JS_EnumerateStub;
jsb_cocos2d_experimental_ui_VideoPlayer_class->resolve = JS_ResolveStub;
jsb_cocos2d_experimental_ui_VideoPlayer_class->convert = JS_ConvertStub;
jsb_cocos2d_experimental_ui_VideoPlayer_class->finalize = js_cocos2d_experimental_ui_VideoPlayer_finalize;
jsb_cocos2d_experimental_ui_VideoPlayer_class->flags = JSCLASS_HAS_RESERVED_SLOTS(2);
static JSPropertySpec properties[] = {
JS_PSG("__nativeObj", js_is_native_obj, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PS_END
};
static JSFunctionSpec funcs[] = {
JS_FN("getFileName", js_cocos2dx_experimental_video_VideoPlayer_getFileName, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getURL", js_cocos2dx_experimental_video_VideoPlayer_getURL, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("play", js_cocos2dx_experimental_video_VideoPlayer_play, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("pause", js_cocos2dx_experimental_video_VideoPlayer_pause, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setKeepAspectRatioEnabled", js_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("resume", js_cocos2dx_experimental_video_VideoPlayer_resume, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("stop", js_cocos2dx_experimental_video_VideoPlayer_stop, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setFullScreenEnabled", js_cocos2dx_experimental_video_VideoPlayer_setFullScreenEnabled, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setFileName", js_cocos2dx_experimental_video_VideoPlayer_setFileName, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setURL", js_cocos2dx_experimental_video_VideoPlayer_setURL, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("isKeepAspectRatioEnabled", js_cocos2dx_experimental_video_VideoPlayer_isKeepAspectRatioEnabled, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("onPlayEvent", js_cocos2dx_experimental_video_VideoPlayer_onPlayEvent, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("isFullScreenEnabled", js_cocos2dx_experimental_video_VideoPlayer_isFullScreenEnabled, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("isPlaying", js_cocos2dx_experimental_video_VideoPlayer_isPlaying, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("seekTo", js_cocos2dx_experimental_video_VideoPlayer_seekTo, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END
};
static JSFunctionSpec st_funcs[] = {
JS_FN("create", js_cocos2dx_experimental_video_VideoPlayer_create, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END
};
jsb_cocos2d_experimental_ui_VideoPlayer_prototype = JS_InitClass(
cx, global,
JS::RootedObject(cx, jsb_cocos2d_ui_Widget_prototype),
jsb_cocos2d_experimental_ui_VideoPlayer_class,
js_cocos2dx_experimental_video_VideoPlayer_constructor, 0, // constructor
properties,
funcs,
NULL, // no static properties
st_funcs);
// make the class enumerable in the registered namespace
// bool found;
//FIXME: Removed in Firefox v27
// JS_SetPropertyAttributes(cx, global, "VideoPlayer", JSPROP_ENUMERATE | JSPROP_READONLY, &found);
// add the proto and JSClass to the type->js info hash table
TypeTest<cocos2d::experimental::ui::VideoPlayer> t;
js_type_class_t *p;
std::string typeName = t.s_name();
if (_js_global_type_map.find(typeName) == _js_global_type_map.end())
{
p = (js_type_class_t *)malloc(sizeof(js_type_class_t));
p->jsclass = jsb_cocos2d_experimental_ui_VideoPlayer_class;
p->proto = jsb_cocos2d_experimental_ui_VideoPlayer_prototype;
p->parentProto = jsb_cocos2d_ui_Widget_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
}
void register_all_cocos2dx_experimental_video(JSContext* cx, JS::HandleObject obj) {
// Get the ns
JS::RootedObject ns(cx);
get_or_create_js_obj(cx, obj, "ccui", &ns);
js_register_cocos2dx_experimental_video_VideoPlayer(cx, ns);
}

View File

@ -0,0 +1,33 @@
#ifndef __cocos2dx_experimental_video_h__
#define __cocos2dx_experimental_video_h__
#include "jsapi.h"
#include "jsfriendapi.h"
extern JSClass *jsb_cocos2d_experimental_ui_VideoPlayer_class;
extern JSObject *jsb_cocos2d_experimental_ui_VideoPlayer_prototype;
bool js_cocos2dx_experimental_video_VideoPlayer_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_cocos2dx_experimental_video_VideoPlayer_finalize(JSContext *cx, JSObject *obj);
void js_register_cocos2dx_experimental_video_VideoPlayer(JSContext *cx, JS::HandleObject global);
void register_all_cocos2dx_experimental_video(JSContext* cx, JS::HandleObject obj);
bool js_cocos2dx_experimental_video_VideoPlayer_getFileName(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_getURL(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_play(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_pause(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_resume(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_stop(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_setFullScreenEnabled(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_setFileName(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_setURL(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_isKeepAspectRatioEnabled(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_onPlayEvent(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_isFullScreenEnabled(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_isPlaying(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_seekTo(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_create(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_VideoPlayer(JSContext *cx, uint32_t argc, jsval *vp);
#endif

View File

@ -1722,6 +1722,22 @@ void js_register_cocos2dx_physics3d_Physics3DRigidBody(JSContext *cx, JS::Handle
JSClass *jsb_cocos2d_Physics3DComponent_class; JSClass *jsb_cocos2d_Physics3DComponent_class;
JSObject *jsb_cocos2d_Physics3DComponent_prototype; JSObject *jsb_cocos2d_Physics3DComponent_prototype;
bool js_cocos2dx_physics3d_Physics3DComponent_syncNodeToPhysics(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::Physics3DComponent* cobj = (cocos2d::Physics3DComponent *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_physics3d_Physics3DComponent_syncNodeToPhysics : Invalid Native Object");
if (argc == 0) {
cobj->syncNodeToPhysics();
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_physics3d_Physics3DComponent_syncNodeToPhysics : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_physics3d_Physics3DComponent_addToPhysicsWorld(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_physics3d_Physics3DComponent_addToPhysicsWorld(JSContext *cx, uint32_t argc, jsval *vp)
{ {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@ -1750,36 +1766,20 @@ bool js_cocos2dx_physics3d_Physics3DComponent_addToPhysicsWorld(JSContext *cx, u
JS_ReportError(cx, "js_cocos2dx_physics3d_Physics3DComponent_addToPhysicsWorld : wrong number of arguments: %d, was expecting %d", argc, 1); JS_ReportError(cx, "js_cocos2dx_physics3d_Physics3DComponent_addToPhysicsWorld : wrong number of arguments: %d, was expecting %d", argc, 1);
return false; return false;
} }
bool js_cocos2dx_physics3d_Physics3DComponent_syncToPhysics(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_physics3d_Physics3DComponent_syncPhysicsToNode(JSContext *cx, uint32_t argc, jsval *vp)
{ {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj); js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::Physics3DComponent* cobj = (cocos2d::Physics3DComponent *)(proxy ? proxy->ptr : NULL); cocos2d::Physics3DComponent* cobj = (cocos2d::Physics3DComponent *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_physics3d_Physics3DComponent_syncToPhysics : Invalid Native Object"); JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_physics3d_Physics3DComponent_syncPhysicsToNode : Invalid Native Object");
if (argc == 0) { if (argc == 0) {
cobj->syncToPhysics(); cobj->syncPhysicsToNode();
args.rval().setUndefined(); args.rval().setUndefined();
return true; return true;
} }
JS_ReportError(cx, "js_cocos2dx_physics3d_Physics3DComponent_syncToPhysics : wrong number of arguments: %d, was expecting %d", argc, 0); JS_ReportError(cx, "js_cocos2dx_physics3d_Physics3DComponent_syncPhysicsToNode : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_physics3d_Physics3DComponent_syncToNode(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::Physics3DComponent* cobj = (cocos2d::Physics3DComponent *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_physics3d_Physics3DComponent_syncToNode : Invalid Native Object");
if (argc == 0) {
cobj->syncToNode();
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_physics3d_Physics3DComponent_syncToNode : wrong number of arguments: %d, was expecting %d", argc, 0);
return false; return false;
} }
bool js_cocos2dx_physics3d_Physics3DComponent_getPhysics3DObject(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_physics3d_Physics3DComponent_getPhysics3DObject(JSContext *cx, uint32_t argc, jsval *vp)
@ -2061,9 +2061,9 @@ void js_register_cocos2dx_physics3d_Physics3DComponent(JSContext *cx, JS::Handle
}; };
static JSFunctionSpec funcs[] = { static JSFunctionSpec funcs[] = {
JS_FN("syncNodeToPhysics", js_cocos2dx_physics3d_Physics3DComponent_syncNodeToPhysics, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("addToPhysicsWorld", js_cocos2dx_physics3d_Physics3DComponent_addToPhysicsWorld, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("addToPhysicsWorld", js_cocos2dx_physics3d_Physics3DComponent_addToPhysicsWorld, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("syncToPhysics", js_cocos2dx_physics3d_Physics3DComponent_syncToPhysics, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("syncPhysicsToNode", js_cocos2dx_physics3d_Physics3DComponent_syncPhysicsToNode, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("syncToNode", js_cocos2dx_physics3d_Physics3DComponent_syncToNode, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getPhysics3DObject", js_cocos2dx_physics3d_Physics3DComponent_getPhysics3DObject, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("getPhysics3DObject", js_cocos2dx_physics3d_Physics3DComponent_getPhysics3DObject, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setPhysics3DObject", js_cocos2dx_physics3d_Physics3DComponent_setPhysics3DObject, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setPhysics3DObject", js_cocos2dx_physics3d_Physics3DComponent_setPhysics3DObject, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setSyncFlag", js_cocos2dx_physics3d_Physics3DComponent_setSyncFlag, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setSyncFlag", js_cocos2dx_physics3d_Physics3DComponent_setSyncFlag, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
@ -2108,36 +2108,36 @@ void js_register_cocos2dx_physics3d_Physics3DComponent(JSContext *cx, JS::Handle
JSClass *jsb_cocos2d_PhysicsSprite3D_class; JSClass *jsb_cocos2d_PhysicsSprite3D_class;
JSObject *jsb_cocos2d_PhysicsSprite3D_prototype; JSObject *jsb_cocos2d_PhysicsSprite3D_prototype;
bool js_cocos2dx_physics3d_PhysicsSprite3D_syncToPhysics(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_physics3d_PhysicsSprite3D_syncNodeToPhysics(JSContext *cx, uint32_t argc, jsval *vp)
{ {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj); js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::PhysicsSprite3D* cobj = (cocos2d::PhysicsSprite3D *)(proxy ? proxy->ptr : NULL); cocos2d::PhysicsSprite3D* cobj = (cocos2d::PhysicsSprite3D *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_physics3d_PhysicsSprite3D_syncToPhysics : Invalid Native Object"); JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_physics3d_PhysicsSprite3D_syncNodeToPhysics : Invalid Native Object");
if (argc == 0) { if (argc == 0) {
cobj->syncToPhysics(); cobj->syncNodeToPhysics();
args.rval().setUndefined(); args.rval().setUndefined();
return true; return true;
} }
JS_ReportError(cx, "js_cocos2dx_physics3d_PhysicsSprite3D_syncToPhysics : wrong number of arguments: %d, was expecting %d", argc, 0); JS_ReportError(cx, "js_cocos2dx_physics3d_PhysicsSprite3D_syncNodeToPhysics : wrong number of arguments: %d, was expecting %d", argc, 0);
return false; return false;
} }
bool js_cocos2dx_physics3d_PhysicsSprite3D_syncToNode(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_physics3d_PhysicsSprite3D_syncPhysicsToNode(JSContext *cx, uint32_t argc, jsval *vp)
{ {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj); js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::PhysicsSprite3D* cobj = (cocos2d::PhysicsSprite3D *)(proxy ? proxy->ptr : NULL); cocos2d::PhysicsSprite3D* cobj = (cocos2d::PhysicsSprite3D *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_physics3d_PhysicsSprite3D_syncToNode : Invalid Native Object"); JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_physics3d_PhysicsSprite3D_syncPhysicsToNode : Invalid Native Object");
if (argc == 0) { if (argc == 0) {
cobj->syncToNode(); cobj->syncPhysicsToNode();
args.rval().setUndefined(); args.rval().setUndefined();
return true; return true;
} }
JS_ReportError(cx, "js_cocos2dx_physics3d_PhysicsSprite3D_syncToNode : wrong number of arguments: %d, was expecting %d", argc, 0); JS_ReportError(cx, "js_cocos2dx_physics3d_PhysicsSprite3D_syncPhysicsToNode : wrong number of arguments: %d, was expecting %d", argc, 0);
return false; return false;
} }
bool js_cocos2dx_physics3d_PhysicsSprite3D_getPhysicsObj(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_physics3d_PhysicsSprite3D_getPhysicsObj(JSContext *cx, uint32_t argc, jsval *vp)
@ -2240,8 +2240,8 @@ void js_register_cocos2dx_physics3d_PhysicsSprite3D(JSContext *cx, JS::HandleObj
}; };
static JSFunctionSpec funcs[] = { static JSFunctionSpec funcs[] = {
JS_FN("syncToPhysics", js_cocos2dx_physics3d_PhysicsSprite3D_syncToPhysics, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("syncNodeToPhysics", js_cocos2dx_physics3d_PhysicsSprite3D_syncNodeToPhysics, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("syncToNode", js_cocos2dx_physics3d_PhysicsSprite3D_syncToNode, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("syncPhysicsToNode", js_cocos2dx_physics3d_PhysicsSprite3D_syncPhysicsToNode, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getPhysicsObj", js_cocos2dx_physics3d_PhysicsSprite3D_getPhysicsObj, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("getPhysicsObj", js_cocos2dx_physics3d_PhysicsSprite3D_getPhysicsObj, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setSyncFlag", js_cocos2dx_physics3d_PhysicsSprite3D_setSyncFlag, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setSyncFlag", js_cocos2dx_physics3d_PhysicsSprite3D_setSyncFlag, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END JS_FS_END
@ -2280,6 +2280,26 @@ void js_register_cocos2dx_physics3d_PhysicsSprite3D(JSContext *cx, JS::HandleObj
JSClass *jsb_cocos2d_Physics3DWorld_class; JSClass *jsb_cocos2d_Physics3DWorld_class;
JSObject *jsb_cocos2d_Physics3DWorld_prototype; JSObject *jsb_cocos2d_Physics3DWorld_prototype;
bool js_cocos2dx_physics3d_Physics3DWorld_setGravity(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::Physics3DWorld* cobj = (cocos2d::Physics3DWorld *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_physics3d_Physics3DWorld_setGravity : Invalid Native Object");
if (argc == 1) {
cocos2d::Vec3 arg0;
ok &= jsval_to_vector3(cx, args.get(0), &arg0);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_physics3d_Physics3DWorld_setGravity : Error processing arguments");
cobj->setGravity(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_physics3d_Physics3DWorld_setGravity : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_physics3d_Physics3DWorld_stepSimulate(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_physics3d_Physics3DWorld_stepSimulate(JSContext *cx, uint32_t argc, jsval *vp)
{ {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@ -2357,32 +2377,20 @@ bool js_cocos2dx_physics3d_Physics3DWorld_init(JSContext *cx, uint32_t argc, jsv
JS_ReportError(cx, "js_cocos2dx_physics3d_Physics3DWorld_init : wrong number of arguments: %d, was expecting %d", argc, 1); JS_ReportError(cx, "js_cocos2dx_physics3d_Physics3DWorld_init : wrong number of arguments: %d, was expecting %d", argc, 1);
return false; return false;
} }
bool js_cocos2dx_physics3d_Physics3DWorld_removePhysics3DConstraint(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_physics3d_Physics3DWorld_removeAllPhysics3DObjects(JSContext *cx, uint32_t argc, jsval *vp)
{ {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj); js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::Physics3DWorld* cobj = (cocos2d::Physics3DWorld *)(proxy ? proxy->ptr : NULL); cocos2d::Physics3DWorld* cobj = (cocos2d::Physics3DWorld *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_physics3d_Physics3DWorld_removePhysics3DConstraint : Invalid Native Object"); JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_physics3d_Physics3DWorld_removeAllPhysics3DObjects : Invalid Native Object");
if (argc == 1) { if (argc == 0) {
cocos2d::Physics3DConstraint* arg0; cobj->removeAllPhysics3DObjects();
do {
if (args.get(0).isNull()) { arg0 = nullptr; break; }
if (!args.get(0).isObject()) { ok = false; break; }
js_proxy_t *jsProxy;
JSObject *tmpObj = args.get(0).toObjectOrNull();
jsProxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocos2d::Physics3DConstraint*)(jsProxy ? jsProxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, false, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_physics3d_Physics3DWorld_removePhysics3DConstraint : Error processing arguments");
cobj->removePhysics3DConstraint(arg0);
args.rval().setUndefined(); args.rval().setUndefined();
return true; return true;
} }
JS_ReportError(cx, "js_cocos2dx_physics3d_Physics3DWorld_removePhysics3DConstraint : wrong number of arguments: %d, was expecting %d", argc, 1); JS_ReportError(cx, "js_cocos2dx_physics3d_Physics3DWorld_removeAllPhysics3DObjects : wrong number of arguments: %d, was expecting %d", argc, 0);
return false; return false;
} }
bool js_cocos2dx_physics3d_Physics3DWorld_isDebugDrawEnabled(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_physics3d_Physics3DWorld_isDebugDrawEnabled(JSContext *cx, uint32_t argc, jsval *vp)
@ -2446,20 +2454,50 @@ bool js_cocos2dx_physics3d_Physics3DWorld_rayCast(JSContext *cx, uint32_t argc,
JS_ReportError(cx, "js_cocos2dx_physics3d_Physics3DWorld_rayCast : wrong number of arguments: %d, was expecting %d", argc, 3); JS_ReportError(cx, "js_cocos2dx_physics3d_Physics3DWorld_rayCast : wrong number of arguments: %d, was expecting %d", argc, 3);
return false; return false;
} }
bool js_cocos2dx_physics3d_Physics3DWorld_removeAllPhysics3DObjects(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_physics3d_Physics3DWorld_getGravity(JSContext *cx, uint32_t argc, jsval *vp)
{ {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj); js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::Physics3DWorld* cobj = (cocos2d::Physics3DWorld *)(proxy ? proxy->ptr : NULL); cocos2d::Physics3DWorld* cobj = (cocos2d::Physics3DWorld *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_physics3d_Physics3DWorld_removeAllPhysics3DObjects : Invalid Native Object"); JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_physics3d_Physics3DWorld_getGravity : Invalid Native Object");
if (argc == 0) { if (argc == 0) {
cobj->removeAllPhysics3DObjects(); cocos2d::Vec3 ret = cobj->getGravity();
jsval jsret = JSVAL_NULL;
jsret = vector3_to_jsval(cx, ret);
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_physics3d_Physics3DWorld_getGravity : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_physics3d_Physics3DWorld_removePhysics3DConstraint(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::Physics3DWorld* cobj = (cocos2d::Physics3DWorld *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_physics3d_Physics3DWorld_removePhysics3DConstraint : Invalid Native Object");
if (argc == 1) {
cocos2d::Physics3DConstraint* arg0;
do {
if (args.get(0).isNull()) { arg0 = nullptr; break; }
if (!args.get(0).isObject()) { ok = false; break; }
js_proxy_t *jsProxy;
JSObject *tmpObj = args.get(0).toObjectOrNull();
jsProxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocos2d::Physics3DConstraint*)(jsProxy ? jsProxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, false, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_physics3d_Physics3DWorld_removePhysics3DConstraint : Error processing arguments");
cobj->removePhysics3DConstraint(arg0);
args.rval().setUndefined(); args.rval().setUndefined();
return true; return true;
} }
JS_ReportError(cx, "js_cocos2dx_physics3d_Physics3DWorld_removeAllPhysics3DObjects : wrong number of arguments: %d, was expecting %d", argc, 0); JS_ReportError(cx, "js_cocos2dx_physics3d_Physics3DWorld_removePhysics3DConstraint : wrong number of arguments: %d, was expecting %d", argc, 1);
return false; return false;
} }
bool js_cocos2dx_physics3d_Physics3DWorld_addPhysics3DObject(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_physics3d_Physics3DWorld_addPhysics3DObject(JSContext *cx, uint32_t argc, jsval *vp)
@ -2766,15 +2804,17 @@ void js_register_cocos2dx_physics3d_Physics3DWorld(JSContext *cx, JS::HandleObje
}; };
static JSFunctionSpec funcs[] = { static JSFunctionSpec funcs[] = {
JS_FN("setGravity", js_cocos2dx_physics3d_Physics3DWorld_setGravity, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("stepSimulate", js_cocos2dx_physics3d_Physics3DWorld_stepSimulate, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("stepSimulate", js_cocos2dx_physics3d_Physics3DWorld_stepSimulate, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("needCollisionChecking", js_cocos2dx_physics3d_Physics3DWorld_needCollisionChecking, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("needCollisionChecking", js_cocos2dx_physics3d_Physics3DWorld_needCollisionChecking, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("collisionChecking", js_cocos2dx_physics3d_Physics3DWorld_collisionChecking, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("collisionChecking", js_cocos2dx_physics3d_Physics3DWorld_collisionChecking, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("init", js_cocos2dx_physics3d_Physics3DWorld_init, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("init", js_cocos2dx_physics3d_Physics3DWorld_init, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("removePhysics3DConstraint", js_cocos2dx_physics3d_Physics3DWorld_removePhysics3DConstraint, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("removeAllPhysics3DObjects", js_cocos2dx_physics3d_Physics3DWorld_removeAllPhysics3DObjects, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("isDebugDrawEnabled", js_cocos2dx_physics3d_Physics3DWorld_isDebugDrawEnabled, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("isDebugDrawEnabled", js_cocos2dx_physics3d_Physics3DWorld_isDebugDrawEnabled, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("removeAllPhysics3DConstraints", js_cocos2dx_physics3d_Physics3DWorld_removeAllPhysics3DConstraints, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("removeAllPhysics3DConstraints", js_cocos2dx_physics3d_Physics3DWorld_removeAllPhysics3DConstraints, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("rayCast", js_cocos2dx_physics3d_Physics3DWorld_rayCast, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("rayCast", js_cocos2dx_physics3d_Physics3DWorld_rayCast, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("removeAllPhysics3DObjects", js_cocos2dx_physics3d_Physics3DWorld_removeAllPhysics3DObjects, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("getGravity", js_cocos2dx_physics3d_Physics3DWorld_getGravity, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("removePhysics3DConstraint", js_cocos2dx_physics3d_Physics3DWorld_removePhysics3DConstraint, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("addPhysics3DObject", js_cocos2dx_physics3d_Physics3DWorld_addPhysics3DObject, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("addPhysics3DObject", js_cocos2dx_physics3d_Physics3DWorld_addPhysics3DObject, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setDebugDrawEnable", js_cocos2dx_physics3d_Physics3DWorld_setDebugDrawEnable, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setDebugDrawEnable", js_cocos2dx_physics3d_Physics3DWorld_setDebugDrawEnable, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("removePhysics3DObject", js_cocos2dx_physics3d_Physics3DWorld_removePhysics3DObject, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("removePhysics3DObject", js_cocos2dx_physics3d_Physics3DWorld_removePhysics3DObject, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),

View File

@ -103,9 +103,9 @@ bool js_cocos2dx_physics3d_Physics3DComponent_constructor(JSContext *cx, uint32_
void js_cocos2dx_physics3d_Physics3DComponent_finalize(JSContext *cx, JSObject *obj); void js_cocos2dx_physics3d_Physics3DComponent_finalize(JSContext *cx, JSObject *obj);
void js_register_cocos2dx_physics3d_Physics3DComponent(JSContext *cx, JS::HandleObject global); void js_register_cocos2dx_physics3d_Physics3DComponent(JSContext *cx, JS::HandleObject global);
void register_all_cocos2dx_physics3d(JSContext* cx, JS::HandleObject obj); void register_all_cocos2dx_physics3d(JSContext* cx, JS::HandleObject obj);
bool js_cocos2dx_physics3d_Physics3DComponent_syncNodeToPhysics(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_Physics3DComponent_addToPhysicsWorld(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_Physics3DComponent_addToPhysicsWorld(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_Physics3DComponent_syncToPhysics(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_Physics3DComponent_syncPhysicsToNode(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_Physics3DComponent_syncToNode(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_Physics3DComponent_getPhysics3DObject(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_Physics3DComponent_getPhysics3DObject(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_Physics3DComponent_setPhysics3DObject(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_Physics3DComponent_setPhysics3DObject(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_Physics3DComponent_setSyncFlag(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_Physics3DComponent_setSyncFlag(JSContext *cx, uint32_t argc, jsval *vp);
@ -121,8 +121,8 @@ bool js_cocos2dx_physics3d_PhysicsSprite3D_constructor(JSContext *cx, uint32_t a
void js_cocos2dx_physics3d_PhysicsSprite3D_finalize(JSContext *cx, JSObject *obj); void js_cocos2dx_physics3d_PhysicsSprite3D_finalize(JSContext *cx, JSObject *obj);
void js_register_cocos2dx_physics3d_PhysicsSprite3D(JSContext *cx, JS::HandleObject global); void js_register_cocos2dx_physics3d_PhysicsSprite3D(JSContext *cx, JS::HandleObject global);
void register_all_cocos2dx_physics3d(JSContext* cx, JS::HandleObject obj); void register_all_cocos2dx_physics3d(JSContext* cx, JS::HandleObject obj);
bool js_cocos2dx_physics3d_PhysicsSprite3D_syncToPhysics(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_PhysicsSprite3D_syncNodeToPhysics(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_PhysicsSprite3D_syncToNode(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_PhysicsSprite3D_syncPhysicsToNode(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_PhysicsSprite3D_getPhysicsObj(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_PhysicsSprite3D_getPhysicsObj(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_PhysicsSprite3D_setSyncFlag(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_PhysicsSprite3D_setSyncFlag(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_PhysicsSprite3D_PhysicsSprite3D(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_PhysicsSprite3D_PhysicsSprite3D(JSContext *cx, uint32_t argc, jsval *vp);
@ -134,15 +134,17 @@ bool js_cocos2dx_physics3d_Physics3DWorld_constructor(JSContext *cx, uint32_t ar
void js_cocos2dx_physics3d_Physics3DWorld_finalize(JSContext *cx, JSObject *obj); void js_cocos2dx_physics3d_Physics3DWorld_finalize(JSContext *cx, JSObject *obj);
void js_register_cocos2dx_physics3d_Physics3DWorld(JSContext *cx, JS::HandleObject global); void js_register_cocos2dx_physics3d_Physics3DWorld(JSContext *cx, JS::HandleObject global);
void register_all_cocos2dx_physics3d(JSContext* cx, JS::HandleObject obj); void register_all_cocos2dx_physics3d(JSContext* cx, JS::HandleObject obj);
bool js_cocos2dx_physics3d_Physics3DWorld_setGravity(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_Physics3DWorld_stepSimulate(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_Physics3DWorld_stepSimulate(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_Physics3DWorld_needCollisionChecking(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_Physics3DWorld_needCollisionChecking(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_Physics3DWorld_collisionChecking(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_Physics3DWorld_collisionChecking(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_Physics3DWorld_init(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_Physics3DWorld_init(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_Physics3DWorld_removePhysics3DConstraint(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_Physics3DWorld_removeAllPhysics3DObjects(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_Physics3DWorld_isDebugDrawEnabled(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_Physics3DWorld_isDebugDrawEnabled(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_Physics3DWorld_removeAllPhysics3DConstraints(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_Physics3DWorld_removeAllPhysics3DConstraints(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_Physics3DWorld_rayCast(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_Physics3DWorld_rayCast(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_Physics3DWorld_removeAllPhysics3DObjects(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_Physics3DWorld_getGravity(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_Physics3DWorld_removePhysics3DConstraint(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_Physics3DWorld_addPhysics3DObject(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_Physics3DWorld_addPhysics3DObject(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_Physics3DWorld_setDebugDrawEnable(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_Physics3DWorld_setDebugDrawEnable(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_physics3d_Physics3DWorld_removePhysics3DObject(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_physics3d_Physics3DWorld_removePhysics3DObject(JSContext *cx, uint32_t argc, jsval *vp);

View File

@ -1058,28 +1058,29 @@ int ScriptingCore::handleComponentEvent(void* data)
JS::RootedValue retval(_cx); JS::RootedValue retval(_cx);
jsval dataVal = INT_TO_JSVAL(1); jsval dataVal = INT_TO_JSVAL(1);
if (action == kComponentOnEnter) JS::RootedValue nodeValue(_cx, OBJECT_TO_JSVAL(p->obj.get()));
if (action == kComponentOnAdd)
{ {
if (isFunctionOverridedInJS(JS::RootedObject(_cx, p->obj.get()), "onEnter", js_cocos2dx_Component_onEnter)) ret = executeFunctionWithOwner(nodeValue, "onAdd", 1, &dataVal, &retval);
{ }
ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "onEnter", 1, &dataVal, &retval); else if (action == kComponentOnRemove)
} {
ret = executeFunctionWithOwner(nodeValue, "onRemove", 1, &dataVal, &retval);
}
else if (action == kComponentOnEnter)
{
ret = executeFunctionWithOwner(nodeValue, "onEnter", 1, &dataVal, &retval);
resumeSchedulesAndActions(p); resumeSchedulesAndActions(p);
} }
else if (action == kComponentOnExit) else if (action == kComponentOnExit)
{ {
if (isFunctionOverridedInJS(JS::RootedObject(_cx, p->obj.get()), "onExit", js_cocos2dx_Component_onExit)) ret = executeFunctionWithOwner(nodeValue, "onExit", 1, &dataVal, &retval);
{
ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "onExit", 1, &dataVal, &retval);
}
pauseSchedulesAndActions(p); pauseSchedulesAndActions(p);
} }
else if (action == kComponentOnUpdate) else if (action == kComponentOnUpdate)
{ {
if (isFunctionOverridedInJS(JS::RootedObject(_cx, p->obj.get()), "update", js_cocos2dx_Component_update)) ret = executeFunctionWithOwner(nodeValue, "update", 1, &dataVal, &retval);
{
ret = executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "update", 1, &dataVal, &retval);
}
} }
return ret; return ret;

View File

@ -2693,36 +2693,6 @@ bool js_cocos2dx_CCNode_convertToWorldSpaceAR(JSContext *cx, uint32_t argc, jsva
return true; return true;
} }
bool js_cocos2dx_Component_onEnter(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *thisObj = JS_THIS_OBJECT(cx, vp);
if (thisObj) {
js_proxy_t *proxy = jsb_get_js_proxy(thisObj);
if (proxy) {
ScriptingCore::getInstance()->setCalledFromScript(true);
static_cast<Component*>(proxy->ptr)->onEnter();
return true;
}
}
JS_ReportError(cx, "Invalid Native Object.");
return false;
}
bool js_cocos2dx_Component_onExit(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *thisObj = JS_THIS_OBJECT(cx, vp);
if (thisObj) {
js_proxy_t *proxy = jsb_get_js_proxy(thisObj);
if (proxy) {
ScriptingCore::getInstance()->setCalledFromScript(true);
static_cast<Component*>(proxy->ptr)->onExit();
return true;
}
}
JS_ReportError(cx, "Invalid Native Object.");
return false;
}
bool js_cocos2dx_CCTMXLayer_tileFlagsAt(JSContext *cx, uint32_t argc, jsval *vp) bool js_cocos2dx_CCTMXLayer_tileFlagsAt(JSContext *cx, uint32_t argc, jsval *vp)
{ {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@ -5490,10 +5460,6 @@ void register_cocos2dx_js_core(JSContext* cx, JS::HandleObject global)
tmpObj.set(jsb_cocos2d_GLProgramState_prototype); tmpObj.set(jsb_cocos2d_GLProgramState_prototype);
JS_DefineFunction(cx, tmpObj, "setVertexAttribPointer", js_cocos2dx_GLProgramState_setVertexAttribPointer, 6, JSPROP_ENUMERATE | JSPROP_PERMANENT); JS_DefineFunction(cx, tmpObj, "setVertexAttribPointer", js_cocos2dx_GLProgramState_setVertexAttribPointer, 6, JSPROP_ENUMERATE | JSPROP_PERMANENT);
JS_DefineFunction(cx, tmpObj, "setUniformVec4", js_cocos2dx_GLProgramState_setUniformVec4, 2, JSPROP_ENUMERATE | JSPROP_PERMANENT); JS_DefineFunction(cx, tmpObj, "setUniformVec4", js_cocos2dx_GLProgramState_setUniformVec4, 2, JSPROP_ENUMERATE | JSPROP_PERMANENT);
tmpObj.set(jsb_cocos2d_Component_prototype);
JS_DefineFunction(cx, tmpObj, "onEnter", js_cocos2dx_Component_onEnter, 0, JSPROP_ENUMERATE | JSPROP_PERMANENT);
JS_DefineFunction(cx, tmpObj, "onExit", js_cocos2dx_Component_onExit, 0, JSPROP_ENUMERATE | JSPROP_PERMANENT);
tmpObj.set(jsb_cocos2d_Scheduler_prototype); tmpObj.set(jsb_cocos2d_Scheduler_prototype);
JS_DefineFunction(cx, tmpObj, "retain", js_cocos2dx_retain, 0, JSPROP_ENUMERATE | JSPROP_PERMANENT); JS_DefineFunction(cx, tmpObj, "retain", js_cocos2dx_retain, 0, JSPROP_ENUMERATE | JSPROP_PERMANENT);

View File

@ -0,0 +1,49 @@
#include "jsb_cocos2dx_experimental_video_manual.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#include "UIVideoPlayer.h"
#include "ScriptingCore.h"
#include "cocos2d_specifics.hpp"
#include "cocos2d.h"
using namespace cocos2d;
static bool jsb_cocos2dx_experimental_ui_VideoPlayer_addEventListener(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
experimental::ui::VideoPlayer* cobj = (experimental::ui::VideoPlayer *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object");
if(argc == 1){
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
std::shared_ptr<JSFunctionWrapper> func(new JSFunctionWrapper(cx, obj, args.get(0)));
cobj->addEventListener([=](Ref* widget, experimental::ui::VideoPlayer::EventType type)->void{
jsval arg[2];
js_proxy_t *proxy = js_get_or_create_proxy(cx, widget);
if(proxy)
arg[0] = OBJECT_TO_JSVAL(proxy->obj);
else
arg[0] = JSVAL_NULL;
arg[1] = int32_to_jsval(cx, (int32_t)type);
JS::RootedValue rval(cx);
bool ok = func->invoke(2, arg, &rval);
if (!ok && JS_IsExceptionPending(cx)) {
JS_ReportPendingException(cx);
}
});
return true;
}
}
extern JSObject* jsb_cocos2d_experimental_ui_VideoPlayer_prototype;
void register_all_cocos2dx_experimental_video_manual(JSContext* cx, JS::HandleObject global)
{
JS_DefineFunction(cx, JS::RootedObject(cx, jsb_cocos2d_experimental_ui_VideoPlayer_prototype), "addEventListener", jsb_cocos2dx_experimental_ui_VideoPlayer_addEventListener, 1, JSPROP_ENUMERATE | JSPROP_PERMANENT);
}
#endif

View File

@ -0,0 +1,9 @@
#ifndef __jsb_cocos2dx_experimental_video_manual__
#define __jsb_cocos2dx_experimental_video_manual__
#include "jsapi.h"
#include "jsfriendapi.h"
void register_all_cocos2dx_experimental_video_manual(JSContext* cx, JS::HandleObject global);
#endif /* defined(__jsb_cocos2dx_experimental_video_manual__) */

View File

@ -908,7 +908,7 @@ bool js_cocos2dx_ext_release(JSContext *cx, uint32_t argc, jsval *vp)
} }
__JSDownloaderDelegator::__JSDownloaderDelegator(JSContext *cx, JS::HandleObject obj, const std::string &url, JS::HandleValue callback) __JSDownloaderDelegator::__JSDownloaderDelegator(JSContext *cx, JS::HandleObject obj, const std::string &url, JS::HandleObject callback)
: _cx(cx) : _cx(cx)
, _url(url) , _url(url)
, _buffer(nullptr) , _buffer(nullptr)
@ -917,7 +917,27 @@ __JSDownloaderDelegator::__JSDownloaderDelegator(JSContext *cx, JS::HandleObject
_obj.ref().set(obj); _obj.ref().set(obj);
_jsCallback.construct(_cx); _jsCallback.construct(_cx);
_jsCallback.ref().set(callback); _jsCallback.ref().set(callback);
}
__JSDownloaderDelegator::~__JSDownloaderDelegator()
{
_obj.destroyIfConstructed();
_jsCallback.destroyIfConstructed();
if (_buffer != nullptr)
free(_buffer);
_downloader->setErrorCallback(nullptr);
_downloader->setSuccessCallback(nullptr);
}
__JSDownloaderDelegator *__JSDownloaderDelegator::create(JSContext *cx, JS::HandleObject obj, const std::string &url, JS::HandleObject callback)
{
__JSDownloaderDelegator *delegate = new (std::nothrow) __JSDownloaderDelegator(cx, obj, url, callback);
delegate->autorelease();
return delegate;
}
void __JSDownloaderDelegator::startDownload()
{
if (Director::getInstance()->getTextureCache()->getTextureForKey(_url)) if (Director::getInstance()->getTextureCache()->getTextureForKey(_url))
{ {
onSuccess(nullptr, nullptr, nullptr); onSuccess(nullptr, nullptr, nullptr);
@ -929,12 +949,9 @@ __JSDownloaderDelegator::__JSDownloaderDelegator(JSContext *cx, JS::HandleObject
_downloader->setErrorCallback( std::bind(&__JSDownloaderDelegator::onError, this, std::placeholders::_1) ); _downloader->setErrorCallback( std::bind(&__JSDownloaderDelegator::onError, this, std::placeholders::_1) );
_downloader->setSuccessCallback( std::bind(&__JSDownloaderDelegator::onSuccess, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3) ); _downloader->setSuccessCallback( std::bind(&__JSDownloaderDelegator::onSuccess, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3) );
long contentSize = _downloader->getContentSize(_url); cocos2d::extension::Downloader::HeaderInfo info = _downloader->getHeader(_url);
if (contentSize == -1) { long contentSize = info.contentSize;
cocos2d::extension::Downloader::Error err; if (contentSize > 0 && info.responseCode < 400) {
onError(err);
}
else {
_size = contentSize / sizeof(unsigned char); _size = contentSize / sizeof(unsigned char);
_buffer = (unsigned char*)malloc(contentSize); _buffer = (unsigned char*)malloc(contentSize);
_downloader->downloadToBufferSync(_url, _buffer, _size); _downloader->downloadToBufferSync(_url, _buffer, _size);
@ -942,79 +959,85 @@ __JSDownloaderDelegator::__JSDownloaderDelegator(JSContext *cx, JS::HandleObject
} }
} }
__JSDownloaderDelegator::~__JSDownloaderDelegator() void __JSDownloaderDelegator::download()
{ {
if (_buffer != nullptr) retain();
free(_buffer); startDownload();
_downloader->setErrorCallback(nullptr); }
_downloader->setSuccessCallback(nullptr);
void __JSDownloaderDelegator::downloadAsync()
{
retain();
auto t = std::thread(&__JSDownloaderDelegator::startDownload, this);
t.detach();
} }
void __JSDownloaderDelegator::onError(const cocos2d::extension::Downloader::Error &error) void __JSDownloaderDelegator::onError(const cocos2d::extension::Downloader::Error &error)
{ {
if (!_jsCallback.ref().isNull()) { Director::getInstance()->getScheduler()->performFunctionInCocosThread([this]
JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); {
JS::RootedObject global(cx, ScriptingCore::getInstance()->getGlobalObject()); JS::RootedValue callback(_cx, OBJECT_TO_JSVAL(_jsCallback.ref()));
if (!callback.isNull()) {
JSAutoCompartment ac(_cx, _obj.ref()); JS::RootedObject global(_cx, ScriptingCore::getInstance()->getGlobalObject());
JSAutoCompartment ac(_cx, global);
jsval succeed = BOOLEAN_TO_JSVAL(false);
JS::RootedValue retval(cx); jsval succeed = BOOLEAN_TO_JSVAL(false);
JS_CallFunctionValue(cx, global, _jsCallback.ref(), JS::HandleValueArray::fromMarkedLocation(1, &succeed), &retval); JS::RootedValue retval(_cx);
} JS_CallFunctionValue(_cx, global, callback, JS::HandleValueArray::fromMarkedLocation(1, &succeed), &retval);
this->release(); }
release();
});
} }
void __JSDownloaderDelegator::onSuccess(const std::string &srcUrl, const std::string &storagePath, const std::string &customId) void __JSDownloaderDelegator::onSuccess(const std::string &srcUrl, const std::string &storagePath, const std::string &customId)
{ {
Image *image = new Image(); Image *image = new Image();
jsval valArr[2];
JSContext *cx = ScriptingCore::getInstance()->getGlobalContext();
JS::RootedObject global(cx, ScriptingCore::getInstance()->getGlobalObject());
cocos2d::TextureCache *cache = Director::getInstance()->getTextureCache(); cocos2d::TextureCache *cache = Director::getInstance()->getTextureCache();
JSAutoCompartment ac(_cx, _obj.ref() ? _obj.ref() : global);
Texture2D *tex = cache->getTextureForKey(_url); Texture2D *tex = cache->getTextureForKey(_url);
if (tex) if (!tex)
{ {
valArr[0] = BOOLEAN_TO_JSVAL(true); if (image->initWithImageData(_buffer, _size))
js_proxy_t* p = jsb_get_native_proxy(tex); {
valArr[1] = OBJECT_TO_JSVAL(p->obj); tex = Director::getInstance()->getTextureCache()->addImage(image, _url);
}
} }
else if (image->initWithImageData(_buffer, _size))
{
tex = Director::getInstance()->getTextureCache()->addImage(image, _url);
valArr[0] = BOOLEAN_TO_JSVAL(true);
JS::RootedObject texProto(cx, jsb_cocos2d_Texture2D_prototype);
JSObject *obj = JS_NewObject(cx, jsb_cocos2d_Texture2D_class, texProto, global);
// link the native object with the javascript object
js_proxy_t* p = jsb_new_proxy(tex, obj);
JS::AddNamedObjectRoot(cx, &p->obj, "cocos2d::Texture2D");
valArr[1] = OBJECT_TO_JSVAL(p->obj);
}
else
{
valArr[0] = BOOLEAN_TO_JSVAL(false);
valArr[1] = JSVAL_NULL;
}
image->release(); image->release();
if (!_jsCallback.ref().isNull()) { Director::getInstance()->getScheduler()->performFunctionInCocosThread([this, tex]
JS::RootedValue retval(cx); {
JS_CallFunctionValue(cx, global, _jsCallback.ref(), JS::HandleValueArray::fromMarkedLocation(2, valArr), &retval); JS::RootedObject global(_cx, ScriptingCore::getInstance()->getGlobalObject());
} JSAutoCompartment ac(_cx, global);
this->release();
} jsval valArr[2];
if (tex)
void __JSDownloaderDelegator::download(JSContext *cx, JS::HandleObject obj, const std::string &url, JS::HandleValue callback) {
{ valArr[0] = BOOLEAN_TO_JSVAL(true);
auto t = std::thread([cx, obj, url, callback]() { js_proxy_t* p = jsb_get_native_proxy(tex);
new __JSDownloaderDelegator(cx, obj, url, callback); if (!p)
{
JS::RootedObject texProto(_cx, jsb_cocos2d_Texture2D_prototype);
JSObject *obj = JS_NewObject(_cx, jsb_cocos2d_Texture2D_class, texProto, global);
// link the native object with the javascript object
p = jsb_new_proxy(tex, obj);
JS::AddNamedObjectRoot(_cx, &p->obj, "cocos2d::Texture2D");
}
valArr[1] = OBJECT_TO_JSVAL(p->obj);
}
else
{
valArr[0] = BOOLEAN_TO_JSVAL(false);
valArr[1] = JSVAL_NULL;
}
JS::RootedValue callback(_cx, OBJECT_TO_JSVAL(_jsCallback.ref()));
if (!callback.isNull())
{
JS::RootedValue retval(_cx);
JS_CallFunctionValue(_cx, global, callback, JS::HandleValueArray::fromMarkedLocation(2, valArr), &retval);
}
release();
}); });
t.detach();
} }
// jsb.loadRemoteImg(url, function(succeed, result) {}) // jsb.loadRemoteImg(url, function(succeed, result) {})
@ -1022,14 +1045,15 @@ bool js_load_remote_image(JSContext *cx, uint32_t argc, jsval *vp)
{ {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, JS_THIS_OBJECT(cx, vp)); JS::RootedObject obj(cx, JS_THIS_OBJECT(cx, vp));
if (argc == 2) { if (argc == 2)
{
std::string url; std::string url;
bool ok = jsval_to_std_string(cx, args.get(0), &url); bool ok = jsval_to_std_string(cx, args.get(0), &url);
JS::RootedValue callback(cx, args.get(1)); JSB_PRECONDITION2(ok, cx, false, "js_load_remote_image : Error processing arguments");
JS::RootedObject callback(cx, args.get(1).toObjectOrNull());
__JSDownloaderDelegator::download(cx, obj, url, callback); __JSDownloaderDelegator *delegate = __JSDownloaderDelegator::create(cx, obj, url, callback);
delegate->downloadAsync();
JSB_PRECONDITION2(ok, cx, false, "js_console_log : Error processing arguments");
args.rval().setUndefined(); args.rval().setUndefined();
return true; return true;

View File

@ -32,12 +32,17 @@
class __JSDownloaderDelegator : cocos2d::Ref class __JSDownloaderDelegator : cocos2d::Ref
{ {
public: public:
static void download(JSContext *cx, JS::HandleObject obj, const std::string &url, JS::HandleValue callback); void downloadAsync();
void download();
static __JSDownloaderDelegator *create(JSContext *cx, JS::HandleObject obj, const std::string &url, JS::HandleObject callback);
protected: protected:
__JSDownloaderDelegator(JSContext *cx, JS::HandleObject obj, const std::string &url, JS::HandleValue callback); __JSDownloaderDelegator(JSContext *cx, JS::HandleObject obj, const std::string &url, JS::HandleObject callback);
~__JSDownloaderDelegator(); ~__JSDownloaderDelegator();
void startDownload();
private: private:
void onSuccess(const std::string &srcUrl, const std::string &storagePath, const std::string &customId); void onSuccess(const std::string &srcUrl, const std::string &storagePath, const std::string &customId);
void onError(const cocos2d::extension::Downloader::Error &error); void onError(const cocos2d::extension::Downloader::Error &error);
@ -46,8 +51,8 @@ private:
std::shared_ptr<cocos2d::extension::Downloader> _downloader; std::shared_ptr<cocos2d::extension::Downloader> _downloader;
std::string _url; std::string _url;
JSContext *_cx; JSContext *_cx;
mozilla::Maybe<JS::RootedValue> _jsCallback; mozilla::Maybe<JS::PersistentRootedObject> _jsCallback;
mozilla::Maybe<JS::RootedObject> _obj; mozilla::Maybe<JS::PersistentRootedObject> _obj;
}; };
void register_all_cocos2dx_extension_manual(JSContext* cx, JS::HandleObject global); void register_all_cocos2dx_extension_manual(JSContext* cx, JS::HandleObject global);

View File

@ -39,6 +39,7 @@ LOCAL_SRC_FILES := ../auto/jsb_cocos2dx_3d_auto.cpp \
../auto/jsb_cocos2dx_extension_auto.cpp \ ../auto/jsb_cocos2dx_extension_auto.cpp \
../auto/jsb_cocos2dx_3d_extension_auto.cpp \ ../auto/jsb_cocos2dx_3d_extension_auto.cpp \
../auto/jsb_cocos2dx_experimental_webView_auto.cpp \ ../auto/jsb_cocos2dx_experimental_webView_auto.cpp \
../auto/jsb_cocos2dx_experimental_video_auto.cpp \
../auto/jsb_cocos2dx_spine_auto.cpp \ ../auto/jsb_cocos2dx_spine_auto.cpp \
../auto/jsb_cocos2dx_auto.cpp \ ../auto/jsb_cocos2dx_auto.cpp \
../auto/jsb_cocos2dx_studio_auto.cpp \ ../auto/jsb_cocos2dx_studio_auto.cpp \
@ -56,6 +57,7 @@ LOCAL_SRC_FILES := ../auto/jsb_cocos2dx_3d_auto.cpp \
../manual/jsb_opengl_registration.cpp \ ../manual/jsb_opengl_registration.cpp \
../manual/jsb_event_dispatcher_manual.cpp \ ../manual/jsb_event_dispatcher_manual.cpp \
../manual/3d/jsb_cocos2dx_3d_manual.cpp \ ../manual/3d/jsb_cocos2dx_3d_manual.cpp \
../manual/experimental/jsb_cocos2dx_experimental_video_manual.cpp \
../manual/experimental/jsb_cocos2dx_experimental_webView_manual.cpp \ ../manual/experimental/jsb_cocos2dx_experimental_webView_manual.cpp \
../manual/chipmunk/js_bindings_chipmunk_auto_classes.cpp \ ../manual/chipmunk/js_bindings_chipmunk_auto_classes.cpp \
../manual/chipmunk/js_bindings_chipmunk_functions.cpp \ ../manual/chipmunk/js_bindings_chipmunk_functions.cpp \

View File

@ -172,6 +172,10 @@
83A5661A18DA878400FC31A0 /* jsb_socketio.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 83A5661718DA878400FC31A0 /* jsb_socketio.cpp */; }; 83A5661A18DA878400FC31A0 /* jsb_socketio.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 83A5661718DA878400FC31A0 /* jsb_socketio.cpp */; };
83A5661B18DA878400FC31A0 /* jsb_socketio.h in Headers */ = {isa = PBXBuildFile; fileRef = 83A5661818DA878400FC31A0 /* jsb_socketio.h */; }; 83A5661B18DA878400FC31A0 /* jsb_socketio.h in Headers */ = {isa = PBXBuildFile; fileRef = 83A5661818DA878400FC31A0 /* jsb_socketio.h */; };
83A5661C18DA878400FC31A0 /* jsb_socketio.h in Headers */ = {isa = PBXBuildFile; fileRef = 83A5661818DA878400FC31A0 /* jsb_socketio.h */; }; 83A5661C18DA878400FC31A0 /* jsb_socketio.h in Headers */ = {isa = PBXBuildFile; fileRef = 83A5661818DA878400FC31A0 /* jsb_socketio.h */; };
B38AD56A1B1D384A0057DD7F /* jsb_cocos2dx_experimental_video_manual.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B38AD5681B1D384A0057DD7F /* jsb_cocos2dx_experimental_video_manual.cpp */; };
B38AD56B1B1D384A0057DD7F /* jsb_cocos2dx_experimental_video_manual.h in Headers */ = {isa = PBXBuildFile; fileRef = B38AD5691B1D384A0057DD7F /* jsb_cocos2dx_experimental_video_manual.h */; };
B38AD56E1B1D38700057DD7F /* jsb_cocos2dx_experimental_video_auto.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B38AD56C1B1D38700057DD7F /* jsb_cocos2dx_experimental_video_auto.cpp */; };
B38AD56F1B1D38700057DD7F /* jsb_cocos2dx_experimental_video_auto.hpp in Headers */ = {isa = PBXBuildFile; fileRef = B38AD56D1B1D38700057DD7F /* jsb_cocos2dx_experimental_video_auto.hpp */; };
BA4095C21A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA4095C01A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.cpp */; }; BA4095C21A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA4095C01A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.cpp */; };
BA4095C31A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA4095C01A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.cpp */; }; BA4095C31A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA4095C01A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.cpp */; };
BA4095C41A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.h in Headers */ = {isa = PBXBuildFile; fileRef = BA4095C11A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.h */; }; BA4095C41A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.h in Headers */ = {isa = PBXBuildFile; fileRef = BA4095C11A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.h */; };
@ -292,6 +296,10 @@
4BE089EA1ADF967400D65D4B /* jsb_cocos2dx_experimental_webView_manual.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsb_cocos2dx_experimental_webView_manual.h; sourceTree = "<group>"; }; 4BE089EA1ADF967400D65D4B /* jsb_cocos2dx_experimental_webView_manual.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsb_cocos2dx_experimental_webView_manual.h; sourceTree = "<group>"; };
83A5661718DA878400FC31A0 /* jsb_socketio.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = jsb_socketio.cpp; sourceTree = "<group>"; }; 83A5661718DA878400FC31A0 /* jsb_socketio.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = jsb_socketio.cpp; sourceTree = "<group>"; };
83A5661818DA878400FC31A0 /* jsb_socketio.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsb_socketio.h; sourceTree = "<group>"; }; 83A5661818DA878400FC31A0 /* jsb_socketio.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsb_socketio.h; sourceTree = "<group>"; };
B38AD5681B1D384A0057DD7F /* jsb_cocos2dx_experimental_video_manual.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = jsb_cocos2dx_experimental_video_manual.cpp; path = experimental/jsb_cocos2dx_experimental_video_manual.cpp; sourceTree = "<group>"; };
B38AD5691B1D384A0057DD7F /* jsb_cocos2dx_experimental_video_manual.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = jsb_cocos2dx_experimental_video_manual.h; path = experimental/jsb_cocos2dx_experimental_video_manual.h; sourceTree = "<group>"; };
B38AD56C1B1D38700057DD7F /* jsb_cocos2dx_experimental_video_auto.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = jsb_cocos2dx_experimental_video_auto.cpp; sourceTree = "<group>"; };
B38AD56D1B1D38700057DD7F /* jsb_cocos2dx_experimental_video_auto.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = jsb_cocos2dx_experimental_video_auto.hpp; sourceTree = "<group>"; };
BA4095C01A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = jsb_cocos2dx_studio_conversions.cpp; sourceTree = "<group>"; }; BA4095C01A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = jsb_cocos2dx_studio_conversions.cpp; sourceTree = "<group>"; };
BA4095C11A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsb_cocos2dx_studio_conversions.h; sourceTree = "<group>"; }; BA4095C11A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsb_cocos2dx_studio_conversions.h; sourceTree = "<group>"; };
BA623DFC191A195F00761F37 /* jsb_pluginx_basic_conversions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = jsb_pluginx_basic_conversions.cpp; path = ../../../../plugin/jsbindings/manual/jsb_pluginx_basic_conversions.cpp; sourceTree = "<group>"; }; BA623DFC191A195F00761F37 /* jsb_pluginx_basic_conversions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = jsb_pluginx_basic_conversions.cpp; path = ../../../../plugin/jsbindings/manual/jsb_pluginx_basic_conversions.cpp; sourceTree = "<group>"; };
@ -357,6 +365,8 @@
1A119E2E18BDF19200352BAA /* auto */ = { 1A119E2E18BDF19200352BAA /* auto */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
B38AD56C1B1D38700057DD7F /* jsb_cocos2dx_experimental_video_auto.cpp */,
B38AD56D1B1D38700057DD7F /* jsb_cocos2dx_experimental_video_auto.hpp */,
4BE089E01ADF965E00D65D4B /* jsb_cocos2dx_experimental_webView_auto.cpp */, 4BE089E01ADF965E00D65D4B /* jsb_cocos2dx_experimental_webView_auto.cpp */,
4BE089E11ADF965E00D65D4B /* jsb_cocos2dx_experimental_webView_auto.hpp */, 4BE089E11ADF965E00D65D4B /* jsb_cocos2dx_experimental_webView_auto.hpp */,
42638FFB1B0EC1B7004C53A2 /* jsb_cocos2dx_physics3d_auto.cpp */, 42638FFB1B0EC1B7004C53A2 /* jsb_cocos2dx_physics3d_auto.cpp */,
@ -578,6 +588,8 @@
42AD25701AFF9DFC000176E2 /* experimental */ = { 42AD25701AFF9DFC000176E2 /* experimental */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
B38AD5681B1D384A0057DD7F /* jsb_cocos2dx_experimental_video_manual.cpp */,
B38AD5691B1D384A0057DD7F /* jsb_cocos2dx_experimental_video_manual.h */,
4B22F4A71B159A7A0044C14E /* jsb_cocos2dx_experimental_webView_manual.cpp */, 4B22F4A71B159A7A0044C14E /* jsb_cocos2dx_experimental_webView_manual.cpp */,
4B22F4A81B159A7A0044C14E /* jsb_cocos2dx_experimental_webView_manual.h */, 4B22F4A81B159A7A0044C14E /* jsb_cocos2dx_experimental_webView_manual.h */,
42AD25711AFF9E17000176E2 /* jsb_cocos2dx_experimental_manual.cpp */, 42AD25711AFF9E17000176E2 /* jsb_cocos2dx_experimental_manual.cpp */,
@ -667,6 +679,7 @@
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
1A119EA418BDF19200352BAA /* jsb_cocos2dx_studio_auto.hpp in Headers */, 1A119EA418BDF19200352BAA /* jsb_cocos2dx_studio_auto.hpp in Headers */,
B38AD56B1B1D384A0057DD7F /* jsb_cocos2dx_experimental_video_manual.h in Headers */,
1A119F0218BDF19200352BAA /* ScriptingCore.h in Headers */, 1A119F0218BDF19200352BAA /* ScriptingCore.h in Headers */,
426390071B0EC1C6004C53A2 /* jsb_cocos2dx_physics3d_manual.h in Headers */, 426390071B0EC1C6004C53A2 /* jsb_cocos2dx_physics3d_manual.h in Headers */,
1A119EBE18BDF19200352BAA /* cocos2d_specifics.hpp in Headers */, 1A119EBE18BDF19200352BAA /* cocos2d_specifics.hpp in Headers */,
@ -719,6 +732,7 @@
1A119E8618BDF19200352BAA /* jsb_cocos2dx_auto.hpp in Headers */, 1A119E8618BDF19200352BAA /* jsb_cocos2dx_auto.hpp in Headers */,
BA623E12191A195F00761F37 /* jsb_pluginx_spidermonkey_specifics.h in Headers */, BA623E12191A195F00761F37 /* jsb_pluginx_spidermonkey_specifics.h in Headers */,
1A119F0818BDF19200352BAA /* jsb_cocos2dx_spine_manual.h in Headers */, 1A119F0818BDF19200352BAA /* jsb_cocos2dx_spine_manual.h in Headers */,
B38AD56F1B1D38700057DD7F /* jsb_cocos2dx_experimental_video_auto.hpp in Headers */,
BA623E0A191A195F00761F37 /* jsb_pluginx_basic_conversions.h in Headers */, BA623E0A191A195F00761F37 /* jsb_pluginx_basic_conversions.h in Headers */,
BA623E14191A195F00761F37 /* pluginxUTF8.h in Headers */, BA623E14191A195F00761F37 /* pluginxUTF8.h in Headers */,
); );
@ -858,6 +872,7 @@
4BE089E41ADF965E00D65D4B /* jsb_cocos2dx_experimental_webView_auto.cpp in Sources */, 4BE089E41ADF965E00D65D4B /* jsb_cocos2dx_experimental_webView_auto.cpp in Sources */,
1A119EF418BDF19200352BAA /* js_bindings_system_registration.cpp in Sources */, 1A119EF418BDF19200352BAA /* js_bindings_system_registration.cpp in Sources */,
42AD256D1AFF9D1A000176E2 /* jsb_cocos2dx_experimental.cpp in Sources */, 42AD256D1AFF9D1A000176E2 /* jsb_cocos2dx_experimental.cpp in Sources */,
B38AD56E1B1D38700057DD7F /* jsb_cocos2dx_experimental_video_auto.cpp in Sources */,
1A119EBC18BDF19200352BAA /* cocos2d_specifics.cpp in Sources */, 1A119EBC18BDF19200352BAA /* cocos2d_specifics.cpp in Sources */,
426390051B0EC1C6004C53A2 /* jsb_cocos2dx_physics3d_manual.cpp in Sources */, 426390051B0EC1C6004C53A2 /* jsb_cocos2dx_physics3d_manual.cpp in Sources */,
42638FFE1B0EC1B7004C53A2 /* jsb_cocos2dx_physics3d_auto.cpp in Sources */, 42638FFE1B0EC1B7004C53A2 /* jsb_cocos2dx_physics3d_auto.cpp in Sources */,
@ -884,6 +899,7 @@
1A119F0018BDF19200352BAA /* ScriptingCore.cpp in Sources */, 1A119F0018BDF19200352BAA /* ScriptingCore.cpp in Sources */,
BA623E09191A195F00761F37 /* jsb_pluginx_basic_conversions.cpp in Sources */, BA623E09191A195F00761F37 /* jsb_pluginx_basic_conversions.cpp in Sources */,
BA623E0D191A195F00761F37 /* jsb_pluginx_manual_callback.cpp in Sources */, BA623E0D191A195F00761F37 /* jsb_pluginx_manual_callback.cpp in Sources */,
B38AD56A1B1D384A0057DD7F /* jsb_cocos2dx_experimental_video_manual.cpp in Sources */,
1A1D3B7918C44FD000922D3C /* jsb_event_dispatcher_manual.cpp in Sources */, 1A1D3B7918C44FD000922D3C /* jsb_event_dispatcher_manual.cpp in Sources */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;

View File

@ -136,10 +136,22 @@ ccui.RichElementCustomNode.prototype._ctor = function(tag, color, opacity, custo
customNode !== undefined && this.init(tag, color, opacity, customNode); customNode !== undefined && this.init(tag, color, opacity, customNode);
}; };
ccui.WebView.prototype._ctor = function(url){ if (ccui.WebView)
this.init(); {
url !== undefined && this.loadURL(url); ccui.WebView.prototype._ctor = function(url){
}; this.init();
url !== undefined && this.loadURL(url);
};
}
if (ccui.VideoPlayer)
{
ccui.VideoPlayer.prototype._ctor = function(url){
this.init();
url !== undefined && this.setURL(url);
};
}
cc.Scale9Sprite.prototype._ctor = function(file, rect, capInsets){ cc.Scale9Sprite.prototype._ctor = function(file, rect, capInsets){
rect = rect || cc.rect(0, 0, 0, 0); rect = rect || cc.rect(0, 0, 0, 0);

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