Merge pull request #7702 from super626/v3_merge

Camera and Camera test
This commit is contained in:
minggo 2014-08-08 15:56:38 +08:00
commit 213f2f5a6c
28 changed files with 1245 additions and 21680 deletions

View File

@ -600,6 +600,10 @@
3EA2A8411987A6810077B3D4 /* CCSkeleton3D.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3EA2A83E1987A6810077B3D4 /* CCSkeleton3D.cpp */; };
3EA2A8421987A6810077B3D4 /* CCSkeleton3D.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EA2A83F1987A6810077B3D4 /* CCSkeleton3D.h */; };
3EA2A8431987A6810077B3D4 /* CCSkeleton3D.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EA2A83F1987A6810077B3D4 /* CCSkeleton3D.h */; };
3EA3EDBC1991CDFA00645534 /* CCCamera.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3EA3EDBA1991CDFA00645534 /* CCCamera.cpp */; };
3EA3EDBD1991CDFA00645534 /* CCCamera.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3EA3EDBA1991CDFA00645534 /* CCCamera.cpp */; };
3EA3EDBE1991CDFA00645534 /* CCCamera.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EA3EDBB1991CDFA00645534 /* CCCamera.h */; };
3EA3EDBF1991CDFA00645534 /* CCCamera.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EA3EDBB1991CDFA00645534 /* CCCamera.h */; };
3EA47870195478E00068D9D1 /* CCBundleReader.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3EA4786E195478E00068D9D1 /* CCBundleReader.cpp */; };
3EA47871195478E00068D9D1 /* CCBundleReader.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3EA4786E195478E00068D9D1 /* CCBundleReader.cpp */; };
3EA47872195478E00068D9D1 /* CCBundleReader.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EA4786F195478E00068D9D1 /* CCBundleReader.h */; };
@ -2479,6 +2483,8 @@
3EA0FB6A191C841D00B170C8 /* UIVideoPlayerIOS.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = UIVideoPlayerIOS.mm; sourceTree = "<group>"; };
3EA2A83E1987A6810077B3D4 /* CCSkeleton3D.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCSkeleton3D.cpp; sourceTree = "<group>"; };
3EA2A83F1987A6810077B3D4 /* CCSkeleton3D.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCSkeleton3D.h; sourceTree = "<group>"; };
3EA3EDBA1991CDFA00645534 /* CCCamera.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCCamera.cpp; path = ../base/CCCamera.cpp; sourceTree = "<group>"; };
3EA3EDBB1991CDFA00645534 /* CCCamera.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCCamera.h; path = ../base/CCCamera.h; sourceTree = "<group>"; };
3EA4786E195478E00068D9D1 /* CCBundleReader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCBundleReader.cpp; sourceTree = "<group>"; };
3EA4786F195478E00068D9D1 /* CCBundleReader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCBundleReader.h; sourceTree = "<group>"; };
464AD6E3197EBB1400E502D8 /* pvr.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = pvr.cpp; path = ../base/pvr.cpp; sourceTree = "<group>"; };
@ -3393,6 +3399,8 @@
1A5700A2180BC5E60088DEC7 /* base */ = {
isa = PBXGroup;
children = (
3EA3EDBA1991CDFA00645534 /* CCCamera.cpp */,
3EA3EDBB1991CDFA00645534 /* CCCamera.h */,
464AD6E3197EBB1400E502D8 /* pvr.cpp */,
464AD6E4197EBB1400E502D8 /* pvr.h */,
3E61781C1966A5A300DE83F5 /* CCController.cpp */,
@ -5392,6 +5400,7 @@
5034CA31191D591100CE6051 /* ccShader_PositionTexture_uColor.vert in Headers */,
50ABBE7B1925AB6F00A911A9 /* CCEventMouse.h in Headers */,
503DD8F91926B0DB00CD74DD /* CCIMEDispatcher.h in Headers */,
3EA3EDBE1991CDFA00645534 /* CCCamera.h in Headers */,
50ABBE8F1925AB6F00A911A9 /* CCPlatformConfig.h in Headers */,
50ABBE291925AB6F00A911A9 /* CCAutoreleasePool.h in Headers */,
50ABBE471925AB6F00A911A9 /* CCEvent.h in Headers */,
@ -5672,6 +5681,7 @@
1A5701A0180BCB590088DEC7 /* CCFont.h in Headers */,
50ABBD9A1925AB4100A911A9 /* CCGLProgramStateCache.h in Headers */,
50ABBD3F1925AB0000A911A9 /* CCGeometry.h in Headers */,
3EA3EDBF1991CDFA00645534 /* CCCamera.h in Headers */,
50ABBFFE1926664800A911A9 /* CCFileUtilsApple.h in Headers */,
1A5701A4180BCB590088DEC7 /* CCFontAtlas.h in Headers */,
1A5701A8180BCB590088DEC7 /* CCFontAtlasCache.h in Headers */,
@ -6719,6 +6729,7 @@
buildActionMask = 2147483647;
files = (
50ABBE2B1925AB6F00A911A9 /* ccCArray.cpp in Sources */,
3EA3EDBC1991CDFA00645534 /* CCCamera.cpp in Sources */,
1A01C68A18F57BE800EFE3A6 /* CCDeprecated.cpp in Sources */,
1A1645B0191B726C008C7C7F /* ConvertUTF.c in Sources */,
50ABBD581925AB0000A911A9 /* Vec2.cpp in Sources */,
@ -7155,6 +7166,7 @@
1A570287180BCC900088DEC7 /* CCSpriteFrame.cpp in Sources */,
1A57028B180BCC900088DEC7 /* CCSpriteFrameCache.cpp in Sources */,
1A570293180BCCAB0088DEC7 /* CCAnimation.cpp in Sources */,
3EA3EDBD1991CDFA00645534 /* CCCamera.cpp in Sources */,
1A570297180BCCAB0088DEC7 /* CCAnimationCache.cpp in Sources */,
50ABBE321925AB6F00A911A9 /* CCConfiguration.cpp in Sources */,
1A5702C9180BCE370088DEC7 /* CCTextFieldTTF.cpp in Sources */,

View File

@ -962,6 +962,8 @@
3E92EA831921A1400094CD21 /* Sprite3DTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3E92EA801921A1400094CD21 /* Sprite3DTest.cpp */; };
3E92EA851921A7720094CD21 /* Sprite3DTest in Resources */ = {isa = PBXBuildFile; fileRef = 3E92EA841921A7720094CD21 /* Sprite3DTest */; };
3E92EA861921A7720094CD21 /* Sprite3DTest in Resources */ = {isa = PBXBuildFile; fileRef = 3E92EA841921A7720094CD21 /* Sprite3DTest */; };
3E9E75D0199324CB005B7047 /* Camera3DTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3E9E75CE199324CB005B7047 /* Camera3DTest.cpp */; };
3E9E75D1199324CB005B7047 /* Camera3DTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3E9E75CE199324CB005B7047 /* Camera3DTest.cpp */; };
3EA0FB5E191B92F100B170C8 /* cocosvideo.mp4 in Resources */ = {isa = PBXBuildFile; fileRef = 3EA0FB5D191B92F100B170C8 /* cocosvideo.mp4 */; };
3EA0FB66191B933000B170C8 /* MediaPlayer.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3EA0FB65191B933000B170C8 /* MediaPlayer.framework */; };
3EA0FB72191C844400B170C8 /* UIVideoPlayerTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3EA0FB70191C844400B170C8 /* UIVideoPlayerTest.cpp */; };
@ -3648,6 +3650,8 @@
3E92EA801921A1400094CD21 /* Sprite3DTest.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = Sprite3DTest.cpp; path = Sprite3DTest/Sprite3DTest.cpp; sourceTree = "<group>"; };
3E92EA811921A1400094CD21 /* Sprite3DTest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Sprite3DTest.h; path = Sprite3DTest/Sprite3DTest.h; sourceTree = "<group>"; };
3E92EA841921A7720094CD21 /* Sprite3DTest */ = {isa = PBXFileReference; lastKnownFileType = folder; name = Sprite3DTest; path = "../tests/cpp-tests/Resources/Sprite3DTest"; sourceTree = "<group>"; };
3E9E75CE199324CB005B7047 /* Camera3DTest.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = Camera3DTest.cpp; path = Camera3DTest/Camera3DTest.cpp; sourceTree = "<group>"; };
3E9E75CF199324CB005B7047 /* Camera3DTest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Camera3DTest.h; path = Camera3DTest/Camera3DTest.h; sourceTree = "<group>"; };
3EA0FB5D191B92F100B170C8 /* cocosvideo.mp4 */ = {isa = PBXFileReference; lastKnownFileType = file; name = cocosvideo.mp4; path = "../tests/cpp-tests/Resources/cocosvideo.mp4"; sourceTree = "<group>"; };
3EA0FB65191B933000B170C8 /* MediaPlayer.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MediaPlayer.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.1.sdk/System/Library/Frameworks/MediaPlayer.framework; sourceTree = DEVELOPER_DIR; };
3EA0FB70191C844400B170C8 /* UIVideoPlayerTest.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = UIVideoPlayerTest.cpp; sourceTree = "<group>"; };
@ -6213,6 +6217,7 @@
1AC3592418CECF0A00F37B72 /* Classes */ = {
isa = PBXGroup;
children = (
3E9E75CB199324A8005B7047 /* Camera3DTest */,
1AC3592818CECF0A00F37B72 /* ActionManagerTest */,
1AC3592B18CECF0A00F37B72 /* ActionsEaseTest */,
1AC3592E18CECF0A00F37B72 /* ActionsProgressTest */,
@ -7892,6 +7897,15 @@
name = Sprite3DTest;
sourceTree = "<group>";
};
3E9E75CB199324A8005B7047 /* Camera3DTest */ = {
isa = PBXGroup;
children = (
3E9E75CE199324CB005B7047 /* Camera3DTest.cpp */,
3E9E75CF199324CB005B7047 /* Camera3DTest.h */,
);
name = Camera3DTest;
sourceTree = "<group>";
};
3EA0FB6F191C844400B170C8 /* UIVideoPlayerTest */ = {
isa = PBXGroup;
children = (
@ -9107,6 +9121,7 @@
1AC35C2718CECF0C00F37B72 /* PerformanceContainerTest.cpp in Sources */,
1AC35BEF18CECF0C00F37B72 /* CCControlSwitchTest.cpp in Sources */,
29080D91191B595E0066F8DF /* CustomGUIScene.cpp in Sources */,
3E9E75D0199324CB005B7047 /* Camera3DTest.cpp in Sources */,
29080DC1191B595E0066F8DF /* UIRichTextTest.cpp in Sources */,
1AC35B2B18CECF0C00F37B72 /* BaseTest.cpp in Sources */,
1AC35B7D18CECF0C00F37B72 /* PlayerController.cpp in Sources */,
@ -9266,6 +9281,7 @@
1AC35C1618CECF0C00F37B72 /* MenuTest.cpp in Sources */,
1AC35C6818CECF0C00F37B72 /* UserDefaultTest.cpp in Sources */,
29080D1D191B574B0066F8DF /* UITest.cpp in Sources */,
3E9E75D1199324CB005B7047 /* Camera3DTest.cpp in Sources */,
1AF152DA18FD252A00A52F3D /* PerformanceCallbackTest.cpp in Sources */,
29080DA0191B595E0066F8DF /* CustomReader.cpp in Sources */,
1AC35C2218CECF0C00F37B72 /* ParallaxTest.cpp in Sources */,

View File

@ -39,6 +39,7 @@ THE SOFTWARE.
#include "base/CCEvent.h"
#include "base/CCEventTouch.h"
#include "base/ccCArray.h"
#include "base/CCCamera.h"
#include "2d/CCGrid.h"
#include "2d/CCActionManager.h"
#include "base/CCScriptSupport.h"
@ -128,6 +129,7 @@ Node::Node(void)
, _usingNormalizedPosition(false)
, _name("")
, _hashOfName(0)
, _cameraMask(1)
{
// set default scheduler and actionManager
Director *director = Director::getInstance();
@ -1240,6 +1242,9 @@ void Node::visit(Renderer* renderer, const Mat4 &parentTransform, uint32_t paren
director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
auto camera = Camera::getVisitingCamera();
bool visibleByCamera = camera ? (unsigned short)camera->getCameraFlag() & _cameraMask : true;
int i = 0;
if(!_children.empty())
@ -1256,14 +1261,16 @@ void Node::visit(Renderer* renderer, const Mat4 &parentTransform, uint32_t paren
break;
}
// self draw
this->draw(renderer, _modelViewTransform, flags);
if (visibleByCamera)
this->draw(renderer, _modelViewTransform, flags);
for(auto it=_children.cbegin()+i; it != _children.cend(); ++it)
(*it)->visit(renderer, _modelViewTransform, flags);
}
else
{
this->draw(renderer, _modelViewTransform, flags);
if (visibleByCamera)
this->draw(renderer, _modelViewTransform, flags);
}
director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
@ -2167,6 +2174,17 @@ void Node::disableCascadeColor()
}
}
void Node::setCameraMask(unsigned short mask, bool applyChildren)
{
_cameraMask = mask;
if (applyChildren)
{
for (auto child : _children) {
child->setCameraMask(mask, applyChildren);
}
}
}
__NodeRGBA::__NodeRGBA()
{
CCLOG("NodeRGBA deprecated.");

View File

@ -1485,6 +1485,10 @@ public:
void setonExitTransitionDidStartCallback(const std::function<void()>& callback) { _onExitTransitionDidStartCallback = callback; }
const std::function<void()>& getonExitTransitionDidStartCallback() const { return _onExitTransitionDidStartCallback; }
/** get & set camera mask, the node is visible by the camera whose camera flag & node's camera mask is true */
unsigned short getCameraMask() const { return _cameraMask; }
void setCameraMask(unsigned short mask, bool applyChildren = true);
CC_CONSTRUCTOR_ACCESS:
// Nodes should be created using create();
Node();
@ -1623,6 +1627,9 @@ protected:
static int s_globalOrderOfArrival;
// camera mask, it is visible only when _cameraMask & current camera' camera flag is true
unsigned short _cameraMask;
std::function<void()> _onEnterCallback;
std::function<void()> _onExitCallback;
std::function<void()> _onEnterTransitionDidFinishCallback;

View File

@ -27,6 +27,7 @@ THE SOFTWARE.
#include "2d/CCScene.h"
#include "base/CCDirector.h"
#include "base/CCCamera.h"
#include "2d/CCLayer.h"
#include "2d/CCSprite.h"
#include "2d/CCSpriteBatchNode.h"
@ -53,6 +54,10 @@ Scene::~Scene()
bool Scene::init()
{
//create default camera
auto camera = Camera::create();
addChild(camera);
auto size = Director::getInstance()->getWinSize();
return initWithSize(size);
}
@ -179,6 +184,7 @@ void Scene::addChildToPhysicsWorld(Node* child)
addToPhysicsWorldFunc(child);
}
}
#endif
NS_CC_END

View File

@ -34,6 +34,7 @@ THE SOFTWARE.
NS_CC_BEGIN
class Camera;
/**
* @addtogroup scene
* @{
@ -64,6 +65,9 @@ public:
using Node::addChild;
virtual std::string getDescription() const override;
/** get all cameras */
const std::vector<Camera*>& getCameras() const { return _cameras; }
CC_CONSTRUCTOR_ACCESS:
Scene();
virtual ~Scene();
@ -75,6 +79,10 @@ protected:
friend class Node;
friend class ProtectedNode;
friend class SpriteBatchNode;
friend class Camera;
friend class Director;
std::vector<Camera*> _cameras; //weak ref to Camera
private:
CC_DISALLOW_COPY_AND_ASSIGN(Scene);

View File

@ -199,6 +199,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClCompile Include="..\base\atitc.cpp" />
<ClCompile Include="..\base\base64.cpp" />
<ClCompile Include="..\base\CCAutoreleasePool.cpp" />
<ClCompile Include="..\base\CCCamera.cpp" />
<ClCompile Include="..\base\ccCArray.cpp" />
<ClCompile Include="..\base\CCConfiguration.cpp" />
<ClCompile Include="..\base\CCConsole.cpp" />
@ -386,6 +387,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClInclude Include="..\base\atitc.h" />
<ClInclude Include="..\base\base64.h" />
<ClInclude Include="..\base\CCAutoreleasePool.h" />
<ClInclude Include="..\base\CCCamera.h" />
<ClInclude Include="..\base\ccCArray.h" />
<ClInclude Include="..\base\ccConfig.h" />
<ClInclude Include="..\base\CCConfiguration.h" />

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="physics">
@ -610,6 +610,9 @@
<ClCompile Include="CCProtectedNode.cpp">
<Filter>2d</Filter>
</ClCompile>
<ClCompile Include="..\base\CCCamera.cpp">
<Filter>base</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\physics\CCPhysicsBody.h">
@ -1240,6 +1243,9 @@
<ClInclude Include="CCProtectedNode.h">
<Filter>2d</Filter>
</ClInclude>
<ClInclude Include="..\base\CCCamera.h">
<Filter>base</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<None Include="..\math\Mat4.inl">

View File

@ -103,6 +103,7 @@ math/Vec2.cpp \
math/Vec3.cpp \
math/Vec4.cpp \
base/CCAutoreleasePool.cpp \
base/CCCamera.cpp \
base/CCConfiguration.cpp \
base/CCConsole.cpp \
base/CCData.cpp \

268
cocos/base/CCCamera.cpp Normal file
View File

@ -0,0 +1,268 @@
/****************************************************************************
Copyright (c) 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 "base/CCCamera.h"
#include "base/CCDirector.h"
#include "platform/CCGLView.h"
#include "2d/CCScene.h"
#include "2d/CCNode.h"
NS_CC_BEGIN
Camera* Camera::_visitingCamera = nullptr;
Camera* Camera::create()
{
Camera* camera = nullptr;
auto size = Director::getInstance()->getWinSize();
//create default camera
auto projection = Director::getInstance()->getProjection();
switch (projection)
{
case Director::Projection::_2D:
{
camera = Camera::createOrthographic(size.width, size.height, -1024, 1024);
break;
}
case Director::Projection::_3D:
{
float zeye = Director::getInstance()->getZEye();
camera = Camera::createPerspective(60, (GLfloat)size.width / size.height, 10, zeye + size.height / 2.0f);
Vec3 eye(size.width/2, size.height/2.0f, zeye), center(size.width/2, size.height/2, 0.0f), up(0.0f, 1.0f, 0.0f);
camera->setPosition3D(eye);
camera->lookAt(center, up);
break;
}
default:
CCLOG("unrecognized projection");
break;
}
return camera;
}
Camera* Camera::createPerspective(float fieldOfView, float aspectRatio, float nearPlane, float farPlane)
{
auto ret = new Camera();
if (ret)
{
ret->_fieldOfView = fieldOfView;
ret->_aspectRatio = aspectRatio;
ret->_nearPlane = nearPlane;
ret->_farPlane = farPlane;
Mat4::createPerspective(ret->_fieldOfView, ret->_aspectRatio, ret->_nearPlane, ret->_farPlane, &ret->_projection);
#if CC_TARGET_PLATFORM == CC_PLATFORM_WP8
//if needed, we need to add a rotation for Landscape orientations on Windows Phone 8 since it is always in Portrait Mode
GLView* view = Director::getInstance()->getOpenGLView();
if(view != nullptr)
{
setAdditionalProjection(view->getOrientationMatrix());
}
#endif
ret->_viewProjectionDirty = true;
ret->autorelease();
return ret;
}
CC_SAFE_DELETE(ret);
return nullptr;
}
Camera* Camera::createOrthographic(float zoomX, float zoomY, float nearPlane, float farPlane)
{
auto ret = new Camera();
if (ret)
{
ret->_zoom[0] = zoomX;
ret->_zoom[1] = zoomY;
ret->_nearPlane = nearPlane;
ret->_farPlane = farPlane;
Mat4::createOrthographic(ret->_zoom[0], ret->_zoom[1], ret->_nearPlane, ret->_farPlane, &ret->_projection);
#if CC_TARGET_PLATFORM == CC_PLATFORM_WP8
//if needed, we need to add a rotation for Landscape orientations on Windows Phone 8 since it is always in Portrait Mode
GLView* view = Director::getInstance()->getOpenGLView();
if(view != nullptr)
{
setAdditionalProjection(view->getOrientationMatrix());
}
#endif
ret->_viewProjectionDirty = true;
ret->autorelease();
return ret;
}
CC_SAFE_DELETE(ret);
return nullptr;
}
Camera::Camera()
: _cameraFlag(1)
, _scene(nullptr)
, _viewProjectionDirty(true)
{
}
Camera::~Camera()
{
}
void Camera::setPosition3D(const Vec3& position)
{
Node::setPosition3D(position);
_transformUpdated = _transformDirty = _inverseDirty = true;
}
const Mat4& Camera::getProjectionMatrix() const
{
return _projection;
}
const Mat4& Camera::getViewMatrix() const
{
Mat4 viewInv(getNodeToWorldTransform());
static int count = sizeof(float) * 16;
if (memcmp(viewInv.m, _viewInv.m, count) != 0)
{
_viewProjectionDirty = true;
_viewInv = viewInv;
_view = viewInv.getInversed();
}
return _view;
}
void Camera::lookAt(const Vec3& lookAtPos, const Vec3& up)
{
Vec3 upv = up;
upv.normalize();
Vec3 zaxis;
Vec3::subtract(this->getPosition3D(), lookAtPos, &zaxis);
zaxis.normalize();
Vec3 xaxis;
Vec3::cross(upv, zaxis, &xaxis);
xaxis.normalize();
Vec3 yaxis;
Vec3::cross(zaxis, xaxis, &yaxis);
yaxis.normalize();
Mat4 rotation;
rotation.m[0] = xaxis.x;
rotation.m[1] = xaxis.y;
rotation.m[2] = xaxis.z;
rotation.m[3] = 0;
rotation.m[4] = yaxis.x;
rotation.m[5] = yaxis.y;
rotation.m[6] = yaxis.z;
rotation.m[7] = 0;
rotation.m[8] = zaxis.x;
rotation.m[9] = zaxis.y;
rotation.m[10] = zaxis.z;
rotation.m[11] = 0;
Quaternion quaternion;
Quaternion::createFromRotationMatrix(rotation,&quaternion);
float fRoll = atan2(2 * (quaternion.w * quaternion.z + quaternion.x * quaternion.y) , 1 - 2 * (quaternion.z * quaternion.z + quaternion.x * quaternion.x));
float fPitch = asin(clampf(2 * (quaternion.w * quaternion.x - quaternion.y * quaternion.z) , -1.0f , 1.0f));
float fYaw = atan2(2 * (quaternion.w * quaternion.y + quaternion.z * quaternion.x) , 1 - 2 * (quaternion.x * quaternion.x + quaternion.y * quaternion.y));
setRotation3D(Vec3(CC_RADIANS_TO_DEGREES(fPitch),CC_RADIANS_TO_DEGREES(fYaw),CC_RADIANS_TO_DEGREES(fRoll)));
}
const Mat4& Camera::getViewProjectionMatrix() const
{
getViewMatrix();
if (_viewProjectionDirty)
{
_viewProjectionDirty = false;
Mat4::multiply(_projection, _view, &_viewProjection);
}
return _viewProjection;
}
void Camera::setAdditionalProjection(const Mat4& mat)
{
_projection = mat * _projection;
getViewProjectionMatrix();
}
void Camera::unproject(const Size& viewport, Vec3* src, Vec3* dst) const
{
assert(dst);
Vec4 screen(src->x / viewport.width, ((viewport.height - src->y)) / viewport.height, src->z, 1.0f);
screen.x = screen.x * 2.0f - 1.0f;
screen.y = screen.y * 2.0f - 1.0f;
screen.z = screen.z * 2.0f - 1.0f;
getViewProjectionMatrix().getInversed().transformVector(screen, &screen);
if (screen.w != 0.0f)
{
screen.x /= screen.w;
screen.y /= screen.w;
screen.z /= screen.w;
}
dst->set(screen.x, screen.y, screen.z);
}
void Camera::onEnter()
{
if (_scene == nullptr)
{
auto scene = getScene();
if (scene)
setScene(scene);
}
Node::onEnter();
}
void Camera::onExit()
{
// remove this camera from scene
setScene(nullptr);
Node::onExit();
}
void Camera::setScene(Scene* scene)
{
if (_scene != scene)
{
//remove old scene
if (_scene)
{
auto& cameras = _scene->_cameras;
auto it = std::find(cameras.begin(), cameras.end(), this);
if (it != cameras.end())
cameras.erase(it);
_scene = nullptr;
}
//set new scene
if (scene)
{
_scene = scene;
auto& cameras = _scene->_cameras;
auto it = std::find(cameras.begin(), cameras.end(), this);
if (it == cameras.end())
_scene->_cameras.push_back(this);
}
}
}
NS_CC_END

170
cocos/base/CCCamera.h Normal file
View File

@ -0,0 +1,170 @@
/****************************************************************************
Copyright (c) 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.
****************************************************************************/
#ifndef _CCCAMERA_H__
#define _CCCAMERA_H__
#include "base/CCVector.h"
#include "2d/CCNode.h"
NS_CC_BEGIN
//class Ray;
class Scene;
enum class CameraFlag
{
DEFAULT = 1,
USER1 = 1 << 1,
USER2 = 1 << 2,
USER3 = 1 << 3,
USER4 = 1 << 4,
USER5 = 1 << 5,
USER6 = 1 << 6,
USER7 = 1 << 7,
USER8 = 1 << 8,
};
/**
* Defines a camera .
*/
class CC_DLL Camera :public Node
{
public:
/**
* The type of camera.
*/
enum class Type
{
PERSPECTIVE = 1,
ORTHOGRAPHIC = 2
};
public:
/**
* Creates a perspective camera.
*
* @param fieldOfView The field of view for the perspective camera (normally in the range of 40-60 degrees).
* @param aspectRatio The aspect ratio of the camera (normally the width of the viewport divided by the height of the viewport).
* @param nearPlane The near plane distance.
* @param farPlane The far plane distance.
*/
static Camera* createPerspective(float fieldOfView, float aspectRatio, float nearPlane, float farPlane);
/**
* Creates an orthographic camera.
*
* @param zoomX The zoom factor along the X-axis of the orthographic projection (the width of the ortho projection).
* @param zoomY The zoom factor along the Y-axis of the orthographic projection (the height of the ortho projection).
* @param aspectRatio The aspect ratio of the orthographic projection.
* @param nearPlane The near plane distance.
* @param farPlane The far plane distance.
*/
static Camera* createOrthographic(float zoomX, float zoomY, float nearPlane, float farPlane);
/** create default camera, the camera type depends on Director::getProjection */
static Camera* create();
/**
* Gets the type of camera.
*
* @return The camera type.
*/
Camera::Type getType() const { return _type; }
/**get & set Camera flag*/
CameraFlag getCameraFlag() const { return (CameraFlag)_cameraFlag; }
void setCameraFlag(CameraFlag flag) { _cameraFlag = (unsigned short)flag; }
/**
* Sets the position (X, Y, and Z) in its parent's coordinate system
*/
virtual void setPosition3D(const Vec3& position) override;
/**
* Creates a view matrix based on the specified input parameters.
*
* @param eyePosition The eye position.
* @param targetPosition The target's center position.
* @param up The up vector.
* @param dst A matrix to store the result in.
*/
virtual void lookAt(const Vec3& target, const Vec3& up);
/**
* Gets the camera's projection matrix.
*
* @return The camera projection matrix.
*/
const Mat4& getProjectionMatrix() const;
/**
* Gets the camera's view matrix.
*
* @return The camera view matrix.
*/
const Mat4& getViewMatrix() const;
/**get view projection matrix*/
const Mat4& getViewProjectionMatrix() const;
/**
* Convert the specified point of viewport from screenspace coordinate into the worldspace coordinate.
*/
void unproject(const Size& viewport, Vec3* src, Vec3* dst) const;
//override
virtual void onEnter() override;
virtual void onExit() override;
static const Camera* getVisitingCamera() { return _visitingCamera; }
CC_CONSTRUCTOR_ACCESS:
Camera();
~Camera();
void setScene(Scene* scene);
/**set additional matrix for the projection matrix, it multiplys mat to projection matrix when called, used by WP8*/
void setAdditionalProjection(const Mat4& mat);
protected:
Scene* _scene; //Scene camera belongs to
Mat4 _projection;
mutable Mat4 _view;
mutable Mat4 _viewInv;
mutable Mat4 _viewProjection;
Vec3 _up;
Camera::Type _type;
float _fieldOfView;
float _zoom[2];
float _aspectRatio;
float _nearPlane;
float _farPlane;
mutable bool _viewProjectionDirty;
unsigned short _cameraFlag; // camera flag
static Camera* _visitingCamera;
friend class Director;
};
NS_CC_END
#endif// __CCCAMERA_H_

View File

@ -47,6 +47,7 @@ THE SOFTWARE.
#include "renderer/CCTextureCache.h"
#include "renderer/ccGLStateCache.h"
#include "renderer/CCRenderer.h"
#include "base/CCCamera.h"
#include "base/CCUserDefault.h"
#include "base/ccFPSImages.h"
#include "base/CCScheduler.h"
@ -284,25 +285,59 @@ void Director::drawScene()
pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
// draw the scene
if (_runningScene)
{
_runningScene->visit(_renderer, Mat4::IDENTITY, false);
Camera* defaultCamera = nullptr;
const auto& cameras = _runningScene->_cameras;
//draw with camera
for (size_t i = 0; i < cameras.size(); i++)
{
Camera::_visitingCamera = cameras[i];
if (Camera::_visitingCamera->getCameraFlag() == CameraFlag::DEFAULT)
{
defaultCamera = Camera::_visitingCamera;
continue;
}
pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, Camera::_visitingCamera->getViewProjectionMatrix());
//visit the scene
_runningScene->visit(_renderer, Mat4::IDENTITY, 0);
_renderer->render();
popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
}
//draw with default camera
if (defaultCamera)
{
Camera::_visitingCamera = defaultCamera;
pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, Camera::_visitingCamera->getViewProjectionMatrix());
//visit the scene
_runningScene->visit(_renderer, Mat4::IDENTITY, 0);
_renderer->render();
popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
}
Camera::_visitingCamera = nullptr;
_eventDispatcher->dispatchEvent(_eventAfterVisit);
}
// draw the notifications node
if (_notificationNode)
{
_notificationNode->visit(_renderer, Mat4::IDENTITY, false);
_notificationNode->visit(_renderer, Mat4::IDENTITY, 0);
}
if (_displayStats)
{
showStats();
}
_renderer->render();
_eventDispatcher->dispatchEvent(_eventAfterDraw);
popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);

View File

@ -61,6 +61,7 @@ class EventCustom;
class EventListenerCustom;
class TextureCache;
class Renderer;
class Camera;
#if (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT)
class Console;

View File

@ -1,5 +1,6 @@
set(COCOS_BASE_SRC
base/CCAutoreleasePool.cpp
base/CCCamera.cpp
base/CCConfiguration.cpp
base/CCConsole.cpp
base/CCData.cpp

View File

@ -61,6 +61,7 @@ THE SOFTWARE.
#include "base/CCIMEDelegate.h"
#include "base/CCIMEDispatcher.h"
#include "base/ccUtils.h"
#include "base/CCCamera.h"
// EventDispatcher
#include "base/CCEventType.h"

View File

@ -283,6 +283,8 @@
"cocos/audio/wp8/SimpleAudioEngine.cpp",
"cocos/base/CCAutoreleasePool.cpp",
"cocos/base/CCAutoreleasePool.h",
"cocos/base/CCCamera.cpp",
"cocos/base/CCCamera.h",
"cocos/base/CCConfiguration.cpp",
"cocos/base/CCConfiguration.h",
"cocos/base/CCConsole.cpp",

View File

@ -33,6 +33,7 @@ Classes/BugsTest/BugsTest.cpp \
Classes/BugsTest/Bug-Child.cpp \
Classes/BugsTest/Bug-458/Bug-458.cpp \
Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp \
Classes/Camera3DTest/Camera3DTest.cpp \
Classes/ChipmunkTest/ChipmunkTest.cpp \
Classes/ClickAndMoveTest/ClickAndMoveTest.cpp \
Classes/ClippingNodeTest/ClippingNodeTest.cpp \

View File

@ -35,6 +35,7 @@ set(SAMPLE_SRC
Classes/BugsTest/Bug-914.cpp
Classes/BugsTest/BugsTest.cpp
Classes/BugsTest/Bug-Child.cpp
Classes/Camera3DTest/Camera3DTest.cpp
Classes/ChipmunkTest/ChipmunkTest.cpp
Classes/ClickAndMoveTest/ClickAndMoveTest.cpp
Classes/ClippingNodeTest/ClippingNodeTest.cpp

View File

@ -0,0 +1,568 @@
/****************************************************************************
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 "Camera3DTest.h"
#include <algorithm>
#include "../testResource.h"
#include "3d/CCAttachNode.h"
////////////DrawLine/////////////////////
class DrawLine3D: public Node
{
public:
/** creates and initialize a node */
static DrawLine3D* create();
/**
* Draw 3D Line
*/
void drawLine(const Vec3 &from, const Vec3 &to, const Color4F &color);
/** Clear the geometry in the node's buffer. */
void clear()
{
_buffer.clear();
}
void onDraw(const Mat4 &transform, uint32_t flags);
// Overrides
virtual void draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) override;
CC_CONSTRUCTOR_ACCESS:
DrawLine3D()
{
}
virtual ~DrawLine3D()
{
}
virtual bool init();
protected:
struct V3F_C4B
{
Vec3 vertices;
Color4B colors;
};
std::vector<V3F_C4B> _buffer;
CustomCommand _customCommand;
private:
CC_DISALLOW_COPY_AND_ASSIGN(DrawLine3D);
};
DrawLine3D* DrawLine3D::create()
{
auto ret = new DrawLine3D();
if (ret && ret->init())
return ret;
CC_SAFE_DELETE(ret);
return nullptr;
}
bool DrawLine3D::init()
{
setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_COLOR));
return true;
}
void DrawLine3D::drawLine(const Vec3 &from, const Vec3 &to, const Color4F &color)
{
Color4B col = Color4B(color);
DrawLine3D::V3F_C4B vertex;
vertex.vertices = from;
vertex.colors = col;
_buffer.push_back(vertex);
vertex.vertices = to;
_buffer.push_back(vertex);
}
void DrawLine3D::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
{
_customCommand.init(_globalZOrder);
_customCommand.func = CC_CALLBACK_0(DrawLine3D::onDraw, this, transform, flags);
renderer->addCommand(&_customCommand);
}
void DrawLine3D::onDraw(const Mat4 &transform, uint32_t flags)
{
auto glProgram = getGLProgram();
glProgram->use();
glProgram->setUniformsForBuiltins(transform);
glEnable(GL_DEPTH_TEST);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_POSITION);
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, sizeof(V3F_C4B), &(_buffer[0].vertices));
glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_COLOR);
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(V3F_C4B), &(_buffer[0].colors));
glDrawArrays(GL_LINES, 0, _buffer.size());
glDisable(GL_DEPTH_TEST);
}
////////////////////////////////////////////////////////////////////////////////
enum
{
IDC_NEXT = 100,
IDC_BACK,
IDC_RESTART
};
static int sceneIdx = -1;
static std::function<Layer*()> createFunctions[] =
{
CL(Camera3DTestDemo),
};
#define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0]))
static Layer* nextSpriteTestAction()
{
sceneIdx++;
sceneIdx = sceneIdx % MAX_LAYER;
auto layer = (createFunctions[sceneIdx])();
return layer;
}
static Layer* backSpriteTestAction()
{
sceneIdx--;
int total = MAX_LAYER;
if( sceneIdx < 0 )
sceneIdx += total;
auto layer = (createFunctions[sceneIdx])();
return layer;
}
static Layer* restartSpriteTestAction()
{
auto layer = (createFunctions[sceneIdx])();
return layer;
}
//------------------------------------------------------------------
//
// SpriteTestDemo
//
//------------------------------------------------------------------
Camera3DTestDemo::Camera3DTestDemo(void)
: BaseTest()
, _camera(nullptr)
{
}
Camera3DTestDemo::~Camera3DTestDemo(void)
{
}
void Camera3DTestDemo::reachEndCallBack()
{
}
std::string Camera3DTestDemo::title() const
{
return "Testing Camera";
}
std::string Camera3DTestDemo::subtitle() const
{
return "";
}
void Camera3DTestDemo::scaleCameraCallback(Ref* sender,float value)
{
if(_camera&& _cameraType!=CameraType::FirstCamera)
{
Vec3 cameraPos= _camera->getPosition3D();
cameraPos+= cameraPos.getNormalized()*value;
_camera->setPosition3D(cameraPos);
}
}
void Camera3DTestDemo::rotateCameraCallback(Ref* sender,float value)
{
if(_cameraType==CameraType::FreeCamera || _cameraType==CameraType::FirstCamera)
{
Vec3 rotation3D= _camera->getRotation3D();
rotation3D.y+= value;
_camera->setRotation3D(rotation3D);
}
}
void Camera3DTestDemo::SwitchViewCallback(Ref* sender, CameraType cameraType)
{
if(_cameraType==cameraType)
{
return ;
}
_cameraType = cameraType;
if(_cameraType==CameraType::FreeCamera)
{
_camera->setPosition3D(Vec3(0, 130, 130) + _sprite3D->getPosition3D());
_camera->lookAt(_sprite3D->getPosition3D(), Vec3(0,1,0));
}
else if(_cameraType==CameraType::FirstCamera)
{
Vec3 newFaceDir;
_sprite3D->getWorldToNodeTransform().getForwardVector(&newFaceDir);
newFaceDir.normalize();
_camera->setPosition3D(Vec3(0,35,0) + _sprite3D->getPosition3D());
_camera->lookAt(_sprite3D->getPosition3D() + newFaceDir*50, Vec3(0, 1, 0));
}
else if(_cameraType==CameraType::ThirdCamera)
{
_camera->setPosition3D(Vec3(0, 130, 130) + _sprite3D->getPosition3D());
_camera->lookAt(_sprite3D->getPosition3D(), Vec3(0,1,0));
}
}
void Camera3DTestDemo::onEnter()
{
BaseTest::onEnter();
_sprite3D=nullptr;
auto s = Director::getInstance()->getWinSize();
auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = CC_CALLBACK_2(Camera3DTestDemo::onTouchesBegan, this);
listener->onTouchesMoved = CC_CALLBACK_2(Camera3DTestDemo::onTouchesMoved, this);
listener->onTouchesEnded = CC_CALLBACK_2(Camera3DTestDemo::onTouchesEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
auto layer3D=Layer::create();
addChild(layer3D,0);
_layer3D=layer3D;
_curState=State_None;
addNewSpriteWithCoords( Vec3(0,0,0),"Sprite3DTest/girl.c3b",true,0.2,true);
TTFConfig ttfConfig("fonts/arial.ttf", 20);
auto label1 = Label::createWithTTF(ttfConfig,"zoom out");
auto menuItem1 = MenuItemLabel::create(label1, CC_CALLBACK_1(Camera3DTestDemo::scaleCameraCallback,this,1));
auto label2 = Label::createWithTTF(ttfConfig,"zoom in");
auto menuItem2 = MenuItemLabel::create(label2, CC_CALLBACK_1(Camera3DTestDemo::scaleCameraCallback,this,-1));
auto label3 = Label::createWithTTF(ttfConfig,"rotate+");
auto menuItem3 = MenuItemLabel::create(label3, CC_CALLBACK_1(Camera3DTestDemo::rotateCameraCallback,this,10));
auto label4 = Label::createWithTTF(ttfConfig,"rotate-");
auto menuItem4 = MenuItemLabel::create(label4, CC_CALLBACK_1(Camera3DTestDemo::rotateCameraCallback,this,-10));
auto label5 = Label::createWithTTF(ttfConfig,"free ");
auto menuItem5 = MenuItemLabel::create(label5, CC_CALLBACK_1(Camera3DTestDemo::SwitchViewCallback,this,CameraType::FreeCamera));
auto label6 = Label::createWithTTF(ttfConfig,"third person");
auto menuItem6 = MenuItemLabel::create(label6, CC_CALLBACK_1(Camera3DTestDemo::SwitchViewCallback,this,CameraType::ThirdCamera));
auto label7 = Label::createWithTTF(ttfConfig,"first person");
auto menuItem7 = MenuItemLabel::create(label7, CC_CALLBACK_1(Camera3DTestDemo::SwitchViewCallback,this,CameraType::FirstCamera));
auto menu = Menu::create(menuItem1,menuItem2,menuItem3,menuItem4,menuItem5,menuItem6,menuItem7,NULL);
menu->setPosition(Vec2::ZERO);
menuItem1->setPosition( Vec2( s.width-50, VisibleRect::top().y-50 ) );
menuItem2->setPosition( Vec2( s.width-50, VisibleRect::top().y-100) );
menuItem3->setPosition( Vec2( s.width-50, VisibleRect::top().y-150) );
menuItem4->setPosition( Vec2( s.width-50, VisibleRect::top().y-200) );
menuItem5->setPosition( Vec2(VisibleRect::left().x+100, VisibleRect::top().y-50) );
menuItem6->setPosition( Vec2(VisibleRect::left().x+100, VisibleRect::top().y -100));
menuItem7->setPosition( Vec2(VisibleRect::left().x+100, VisibleRect::top().y -150));
addChild(menu, 0);
schedule(schedule_selector(Camera3DTestDemo::updateCamera), 0.0f);
if (_camera == nullptr)
{
_camera=Camera::createPerspective(60, (GLfloat)s.width/s.height, 1, 1000);
_camera->setCameraFlag(CameraFlag::USER1);
_layer3D->addChild(_camera);
}
SwitchViewCallback(this,CameraType::ThirdCamera);
DrawLine3D* line =DrawLine3D::create();
//draw x
for( int j =-20; j<=20 ;j++)
{
line->drawLine(Vec3(-100, 0, 5*j),Vec3(100,0,5*j),Color4F(1,0,0,1));
}
//draw z
for( int j =-20; j<=20 ;j++)
{
line->drawLine(Vec3(5*j, 0, -100),Vec3(5*j,0,100),Color4F(0,0,1,1));
}
//draw y
line->drawLine(Vec3(0, -50, 0),Vec3(0,0,0),Color4F(0,0.5,0,1));
line->drawLine(Vec3(0, 0, 0),Vec3(0,50,0),Color4F(0,1,0,1));
_layer3D->addChild(line);
_layer3D->setCameraMask(2);
}
void Camera3DTestDemo::onExit()
{
BaseTest::onExit();
if (_camera)
{
_camera = nullptr;
}
}
void Camera3DTestDemo::restartCallback(Ref* sender)
{
auto s = new Camera3DTestScene();
s->addChild(restartSpriteTestAction());
Director::getInstance()->replaceScene(s);
s->release();
}
void Camera3DTestDemo::nextCallback(Ref* sender)
{
auto s = new Camera3DTestScene();
s->addChild( nextSpriteTestAction() );
Director::getInstance()->replaceScene(s);
s->release();
}
void Camera3DTestDemo::backCallback(Ref* sender)
{
auto s = new Camera3DTestScene();
s->addChild( backSpriteTestAction() );
Director::getInstance()->replaceScene(s);
s->release();
}
void Camera3DTestDemo::addNewSpriteWithCoords(Vec3 p,std::string fileName,bool playAnimation,float scale,bool bindCamera)
{
auto sprite = Sprite3D::create(fileName);
sprite->setScale(1);
_layer3D->addChild(sprite);
float globalZOrder=sprite->getGlobalZOrder();
sprite->setPosition3D( Vec3( p.x, p.y,p.z) );
sprite->setGlobalZOrder(globalZOrder);
if(playAnimation)
{
auto animation = Animation3D::create(fileName,"Take 001");
if (animation)
{
auto animate = Animate3D::create(animation);
bool inverse = (std::rand() % 3 == 0);
int rand2 = std::rand();
float speed = 1.0f;
if(rand2 % 3 == 1)
{
speed = animate->getSpeed() + CCRANDOM_0_1();
}
else if(rand2 % 3 == 2)
{
speed = animate->getSpeed() - 0.5 * CCRANDOM_0_1();
}
animate->setSpeed(inverse ? -speed : speed);
sprite->runAction(RepeatForever::create(animate));
//auto sp = Sprite3D::create("Sprite3DTest/axe.c3b");
// sprite->getAttachNode("Bip001 R Hand")->addChild(sp);
}
}
if(bindCamera)
{
_sprite3D=sprite;
// auto sp = Sprite3D::create("Sprite3DTest/axe.c3b");
// sp->setScale(3);
//sprite->getAttachNode("Bip001 R Hand")->addChild(sp);
//ParticleSystem3D* particleSystem3D = ParticleSystem3D::create("CameraTest/particle3Dtest1.particle");
//particleSystem3D->start();
//sprite->getAttachNode("Bip001 R Hand")->addChild(particleSystem3D);
}
sprite->setScale(scale);
}
void Camera3DTestDemo::onTouchesBegan(const std::vector<Touch*>& touches, cocos2d::Event *event)
{
for ( auto &item: touches )
{
auto touch = item;
auto location = touch->getLocation();
}
}
void Camera3DTestDemo::onTouchesMoved(const std::vector<Touch*>& touches, cocos2d::Event *event)
{
if(touches.size()==1)
{
auto touch = touches[0];
auto location = touch->getLocation();
Point newPos = touch->getPreviousLocation()-location;
if(_cameraType==CameraType::FreeCamera || _cameraType==CameraType::FirstCamera)
{
Vec3 cameraDir;
Vec3 cameraRightDir;
_camera->getNodeToWorldTransform().getForwardVector(&cameraDir);
cameraDir.normalize();
cameraDir.y=0;
_camera->getNodeToWorldTransform().getRightVector(&cameraRightDir);
cameraRightDir.normalize();
cameraRightDir.y=0;
Vec3 cameraPos= _camera->getPosition3D();
cameraPos+=cameraDir*newPos.y*0.1;
cameraPos+=cameraRightDir*newPos.x*0.1;
_camera->setPosition3D(cameraPos);
if(_sprite3D && _cameraType==CameraType::FirstCamera)
{
_sprite3D->setPosition3D(Vec3(_camera->getPositionX(),0,_camera->getPositionZ()));
_targetPos=_sprite3D->getPosition3D();
}
}
}
}
void Camera3DTestDemo::move3D(float elapsedTime)
{
if(_sprite3D)
{
Vec3 curPos= _sprite3D->getPosition3D();
Vec3 newFaceDir = _targetPos - curPos;
newFaceDir.y = 0.0f;
newFaceDir.normalize();
Vec3 offset = newFaceDir * 25.0f * elapsedTime;
curPos+=offset;
_sprite3D->setPosition3D(curPos);
offset.x=offset.x;
offset.z=offset.z;
if(_cameraType==CameraType::ThirdCamera)
{
Vec3 cameraPos= _camera->getPosition3D();
cameraPos.x+=offset.x;
cameraPos.z+=offset.z;
_camera->setPosition3D(cameraPos);
}
}
}
void Camera3DTestDemo::updateState(float elapsedTime)
{
if(_sprite3D)
{
Vec3 curPos= _sprite3D->getPosition3D();
Vec3 curFaceDir;
_sprite3D->getNodeToWorldTransform().getForwardVector(&curFaceDir);
curFaceDir=-curFaceDir;
curFaceDir.normalize();
Vec3 newFaceDir = _targetPos - curPos;
newFaceDir.y = 0.0f;
newFaceDir.normalize();
float cosAngle = std::fabs(Vec3::dot(curFaceDir,newFaceDir) - 1.0f);
float dist = curPos.distanceSquared(_targetPos);
if(dist<=4.0f)
{
if(cosAngle<=0.01f)
_curState = State_Idle;
else
_curState = State_Rotate;
}
else
{
if(cosAngle>0.01f)
_curState = State_Rotate | State_Move;
else
_curState = State_Move;
}
}
}
void Camera3DTestDemo::onTouchesEnded(const std::vector<Touch*>& touches, cocos2d::Event *event)
{
for ( auto &item: touches )
{
auto touch = item;
auto location = touch->getLocationInView();
if(_camera)
{
if(_sprite3D && _cameraType==CameraType::ThirdCamera)
{
Vec3 nearP(location.x, location.y, -1.0f), farP(location.x, location.y, 1.0f);
auto size = Director::getInstance()->getWinSize();
_camera->unproject(size, &nearP, &nearP);
_camera->unproject(size, &farP, &farP);
Vec3 dir(farP - nearP);
float dist=0.0f;
float ndd = Vec3::dot(Vec3(0,1,0),dir);
if(ndd == 0)
dist=0.0f;
float ndo = Vec3::dot(Vec3(0,1,0),nearP);
dist= (0 - ndo) / ndd;
Vec3 p = nearP + dist * dir;
_targetPos=p;
}
}
}
}
void onTouchesCancelled(const std::vector<Touch*>& touches, cocos2d::Event *event)
{
}
void Camera3DTestDemo::updateCamera(float fDelta)
{
if(_sprite3D)
{
if( _cameraType==CameraType::ThirdCamera)
{
updateState(fDelta);
if(isState(_curState,State_Move))
{
move3D(fDelta);
if(isState(_curState,State_Rotate))
{
Vec3 curPos = _sprite3D->getPosition3D();
Vec3 newFaceDir = _targetPos - curPos;
newFaceDir.y = 0;
newFaceDir.normalize();
Vec3 up;
_sprite3D->getNodeToWorldTransform().getUpVector(&up);
up.normalize();
Vec3 right;
Vec3::cross(-newFaceDir,up,&right);
right.normalize();
Vec3 pos = Vec3(0,0,0);
Mat4 mat;
mat.m[0] = right.x;
mat.m[1] = right.y;
mat.m[2] = right.z;
mat.m[3] = 0.0f;
mat.m[4] = up.x;
mat.m[5] = up.y;
mat.m[6] = up.z;
mat.m[7] = 0.0f;
mat.m[8] = newFaceDir.x;
mat.m[9] = newFaceDir.y;
mat.m[10] = newFaceDir.z;
mat.m[11] = 0.0f;
mat.m[12] = pos.x;
mat.m[13] = pos.y;
mat.m[14] = pos.z;
mat.m[15] = 1.0f;
_sprite3D->setAdditionalTransform(&mat);
}
}
}
}
}
bool Camera3DTestDemo::isState(unsigned int state,unsigned int bit) const
{
return (state & bit) == bit;
}
void Camera3DTestScene::runThisTest()
{
auto layer = nextSpriteTestAction();
addChild(layer);
Director::getInstance()->replaceScene(this);
}

View File

@ -0,0 +1,95 @@
/****************************************************************************
Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef _CAMERA3D_TEST_H_
#define _CAMERA3D_TEST_H_
#include "../testBasic.h"
#include "../BaseTest.h"
#include <string>
#include "base/CCCamera.h"
namespace cocos2d {
class Sprite3D;
class Delay;
}
enum State
{
State_None = 0,
State_Idle = 0x01,
State_Move = 0x02,
State_Rotate = 0x04,
State_Speak = 0x08,
State_MeleeAttack = 0x10,
State_RemoteAttack = 0x20,
State_Attack = 0x40,
};
enum class CameraType
{
FreeCamera=0,
FirstCamera=1,
ThirdCamera=2,
};
class Camera3DTestDemo : public BaseTest
{
public:
CREATE_FUNC(Camera3DTestDemo);
Camera3DTestDemo(void);
virtual ~Camera3DTestDemo(void);
void restartCallback(Ref* sender);
void nextCallback(Ref* sender);
void backCallback(Ref* sender);
virtual void onEnter() override;
virtual void onExit() override;
// overrides
virtual std::string title() const override;
virtual std::string subtitle() const override;
void addNewSpriteWithCoords(Vec3 p,std::string fileName,bool playAnimation=false,float scale=1.0f,bool bindCamera=false);
void onTouchesBegan(const std::vector<Touch*>& touches, cocos2d::Event *event);
void onTouchesMoved(const std::vector<Touch*>& touches, cocos2d::Event *event);
void onTouchesEnded(const std::vector<Touch*>& touches, cocos2d::Event *event);
void scaleCameraCallback(Ref* sender,float value);
void rotateCameraCallback(Ref* sender,float value);
void SwitchViewCallback(Ref* sender,CameraType cameraType);
void updateCamera(float fDelta);
void move3D(float elapsedTime);
void updateState(float elapsedTime);
bool isState(unsigned int state,unsigned int bit) const;
void reachEndCallBack();
protected:
std::string _title;
Layer* _layer3D;
Sprite3D* _sprite3D;
Vec3 _targetPos;
CameraType _cameraType;
unsigned int _curState;
Camera* _camera;
MoveTo* _moveAction;
};
class Camera3DTestScene : public TestScene
{
public:
virtual void runThisTest();
};
#endif

View File

@ -76,6 +76,7 @@ Controller g_aTestNames[] = {
{ "Node: Spine", []() { return new SpineTestScene(); } },
{ "Node: Sprite", [](){return new SpriteTestScene(); } },
{ "Node: Sprite3D", [](){ return new Sprite3DTestScene(); }},
{ "Node: Camera 3D Test", [](){ return new Camera3DTestScene(); }},
{ "Node: TileMap", [](){return new TileMapTestScene(); } },
#if CC_TARGET_PLATFORM != CC_PLATFORM_WP8
{ "Node: FastTileMap", [](){return new TileMapTestSceneNew(); } },

View File

@ -69,5 +69,6 @@
#include "ReleasePoolTest/ReleasePoolTest.h"
#include "Sprite3DTest/Sprite3DTest.h"
#include "Camera3DTest/Camera3DTest.h"
#endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -140,6 +140,7 @@
<ItemGroup>
<ClCompile Include="..\Classes\BaseTest.cpp" />
<ClCompile Include="..\Classes\BugsTest\Bug-Child.cpp" />
<ClCompile Include="..\Classes\Camera3DTest\Camera3DTest.cpp" />
<ClCompile Include="..\Classes\ChipmunkTest\ChipmunkTest.cpp" />
<ClCompile Include="..\Classes\ClippingNodeTest\ClippingNodeTest.cpp" />
<ClCompile Include="..\Classes\ConfigurationTest\ConfigurationTest.cpp" />
@ -323,6 +324,7 @@
<ClInclude Include="..\Classes\Box2DTestBed\Tests\MobileBalanced.h" />
<ClInclude Include="..\Classes\Box2DTestBed\Tests\MotorJoint.h" />
<ClInclude Include="..\Classes\BugsTest\Bug-Child.h" />
<ClInclude Include="..\Classes\Camera3DTest\Camera3DTest.h" />
<ClInclude Include="..\Classes\ChipmunkTest\ChipmunkTest.h" />
<ClInclude Include="..\Classes\ClippingNodeTest\ClippingNodeTest.h" />
<ClInclude Include="..\Classes\ConfigurationTest\ConfigurationTest.h" />

View File

@ -328,6 +328,9 @@
<Filter Include="Classes\ExtensionsTest\CocoStudioActionTimelineTest">
<UniqueIdentifier>{fa88df83-76d7-4f41-ad48-801dafd44889}</UniqueIdentifier>
</Filter>
<Filter Include="Classes\Camera3DTest">
<UniqueIdentifier>{7f85be1c-98c5-4412-afc5-6f39ae1452a7}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="main.cpp">
@ -858,6 +861,9 @@
<ClCompile Include="..\Classes\UITest\CocoStudioGUITest\UIScale9SpriteTest.cpp">
<Filter>Classes\UITest\CocostudioGUISceneTest</Filter>
</ClCompile>
<ClCompile Include="..\Classes\Camera3DTest\Camera3DTest.cpp">
<Filter>Classes\Camera3DTest</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="main.h">
@ -1586,5 +1592,8 @@
<ClInclude Include="..\Classes\UITest\CocoStudioGUITest\UIScale9SpriteTest.h">
<Filter>Classes\UITest\CocostudioGUISceneTest</Filter>
</ClInclude>
<ClInclude Include="..\Classes\Camera3DTest\Camera3DTest.h">
<Filter>Classes\Camera3DTest</Filter>
</ClInclude>
</ItemGroup>
</Project>

@ -1 +1 @@
Subproject commit 65e93f5d573f203c2a193d038f831ae635ac3e9d
Subproject commit 5db5a4283aa22e362901e2924146ad66c2e1484f

View File

@ -26,7 +26,7 @@ headers = %(cocosdir)s/cocos/cocos2d.h %(cocosdir)s/cocos/2d/CCProtectedNode.h %
# what classes to produce code for. You can use regular expressions here. When testing the regular
# expression, it will be enclosed in "^$", like this: "^Menu*$".
classes = New.* Sprite.* Scene Node.* Director Layer.* Menu.* Touch .*Action.* Move.* Rotate.* Blink.* Tint.* Sequence Repeat.* Fade.* Ease.* Scale.* Transition.* Spawn Animat.* Flip.* Delay.* Skew.* Jump.* Place.* Show.* Progress.* PointArray ToggleVisibility.* RemoveSelf Hide Particle.* Label.* Atlas.* TextureCache.* Texture2D Cardinal.* CatmullRom.* ParallaxNode TileMap.* .*TMX.* CallFunc RenderTexture GridAction Grid3DAction GridBase$ .+Grid Shaky3D Waves3D FlipX3D FlipY3D Speed ActionManager Set Scheduler Timer Orbit.* Follow.* Bezier.* CardinalSpline.* Camera.* DrawNode .*3D$ Liquid$ Waves$ ShuffleTiles$ TurnOffTiles$ Split.* Twirl$ FileUtils$ GLProgram ShaderCache Application ClippingNode MotionStreak ^Ref$ UserDefault GLViewImpl GLView Image Event(?!.*(Physics).*).* Component ProtectedNode Console Mesh GLProgramCache GLProgramState SubMeshState AttachNode
classes = New.* Sprite.* Scene Node.* Director Layer.* Menu.* Touch .*Action.* Move.* Rotate.* Blink.* Tint.* Sequence Repeat.* Fade.* Ease.* Scale.* Transition.* Spawn Animat.* Flip.* Delay.* Skew.* Jump.* Place.* Show.* Progress.* PointArray ToggleVisibility.* RemoveSelf Hide Particle.* Label.* Atlas.* TextureCache.* Texture2D Cardinal.* CatmullRom.* ParallaxNode TileMap.* .*TMX.* CallFunc RenderTexture GridAction Grid3DAction GridBase$ .+Grid Shaky3D Waves3D FlipX3D FlipY3D Speed ActionManager Set Scheduler Timer Orbit.* Follow.* Bezier.* CardinalSpline.* Camera.* DrawNode .*3D$ Liquid$ Waves$ ShuffleTiles$ TurnOffTiles$ Split.* Twirl$ FileUtils$ GLProgram ShaderCache Application ClippingNode MotionStreak ^Ref$ UserDefault GLViewImpl GLView Image Event(?!.*(Physics).*).* Component ProtectedNode Console Mesh GLProgramCache GLProgramState SubMeshState AttachNode Camera
# what should we skip? in the format ClassName::[function function]
# ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also
@ -132,7 +132,8 @@ skip = Node::[setGLServerState description getUserObject .*UserData getGLServerS
Animation3D::[getBoneCurveByName],
Animation3DCache::[*],
Sprite3DMaterialCache::[*],
Bone3D::[*]
Bone3D::[*],
Scene::[getCameras]
rename_functions = SpriteFrameCache::[addSpriteFramesWithFile=addSpriteFrames getSpriteFrameByName=getSpriteFrame],
ProgressTimer::[setReverseProgress=setReverseDirection],