CCSprite.cpp 51 KB

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