CCNode.cpp 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240
  1. /****************************************************************************
  2. Copyright (c) 2008-2010 Ricardo Quesada
  3. Copyright (c) 2009 Valentin Milea
  4. Copyright (c) 2010-2012 cocos2d-x.org
  5. Copyright (c) 2011 Zynga Inc.
  6. Copyright (c) 2013-2016 Chukong Technologies Inc.
  7. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  8. http://www.cocos2d-x.org
  9. Permission is hereby granted, free of charge, to any person obtaining a copy
  10. of this software and associated documentation files (the "Software"), to deal
  11. in the Software without restriction, including without limitation the rights
  12. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. copies of the Software, and to permit persons to whom the Software is
  14. furnished to do so, subject to the following conditions:
  15. The above copyright notice and this permission notice shall be included in
  16. all copies or substantial portions of the Software.
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. THE SOFTWARE.
  24. ****************************************************************************/
  25. #include "2d/CCNode.h"
  26. #include <algorithm>
  27. #include <string>
  28. #include <regex>
  29. #include "base/CCDirector.h"
  30. #include "base/CCScheduler.h"
  31. #include "base/CCEventDispatcher.h"
  32. #include "base/ccUTF8.h"
  33. #include "2d/CCCamera.h"
  34. #include "2d/CCActionManager.h"
  35. #include "2d/CCScene.h"
  36. #include "2d/CCComponent.h"
  37. #include "renderer/CCGLProgram.h"
  38. #include "renderer/CCGLProgramState.h"
  39. #include "renderer/CCMaterial.h"
  40. #include "math/TransformUtils.h"
  41. #if CC_NODE_RENDER_SUBPIXEL
  42. #define RENDER_IN_SUBPIXEL
  43. #else
  44. #define RENDER_IN_SUBPIXEL(__ARGS__) (ceil(__ARGS__))
  45. #endif
  46. NS_CC_BEGIN
  47. // FIXME:: Yes, nodes might have a sort problem once every 30 days if the game runs at 60 FPS and each frame sprites are reordered.
  48. std::uint32_t Node::s_globalOrderOfArrival = 0;
  49. int Node::__attachedNodeCount = 0;
  50. // MARK: Constructor, Destructor, Init
  51. Node::Node()
  52. : _rotationX(0.0f)
  53. , _rotationY(0.0f)
  54. , _rotationZ_X(0.0f)
  55. , _rotationZ_Y(0.0f)
  56. , _scaleX(1.0f)
  57. , _scaleY(1.0f)
  58. , _scaleZ(1.0f)
  59. , _positionZ(0.0f)
  60. , _usingNormalizedPosition(false)
  61. , _normalizedPositionDirty(false)
  62. , _skewX(0.0f)
  63. , _skewY(0.0f)
  64. , _contentSize(Size::ZERO)
  65. , _contentSizeDirty(true)
  66. , _transformDirty(true)
  67. , _inverseDirty(true)
  68. , _additionalTransform(nullptr)
  69. , _additionalTransformDirty(false)
  70. , _transformUpdated(true)
  71. // children (lazy allocs)
  72. // lazy alloc
  73. , _localZOrder$Arrival(0LL)
  74. , _globalZOrder(0)
  75. , _parent(nullptr)
  76. // "whole screen" objects. like Scenes and Layers, should set _ignoreAnchorPointForPosition to true
  77. , _tag(Node::INVALID_TAG)
  78. , _name("")
  79. , _hashOfName(0)
  80. // userData is always inited as nil
  81. , _userData(nullptr)
  82. , _userObject(nullptr)
  83. , _glProgramState(nullptr)
  84. , _running(false)
  85. , _visible(true)
  86. , _ignoreAnchorPointForPosition(false)
  87. , _reorderChildDirty(false)
  88. , _isTransitionFinished(false)
  89. #if CC_ENABLE_SCRIPT_BINDING
  90. , _updateScriptHandler(0)
  91. #endif
  92. , _componentContainer(nullptr)
  93. , _displayedOpacity(255)
  94. , _realOpacity(255)
  95. , _displayedColor(Color3B::WHITE)
  96. , _realColor(Color3B::WHITE)
  97. , _cascadeColorEnabled(false)
  98. , _cascadeOpacityEnabled(false)
  99. , _cameraMask(1)
  100. #if CC_USE_PHYSICS
  101. , _physicsBody(nullptr)
  102. #endif
  103. , _anchorPoint(0, 0)
  104. , _onEnterCallback(nullptr)
  105. , _onExitCallback(nullptr)
  106. , _onEnterTransitionDidFinishCallback(nullptr)
  107. , _onExitTransitionDidStartCallback(nullptr)
  108. {
  109. // set default scheduler and actionManager
  110. _director = Director::getInstance();
  111. _actionManager = _director->getActionManager();
  112. _actionManager->retain();
  113. _scheduler = _director->getScheduler();
  114. _scheduler->retain();
  115. _eventDispatcher = _director->getEventDispatcher();
  116. _eventDispatcher->retain();
  117. #if CC_ENABLE_SCRIPT_BINDING
  118. ScriptEngineProtocol* engine = ScriptEngineManager::getInstance()->getScriptEngine();
  119. _scriptType = engine != nullptr ? engine->getScriptType() : kScriptTypeNone;
  120. #endif
  121. _transform = _inverse = Mat4::IDENTITY;
  122. }
  123. Node * Node::create()
  124. {
  125. Node * ret = new (std::nothrow) Node();
  126. if (ret && ret->init())
  127. {
  128. ret->autorelease();
  129. }
  130. else
  131. {
  132. CC_SAFE_DELETE(ret);
  133. }
  134. return ret;
  135. }
  136. Node::~Node()
  137. {
  138. CCLOGINFO( "deallocing Node: %p - tag: %i", this, _tag );
  139. #if CC_ENABLE_SCRIPT_BINDING
  140. if (_updateScriptHandler)
  141. {
  142. ScriptEngineManager::getInstance()->getScriptEngine()->removeScriptHandler(_updateScriptHandler);
  143. }
  144. #endif
  145. // User object has to be released before others, since userObject may have a weak reference of this node
  146. // It may invoke `node->stopAllActions();` while `_actionManager` is null if the next line is after `CC_SAFE_RELEASE_NULL(_actionManager)`.
  147. CC_SAFE_RELEASE_NULL(_userObject);
  148. // attributes
  149. CC_SAFE_RELEASE_NULL(_glProgramState);
  150. for (auto& child : _children)
  151. {
  152. child->_parent = nullptr;
  153. }
  154. removeAllComponents();
  155. CC_SAFE_DELETE(_componentContainer);
  156. stopAllActions();
  157. unscheduleAllCallbacks();
  158. CC_SAFE_RELEASE_NULL(_actionManager);
  159. CC_SAFE_RELEASE_NULL(_scheduler);
  160. _eventDispatcher->removeEventListenersForTarget(this);
  161. #if CC_NODE_DEBUG_VERIFY_EVENT_LISTENERS && COCOS2D_DEBUG > 0
  162. _eventDispatcher->debugCheckNodeHasNoEventListenersOnDestruction(this);
  163. #endif
  164. CCASSERT(!_running, "Node still marked as running on node destruction! Was base class onExit() called in derived class onExit() implementations?");
  165. CC_SAFE_RELEASE(_eventDispatcher);
  166. delete[] _additionalTransform;
  167. }
  168. bool Node::init()
  169. {
  170. return true;
  171. }
  172. void Node::cleanup()
  173. {
  174. #if CC_ENABLE_SCRIPT_BINDING
  175. if (_scriptType == kScriptTypeJavascript)
  176. {
  177. if (ScriptEngineManager::sendNodeEventToJS(this, kNodeOnCleanup))
  178. return;
  179. }
  180. else if (_scriptType == kScriptTypeLua)
  181. {
  182. ScriptEngineManager::sendNodeEventToLua(this, kNodeOnCleanup);
  183. }
  184. #endif // #if CC_ENABLE_SCRIPT_BINDING
  185. // actions
  186. this->stopAllActions();
  187. // timers
  188. this->unscheduleAllCallbacks();
  189. // NOTE: Although it was correct that removing event listeners associated with current node in Node::cleanup.
  190. // But it broke the compatibility to the versions before v3.16 .
  191. // User code may call `node->removeFromParent(true)` which will trigger node's cleanup method, when the node
  192. // is added to scene again, event listeners like EventListenerTouchOneByOne will be lost.
  193. // In fact, user's code should use `node->removeFromParent(false)` in order not to do a cleanup and just remove node
  194. // from its parent. For more discussion about why we revert this change is at https://github.com/cocos2d/cocos2d-x/issues/18104.
  195. // We need to consider more before we want to correct the old and wrong logic code.
  196. // For now, compatiblity is the most important for our users.
  197. // _eventDispatcher->removeEventListenersForTarget(this);
  198. for( const auto &child: _children)
  199. child->cleanup();
  200. }
  201. std::string Node::getDescription() const
  202. {
  203. return StringUtils::format("<Node | Tag = %d", _tag);
  204. }
  205. // MARK: getters / setters
  206. float Node::getSkewX() const
  207. {
  208. return _skewX;
  209. }
  210. void Node::setSkewX(float skewX)
  211. {
  212. if (_skewX == skewX)
  213. return;
  214. _skewX = skewX;
  215. _transformUpdated = _transformDirty = _inverseDirty = true;
  216. }
  217. float Node::getSkewY() const
  218. {
  219. return _skewY;
  220. }
  221. void Node::setSkewY(float skewY)
  222. {
  223. if (_skewY == skewY)
  224. return;
  225. _skewY = skewY;
  226. _transformUpdated = _transformDirty = _inverseDirty = true;
  227. }
  228. void Node::setLocalZOrder(std::int32_t z)
  229. {
  230. if (getLocalZOrder() == z)
  231. return;
  232. _setLocalZOrder(z);
  233. if (_parent)
  234. {
  235. _parent->reorderChild(this, z);
  236. }
  237. _eventDispatcher->setDirtyForNode(this);
  238. }
  239. /// zOrder setter : private method
  240. /// used internally to alter the zOrder variable. DON'T call this method manually
  241. void Node::_setLocalZOrder(std::int32_t z)
  242. {
  243. _localZOrder = z;
  244. }
  245. void Node::updateOrderOfArrival()
  246. {
  247. _orderOfArrival = (++s_globalOrderOfArrival);
  248. }
  249. void Node::setGlobalZOrder(float globalZOrder)
  250. {
  251. if (_globalZOrder != globalZOrder)
  252. {
  253. _globalZOrder = globalZOrder;
  254. _eventDispatcher->setDirtyForNode(this);
  255. }
  256. }
  257. /// rotation getter
  258. float Node::getRotation() const
  259. {
  260. //CCASSERT(_rotationZ_X == _rotationZ_Y, "CCNode#rotation. RotationX != RotationY. Don't know which one to return");
  261. return _rotationZ_X;
  262. }
  263. /// rotation setter
  264. void Node::setRotation(float rotation)
  265. {
  266. if (_rotationZ_X == rotation)
  267. return;
  268. _rotationZ_X = _rotationZ_Y = rotation;
  269. _transformUpdated = _transformDirty = _inverseDirty = true;
  270. updateRotationQuat();
  271. }
  272. float Node::getRotationSkewX() const
  273. {
  274. return _rotationZ_X;
  275. }
  276. void Node::setRotation3D(const Vec3& rotation)
  277. {
  278. if (_rotationX == rotation.x &&
  279. _rotationY == rotation.y &&
  280. _rotationZ_X == rotation.z)
  281. return;
  282. _transformUpdated = _transformDirty = _inverseDirty = true;
  283. _rotationX = rotation.x;
  284. _rotationY = rotation.y;
  285. // rotation Z is decomposed in 2 to simulate Skew for Flash animations
  286. _rotationZ_Y = _rotationZ_X = rotation.z;
  287. updateRotationQuat();
  288. }
  289. Vec3 Node::getRotation3D() const
  290. {
  291. // rotation Z is decomposed in 2 to simulate Skew for Flash animations
  292. CCASSERT(_rotationZ_X == _rotationZ_Y, "_rotationZ_X != _rotationZ_Y");
  293. return Vec3(_rotationX,_rotationY,_rotationZ_X);
  294. }
  295. void Node::updateRotationQuat()
  296. {
  297. // convert Euler angle to quaternion
  298. // when _rotationZ_X == _rotationZ_Y, _rotationQuat = RotationZ_X * RotationY * RotationX
  299. // when _rotationZ_X != _rotationZ_Y, _rotationQuat = RotationY * RotationX
  300. float halfRadx = CC_DEGREES_TO_RADIANS(_rotationX / 2.f), halfRady = CC_DEGREES_TO_RADIANS(_rotationY / 2.f), halfRadz = _rotationZ_X == _rotationZ_Y ? -CC_DEGREES_TO_RADIANS(_rotationZ_X / 2.f) : 0;
  301. float coshalfRadx = cosf(halfRadx), sinhalfRadx = sinf(halfRadx), coshalfRady = cosf(halfRady), sinhalfRady = sinf(halfRady), coshalfRadz = cosf(halfRadz), sinhalfRadz = sinf(halfRadz);
  302. _rotationQuat.x = sinhalfRadx * coshalfRady * coshalfRadz - coshalfRadx * sinhalfRady * sinhalfRadz;
  303. _rotationQuat.y = coshalfRadx * sinhalfRady * coshalfRadz + sinhalfRadx * coshalfRady * sinhalfRadz;
  304. _rotationQuat.z = coshalfRadx * coshalfRady * sinhalfRadz - sinhalfRadx * sinhalfRady * coshalfRadz;
  305. _rotationQuat.w = coshalfRadx * coshalfRady * coshalfRadz + sinhalfRadx * sinhalfRady * sinhalfRadz;
  306. }
  307. void Node::updateRotation3D()
  308. {
  309. //convert quaternion to Euler angle
  310. float x = _rotationQuat.x, y = _rotationQuat.y, z = _rotationQuat.z, w = _rotationQuat.w;
  311. _rotationX = atan2f(2.f * (w * x + y * z), 1.f - 2.f * (x * x + y * y));
  312. float sy = 2.f * (w * y - z * x);
  313. sy = clampf(sy, -1, 1);
  314. _rotationY = asinf(sy);
  315. _rotationZ_X = atan2f(2.f * (w * z + x * y), 1.f - 2.f * (y * y + z * z));
  316. _rotationX = CC_RADIANS_TO_DEGREES(_rotationX);
  317. _rotationY = CC_RADIANS_TO_DEGREES(_rotationY);
  318. _rotationZ_X = _rotationZ_Y = -CC_RADIANS_TO_DEGREES(_rotationZ_X);
  319. }
  320. void Node::setRotationQuat(const Quaternion& quat)
  321. {
  322. _rotationQuat = quat;
  323. updateRotation3D();
  324. _transformUpdated = _transformDirty = _inverseDirty = true;
  325. }
  326. Quaternion Node::getRotationQuat() const
  327. {
  328. return _rotationQuat;
  329. }
  330. void Node::setRotationSkewX(float rotationX)
  331. {
  332. if (_rotationZ_X == rotationX)
  333. return;
  334. _rotationZ_X = rotationX;
  335. _transformUpdated = _transformDirty = _inverseDirty = true;
  336. updateRotationQuat();
  337. }
  338. float Node::getRotationSkewY() const
  339. {
  340. return _rotationZ_Y;
  341. }
  342. void Node::setRotationSkewY(float rotationY)
  343. {
  344. if (_rotationZ_Y == rotationY)
  345. return;
  346. _rotationZ_Y = rotationY;
  347. _transformUpdated = _transformDirty = _inverseDirty = true;
  348. updateRotationQuat();
  349. }
  350. /// scale getter
  351. float Node::getScale(void) const
  352. {
  353. CCASSERT( _scaleX == _scaleY, "CCNode#scale. ScaleX != ScaleY. Don't know which one to return");
  354. return _scaleX;
  355. }
  356. /// scale setter
  357. void Node::setScale(float scale)
  358. {
  359. if (_scaleX == scale && _scaleY == scale && _scaleZ == scale)
  360. return;
  361. _scaleX = _scaleY = _scaleZ = scale;
  362. _transformUpdated = _transformDirty = _inverseDirty = true;
  363. }
  364. /// scaleX getter
  365. float Node::getScaleX() const
  366. {
  367. return _scaleX;
  368. }
  369. /// scale setter
  370. void Node::setScale(float scaleX,float scaleY)
  371. {
  372. if (_scaleX == scaleX && _scaleY == scaleY)
  373. return;
  374. _scaleX = scaleX;
  375. _scaleY = scaleY;
  376. _transformUpdated = _transformDirty = _inverseDirty = true;
  377. }
  378. /// scaleX setter
  379. void Node::setScaleX(float scaleX)
  380. {
  381. if (_scaleX == scaleX)
  382. return;
  383. _scaleX = scaleX;
  384. _transformUpdated = _transformDirty = _inverseDirty = true;
  385. }
  386. /// scaleY getter
  387. float Node::getScaleY() const
  388. {
  389. return _scaleY;
  390. }
  391. /// scaleY setter
  392. void Node::setScaleZ(float scaleZ)
  393. {
  394. if (_scaleZ == scaleZ)
  395. return;
  396. _scaleZ = scaleZ;
  397. _transformUpdated = _transformDirty = _inverseDirty = true;
  398. }
  399. /// scaleY getter
  400. float Node::getScaleZ() const
  401. {
  402. return _scaleZ;
  403. }
  404. /// scaleY setter
  405. void Node::setScaleY(float scaleY)
  406. {
  407. if (_scaleY == scaleY)
  408. return;
  409. _scaleY = scaleY;
  410. _transformUpdated = _transformDirty = _inverseDirty = true;
  411. }
  412. /// position getter
  413. const Vec2& Node::getPosition() const
  414. {
  415. return _position;
  416. }
  417. /// position setter
  418. void Node::setPosition(const Vec2& position)
  419. {
  420. setPosition(position.x, position.y);
  421. }
  422. void Node::getPosition(float* x, float* y) const
  423. {
  424. *x = _position.x;
  425. *y = _position.y;
  426. }
  427. void Node::setPosition(float x, float y)
  428. {
  429. if (_position.x == x && _position.y == y)
  430. return;
  431. _position.x = x;
  432. _position.y = y;
  433. _transformUpdated = _transformDirty = _inverseDirty = true;
  434. _usingNormalizedPosition = false;
  435. }
  436. void Node::setPosition3D(const Vec3& position)
  437. {
  438. setPositionZ(position.z);
  439. setPosition(position.x, position.y);
  440. }
  441. Vec3 Node::getPosition3D() const
  442. {
  443. return Vec3(_position.x, _position.y, _positionZ);
  444. }
  445. float Node::getPositionX() const
  446. {
  447. return _position.x;
  448. }
  449. void Node::setPositionX(float x)
  450. {
  451. setPosition(x, _position.y);
  452. }
  453. float Node::getPositionY() const
  454. {
  455. return _position.y;
  456. }
  457. void Node::setPositionY(float y)
  458. {
  459. setPosition(_position.x, y);
  460. }
  461. float Node::getPositionZ() const
  462. {
  463. return _positionZ;
  464. }
  465. void Node::setPositionZ(float positionZ)
  466. {
  467. if (_positionZ == positionZ)
  468. return;
  469. _transformUpdated = _transformDirty = _inverseDirty = true;
  470. _positionZ = positionZ;
  471. }
  472. /// position getter
  473. const Vec2& Node::getPositionNormalized() const
  474. {
  475. return _normalizedPosition;
  476. }
  477. /// position setter
  478. void Node::setPositionNormalized(const Vec2& position)
  479. {
  480. if (_normalizedPosition.equals(position))
  481. return;
  482. _normalizedPosition = position;
  483. _usingNormalizedPosition = true;
  484. _normalizedPositionDirty = true;
  485. _transformUpdated = _transformDirty = _inverseDirty = true;
  486. }
  487. ssize_t Node::getChildrenCount() const
  488. {
  489. return _children.size();
  490. }
  491. /// isVisible getter
  492. bool Node::isVisible() const
  493. {
  494. return _visible;
  495. }
  496. /// isVisible setter
  497. void Node::setVisible(bool visible)
  498. {
  499. if(visible != _visible)
  500. {
  501. _visible = visible;
  502. if(_visible)
  503. _transformUpdated = _transformDirty = _inverseDirty = true;
  504. }
  505. }
  506. const Vec2& Node::getAnchorPointInPoints() const
  507. {
  508. return _anchorPointInPoints;
  509. }
  510. /// anchorPoint getter
  511. const Vec2& Node::getAnchorPoint() const
  512. {
  513. return _anchorPoint;
  514. }
  515. void Node::setAnchorPoint(const Vec2& point)
  516. {
  517. if (! point.equals(_anchorPoint))
  518. {
  519. _anchorPoint = point;
  520. _anchorPointInPoints.set(_contentSize.width * _anchorPoint.x, _contentSize.height * _anchorPoint.y);
  521. _transformUpdated = _transformDirty = _inverseDirty = true;
  522. }
  523. }
  524. /// contentSize getter
  525. const Size& Node::getContentSize() const
  526. {
  527. return _contentSize;
  528. }
  529. void Node::setContentSize(const Size & size)
  530. {
  531. if (! size.equals(_contentSize))
  532. {
  533. _contentSize = size;
  534. _anchorPointInPoints.set(_contentSize.width * _anchorPoint.x, _contentSize.height * _anchorPoint.y);
  535. _transformUpdated = _transformDirty = _inverseDirty = _contentSizeDirty = true;
  536. }
  537. }
  538. // isRunning getter
  539. bool Node::isRunning() const
  540. {
  541. return _running;
  542. }
  543. /// parent setter
  544. void Node::setParent(Node * parent)
  545. {
  546. _parent = parent;
  547. _transformUpdated = _transformDirty = _inverseDirty = true;
  548. }
  549. /// isRelativeAnchorPoint getter
  550. bool Node::isIgnoreAnchorPointForPosition() const
  551. {
  552. return _ignoreAnchorPointForPosition;
  553. }
  554. /// isRelativeAnchorPoint setter
  555. void Node::setIgnoreAnchorPointForPosition(bool newValue)
  556. {
  557. if (newValue != _ignoreAnchorPointForPosition)
  558. {
  559. _ignoreAnchorPointForPosition = newValue;
  560. _transformUpdated = _transformDirty = _inverseDirty = true;
  561. }
  562. }
  563. /// tag getter
  564. int Node::getTag() const
  565. {
  566. return _tag;
  567. }
  568. /// tag setter
  569. void Node::setTag(int tag)
  570. {
  571. _tag = tag ;
  572. }
  573. const std::string& Node::getName() const
  574. {
  575. return _name;
  576. }
  577. void Node::setName(const std::string& name)
  578. {
  579. _name = name;
  580. std::hash<std::string> h;
  581. _hashOfName = h(name);
  582. }
  583. /// userData setter
  584. void Node::setUserData(void *userData)
  585. {
  586. _userData = userData;
  587. }
  588. void Node::setUserObject(Ref* userObject)
  589. {
  590. #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
  591. auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
  592. if (sEngine)
  593. {
  594. if (userObject)
  595. sEngine->retainScriptObject(this, userObject);
  596. if (_userObject)
  597. sEngine->releaseScriptObject(this, _userObject);
  598. }
  599. #endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
  600. CC_SAFE_RETAIN(userObject);
  601. CC_SAFE_RELEASE(_userObject);
  602. _userObject = userObject;
  603. }
  604. GLProgramState* Node::getGLProgramState() const
  605. {
  606. return _glProgramState;
  607. }
  608. void Node::setGLProgramState(cocos2d::GLProgramState* glProgramState)
  609. {
  610. if (glProgramState != _glProgramState)
  611. {
  612. CC_SAFE_RELEASE(_glProgramState);
  613. _glProgramState = glProgramState;
  614. CC_SAFE_RETAIN(_glProgramState);
  615. if (_glProgramState)
  616. _glProgramState->setNodeBinding(this);
  617. }
  618. }
  619. void Node::setGLProgram(GLProgram* glProgram)
  620. {
  621. if (_glProgramState == nullptr || (_glProgramState && _glProgramState->getGLProgram() != glProgram))
  622. {
  623. CC_SAFE_RELEASE(_glProgramState);
  624. _glProgramState = GLProgramState::getOrCreateWithGLProgram(glProgram);
  625. _glProgramState->retain();
  626. _glProgramState->setNodeBinding(this);
  627. }
  628. }
  629. GLProgram * Node::getGLProgram() const
  630. {
  631. return _glProgramState ? _glProgramState->getGLProgram() : nullptr;
  632. }
  633. Scene* Node::getScene() const
  634. {
  635. if (!_parent)
  636. return nullptr;
  637. auto sceneNode = _parent;
  638. while (sceneNode->_parent)
  639. {
  640. sceneNode = sceneNode->_parent;
  641. }
  642. return dynamic_cast<Scene*>(sceneNode);
  643. }
  644. Rect Node::getBoundingBox() const
  645. {
  646. Rect rect(0, 0, _contentSize.width, _contentSize.height);
  647. return RectApplyAffineTransform(rect, getNodeToParentAffineTransform());
  648. }
  649. // MARK: Children logic
  650. // lazy allocs
  651. void Node::childrenAlloc()
  652. {
  653. _children.reserve(4);
  654. }
  655. Node* Node::getChildByTag(int tag) const
  656. {
  657. CCASSERT(tag != Node::INVALID_TAG, "Invalid tag");
  658. for (const auto child : _children)
  659. {
  660. if(child && child->_tag == tag)
  661. return child;
  662. }
  663. return nullptr;
  664. }
  665. Node* Node::getChildByName(const std::string& name) const
  666. {
  667. CCASSERT(!name.empty(), "Invalid name");
  668. std::hash<std::string> h;
  669. size_t hash = h(name);
  670. for (const auto& child : _children)
  671. {
  672. // Different strings may have the same hash code, but can use it to compare first for speed
  673. if(child->_hashOfName == hash && child->_name.compare(name) == 0)
  674. return child;
  675. }
  676. return nullptr;
  677. }
  678. void Node::enumerateChildren(const std::string &name, std::function<bool (Node *)> callback) const
  679. {
  680. CCASSERT(!name.empty(), "Invalid name");
  681. CCASSERT(callback != nullptr, "Invalid callback function");
  682. size_t length = name.length();
  683. size_t subStrStartPos = 0; // sub string start index
  684. size_t subStrlength = length; // sub string length
  685. // Starts with '//'?
  686. bool searchRecursively = false;
  687. if (length > 2 && name[0] == '/' && name[1] == '/')
  688. {
  689. searchRecursively = true;
  690. subStrStartPos = 2;
  691. subStrlength -= 2;
  692. }
  693. // End with '/..'?
  694. bool searchFromParent = false;
  695. if (length > 3 &&
  696. name[length-3] == '/' &&
  697. name[length-2] == '.' &&
  698. name[length-1] == '.')
  699. {
  700. searchFromParent = true;
  701. subStrlength -= 3;
  702. }
  703. // Remove '//', '/..' if exist
  704. std::string newName = name.substr(subStrStartPos, subStrlength);
  705. if (searchFromParent)
  706. {
  707. newName.insert(0, "[[:alnum:]]+/");
  708. }
  709. if (searchRecursively)
  710. {
  711. // name is '//xxx'
  712. doEnumerateRecursive(this, newName, callback);
  713. }
  714. else
  715. {
  716. // name is xxx
  717. doEnumerate(newName, callback);
  718. }
  719. }
  720. bool Node::doEnumerateRecursive(const Node* node, const std::string &name, std::function<bool (Node *)> callback) const
  721. {
  722. bool ret =false;
  723. if (node->doEnumerate(name, callback))
  724. {
  725. // search itself
  726. ret = true;
  727. }
  728. else
  729. {
  730. // search its children
  731. for (const auto& child : node->getChildren())
  732. {
  733. if (doEnumerateRecursive(child, name, callback))
  734. {
  735. ret = true;
  736. break;
  737. }
  738. }
  739. }
  740. return ret;
  741. }
  742. bool Node::doEnumerate(std::string name, std::function<bool (Node *)> callback) const
  743. {
  744. // name may be xxx/yyy, should find its parent
  745. size_t pos = name.find('/');
  746. std::string searchName = name;
  747. bool needRecursive = false;
  748. if (pos != name.npos)
  749. {
  750. searchName = name.substr(0, pos);
  751. name.erase(0, pos+1);
  752. needRecursive = true;
  753. }
  754. bool ret = false;
  755. for (const auto& child : getChildren())
  756. {
  757. if (std::regex_match(child->_name, std::regex(searchName)))
  758. {
  759. if (!needRecursive)
  760. {
  761. // terminate enumeration if callback return true
  762. if (callback(child))
  763. {
  764. ret = true;
  765. break;
  766. }
  767. }
  768. else
  769. {
  770. ret = child->doEnumerate(name, callback);
  771. if (ret)
  772. break;
  773. }
  774. }
  775. }
  776. return ret;
  777. }
  778. /* "add" logic MUST only be on this method
  779. * If a class want's to extend the 'addChild' behavior it only needs
  780. * to override this method
  781. */
  782. void Node::addChild(Node *child, int localZOrder, int tag)
  783. {
  784. CCASSERT( child != nullptr, "Argument must be non-nil");
  785. CCASSERT( child->_parent == nullptr, "child already added. It can't be added again");
  786. addChildHelper(child, localZOrder, tag, "", true);
  787. }
  788. void Node::addChild(Node* child, int localZOrder, const std::string &name)
  789. {
  790. CCASSERT(child != nullptr, "Argument must be non-nil");
  791. CCASSERT(child->_parent == nullptr, "child already added. It can't be added again");
  792. addChildHelper(child, localZOrder, INVALID_TAG, name, false);
  793. }
  794. void Node::addChildHelper(Node* child, int localZOrder, int tag, const std::string &name, bool setTag)
  795. {
  796. auto assertNotSelfChild
  797. ( [ this, child ]() -> bool
  798. {
  799. for ( Node* parent( getParent() ); parent != nullptr;
  800. parent = parent->getParent() )
  801. if ( parent == child )
  802. return false;
  803. return true;
  804. } );
  805. (void)assertNotSelfChild;
  806. CCASSERT( assertNotSelfChild(),
  807. "A node cannot be the child of his own children" );
  808. if (_children.empty())
  809. {
  810. this->childrenAlloc();
  811. }
  812. this->insertChild(child, localZOrder);
  813. if (setTag)
  814. child->setTag(tag);
  815. else
  816. child->setName(name);
  817. child->setParent(this);
  818. child->updateOrderOfArrival();
  819. if( _running )
  820. {
  821. child->onEnter();
  822. // prevent onEnterTransitionDidFinish to be called twice when a node is added in onEnter
  823. if (_isTransitionFinished)
  824. {
  825. child->onEnterTransitionDidFinish();
  826. }
  827. }
  828. if (_cascadeColorEnabled)
  829. {
  830. updateCascadeColor();
  831. }
  832. if (_cascadeOpacityEnabled)
  833. {
  834. updateCascadeOpacity();
  835. }
  836. }
  837. void Node::addChild(Node *child, int zOrder)
  838. {
  839. CCASSERT( child != nullptr, "Argument must be non-nil");
  840. this->addChild(child, zOrder, child->_name);
  841. }
  842. void Node::addChild(Node *child)
  843. {
  844. CCASSERT( child != nullptr, "Argument must be non-nil");
  845. this->addChild(child, child->getLocalZOrder(), child->_name);
  846. }
  847. void Node::removeFromParent()
  848. {
  849. this->removeFromParentAndCleanup(true);
  850. }
  851. void Node::removeFromParentAndCleanup(bool cleanup)
  852. {
  853. if (_parent != nullptr)
  854. {
  855. _parent->removeChild(this,cleanup);
  856. }
  857. }
  858. /* "remove" logic MUST only be on this method
  859. * If a class want's to extend the 'removeChild' behavior it only needs
  860. * to override this method
  861. */
  862. void Node::removeChild(Node* child, bool cleanup /* = true */)
  863. {
  864. // explicit nil handling
  865. if (_children.empty())
  866. {
  867. return;
  868. }
  869. ssize_t index = _children.getIndex(child);
  870. if( index != CC_INVALID_INDEX )
  871. this->detachChild( child, index, cleanup );
  872. }
  873. void Node::removeChildByTag(int tag, bool cleanup/* = true */)
  874. {
  875. CCASSERT( tag != Node::INVALID_TAG, "Invalid tag");
  876. Node *child = this->getChildByTag(tag);
  877. if (child == nullptr)
  878. {
  879. CCLOG("cocos2d: removeChildByTag(tag = %d): child not found!", tag);
  880. }
  881. else
  882. {
  883. this->removeChild(child, cleanup);
  884. }
  885. }
  886. void Node::removeChildByName(const std::string &name, bool cleanup)
  887. {
  888. CCASSERT(!name.empty(), "Invalid name");
  889. Node *child = this->getChildByName(name);
  890. if (child == nullptr)
  891. {
  892. CCLOG("cocos2d: removeChildByName(name = %s): child not found!", name.c_str());
  893. }
  894. else
  895. {
  896. this->removeChild(child, cleanup);
  897. }
  898. }
  899. void Node::removeAllChildren()
  900. {
  901. this->removeAllChildrenWithCleanup(true);
  902. }
  903. void Node::removeAllChildrenWithCleanup(bool cleanup)
  904. {
  905. // not using detachChild improves speed here
  906. for (const auto& child : _children)
  907. {
  908. // IMPORTANT:
  909. // -1st do onExit
  910. // -2nd cleanup
  911. if(_running)
  912. {
  913. child->onExitTransitionDidStart();
  914. child->onExit();
  915. }
  916. if (cleanup)
  917. {
  918. child->cleanup();
  919. }
  920. #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
  921. auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
  922. if (sEngine)
  923. {
  924. sEngine->releaseScriptObject(this, child);
  925. }
  926. #endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
  927. // set parent nil at the end
  928. child->setParent(nullptr);
  929. }
  930. _children.clear();
  931. }
  932. void Node::detachChild(Node *child, ssize_t childIndex, bool doCleanup)
  933. {
  934. // IMPORTANT:
  935. // -1st do onExit
  936. // -2nd cleanup
  937. if (_running)
  938. {
  939. child->onExitTransitionDidStart();
  940. child->onExit();
  941. }
  942. // If you don't do cleanup, the child's actions will not get removed and the
  943. // its scheduledSelectors_ dict will not get released!
  944. if (doCleanup)
  945. {
  946. child->cleanup();
  947. }
  948. #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
  949. auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
  950. if (sEngine)
  951. {
  952. sEngine->releaseScriptObject(this, child);
  953. }
  954. #endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
  955. // set parent nil at the end
  956. child->setParent(nullptr);
  957. _children.erase(childIndex);
  958. }
  959. // helper used by reorderChild & add
  960. void Node::insertChild(Node* child, int z)
  961. {
  962. #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
  963. auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
  964. if (sEngine)
  965. {
  966. sEngine->retainScriptObject(this, child);
  967. }
  968. #endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
  969. _transformUpdated = true;
  970. _reorderChildDirty = true;
  971. _children.pushBack(child);
  972. child->_setLocalZOrder(z);
  973. }
  974. void Node::reorderChild(Node *child, int zOrder)
  975. {
  976. CCASSERT( child != nullptr, "Child must be non-nil");
  977. _reorderChildDirty = true;
  978. child->updateOrderOfArrival();
  979. child->_setLocalZOrder(zOrder);
  980. }
  981. void Node::sortAllChildren()
  982. {
  983. if (_reorderChildDirty)
  984. {
  985. sortNodes(_children);
  986. _reorderChildDirty = false;
  987. _eventDispatcher->setDirtyForNode(this);
  988. }
  989. }
  990. // MARK: draw / visit
  991. void Node::draw()
  992. {
  993. auto renderer = _director->getRenderer();
  994. draw(renderer, _modelViewTransform, true);
  995. }
  996. void Node::draw(Renderer* /*renderer*/, const Mat4 & /*transform*/, uint32_t /*flags*/)
  997. {
  998. }
  999. void Node::visit()
  1000. {
  1001. auto renderer = _director->getRenderer();
  1002. auto& parentTransform = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
  1003. visit(renderer, parentTransform, true);
  1004. }
  1005. uint32_t Node::processParentFlags(const Mat4& parentTransform, uint32_t parentFlags)
  1006. {
  1007. if(_usingNormalizedPosition)
  1008. {
  1009. CCASSERT(_parent, "setPositionNormalized() doesn't work with orphan nodes");
  1010. if ((parentFlags & FLAGS_CONTENT_SIZE_DIRTY) || _normalizedPositionDirty)
  1011. {
  1012. auto& s = _parent->getContentSize();
  1013. _position.x = _normalizedPosition.x * s.width;
  1014. _position.y = _normalizedPosition.y * s.height;
  1015. _transformUpdated = _transformDirty = _inverseDirty = true;
  1016. _normalizedPositionDirty = false;
  1017. }
  1018. }
  1019. // Fixes Github issue #16100. Basically when having two cameras, one camera might set as dirty the
  1020. // node that is not visited by it, and might affect certain calculations. Besides, it is faster to do this.
  1021. if (!isVisitableByVisitingCamera())
  1022. return parentFlags;
  1023. uint32_t flags = parentFlags;
  1024. flags |= (_transformUpdated ? FLAGS_TRANSFORM_DIRTY : 0);
  1025. flags |= (_contentSizeDirty ? FLAGS_CONTENT_SIZE_DIRTY : 0);
  1026. if(flags & FLAGS_DIRTY_MASK)
  1027. _modelViewTransform = this->transform(parentTransform);
  1028. _transformUpdated = false;
  1029. _contentSizeDirty = false;
  1030. return flags;
  1031. }
  1032. bool Node::isVisitableByVisitingCamera() const
  1033. {
  1034. auto camera = Camera::getVisitingCamera();
  1035. bool visibleByCamera = camera ? ((unsigned short)camera->getCameraFlag() & _cameraMask) != 0 : true;
  1036. return visibleByCamera;
  1037. }
  1038. void Node::visit(Renderer* renderer, const Mat4 &parentTransform, uint32_t parentFlags)
  1039. {
  1040. // quick return if not visible. children won't be drawn.
  1041. if (!_visible)
  1042. {
  1043. return;
  1044. }
  1045. uint32_t flags = processParentFlags(parentTransform, parentFlags);
  1046. // IMPORTANT:
  1047. // To ease the migration to v3.0, we still support the Mat4 stack,
  1048. // but it is deprecated and your code should not rely on it
  1049. _director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
  1050. _director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
  1051. bool visibleByCamera = isVisitableByVisitingCamera();
  1052. int i = 0;
  1053. if(!_children.empty())
  1054. {
  1055. sortAllChildren();
  1056. // draw children zOrder < 0
  1057. for(auto size = _children.size(); i < size; ++i)
  1058. {
  1059. auto node = _children.at(i);
  1060. if (node && node->_localZOrder < 0)
  1061. node->visit(renderer, _modelViewTransform, flags);
  1062. else
  1063. break;
  1064. }
  1065. // self draw
  1066. if (visibleByCamera)
  1067. this->draw(renderer, _modelViewTransform, flags);
  1068. for(auto it=_children.cbegin()+i, itCend = _children.cend(); it != itCend; ++it)
  1069. (*it)->visit(renderer, _modelViewTransform, flags);
  1070. }
  1071. else if (visibleByCamera)
  1072. {
  1073. this->draw(renderer, _modelViewTransform, flags);
  1074. }
  1075. _director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
  1076. // FIX ME: Why need to set _orderOfArrival to 0??
  1077. // Please refer to https://github.com/cocos2d/cocos2d-x/pull/6920
  1078. // reset for next frame
  1079. // _orderOfArrival = 0;
  1080. }
  1081. Mat4 Node::transform(const Mat4& parentTransform)
  1082. {
  1083. return parentTransform * this->getNodeToParentTransform();
  1084. }
  1085. // MARK: events
  1086. void Node::onEnter()
  1087. {
  1088. if (!_running)
  1089. {
  1090. ++__attachedNodeCount;
  1091. }
  1092. #if CC_ENABLE_SCRIPT_BINDING
  1093. if (_scriptType == kScriptTypeJavascript)
  1094. {
  1095. if (ScriptEngineManager::sendNodeEventToJS(this, kNodeOnEnter))
  1096. return;
  1097. }
  1098. #endif
  1099. if (_onEnterCallback)
  1100. _onEnterCallback();
  1101. if (_componentContainer && !_componentContainer->isEmpty())
  1102. {
  1103. _componentContainer->onEnter();
  1104. }
  1105. _isTransitionFinished = false;
  1106. //LLJ 这里改写法,在连本地服务器时,这里因为空指针的原因会报异常崩溃
  1107. /*for( const auto &child: _children)
  1108. child->onEnter();*/
  1109. if (_children.size() > 0)
  1110. {
  1111. for (int i=0;i< _children.size();i++)
  1112. {
  1113. const auto &child = _children.at(i);
  1114. if (child)
  1115. {
  1116. child->onEnter();
  1117. }
  1118. }
  1119. }
  1120. this->resume();
  1121. _running = true;
  1122. #if CC_ENABLE_SCRIPT_BINDING
  1123. if (_scriptType == kScriptTypeLua)
  1124. {
  1125. ScriptEngineManager::sendNodeEventToLua(this, kNodeOnEnter);
  1126. }
  1127. #endif
  1128. }
  1129. void Node::onEnterTransitionDidFinish()
  1130. {
  1131. #if CC_ENABLE_SCRIPT_BINDING
  1132. if (_scriptType == kScriptTypeJavascript)
  1133. {
  1134. if (ScriptEngineManager::sendNodeEventToJS(this, kNodeOnEnterTransitionDidFinish))
  1135. return;
  1136. }
  1137. #endif
  1138. if (_onEnterTransitionDidFinishCallback)
  1139. _onEnterTransitionDidFinishCallback();
  1140. _isTransitionFinished = true;
  1141. for( const auto &child: _children)
  1142. child->onEnterTransitionDidFinish();
  1143. #if CC_ENABLE_SCRIPT_BINDING
  1144. if (_scriptType == kScriptTypeLua)
  1145. {
  1146. ScriptEngineManager::sendNodeEventToLua(this, kNodeOnEnterTransitionDidFinish);
  1147. }
  1148. #endif
  1149. }
  1150. void Node::onExitTransitionDidStart()
  1151. {
  1152. #if CC_ENABLE_SCRIPT_BINDING
  1153. if (_scriptType == kScriptTypeJavascript)
  1154. {
  1155. if (ScriptEngineManager::sendNodeEventToJS(this, kNodeOnExitTransitionDidStart))
  1156. return;
  1157. }
  1158. #endif
  1159. if (_onExitTransitionDidStartCallback)
  1160. _onExitTransitionDidStartCallback();
  1161. for( const auto &child: _children)
  1162. child->onExitTransitionDidStart();
  1163. #if CC_ENABLE_SCRIPT_BINDING
  1164. if (_scriptType == kScriptTypeLua)
  1165. {
  1166. ScriptEngineManager::sendNodeEventToLua(this, kNodeOnExitTransitionDidStart);
  1167. }
  1168. #endif
  1169. }
  1170. void Node::onExit()
  1171. {
  1172. if (_running)
  1173. {
  1174. --__attachedNodeCount;
  1175. }
  1176. #if CC_ENABLE_SCRIPT_BINDING
  1177. if (_scriptType == kScriptTypeJavascript)
  1178. {
  1179. if (ScriptEngineManager::sendNodeEventToJS(this, kNodeOnExit))
  1180. return;
  1181. }
  1182. #endif
  1183. if (_onExitCallback)
  1184. _onExitCallback();
  1185. if (_componentContainer && !_componentContainer->isEmpty())
  1186. {
  1187. _componentContainer->onExit();
  1188. }
  1189. this->pause();
  1190. _running = false;
  1191. for( const auto &child: _children)
  1192. child->onExit();
  1193. #if CC_ENABLE_SCRIPT_BINDING
  1194. if (_scriptType == kScriptTypeLua)
  1195. {
  1196. ScriptEngineManager::sendNodeEventToLua(this, kNodeOnExit);
  1197. }
  1198. #endif
  1199. }
  1200. void Node::setEventDispatcher(EventDispatcher* dispatcher)
  1201. {
  1202. if (dispatcher != _eventDispatcher)
  1203. {
  1204. _eventDispatcher->removeEventListenersForTarget(this);
  1205. CC_SAFE_RETAIN(dispatcher);
  1206. CC_SAFE_RELEASE(_eventDispatcher);
  1207. _eventDispatcher = dispatcher;
  1208. }
  1209. }
  1210. void Node::setActionManager(ActionManager* actionManager)
  1211. {
  1212. if( actionManager != _actionManager )
  1213. {
  1214. this->stopAllActions();
  1215. CC_SAFE_RETAIN(actionManager);
  1216. CC_SAFE_RELEASE(_actionManager);
  1217. _actionManager = actionManager;
  1218. }
  1219. }
  1220. // MARK: actions
  1221. Action * Node::runAction(Action* action)
  1222. {
  1223. CCASSERT( action != nullptr, "Argument must be non-nil");
  1224. _actionManager->addAction(action, this, !_running);
  1225. return action;
  1226. }
  1227. void Node::stopAllActions()
  1228. {
  1229. _actionManager->removeAllActionsFromTarget(this);
  1230. }
  1231. void Node::stopAction(Action* action)
  1232. {
  1233. _actionManager->removeAction(action);
  1234. }
  1235. void Node::stopActionByTag(int tag)
  1236. {
  1237. CCASSERT( tag != Action::INVALID_TAG, "Invalid tag");
  1238. _actionManager->removeActionByTag(tag, this);
  1239. }
  1240. void Node::stopAllActionsByTag(int tag)
  1241. {
  1242. CCASSERT( tag != Action::INVALID_TAG, "Invalid tag");
  1243. _actionManager->removeAllActionsByTag(tag, this);
  1244. }
  1245. void Node::stopActionsByFlags(unsigned int flags)
  1246. {
  1247. if (flags > 0)
  1248. {
  1249. _actionManager->removeActionsByFlags(flags, this);
  1250. }
  1251. }
  1252. Action * Node::getActionByTag(int tag)
  1253. {
  1254. CCASSERT( tag != Action::INVALID_TAG, "Invalid tag");
  1255. return _actionManager->getActionByTag(tag, this);
  1256. }
  1257. ssize_t Node::getNumberOfRunningActions() const
  1258. {
  1259. return _actionManager->getNumberOfRunningActionsInTarget(this);
  1260. }
  1261. ssize_t Node::getNumberOfRunningActionsByTag(int tag) const
  1262. {
  1263. return _actionManager->getNumberOfRunningActionsInTargetByTag(this, tag);
  1264. }
  1265. // MARK: Callbacks
  1266. void Node::setScheduler(Scheduler* scheduler)
  1267. {
  1268. if( scheduler != _scheduler )
  1269. {
  1270. this->unscheduleAllCallbacks();
  1271. CC_SAFE_RETAIN(scheduler);
  1272. CC_SAFE_RELEASE(_scheduler);
  1273. _scheduler = scheduler;
  1274. }
  1275. }
  1276. bool Node::isScheduled(SEL_SCHEDULE selector) const
  1277. {
  1278. return _scheduler->isScheduled(selector, this);
  1279. }
  1280. bool Node::isScheduled(const std::string &key) const
  1281. {
  1282. return _scheduler->isScheduled(key, this);
  1283. }
  1284. void Node::scheduleUpdate()
  1285. {
  1286. scheduleUpdateWithPriority(0);
  1287. }
  1288. void Node::scheduleUpdateWithPriority(int priority)
  1289. {
  1290. _scheduler->scheduleUpdate(this, priority, !_running);
  1291. }
  1292. void Node::scheduleUpdateWithPriorityLua(int nHandler, int priority)
  1293. {
  1294. unscheduleUpdate();
  1295. #if CC_ENABLE_SCRIPT_BINDING
  1296. _updateScriptHandler = nHandler;
  1297. #endif
  1298. _scheduler->scheduleUpdate(this, priority, !_running);
  1299. }
  1300. void Node::unscheduleUpdate()
  1301. {
  1302. _scheduler->unscheduleUpdate(this);
  1303. #if CC_ENABLE_SCRIPT_BINDING
  1304. if (_updateScriptHandler)
  1305. {
  1306. ScriptEngineManager::getInstance()->getScriptEngine()->removeScriptHandler(_updateScriptHandler);
  1307. _updateScriptHandler = 0;
  1308. }
  1309. #endif
  1310. }
  1311. void Node::schedule(SEL_SCHEDULE selector)
  1312. {
  1313. this->schedule(selector, 0.0f, CC_REPEAT_FOREVER, 0.0f);
  1314. }
  1315. void Node::schedule(SEL_SCHEDULE selector, float interval)
  1316. {
  1317. this->schedule(selector, interval, CC_REPEAT_FOREVER, 0.0f);
  1318. }
  1319. void Node::schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, float delay)
  1320. {
  1321. CCASSERT( selector, "Argument must be non-nil");
  1322. CCASSERT( interval >=0, "Argument must be positive");
  1323. _scheduler->schedule(selector, this, interval , repeat, delay, !_running);
  1324. }
  1325. void Node::schedule(const std::function<void(float)> &callback, const std::string &key)
  1326. {
  1327. _scheduler->schedule(callback, this, 0, !_running, key);
  1328. }
  1329. void Node::schedule(const std::function<void(float)> &callback, float interval, const std::string &key)
  1330. {
  1331. _scheduler->schedule(callback, this, interval, !_running, key);
  1332. }
  1333. void Node::schedule(const std::function<void(float)>& callback, float interval, unsigned int repeat, float delay, const std::string &key)
  1334. {
  1335. _scheduler->schedule(callback, this, interval, repeat, delay, !_running, key);
  1336. }
  1337. void Node::scheduleOnce(SEL_SCHEDULE selector, float delay)
  1338. {
  1339. this->schedule(selector, 0.0f, 0, delay);
  1340. }
  1341. void Node::scheduleOnce(const std::function<void(float)> &callback, float delay, const std::string &key)
  1342. {
  1343. _scheduler->schedule(callback, this, 0, 0, delay, !_running, key);
  1344. }
  1345. void Node::unschedule(SEL_SCHEDULE selector)
  1346. {
  1347. // explicit null handling
  1348. if (selector == nullptr)
  1349. return;
  1350. _scheduler->unschedule(selector, this);
  1351. }
  1352. void Node::unschedule(const std::string &key)
  1353. {
  1354. _scheduler->unschedule(key, this);
  1355. }
  1356. void Node::unscheduleAllCallbacks()
  1357. {
  1358. _scheduler->unscheduleAllForTarget(this);
  1359. }
  1360. void Node::resume()
  1361. {
  1362. _scheduler->resumeTarget(this);
  1363. _actionManager->resumeTarget(this);
  1364. _eventDispatcher->resumeEventListenersForTarget(this);
  1365. }
  1366. void Node::pause()
  1367. {
  1368. _scheduler->pauseTarget(this);
  1369. _actionManager->pauseTarget(this);
  1370. _eventDispatcher->pauseEventListenersForTarget(this);
  1371. }
  1372. void Node::resumeSchedulerAndActions()
  1373. {
  1374. resume();
  1375. }
  1376. void Node::pauseSchedulerAndActions()
  1377. {
  1378. pause();
  1379. }
  1380. // override me
  1381. void Node::update(float fDelta)
  1382. {
  1383. #if CC_ENABLE_SCRIPT_BINDING
  1384. if (0 != _updateScriptHandler)
  1385. {
  1386. //only lua use
  1387. SchedulerScriptData data(_updateScriptHandler,fDelta);
  1388. ScriptEvent event(kScheduleEvent,&data);
  1389. ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
  1390. }
  1391. #endif
  1392. if (_componentContainer && !_componentContainer->isEmpty())
  1393. {
  1394. _componentContainer->visit(fDelta);
  1395. }
  1396. }
  1397. // MARK: coordinates
  1398. AffineTransform Node::getNodeToParentAffineTransform() const
  1399. {
  1400. AffineTransform ret;
  1401. GLToCGAffine(getNodeToParentTransform().m, &ret);
  1402. return ret;
  1403. }
  1404. Mat4 Node::getNodeToParentTransform(Node* ancestor) const
  1405. {
  1406. Mat4 t(this->getNodeToParentTransform());
  1407. for (Node *p = _parent; p != nullptr && p != ancestor ; p = p->getParent())
  1408. {
  1409. t = p->getNodeToParentTransform() * t;
  1410. }
  1411. return t;
  1412. }
  1413. AffineTransform Node::getNodeToParentAffineTransform(Node* ancestor) const
  1414. {
  1415. AffineTransform t(this->getNodeToParentAffineTransform());
  1416. for (Node *p = _parent; p != nullptr && p != ancestor; p = p->getParent())
  1417. t = AffineTransformConcat(t, p->getNodeToParentAffineTransform());
  1418. return t;
  1419. }
  1420. const Mat4& Node::getNodeToParentTransform() const
  1421. {
  1422. if (_transformDirty)
  1423. {
  1424. // Translate values
  1425. float x = _position.x;
  1426. float y = _position.y;
  1427. float z = _positionZ;
  1428. if (_ignoreAnchorPointForPosition)
  1429. {
  1430. x += _anchorPointInPoints.x;
  1431. y += _anchorPointInPoints.y;
  1432. }
  1433. bool needsSkewMatrix = ( _skewX || _skewY );
  1434. // Build Transform Matrix = translation * rotation * scale
  1435. Mat4 translation;
  1436. //move to anchor point first, then rotate
  1437. Mat4::createTranslation(x, y, z, &translation);
  1438. Mat4::createRotation(_rotationQuat, &_transform);
  1439. if (_rotationZ_X != _rotationZ_Y)
  1440. {
  1441. // Rotation values
  1442. // Change rotation code to handle X and Y
  1443. // If we skew with the exact same value for both x and y then we're simply just rotating
  1444. float radiansX = -CC_DEGREES_TO_RADIANS(_rotationZ_X);
  1445. float radiansY = -CC_DEGREES_TO_RADIANS(_rotationZ_Y);
  1446. float cx = cosf(radiansX);
  1447. float sx = sinf(radiansX);
  1448. float cy = cosf(radiansY);
  1449. float sy = sinf(radiansY);
  1450. float m0 = _transform.m[0], m1 = _transform.m[1], m4 = _transform.m[4], m5 = _transform.m[5], m8 = _transform.m[8], m9 = _transform.m[9];
  1451. _transform.m[0] = cy * m0 - sx * m1, _transform.m[4] = cy * m4 - sx * m5, _transform.m[8] = cy * m8 - sx * m9;
  1452. _transform.m[1] = sy * m0 + cx * m1, _transform.m[5] = sy * m4 + cx * m5, _transform.m[9] = sy * m8 + cx * m9;
  1453. }
  1454. _transform = translation * _transform;
  1455. if (_scaleX != 1.f)
  1456. {
  1457. _transform.m[0] *= _scaleX, _transform.m[1] *= _scaleX, _transform.m[2] *= _scaleX;
  1458. }
  1459. if (_scaleY != 1.f)
  1460. {
  1461. _transform.m[4] *= _scaleY, _transform.m[5] *= _scaleY, _transform.m[6] *= _scaleY;
  1462. }
  1463. if (_scaleZ != 1.f)
  1464. {
  1465. _transform.m[8] *= _scaleZ, _transform.m[9] *= _scaleZ, _transform.m[10] *= _scaleZ;
  1466. }
  1467. // FIXME:: Try to inline skew
  1468. // If skew is needed, apply skew and then anchor point
  1469. if (needsSkewMatrix)
  1470. {
  1471. float skewMatArray[16] =
  1472. {
  1473. 1, (float)tanf(CC_DEGREES_TO_RADIANS(_skewY)), 0, 0,
  1474. (float)tanf(CC_DEGREES_TO_RADIANS(_skewX)), 1, 0, 0,
  1475. 0, 0, 1, 0,
  1476. 0, 0, 0, 1
  1477. };
  1478. Mat4 skewMatrix(skewMatArray);
  1479. _transform = _transform * skewMatrix;
  1480. }
  1481. // adjust anchor point
  1482. if (!_anchorPointInPoints.isZero())
  1483. {
  1484. // FIXME:: Argh, Mat4 needs a "translate" method.
  1485. // FIXME:: Although this is faster than multiplying a vec4 * mat4
  1486. _transform.m[12] += _transform.m[0] * -_anchorPointInPoints.x + _transform.m[4] * -_anchorPointInPoints.y;
  1487. _transform.m[13] += _transform.m[1] * -_anchorPointInPoints.x + _transform.m[5] * -_anchorPointInPoints.y;
  1488. _transform.m[14] += _transform.m[2] * -_anchorPointInPoints.x + _transform.m[6] * -_anchorPointInPoints.y;
  1489. }
  1490. }
  1491. if (_additionalTransform)
  1492. {
  1493. // This is needed to support both Node::setNodeToParentTransform() and Node::setAdditionalTransform()
  1494. // at the same time. The scenario is this:
  1495. // at some point setNodeToParentTransform() is called.
  1496. // and later setAdditionalTransform() is called every time. And since _transform
  1497. // is being overwritten everyframe, _additionalTransform[1] is used to have a copy
  1498. // of the last "_transform without _additionalTransform"
  1499. if (_transformDirty)
  1500. _additionalTransform[1] = _transform;
  1501. if (_transformUpdated)
  1502. _transform = _additionalTransform[1] * _additionalTransform[0];
  1503. }
  1504. _transformDirty = _additionalTransformDirty = false;
  1505. return _transform;
  1506. }
  1507. void Node::setNodeToParentTransform(const Mat4& transform)
  1508. {
  1509. _transform = transform;
  1510. _transformDirty = false;
  1511. _transformUpdated = true;
  1512. if (_additionalTransform)
  1513. // _additionalTransform[1] has a copy of lastest transform
  1514. _additionalTransform[1] = transform;
  1515. }
  1516. void Node::setAdditionalTransform(const AffineTransform& additionalTransform)
  1517. {
  1518. Mat4 tmp;
  1519. CGAffineToGL(additionalTransform, tmp.m);
  1520. setAdditionalTransform(&tmp);
  1521. }
  1522. void Node::setAdditionalTransform(const Mat4* additionalTransform)
  1523. {
  1524. if (additionalTransform == nullptr)
  1525. {
  1526. if(_additionalTransform) _transform = _additionalTransform[1];
  1527. delete[] _additionalTransform;
  1528. _additionalTransform = nullptr;
  1529. }
  1530. else
  1531. {
  1532. if (!_additionalTransform) {
  1533. _additionalTransform = new Mat4[2];
  1534. // _additionalTransform[1] is used as a backup for _transform
  1535. _additionalTransform[1] = _transform;
  1536. }
  1537. _additionalTransform[0] = *additionalTransform;
  1538. }
  1539. _transformUpdated = _additionalTransformDirty = _inverseDirty = true;
  1540. }
  1541. void Node::setAdditionalTransform(const Mat4& additionalTransform)
  1542. {
  1543. setAdditionalTransform(&additionalTransform);
  1544. }
  1545. AffineTransform Node::getParentToNodeAffineTransform() const
  1546. {
  1547. AffineTransform ret;
  1548. GLToCGAffine(getParentToNodeTransform().m,&ret);
  1549. return ret;
  1550. }
  1551. const Mat4& Node::getParentToNodeTransform() const
  1552. {
  1553. if ( _inverseDirty )
  1554. {
  1555. _inverse = getNodeToParentTransform().getInversed();
  1556. _inverseDirty = false;
  1557. }
  1558. return _inverse;
  1559. }
  1560. AffineTransform Node::getNodeToWorldAffineTransform() const
  1561. {
  1562. return this->getNodeToParentAffineTransform(nullptr);
  1563. }
  1564. Mat4 Node::getNodeToWorldTransform() const
  1565. {
  1566. return this->getNodeToParentTransform(nullptr);
  1567. }
  1568. AffineTransform Node::getWorldToNodeAffineTransform() const
  1569. {
  1570. return AffineTransformInvert(this->getNodeToWorldAffineTransform());
  1571. }
  1572. Mat4 Node::getWorldToNodeTransform() const
  1573. {
  1574. return getNodeToWorldTransform().getInversed();
  1575. }
  1576. Vec2 Node::convertToNodeSpace(const Vec2& worldPoint) const
  1577. {
  1578. Mat4 tmp = getWorldToNodeTransform();
  1579. Vec3 vec3(worldPoint.x, worldPoint.y, 0);
  1580. Vec3 ret;
  1581. tmp.transformPoint(vec3,&ret);
  1582. return Vec2(ret.x, ret.y);
  1583. }
  1584. Vec2 Node::convertToWorldSpace(const Vec2& nodePoint) const
  1585. {
  1586. Mat4 tmp = getNodeToWorldTransform();
  1587. Vec3 vec3(nodePoint.x, nodePoint.y, 0);
  1588. Vec3 ret;
  1589. tmp.transformPoint(vec3,&ret);
  1590. return Vec2(ret.x, ret.y);
  1591. }
  1592. Vec2 Node::convertToNodeSpaceAR(const Vec2& worldPoint) const
  1593. {
  1594. Vec2 nodePoint(convertToNodeSpace(worldPoint));
  1595. return nodePoint - _anchorPointInPoints;
  1596. }
  1597. Vec2 Node::convertToWorldSpaceAR(const Vec2& nodePoint) const
  1598. {
  1599. return convertToWorldSpace(nodePoint + _anchorPointInPoints);
  1600. }
  1601. Vec2 Node::convertToWindowSpace(const Vec2& nodePoint) const
  1602. {
  1603. Vec2 worldPoint(this->convertToWorldSpace(nodePoint));
  1604. return _director->convertToUI(worldPoint);
  1605. }
  1606. // convenience methods which take a Touch instead of Vec2
  1607. Vec2 Node::convertTouchToNodeSpace(Touch *touch) const
  1608. {
  1609. return this->convertToNodeSpace(touch->getLocation());
  1610. }
  1611. Vec2 Node::convertTouchToNodeSpaceAR(Touch *touch) const
  1612. {
  1613. Vec2 point = touch->getLocation();
  1614. return this->convertToNodeSpaceAR(point);
  1615. }
  1616. void Node::updateTransform()
  1617. {
  1618. // Recursively iterate over children
  1619. for( const auto &child: _children)
  1620. child->updateTransform();
  1621. }
  1622. // MARK: components
  1623. Component* Node::getComponent(const std::string& name)
  1624. {
  1625. if (_componentContainer)
  1626. return _componentContainer->get(name);
  1627. return nullptr;
  1628. }
  1629. bool Node::addComponent(Component *component)
  1630. {
  1631. // lazy alloc
  1632. if (!_componentContainer)
  1633. _componentContainer = new (std::nothrow) ComponentContainer(this);
  1634. // should enable schedule update, then all components can receive this call back
  1635. scheduleUpdate();
  1636. return _componentContainer->add(component);
  1637. }
  1638. bool Node::removeComponent(const std::string& name)
  1639. {
  1640. if (_componentContainer)
  1641. return _componentContainer->remove(name);
  1642. return false;
  1643. }
  1644. bool Node::removeComponent(Component *component)
  1645. {
  1646. if (_componentContainer)
  1647. {
  1648. return _componentContainer->remove(component);
  1649. }
  1650. return false;
  1651. }
  1652. void Node::removeAllComponents()
  1653. {
  1654. if (_componentContainer)
  1655. _componentContainer->removeAll();
  1656. }
  1657. // MARK: Opacity and Color
  1658. GLubyte Node::getOpacity(void) const
  1659. {
  1660. return _realOpacity;
  1661. }
  1662. GLubyte Node::getDisplayedOpacity() const
  1663. {
  1664. return _displayedOpacity;
  1665. }
  1666. void Node::setOpacity(GLubyte opacity)
  1667. {
  1668. _displayedOpacity = _realOpacity = opacity;
  1669. updateCascadeOpacity();
  1670. }
  1671. void Node::updateDisplayedOpacity(GLubyte parentOpacity)
  1672. {
  1673. _displayedOpacity = _realOpacity * parentOpacity/255.0;
  1674. updateColor();
  1675. if (_cascadeOpacityEnabled)
  1676. {
  1677. for(const auto& child : _children)
  1678. {
  1679. child->updateDisplayedOpacity(_displayedOpacity);
  1680. }
  1681. }
  1682. }
  1683. bool Node::isCascadeOpacityEnabled(void) const
  1684. {
  1685. return _cascadeOpacityEnabled;
  1686. }
  1687. void Node::setCascadeOpacityEnabled(bool cascadeOpacityEnabled)
  1688. {
  1689. if (_cascadeOpacityEnabled == cascadeOpacityEnabled)
  1690. {
  1691. return;
  1692. }
  1693. _cascadeOpacityEnabled = cascadeOpacityEnabled;
  1694. if (cascadeOpacityEnabled)
  1695. {
  1696. updateCascadeOpacity();
  1697. }
  1698. else
  1699. {
  1700. disableCascadeOpacity();
  1701. }
  1702. }
  1703. void Node::updateCascadeOpacity()
  1704. {
  1705. GLubyte parentOpacity = 255;
  1706. if (_parent != nullptr && _parent->isCascadeOpacityEnabled())
  1707. {
  1708. parentOpacity = _parent->getDisplayedOpacity();
  1709. }
  1710. updateDisplayedOpacity(parentOpacity);
  1711. }
  1712. void Node::disableCascadeOpacity()
  1713. {
  1714. _displayedOpacity = _realOpacity;
  1715. for(const auto& child : _children)
  1716. {
  1717. child->updateDisplayedOpacity(255);
  1718. }
  1719. }
  1720. void Node::setOpacityModifyRGB(bool /*value*/)
  1721. {}
  1722. bool Node::isOpacityModifyRGB() const
  1723. {
  1724. return false;
  1725. }
  1726. const Color3B& Node::getColor(void) const
  1727. {
  1728. return _realColor;
  1729. }
  1730. const Color3B& Node::getDisplayedColor() const
  1731. {
  1732. return _displayedColor;
  1733. }
  1734. void Node::setColor(const Color3B& color)
  1735. {
  1736. _displayedColor = _realColor = color;
  1737. updateCascadeColor();
  1738. }
  1739. void Node::updateDisplayedColor(const Color3B& parentColor)
  1740. {
  1741. _displayedColor.r = _realColor.r * parentColor.r/255.0;
  1742. _displayedColor.g = _realColor.g * parentColor.g/255.0;
  1743. _displayedColor.b = _realColor.b * parentColor.b/255.0;
  1744. updateColor();
  1745. if (_cascadeColorEnabled)
  1746. {
  1747. for(const auto &child : _children)
  1748. {
  1749. child->updateDisplayedColor(_displayedColor);
  1750. }
  1751. }
  1752. }
  1753. bool Node::isCascadeColorEnabled(void) const
  1754. {
  1755. return _cascadeColorEnabled;
  1756. }
  1757. void Node::setCascadeColorEnabled(bool cascadeColorEnabled)
  1758. {
  1759. if (_cascadeColorEnabled == cascadeColorEnabled)
  1760. {
  1761. return;
  1762. }
  1763. _cascadeColorEnabled = cascadeColorEnabled;
  1764. if (_cascadeColorEnabled)
  1765. {
  1766. updateCascadeColor();
  1767. }
  1768. else
  1769. {
  1770. disableCascadeColor();
  1771. }
  1772. }
  1773. void Node::updateCascadeColor()
  1774. {
  1775. Color3B parentColor = Color3B::WHITE;
  1776. if (_parent && _parent->isCascadeColorEnabled())
  1777. {
  1778. parentColor = _parent->getDisplayedColor();
  1779. }
  1780. updateDisplayedColor(parentColor);
  1781. }
  1782. void Node::disableCascadeColor()
  1783. {
  1784. for(const auto& child : _children)
  1785. {
  1786. child->updateDisplayedColor(Color3B::WHITE);
  1787. }
  1788. }
  1789. bool isScreenPointInRect(const Vec2 &pt, const Camera* camera, const Mat4& w2l, const Rect& rect, Vec3 *p)
  1790. {
  1791. if (nullptr == camera || rect.size.width <= 0 || rect.size.height <= 0)
  1792. {
  1793. return false;
  1794. }
  1795. // first, convert pt to near/far plane, get Pn and Pf
  1796. Vec3 Pn(pt.x, pt.y, -1), Pf(pt.x, pt.y, 1);
  1797. Pn = camera->unprojectGL(Pn);
  1798. Pf = camera->unprojectGL(Pf);
  1799. // then convert Pn and Pf to node space
  1800. w2l.transformPoint(&Pn);
  1801. w2l.transformPoint(&Pf);
  1802. // Pn and Pf define a line Q(t) = D + t * E which D = Pn
  1803. auto E = Pf - Pn;
  1804. // second, get three points which define content plane
  1805. // these points define a plane P(u, w) = A + uB + wC
  1806. Vec3 A = Vec3(rect.origin.x, rect.origin.y, 0);
  1807. Vec3 B(rect.origin.x + rect.size.width, rect.origin.y, 0);
  1808. Vec3 C(rect.origin.x, rect.origin.y + rect.size.height, 0);
  1809. B = B - A;
  1810. C = C - A;
  1811. // the line Q(t) intercept with plane P(u, w)
  1812. // calculate the intercept point P = Q(t)
  1813. // (BxC).A - (BxC).D
  1814. // t = -----------------
  1815. // (BxC).E
  1816. Vec3 BxC;
  1817. Vec3::cross(B, C, &BxC);
  1818. auto BxCdotE = BxC.dot(E);
  1819. if (BxCdotE == 0) {
  1820. return false;
  1821. }
  1822. auto t = (BxC.dot(A) - BxC.dot(Pn)) / BxCdotE;
  1823. Vec3 P = Pn + t * E;
  1824. if (p) {
  1825. *p = P;
  1826. }
  1827. return rect.containsPoint(Vec2(P.x, P.y));
  1828. }
  1829. // MARK: Camera
  1830. void Node::setCameraMask(unsigned short mask, bool applyChildren)
  1831. {
  1832. _cameraMask = mask;
  1833. if (applyChildren)
  1834. {
  1835. for (const auto& child : _children)
  1836. {
  1837. child->setCameraMask(mask, applyChildren);
  1838. }
  1839. }
  1840. }
  1841. int Node::getAttachedNodeCount()
  1842. {
  1843. return __attachedNodeCount;
  1844. }
  1845. // MARK: Deprecated
  1846. __NodeRGBA::__NodeRGBA()
  1847. {
  1848. CCLOG("NodeRGBA deprecated.");
  1849. }
  1850. NS_CC_END