CCCamera.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. /****************************************************************************
  2. Copyright (c) 2014-2017 Chukong Technologies Inc.
  3. http://www.cocos2d-x.org
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. Code based GamePlay3D's Camera: http://gameplay3d.org
  20. ****************************************************************************/
  21. #include "2d/CCCamera.h"
  22. #include "2d/CCCameraBackgroundBrush.h"
  23. #include "base/CCDirector.h"
  24. #include "platform/CCGLView.h"
  25. #include "2d/CCScene.h"
  26. #include "renderer/CCRenderer.h"
  27. #include "renderer/CCQuadCommand.h"
  28. #include "renderer/CCGLProgramCache.h"
  29. #include "renderer/ccGLStateCache.h"
  30. #include "renderer/CCFrameBuffer.h"
  31. #include "renderer/CCRenderState.h"
  32. NS_CC_BEGIN
  33. Camera* Camera::_visitingCamera = nullptr;
  34. experimental::Viewport Camera::_defaultViewport;
  35. // start static methods
  36. Camera* Camera::create()
  37. {
  38. Camera* camera = new (std::nothrow) Camera();
  39. camera->initDefault();
  40. camera->autorelease();
  41. camera->setDepth(0.f);
  42. return camera;
  43. }
  44. Camera* Camera::createPerspective(float fieldOfView, float aspectRatio, float nearPlane, float farPlane)
  45. {
  46. auto ret = new (std::nothrow) Camera();
  47. if (ret)
  48. {
  49. ret->initPerspective(fieldOfView, aspectRatio, nearPlane, farPlane);
  50. ret->autorelease();
  51. return ret;
  52. }
  53. CC_SAFE_DELETE(ret);
  54. return nullptr;
  55. }
  56. Camera* Camera::createOrthographic(float zoomX, float zoomY, float nearPlane, float farPlane)
  57. {
  58. auto ret = new (std::nothrow) Camera();
  59. if (ret)
  60. {
  61. ret->initOrthographic(zoomX, zoomY, nearPlane, farPlane);
  62. ret->autorelease();
  63. return ret;
  64. }
  65. CC_SAFE_DELETE(ret);
  66. return nullptr;
  67. }
  68. Camera* Camera::getDefaultCamera()
  69. {
  70. auto scene = Director::getInstance()->getRunningScene();
  71. if(scene)
  72. {
  73. return scene->getDefaultCamera();
  74. }
  75. return nullptr;
  76. }
  77. const experimental::Viewport& Camera::getDefaultViewport()
  78. {
  79. return _defaultViewport;
  80. }
  81. void Camera::setDefaultViewport(const experimental::Viewport& vp)
  82. {
  83. _defaultViewport = vp;
  84. }
  85. const Camera* Camera::getVisitingCamera()
  86. {
  87. return _visitingCamera;
  88. }
  89. // end static methods
  90. Camera::Camera()
  91. : _scene(nullptr)
  92. , _viewProjectionDirty(true)
  93. , _cameraFlag(1)
  94. , _frustumDirty(true)
  95. , _viewProjectionUpdated(false)
  96. , _depth(-1)
  97. , _fbo(nullptr)
  98. {
  99. _frustum.setClipZ(true);
  100. _clearBrush = CameraBackgroundBrush::createDepthBrush(1.f);
  101. _clearBrush->retain();
  102. }
  103. Camera::~Camera()
  104. {
  105. CC_SAFE_RELEASE_NULL(_fbo);
  106. CC_SAFE_RELEASE(_clearBrush);
  107. }
  108. const Mat4& Camera::getProjectionMatrix() const
  109. {
  110. return _projection;
  111. }
  112. const Mat4& Camera::getViewMatrix() const
  113. {
  114. Mat4 viewInv(getNodeToWorldTransform());
  115. static int count = sizeof(float) * 16;
  116. if (memcmp(viewInv.m, _viewInv.m, count) != 0)
  117. {
  118. _viewProjectionDirty = true;
  119. _frustumDirty = true;
  120. _viewInv = viewInv;
  121. _view = viewInv.getInversed();
  122. }
  123. return _view;
  124. }
  125. void Camera::lookAt(const Vec3& lookAtPos, const Vec3& up)
  126. {
  127. Vec3 upv = up;
  128. upv.normalize();
  129. Vec3 zaxis;
  130. Vec3::subtract(this->getPosition3D(), lookAtPos, &zaxis);
  131. zaxis.normalize();
  132. Vec3 xaxis;
  133. Vec3::cross(upv, zaxis, &xaxis);
  134. xaxis.normalize();
  135. Vec3 yaxis;
  136. Vec3::cross(zaxis, xaxis, &yaxis);
  137. yaxis.normalize();
  138. Mat4 rotation;
  139. rotation.m[0] = xaxis.x;
  140. rotation.m[1] = xaxis.y;
  141. rotation.m[2] = xaxis.z;
  142. rotation.m[3] = 0;
  143. rotation.m[4] = yaxis.x;
  144. rotation.m[5] = yaxis.y;
  145. rotation.m[6] = yaxis.z;
  146. rotation.m[7] = 0;
  147. rotation.m[8] = zaxis.x;
  148. rotation.m[9] = zaxis.y;
  149. rotation.m[10] = zaxis.z;
  150. rotation.m[11] = 0;
  151. Quaternion quaternion;
  152. Quaternion::createFromRotationMatrix(rotation,&quaternion);
  153. quaternion.normalize();
  154. setRotationQuat(quaternion);
  155. }
  156. const Mat4& Camera::getViewProjectionMatrix() const
  157. {
  158. getViewMatrix();
  159. if (_viewProjectionDirty)
  160. {
  161. _viewProjectionDirty = false;
  162. Mat4::multiply(_projection, _view, &_viewProjection);
  163. }
  164. return _viewProjection;
  165. }
  166. void Camera::setAdditionalProjection(const Mat4& mat)
  167. {
  168. _projection = mat * _projection;
  169. getViewProjectionMatrix();
  170. }
  171. bool Camera::initDefault()
  172. {
  173. auto size = Director::getInstance()->getWinSize();
  174. //create default camera
  175. auto projection = Director::getInstance()->getProjection();
  176. switch (projection)
  177. {
  178. case Director::Projection::_2D:
  179. {
  180. initOrthographic(size.width, size.height, -1024, 1024);
  181. setPosition3D(Vec3(0.0f, 0.0f, 0.0f));
  182. setRotation3D(Vec3(0.f, 0.f, 0.f));
  183. break;
  184. }
  185. case Director::Projection::_3D:
  186. {
  187. float zeye = Director::getInstance()->getZEye();
  188. initPerspective(60, (GLfloat)size.width / size.height, 10, zeye + size.height / 2.0f);
  189. 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);
  190. setPosition3D(eye);
  191. lookAt(center, up);
  192. break;
  193. }
  194. default:
  195. CCLOG("unrecognized projection");
  196. break;
  197. }
  198. return true;
  199. }
  200. bool Camera::initPerspective(float fieldOfView, float aspectRatio, float nearPlane, float farPlane)
  201. {
  202. _fieldOfView = fieldOfView;
  203. _aspectRatio = aspectRatio;
  204. _nearPlane = nearPlane;
  205. _farPlane = farPlane;
  206. Mat4::createPerspective(_fieldOfView, _aspectRatio, _nearPlane, _farPlane, &_projection);
  207. _viewProjectionDirty = true;
  208. _frustumDirty = true;
  209. return true;
  210. }
  211. bool Camera::initOrthographic(float zoomX, float zoomY, float nearPlane, float farPlane)
  212. {
  213. _zoom[0] = zoomX;
  214. _zoom[1] = zoomY;
  215. _nearPlane = nearPlane;
  216. _farPlane = farPlane;
  217. Mat4::createOrthographicOffCenter(0, _zoom[0], 0, _zoom[1], _nearPlane, _farPlane, &_projection);
  218. _viewProjectionDirty = true;
  219. _frustumDirty = true;
  220. return true;
  221. }
  222. Vec2 Camera::project(const Vec3& src) const
  223. {
  224. Vec2 screenPos;
  225. auto viewport = Director::getInstance()->getWinSize();
  226. Vec4 clipPos;
  227. getViewProjectionMatrix().transformVector(Vec4(src.x, src.y, src.z, 1.0f), &clipPos);
  228. CCASSERT(clipPos.w != 0.0f, "clipPos.w can't be 0.0f!");
  229. float ndcX = clipPos.x / clipPos.w;
  230. float ndcY = clipPos.y / clipPos.w;
  231. screenPos.x = (ndcX + 1.0f) * 0.5f * viewport.width;
  232. screenPos.y = (1.0f - (ndcY + 1.0f) * 0.5f) * viewport.height;
  233. return screenPos;
  234. }
  235. Vec2 Camera::projectGL(const Vec3& src) const
  236. {
  237. Vec2 screenPos;
  238. auto viewport = Director::getInstance()->getWinSize();
  239. Vec4 clipPos;
  240. getViewProjectionMatrix().transformVector(Vec4(src.x, src.y, src.z, 1.0f), &clipPos);
  241. CCASSERT(clipPos.w != 0.0f, "clipPos.w can't be 0.0f!");
  242. float ndcX = clipPos.x / clipPos.w;
  243. float ndcY = clipPos.y / clipPos.w;
  244. screenPos.x = (ndcX + 1.0f) * 0.5f * viewport.width;
  245. screenPos.y = (ndcY + 1.0f) * 0.5f * viewport.height;
  246. return screenPos;
  247. }
  248. Vec3 Camera::unproject(const Vec3& src) const
  249. {
  250. Vec3 dst;
  251. unproject(Director::getInstance()->getWinSize(), &src, &dst);
  252. return dst;
  253. }
  254. Vec3 Camera::unprojectGL(const Vec3& src) const
  255. {
  256. Vec3 dst;
  257. unprojectGL(Director::getInstance()->getWinSize(), &src, &dst);
  258. return dst;
  259. }
  260. void Camera::unproject(const Size& viewport, const Vec3* src, Vec3* dst) const
  261. {
  262. CCASSERT(src && dst, "vec3 can not be null");
  263. Vec4 screen(src->x / viewport.width, ((viewport.height - src->y)) / viewport.height, src->z, 1.0f);
  264. screen.x = screen.x * 2.0f - 1.0f;
  265. screen.y = screen.y * 2.0f - 1.0f;
  266. screen.z = screen.z * 2.0f - 1.0f;
  267. getViewProjectionMatrix().getInversed().transformVector(screen, &screen);
  268. if (screen.w != 0.0f)
  269. {
  270. screen.x /= screen.w;
  271. screen.y /= screen.w;
  272. screen.z /= screen.w;
  273. }
  274. dst->set(screen.x, screen.y, screen.z);
  275. }
  276. void Camera::unprojectGL(const Size& viewport, const Vec3* src, Vec3* dst) const
  277. {
  278. CCASSERT(src && dst, "vec3 can not be null");
  279. Vec4 screen(src->x / viewport.width, src->y / viewport.height, src->z, 1.0f);
  280. screen.x = screen.x * 2.0f - 1.0f;
  281. screen.y = screen.y * 2.0f - 1.0f;
  282. screen.z = screen.z * 2.0f - 1.0f;
  283. getViewProjectionMatrix().getInversed().transformVector(screen, &screen);
  284. if (screen.w != 0.0f)
  285. {
  286. screen.x /= screen.w;
  287. screen.y /= screen.w;
  288. screen.z /= screen.w;
  289. }
  290. dst->set(screen.x, screen.y, screen.z);
  291. }
  292. bool Camera::isVisibleInFrustum(const AABB* aabb) const
  293. {
  294. if (_frustumDirty)
  295. {
  296. _frustum.initFrustum(this);
  297. _frustumDirty = false;
  298. }
  299. return !_frustum.isOutOfFrustum(*aabb);
  300. }
  301. float Camera::getDepthInView(const Mat4& transform) const
  302. {
  303. Mat4 camWorldMat = getNodeToWorldTransform();
  304. const Mat4 &viewMat = camWorldMat.getInversed();
  305. float depth = -(viewMat.m[2] * transform.m[12] + viewMat.m[6] * transform.m[13] + viewMat.m[10] * transform.m[14] + viewMat.m[14]);
  306. return depth;
  307. }
  308. void Camera::setDepth(int8_t depth)
  309. {
  310. if (_depth != depth)
  311. {
  312. _depth = depth;
  313. if (_scene)
  314. {
  315. //notify scene that the camera order is dirty
  316. _scene->setCameraOrderDirty();
  317. }
  318. }
  319. }
  320. void Camera::onEnter()
  321. {
  322. if (_scene == nullptr)
  323. {
  324. auto scene = getScene();
  325. if (scene)
  326. {
  327. setScene(scene);
  328. }
  329. }
  330. Node::onEnter();
  331. }
  332. void Camera::onExit()
  333. {
  334. // remove this camera from scene
  335. setScene(nullptr);
  336. Node::onExit();
  337. }
  338. void Camera::setScene(Scene* scene)
  339. {
  340. if (_scene != scene)
  341. {
  342. //remove old scene
  343. if (_scene)
  344. {
  345. auto& cameras = _scene->_cameras;
  346. auto it = std::find(cameras.begin(), cameras.end(), this);
  347. if (it != cameras.end())
  348. cameras.erase(it);
  349. _scene = nullptr;
  350. }
  351. //set new scene
  352. if (scene)
  353. {
  354. _scene = scene;
  355. auto& cameras = _scene->_cameras;
  356. auto it = std::find(cameras.begin(), cameras.end(), this);
  357. if (it == cameras.end())
  358. {
  359. _scene->_cameras.push_back(this);
  360. //notify scene that the camera order is dirty
  361. _scene->setCameraOrderDirty();
  362. }
  363. }
  364. }
  365. }
  366. void Camera::clearBackground()
  367. {
  368. if (_clearBrush)
  369. {
  370. _clearBrush->drawBackground(this);
  371. }
  372. }
  373. void Camera::setFrameBufferObject(experimental::FrameBuffer *fbo)
  374. {
  375. CC_SAFE_RETAIN(fbo);
  376. CC_SAFE_RELEASE_NULL(_fbo);
  377. _fbo = fbo;
  378. if(_scene)
  379. {
  380. _scene->setCameraOrderDirty();
  381. }
  382. }
  383. void Camera::apply()
  384. {
  385. _viewProjectionUpdated = _transformUpdated;
  386. applyFrameBufferObject();
  387. applyViewport();
  388. }
  389. void Camera::applyFrameBufferObject()
  390. {
  391. if(nullptr == _fbo)
  392. {
  393. // inherit from context if it doesn't have a FBO
  394. // don't call apply the default one
  395. // experimental::FrameBuffer::applyDefaultFBO();
  396. }
  397. else
  398. {
  399. _fbo->applyFBO();
  400. }
  401. }
  402. void Camera::applyViewport()
  403. {
  404. glGetIntegerv(GL_VIEWPORT, _oldViewport);
  405. if(nullptr == _fbo)
  406. {
  407. glViewport(getDefaultViewport()._left, getDefaultViewport()._bottom, getDefaultViewport()._width, getDefaultViewport()._height);
  408. }
  409. else
  410. {
  411. glViewport(_viewport._left * _fbo->getWidth(), _viewport._bottom * _fbo->getHeight(),
  412. _viewport._width * _fbo->getWidth(), _viewport._height * _fbo->getHeight());
  413. }
  414. }
  415. void Camera::setViewport(const experimental::Viewport& vp)
  416. {
  417. _viewport = vp;
  418. }
  419. void Camera::restore()
  420. {
  421. restoreFrameBufferObject();
  422. restoreViewport();
  423. }
  424. void Camera::restoreFrameBufferObject()
  425. {
  426. if(nullptr == _fbo)
  427. {
  428. // it was inherited from context if it doesn't have a FBO
  429. // don't call restore the default one... just keep using the previous one
  430. // experimental::FrameBuffer::applyDefaultFBO();
  431. }
  432. else
  433. {
  434. _fbo->restoreFBO();
  435. }
  436. }
  437. void Camera::restoreViewport()
  438. {
  439. glViewport(_oldViewport[0], _oldViewport[1], _oldViewport[2], _oldViewport[3]);
  440. }
  441. int Camera::getRenderOrder() const
  442. {
  443. int result(0);
  444. if(_fbo)
  445. {
  446. result = _fbo->getFID()<<8;
  447. }
  448. else
  449. {
  450. result = 127 <<8;
  451. }
  452. result += _depth;
  453. return result;
  454. }
  455. void Camera::visit(Renderer* renderer, const Mat4 &parentTransform, uint32_t parentFlags)
  456. {
  457. _viewProjectionUpdated = _transformUpdated;
  458. return Node::visit(renderer, parentTransform, parentFlags);
  459. }
  460. void Camera::setBackgroundBrush(CameraBackgroundBrush* clearBrush)
  461. {
  462. CC_SAFE_RETAIN(clearBrush);
  463. CC_SAFE_RELEASE(_clearBrush);
  464. _clearBrush = clearBrush;
  465. }
  466. bool Camera::isBrushValid()
  467. {
  468. return _clearBrush != nullptr && _clearBrush->isValid();
  469. }
  470. NS_CC_END