CCFastTMXLayer.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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. Copyright (c) 2011 HKASoftware
  8. http://www.cocos2d-x.org
  9. Permission is hereby granted, free of charge, to any person obtaining a copy
  10. of this software and associated documentation files (the "Software"), to deal
  11. in the Software without restriction, including without limitation the rights
  12. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. copies of the Software, and to permit persons to whom the Software is
  14. furnished to do so, subject to the following conditions:
  15. The above copyright notice and this permission notice shall be included in
  16. all copies or substantial portions of the Software.
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. THE SOFTWARE.
  24. ****************************************************************************/
  25. /*
  26. Original rewrite of TMXLayer was based on HKTMXTiledMap by HKASoftware http://hkasoftware.com
  27. Further info: http://www.cocos2d-iphone.org/forums/topic/hktmxtiledmap/
  28. It was rewritten again, and only a small part of the original HK ideas/code remains in this implementation
  29. */
  30. #include "2d/CCFastTMXLayer.h"
  31. #include "2d/CCFastTMXTiledMap.h"
  32. #include "2d/CCSprite.h"
  33. #include "2d/CCCamera.h"
  34. #include "renderer/CCTextureCache.h"
  35. #include "renderer/CCGLProgramCache.h"
  36. #include "renderer/ccGLStateCache.h"
  37. #include "renderer/CCRenderer.h"
  38. #include "renderer/CCVertexIndexBuffer.h"
  39. #include "base/CCDirector.h"
  40. #include "base/ccUTF8.h"
  41. NS_CC_BEGIN
  42. namespace experimental {
  43. const int TMXLayer::FAST_TMX_ORIENTATION_ORTHO = 0;
  44. const int TMXLayer::FAST_TMX_ORIENTATION_HEX = 1;
  45. const int TMXLayer::FAST_TMX_ORIENTATION_ISO = 2;
  46. // FastTMXLayer - init & alloc & dealloc
  47. TMXLayer * TMXLayer::create(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo)
  48. {
  49. TMXLayer *ret = new (std::nothrow) TMXLayer();
  50. if (ret->initWithTilesetInfo(tilesetInfo, layerInfo, mapInfo))
  51. {
  52. ret->autorelease();
  53. return ret;
  54. }
  55. CC_SAFE_DELETE(ret);
  56. return nullptr;
  57. }
  58. bool TMXLayer::initWithTilesetInfo(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo)
  59. {
  60. if( tilesetInfo )
  61. {
  62. _texture = Director::getInstance()->getTextureCache()->addImage(tilesetInfo->_sourceImage);
  63. _texture->retain();
  64. }
  65. // layerInfo
  66. _layerName = layerInfo->_name;
  67. _layerSize = layerInfo->_layerSize;
  68. _tiles = layerInfo->_tiles;
  69. _quadsDirty = true;
  70. setOpacity( layerInfo->_opacity );
  71. setProperties(layerInfo->getProperties());
  72. // tilesetInfo
  73. _tileSet = tilesetInfo;
  74. CC_SAFE_RETAIN(_tileSet);
  75. // mapInfo
  76. _mapTileSize = mapInfo->getTileSize();
  77. _layerOrientation = mapInfo->getOrientation();
  78. // offset (after layer orientation is set);
  79. Vec2 offset = this->calculateLayerOffset(layerInfo->_offset);
  80. this->setPosition(CC_POINT_PIXELS_TO_POINTS(offset));
  81. this->setContentSize(CC_SIZE_PIXELS_TO_POINTS(Size(_layerSize.width * _mapTileSize.width, _layerSize.height * _mapTileSize.height)));
  82. this->tileToNodeTransform();
  83. // shader, and other stuff
  84. setGLProgram(GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
  85. _useAutomaticVertexZ = false;
  86. _vertexZvalue = 0;
  87. return true;
  88. }
  89. TMXLayer::TMXLayer()
  90. : _layerName("")
  91. , _layerSize(Size::ZERO)
  92. , _mapTileSize(Size::ZERO)
  93. , _tiles(nullptr)
  94. , _tileSet(nullptr)
  95. , _layerOrientation(FAST_TMX_ORIENTATION_ORTHO)
  96. , _texture(nullptr)
  97. , _vertexZvalue(0)
  98. , _useAutomaticVertexZ(false)
  99. , _quadsDirty(true)
  100. , _dirty(true)
  101. , _vertexBuffer(nullptr)
  102. , _vData(nullptr)
  103. , _indexBuffer(nullptr)
  104. {
  105. }
  106. TMXLayer::~TMXLayer()
  107. {
  108. CC_SAFE_RELEASE(_tileSet);
  109. CC_SAFE_RELEASE(_texture);
  110. CC_SAFE_FREE(_tiles);
  111. CC_SAFE_RELEASE(_vData);
  112. CC_SAFE_RELEASE(_vertexBuffer);
  113. CC_SAFE_RELEASE(_indexBuffer);
  114. }
  115. void TMXLayer::draw(Renderer *renderer, const Mat4& transform, uint32_t flags)
  116. {
  117. updateTotalQuads();
  118. bool isViewProjectionUpdated = true;
  119. auto visitingCamera = Camera::getVisitingCamera();
  120. auto defaultCamera = Camera::getDefaultCamera();
  121. if (visitingCamera == defaultCamera) {
  122. isViewProjectionUpdated = visitingCamera->isViewProjectionUpdated();
  123. }
  124. if( flags != 0 || _dirty || _quadsDirty || isViewProjectionUpdated)
  125. {
  126. Size s = Director::getInstance()->getVisibleSize();
  127. auto rect = Rect(Camera::getVisitingCamera()->getPositionX() - s.width * 0.5f,
  128. Camera::getVisitingCamera()->getPositionY() - s.height * 0.5f,
  129. s.width,
  130. s.height);
  131. Mat4 inv = transform;
  132. inv.inverse();
  133. rect = RectApplyTransform(rect, inv);
  134. updateTiles(rect);
  135. updateIndexBuffer();
  136. updatePrimitives();
  137. _dirty = false;
  138. }
  139. if(_renderCommands.size() < static_cast<size_t>(_primitives.size()))
  140. {
  141. _renderCommands.resize(_primitives.size());
  142. }
  143. int index = 0;
  144. for(const auto& iter : _primitives)
  145. {
  146. if(iter.second->getCount() > 0)
  147. {
  148. auto& cmd = _renderCommands[index++];
  149. auto blendfunc = _texture->hasPremultipliedAlpha() ? BlendFunc::ALPHA_PREMULTIPLIED : BlendFunc::ALPHA_NON_PREMULTIPLIED;
  150. cmd.init(iter.first, _texture->getName(), getGLProgramState(), blendfunc, iter.second, _modelViewTransform, flags);
  151. renderer->addCommand(&cmd);
  152. }
  153. }
  154. }
  155. void TMXLayer::onDraw(Primitive *primitive)
  156. {
  157. GL::bindTexture2D(_texture->getName());
  158. getGLProgramState()->apply(_modelViewTransform);
  159. GL::bindVAO(0);
  160. primitive->draw();
  161. glBindBuffer(GL_ARRAY_BUFFER, 0);
  162. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  163. CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1, primitive->getCount() * 4);
  164. }
  165. void TMXLayer::updateTiles(const Rect& culledRect)
  166. {
  167. Rect visibleTiles = Rect(culledRect.origin, culledRect.size * Director::getInstance()->getContentScaleFactor());
  168. Size mapTileSize = CC_SIZE_PIXELS_TO_POINTS(_mapTileSize);
  169. Size tileSize = CC_SIZE_PIXELS_TO_POINTS(_tileSet->_tileSize);
  170. Mat4 nodeToTileTransform = _tileToNodeTransform.getInversed();
  171. //transform to tile
  172. visibleTiles = RectApplyTransform(visibleTiles, nodeToTileTransform);
  173. // tile coordinate is upside-down, so we need to make the tile coordinate use top-left for the start point.
  174. visibleTiles.origin.y += 1;
  175. // if x=0.7, width=9.5, we need to draw number 0~10 of tiles, and so is height.
  176. visibleTiles.size.width = ceil(visibleTiles.origin.x + visibleTiles.size.width) - floor(visibleTiles.origin.x);
  177. visibleTiles.size.height = ceil(visibleTiles.origin.y + visibleTiles.size.height) - floor(visibleTiles.origin.y);
  178. visibleTiles.origin.x = floor(visibleTiles.origin.x);
  179. visibleTiles.origin.y = floor(visibleTiles.origin.y);
  180. // for the bigger tiles.
  181. int tilesOverX = 0;
  182. int tilesOverY = 0;
  183. // for diagonal orientation tiles
  184. float tileSizeMax = std::max(tileSize.width, tileSize.height);
  185. if (_layerOrientation == FAST_TMX_ORIENTATION_ORTHO)
  186. {
  187. tilesOverX = ceil(tileSizeMax / mapTileSize.width) - 1;
  188. tilesOverY = ceil(tileSizeMax / mapTileSize.height) - 1;
  189. if (tilesOverX < 0) tilesOverX = 0;
  190. if (tilesOverY < 0) tilesOverY = 0;
  191. }
  192. else if(_layerOrientation == FAST_TMX_ORIENTATION_ISO)
  193. {
  194. Rect overTileRect(0, 0, tileSizeMax - mapTileSize.width, tileSizeMax - mapTileSize.height);
  195. if (overTileRect.size.width < 0) overTileRect.size.width = 0;
  196. if (overTileRect.size.height < 0) overTileRect.size.height = 0;
  197. overTileRect = RectApplyTransform(overTileRect, nodeToTileTransform);
  198. tilesOverX = ceil(overTileRect.origin.x + overTileRect.size.width) - floor(overTileRect.origin.x);
  199. tilesOverY = ceil(overTileRect.origin.y + overTileRect.size.height) - floor(overTileRect.origin.y);
  200. }
  201. else
  202. {
  203. //do nothing, do not support
  204. //CCASSERT(0, "TMX invalid value");
  205. }
  206. _indicesVertexZNumber.clear();
  207. for(const auto& iter : _indicesVertexZOffsets)
  208. {
  209. _indicesVertexZNumber[iter.first] = iter.second;
  210. }
  211. int yBegin = std::max(0.f,visibleTiles.origin.y - tilesOverY);
  212. int yEnd = std::min(_layerSize.height,visibleTiles.origin.y + visibleTiles.size.height + tilesOverY);
  213. int xBegin = std::max(0.f,visibleTiles.origin.x - tilesOverX);
  214. int xEnd = std::min(_layerSize.width,visibleTiles.origin.x + visibleTiles.size.width + tilesOverX);
  215. for (int y = yBegin; y < yEnd; ++y)
  216. {
  217. for (int x = xBegin; x < xEnd; ++x)
  218. {
  219. int tileIndex = getTileIndexByPos(x, y);
  220. if(_tiles[tileIndex] == 0) continue;
  221. int vertexZ = getVertexZForPos(Vec2(x,y));
  222. auto iter = _indicesVertexZNumber.find(vertexZ);
  223. int offset = iter->second;
  224. iter->second++;
  225. int quadIndex = _tileToQuadIndex[tileIndex];
  226. CC_ASSERT(-1 != quadIndex);
  227. _indices[6 * offset + 0] = quadIndex * 4 + 0;
  228. _indices[6 * offset + 1] = quadIndex * 4 + 1;
  229. _indices[6 * offset + 2] = quadIndex * 4 + 2;
  230. _indices[6 * offset + 3] = quadIndex * 4 + 3;
  231. _indices[6 * offset + 4] = quadIndex * 4 + 2;
  232. _indices[6 * offset + 5] = quadIndex * 4 + 1;
  233. } // for x
  234. } // for y
  235. for(const auto& iter : _indicesVertexZOffsets)
  236. {
  237. _indicesVertexZNumber[iter.first] -= iter.second;
  238. if(_indicesVertexZNumber[iter.first] == 0)
  239. {
  240. _indicesVertexZNumber.erase(iter.first);
  241. }
  242. }
  243. }
  244. void TMXLayer::updateVertexBuffer()
  245. {
  246. GL::bindVAO(0);
  247. if(nullptr == _vData)
  248. {
  249. _vertexBuffer = VertexBuffer::create(sizeof(V3F_C4B_T2F), (int)_totalQuads.size() * 4);
  250. _vData = VertexData::create();
  251. _vData->setStream(_vertexBuffer, VertexStreamAttribute(0, GLProgram::VERTEX_ATTRIB_POSITION, GL_FLOAT, 3));
  252. _vData->setStream(_vertexBuffer, VertexStreamAttribute(offsetof(V3F_C4B_T2F, colors), GLProgram::VERTEX_ATTRIB_COLOR, GL_UNSIGNED_BYTE, 4, true));
  253. _vData->setStream(_vertexBuffer, VertexStreamAttribute(offsetof(V3F_C4B_T2F, texCoords), GLProgram::VERTEX_ATTRIB_TEX_COORD, GL_FLOAT, 2));
  254. CC_SAFE_RETAIN(_vData);
  255. CC_SAFE_RETAIN(_vertexBuffer);
  256. }
  257. if(_vertexBuffer)
  258. {
  259. _vertexBuffer->updateVertices((void*)&_totalQuads[0], (int)_totalQuads.size() * 4, 0);
  260. }
  261. }
  262. void TMXLayer::updateIndexBuffer()
  263. {
  264. if(nullptr == _indexBuffer)
  265. {
  266. #ifdef CC_FAST_TILEMAP_32_BIT_INDICES
  267. _indexBuffer = IndexBuffer::create(IndexBuffer::IndexType::INDEX_TYPE_UINT_32, (int)_indices.size());
  268. #else
  269. _indexBuffer = IndexBuffer::create(IndexBuffer::IndexType::INDEX_TYPE_SHORT_16, (int)_indices.size());
  270. #endif
  271. CC_SAFE_RETAIN(_indexBuffer);
  272. }
  273. _indexBuffer->updateIndices(&_indices[0], (int)_indices.size(), 0);
  274. }
  275. // FastTMXLayer - setup Tiles
  276. void TMXLayer::setupTiles()
  277. {
  278. // Optimization: quick hack that sets the image size on the tileset
  279. _tileSet->_imageSize = _texture->getContentSizeInPixels();
  280. // By default all the tiles are aliased
  281. // pros: easier to render
  282. // cons: difficult to scale / rotate / etc.
  283. _texture->setAliasTexParameters();
  284. //CFByteOrder o = CFByteOrderGetCurrent();
  285. // Parse cocos2d properties
  286. this->parseInternalProperties();
  287. Size screenSize = Director::getInstance()->getWinSize();
  288. switch (_layerOrientation)
  289. {
  290. case FAST_TMX_ORIENTATION_ORTHO:
  291. _screenGridSize.width = ceil(screenSize.width / _mapTileSize.width) + 1;
  292. _screenGridSize.height = ceil(screenSize.height / _mapTileSize.height) + 1;
  293. // tiles could be bigger than the grid, add additional rows if needed
  294. _screenGridSize.height += _tileSet->_tileSize.height / _mapTileSize.height;
  295. break;
  296. case FAST_TMX_ORIENTATION_ISO:
  297. _screenGridSize.width = ceil(screenSize.width / _mapTileSize.width) + 2;
  298. _screenGridSize.height = ceil(screenSize.height / (_mapTileSize.height/2)) + 4;
  299. break;
  300. case FAST_TMX_ORIENTATION_HEX:
  301. default:
  302. CCLOGERROR("FastTMX does not support type %d", _layerOrientation);
  303. break;
  304. }
  305. _screenTileCount = _screenGridSize.width * _screenGridSize.height;
  306. }
  307. Mat4 TMXLayer::tileToNodeTransform()
  308. {
  309. float w = _mapTileSize.width / CC_CONTENT_SCALE_FACTOR();
  310. float h = _mapTileSize.height / CC_CONTENT_SCALE_FACTOR();
  311. float offY = (_layerSize.height - 1) * h;
  312. switch(_layerOrientation)
  313. {
  314. case FAST_TMX_ORIENTATION_ORTHO:
  315. {
  316. _tileToNodeTransform = Mat4
  317. (
  318. w, 0.0f, 0.0f, 0.0f,
  319. 0.0f, -h, 0.0f, offY,
  320. 0.0f, 0.0f, 1.0f, 0.0f,
  321. 0.0f, 0.0, 0.0f, 1.0f
  322. );
  323. return _tileToNodeTransform;
  324. }
  325. case FAST_TMX_ORIENTATION_ISO:
  326. {
  327. float offX = (_layerSize.width - 1) * w / 2;
  328. _tileToNodeTransform = Mat4
  329. (
  330. w/2, -w/2, 0.0f, offX,
  331. -h/2, -h/2, 0.0f, offY,
  332. 0.0f, 0.0f, 1.0f, 0.0f,
  333. 0.0f, 0.0f, 0.0f, 1.0f
  334. );
  335. return _tileToNodeTransform;
  336. }
  337. case FAST_TMX_ORIENTATION_HEX:
  338. {
  339. _tileToNodeTransform = Mat4
  340. (
  341. h * sqrtf(0.75), 0, 0, 0,
  342. -h/2, -h, 0, offY,
  343. 0, 0, 1, 0,
  344. 0, 0, 0, 1
  345. );
  346. return _tileToNodeTransform;
  347. }
  348. default:
  349. {
  350. _tileToNodeTransform = Mat4::IDENTITY;
  351. return _tileToNodeTransform;
  352. }
  353. }
  354. }
  355. void TMXLayer::updatePrimitives()
  356. {
  357. for(const auto& iter : _indicesVertexZNumber)
  358. {
  359. int start = _indicesVertexZOffsets.at(iter.first);
  360. auto primitiveIter= _primitives.find(iter.first);
  361. if(primitiveIter == _primitives.end())
  362. {
  363. auto primitive = Primitive::create(_vData, _indexBuffer, GL_TRIANGLES);
  364. primitive->setCount(iter.second * 6);
  365. primitive->setStart(start * 6);
  366. _primitives.insert(iter.first, primitive);
  367. }
  368. else
  369. {
  370. primitiveIter->second->setCount(iter.second * 6);
  371. primitiveIter->second->setStart(start * 6);
  372. }
  373. }
  374. }
  375. void TMXLayer::updateTotalQuads()
  376. {
  377. if(_quadsDirty)
  378. {
  379. Size tileSize = CC_SIZE_PIXELS_TO_POINTS(_tileSet->_tileSize);
  380. Size texSize = _tileSet->_imageSize;
  381. _tileToQuadIndex.clear();
  382. _totalQuads.resize(int(_layerSize.width * _layerSize.height));
  383. _indices.resize(6 * int(_layerSize.width * _layerSize.height));
  384. _tileToQuadIndex.resize(int(_layerSize.width * _layerSize.height),-1);
  385. _indicesVertexZOffsets.clear();
  386. int quadIndex = 0;
  387. for(int y = 0; y < _layerSize.height; ++y)
  388. {
  389. for(int x =0; x < _layerSize.width; ++x)
  390. {
  391. int tileIndex = getTileIndexByPos(x, y);
  392. int tileGID = _tiles[tileIndex];
  393. if(tileGID == 0) continue;
  394. _tileToQuadIndex[tileIndex] = quadIndex;
  395. auto& quad = _totalQuads[quadIndex];
  396. Vec3 nodePos(float(x), float(y), 0);
  397. _tileToNodeTransform.transformPoint(&nodePos);
  398. float left, right, top, bottom, z;
  399. z = getVertexZForPos(Vec2(x, y));
  400. auto iter = _indicesVertexZOffsets.find(z);
  401. if(iter == _indicesVertexZOffsets.end())
  402. {
  403. _indicesVertexZOffsets[z] = 1;
  404. }
  405. else
  406. {
  407. iter->second++;
  408. }
  409. // vertices
  410. if (tileGID & kTMXTileDiagonalFlag)
  411. {
  412. left = nodePos.x;
  413. right = nodePos.x + tileSize.height;
  414. bottom = nodePos.y + tileSize.width;
  415. top = nodePos.y;
  416. }
  417. else
  418. {
  419. left = nodePos.x;
  420. right = nodePos.x + tileSize.width;
  421. bottom = nodePos.y + tileSize.height;
  422. top = nodePos.y;
  423. }
  424. if(tileGID & kTMXTileVerticalFlag)
  425. std::swap(top, bottom);
  426. if(tileGID & kTMXTileHorizontalFlag)
  427. std::swap(left, right);
  428. if(tileGID & kTMXTileDiagonalFlag)
  429. {
  430. // FIXME: not working correctly
  431. quad.bl.vertices.x = left;
  432. quad.bl.vertices.y = bottom;
  433. quad.bl.vertices.z = z;
  434. quad.br.vertices.x = left;
  435. quad.br.vertices.y = top;
  436. quad.br.vertices.z = z;
  437. quad.tl.vertices.x = right;
  438. quad.tl.vertices.y = bottom;
  439. quad.tl.vertices.z = z;
  440. quad.tr.vertices.x = right;
  441. quad.tr.vertices.y = top;
  442. quad.tr.vertices.z = z;
  443. }
  444. else
  445. {
  446. quad.bl.vertices.x = left;
  447. quad.bl.vertices.y = bottom;
  448. quad.bl.vertices.z = z;
  449. quad.br.vertices.x = right;
  450. quad.br.vertices.y = bottom;
  451. quad.br.vertices.z = z;
  452. quad.tl.vertices.x = left;
  453. quad.tl.vertices.y = top;
  454. quad.tl.vertices.z = z;
  455. quad.tr.vertices.x = right;
  456. quad.tr.vertices.y = top;
  457. quad.tr.vertices.z = z;
  458. }
  459. // texcoords
  460. Rect tileTexture = _tileSet->getRectForGID(tileGID);
  461. left = (tileTexture.origin.x / texSize.width);
  462. right = left + (tileTexture.size.width / texSize.width);
  463. bottom = (tileTexture.origin.y / texSize.height);
  464. top = bottom + (tileTexture.size.height / texSize.height);
  465. quad.bl.texCoords.u = left;
  466. quad.bl.texCoords.v = bottom;
  467. quad.br.texCoords.u = right;
  468. quad.br.texCoords.v = bottom;
  469. quad.tl.texCoords.u = left;
  470. quad.tl.texCoords.v = top;
  471. quad.tr.texCoords.u = right;
  472. quad.tr.texCoords.v = top;
  473. quad.bl.colors = Color4B::WHITE;
  474. quad.br.colors = Color4B::WHITE;
  475. quad.tl.colors = Color4B::WHITE;
  476. quad.tr.colors = Color4B::WHITE;
  477. ++quadIndex;
  478. }
  479. }
  480. int offset = 0;
  481. for(auto& vertexZOffset : _indicesVertexZOffsets)
  482. {
  483. std::swap(offset, vertexZOffset.second);
  484. offset += vertexZOffset.second;
  485. }
  486. updateVertexBuffer();
  487. _quadsDirty = false;
  488. }
  489. }
  490. // removing / getting tiles
  491. Sprite* TMXLayer::getTileAt(const Vec2& tileCoordinate)
  492. {
  493. CCASSERT( tileCoordinate.x < _layerSize.width && tileCoordinate.y < _layerSize.height && tileCoordinate.x >=0 && tileCoordinate.y >=0, "TMXLayer: invalid position");
  494. CCASSERT( _tiles, "TMXLayer: the tiles map has been released");
  495. Sprite *tile = nullptr;
  496. int gid = this->getTileGIDAt(tileCoordinate);
  497. // if GID == 0, then no tile is present
  498. if( gid ) {
  499. int index = (int) tileCoordinate.x + (int) tileCoordinate.y * _layerSize.width;
  500. auto it = _spriteContainer.find(index);
  501. if (it != _spriteContainer.end())
  502. {
  503. tile = it->second.first;
  504. }
  505. else
  506. {
  507. // tile not created yet. create it
  508. Rect rect = _tileSet->getRectForGID(gid);
  509. rect = CC_RECT_PIXELS_TO_POINTS(rect);
  510. tile = Sprite::createWithTexture(_texture, rect);
  511. Vec2 p = this->getPositionAt(tileCoordinate);
  512. tile->setAnchorPoint(Vec2::ZERO);
  513. tile->setPosition(p);
  514. tile->setPositionZ((float)getVertexZForPos(tileCoordinate));
  515. tile->setOpacity(this->getOpacity());
  516. tile->setTag(index);
  517. this->addChild(tile, index);
  518. _spriteContainer.insert(std::pair<int, std::pair<Sprite*, int> >(index, std::pair<Sprite*, int>(tile, gid)));
  519. // tile is converted to sprite.
  520. setFlaggedTileGIDByIndex(index, 0);
  521. }
  522. }
  523. return tile;
  524. }
  525. int TMXLayer::getTileGIDAt(const Vec2& tileCoordinate, TMXTileFlags* flags/* = nullptr*/)
  526. {
  527. CCASSERT(tileCoordinate.x < _layerSize.width && tileCoordinate.y < _layerSize.height && tileCoordinate.x >=0 && tileCoordinate.y >=0, "TMXLayer: invalid position");
  528. CCASSERT(_tiles, "TMXLayer: the tiles map has been released");
  529. int idx = static_cast<int>(((int) tileCoordinate.x + (int) tileCoordinate.y * _layerSize.width));
  530. // Bits on the far end of the 32-bit global tile ID are used for tile flags
  531. int tile = _tiles[idx];
  532. auto it = _spriteContainer.find(idx);
  533. // converted to sprite.
  534. if (tile == 0 && it != _spriteContainer.end())
  535. {
  536. tile = it->second.second;
  537. }
  538. // issue1264, flipped tiles can be changed dynamically
  539. if (flags)
  540. {
  541. *flags = (TMXTileFlags)(tile & kTMXFlipedAll);
  542. }
  543. return (tile & kTMXFlippedMask);
  544. }
  545. Vec2 TMXLayer::getPositionAt(const Vec2& pos)
  546. {
  547. return PointApplyTransform(pos, _tileToNodeTransform);
  548. }
  549. int TMXLayer::getVertexZForPos(const Vec2& pos)
  550. {
  551. int ret = 0;
  552. int maxVal = 0;
  553. if (_useAutomaticVertexZ)
  554. {
  555. switch (_layerOrientation)
  556. {
  557. case FAST_TMX_ORIENTATION_ISO:
  558. maxVal = static_cast<int>(_layerSize.width + _layerSize.height);
  559. ret = static_cast<int>(-(maxVal - (pos.x + pos.y)));
  560. break;
  561. case FAST_TMX_ORIENTATION_ORTHO:
  562. ret = static_cast<int>(-(_layerSize.height-pos.y));
  563. break;
  564. case FAST_TMX_ORIENTATION_HEX:
  565. CCASSERT(0, "TMX Hexa vertexZ not supported");
  566. break;
  567. default:
  568. CCASSERT(0, "TMX invalid value");
  569. break;
  570. }
  571. }
  572. else
  573. {
  574. ret = _vertexZvalue;
  575. }
  576. return ret;
  577. }
  578. void TMXLayer::removeTileAt(const Vec2& tileCoordinate)
  579. {
  580. CCASSERT( tileCoordinate.x < _layerSize.width && tileCoordinate.y < _layerSize.height && tileCoordinate.x >=0 && tileCoordinate.y >=0, "TMXLayer: invalid position");
  581. int gid = this->getTileGIDAt(tileCoordinate);
  582. if( gid ) {
  583. int z = (int) tileCoordinate.x + (int) tileCoordinate.y * _layerSize.width;
  584. // remove tile from GID map
  585. setFlaggedTileGIDByIndex(z, 0);
  586. // remove it from sprites
  587. auto it = _spriteContainer.find(z);
  588. if (it != _spriteContainer.end())
  589. {
  590. this->removeChild(it->second.first);
  591. }
  592. }
  593. }
  594. void TMXLayer::setFlaggedTileGIDByIndex(int index, uint32_t gid)
  595. {
  596. if(gid == _tiles[index]) return;
  597. _tiles[index] = gid;
  598. _quadsDirty = true;
  599. _dirty = true;
  600. }
  601. void TMXLayer::removeChild(Node* node, bool cleanup)
  602. {
  603. int tag = node->getTag();
  604. auto it = _spriteContainer.find(tag);
  605. if (it != _spriteContainer.end() && it->second.first == node)
  606. {
  607. _spriteContainer.erase(it);
  608. }
  609. Node::removeChild(node, cleanup);
  610. }
  611. // TMXLayer - Properties
  612. Value TMXLayer::getProperty(const std::string& propertyName) const
  613. {
  614. if (_properties.find(propertyName) != _properties.end())
  615. return _properties.at(propertyName);
  616. return Value();
  617. }
  618. void TMXLayer::parseInternalProperties()
  619. {
  620. auto vertexz = getProperty("cc_vertexz");
  621. if (vertexz.isNull()) return;
  622. std::string vertexZStr = vertexz.asString();
  623. // If "automatic" is on, then parse the "cc_alpha_func" too
  624. if (vertexZStr == "automatic")
  625. {
  626. _useAutomaticVertexZ = true;
  627. auto alphaFuncVal = getProperty("cc_alpha_func");
  628. float alphaFuncValue = alphaFuncVal.asFloat();
  629. setGLProgram(GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST));
  630. GLint alphaValueLocation = glGetUniformLocation(getGLProgram()->getProgram(), GLProgram::UNIFORM_NAME_ALPHA_TEST_VALUE);
  631. // NOTE: alpha test shader is hard-coded to use the equivalent of a glAlphaFunc(GL_GREATER) comparison
  632. // use shader program to set uniform
  633. getGLProgram()->use();
  634. getGLProgram()->setUniformLocationWith1f(alphaValueLocation, alphaFuncValue);
  635. CHECK_GL_ERROR_DEBUG();
  636. }
  637. else
  638. {
  639. _vertexZvalue = vertexz.asInt();
  640. }
  641. }
  642. //CCTMXLayer2 - obtaining positions, offset
  643. Vec2 TMXLayer::calculateLayerOffset(const Vec2& pos)
  644. {
  645. Vec2 ret;
  646. switch (_layerOrientation)
  647. {
  648. case FAST_TMX_ORIENTATION_ORTHO:
  649. ret.set( pos.x * _mapTileSize.width, -pos.y *_mapTileSize.height);
  650. break;
  651. case FAST_TMX_ORIENTATION_ISO:
  652. ret.set((_mapTileSize.width /2) * (pos.x - pos.y),
  653. (_mapTileSize.height /2 ) * (-pos.x - pos.y));
  654. break;
  655. case FAST_TMX_ORIENTATION_HEX:
  656. default:
  657. CCASSERT(pos.isZero(), "offset for this map not implemented yet");
  658. break;
  659. }
  660. return ret;
  661. }
  662. // TMXLayer - adding / remove tiles
  663. void TMXLayer::setTileGID(int gid, const Vec2& tileCoordinate)
  664. {
  665. setTileGID(gid, tileCoordinate, (TMXTileFlags)0);
  666. }
  667. void TMXLayer::setTileGID(int gid, const Vec2& tileCoordinate, TMXTileFlags flags)
  668. {
  669. CCASSERT(tileCoordinate.x < _layerSize.width && tileCoordinate.y < _layerSize.height && tileCoordinate.x >=0 && tileCoordinate.y >=0, "TMXLayer: invalid position");
  670. CCASSERT(_tiles, "TMXLayer: the tiles map has been released");
  671. CCASSERT(gid == 0 || gid >= _tileSet->_firstGid, "TMXLayer: invalid gid" );
  672. TMXTileFlags currentFlags;
  673. int currentGID = getTileGIDAt(tileCoordinate, &currentFlags);
  674. if (currentGID == gid && currentFlags == flags) return;
  675. uint32_t gidAndFlags = gid | flags;
  676. // setting gid=0 is equal to remove the tile
  677. if (gid == 0)
  678. {
  679. removeTileAt(tileCoordinate);
  680. }
  681. // empty tile. create a new one
  682. else if (currentGID == 0)
  683. {
  684. int z = (int) tileCoordinate.x + (int) tileCoordinate.y * _layerSize.width;
  685. setFlaggedTileGIDByIndex(z, gidAndFlags);
  686. }
  687. // modifying an existing tile with a non-empty tile
  688. else
  689. {
  690. int z = (int) tileCoordinate.x + (int) tileCoordinate.y * _layerSize.width;
  691. auto it = _spriteContainer.find(z);
  692. if (it != _spriteContainer.end())
  693. {
  694. Sprite *sprite = it->second.first;
  695. Rect rect = _tileSet->getRectForGID(gid);
  696. rect = CC_RECT_PIXELS_TO_POINTS(rect);
  697. sprite->setTextureRect(rect, false, rect.size);
  698. this->reorderChild(sprite, z);
  699. if (flags)
  700. {
  701. setupTileSprite(sprite, sprite->getPosition(), gidAndFlags);
  702. }
  703. it->second.second = gidAndFlags;
  704. }
  705. else
  706. {
  707. setFlaggedTileGIDByIndex(z, gidAndFlags);
  708. }
  709. }
  710. }
  711. void TMXLayer::setupTileSprite(Sprite* sprite, const Vec2& pos, uint32_t gid)
  712. {
  713. sprite->setPosition(getPositionAt(pos));
  714. sprite->setPositionZ((float)getVertexZForPos(pos));
  715. sprite->setAnchorPoint(Vec2::ZERO);
  716. sprite->setOpacity(this->getOpacity());
  717. //issue 1264, flip can be undone as well
  718. sprite->setFlippedX(false);
  719. sprite->setFlippedY(false);
  720. sprite->setRotation(0.0f);
  721. // Rotation in tiled is achieved using 3 flipped states, flipping across the horizontal, vertical, and diagonal axes of the tiles.
  722. if (gid & kTMXTileDiagonalFlag)
  723. {
  724. // put the anchor in the middle for ease of rotation.
  725. sprite->setAnchorPoint(Vec2(0.5f,0.5f));
  726. sprite->setPosition(getPositionAt(pos).x + sprite->getContentSize().height/2,
  727. getPositionAt(pos).y + sprite->getContentSize().width/2 );
  728. uint32_t flag = gid & (kTMXTileHorizontalFlag | kTMXTileVerticalFlag );
  729. // handle the 4 diagonally flipped states.
  730. if (flag == kTMXTileHorizontalFlag)
  731. {
  732. sprite->setRotation(90.0f);
  733. }
  734. else if (flag == kTMXTileVerticalFlag)
  735. {
  736. sprite->setRotation(270.0f);
  737. }
  738. else if (flag == (kTMXTileVerticalFlag | kTMXTileHorizontalFlag) )
  739. {
  740. sprite->setRotation(90.0f);
  741. sprite->setFlippedX(true);
  742. }
  743. else
  744. {
  745. sprite->setRotation(270.0f);
  746. sprite->setFlippedX(true);
  747. }
  748. }
  749. else
  750. {
  751. if (gid & kTMXTileHorizontalFlag)
  752. {
  753. sprite->setFlippedX(true);
  754. }
  755. if (gid & kTMXTileVerticalFlag)
  756. {
  757. sprite->setFlippedY(true);
  758. }
  759. }
  760. }
  761. std::string TMXLayer::getDescription() const
  762. {
  763. return StringUtils::format("<FastTMXLayer | tag = %d, size = %d,%d>", _tag, (int)_mapTileSize.width, (int)_mapTileSize.height);
  764. }
  765. } //end of namespace experimental
  766. NS_CC_END