CCTMXXMLParser.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  1. /****************************************************************************
  2. Copyright (c) 2011 Максим Аксенов
  3. Copyright (c) 2009-2010 Ricardo Quesada
  4. Copyright (c) 2010-2012 cocos2d-x.org
  5. Copyright (c) 2011 Zynga Inc.
  6. Copyright (c) 2013-2016 Chukong Technologies Inc.
  7. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  8. http://www.cocos2d-x.org
  9. Permission is hereby granted, free of charge, to any person obtaining a copy
  10. of this software and associated documentation files (the "Software"), to deal
  11. in the Software without restriction, including without limitation the rights
  12. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. copies of the Software, and to permit persons to whom the Software is
  14. furnished to do so, subject to the following conditions:
  15. The above copyright notice and this permission notice shall be included in
  16. all copies or substantial portions of the Software.
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. THE SOFTWARE.
  24. ****************************************************************************/
  25. #include "2d/CCTMXXMLParser.h"
  26. #include <unordered_map>
  27. #include <sstream>
  28. #include "2d/CCTMXTiledMap.h"
  29. #include "base/ZipUtils.h"
  30. #include "base/base64.h"
  31. #include "base/CCDirector.h"
  32. #include "platform/CCFileUtils.h"
  33. using namespace std;
  34. NS_CC_BEGIN
  35. // implementation TMXLayerInfo
  36. TMXLayerInfo::TMXLayerInfo()
  37. : _name("")
  38. , _tiles(nullptr)
  39. , _ownTiles(true)
  40. {
  41. }
  42. TMXLayerInfo::~TMXLayerInfo()
  43. {
  44. CCLOGINFO("deallocing TMXLayerInfo: %p", this);
  45. if (_ownTiles && _tiles)
  46. {
  47. free(_tiles);
  48. _tiles = nullptr;
  49. }
  50. }
  51. ValueMap& TMXLayerInfo::getProperties()
  52. {
  53. return _properties;
  54. }
  55. void TMXLayerInfo::setProperties(ValueMap var)
  56. {
  57. _properties = var;
  58. }
  59. // implementation TMXTilesetInfo
  60. TMXTilesetInfo::TMXTilesetInfo()
  61. :_firstGid(0)
  62. ,_tileSize(Size::ZERO)
  63. ,_spacing(0)
  64. ,_margin(0)
  65. ,_imageSize(Size::ZERO)
  66. {
  67. }
  68. TMXTilesetInfo::~TMXTilesetInfo()
  69. {
  70. CCLOGINFO("deallocing TMXTilesetInfo: %p", this);
  71. }
  72. Rect TMXTilesetInfo::getRectForGID(uint32_t gid)
  73. {
  74. Rect rect;
  75. rect.size = _tileSize;
  76. gid &= kTMXFlippedMask;
  77. gid = gid - _firstGid;
  78. // max_x means the column count in tile map
  79. // in the origin:
  80. // max_x = (int)((_imageSize.width - _margin*2 + _spacing) / (_tileSize.width + _spacing));
  81. // but in editor "Tiled", _margin variable only effect the left side
  82. // for compatible with "Tiled", change the max_x calculation
  83. int max_x = (int)((_imageSize.width - _margin + _spacing) / (_tileSize.width + _spacing));
  84. rect.origin.x = (gid % max_x) * (_tileSize.width + _spacing) + _margin;
  85. rect.origin.y = (gid / max_x) * (_tileSize.height + _spacing) + _margin;
  86. return rect;
  87. }
  88. // implementation TMXMapInfo
  89. TMXMapInfo * TMXMapInfo::create(const std::string& tmxFile)
  90. {
  91. TMXMapInfo *ret = new (std::nothrow) TMXMapInfo();
  92. if (ret->initWithTMXFile(tmxFile))
  93. {
  94. ret->autorelease();
  95. return ret;
  96. }
  97. CC_SAFE_DELETE(ret);
  98. return nullptr;
  99. }
  100. TMXMapInfo * TMXMapInfo::createWithXML(const std::string& tmxString, const std::string& resourcePath)
  101. {
  102. TMXMapInfo *ret = new (std::nothrow) TMXMapInfo();
  103. if (ret->initWithXML(tmxString, resourcePath))
  104. {
  105. ret->autorelease();
  106. return ret;
  107. }
  108. CC_SAFE_DELETE(ret);
  109. return nullptr;
  110. }
  111. void TMXMapInfo::internalInit(const std::string& tmxFileName, const std::string& resourcePath)
  112. {
  113. if (!tmxFileName.empty())
  114. {
  115. _TMXFileName = FileUtils::getInstance()->fullPathForFilename(tmxFileName);
  116. }
  117. if (!resourcePath.empty())
  118. {
  119. _resources = resourcePath;
  120. }
  121. _objectGroups.reserve(4);
  122. // tmp vars
  123. _currentString = "";
  124. _storingCharacters = false;
  125. _layerAttribs = TMXLayerAttribNone;
  126. _parentElement = TMXPropertyNone;
  127. _currentFirstGID = -1;
  128. }
  129. bool TMXMapInfo::initWithXML(const std::string& tmxString, const std::string& resourcePath)
  130. {
  131. internalInit("", resourcePath);
  132. return parseXMLString(tmxString);
  133. }
  134. bool TMXMapInfo::initWithTMXFile(const std::string& tmxFile)
  135. {
  136. internalInit(tmxFile, "");
  137. return parseXMLFile(_TMXFileName);
  138. }
  139. TMXMapInfo::TMXMapInfo()
  140. : _orientation(TMXOrientationOrtho)
  141. , _staggerAxis(TMXStaggerAxis_Y)
  142. , _staggerIndex(TMXStaggerIndex_Even)
  143. , _hexSideLength(0)
  144. , _parentElement(0)
  145. , _parentGID(0)
  146. , _mapSize(Size::ZERO)
  147. , _tileSize(Size::ZERO)
  148. , _layerAttribs(0)
  149. , _storingCharacters(false)
  150. , _xmlTileIndex(0)
  151. , _currentFirstGID(-1)
  152. , _recordFirstGID(true)
  153. {
  154. }
  155. TMXMapInfo::~TMXMapInfo()
  156. {
  157. CCLOGINFO("deallocing TMXMapInfo: %p", this);
  158. }
  159. bool TMXMapInfo::parseXMLString(const std::string& xmlString)
  160. {
  161. size_t len = xmlString.size();
  162. if (len <= 0)
  163. return false;
  164. SAXParser parser;
  165. if (false == parser.init("UTF-8") )
  166. {
  167. return false;
  168. }
  169. parser.setDelegator(this);
  170. return parser.parse(xmlString.c_str(), len);
  171. }
  172. bool TMXMapInfo::parseXMLFile(const std::string& xmlFilename)
  173. {
  174. SAXParser parser;
  175. if (false == parser.init("UTF-8") )
  176. {
  177. return false;
  178. }
  179. parser.setDelegator(this);
  180. return parser.parse(FileUtils::getInstance()->fullPathForFilename(xmlFilename));
  181. }
  182. // the XML parser calls here with all the elements
  183. void TMXMapInfo::startElement(void* /*ctx*/, const char *name, const char **atts)
  184. {
  185. TMXMapInfo *tmxMapInfo = this;
  186. std::string elementName = name;
  187. ValueMap attributeDict;
  188. if (atts && atts[0])
  189. {
  190. for (int i = 0; atts[i]; i += 2)
  191. {
  192. std::string key = atts[i];
  193. std::string value = atts[i+1];
  194. attributeDict.emplace(key, Value(value));
  195. }
  196. }
  197. if (elementName == "map")
  198. {
  199. std::string version = attributeDict["version"].asString();
  200. if ( version != "1.0")
  201. {
  202. CCLOG("cocos2d: TMXFormat: Unsupported TMX version: %s", version.c_str());
  203. }
  204. std::string orientationStr = attributeDict["orientation"].asString();
  205. if (orientationStr == "orthogonal") {
  206. tmxMapInfo->setOrientation(TMXOrientationOrtho);
  207. }
  208. else if (orientationStr == "isometric") {
  209. tmxMapInfo->setOrientation(TMXOrientationIso);
  210. }
  211. else if (orientationStr == "hexagonal") {
  212. tmxMapInfo->setOrientation(TMXOrientationHex);
  213. }
  214. else if (orientationStr == "staggered") {
  215. tmxMapInfo->setOrientation(TMXOrientationStaggered);
  216. }
  217. else {
  218. CCLOG("cocos2d: TMXFomat: Unsupported orientation: %d", tmxMapInfo->getOrientation());
  219. }
  220. std::string staggerAxisStr = attributeDict["staggeraxis"].asString();
  221. if (staggerAxisStr == "x") {
  222. tmxMapInfo->setStaggerAxis(TMXStaggerAxis_X);
  223. }
  224. else if (staggerAxisStr == "y") {
  225. tmxMapInfo->setStaggerAxis(TMXStaggerAxis_Y);
  226. }
  227. std::string staggerIndex = attributeDict["staggerindex"].asString();
  228. if (staggerIndex == "odd") {
  229. tmxMapInfo->setStaggerIndex(TMXStaggerIndex_Odd);
  230. }
  231. else if (staggerIndex == "even") {
  232. tmxMapInfo->setStaggerIndex(TMXStaggerIndex_Even);
  233. }
  234. float hexSideLength = attributeDict["hexsidelength"].asFloat();
  235. tmxMapInfo->setHexSideLength(hexSideLength);
  236. Size s;
  237. s.width = attributeDict["width"].asFloat();
  238. s.height = attributeDict["height"].asFloat();
  239. tmxMapInfo->setMapSize(s);
  240. s.width = attributeDict["tilewidth"].asFloat();
  241. s.height = attributeDict["tileheight"].asFloat();
  242. tmxMapInfo->setTileSize(s);
  243. // The parent element is now "map"
  244. tmxMapInfo->setParentElement(TMXPropertyMap);
  245. }
  246. else if (elementName == "tileset")
  247. {
  248. // If this is an external tileset then start parsing that
  249. std::string externalTilesetFilename = attributeDict["source"].asString();
  250. if (externalTilesetFilename != "")
  251. {
  252. _externalTilesetFilename = externalTilesetFilename;
  253. // Tileset file will be relative to the map file. So we need to convert it to an absolute path
  254. if (_TMXFileName.find_last_of("/") != string::npos)
  255. {
  256. string dir = _TMXFileName.substr(0, _TMXFileName.find_last_of("/") + 1);
  257. externalTilesetFilename = dir + externalTilesetFilename;
  258. }
  259. else
  260. {
  261. externalTilesetFilename = _resources + "/" + externalTilesetFilename;
  262. }
  263. externalTilesetFilename = FileUtils::getInstance()->fullPathForFilename(externalTilesetFilename);
  264. _currentFirstGID = attributeDict["firstgid"].asInt();
  265. if (_currentFirstGID < 0)
  266. {
  267. _currentFirstGID = 0;
  268. }
  269. _recordFirstGID = false;
  270. tmxMapInfo->parseXMLFile(externalTilesetFilename);
  271. }
  272. else
  273. {
  274. TMXTilesetInfo *tileset = new (std::nothrow) TMXTilesetInfo();
  275. tileset->_name = attributeDict["name"].asString();
  276. if (_recordFirstGID)
  277. {
  278. // unset before, so this is tmx file.
  279. tileset->_firstGid = attributeDict["firstgid"].asInt();
  280. if (tileset->_firstGid < 0)
  281. {
  282. tileset->_firstGid = 0;
  283. }
  284. }
  285. else
  286. {
  287. tileset->_firstGid = _currentFirstGID;
  288. _currentFirstGID = 0;
  289. }
  290. tileset->_spacing = attributeDict["spacing"].asInt();
  291. tileset->_margin = attributeDict["margin"].asInt();
  292. Size s;
  293. s.width = attributeDict["tilewidth"].asFloat();
  294. s.height = attributeDict["tileheight"].asFloat();
  295. tileset->_tileSize = s;
  296. tmxMapInfo->getTilesets().pushBack(tileset);
  297. tileset->release();
  298. }
  299. }
  300. else if (elementName == "tile")
  301. {
  302. if (tmxMapInfo->getParentElement() == TMXPropertyLayer)
  303. {
  304. TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
  305. Size layerSize = layer->_layerSize;
  306. uint32_t gid = static_cast<uint32_t>(attributeDict["gid"].asUnsignedInt());
  307. int tilesAmount = layerSize.width*layerSize.height;
  308. if (_xmlTileIndex < tilesAmount)
  309. {
  310. layer->_tiles[_xmlTileIndex++] = gid;
  311. }
  312. }
  313. else
  314. {
  315. TMXTilesetInfo* info = tmxMapInfo->getTilesets().back();
  316. tmxMapInfo->setParentGID(info->_firstGid + attributeDict["id"].asInt());
  317. tmxMapInfo->getTileProperties()[tmxMapInfo->getParentGID()] = Value(ValueMap());
  318. tmxMapInfo->setParentElement(TMXPropertyTile);
  319. }
  320. }
  321. else if (elementName == "layer")
  322. {
  323. TMXLayerInfo *layer = new (std::nothrow) TMXLayerInfo();
  324. layer->_name = attributeDict["name"].asString();
  325. Size s;
  326. s.width = attributeDict["width"].asFloat();
  327. s.height = attributeDict["height"].asFloat();
  328. layer->_layerSize = s;
  329. Value& visibleValue = attributeDict["visible"];
  330. layer->_visible = visibleValue.isNull() ? true : visibleValue.asBool();
  331. Value& opacityValue = attributeDict["opacity"];
  332. layer->_opacity = opacityValue.isNull() ? 255 : (unsigned char)(255.0f * opacityValue.asFloat());
  333. float x = attributeDict["x"].asFloat();
  334. float y = attributeDict["y"].asFloat();
  335. layer->_offset.set(x, y);
  336. tmxMapInfo->getLayers().pushBack(layer);
  337. layer->release();
  338. // The parent element is now "layer"
  339. tmxMapInfo->setParentElement(TMXPropertyLayer);
  340. }
  341. else if (elementName == "objectgroup")
  342. {
  343. TMXObjectGroup *objectGroup = new (std::nothrow) TMXObjectGroup();
  344. objectGroup->setGroupName(attributeDict["name"].asString());
  345. Vec2 positionOffset;
  346. positionOffset.x = attributeDict["x"].asFloat() * tmxMapInfo->getTileSize().width;
  347. positionOffset.y = attributeDict["y"].asFloat() * tmxMapInfo->getTileSize().height;
  348. objectGroup->setPositionOffset(positionOffset);
  349. tmxMapInfo->getObjectGroups().pushBack(objectGroup);
  350. objectGroup->release();
  351. // The parent element is now "objectgroup"
  352. tmxMapInfo->setParentElement(TMXPropertyObjectGroup);
  353. }
  354. else if (elementName == "tileoffset")
  355. {
  356. TMXTilesetInfo* tileset = tmxMapInfo->getTilesets().back();
  357. double tileOffsetX = attributeDict["x"].asDouble();
  358. double tileOffsetY = attributeDict["y"].asDouble();
  359. tileset->_tileOffset = Vec2(tileOffsetX, tileOffsetY);
  360. }
  361. else if (elementName == "image")
  362. {
  363. TMXTilesetInfo* tileset = tmxMapInfo->getTilesets().back();
  364. // build full path
  365. std::string imagename = attributeDict["source"].asString();
  366. tileset->_originSourceImage = imagename;
  367. if (_TMXFileName.find_last_of("/") != string::npos)
  368. {
  369. string dir = _TMXFileName.substr(0, _TMXFileName.find_last_of("/") + 1);
  370. tileset->_sourceImage = dir + imagename;
  371. }
  372. else
  373. {
  374. tileset->_sourceImage = _resources + (_resources.size() ? "/" : "") + imagename;
  375. }
  376. }
  377. else if (elementName == "data")
  378. {
  379. std::string encoding = attributeDict["encoding"].asString();
  380. std::string compression = attributeDict["compression"].asString();
  381. if (encoding == "")
  382. {
  383. tmxMapInfo->setLayerAttribs(tmxMapInfo->getLayerAttribs() | TMXLayerAttribNone);
  384. TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
  385. Size layerSize = layer->_layerSize;
  386. int tilesAmount = layerSize.width*layerSize.height;
  387. uint32_t *tiles = (uint32_t*) malloc(tilesAmount*sizeof(uint32_t));
  388. // set all value to 0
  389. memset(tiles, 0, tilesAmount*sizeof(int));
  390. layer->_tiles = tiles;
  391. }
  392. else if (encoding == "base64")
  393. {
  394. int layerAttribs = tmxMapInfo->getLayerAttribs();
  395. tmxMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribBase64);
  396. tmxMapInfo->setStoringCharacters(true);
  397. if (compression == "gzip")
  398. {
  399. layerAttribs = tmxMapInfo->getLayerAttribs();
  400. tmxMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribGzip);
  401. } else
  402. if (compression == "zlib")
  403. {
  404. layerAttribs = tmxMapInfo->getLayerAttribs();
  405. tmxMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribZlib);
  406. }
  407. CCASSERT( compression == "" || compression == "gzip" || compression == "zlib", "TMX: unsupported compression method" );
  408. }
  409. else if (encoding == "csv")
  410. {
  411. int layerAttribs = tmxMapInfo->getLayerAttribs();
  412. tmxMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribCSV);
  413. tmxMapInfo->setStoringCharacters(true);
  414. }
  415. }
  416. else if (elementName == "object")
  417. {
  418. TMXObjectGroup* objectGroup = tmxMapInfo->getObjectGroups().back();
  419. // The value for "type" was blank or not a valid class name
  420. // Create an instance of TMXObjectInfo to store the object and its properties
  421. ValueMap dict;
  422. // Parse everything automatically
  423. const char* keys[] = {"name", "type", "width", "height", "gid", "id"};
  424. for (const auto& key : keys)
  425. {
  426. Value value = attributeDict[key];
  427. dict[key] = value;
  428. }
  429. // But X and Y since they need special treatment
  430. // X
  431. int x = attributeDict["x"].asInt();
  432. // Y
  433. int y = attributeDict["y"].asInt();
  434. Vec2 p(x + objectGroup->getPositionOffset().x, _mapSize.height * _tileSize.height - y - objectGroup->getPositionOffset().y - attributeDict["height"].asInt());
  435. p = CC_POINT_PIXELS_TO_POINTS(p);
  436. dict["x"] = Value(p.x);
  437. dict["y"] = Value(p.y);
  438. int width = attributeDict["width"].asInt();
  439. int height = attributeDict["height"].asInt();
  440. Size s(width, height);
  441. s = CC_SIZE_PIXELS_TO_POINTS(s);
  442. dict["width"] = Value(s.width);
  443. dict["height"] = Value(s.height);
  444. dict["rotation"] = attributeDict["rotation"].asDouble();
  445. // Add the object to the objectGroup
  446. objectGroup->getObjects().push_back(Value(dict));
  447. // The parent element is now "object"
  448. tmxMapInfo->setParentElement(TMXPropertyObject);
  449. }
  450. else if (elementName == "property")
  451. {
  452. if ( tmxMapInfo->getParentElement() == TMXPropertyNone )
  453. {
  454. CCLOG( "TMX tile map: Parent element is unsupported. Cannot add property named '%s' with value '%s'",
  455. attributeDict["name"].asString().c_str(), attributeDict["value"].asString().c_str() );
  456. }
  457. else if ( tmxMapInfo->getParentElement() == TMXPropertyMap )
  458. {
  459. // The parent element is the map
  460. Value value = attributeDict["value"];
  461. std::string key = attributeDict["name"].asString();
  462. tmxMapInfo->getProperties().emplace(key, value);
  463. }
  464. else if ( tmxMapInfo->getParentElement() == TMXPropertyLayer )
  465. {
  466. // The parent element is the last layer
  467. TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
  468. Value value = attributeDict["value"];
  469. std::string key = attributeDict["name"].asString();
  470. // Add the property to the layer
  471. layer->getProperties().emplace(key, value);
  472. }
  473. else if ( tmxMapInfo->getParentElement() == TMXPropertyObjectGroup )
  474. {
  475. // The parent element is the last object group
  476. TMXObjectGroup* objectGroup = tmxMapInfo->getObjectGroups().back();
  477. Value value = attributeDict["value"];
  478. std::string key = attributeDict["name"].asString();
  479. objectGroup->getProperties().emplace(key, value);
  480. }
  481. else if ( tmxMapInfo->getParentElement() == TMXPropertyObject )
  482. {
  483. // The parent element is the last object
  484. TMXObjectGroup* objectGroup = tmxMapInfo->getObjectGroups().back();
  485. ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap();
  486. std::string propertyName = attributeDict["name"].asString();
  487. dict[propertyName] = attributeDict["value"];
  488. }
  489. else if ( tmxMapInfo->getParentElement() == TMXPropertyTile )
  490. {
  491. ValueMap& dict = tmxMapInfo->getTileProperties().at(tmxMapInfo->getParentGID()).asValueMap();
  492. std::string propertyName = attributeDict["name"].asString();
  493. dict[propertyName] = attributeDict["value"];
  494. }
  495. }
  496. else if (elementName == "polygon")
  497. {
  498. // find parent object's dict and add polygon-points to it
  499. TMXObjectGroup* objectGroup = _objectGroups.back();
  500. ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap();
  501. // get points value string
  502. std::string value = attributeDict["points"].asString();
  503. if (!value.empty())
  504. {
  505. ValueVector pointsArray;
  506. pointsArray.reserve(10);
  507. // parse points string into a space-separated set of points
  508. stringstream pointsStream(value);
  509. string pointPair;
  510. while (std::getline(pointsStream, pointPair, ' '))
  511. {
  512. // parse each point combo into a comma-separated x,y point
  513. stringstream pointStream(pointPair);
  514. string xStr, yStr;
  515. ValueMap pointDict;
  516. // set x
  517. if (std::getline(pointStream, xStr, ','))
  518. {
  519. int x = atoi(xStr.c_str()) + (int)objectGroup->getPositionOffset().x;
  520. pointDict["x"] = Value(x);
  521. }
  522. // set y
  523. if (std::getline(pointStream, yStr, ','))
  524. {
  525. int y = atoi(yStr.c_str()) + (int)objectGroup->getPositionOffset().y;
  526. pointDict["y"] = Value(y);
  527. }
  528. // add to points array
  529. pointsArray.push_back(Value(pointDict));
  530. }
  531. dict["points"] = Value(pointsArray);
  532. }
  533. }
  534. else if (elementName == "polyline")
  535. {
  536. // find parent object's dict and add polyline-points to it
  537. TMXObjectGroup* objectGroup = _objectGroups.back();
  538. ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap();
  539. // get points value string
  540. std::string value = attributeDict["points"].asString();
  541. if (!value.empty())
  542. {
  543. ValueVector pointsArray;
  544. pointsArray.reserve(10);
  545. // parse points string into a space-separated set of points
  546. stringstream pointsStream(value);
  547. string pointPair;
  548. while (std::getline(pointsStream, pointPair, ' '))
  549. {
  550. // parse each point combo into a comma-separated x,y point
  551. stringstream pointStream(pointPair);
  552. string xStr, yStr;
  553. ValueMap pointDict;
  554. // set x
  555. if (std::getline(pointStream, xStr, ','))
  556. {
  557. int x = atoi(xStr.c_str()) + (int)objectGroup->getPositionOffset().x;
  558. pointDict["x"] = Value(x);
  559. }
  560. // set y
  561. if (std::getline(pointStream, yStr, ','))
  562. {
  563. int y = atoi(yStr.c_str()) + (int)objectGroup->getPositionOffset().y;
  564. pointDict["y"] = Value(y);
  565. }
  566. // add to points array
  567. pointsArray.push_back(Value(pointDict));
  568. }
  569. dict["polylinePoints"] = Value(pointsArray);
  570. }
  571. }
  572. }
  573. void TMXMapInfo::endElement(void* /*ctx*/, const char *name)
  574. {
  575. TMXMapInfo *tmxMapInfo = this;
  576. std::string elementName = name;
  577. if (elementName == "data")
  578. {
  579. if (tmxMapInfo->getLayerAttribs() & TMXLayerAttribBase64)
  580. {
  581. tmxMapInfo->setStoringCharacters(false);
  582. TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
  583. std::string currentString = tmxMapInfo->getCurrentString();
  584. unsigned char *buffer;
  585. auto len = base64Decode((unsigned char*)currentString.c_str(), (unsigned int)currentString.length(), &buffer);
  586. if (!buffer)
  587. {
  588. CCLOG("cocos2d: TiledMap: decode data error");
  589. return;
  590. }
  591. if (tmxMapInfo->getLayerAttribs() & (TMXLayerAttribGzip | TMXLayerAttribZlib))
  592. {
  593. unsigned char *deflated = nullptr;
  594. Size s = layer->_layerSize;
  595. // int sizeHint = s.width * s.height * sizeof(uint32_t);
  596. ssize_t sizeHint = s.width * s.height * sizeof(unsigned int);
  597. ssize_t CC_UNUSED inflatedLen = ZipUtils::inflateMemoryWithHint(buffer, len, &deflated, sizeHint);
  598. CCASSERT(inflatedLen == sizeHint, "inflatedLen should be equal to sizeHint!");
  599. free(buffer);
  600. buffer = nullptr;
  601. if (!deflated)
  602. {
  603. CCLOG("cocos2d: TiledMap: inflate data error");
  604. return;
  605. }
  606. layer->_tiles = reinterpret_cast<uint32_t*>(deflated);
  607. }
  608. else
  609. {
  610. layer->_tiles = reinterpret_cast<uint32_t*>(buffer);
  611. }
  612. tmxMapInfo->setCurrentString("");
  613. }
  614. else if (tmxMapInfo->getLayerAttribs() & TMXLayerAttribCSV)
  615. {
  616. unsigned char *buffer;
  617. TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
  618. tmxMapInfo->setStoringCharacters(false);
  619. std::string currentString = tmxMapInfo->getCurrentString();
  620. vector<string> gidTokens;
  621. istringstream filestr(currentString);
  622. string sRow;
  623. while(getline(filestr, sRow, '\n')) {
  624. string sGID;
  625. istringstream rowstr(sRow);
  626. while (getline(rowstr, sGID, ',')) {
  627. gidTokens.push_back(sGID);
  628. }
  629. }
  630. // 32-bits per gid
  631. buffer = (unsigned char*)malloc(gidTokens.size() * 4);
  632. if (!buffer)
  633. {
  634. CCLOG("cocos2d: TiledMap: CSV buffer not allocated.");
  635. return;
  636. }
  637. uint32_t* bufferPtr = reinterpret_cast<uint32_t*>(buffer);
  638. for(auto gidToken : gidTokens) {
  639. auto tileGid = (uint32_t)strtoul(gidToken.c_str(), nullptr, 10);
  640. *bufferPtr = tileGid;
  641. bufferPtr++;
  642. }
  643. layer->_tiles = reinterpret_cast<uint32_t*>(buffer);
  644. tmxMapInfo->setCurrentString("");
  645. }
  646. else if (tmxMapInfo->getLayerAttribs() & TMXLayerAttribNone)
  647. {
  648. _xmlTileIndex = 0;
  649. }
  650. }
  651. else if (elementName == "map")
  652. {
  653. // The map element has ended
  654. tmxMapInfo->setParentElement(TMXPropertyNone);
  655. }
  656. else if (elementName == "layer")
  657. {
  658. // The layer element has ended
  659. tmxMapInfo->setParentElement(TMXPropertyNone);
  660. }
  661. else if (elementName == "objectgroup")
  662. {
  663. // The objectgroup element has ended
  664. tmxMapInfo->setParentElement(TMXPropertyNone);
  665. }
  666. else if (elementName == "object")
  667. {
  668. // The object element has ended
  669. tmxMapInfo->setParentElement(TMXPropertyNone);
  670. }
  671. else if (elementName == "tileset")
  672. {
  673. _recordFirstGID = true;
  674. }
  675. }
  676. void TMXMapInfo::textHandler(void* /*ctx*/, const char *ch, size_t len)
  677. {
  678. TMXMapInfo *tmxMapInfo = this;
  679. std::string text(ch, 0, len);
  680. if (tmxMapInfo->isStoringCharacters())
  681. {
  682. std::string currentString = tmxMapInfo->getCurrentString();
  683. currentString += text;
  684. tmxMapInfo->setCurrentString(currentString);
  685. }
  686. }
  687. NS_CC_END