CCArmature.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. /****************************************************************************
  2. Copyright (c) 2013-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. ****************************************************************************/
  20. #include "editor-support/cocostudio/CCArmature.h"
  21. #include "editor-support/cocostudio/CCArmatureDataManager.h"
  22. #include "editor-support/cocostudio/CCArmatureDefine.h"
  23. #include "editor-support/cocostudio/CCDataReaderHelper.h"
  24. #include "editor-support/cocostudio/CCDatas.h"
  25. #include "editor-support/cocostudio/CCSkin.h"
  26. #include "renderer/CCRenderer.h"
  27. #include "renderer/CCGroupCommand.h"
  28. #include "renderer/CCGLProgramState.h"
  29. #include "2d/CCDrawingPrimitives.h"
  30. #include "base/CCDirector.h"
  31. #if ENABLE_PHYSICS_BOX2D_DETECT
  32. #include "Box2D/Box2D.h"
  33. #elif ENABLE_PHYSICS_CHIPMUNK_DETECT
  34. #include "chipmunk/chipmunk.h"
  35. #endif
  36. using namespace cocos2d;
  37. namespace cocostudio {
  38. Armature *Armature::create()
  39. {
  40. Armature *armature = new (std::nothrow) Armature();
  41. if (armature && armature->init())
  42. {
  43. armature->autorelease();
  44. return armature;
  45. }
  46. CC_SAFE_DELETE(armature);
  47. return nullptr;
  48. }
  49. Armature *Armature::create(const std::string& name)
  50. {
  51. Armature *armature = new (std::nothrow) Armature();
  52. if (armature && armature->init(name))
  53. {
  54. armature->autorelease();
  55. return armature;
  56. }
  57. CC_SAFE_DELETE(armature);
  58. return nullptr;
  59. }
  60. Armature *Armature::create(const std::string& name, Bone *parentBone)
  61. {
  62. Armature *armature = new (std::nothrow) Armature();
  63. if (armature && armature->init(name, parentBone))
  64. {
  65. armature->autorelease();
  66. return armature;
  67. }
  68. CC_SAFE_DELETE(armature);
  69. return nullptr;
  70. }
  71. Armature::Armature()
  72. : _armatureData(nullptr)
  73. , _batchNode(nullptr)
  74. , _parentBone(nullptr)
  75. , _armatureTransformDirty(true)
  76. , _animation(nullptr)
  77. {
  78. }
  79. Armature::~Armature(void)
  80. {
  81. _boneDic.clear();
  82. _topBoneList.clear();
  83. CC_SAFE_DELETE(_animation);
  84. }
  85. bool Armature::init()
  86. {
  87. return init("");
  88. }
  89. bool Armature::init(const std::string& name)
  90. {
  91. bool bRet = false;
  92. do
  93. {
  94. removeAllChildren();
  95. CC_SAFE_DELETE(_animation);
  96. _animation = new (std::nothrow) ArmatureAnimation();
  97. _animation->init(this);
  98. _boneDic.clear();
  99. _topBoneList.clear();
  100. _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;
  101. _name = name;
  102. ArmatureDataManager *armatureDataManager = ArmatureDataManager::getInstance();
  103. if(!_name.empty())
  104. {
  105. AnimationData *animationData = armatureDataManager->getAnimationData(name);
  106. CCASSERT(animationData, "AnimationData not exist! ");
  107. _animation->setAnimationData(animationData);
  108. ArmatureData *armatureData = armatureDataManager->getArmatureData(name);
  109. CCASSERT(armatureData, "armatureData doesn't exists!");
  110. _armatureData = armatureData;
  111. for (auto& element : armatureData->boneDataDic)
  112. {
  113. Bone *bone = createBone(element.first);
  114. //! init bone's Tween to 1st movement's 1st frame
  115. do
  116. {
  117. MovementData *movData = animationData->getMovement(animationData->movementNames.at(0));
  118. CC_BREAK_IF(!movData);
  119. MovementBoneData *movBoneData = movData->getMovementBoneData(bone->getName());
  120. CC_BREAK_IF(!movBoneData || movBoneData->frameList.size() <= 0);
  121. FrameData *frameData = movBoneData->getFrameData(0);
  122. CC_BREAK_IF(!frameData);
  123. bone->getTweenData()->copy(frameData);
  124. bone->changeDisplayWithIndex(frameData->displayIndex, false);
  125. }
  126. while (0);
  127. }
  128. update(0);
  129. updateOffsetPoint();
  130. }
  131. else
  132. {
  133. _name = "new_armature";
  134. _armatureData = ArmatureData::create();
  135. _armatureData->name = _name;
  136. AnimationData *animationData = AnimationData::create();
  137. animationData->name = _name;
  138. armatureDataManager->addArmatureData(_name, _armatureData);
  139. armatureDataManager->addAnimationData(_name, animationData);
  140. _animation->setAnimationData(animationData);
  141. }
  142. setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
  143. setCascadeOpacityEnabled(true);
  144. setCascadeColorEnabled(true);
  145. bRet = true;
  146. }
  147. while (0);
  148. return bRet;
  149. }
  150. bool Armature::init(const std::string& name, Bone *parentBone)
  151. {
  152. _parentBone = parentBone;
  153. return init(name);
  154. }
  155. Bone *Armature::createBone(const std::string& boneName)
  156. {
  157. Bone *existedBone = getBone(boneName);
  158. if(existedBone != nullptr)
  159. return existedBone;
  160. BoneData *boneData = (BoneData *)_armatureData->getBoneData(boneName);
  161. std::string parentName = boneData->parentName;
  162. Bone *bone = nullptr;
  163. if( !parentName.empty())
  164. {
  165. createBone(parentName);
  166. bone = Bone::create(boneName);
  167. addBone(bone, parentName);
  168. }
  169. else
  170. {
  171. bone = Bone::create(boneName);
  172. addBone(bone, "");
  173. }
  174. bone->setBoneData(boneData);
  175. bone->getDisplayManager()->changeDisplayWithIndex(-1, false);
  176. return bone;
  177. }
  178. void Armature::addBone(Bone *bone, const std::string& parentName)
  179. {
  180. CCASSERT( bone != nullptr, "Argument must be non-nil");
  181. CCASSERT(_boneDic.at(bone->getName()) == nullptr, "bone already added. It can't be added again");
  182. if (!parentName.empty())
  183. {
  184. Bone *boneParent = _boneDic.at(parentName);
  185. if (boneParent)
  186. {
  187. boneParent->addChildBone(bone);
  188. }
  189. else
  190. {
  191. _topBoneList.pushBack(bone);
  192. }
  193. }
  194. else
  195. {
  196. _topBoneList.pushBack(bone);
  197. }
  198. bone->setArmature(this);
  199. _boneDic.insert(bone->getName(), bone);
  200. addChild(bone);
  201. }
  202. void Armature::removeBone(Bone *bone, bool recursion)
  203. {
  204. CCASSERT(bone != nullptr, "bone must be added to the bone dictionary!");
  205. bone->setArmature(nullptr);
  206. bone->removeFromParent(recursion);
  207. if (_topBoneList.contains(bone))
  208. {
  209. _topBoneList.eraseObject(bone);
  210. }
  211. _boneDic.erase(bone->getName());
  212. removeChild(bone, true);
  213. }
  214. Bone *Armature::getBone(const std::string& name) const
  215. {
  216. return _boneDic.at(name);
  217. }
  218. void Armature::changeBoneParent(Bone *bone, const std::string& parentName)
  219. {
  220. CCASSERT(bone != nullptr, "bone must be added to the bone dictionary!");
  221. if(bone->getParentBone())
  222. {
  223. bone->getParentBone()->getChildren().eraseObject(bone);
  224. bone->setParentBone(nullptr);
  225. }
  226. if (!parentName.empty())
  227. {
  228. Bone *boneParent = _boneDic.at(parentName);
  229. if (boneParent)
  230. {
  231. boneParent->addChildBone(bone);
  232. if (_topBoneList.contains(bone))
  233. {
  234. _topBoneList.eraseObject(bone);
  235. }
  236. }
  237. else
  238. {
  239. _topBoneList.pushBack(bone);
  240. }
  241. }
  242. }
  243. const cocos2d::Map<std::string, Bone*>& Armature::getBoneDic() const
  244. {
  245. return _boneDic;
  246. }
  247. const Mat4& Armature::getNodeToParentTransform() const
  248. {
  249. if (_transformDirty)
  250. _armatureTransformDirty = true;
  251. return Node::getNodeToParentTransform();
  252. }
  253. void Armature::updateOffsetPoint()
  254. {
  255. // Set contentsize and Calculate anchor point.
  256. Rect rect = getBoundingBox();
  257. setContentSize(rect.size);
  258. _offsetPoint.set(-rect.origin.x, -rect.origin.y);
  259. if (rect.size.width != 0 && rect.size.height != 0)
  260. {
  261. setAnchorPoint(Vec2(_offsetPoint.x / rect.size.width, _offsetPoint.y / rect.size.height));
  262. }
  263. }
  264. void Armature::setAnchorPoint(const Vec2& point)
  265. {
  266. if( ! point.equals(_anchorPoint))
  267. {
  268. _anchorPoint = point;
  269. _anchorPointInPoints.set(_contentSize.width * _anchorPoint.x - _offsetPoint.x, _contentSize.height * _anchorPoint.y - _offsetPoint.y);
  270. _realAnchorPointInPoints.set(_contentSize.width * _anchorPoint.x, _contentSize.height * _anchorPoint.y);
  271. _transformDirty = _inverseDirty = true;
  272. }
  273. }
  274. const Vec2& Armature::getAnchorPointInPoints() const
  275. {
  276. return _realAnchorPointInPoints;
  277. }
  278. const Vec2& Armature::getOffsetPoints() const
  279. {
  280. return _offsetPoint;
  281. }
  282. void Armature::setAnimation(ArmatureAnimation *animation)
  283. {
  284. _animation = animation;
  285. }
  286. ArmatureAnimation *Armature::getAnimation() const
  287. {
  288. return _animation;
  289. }
  290. bool Armature::getArmatureTransformDirty() const
  291. {
  292. return _armatureTransformDirty;
  293. }
  294. void Armature::update(float dt)
  295. {
  296. _animation->update(dt);
  297. for(const auto &bone : _topBoneList) {
  298. bone->update(dt);
  299. }
  300. _armatureTransformDirty = false;
  301. }
  302. void Armature::draw(cocos2d::Renderer *renderer, const Mat4 &transform, uint32_t flags)
  303. {
  304. if (_parentBone == nullptr && _batchNode == nullptr)
  305. {
  306. // CC_NODE_DRAW_SETUP();
  307. }
  308. for (auto& object : _children)
  309. {
  310. if (Bone *bone = dynamic_cast<Bone *>(object))
  311. {
  312. Node *node = bone->getDisplayRenderNode();
  313. if (nullptr == node)
  314. continue;
  315. switch (bone->getDisplayRenderNodeType())
  316. {
  317. case CS_DISPLAY_SPRITE:
  318. {
  319. Skin *skin = static_cast<Skin *>(node);
  320. skin->updateTransform();
  321. BlendFunc func = bone->getBlendFunc();
  322. if (func.src != BlendFunc::ALPHA_PREMULTIPLIED.src || func.dst != BlendFunc::ALPHA_PREMULTIPLIED.dst)
  323. {
  324. skin->setBlendFunc(bone->getBlendFunc());
  325. }
  326. else
  327. {
  328. if (_blendFunc == BlendFunc::ALPHA_PREMULTIPLIED && !skin->getTexture()->hasPremultipliedAlpha())
  329. {
  330. skin->setBlendFunc(_blendFunc.ALPHA_NON_PREMULTIPLIED);
  331. }
  332. else
  333. {
  334. skin->setBlendFunc(_blendFunc);
  335. }
  336. }
  337. skin->draw(renderer, transform, flags);
  338. }
  339. break;
  340. case CS_DISPLAY_ARMATURE:
  341. {
  342. node->draw(renderer, transform, flags);
  343. }
  344. break;
  345. default:
  346. {
  347. node->visit(renderer, transform, flags);
  348. // CC_NODE_DRAW_SETUP();
  349. }
  350. break;
  351. }
  352. }
  353. else if(Node *node = dynamic_cast<Node *>(object))
  354. {
  355. node->visit(renderer, transform, flags);
  356. // CC_NODE_DRAW_SETUP();
  357. }
  358. }
  359. }
  360. void Armature::onEnter()
  361. {
  362. #if CC_ENABLE_SCRIPT_BINDING
  363. if (_scriptType == kScriptTypeJavascript)
  364. {
  365. if (ScriptEngineManager::sendNodeEventToJSExtended(this, kNodeOnEnter))
  366. return;
  367. }
  368. #endif
  369. Node::onEnter();
  370. scheduleUpdate();
  371. }
  372. void Armature::onExit()
  373. {
  374. #if CC_ENABLE_SCRIPT_BINDING
  375. if (_scriptType == kScriptTypeJavascript)
  376. {
  377. if (ScriptEngineManager::sendNodeEventToJSExtended(this, kNodeOnExit))
  378. return;
  379. }
  380. #endif
  381. Node::onExit();
  382. unscheduleUpdate();
  383. }
  384. void Armature::visit(cocos2d::Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags)
  385. {
  386. // quick return if not visible. children won't be drawn.
  387. if (!_visible)
  388. {
  389. return;
  390. }
  391. uint32_t flags = processParentFlags(parentTransform, parentFlags);
  392. if (isVisitableByVisitingCamera())
  393. {
  394. // IMPORTANT:
  395. // To ease the migration to v3.0, we still support the Mat4 stack,
  396. // but it is deprecated and your code should not rely on it
  397. Director* director = Director::getInstance();
  398. CCASSERT(nullptr != director, "Director is null when setting matrix stack");
  399. director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
  400. director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
  401. sortAllChildren();
  402. draw(renderer, _modelViewTransform, flags);
  403. // FIX ME: Why need to set _orderOfArrival to 0??
  404. // Please refer to https://github.com/cocos2d/cocos2d-x/pull/6920
  405. // setOrderOfArrival(0);
  406. director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
  407. }
  408. }
  409. Rect Armature::getBoundingBox() const
  410. {
  411. float minx, miny, maxx, maxy = 0;
  412. bool first = true;
  413. Rect boundingBox = Rect(0, 0, 0, 0);
  414. for (const auto& object : _children)
  415. {
  416. if (Bone *bone = dynamic_cast<Bone *>(object))
  417. {
  418. Rect r = bone->getDisplayManager()->getBoundingBox();
  419. if (r.equals(Rect::ZERO))
  420. continue;
  421. if(first)
  422. {
  423. minx = r.getMinX();
  424. miny = r.getMinY();
  425. maxx = r.getMaxX();
  426. maxy = r.getMaxY();
  427. first = false;
  428. }
  429. else
  430. {
  431. minx = r.getMinX() < boundingBox.getMinX() ? r.getMinX() : boundingBox.getMinX();
  432. miny = r.getMinY() < boundingBox.getMinY() ? r.getMinY() : boundingBox.getMinY();
  433. maxx = r.getMaxX() > boundingBox.getMaxX() ? r.getMaxX() : boundingBox.getMaxX();
  434. maxy = r.getMaxY() > boundingBox.getMaxY() ? r.getMaxY() : boundingBox.getMaxY();
  435. }
  436. boundingBox.setRect(minx, miny, maxx - minx, maxy - miny);
  437. }
  438. }
  439. return RectApplyTransform(boundingBox, getNodeToParentTransform());
  440. }
  441. Bone *Armature::getBoneAtPoint(float x, float y) const
  442. {
  443. long length = _children.size();
  444. Bone *bs;
  445. for(long i = length - 1; i >= 0; i--)
  446. {
  447. bs = static_cast<Bone*>( _children.at(i) );
  448. if(bs->getDisplayManager()->containPoint(x, y))
  449. {
  450. return bs;
  451. }
  452. }
  453. return nullptr;
  454. }
  455. void Armature::setParentBone(Bone *parentBone)
  456. {
  457. _parentBone = parentBone;
  458. for (auto& element : _boneDic)
  459. {
  460. element.second->setArmature(this);
  461. }
  462. }
  463. Bone *Armature::getParentBone() const
  464. {
  465. return _parentBone;
  466. }
  467. #if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT
  468. void Armature::setColliderFilter(ColliderFilter *filter)
  469. {
  470. for (auto& element : _boneDic)
  471. {
  472. element.second->setColliderFilter(filter);
  473. }
  474. }
  475. #elif ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX
  476. void Armature::drawContour()
  477. {
  478. for(auto& element : _boneDic)
  479. {
  480. Bone *bone = element.second;
  481. ColliderDetector *detector = bone->getColliderDetector();
  482. if (!detector)
  483. continue;
  484. const cocos2d::Vector<ColliderBody*>& bodyList = detector->getColliderBodyList();
  485. for (auto& object : bodyList)
  486. {
  487. ColliderBody *body = static_cast<ColliderBody*>(object);
  488. const std::vector<Vec2> &vertexList = body->getCalculatedVertexList();
  489. unsigned long length = vertexList.size();
  490. Vec2 *points = new (std::nothrow) Vec2[length];
  491. for (unsigned long i = 0; i<length; i++)
  492. {
  493. Vec2 p = vertexList.at(i);
  494. points[i].x = p.x;
  495. points[i].y = p.y;
  496. }
  497. #if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
  498. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  499. #elif _MSC_VER >= 1400 //vs 2005 or higher
  500. #pragma warning (push)
  501. #pragma warning (disable: 4996)
  502. #endif
  503. DrawPrimitives::drawPoly( points, (unsigned int)length, true );
  504. #if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
  505. #pragma GCC diagnostic warning "-Wdeprecated-declarations"
  506. #elif _MSC_VER >= 1400 //vs 2005 or higher
  507. #pragma warning (pop)
  508. #endif
  509. delete []points;
  510. }
  511. }
  512. }
  513. #endif
  514. #if ENABLE_PHYSICS_BOX2D_DETECT
  515. b2Body *Armature::getBody() const
  516. {
  517. return _body;
  518. }
  519. void Armature::setBody(b2Body *body)
  520. {
  521. if (_body == body)
  522. {
  523. return;
  524. }
  525. _body = body;
  526. _body->SetUserData(this);
  527. for(auto& object : _children)
  528. {
  529. if (Bone *bone = dynamic_cast<Bone *>(object))
  530. {
  531. auto displayList = bone->getDisplayManager()->getDecorativeDisplayList();
  532. for(auto displayObject : displayList)
  533. {
  534. ColliderDetector *detector = static_cast<DecorativeDisplay *>(displayObject)->getColliderDetector();
  535. if (detector != nullptr)
  536. {
  537. detector->setBody(_body);
  538. }
  539. }
  540. }
  541. }
  542. }
  543. b2Fixture *Armature::getShapeList()
  544. {
  545. if (_body)
  546. {
  547. return _body->GetFixtureList();
  548. }
  549. else
  550. {
  551. return nullptr;
  552. }
  553. }
  554. #elif ENABLE_PHYSICS_CHIPMUNK_DETECT
  555. cpBody *Armature::getBody() const
  556. {
  557. return _body;
  558. }
  559. void Armature::setBody(cpBody *body)
  560. {
  561. if (_body == body)
  562. {
  563. return;
  564. }
  565. _body = body;
  566. _body->data = this;
  567. for (const auto& object : _children)
  568. {
  569. if (Bone *bone = dynamic_cast<Bone *>(object))
  570. {
  571. auto displayList = bone->getDisplayManager()->getDecorativeDisplayList();
  572. for (const auto& displayObject : displayList)
  573. {
  574. auto detector = displayObject->getColliderDetector();
  575. if (detector != nullptr)
  576. {
  577. detector->setBody(body);
  578. }
  579. });
  580. }
  581. }
  582. }
  583. cpShape *Armature::getShapeList()
  584. {
  585. if (_body)
  586. {
  587. return _body->shapeList_private;
  588. }
  589. else
  590. {
  591. return nullptr;
  592. }
  593. }
  594. #endif
  595. }