1
0

CCSprite.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715
  1. /****************************************************************************
  2. Copyright (c) 2008-2010 Ricardo Quesada
  3. Copyright (c) 2010-2012 cocos2d-x.org
  4. Copyright (c) 2011 Zynga Inc.
  5. Copyright (c) 2013-2017 Chukong Technologies Inc.
  6. http://www.cocos2d-x.org
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. ****************************************************************************/
  23. #include "2d/CCSprite.h"
  24. #include <algorithm>
  25. #include "2d/CCSpriteBatchNode.h"
  26. #include "2d/CCAnimationCache.h"
  27. #include "2d/CCSpriteFrame.h"
  28. #include "2d/CCSpriteFrameCache.h"
  29. #include "renderer/CCTextureCache.h"
  30. #include "renderer/CCTexture2D.h"
  31. #include "renderer/CCRenderer.h"
  32. #include "base/CCDirector.h"
  33. #include "base/ccUTF8.h"
  34. #include "2d/CCCamera.h"
  35. NS_CC_BEGIN
  36. // MARK: create, init, dealloc
  37. Sprite* Sprite::createWithTexture(Texture2D *texture)
  38. {
  39. Sprite *sprite = new (std::nothrow) Sprite();
  40. if (sprite && sprite->initWithTexture(texture))
  41. {
  42. sprite->autorelease();
  43. return sprite;
  44. }
  45. CC_SAFE_DELETE(sprite);
  46. return nullptr;
  47. }
  48. Sprite* Sprite::createWithTexture(Texture2D *texture, const Rect& rect, bool rotated)
  49. {
  50. Sprite *sprite = new (std::nothrow) Sprite();
  51. if (sprite && sprite->initWithTexture(texture, rect, rotated))
  52. {
  53. sprite->autorelease();
  54. return sprite;
  55. }
  56. CC_SAFE_DELETE(sprite);
  57. return nullptr;
  58. }
  59. Sprite* Sprite::create(const std::string& filename)
  60. {
  61. Sprite *sprite = new (std::nothrow) Sprite();
  62. if (sprite && sprite->initWithFile(filename))
  63. {
  64. sprite->autorelease();
  65. return sprite;
  66. }
  67. CC_SAFE_DELETE(sprite);
  68. return nullptr;
  69. }
  70. Sprite* Sprite::create(const PolygonInfo& info)
  71. {
  72. Sprite *sprite = new (std::nothrow) Sprite();
  73. if(sprite && sprite->initWithPolygon(info))
  74. {
  75. sprite->autorelease();
  76. return sprite;
  77. }
  78. CC_SAFE_DELETE(sprite);
  79. return nullptr;
  80. }
  81. Sprite* Sprite::create(const std::string& filename, const Rect& rect)
  82. {
  83. Sprite *sprite = new (std::nothrow) Sprite();
  84. if (sprite && sprite->initWithFile(filename, rect))
  85. {
  86. sprite->autorelease();
  87. return sprite;
  88. }
  89. CC_SAFE_DELETE(sprite);
  90. return nullptr;
  91. }
  92. Sprite* Sprite::createWithSpriteFrame(SpriteFrame *spriteFrame)
  93. {
  94. Sprite *sprite = new (std::nothrow) Sprite();
  95. if (sprite && spriteFrame && sprite->initWithSpriteFrame(spriteFrame))
  96. {
  97. sprite->autorelease();
  98. return sprite;
  99. }
  100. CC_SAFE_DELETE(sprite);
  101. return nullptr;
  102. }
  103. Sprite* Sprite::createWithSpriteFrameName(const std::string& spriteFrameName)
  104. {
  105. SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName);
  106. #if COCOS2D_DEBUG > 0
  107. char msg[256] = {0};
  108. sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName.c_str());
  109. CCASSERT(frame != nullptr, msg);
  110. #endif
  111. return createWithSpriteFrame(frame);
  112. }
  113. Sprite* Sprite::create()
  114. {
  115. Sprite *sprite = new (std::nothrow) Sprite();
  116. if (sprite && sprite->init())
  117. {
  118. sprite->autorelease();
  119. return sprite;
  120. }
  121. CC_SAFE_DELETE(sprite);
  122. return nullptr;
  123. }
  124. bool Sprite::init()
  125. {
  126. initWithTexture(nullptr, Rect::ZERO);
  127. return true;
  128. }
  129. bool Sprite::initWithTexture(Texture2D *texture)
  130. {
  131. CCASSERT(texture != nullptr, "Invalid texture for sprite");
  132. Rect rect = Rect::ZERO;
  133. if (texture) {
  134. rect.size = texture->getContentSize();
  135. }
  136. return initWithTexture(texture, rect, false);
  137. }
  138. bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect)
  139. {
  140. return initWithTexture(texture, rect, false);
  141. }
  142. bool Sprite::initWithFile(const std::string& filename)
  143. {
  144. if (filename.empty())
  145. {
  146. CCLOG("Call Sprite::initWithFile with blank resource filename.");
  147. return false;
  148. }
  149. _fileName = filename;
  150. _fileType = 0;
  151. Texture2D *texture = _director->getTextureCache()->addImage(filename);
  152. if (texture)
  153. {
  154. Rect rect = Rect::ZERO;
  155. rect.size = texture->getContentSize();
  156. return initWithTexture(texture, rect);
  157. }
  158. // don't release here.
  159. // when load texture failed, it's better to get a "transparent" sprite then a crashed program
  160. // this->release();
  161. return false;
  162. }
  163. bool Sprite::initWithFile(const std::string &filename, const Rect& rect)
  164. {
  165. CCASSERT(!filename.empty(), "Invalid filename");
  166. if (filename.empty())
  167. {
  168. return false;
  169. }
  170. _fileName = filename;
  171. _fileType = 0;
  172. Texture2D *texture = _director->getTextureCache()->addImage(filename);
  173. if (texture)
  174. {
  175. return initWithTexture(texture, rect);
  176. }
  177. // don't release here.
  178. // when load texture failed, it's better to get a "transparent" sprite then a crashed program
  179. // this->release();
  180. return false;
  181. }
  182. bool Sprite::initWithSpriteFrameName(const std::string& spriteFrameName)
  183. {
  184. CCASSERT(!spriteFrameName.empty(), "Invalid spriteFrameName");
  185. if (spriteFrameName.empty())
  186. {
  187. return false;
  188. }
  189. _fileName = spriteFrameName;
  190. _fileType = 1;
  191. SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName);
  192. return initWithSpriteFrame(frame);
  193. }
  194. bool Sprite::initWithSpriteFrame(SpriteFrame *spriteFrame)
  195. {
  196. CCASSERT(spriteFrame != nullptr, "spriteFrame can't be nullptr!");
  197. if (spriteFrame == nullptr)
  198. {
  199. return false;
  200. }
  201. bool ret = initWithTexture(spriteFrame->getTexture(), spriteFrame->getRect(), spriteFrame->isRotated());
  202. setSpriteFrame(spriteFrame);
  203. return ret;
  204. }
  205. bool Sprite::initWithPolygon(const cocos2d::PolygonInfo &info)
  206. {
  207. bool ret = false;
  208. Texture2D *texture = _director->getTextureCache()->addImage(info.getFilename());
  209. if(texture && initWithTexture(texture))
  210. {
  211. _polyInfo = info;
  212. _renderMode = RenderMode::POLYGON;
  213. Node::setContentSize(_polyInfo.getRect().size / _director->getContentScaleFactor());
  214. ret = true;
  215. }
  216. return ret;
  217. }
  218. // designated initializer
  219. bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect, bool rotated)
  220. {
  221. bool result = false;
  222. if (Node::init())
  223. {
  224. _batchNode = nullptr;
  225. _recursiveDirty = false;
  226. setDirty(false);
  227. _opacityModifyRGB = true;
  228. _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;
  229. _flippedX = _flippedY = false;
  230. // default transform anchor: center
  231. setAnchorPoint(Vec2::ANCHOR_MIDDLE);
  232. // zwoptex default values
  233. _offsetPosition.setZero();
  234. // clean the Quad
  235. memset(&_quad, 0, sizeof(_quad));
  236. // Atlas: Color
  237. _quad.bl.colors = Color4B::WHITE;
  238. _quad.br.colors = Color4B::WHITE;
  239. _quad.tl.colors = Color4B::WHITE;
  240. _quad.tr.colors = Color4B::WHITE;
  241. // update texture (calls updateBlendFunc)
  242. setTexture(texture);
  243. setTextureRect(rect, rotated, rect.size);
  244. // by default use "Self Render".
  245. // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render"
  246. setBatchNode(nullptr);
  247. result = true;
  248. }
  249. _recursiveDirty = true;
  250. setDirty(true);
  251. return result;
  252. }
  253. Sprite::Sprite(void)
  254. : _batchNode(nullptr)
  255. , _textureAtlas(nullptr)
  256. , _shouldBeHidden(false)
  257. , _texture(nullptr)
  258. , _spriteFrame(nullptr)
  259. , _insideBounds(true)
  260. , _centerRectNormalized(0,0,1,1)
  261. , _renderMode(Sprite::RenderMode::QUAD)
  262. , _trianglesVertex(nullptr)
  263. , _trianglesIndex(nullptr)
  264. , _stretchFactor(Vec2::ONE)
  265. , _originalContentSize(Size::ZERO)
  266. , _stretchEnabled(true)
  267. {
  268. #if CC_SPRITE_DEBUG_DRAW
  269. _debugDrawNode = DrawNode::create();
  270. addChild(_debugDrawNode);
  271. #endif //CC_SPRITE_DEBUG_DRAW
  272. }
  273. Sprite::~Sprite()
  274. {
  275. CC_SAFE_FREE(_trianglesVertex);
  276. CC_SAFE_FREE(_trianglesIndex);
  277. CC_SAFE_RELEASE(_spriteFrame);
  278. CC_SAFE_RELEASE(_texture);
  279. }
  280. /*
  281. * Texture methods
  282. */
  283. /*
  284. * This array is the data of a white image with 2 by 2 dimension.
  285. * It's used for creating a default texture when sprite's texture is set to nullptr.
  286. * Supposing codes as follows:
  287. *
  288. * auto sp = new (std::nothrow) Sprite();
  289. * sp->init(); // Texture was set to nullptr, in order to make opacity and color to work correctly, we need to create a 2x2 white texture.
  290. *
  291. * The test is in "TestCpp/SpriteTest/Sprite without texture".
  292. */
  293. static unsigned char cc_2x2_white_image[] = {
  294. // RGBA8888
  295. 0xFF, 0xFF, 0xFF, 0xFF,
  296. 0xFF, 0xFF, 0xFF, 0xFF,
  297. 0xFF, 0xFF, 0xFF, 0xFF,
  298. 0xFF, 0xFF, 0xFF, 0xFF
  299. };
  300. #define CC_2x2_WHITE_IMAGE_KEY "/cc_2x2_white_image"
  301. // MARK: texture
  302. void Sprite::setTexture(const std::string &filename)
  303. {
  304. Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename);
  305. setTexture(texture);
  306. _unflippedOffsetPositionFromCenter = Vec2::ZERO;
  307. Rect rect = Rect::ZERO;
  308. if (texture)
  309. rect.size = texture->getContentSize();
  310. setTextureRect(rect);
  311. }
  312. void Sprite::setTexture(Texture2D *texture)
  313. {
  314. setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP, texture));
  315. // If batchnode, then texture id should be the same
  316. CCASSERT(! _batchNode || (texture && texture->getName() == _batchNode->getTexture()->getName()), "CCSprite: Batched sprites should use the same texture as the batchnode");
  317. // accept texture==nil as argument
  318. CCASSERT( !texture || dynamic_cast<Texture2D*>(texture), "setTexture expects a Texture2D. Invalid argument");
  319. if (texture == nullptr)
  320. {
  321. // Gets the texture by key firstly.
  322. texture = _director->getTextureCache()->getTextureForKey(CC_2x2_WHITE_IMAGE_KEY);
  323. // If texture wasn't in cache, create it from RAW data.
  324. if (texture == nullptr)
  325. {
  326. Image* image = new (std::nothrow) Image();
  327. bool CC_UNUSED isOK = image->initWithRawData(cc_2x2_white_image, sizeof(cc_2x2_white_image), 2, 2, 8);
  328. CCASSERT(isOK, "The 2x2 empty texture was created unsuccessfully.");
  329. texture = _director->getTextureCache()->addImage(image, CC_2x2_WHITE_IMAGE_KEY);
  330. CC_SAFE_RELEASE(image);
  331. }
  332. }
  333. if ((_renderMode != RenderMode::QUAD_BATCHNODE) && (_texture != texture))
  334. {
  335. CC_SAFE_RETAIN(texture);
  336. CC_SAFE_RELEASE(_texture);
  337. _texture = texture;
  338. updateBlendFunc();
  339. }
  340. }
  341. Texture2D* Sprite::getTexture() const
  342. {
  343. return _texture;
  344. }
  345. void Sprite::setTextureRect(const Rect& rect)
  346. {
  347. setTextureRect(rect, false, rect.size);
  348. }
  349. void Sprite::setTextureRect(const Rect& rect, bool rotated, const Size& untrimmedSize)
  350. {
  351. _rectRotated = rotated;
  352. Node::setContentSize(untrimmedSize);
  353. _originalContentSize = untrimmedSize;
  354. setVertexRect(rect);
  355. updateStretchFactor();
  356. updatePoly();
  357. }
  358. void Sprite::updatePoly()
  359. {
  360. // There are 3 cases:
  361. //
  362. // A) a non 9-sliced, non stretched
  363. // contentsize doesn't not affect the stretching, since there is no stretching
  364. // this was the original behavior, and we keep it for backwards compatibility reasons
  365. // When non-stretching is enabled, we have to change the offset in order to "fill the empty" space at the
  366. // left-top of the texture
  367. // B) non 9-sliced, stretched
  368. // the texture is stretched to the content size
  369. // C) 9-sliced, stretched
  370. // the sprite is 9-sliced and stretched.
  371. if (_renderMode == RenderMode::QUAD || _renderMode == RenderMode::QUAD_BATCHNODE) {
  372. Rect copyRect;
  373. if (_stretchEnabled) {
  374. // case B)
  375. copyRect = Rect(0, 0, _rect.size.width * _stretchFactor.x, _rect.size.height * _stretchFactor.y);
  376. } else {
  377. // case A)
  378. // modify origin to put the sprite in the correct offset
  379. copyRect = Rect((_contentSize.width - _originalContentSize.width) / 2.0f,
  380. (_contentSize.height - _originalContentSize.height) / 2.0f,
  381. _rect.size.width,
  382. _rect.size.height);
  383. }
  384. setTextureCoords(_rect, &_quad);
  385. setVertexCoords(copyRect, &_quad);
  386. _polyInfo.setQuad(&_quad);
  387. } else if (_renderMode == RenderMode::SLICE9) {
  388. // case C)
  389. // How the texture is split
  390. //
  391. // u,v: are the texture coordinates
  392. // w,h: are the width and heights
  393. //
  394. // w0 w1 w2
  395. // v2 +----+------+--+
  396. // | | | |
  397. // | | | |
  398. // | 6 | 7 | 8| h2
  399. // | | | |
  400. // v1 +----+------+--|
  401. // | | | |
  402. // | 3 | 4 | 5| h1
  403. // v0 +----+------+--|
  404. // | | | |
  405. // | 0 | 1 | 2| h0
  406. // | | | |
  407. // +----+------+--+
  408. // u0 u1 u2
  409. //
  410. //
  411. // and when the texture is rotated, it will get transformed.
  412. // not only the rects have a different position, but also u,v
  413. // points to the bottom-left and not top-right of the texture
  414. // so some swaping/origin/reordering needs to be done in order
  415. // to support rotated slice-9 correctly
  416. //
  417. // w0 w1 w2
  418. // v2 +------+----+--------+
  419. // | | | |
  420. // | 0 | 3 | 6 | h2
  421. // v1 +------+----+--------+
  422. // | | | |
  423. // | 1 | 4 | 7 | h1
  424. // | | | |
  425. // v0 +------+----+--------+
  426. // | 2 | 5 | 8 | h0
  427. // +------+----+--------+
  428. // u0 u1 u2
  429. // center rect
  430. float cx1 = _centerRectNormalized.origin.x;
  431. float cy1 = _centerRectNormalized.origin.y;
  432. float cx2 = _centerRectNormalized.origin.x + _centerRectNormalized.size.width;
  433. float cy2 = _centerRectNormalized.origin.y + _centerRectNormalized.size.height;
  434. // "O"riginal rect
  435. const float oox = _rect.origin.x;
  436. const float ooy = _rect.origin.y;
  437. float osw = _rect.size.width;
  438. float osh = _rect.size.height;
  439. if (_rectRotated) {
  440. std::swap(cx1, cy1);
  441. std::swap(cx2, cy2);
  442. // when the texture is rotated, then the centerRect starts from the "bottom" (left)
  443. // but when it is not rotated, it starts from the top, so invert it
  444. cy2 = 1 - cy2;
  445. cy1 = 1 - cy1;
  446. std::swap(cy1, cy2);
  447. std::swap(osw, osh);
  448. }
  449. //
  450. // textCoords Data: Y must be inverted.
  451. //
  452. const float w0 = osw * cx1;
  453. const float w1 = osw * (cx2-cx1);
  454. const float w2 = osw * (1-cx2);
  455. const float h0 = osh * cy1;
  456. const float h1 = osh * (cy2-cy1);
  457. const float h2 = osh * (1-cy2);
  458. const float u0 = oox;
  459. const float u1 = u0 + w0;
  460. const float u2 = u1 + w1;
  461. const float v2 = ooy;
  462. const float v1 = v2 + h2;
  463. const float v0 = v1 + h1;
  464. const Rect texRects_normal[9] = {
  465. Rect(u0, v0, w0, h0), // bottom-left
  466. Rect(u1, v0, w1, h0), // bottom
  467. Rect(u2, v0, w2, h0), // bottom-right
  468. Rect(u0, v1, w0, h1), // left
  469. Rect(u1, v1, w1, h1), // center
  470. Rect(u2, v1, w2, h1), // right
  471. Rect(u0, v2, w0, h2), // top-left
  472. Rect(u1, v2, w1, h2), // top
  473. Rect(u2, v2, w2, h2), // top-right
  474. };
  475. // swap width and height because setTextureCoords()
  476. // will expects the hight and width to be swapped
  477. const Rect texRects_rotated[9] = {
  478. Rect(u0, v2, h2, w0), // top-left
  479. Rect(u0, v1, h1, w0), // left
  480. Rect(u0, v0, h0, w0), // bottom-left
  481. Rect(u1, v2, h2, w1), // top
  482. Rect(u1, v1, h1, w1), // center
  483. Rect(u1, v0, h0, w1), // bottom
  484. Rect(u2, v2, h2, w2), // top-right
  485. Rect(u2, v1, h1, w2), // right
  486. Rect(u2, v0, h0, w2), // bottom-right
  487. };
  488. const Rect* texRects = _rectRotated ? texRects_rotated : texRects_normal;
  489. //
  490. // vertex Data.
  491. //
  492. // reset center rect since it is altered when when the texture
  493. // is rotated
  494. cx1 = _centerRectNormalized.origin.x;
  495. cy1 = _centerRectNormalized.origin.y;
  496. cx2 = _centerRectNormalized.origin.x + _centerRectNormalized.size.width;
  497. cy2 = _centerRectNormalized.origin.y + _centerRectNormalized.size.height;
  498. if (_rectRotated)
  499. std::swap(osw, osh);
  500. // sizes
  501. float x0_s = osw * cx1;
  502. float x1_s = osw * (cx2-cx1) * _stretchFactor.x;
  503. float x2_s = osw * (1-cx2);
  504. float y0_s = osh * cy1;
  505. float y1_s = osh * (cy2-cy1) * _stretchFactor.y;
  506. float y2_s = osh * (1-cy2);
  507. // avoid negative size:
  508. if (_contentSize.width < x0_s + x2_s) {
  509. x2_s = x0_s = _contentSize.width / 2;
  510. }
  511. if (_contentSize.height < y0_s + y2_s) {
  512. y2_s = y0_s = _contentSize.height / 2;
  513. }
  514. // is it flipped?
  515. // swap sizes to calculate offset correctly
  516. if (_flippedX)
  517. std::swap(x0_s, x2_s);
  518. if (_flippedY)
  519. std::swap(y0_s, y2_s);
  520. // origins
  521. float x0 = 0;
  522. float x1 = x0 + x0_s;
  523. float x2 = x1 + x1_s;
  524. float y0 = 0;
  525. float y1 = y0 + y0_s;
  526. float y2 = y1 + y1_s;
  527. // swap origin, but restore size to its original value
  528. if (_flippedX) {
  529. std::swap(x0, x2);
  530. std::swap(x0_s, x2_s);
  531. }
  532. if (_flippedY) {
  533. std::swap(y0, y2);
  534. std::swap(y0_s, y2_s);
  535. }
  536. const Rect verticesRects[9] = {
  537. Rect(x0, y0, x0_s, y0_s), // bottom-left
  538. Rect(x1, y0, x1_s, y0_s), // bottom
  539. Rect(x2, y0, x2_s, y0_s), // bottom-right
  540. Rect(x0, y1, x0_s, y1_s), // left
  541. Rect(x1, y1, x1_s, y1_s), // center
  542. Rect(x2, y1, x2_s, y1_s), // right
  543. Rect(x0, y2, x0_s, y2_s), // top-left
  544. Rect(x1, y2, x1_s, y2_s), // top
  545. Rect(x2, y2, x2_s, y2_s), // top-right
  546. };
  547. // needed in order to get color from "_quad"
  548. V3F_C4B_T2F_Quad tmpQuad = _quad;
  549. for (int i=0; i<9; ++i) {
  550. setTextureCoords(texRects[i], &tmpQuad);
  551. setVertexCoords(verticesRects[i], &tmpQuad);
  552. populateTriangle(i, tmpQuad);
  553. }
  554. TrianglesCommand::Triangles triangles;
  555. triangles.verts = _trianglesVertex;
  556. triangles.vertCount = 16;
  557. triangles.indices = _trianglesIndex;
  558. triangles.indexCount = 6 * 9; // 9 quads, each needs 6 vertices
  559. // probably we can update the _trianglesCommand directly
  560. // to avoid memcpy'ing stuff
  561. _polyInfo.setTriangles(triangles);
  562. }
  563. }
  564. void Sprite::setCenterRectNormalized(const cocos2d::Rect &rectTopLeft)
  565. {
  566. if (_renderMode != RenderMode::QUAD && _renderMode != RenderMode::SLICE9) {
  567. CCLOGWARN("Warning: Sprite::setCenterRectNormalized() only works with QUAD and SLICE9 render modes");
  568. return;
  569. }
  570. // FIMXE: Rect is has origin on top-left (like text coordinate).
  571. // but all the logic has been done using bottom-left as origin. So it is easier to invert Y
  572. // here, than in the rest of the places... but it is not as clean.
  573. Rect rect(rectTopLeft.origin.x, 1 - rectTopLeft.origin.y - rectTopLeft.size.height, rectTopLeft.size.width, rectTopLeft.size.height);
  574. if (!_centerRectNormalized.equals(rect)) {
  575. _centerRectNormalized = rect;
  576. // convert it to 1-slice when the centerRect is not present.
  577. if (rect.equals(Rect(0,0,1,1))) {
  578. _renderMode = RenderMode::QUAD;
  579. free(_trianglesVertex);
  580. free(_trianglesIndex);
  581. _trianglesVertex = nullptr;
  582. _trianglesIndex = nullptr;
  583. }
  584. else
  585. {
  586. // convert it to 9-slice if it isn't already
  587. if (_renderMode != RenderMode::SLICE9) {
  588. _renderMode = RenderMode::SLICE9;
  589. // 9 quads + 7 exterior points = 16
  590. _trianglesVertex = (V3F_C4B_T2F*) malloc(sizeof(*_trianglesVertex) * (9 + 3 + 4));
  591. // 9 quads, each needs 6 vertices = 54
  592. _trianglesIndex = (unsigned short*) malloc(sizeof(*_trianglesIndex) * 6 * 9);
  593. // populate indices in CCW direction
  594. for (int i=0; i<9; ++i) {
  595. _trianglesIndex[i * 6 + 0] = (i * 4 / 3) + 4;
  596. _trianglesIndex[i * 6 + 1] = (i * 4 / 3) + 0;
  597. _trianglesIndex[i * 6 + 2] = (i * 4 / 3) + 5;
  598. _trianglesIndex[i * 6 + 3] = (i * 4 / 3) + 1;
  599. _trianglesIndex[i * 6 + 4] = (i * 4 / 3) + 5;
  600. _trianglesIndex[i * 6 + 5] = (i * 4 / 3) + 0;
  601. }
  602. }
  603. }
  604. updateStretchFactor();
  605. updatePoly();
  606. updateColor();
  607. }
  608. }
  609. void Sprite::setCenterRect(const cocos2d::Rect &rectInPoints)
  610. {
  611. if (_renderMode != RenderMode::QUAD && _renderMode != RenderMode::SLICE9) {
  612. CCLOGWARN("Warning: Sprite::setCenterRect() only works with QUAD and SLICE9 render modes");
  613. return;
  614. }
  615. if (!_originalContentSize.equals(Size::ZERO))
  616. {
  617. Rect rect = rectInPoints;
  618. const float x = rect.origin.x / _rect.size.width;
  619. const float y = rect.origin.y / _rect.size.height;
  620. const float w = rect.size.width / _rect.size.width;
  621. const float h = rect.size.height / _rect.size.height;
  622. setCenterRectNormalized(Rect(x,y,w,h));
  623. }
  624. }
  625. Rect Sprite::getCenterRectNormalized() const
  626. {
  627. // FIXME: _centerRectNormalized is in bottom-left coords, but should converted to top-left
  628. Rect ret(_centerRectNormalized.origin.x,
  629. 1 - _centerRectNormalized.origin.y - _centerRectNormalized.size.height,
  630. _centerRectNormalized.size.width,
  631. _centerRectNormalized.size.height);
  632. return ret;
  633. }
  634. Rect Sprite::getCenterRect() const
  635. {
  636. Rect rect = getCenterRectNormalized();
  637. rect.origin.x *= _rect.size.width;
  638. rect.origin.y *= _rect.size.height;
  639. rect.size.width *= _rect.size.width;
  640. rect.size.height *= _rect.size.height;
  641. return rect;
  642. }
  643. // override this method to generate "double scale" sprites
  644. void Sprite::setVertexRect(const Rect& rect)
  645. {
  646. _rect = rect;
  647. }
  648. void Sprite::setTextureCoords(const Rect& rectInPoints)
  649. {
  650. setTextureCoords(rectInPoints, &_quad);
  651. }
  652. void Sprite::setTextureCoords(const Rect& rectInPoints, V3F_C4B_T2F_Quad* outQuad)
  653. {
  654. Texture2D *tex = (_renderMode == RenderMode::QUAD_BATCHNODE) ? _textureAtlas->getTexture() : _texture;
  655. if (tex == nullptr)
  656. {
  657. return;
  658. }
  659. const auto rectInPixels = CC_RECT_POINTS_TO_PIXELS(rectInPoints);
  660. const float atlasWidth = (float)tex->getPixelsWide();
  661. const float atlasHeight = (float)tex->getPixelsHigh();
  662. float rw = rectInPixels.size.width;
  663. float rh = rectInPixels.size.height;
  664. // if the rect is rotated, it means that the frame is rotated 90 degrees (clockwise) and:
  665. // - rectInpoints: origin will be the bottom-left of the frame (and not the top-right)
  666. // - size: represents the unrotated texture size
  667. //
  668. // so what we have to do is:
  669. // - swap texture width and height
  670. // - take into account the origin
  671. // - flip X instead of Y when flipY is enabled
  672. // - flip Y instead of X when flipX is enabled
  673. if (_rectRotated)
  674. std::swap(rw, rh);
  675. #if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL
  676. float left = (2*rectInPixels.origin.x+1) / (2*atlasWidth);
  677. float right = left+(rw*2-2) / (2*atlasWidth);
  678. float top = (2*rectInPixels.origin.y+1) / (2*atlasHeight);
  679. float bottom = top+(rh*2-2) / (2*atlasHeight);
  680. #else
  681. float left = rectInPixels.origin.x / atlasWidth;
  682. float right = (rectInPixels.origin.x + rw) / atlasWidth;
  683. float top = rectInPixels.origin.y / atlasHeight;
  684. float bottom = (rectInPixels.origin.y + rh) / atlasHeight;
  685. #endif // CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL
  686. if ((!_rectRotated && _flippedX) || (_rectRotated && _flippedY))
  687. {
  688. std::swap(left, right);
  689. }
  690. if ((!_rectRotated && _flippedY) || (_rectRotated && _flippedX))
  691. {
  692. std::swap(top, bottom);
  693. }
  694. if (_rectRotated)
  695. {
  696. outQuad->bl.texCoords.u = left;
  697. outQuad->bl.texCoords.v = top;
  698. outQuad->br.texCoords.u = left;
  699. outQuad->br.texCoords.v = bottom;
  700. outQuad->tl.texCoords.u = right;
  701. outQuad->tl.texCoords.v = top;
  702. outQuad->tr.texCoords.u = right;
  703. outQuad->tr.texCoords.v = bottom;
  704. }
  705. else
  706. {
  707. outQuad->bl.texCoords.u = left;
  708. outQuad->bl.texCoords.v = bottom;
  709. outQuad->br.texCoords.u = right;
  710. outQuad->br.texCoords.v = bottom;
  711. outQuad->tl.texCoords.u = left;
  712. outQuad->tl.texCoords.v = top;
  713. outQuad->tr.texCoords.u = right;
  714. outQuad->tr.texCoords.v = top;
  715. }
  716. }
  717. void Sprite::setVertexCoords(const Rect& rect, V3F_C4B_T2F_Quad* outQuad)
  718. {
  719. float relativeOffsetX = _unflippedOffsetPositionFromCenter.x;
  720. float relativeOffsetY = _unflippedOffsetPositionFromCenter.y;
  721. // issue #732
  722. if (_flippedX)
  723. {
  724. relativeOffsetX = -relativeOffsetX;
  725. }
  726. if (_flippedY)
  727. {
  728. relativeOffsetY = -relativeOffsetY;
  729. }
  730. _offsetPosition.x = relativeOffsetX + (_originalContentSize.width - _rect.size.width) / 2;
  731. _offsetPosition.y = relativeOffsetY + (_originalContentSize.height - _rect.size.height) / 2;
  732. // FIXME: Stretching should be applied to the "offset" as well
  733. // but probably it should be calculated in the caller function. It will be tidier
  734. if (_renderMode == RenderMode::QUAD) {
  735. _offsetPosition.x *= _stretchFactor.x;
  736. _offsetPosition.y *= _stretchFactor.y;
  737. }
  738. // rendering using batch node
  739. if (_renderMode == RenderMode::QUAD_BATCHNODE)
  740. {
  741. // update dirty_, don't update recursiveDirty_
  742. setDirty(true);
  743. }
  744. else
  745. {
  746. // self rendering
  747. // Atlas: Vertex
  748. const float x1 = 0.0f + _offsetPosition.x + rect.origin.x;
  749. const float y1 = 0.0f + _offsetPosition.y + rect.origin.y;
  750. const float x2 = x1 + rect.size.width;
  751. const float y2 = y1 + rect.size.height;
  752. // Don't update Z.
  753. outQuad->bl.vertices.set(x1, y1, 0.0f);
  754. outQuad->br.vertices.set(x2, y1, 0.0f);
  755. outQuad->tl.vertices.set(x1, y2, 0.0f);
  756. outQuad->tr.vertices.set(x2, y2, 0.0f);
  757. }
  758. }
  759. void Sprite::populateTriangle(int quadIndex, const V3F_C4B_T2F_Quad& quad)
  760. {
  761. CCASSERT(quadIndex < 9, "Invalid quadIndex");
  762. // convert Quad intro Triangle since it takes less memory
  763. // Triangles are ordered like the following:
  764. // Numbers: Quad Index
  765. // Letters: triangles' vertices
  766. //
  767. // M-----N-----O-----P
  768. // | | | |
  769. // | 6 | 7 | 8 |
  770. // | | | |
  771. // I-----J-----K-----L
  772. // | | | |
  773. // | 3 | 4 | 5 |
  774. // | | | |
  775. // E-----F-----G-----H
  776. // | | | |
  777. // | 0 | 1 | 2 |
  778. // | | | |
  779. // A-----B-----C-----D
  780. //
  781. // So, if QuadIndex == 4, then it should update vertices J,K,F,G
  782. // Optimization: I don't need to copy all the vertices all the time. just the 4 "quads" from the corners.
  783. if (quadIndex == 0 || quadIndex == 2 || quadIndex == 6 || quadIndex == 8)
  784. {
  785. if (_flippedX) {
  786. if (quadIndex % 3 == 0)
  787. quadIndex += 2;
  788. else
  789. quadIndex -= 2;
  790. }
  791. if (_flippedY) {
  792. if (quadIndex <= 2)
  793. quadIndex += 6;
  794. else
  795. quadIndex -= 6;
  796. }
  797. const int index_bl = quadIndex * 4 / 3;
  798. const int index_br = index_bl + 1;
  799. const int index_tl = index_bl + 4;
  800. const int index_tr = index_bl + 5;
  801. _trianglesVertex[index_tr] = quad.tr;
  802. _trianglesVertex[index_br] = quad.br;
  803. _trianglesVertex[index_tl] = quad.tl;
  804. _trianglesVertex[index_bl] = quad.bl;
  805. }
  806. }
  807. // MARK: visit, draw, transform
  808. void Sprite::updateTransform(void)
  809. {
  810. CCASSERT(_renderMode == RenderMode::QUAD_BATCHNODE, "updateTransform is only valid when Sprite is being rendered using an SpriteBatchNode");
  811. // recalculate matrix only if it is dirty
  812. if( isDirty() ) {
  813. // If it is not visible, or one of its ancestors is not visible, then do nothing:
  814. if( !_visible || ( _parent && _parent != _batchNode && static_cast<Sprite*>(_parent)->_shouldBeHidden) )
  815. {
  816. _quad.br.vertices.setZero();
  817. _quad.tl.vertices.setZero();
  818. _quad.tr.vertices.setZero();
  819. _quad.bl.vertices.setZero();
  820. _shouldBeHidden = true;
  821. }
  822. else
  823. {
  824. _shouldBeHidden = false;
  825. if( ! _parent || _parent == _batchNode )
  826. {
  827. _transformToBatch = getNodeToParentTransform();
  828. }
  829. else
  830. {
  831. CCASSERT( dynamic_cast<Sprite*>(_parent), "Logic error in Sprite. Parent must be a Sprite");
  832. const Mat4 &nodeToParent = getNodeToParentTransform();
  833. Mat4 &parentTransform = static_cast<Sprite*>(_parent)->_transformToBatch;
  834. _transformToBatch = parentTransform * nodeToParent;
  835. }
  836. //
  837. // calculate the Quad based on the Affine Matrix
  838. //
  839. Size &size = _rect.size;
  840. float x1 = _offsetPosition.x;
  841. float y1 = _offsetPosition.y;
  842. float x2 = x1 + size.width;
  843. float y2 = y1 + size.height;
  844. float x = _transformToBatch.m[12];
  845. float y = _transformToBatch.m[13];
  846. float cr = _transformToBatch.m[0];
  847. float sr = _transformToBatch.m[1];
  848. float cr2 = _transformToBatch.m[5];
  849. float sr2 = -_transformToBatch.m[4];
  850. float ax = x1 * cr - y1 * sr2 + x;
  851. float ay = x1 * sr + y1 * cr2 + y;
  852. float bx = x2 * cr - y1 * sr2 + x;
  853. float by = x2 * sr + y1 * cr2 + y;
  854. float cx = x2 * cr - y2 * sr2 + x;
  855. float cy = x2 * sr + y2 * cr2 + y;
  856. float dx = x1 * cr - y2 * sr2 + x;
  857. float dy = x1 * sr + y2 * cr2 + y;
  858. _quad.bl.vertices.set(SPRITE_RENDER_IN_SUBPIXEL(ax), SPRITE_RENDER_IN_SUBPIXEL(ay), _positionZ);
  859. _quad.br.vertices.set(SPRITE_RENDER_IN_SUBPIXEL(bx), SPRITE_RENDER_IN_SUBPIXEL(by), _positionZ);
  860. _quad.tl.vertices.set(SPRITE_RENDER_IN_SUBPIXEL(dx), SPRITE_RENDER_IN_SUBPIXEL(dy), _positionZ);
  861. _quad.tr.vertices.set(SPRITE_RENDER_IN_SUBPIXEL(cx), SPRITE_RENDER_IN_SUBPIXEL(cy), _positionZ);
  862. setTextureCoords(_rect);
  863. }
  864. // MARMALADE CHANGE: ADDED CHECK FOR nullptr, TO PERMIT SPRITES WITH NO BATCH NODE / TEXTURE ATLAS
  865. if (_textureAtlas)
  866. {
  867. _textureAtlas->updateQuad(&_quad, _atlasIndex);
  868. }
  869. _recursiveDirty = false;
  870. setDirty(false);
  871. }
  872. // MARMALADE CHANGED
  873. // recursively iterate over children
  874. /* if( _hasChildren )
  875. {
  876. // MARMALADE: CHANGED TO USE Node*
  877. // NOTE THAT WE HAVE ALSO DEFINED virtual Node::updateTransform()
  878. arrayMakeObjectsPerformSelector(_children, updateTransform, Sprite*);
  879. }*/
  880. Node::updateTransform();
  881. }
  882. // draw
  883. void Sprite::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
  884. {
  885. if (_texture == nullptr)
  886. {
  887. return;
  888. }
  889. #if CC_USE_CULLING
  890. // Don't calculate the culling if the transform was not updated
  891. auto visitingCamera = Camera::getVisitingCamera();
  892. auto defaultCamera = Camera::getDefaultCamera();
  893. if (visitingCamera == defaultCamera) {
  894. _insideBounds = ((flags & FLAGS_TRANSFORM_DIRTY) || visitingCamera->isViewProjectionUpdated()) ? renderer->checkVisibility(transform, _contentSize) : _insideBounds;
  895. }
  896. else
  897. {
  898. // XXX: this always return true since
  899. _insideBounds = renderer->checkVisibility(transform, _contentSize);
  900. }
  901. if(_insideBounds)
  902. #endif
  903. {
  904. _trianglesCommand.init(_globalZOrder,
  905. _texture,
  906. getGLProgramState(),
  907. _blendFunc,
  908. _polyInfo.triangles,
  909. transform,
  910. flags);
  911. renderer->addCommand(&_trianglesCommand);
  912. #if CC_SPRITE_DEBUG_DRAW
  913. _debugDrawNode->clear();
  914. auto count = _polyInfo.triangles.indexCount/3;
  915. auto indices = _polyInfo.triangles.indices;
  916. auto verts = _polyInfo.triangles.verts;
  917. for(ssize_t i = 0; i < count; i++)
  918. {
  919. //draw 3 lines
  920. Vec3 from =verts[indices[i*3]].vertices;
  921. Vec3 to = verts[indices[i*3+1]].vertices;
  922. _debugDrawNode->drawLine(Vec2(from.x, from.y), Vec2(to.x,to.y), Color4F::WHITE);
  923. from =verts[indices[i*3+1]].vertices;
  924. to = verts[indices[i*3+2]].vertices;
  925. _debugDrawNode->drawLine(Vec2(from.x, from.y), Vec2(to.x,to.y), Color4F::WHITE);
  926. from =verts[indices[i*3+2]].vertices;
  927. to = verts[indices[i*3]].vertices;
  928. _debugDrawNode->drawLine(Vec2(from.x, from.y), Vec2(to.x,to.y), Color4F::WHITE);
  929. }
  930. #endif //CC_SPRITE_DEBUG_DRAW
  931. }
  932. }
  933. // MARK: visit, draw, transform
  934. void Sprite::addChild(Node *child, int zOrder, int tag)
  935. {
  936. CCASSERT(child != nullptr, "Argument must be non-nullptr");
  937. if (child == nullptr)
  938. {
  939. return;
  940. }
  941. if (_renderMode == RenderMode::QUAD_BATCHNODE)
  942. {
  943. Sprite* childSprite = dynamic_cast<Sprite*>(child);
  944. CCASSERT( childSprite, "CCSprite only supports Sprites as children when using SpriteBatchNode");
  945. CCASSERT(childSprite->getTexture()->getName() == _textureAtlas->getTexture()->getName(), "childSprite's texture name should be equal to _textureAtlas's texture name!");
  946. //put it in descendants array of batch node
  947. _batchNode->appendChild(childSprite);
  948. if (!_reorderChildDirty)
  949. {
  950. setReorderChildDirtyRecursively();
  951. }
  952. }
  953. //CCNode already sets isReorderChildDirty_ so this needs to be after batchNode check
  954. Node::addChild(child, zOrder, tag);
  955. }
  956. void Sprite::addChild(Node *child, int zOrder, const std::string &name)
  957. {
  958. CCASSERT(child != nullptr, "Argument must be non-nullptr");
  959. if (child == nullptr)
  960. {
  961. return;
  962. }
  963. if (_renderMode == RenderMode::QUAD_BATCHNODE)
  964. {
  965. Sprite* childSprite = dynamic_cast<Sprite*>(child);
  966. CCASSERT( childSprite, "CCSprite only supports Sprites as children when using SpriteBatchNode");
  967. CCASSERT(childSprite->getTexture()->getName() == _textureAtlas->getTexture()->getName(),
  968. "childSprite's texture name should be equal to _textureAtlas's texture name.");
  969. //put it in descendants array of batch node
  970. _batchNode->appendChild(childSprite);
  971. if (!_reorderChildDirty)
  972. {
  973. setReorderChildDirtyRecursively();
  974. }
  975. }
  976. //CCNode already sets isReorderChildDirty_ so this needs to be after batchNode check
  977. Node::addChild(child, zOrder, name);
  978. }
  979. void Sprite::reorderChild(Node *child, int zOrder)
  980. {
  981. CCASSERT(child != nullptr, "child must be non null");
  982. CCASSERT(_children.contains(child), "child does not belong to this");
  983. if ((_renderMode == RenderMode::QUAD_BATCHNODE) && ! _reorderChildDirty)
  984. {
  985. setReorderChildDirtyRecursively();
  986. _batchNode->reorderBatch(true);
  987. }
  988. Node::reorderChild(child, zOrder);
  989. }
  990. void Sprite::removeChild(Node *child, bool cleanup)
  991. {
  992. if (_renderMode == RenderMode::QUAD_BATCHNODE)
  993. {
  994. _batchNode->removeSpriteFromAtlas((Sprite*)(child));
  995. }
  996. Node::removeChild(child, cleanup);
  997. }
  998. void Sprite::removeAllChildrenWithCleanup(bool cleanup)
  999. {
  1000. if (_renderMode == RenderMode::QUAD_BATCHNODE)
  1001. {
  1002. for(const auto &child : _children) {
  1003. Sprite* sprite = dynamic_cast<Sprite*>(child);
  1004. if (sprite)
  1005. {
  1006. _batchNode->removeSpriteFromAtlas(sprite);
  1007. }
  1008. }
  1009. }
  1010. Node::removeAllChildrenWithCleanup(cleanup);
  1011. }
  1012. void Sprite::sortAllChildren()
  1013. {
  1014. if (_reorderChildDirty)
  1015. {
  1016. sortNodes(_children);
  1017. if (_renderMode == RenderMode::QUAD_BATCHNODE)
  1018. {
  1019. for(const auto &child : _children)
  1020. child->sortAllChildren();
  1021. }
  1022. _reorderChildDirty = false;
  1023. }
  1024. }
  1025. //
  1026. // Node property overloads
  1027. // used only when parent is SpriteBatchNode
  1028. //
  1029. void Sprite::setReorderChildDirtyRecursively(void)
  1030. {
  1031. //only set parents flag the first time
  1032. if ( ! _reorderChildDirty )
  1033. {
  1034. _reorderChildDirty = true;
  1035. Node* node = static_cast<Node*>(_parent);
  1036. while (node && node != _batchNode)
  1037. {
  1038. static_cast<Sprite*>(node)->setReorderChildDirtyRecursively();
  1039. node=node->getParent();
  1040. }
  1041. }
  1042. }
  1043. void Sprite::setDirtyRecursively(bool bValue)
  1044. {
  1045. _recursiveDirty = bValue;
  1046. setDirty(bValue);
  1047. for(const auto &child: _children) {
  1048. Sprite* sp = dynamic_cast<Sprite*>(child);
  1049. if (sp)
  1050. {
  1051. sp->setDirtyRecursively(true);
  1052. }
  1053. }
  1054. }
  1055. // FIXME: HACK: optimization
  1056. #define SET_DIRTY_RECURSIVELY() { \
  1057. if (! _recursiveDirty) { \
  1058. _recursiveDirty = true; \
  1059. setDirty(true); \
  1060. if (!_children.empty()) \
  1061. setDirtyRecursively(true); \
  1062. } \
  1063. }
  1064. void Sprite::setPosition(const Vec2& pos)
  1065. {
  1066. Node::setPosition(pos);
  1067. SET_DIRTY_RECURSIVELY();
  1068. }
  1069. void Sprite::setPosition(float x, float y)
  1070. {
  1071. Node::setPosition(x, y);
  1072. SET_DIRTY_RECURSIVELY();
  1073. }
  1074. void Sprite::setRotation(float rotation)
  1075. {
  1076. Node::setRotation(rotation);
  1077. SET_DIRTY_RECURSIVELY();
  1078. }
  1079. void Sprite::setRotationSkewX(float fRotationX)
  1080. {
  1081. Node::setRotationSkewX(fRotationX);
  1082. SET_DIRTY_RECURSIVELY();
  1083. }
  1084. void Sprite::setRotationSkewY(float fRotationY)
  1085. {
  1086. Node::setRotationSkewY(fRotationY);
  1087. SET_DIRTY_RECURSIVELY();
  1088. }
  1089. void Sprite::setSkewX(float sx)
  1090. {
  1091. Node::setSkewX(sx);
  1092. SET_DIRTY_RECURSIVELY();
  1093. }
  1094. void Sprite::setSkewY(float sy)
  1095. {
  1096. Node::setSkewY(sy);
  1097. SET_DIRTY_RECURSIVELY();
  1098. }
  1099. void Sprite::setScaleX(float scaleX)
  1100. {
  1101. Node::setScaleX(scaleX);
  1102. SET_DIRTY_RECURSIVELY();
  1103. }
  1104. void Sprite::setScaleY(float scaleY)
  1105. {
  1106. Node::setScaleY(scaleY);
  1107. SET_DIRTY_RECURSIVELY();
  1108. }
  1109. void Sprite::setScale(float fScale)
  1110. {
  1111. Node::setScale(fScale);
  1112. SET_DIRTY_RECURSIVELY();
  1113. }
  1114. void Sprite::setScale(float scaleX, float scaleY)
  1115. {
  1116. Node::setScale(scaleX, scaleY);
  1117. SET_DIRTY_RECURSIVELY();
  1118. }
  1119. void Sprite::setPositionZ(float fVertexZ)
  1120. {
  1121. Node::setPositionZ(fVertexZ);
  1122. SET_DIRTY_RECURSIVELY();
  1123. }
  1124. void Sprite::setAnchorPoint(const Vec2& anchor)
  1125. {
  1126. Node::setAnchorPoint(anchor);
  1127. SET_DIRTY_RECURSIVELY();
  1128. }
  1129. void Sprite::setIgnoreAnchorPointForPosition(bool value)
  1130. {
  1131. CCASSERT(_renderMode != RenderMode::QUAD_BATCHNODE, "setIgnoreAnchorPointForPosition is invalid in Sprite");
  1132. Node::setIgnoreAnchorPointForPosition(value);
  1133. }
  1134. void Sprite::setVisible(bool bVisible)
  1135. {
  1136. Node::setVisible(bVisible);
  1137. SET_DIRTY_RECURSIVELY();
  1138. }
  1139. void Sprite::setContentSize(const Size& size)
  1140. {
  1141. if (_renderMode == RenderMode::QUAD_BATCHNODE || _renderMode == RenderMode::POLYGON)
  1142. CCLOGWARN("Sprite::setContentSize() doesn't stretch the sprite when using QUAD_BATCHNODE or POLYGON render modes");
  1143. Node::setContentSize(size);
  1144. updateStretchFactor();
  1145. updatePoly();
  1146. }
  1147. void Sprite::setStretchEnabled(bool enabled)
  1148. {
  1149. if (_stretchEnabled != enabled) {
  1150. _stretchEnabled = enabled;
  1151. // disabled centerrect / number of slices if disabled
  1152. if (!enabled)
  1153. setCenterRectNormalized(Rect(0,0,1,1));
  1154. updateStretchFactor();
  1155. updatePoly();
  1156. }
  1157. }
  1158. void Sprite::setStrechEnabled(bool enabled)
  1159. {
  1160. setStretchEnabled(enabled);
  1161. }
  1162. bool Sprite::isStretchEnabled() const
  1163. {
  1164. return _stretchEnabled;
  1165. }
  1166. bool Sprite::isStrechEnabled() const
  1167. {
  1168. return isStretchEnabled();
  1169. }
  1170. void Sprite::updateStretchFactor()
  1171. {
  1172. const Size size = getContentSize();
  1173. if (_renderMode == RenderMode::QUAD)
  1174. {
  1175. // If stretch is disabled, calculate the stretch anyway
  1176. // since it is needed to calculate the offset
  1177. const float x_factor = size.width / _originalContentSize.width;
  1178. const float y_factor = size.height / _originalContentSize.height;
  1179. _stretchFactor = Vec2(std::max(0.0f, x_factor),
  1180. std::max(0.0f, y_factor));
  1181. }
  1182. else if (_renderMode == RenderMode::SLICE9)
  1183. {
  1184. const float x1 = _rect.size.width * _centerRectNormalized.origin.x;
  1185. const float x2 = _rect.size.width * _centerRectNormalized.size.width;
  1186. const float x3 = _rect.size.width * (1 - _centerRectNormalized.origin.x - _centerRectNormalized.size.width);
  1187. const float y1 = _rect.size.height * _centerRectNormalized.origin.y;
  1188. const float y2 = _rect.size.height * _centerRectNormalized.size.height;
  1189. const float y3 = _rect.size.height * (1 - _centerRectNormalized.origin.y - _centerRectNormalized.size.height);
  1190. // adjustedSize = the new _rect size
  1191. const float adjustedWidth = size.width - (_originalContentSize.width - _rect.size.width);
  1192. const float adjustedHeight = size.height - (_originalContentSize.height - _rect.size.height);
  1193. const float x_factor = (adjustedWidth - x1 - x3) / x2;
  1194. const float y_factor = (adjustedHeight - y1 - y3) / y2;
  1195. _stretchFactor = Vec2(std::max(0.0f, x_factor),
  1196. std::max(0.0f, y_factor));
  1197. }
  1198. // else:
  1199. // Do nothing if renderMode is Polygon
  1200. }
  1201. void Sprite::setFlippedX(bool flippedX)
  1202. {
  1203. if (_flippedX != flippedX)
  1204. {
  1205. _flippedX = flippedX;
  1206. if (_renderMode == RenderMode::QUAD_BATCHNODE)
  1207. {
  1208. setDirty(true);
  1209. }
  1210. else if (_renderMode == RenderMode::POLYGON)
  1211. {
  1212. for (ssize_t i = 0; i < _polyInfo.triangles.vertCount; i++) {
  1213. auto& v = _polyInfo.triangles.verts[i].vertices;
  1214. v.x = _contentSize.width -v.x;
  1215. }
  1216. }
  1217. else
  1218. {
  1219. // RenderMode:: Quad or Slice9
  1220. updatePoly();
  1221. }
  1222. }
  1223. }
  1224. bool Sprite::isFlippedX(void) const
  1225. {
  1226. return _flippedX;
  1227. }
  1228. void Sprite::setFlippedY(bool flippedY)
  1229. {
  1230. if (_flippedY != flippedY)
  1231. {
  1232. _flippedY = flippedY;
  1233. if (_renderMode == RenderMode::QUAD_BATCHNODE)
  1234. {
  1235. setDirty(true);
  1236. }
  1237. else if (_renderMode == RenderMode::POLYGON)
  1238. {
  1239. for (ssize_t i = 0; i < _polyInfo.triangles.vertCount; i++) {
  1240. auto& v = _polyInfo.triangles.verts[i].vertices;
  1241. v.y = _contentSize.height -v.y;
  1242. }
  1243. }
  1244. else
  1245. {
  1246. // RenderMode:: Quad or Slice9
  1247. updatePoly();
  1248. }
  1249. }
  1250. }
  1251. bool Sprite::isFlippedY(void) const
  1252. {
  1253. return _flippedY;
  1254. }
  1255. //
  1256. // MARK: RGBA protocol
  1257. //
  1258. void Sprite::updateColor(void)
  1259. {
  1260. Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity );
  1261. // special opacity for premultiplied textures
  1262. if (_opacityModifyRGB)
  1263. {
  1264. color4.r *= _displayedOpacity/255.0f;
  1265. color4.g *= _displayedOpacity/255.0f;
  1266. color4.b *= _displayedOpacity/255.0f;
  1267. }
  1268. for (ssize_t i = 0; i < _polyInfo.triangles.vertCount; i++) {
  1269. _polyInfo.triangles.verts[i].colors = color4;
  1270. }
  1271. // related to issue #17116
  1272. // when switching from Quad to Slice9, the color will be obtained from _quad
  1273. // so it is important to update _quad colors as well.
  1274. _quad.bl.colors = _quad.tl.colors = _quad.br.colors = _quad.tr.colors = color4;
  1275. // renders using batch node
  1276. if (_renderMode == RenderMode::QUAD_BATCHNODE)
  1277. {
  1278. if (_atlasIndex != INDEX_NOT_INITIALIZED)
  1279. {
  1280. _textureAtlas->updateQuad(&_quad, _atlasIndex);
  1281. }
  1282. else
  1283. {
  1284. // no need to set it recursively
  1285. // update dirty_, don't update recursiveDirty_
  1286. setDirty(true);
  1287. }
  1288. }
  1289. // self render
  1290. // do nothing
  1291. }
  1292. void Sprite::setOpacityModifyRGB(bool modify)
  1293. {
  1294. if (_opacityModifyRGB != modify)
  1295. {
  1296. _opacityModifyRGB = modify;
  1297. updateColor();
  1298. }
  1299. }
  1300. bool Sprite::isOpacityModifyRGB(void) const
  1301. {
  1302. return _opacityModifyRGB;
  1303. }
  1304. // MARK: Frames
  1305. void Sprite::setSpriteFrame(const std::string &spriteFrameName)
  1306. {
  1307. CCASSERT(!spriteFrameName.empty(), "spriteFrameName must not be empty");
  1308. if (spriteFrameName.empty())
  1309. {
  1310. return;
  1311. }
  1312. SpriteFrameCache *cache = SpriteFrameCache::getInstance();
  1313. SpriteFrame *spriteFrame = cache->getSpriteFrameByName(spriteFrameName);
  1314. CCASSERT(spriteFrame, std::string("Invalid spriteFrameName :").append(spriteFrameName).c_str());
  1315. setSpriteFrame(spriteFrame);
  1316. }
  1317. void Sprite::setSpriteFrame(SpriteFrame *spriteFrame)
  1318. {
  1319. // retain the sprite frame
  1320. // do not removed by SpriteFrameCache::removeUnusedSpriteFrames
  1321. if (_spriteFrame != spriteFrame)
  1322. {
  1323. CC_SAFE_RELEASE(_spriteFrame);
  1324. _spriteFrame = spriteFrame;
  1325. spriteFrame->retain();
  1326. }
  1327. _unflippedOffsetPositionFromCenter = spriteFrame->getOffset();
  1328. Texture2D *texture = spriteFrame->getTexture();
  1329. // update texture before updating texture rect
  1330. if (texture != _texture)
  1331. {
  1332. setTexture(texture);
  1333. }
  1334. // update rect
  1335. _rectRotated = spriteFrame->isRotated();
  1336. setTextureRect(spriteFrame->getRect(), _rectRotated, spriteFrame->getOriginalSize());
  1337. if (spriteFrame->hasPolygonInfo())
  1338. {
  1339. _polyInfo = spriteFrame->getPolygonInfo();
  1340. _renderMode = RenderMode::POLYGON;
  1341. }
  1342. if (spriteFrame->hasAnchorPoint())
  1343. {
  1344. setAnchorPoint(spriteFrame->getAnchorPoint());
  1345. }
  1346. if (spriteFrame->hasCenterRect())
  1347. {
  1348. setCenterRect(spriteFrame->getCenterRect());
  1349. }
  1350. }
  1351. void Sprite::setDisplayFrameWithAnimationName(const std::string& animationName, ssize_t frameIndex)
  1352. {
  1353. CCASSERT(!animationName.empty(), "CCSprite#setDisplayFrameWithAnimationName. animationName must not be nullptr");
  1354. if (animationName.empty())
  1355. {
  1356. return;
  1357. }
  1358. Animation *a = AnimationCache::getInstance()->getAnimation(animationName);
  1359. CCASSERT(a, "CCSprite#setDisplayFrameWithAnimationName: Frame not found");
  1360. AnimationFrame* frame = a->getFrames().at(frameIndex);
  1361. CCASSERT(frame, "CCSprite#setDisplayFrame. Invalid frame");
  1362. setSpriteFrame(frame->getSpriteFrame());
  1363. }
  1364. bool Sprite::isFrameDisplayed(SpriteFrame *frame) const
  1365. {
  1366. Rect r = frame->getRect();
  1367. return (r.equals(_rect) &&
  1368. frame->getTexture()->getName() == _texture->getName() &&
  1369. frame->getOffset().equals(_unflippedOffsetPositionFromCenter));
  1370. }
  1371. SpriteFrame* Sprite::getSpriteFrame() const
  1372. {
  1373. if(nullptr != this->_spriteFrame)
  1374. {
  1375. return this->_spriteFrame;
  1376. }
  1377. return SpriteFrame::createWithTexture(_texture,
  1378. CC_RECT_POINTS_TO_PIXELS(_rect),
  1379. _rectRotated,
  1380. CC_POINT_POINTS_TO_PIXELS(_unflippedOffsetPositionFromCenter),
  1381. CC_SIZE_POINTS_TO_PIXELS(_originalContentSize));
  1382. }
  1383. SpriteBatchNode* Sprite::getBatchNode() const
  1384. {
  1385. return _batchNode;
  1386. }
  1387. void Sprite::setBatchNode(SpriteBatchNode *spriteBatchNode)
  1388. {
  1389. _batchNode = spriteBatchNode; // weak reference
  1390. // self render
  1391. if( ! _batchNode ) {
  1392. _renderMode = RenderMode::QUAD;
  1393. _atlasIndex = INDEX_NOT_INITIALIZED;
  1394. setTextureAtlas(nullptr);
  1395. _recursiveDirty = false;
  1396. setDirty(false);
  1397. float x1 = _offsetPosition.x;
  1398. float y1 = _offsetPosition.y;
  1399. float x2 = x1 + _rect.size.width;
  1400. float y2 = y1 + _rect.size.height;
  1401. _quad.bl.vertices.set( x1, y1, 0 );
  1402. _quad.br.vertices.set(x2, y1, 0);
  1403. _quad.tl.vertices.set(x1, y2, 0);
  1404. _quad.tr.vertices.set(x2, y2, 0);
  1405. } else {
  1406. // using batch
  1407. _renderMode = RenderMode::QUAD_BATCHNODE;
  1408. _transformToBatch = Mat4::IDENTITY;
  1409. setTextureAtlas(_batchNode->getTextureAtlas()); // weak ref
  1410. }
  1411. }
  1412. // MARK: Texture protocol
  1413. void Sprite::updateBlendFunc(void)
  1414. {
  1415. CCASSERT(_renderMode != RenderMode::QUAD_BATCHNODE, "CCSprite: updateBlendFunc doesn't work when the sprite is rendered using a SpriteBatchNode");
  1416. // it is possible to have an untextured sprite
  1417. if (! _texture || ! _texture->hasPremultipliedAlpha())
  1418. {
  1419. _blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED;
  1420. setOpacityModifyRGB(false);
  1421. }
  1422. else
  1423. {
  1424. _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;
  1425. setOpacityModifyRGB(true);
  1426. }
  1427. }
  1428. std::string Sprite::getDescription() const
  1429. {
  1430. int texture_id = -1;
  1431. if (_renderMode == RenderMode::QUAD_BATCHNODE)
  1432. texture_id = _batchNode->getTextureAtlas()->getTexture()->getName();
  1433. else
  1434. texture_id = _texture->getName();
  1435. return StringUtils::format("<Sprite | Tag = %d, TextureID = %d>", _tag, texture_id );
  1436. }
  1437. const PolygonInfo& Sprite::getPolygonInfo() const
  1438. {
  1439. return _polyInfo;
  1440. }
  1441. void Sprite::setPolygonInfo(const PolygonInfo& info)
  1442. {
  1443. _polyInfo = info;
  1444. _renderMode = RenderMode::POLYGON;
  1445. }
  1446. NS_CC_END