CCTMXLayer.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  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/CCTMXLayer.h"
  24. #include "2d/CCTMXTiledMap.h"
  25. #include "2d/CCSprite.h"
  26. #include "base/CCDirector.h"
  27. #include "base/ccUTF8.h"
  28. #include "renderer/CCTextureCache.h"
  29. #include "renderer/CCGLProgram.h"
  30. NS_CC_BEGIN
  31. // TMXLayer - init & alloc & dealloc
  32. TMXLayer * TMXLayer::create(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo)
  33. {
  34. TMXLayer *ret = new (std::nothrow) TMXLayer();
  35. if (ret->initWithTilesetInfo(tilesetInfo, layerInfo, mapInfo))
  36. {
  37. ret->autorelease();
  38. return ret;
  39. }
  40. CC_SAFE_DELETE(ret);
  41. return nullptr;
  42. }
  43. bool TMXLayer::initWithTilesetInfo(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo)
  44. {
  45. // FIXME:: is 35% a good estimate ?
  46. Size size = layerInfo->_layerSize;
  47. float totalNumberOfTiles = size.width * size.height;
  48. float capacity = totalNumberOfTiles * 0.35f + 1; // 35 percent is occupied ?
  49. Texture2D *texture = nullptr;
  50. if( tilesetInfo )
  51. {
  52. texture = Director::getInstance()->getTextureCache()->addImage(tilesetInfo->_sourceImage);
  53. }
  54. if (nullptr == texture)
  55. return false;
  56. if (SpriteBatchNode::initWithTexture(texture, static_cast<ssize_t>(capacity)))
  57. {
  58. // layerInfo
  59. _layerName = layerInfo->_name;
  60. _layerSize = size;
  61. _tiles = layerInfo->_tiles;
  62. _opacity = layerInfo->_opacity;
  63. setProperties(layerInfo->getProperties());
  64. _contentScaleFactor = Director::getInstance()->getContentScaleFactor();
  65. // tilesetInfo
  66. _tileSet = tilesetInfo;
  67. CC_SAFE_RETAIN(_tileSet);
  68. // mapInfo
  69. _mapTileSize = mapInfo->getTileSize();
  70. _layerOrientation = mapInfo->getOrientation();
  71. _staggerAxis = mapInfo->getStaggerAxis();
  72. _staggerIndex = mapInfo->getStaggerIndex();
  73. _hexSideLength = mapInfo->getHexSideLength();
  74. // offset (after layer orientation is set);
  75. Vec2 offset = this->calculateLayerOffset(layerInfo->_offset);
  76. this->setPosition(CC_POINT_PIXELS_TO_POINTS(offset));
  77. _atlasIndexArray = ccCArrayNew(totalNumberOfTiles);
  78. float width = 0;
  79. float height = 0;
  80. if (_layerOrientation == TMXOrientationHex) {
  81. if (_staggerAxis == TMXStaggerAxis_X) {
  82. height = _mapTileSize.height * (_layerSize.height + 0.5);
  83. width = (_mapTileSize.width + _hexSideLength) * ((int)(_layerSize.width / 2)) + _mapTileSize.width * ((int)_layerSize.width % 2);
  84. } else {
  85. width = _mapTileSize.width * (_layerSize.width + 0.5);
  86. height = (_mapTileSize.height + _hexSideLength) * ((int)(_layerSize.height / 2)) + _mapTileSize.height * ((int)_layerSize.height % 2);
  87. }
  88. } else {
  89. width = _layerSize.width * _mapTileSize.width;
  90. height = _layerSize.height * _mapTileSize.height;
  91. }
  92. this->setContentSize(CC_SIZE_PIXELS_TO_POINTS(Size(width, height)));
  93. _useAutomaticVertexZ = false;
  94. _vertexZvalue = 0;
  95. return true;
  96. }
  97. return false;
  98. }
  99. TMXLayer::TMXLayer()
  100. :_layerName("")
  101. ,_opacity(0)
  102. ,_vertexZvalue(0)
  103. ,_useAutomaticVertexZ(false)
  104. ,_reusedTile(nullptr)
  105. ,_atlasIndexArray(nullptr)
  106. ,_contentScaleFactor(1.0f)
  107. ,_layerSize(Size::ZERO)
  108. ,_mapTileSize(Size::ZERO)
  109. ,_tiles(nullptr)
  110. ,_tileSet(nullptr)
  111. ,_layerOrientation(TMXOrientationOrtho)
  112. ,_staggerAxis(TMXStaggerAxis_Y)
  113. ,_staggerIndex(TMXStaggerIndex_Even)
  114. ,_hexSideLength(0)
  115. {}
  116. TMXLayer::~TMXLayer()
  117. {
  118. CC_SAFE_RELEASE(_tileSet);
  119. CC_SAFE_RELEASE(_reusedTile);
  120. if (_atlasIndexArray)
  121. {
  122. ccCArrayFree(_atlasIndexArray);
  123. _atlasIndexArray = nullptr;
  124. }
  125. CC_SAFE_FREE(_tiles);
  126. }
  127. void TMXLayer::releaseMap()
  128. {
  129. if (_tiles)
  130. {
  131. free(_tiles);
  132. _tiles = nullptr;
  133. }
  134. if (_atlasIndexArray)
  135. {
  136. ccCArrayFree(_atlasIndexArray);
  137. _atlasIndexArray = nullptr;
  138. }
  139. }
  140. // TMXLayer - setup Tiles
  141. void TMXLayer::setupTiles()
  142. {
  143. // Optimization: quick hack that sets the image size on the tileset
  144. _tileSet->_imageSize = _textureAtlas->getTexture()->getContentSizeInPixels();
  145. // By default all the tiles are aliased
  146. // pros:
  147. // - easier to render
  148. // cons:
  149. // - difficult to scale / rotate / etc.
  150. _textureAtlas->getTexture()->setAliasTexParameters();
  151. //CFByteOrder o = CFByteOrderGetCurrent();
  152. // Parse cocos2d properties
  153. this->parseInternalProperties();
  154. for (int y=0; y < _layerSize.height; y++)
  155. {
  156. for (int x=0; x < _layerSize.width; x++)
  157. {
  158. int newX = x;
  159. // fix correct render ordering in Hexagonal maps when stagger axis == x
  160. if (_staggerAxis == TMXStaggerAxis_X && _layerOrientation == TMXOrientationHex)
  161. {
  162. if (_staggerIndex == TMXStaggerIndex_Odd)
  163. {
  164. if (x >= _layerSize.width/2)
  165. newX = (x - std::ceil(_layerSize.width/2)) * 2 + 1;
  166. else
  167. newX = x * 2;
  168. } else {
  169. // TMXStaggerIndex_Even
  170. if (x >= static_cast<int>(_layerSize.width/2))
  171. newX = (x - static_cast<int>(_layerSize.width/2)) * 2;
  172. else
  173. newX = x * 2 + 1;
  174. }
  175. }
  176. int pos = static_cast<int>(newX + _layerSize.width * y);
  177. int gid = _tiles[ pos ];
  178. // gid are stored in little endian.
  179. // if host is big endian, then swap
  180. //if( o == CFByteOrderBigEndian )
  181. // gid = CFSwapInt32( gid );
  182. /* We support little endian.*/
  183. // FIXME:: gid == 0 --> empty tile
  184. if (gid != 0)
  185. {
  186. this->appendTileForGID(gid, Vec2(newX, y));
  187. }
  188. }
  189. }
  190. }
  191. // TMXLayer - Properties
  192. Value TMXLayer::getProperty(const std::string& propertyName) const
  193. {
  194. if (_properties.find(propertyName) != _properties.end())
  195. return _properties.at(propertyName);
  196. return Value();
  197. }
  198. void TMXLayer::parseInternalProperties()
  199. {
  200. // if cc_vertex=automatic, then tiles will be rendered using vertexz
  201. auto vertexz = getProperty("cc_vertexz");
  202. if (!vertexz.isNull())
  203. {
  204. std::string vertexZStr = vertexz.asString();
  205. // If "automatic" is on, then parse the "cc_alpha_func" too
  206. if (vertexZStr == "automatic")
  207. {
  208. _useAutomaticVertexZ = true;
  209. auto alphaFuncVal = getProperty("cc_alpha_func");
  210. float alphaFuncValue = alphaFuncVal.asFloat();
  211. setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST));
  212. GLint alphaValueLocation = glGetUniformLocation(getGLProgram()->getProgram(), GLProgram::UNIFORM_NAME_ALPHA_TEST_VALUE);
  213. // NOTE: alpha test shader is hard-coded to use the equivalent of a glAlphaFunc(GL_GREATER) comparison
  214. // use shader program to set uniform
  215. getGLProgram()->use();
  216. getGLProgram()->setUniformLocationWith1f(alphaValueLocation, alphaFuncValue);
  217. CHECK_GL_ERROR_DEBUG();
  218. }
  219. else
  220. {
  221. _vertexZvalue = vertexz.asInt();
  222. }
  223. }
  224. }
  225. void TMXLayer::setupTileSprite(Sprite* sprite, const Vec2& pos, uint32_t gid)
  226. {
  227. sprite->setPosition(getPositionAt(pos));
  228. sprite->setPositionZ((float)getVertexZForPos(pos));
  229. sprite->setAnchorPoint(Vec2::ZERO);
  230. sprite->setOpacity(_opacity);
  231. //issue 1264, flip can be undone as well
  232. sprite->setFlippedX(false);
  233. sprite->setFlippedY(false);
  234. sprite->setRotation(0.0f);
  235. sprite->setAnchorPoint(Vec2(0,0));
  236. // Rotation in tiled is achieved using 3 flipped states, flipping across the horizontal, vertical, and diagonal axes of the tiles.
  237. if (gid & kTMXTileDiagonalFlag)
  238. {
  239. // put the anchor in the middle for ease of rotation.
  240. sprite->setAnchorPoint(Vec2(0.5f,0.5f));
  241. sprite->setPosition(getPositionAt(pos).x + sprite->getContentSize().height/2,
  242. getPositionAt(pos).y + sprite->getContentSize().width/2 );
  243. auto flag = gid & (kTMXTileHorizontalFlag | kTMXTileVerticalFlag );
  244. // handle the 4 diagonally flipped states.
  245. if (flag == kTMXTileHorizontalFlag)
  246. {
  247. sprite->setRotation(90.0f);
  248. }
  249. else if (flag == kTMXTileVerticalFlag)
  250. {
  251. sprite->setRotation(270.0f);
  252. }
  253. else if (flag == (kTMXTileVerticalFlag | kTMXTileHorizontalFlag) )
  254. {
  255. sprite->setRotation(90.0f);
  256. sprite->setFlippedX(true);
  257. }
  258. else
  259. {
  260. sprite->setRotation(270.0f);
  261. sprite->setFlippedX(true);
  262. }
  263. }
  264. else
  265. {
  266. if (gid & kTMXTileHorizontalFlag)
  267. {
  268. sprite->setFlippedX(true);
  269. }
  270. if (gid & kTMXTileVerticalFlag)
  271. {
  272. sprite->setFlippedY(true);
  273. }
  274. }
  275. }
  276. Sprite* TMXLayer::reusedTileWithRect(const Rect& rect)
  277. {
  278. if (! _reusedTile)
  279. {
  280. _reusedTile = Sprite::createWithTexture(_textureAtlas->getTexture(), rect);
  281. _reusedTile->setBatchNode(this);
  282. _reusedTile->retain();
  283. }
  284. else
  285. {
  286. // FIXME: HACK: Needed because if "batch node" is nil,
  287. // then the Sprite'squad will be reset
  288. _reusedTile->setBatchNode(nullptr);
  289. // Re-init the sprite
  290. _reusedTile->setTextureRect(rect, false, rect.size);
  291. // restore the batch node
  292. _reusedTile->setBatchNode(this);
  293. }
  294. return _reusedTile;
  295. }
  296. // TMXLayer - obtaining tiles/gids
  297. Sprite * TMXLayer::getTileAt(const Vec2& pos)
  298. {
  299. CCASSERT(pos.x < _layerSize.width && pos.y < _layerSize.height && pos.x >=0 && pos.y >=0, "TMXLayer: invalid position");
  300. CCASSERT(_tiles && _atlasIndexArray, "TMXLayer: the tiles map has been released");
  301. Sprite *tile = nullptr;
  302. int gid = this->getTileGIDAt(pos);
  303. // if GID == 0, then no tile is present
  304. if (gid)
  305. {
  306. int z = (int)(pos.x + pos.y * _layerSize.width);
  307. tile = static_cast<Sprite*>(this->getChildByTag(z));
  308. // tile not created yet. create it
  309. if (! tile)
  310. {
  311. Rect rect = _tileSet->getRectForGID(gid);
  312. rect = CC_RECT_PIXELS_TO_POINTS(rect);
  313. tile = Sprite::createWithTexture(this->getTexture(), rect);
  314. tile->setBatchNode(this);
  315. tile->setPosition(getPositionAt(pos));
  316. tile->setPositionZ((float)getVertexZForPos(pos));
  317. tile->setAnchorPoint(Vec2::ZERO);
  318. tile->setOpacity(_opacity);
  319. ssize_t indexForZ = atlasIndexForExistantZ(z);
  320. this->addSpriteWithoutQuad(tile, static_cast<int>(indexForZ), z);
  321. }
  322. }
  323. return tile;
  324. }
  325. uint32_t TMXLayer::getTileGIDAt(const Vec2& pos, TMXTileFlags* flags/* = nullptr*/)
  326. {
  327. CCASSERT(pos.x < _layerSize.width && pos.y < _layerSize.height && pos.x >=0 && pos.y >=0, "TMXLayer: invalid position");
  328. CCASSERT(_tiles && _atlasIndexArray, "TMXLayer: the tiles map has been released");
  329. ssize_t idx = static_cast<int>(((int) pos.x + (int) pos.y * _layerSize.width));
  330. // Bits on the far end of the 32-bit global tile ID are used for tile flags
  331. uint32_t tile = _tiles[idx];
  332. // issue1264, flipped tiles can be changed dynamically
  333. if (flags)
  334. {
  335. *flags = (TMXTileFlags)(tile & kTMXFlipedAll);
  336. }
  337. return (tile & kTMXFlippedMask);
  338. }
  339. // TMXLayer - adding helper methods
  340. Sprite * TMXLayer::insertTileForGID(uint32_t gid, const Vec2& pos)
  341. {
  342. if (gid != 0 && (static_cast<int>((gid & kTMXFlippedMask)) - _tileSet->_firstGid) >= 0)
  343. {
  344. Rect rect = _tileSet->getRectForGID(gid);
  345. rect = CC_RECT_PIXELS_TO_POINTS(rect);
  346. intptr_t z = (intptr_t)((int) pos.x + (int) pos.y * _layerSize.width);
  347. Sprite *tile = reusedTileWithRect(rect);
  348. setupTileSprite(tile, pos, gid);
  349. // get atlas index
  350. ssize_t indexForZ = atlasIndexForNewZ(static_cast<int>(z));
  351. // Optimization: add the quad without adding a child
  352. this->insertQuadFromSprite(tile, indexForZ);
  353. // insert it into the local atlasindex array
  354. ccCArrayInsertValueAtIndex(_atlasIndexArray, (void*)z, indexForZ);
  355. // update possible children
  356. for(const auto &child : _children) {
  357. Sprite* sp = static_cast<Sprite*>(child);
  358. ssize_t ai = sp->getAtlasIndex();
  359. if ( ai >= indexForZ )
  360. {
  361. sp->setAtlasIndex(ai+1);
  362. }
  363. }
  364. _tiles[z] = gid;
  365. return tile;
  366. }
  367. return nullptr;
  368. }
  369. Sprite * TMXLayer::updateTileForGID(uint32_t gid, const Vec2& pos)
  370. {
  371. Rect rect = _tileSet->getRectForGID(gid);
  372. rect = Rect(rect.origin.x / _contentScaleFactor, rect.origin.y / _contentScaleFactor, rect.size.width/ _contentScaleFactor, rect.size.height/ _contentScaleFactor);
  373. int z = (int)((int) pos.x + (int) pos.y * _layerSize.width);
  374. Sprite *tile = reusedTileWithRect(rect);
  375. setupTileSprite(tile ,pos ,gid);
  376. // get atlas index
  377. ssize_t indexForZ = atlasIndexForExistantZ(z);
  378. tile->setAtlasIndex(indexForZ);
  379. tile->setDirty(true);
  380. tile->updateTransform();
  381. _tiles[z] = gid;
  382. return tile;
  383. }
  384. intptr_t TMXLayer::getZForPos(const Vec2& pos) const
  385. {
  386. intptr_t z = -1;
  387. // fix correct render ordering in Hexagonal maps when stagger axis == x
  388. if (_staggerAxis == TMXStaggerAxis_X && _layerOrientation == TMXOrientationHex)
  389. {
  390. if (_staggerIndex == TMXStaggerIndex_Odd)
  391. {
  392. if (((int)pos.x % 2) == 0)
  393. z = pos.x / 2 + pos.y * _layerSize.width;
  394. else
  395. z = pos.x / 2 + std::ceil(_layerSize.width / 2) + pos.y * _layerSize.width;
  396. } else {
  397. // TMXStaggerIndex_Even
  398. if (((int)pos.x % 2) == 1)
  399. z = pos.x / 2 + pos.y * _layerSize.width;
  400. else
  401. z = pos.x / 2 + std::floor(_layerSize.width / 2) + pos.y * _layerSize.width;
  402. }
  403. }
  404. else
  405. {
  406. z = (pos.x + pos.y * _layerSize.width);
  407. }
  408. CCASSERT(z != -1, "Invalid Z");
  409. return z;
  410. }
  411. // used only when parsing the map. useless after the map was parsed
  412. // since lot's of assumptions are no longer true
  413. Sprite * TMXLayer::appendTileForGID(uint32_t gid, const Vec2& pos)
  414. {
  415. if (gid != 0 && (static_cast<int>((gid & kTMXFlippedMask)) - _tileSet->_firstGid) >= 0)
  416. {
  417. Rect rect = _tileSet->getRectForGID(gid);
  418. rect = CC_RECT_PIXELS_TO_POINTS(rect);
  419. // Z could be just an integer that gets incremented each time it is called.
  420. // but that wouldn't work on layers with empty tiles.
  421. // and it is IMPORTANT that Z returns an unique and bigger number than the previous one.
  422. // since _atlasIndexArray must be ordered because `bsearch` is used to find the GID for
  423. // a given Z. (github issue #16512)
  424. intptr_t z = getZForPos(pos);
  425. Sprite *tile = reusedTileWithRect(rect);
  426. setupTileSprite(tile ,pos ,gid);
  427. // optimization:
  428. // The difference between appendTileForGID and insertTileforGID is that append is faster, since
  429. // it appends the tile at the end of the texture atlas
  430. ssize_t indexForZ = _atlasIndexArray->num;
  431. // don't add it using the "standard" way.
  432. insertQuadFromSprite(tile, indexForZ);
  433. // append should be after addQuadFromSprite since it modifies the quantity values
  434. ccCArrayInsertValueAtIndex(_atlasIndexArray, (void*)z, indexForZ);
  435. // Validation for issue #16512
  436. CCASSERT(_atlasIndexArray->num == 1 ||
  437. _atlasIndexArray->arr[_atlasIndexArray->num-1] > _atlasIndexArray->arr[_atlasIndexArray->num-2], "Invalid z for _atlasIndexArray");
  438. return tile;
  439. }
  440. return nullptr;
  441. }
  442. // TMXLayer - atlasIndex and Z
  443. static inline int compareInts(const void * a, const void * b)
  444. {
  445. const int ia = *(int*)a;
  446. const int ib = *(int*)b;
  447. return (ia-ib);
  448. }
  449. ssize_t TMXLayer::atlasIndexForExistantZ(int z)
  450. {
  451. int key=z;
  452. int *item = (int*)bsearch((void*)&key, (void*)&_atlasIndexArray->arr[0], _atlasIndexArray->num, sizeof(void*), compareInts);
  453. CCASSERT(item, "TMX atlas index not found. Shall not happen");
  454. ssize_t index = ((size_t)item - (size_t)_atlasIndexArray->arr) / sizeof(void*);
  455. return index;
  456. }
  457. ssize_t TMXLayer::atlasIndexForNewZ(int z)
  458. {
  459. // FIXME:: This can be improved with a sort of binary search
  460. ssize_t i=0;
  461. for (i=0; i< _atlasIndexArray->num ; i++)
  462. {
  463. ssize_t val = (size_t) _atlasIndexArray->arr[i];
  464. if (z < val)
  465. {
  466. break;
  467. }
  468. }
  469. return i;
  470. }
  471. // TMXLayer - adding / remove tiles
  472. void TMXLayer::setTileGID(uint32_t gid, const Vec2& pos)
  473. {
  474. setTileGID(gid, pos, (TMXTileFlags)0);
  475. }
  476. void TMXLayer::setTileGID(uint32_t gid, const Vec2& pos, TMXTileFlags flags)
  477. {
  478. CCASSERT(pos.x < _layerSize.width && pos.y < _layerSize.height && pos.x >=0 && pos.y >=0, "TMXLayer: invalid position");
  479. CCASSERT(_tiles && _atlasIndexArray, "TMXLayer: the tiles map has been released");
  480. CCASSERT(gid == 0 || (int)gid >= _tileSet->_firstGid, "TMXLayer: invalid gid" );
  481. TMXTileFlags currentFlags;
  482. uint32_t currentGID = getTileGIDAt(pos, &currentFlags);
  483. if (currentGID != gid || currentFlags != flags)
  484. {
  485. uint32_t gidAndFlags = gid | flags;
  486. // setting gid=0 is equal to remove the tile
  487. if (gid == 0)
  488. {
  489. removeTileAt(pos);
  490. }
  491. // empty tile. create a new one
  492. else if (currentGID == 0)
  493. {
  494. insertTileForGID(gidAndFlags, pos);
  495. }
  496. // modifying an existing tile with a non-empty tile
  497. else
  498. {
  499. int z = (int) pos.x + (int) pos.y * _layerSize.width;
  500. Sprite *sprite = static_cast<Sprite*>(getChildByTag(z));
  501. if (sprite)
  502. {
  503. Rect rect = _tileSet->getRectForGID(gid);
  504. rect = CC_RECT_PIXELS_TO_POINTS(rect);
  505. sprite->setTextureRect(rect, false, rect.size);
  506. if (flags)
  507. {
  508. setupTileSprite(sprite, sprite->getPosition(), gidAndFlags);
  509. }
  510. _tiles[z] = gidAndFlags;
  511. }
  512. else
  513. {
  514. updateTileForGID(gidAndFlags, pos);
  515. }
  516. }
  517. }
  518. }
  519. void TMXLayer::addChild(Node* /*child*/, int /*zOrder*/, int /*tag*/)
  520. {
  521. CCASSERT(0, "addChild: is not supported on TMXLayer. Instead use setTileGID:at:/tileAt:");
  522. }
  523. void TMXLayer::removeChild(Node* node, bool cleanup)
  524. {
  525. Sprite *sprite = (Sprite*)node;
  526. // allows removing nil objects
  527. if (! sprite)
  528. {
  529. return;
  530. }
  531. CCASSERT(_children.contains(sprite), "Tile does not belong to TMXLayer");
  532. ssize_t atlasIndex = sprite->getAtlasIndex();
  533. ssize_t zz = (ssize_t)_atlasIndexArray->arr[atlasIndex];
  534. _tiles[zz] = 0;
  535. ccCArrayRemoveValueAtIndex(_atlasIndexArray, atlasIndex);
  536. SpriteBatchNode::removeChild(sprite, cleanup);
  537. }
  538. void TMXLayer::removeTileAt(const Vec2& pos)
  539. {
  540. CCASSERT(pos.x < _layerSize.width && pos.y < _layerSize.height && pos.x >=0 && pos.y >=0, "TMXLayer: invalid position");
  541. CCASSERT(_tiles && _atlasIndexArray, "TMXLayer: the tiles map has been released");
  542. int gid = getTileGIDAt(pos);
  543. if (gid)
  544. {
  545. int z = pos.x + pos.y * _layerSize.width;
  546. ssize_t atlasIndex = atlasIndexForExistantZ(z);
  547. // remove tile from GID map
  548. _tiles[z] = 0;
  549. // remove tile from atlas position array
  550. ccCArrayRemoveValueAtIndex(_atlasIndexArray, atlasIndex);
  551. // remove it from sprites and/or texture atlas
  552. Sprite *sprite = (Sprite*)getChildByTag(z);
  553. if (sprite)
  554. {
  555. SpriteBatchNode::removeChild(sprite, true);
  556. }
  557. else
  558. {
  559. _textureAtlas->removeQuadAtIndex(atlasIndex);
  560. // update possible children
  561. for(const auto &obj : _children) {
  562. Sprite* child = static_cast<Sprite*>(obj);
  563. ssize_t ai = child->getAtlasIndex();
  564. if ( ai >= atlasIndex )
  565. {
  566. child->setAtlasIndex(ai-1);
  567. }
  568. }
  569. }
  570. }
  571. }
  572. //CCTMXLayer - obtaining positions, offset
  573. Vec2 TMXLayer::calculateLayerOffset(const Vec2& pos)
  574. {
  575. Vec2 ret;
  576. switch (_layerOrientation)
  577. {
  578. case TMXOrientationOrtho:
  579. ret.set( pos.x * _mapTileSize.width, -pos.y *_mapTileSize.height);
  580. break;
  581. case TMXOrientationIso:
  582. ret.set((_mapTileSize.width /2) * (pos.x - pos.y),
  583. (_mapTileSize.height /2 ) * (-pos.x - pos.y));
  584. break;
  585. case TMXOrientationHex:
  586. {
  587. if(_staggerAxis == TMXStaggerAxis_Y)
  588. {
  589. int diffX = (_staggerIndex == TMXStaggerIndex_Even) ? _mapTileSize.width/2 : 0;
  590. ret.set(pos.x * _mapTileSize.width + diffX, -pos.y * (_mapTileSize.height - (_mapTileSize.width - _hexSideLength) / 2));
  591. }
  592. else if(_staggerAxis == TMXStaggerAxis_X)
  593. {
  594. int diffY = (_staggerIndex == TMXStaggerIndex_Odd) ? _mapTileSize.height/2 : 0;
  595. ret.set(pos.x * (_mapTileSize.width - (_mapTileSize.width - _hexSideLength) / 2), -pos.y * _mapTileSize.height + diffY);
  596. }
  597. break;
  598. }
  599. case TMXOrientationStaggered:
  600. {
  601. float diffX = 0;
  602. if ((int)std::abs(pos.y) % 2 == 1)
  603. {
  604. diffX = _mapTileSize.width/2;
  605. }
  606. ret.set(pos.x * _mapTileSize.width + diffX,
  607. (-pos.y) * _mapTileSize.height/2);
  608. }
  609. break;
  610. }
  611. return ret;
  612. }
  613. Vec2 TMXLayer::getPositionAt(const Vec2& pos)
  614. {
  615. Vec2 ret;
  616. switch (_layerOrientation)
  617. {
  618. case TMXOrientationOrtho:
  619. ret = getPositionForOrthoAt(pos);
  620. break;
  621. case TMXOrientationIso:
  622. ret = getPositionForIsoAt(pos);
  623. break;
  624. case TMXOrientationHex:
  625. ret = getPositionForHexAt(pos);
  626. break;
  627. case TMXOrientationStaggered:
  628. ret = getPositionForStaggeredAt(pos);
  629. break;
  630. }
  631. ret = CC_POINT_PIXELS_TO_POINTS( ret );
  632. return ret;
  633. }
  634. Vec2 TMXLayer::getPositionForOrthoAt(const Vec2& pos)
  635. {
  636. return Vec2(pos.x * _mapTileSize.width,
  637. (_layerSize.height - pos.y - 1) * _mapTileSize.height);
  638. }
  639. Vec2 TMXLayer::getPositionForIsoAt(const Vec2& pos)
  640. {
  641. return Vec2(_mapTileSize.width /2 * (_layerSize.width + pos.x - pos.y - 1),
  642. _mapTileSize.height /2 * ((_layerSize.height * 2 - pos.x - pos.y) - 2));
  643. }
  644. Vec2 TMXLayer::getPositionForHexAt(const Vec2& pos)
  645. {
  646. Vec2 xy;
  647. Vec2 offset = _tileSet->_tileOffset;
  648. int odd_even = (_staggerIndex == TMXStaggerIndex_Odd) ? 1 : -1;
  649. switch (_staggerAxis)
  650. {
  651. case TMXStaggerAxis_Y:
  652. {
  653. float diffX = 0;
  654. if ((int)pos.y % 2 == 1)
  655. {
  656. diffX = _mapTileSize.width/2 * odd_even;
  657. }
  658. xy = Vec2(pos.x * _mapTileSize.width+diffX+offset.x,
  659. (_layerSize.height - pos.y - 1) * (_mapTileSize.height-(_mapTileSize.height-_hexSideLength)/2)-offset.y);
  660. break;
  661. }
  662. case TMXStaggerAxis_X:
  663. {
  664. float diffY = 0;
  665. if ((int)pos.x % 2 == 1)
  666. {
  667. diffY = _mapTileSize.height/2 * -odd_even;
  668. }
  669. xy = Vec2(pos.x * (_mapTileSize.width-(_mapTileSize.width-_hexSideLength)/2)+offset.x,
  670. (_layerSize.height - pos.y - 1) * _mapTileSize.height + diffY-offset.y);
  671. break;
  672. }
  673. }
  674. return xy;
  675. }
  676. Vec2 TMXLayer::getPositionForStaggeredAt(const Vec2 &pos)
  677. {
  678. float diffX = 0;
  679. if ((int)pos.y % 2 == 1)
  680. {
  681. diffX = _mapTileSize.width/2;
  682. }
  683. return Vec2(pos.x * _mapTileSize.width + diffX,
  684. (_layerSize.height - pos.y - 1) * _mapTileSize.height/2);
  685. }
  686. int TMXLayer::getVertexZForPos(const Vec2& pos)
  687. {
  688. int ret = 0;
  689. int maxVal = 0;
  690. if (_useAutomaticVertexZ)
  691. {
  692. switch (_layerOrientation)
  693. {
  694. case TMXOrientationIso:
  695. maxVal = static_cast<int>(_layerSize.width + _layerSize.height);
  696. ret = static_cast<int>(-(maxVal - (pos.x + pos.y)));
  697. break;
  698. case TMXOrientationOrtho:
  699. ret = static_cast<int>(-(_layerSize.height-pos.y));
  700. break;
  701. case TMXOrientationStaggered:
  702. ret = static_cast<int>(-(_layerSize.height-pos.y));
  703. break;
  704. case TMXOrientationHex:
  705. ret = static_cast<int>(-(_layerSize.height-pos.y));
  706. break;
  707. default:
  708. CCASSERT(0, "TMX invalid value");
  709. break;
  710. }
  711. }
  712. else
  713. {
  714. ret = _vertexZvalue;
  715. }
  716. return ret;
  717. }
  718. std::string TMXLayer::getDescription() const
  719. {
  720. return StringUtils::format("<TMXLayer | tag = %d, size = %d,%d>", _tag, (int)_mapTileSize.width, (int)_mapTileSize.height);
  721. }
  722. NS_CC_END