TMXSceneEncoder.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. #include <string>
  2. #include <zlib.h>
  3. #include "TMXSceneEncoder.h"
  4. using namespace gameplay;
  5. using namespace tinyxml2;
  6. using std::string;
  7. #ifdef GP_4_SPACE_TABS
  8. #define TAB_STRING(count) string((count) * 4, ' ')
  9. #else
  10. #define TAB_STRING(count) string((count), '\t')
  11. #endif
  12. #define BUFFER_SIZE 256
  13. #ifdef WIN32
  14. #define snprintf(s, n, fmt, ...) sprintf((s), (fmt), __VA_ARGS__)
  15. #endif
  16. TMXSceneEncoder::TMXSceneEncoder() :
  17. _tabCount(0)
  18. {
  19. }
  20. TMXSceneEncoder::~TMXSceneEncoder()
  21. {
  22. }
  23. void TMXSceneEncoder::write(const EncoderArguments& arguments)
  24. {
  25. XMLDocument xmlDoc;
  26. XMLError err;
  27. if ((err = xmlDoc.LoadFile(arguments.getFilePath().c_str())) != XML_NO_ERROR)
  28. {
  29. LOG(1, "Call to XMLDocument::LoadFile() failed.\n");
  30. LOG(1, "Error returned: %d\n\n", err);
  31. return;
  32. }
  33. // Parse the Tiled map
  34. TMXMap map;
  35. string inputDirectory = arguments.getFileDirPath();
  36. LOG(2, "Parsing .tmx file.\n");
  37. if (!parseTmx(xmlDoc, map, inputDirectory))
  38. {
  39. return;
  40. }
  41. // Apply a gutter, or skirt, around the tiles to prevent gaps
  42. if (arguments.generateTextureGutter())
  43. {
  44. LOG(2, "Bulding gutter tilesets.\n");
  45. buildTileGutter(map, inputDirectory, arguments.getOutputDirPath());
  46. }
  47. // Write the tile map
  48. string fileName = arguments.getFileName();
  49. int pos = fileName.find_last_of('.');
  50. LOG(2, "Writing .scene file.\n");
  51. writeScene(map, arguments.getOutputFilePath(), (pos == -1 ? fileName : fileName.substr(0, pos)));
  52. }
  53. bool TMXSceneEncoder::parseTmx(const XMLDocument& xmlDoc, TMXMap& map, const string& inputDirectory) const
  54. {
  55. const XMLElement* xmlMap = xmlDoc.FirstChildElement("map");
  56. if (!xmlMap)
  57. {
  58. LOG(1, "Missing root <map> element.\n");
  59. return false;
  60. }
  61. // Read in the map values //XXX should compact this so XML attribute parsing is a little nicer
  62. unsigned int uiValue;
  63. int iValue;
  64. const char* attValue = xmlMap->Attribute("width");
  65. sscanf(attValue, "%u", &uiValue);
  66. map.setWidth(uiValue);
  67. attValue = xmlMap->Attribute("height");
  68. sscanf(attValue, "%u", &uiValue);
  69. map.setHeight(uiValue);
  70. float fValue;
  71. attValue = xmlMap->Attribute("tilewidth");
  72. sscanf(attValue, "%f", &fValue);
  73. map.setTileWidth(fValue);
  74. attValue = xmlMap->Attribute("tileheight");
  75. sscanf(attValue, "%f", &fValue);
  76. map.setTileHeight(fValue);
  77. // Now we load all tilesets
  78. const XMLElement* xmlTileSet = xmlMap->FirstChildElement("tileset");
  79. while (xmlTileSet)
  80. {
  81. TMXTileSet tileSet;
  82. attValue = xmlTileSet->Attribute("firstgid");
  83. sscanf(attValue, "%u", &uiValue);
  84. tileSet.setFirstGid(uiValue);
  85. XMLDocument sourceXmlDoc;
  86. const XMLElement* xmlTileSetToLoad;
  87. attValue = xmlTileSet->Attribute("source");
  88. if (attValue)
  89. {
  90. XMLError err;
  91. string tsxLocation = buildFilePath(inputDirectory, attValue);
  92. if ((err = sourceXmlDoc.LoadFile(tsxLocation.c_str())) != XML_NO_ERROR)
  93. {
  94. LOG(1, "Could not load tileset's source TSX.\n");
  95. return false;
  96. }
  97. xmlTileSetToLoad = sourceXmlDoc.RootElement();
  98. }
  99. else
  100. {
  101. xmlTileSetToLoad = xmlTileSet;
  102. }
  103. // Maximum tile size
  104. attValue = xmlTileSetToLoad->Attribute("tilewidth");
  105. if (attValue)
  106. {
  107. sscanf(attValue, "%u", &uiValue);
  108. tileSet.setMaxTileWidth(uiValue);
  109. }
  110. else
  111. {
  112. tileSet.setMaxTileWidth(map.getTileWidth());
  113. }
  114. attValue = xmlTileSetToLoad->Attribute("tileheight");
  115. if (attValue)
  116. {
  117. sscanf(attValue, "%u", &uiValue);
  118. tileSet.setMaxTileHeight(uiValue);
  119. }
  120. else
  121. {
  122. tileSet.setMaxTileHeight(map.getTileHeight());
  123. }
  124. // Spacing and margin
  125. attValue = xmlTileSetToLoad->Attribute("spacing");
  126. if (attValue)
  127. {
  128. sscanf(attValue, "%u", &uiValue);
  129. tileSet.setSpacing(uiValue);
  130. }
  131. attValue = xmlTileSetToLoad->Attribute("margin");
  132. if (attValue)
  133. {
  134. sscanf(attValue, "%u", &uiValue);
  135. tileSet.setMargin(uiValue);
  136. }
  137. // Tile offset
  138. const XMLElement* xmlTileOffset = xmlTileSetToLoad->FirstChildElement("tileoffset");
  139. if (xmlTileOffset)
  140. {
  141. Vector2 offset;
  142. attValue = xmlTileOffset->Attribute("x");
  143. sscanf(attValue, "%d", &iValue);
  144. offset.x = iValue;
  145. attValue = xmlTileOffset->Attribute("y");
  146. sscanf(attValue, "%d", &iValue);
  147. offset.y = iValue;
  148. tileSet.setOffset(offset);
  149. }
  150. // Load image source. Don't worry about <data> or trans
  151. const XMLElement* xmlTileSetImage = xmlTileSetToLoad->FirstChildElement("image");
  152. if (!xmlTileSetImage)
  153. {
  154. LOG(1, "Could not find <image> element for tileset.\n");
  155. return false;
  156. }
  157. tileSet.setImagePath(xmlTileSetImage->Attribute("source"));
  158. if (xmlTileSetImage->Attribute("width") && xmlTileSetImage->Attribute("height"))
  159. {
  160. attValue = xmlTileSetImage->Attribute("width");
  161. sscanf(attValue, "%u", &uiValue);
  162. tileSet.setImageWidth(uiValue);
  163. attValue = xmlTileSetImage->Attribute("height");
  164. sscanf(attValue, "%u", &uiValue);
  165. tileSet.setImageHeight(uiValue);
  166. }
  167. else
  168. {
  169. // Load the image itself to get the width
  170. string imageLocation = buildFilePath(inputDirectory, tileSet.getImagePath());
  171. int pos = imageLocation.find_last_of('.');
  172. if (imageLocation.substr(pos).compare(".png") != 0)
  173. {
  174. LOG(1, "TileSet image must be a PNG. %s\n", imageLocation.c_str());
  175. return false;
  176. }
  177. Image* img = Image::create(imageLocation.c_str());
  178. if (!img)
  179. {
  180. LOG(1, "Could not load TileSet image. %s\n", imageLocation.c_str());
  181. return false;
  182. }
  183. tileSet.setImageWidth(img->getWidth());
  184. tileSet.setImageHeight(img->getHeight());
  185. SAFE_DELETE(img);
  186. }
  187. //TODO: tiles (specifically, tile animations) if possible. May require marking tiles as special tiles, and spinning them off to Sprites
  188. //<tile id="relId"><animation><frame tileid="relId" duration="numInMS"></...></...></...>
  189. // Save the tileset
  190. map.addTileSet(tileSet);
  191. xmlTileSet = xmlTileSet->NextSiblingElement("tileset");
  192. }
  193. // Load the layers
  194. const XMLElement* xmlLayer = xmlMap->FirstChildElement("layer");
  195. while (xmlLayer)
  196. {
  197. TMXLayer* layer = new TMXLayer();
  198. parseBaseLayerProperties(xmlLayer, layer);
  199. // Load properties
  200. attValue = xmlLayer->Attribute("width");
  201. if (attValue)
  202. {
  203. sscanf(attValue, "%u", &uiValue);
  204. layer->setWidth(uiValue);
  205. }
  206. else
  207. {
  208. layer->setWidth(map.getWidth());
  209. }
  210. attValue = xmlLayer->Attribute("height");
  211. if (attValue)
  212. {
  213. sscanf(attValue, "%u", &uiValue);
  214. layer->setHeight(uiValue);
  215. }
  216. else
  217. {
  218. layer->setHeight(map.getHeight());
  219. }
  220. // Load tiles
  221. layer->setupTiles();
  222. auto data = loadDataElement(xmlLayer->FirstChildElement("data"));
  223. size_t dataSize = data.size();
  224. for (int i = 0; i < dataSize; i++)
  225. {
  226. //XXX this might depend on map's renderorder... not sure
  227. unsigned int x = i % layer->getWidth();
  228. unsigned int y = i / layer->getWidth();
  229. layer->setTile(x, y, data[i]);
  230. }
  231. // Save layer
  232. map.addLayer(layer);
  233. xmlLayer = xmlLayer->NextSiblingElement("layer");
  234. }
  235. // Load image layers
  236. const XMLElement* xmlImgLayer = xmlMap->FirstChildElement("imagelayer");
  237. while (xmlImgLayer)
  238. {
  239. TMXImageLayer* imgLayer = new TMXImageLayer();
  240. parseBaseLayerProperties(xmlImgLayer, imgLayer);
  241. // Load properties
  242. attValue = xmlImgLayer->Attribute("x");
  243. if (attValue)
  244. {
  245. sscanf(attValue, "%d", &iValue);
  246. imgLayer->setX(iValue);
  247. }
  248. attValue = xmlImgLayer->Attribute("y");
  249. if (attValue)
  250. {
  251. sscanf(attValue, "%d", &iValue);
  252. imgLayer->setY(iValue);
  253. }
  254. // Load image source. Don't worry about <data>, trans, width, or height
  255. const XMLElement* xmlImage = xmlImgLayer->FirstChildElement("image");
  256. if (!xmlImage)
  257. {
  258. LOG(1, "Could not find <image> element for the image layer.\n");
  259. return false;
  260. }
  261. imgLayer->setImagePath(xmlImage->Attribute("source"));
  262. // Save image layer
  263. map.addLayer(imgLayer);
  264. xmlImgLayer = xmlImgLayer->NextSiblingElement("imagelayer");
  265. }
  266. return true;
  267. }
  268. void TMXSceneEncoder::parseBaseLayerProperties(const tinyxml2::XMLElement* xmlBaseLayer, gameplay::TMXBaseLayer* layer) const
  269. {
  270. layer->setName(xmlBaseLayer->Attribute("name"));
  271. float fValue;
  272. unsigned int uiValue;
  273. const char* attValue = xmlBaseLayer->Attribute("opacity");
  274. if (attValue)
  275. {
  276. sscanf(attValue, "%f", &fValue);
  277. layer->setOpacity(fValue);
  278. }
  279. attValue = xmlBaseLayer->Attribute("visible");
  280. if (attValue)
  281. {
  282. sscanf(attValue, "%u", &uiValue);
  283. layer->setVisible(uiValue == 1);
  284. }
  285. const XMLElement* xmlProperties = xmlBaseLayer->FirstChildElement("properties");
  286. if (xmlProperties)
  287. {
  288. TMXProperties& properties = layer->getProperties();
  289. const XMLElement* xmlProperty = xmlProperties->FirstChildElement("property");
  290. while (xmlProperty)
  291. {
  292. properties[xmlProperty->Attribute("name")] = xmlProperty->Attribute("value");
  293. xmlProperty = xmlProperty->NextSiblingElement("property");
  294. }
  295. }
  296. }
  297. void TMXSceneEncoder::buildTileGutter(TMXMap& map, const string& inputDirectory, const string& outputDirectory)
  298. {
  299. #define ACTUAL_ADJUST_TILESET(imgPath, spacing, margin) tileset.setImagePath((imgPath)); \
  300. tileset.setSpacing(tileset.getSpacing() + (spacing), false); \
  301. tileset.setMargin(tileset.getMargin() + (margin), false); \
  302. tileset.setImageWidth(TMXTileSet::calculateImageDimension(tileset.getHorizontalTileCount(), tileset.getMaxTileWidth(), tileset.getSpacing(), tileset.getMargin())); \
  303. tileset.setImageHeight(TMXTileSet::calculateImageDimension(tileset.getVerticalTileCount(), tileset.getMaxTileHeight(), tileset.getSpacing(), tileset.getMargin()))
  304. #define ADJUST_TILESET(imgPath) ACTUAL_ADJUST_TILESET(imgPath, 2, 1)
  305. #define UNDO_ADJUST_TILESET(imgPath) ACTUAL_ADJUST_TILESET(imgPath, -2, -1)
  306. std::unordered_map<std::string, std::string> processedFiles;
  307. std::unordered_map<std::string, std::string> reverseLookupProcessedFiles;
  308. unsigned int tilesetCount = map.getTileSetCount();
  309. for (unsigned int i = 0; i < tilesetCount; i++)
  310. {
  311. TMXTileSet& tileset = map.getTileSet(i);
  312. // See if the tileset was already processed. Then we can skip it
  313. auto potentialEasyProcess = processedFiles.find(tileset.getImagePath());
  314. if (potentialEasyProcess != processedFiles.end())
  315. {
  316. ADJUST_TILESET(potentialEasyProcess->second);
  317. continue;
  318. }
  319. // Process tileset
  320. string orgImgPath = tileset.getImagePath();
  321. string imgPath = orgImgPath;
  322. string inputFile = buildFilePath(inputDirectory, imgPath);
  323. int pos = imgPath.find_last_of('.');
  324. if (pos == -1)
  325. {
  326. imgPath = imgPath + "_guttered";
  327. }
  328. else
  329. {
  330. imgPath = imgPath.substr(0, pos) + "_guttered" + imgPath.substr(pos);
  331. }
  332. string outputFile = buildFilePath(outputDirectory, imgPath);
  333. if (buildTileGutterTileset(tileset, inputFile, outputFile))
  334. {
  335. // Update tileset
  336. ADJUST_TILESET(imgPath);
  337. // Remember image paths
  338. processedFiles[orgImgPath] = imgPath;
  339. reverseLookupProcessedFiles[imgPath] = orgImgPath;
  340. }
  341. else
  342. {
  343. // Revert all processed tilemaps
  344. for (unsigned int k = 0; k < i; k++)
  345. {
  346. tileset = map.getTileSet(k);
  347. // Revert to original image and settings
  348. orgImgPath = reverseLookupProcessedFiles[tileset.getImagePath()];
  349. UNDO_ADJUST_TILESET(orgImgPath);
  350. // Delete the processed image, if they exist
  351. auto it = processedFiles.find(orgImgPath);
  352. if (it != processedFiles.end())
  353. {
  354. outputFile = buildFilePath(outputDirectory, it->second);
  355. if (remove(outputFile.c_str()) != 0)
  356. {
  357. LOG(3, "Could not remove '%s' during tileset revert.\n", outputFile.c_str());
  358. }
  359. processedFiles.erase(it);
  360. }
  361. }
  362. LOG(1, "Failed to process '%s'. Reverting all tileset gutters.\n", orgImgPath.c_str());
  363. return;
  364. }
  365. }
  366. #undef UNDO_ADJUST_TILESET
  367. #undef ADJUST_TILESET
  368. #undef ACTUAL_ADJUST_TILESET
  369. }
  370. bool TMXSceneEncoder::buildTileGutterTileset(const TMXTileSet& tileset, const string& inputFile, const string& outputFile)
  371. {
  372. #define COPY_CONTENTS(sx, sy, dx, dy, w, h) copyImage(outputData, static_cast<unsigned char*>(inputImage->getData()), \
  373. inputImageWidth, outputImageWidth, bpp, \
  374. (sx), (sy), (dx), (dy), (w), (h))
  375. // Setup images
  376. const Image* inputImage = Image::create(inputFile.c_str());
  377. if (!inputImage)
  378. {
  379. return false;
  380. }
  381. unsigned int tilesetWidth = tileset.getHorizontalTileCount();
  382. unsigned int tilesetHeight = tileset.getVerticalTileCount();
  383. Vector2 tileSize = Vector2(tileset.getMaxTileWidth(), tileset.getMaxTileHeight());
  384. unsigned int bpp = 0;
  385. switch (inputImage->getFormat())
  386. {
  387. case Image::LUMINANCE:
  388. bpp = 1;
  389. break;
  390. case Image::RGB:
  391. bpp = 3;
  392. break;
  393. case Image::RGBA:
  394. bpp = 4;
  395. break;
  396. default:
  397. LOG(4, "Unknown image format. Possibly need update by developer.\n")
  398. return false;
  399. }
  400. Image* outputImage = Image::create(inputImage->getFormat(),
  401. TMXTileSet::calculateImageDimension(tilesetWidth, tileSize.x, tileset.getSpacing() + 2, tileset.getMargin() + 1),
  402. TMXTileSet::calculateImageDimension(tilesetHeight, tileSize.y, tileset.getSpacing() + 2, tileset.getMargin() + 1));
  403. // Get a couple variables so we don't constantly call functions (they aren't inline)
  404. unsigned int inputImageWidth = inputImage->getWidth();
  405. unsigned int inputImageHeight = inputImage->getHeight();
  406. unsigned int outputImageWidth = outputImage->getWidth();
  407. unsigned int outputImageHeight = outputImage->getHeight();
  408. unsigned char* outputData = static_cast<unsigned char*>(outputImage->getData());
  409. unsigned int tilesetSpacing = tileset.getSpacing();
  410. unsigned int tilesetMargin = tileset.getMargin();
  411. // Copy margin
  412. if (tilesetMargin != 0)
  413. {
  414. // Horizontal
  415. unsigned int avaliable = inputImageWidth;
  416. unsigned int remaining = outputImageWidth;
  417. unsigned int use = min(avaliable, remaining);
  418. while (remaining > 0)
  419. {
  420. // Top
  421. COPY_CONTENTS(0, 0, outputImageWidth - remaining, 0, use, tilesetMargin);
  422. // Bottom
  423. COPY_CONTENTS(0, inputImageHeight - tilesetMargin - 1, outputImageWidth - remaining, outputImageHeight - tilesetMargin - 1, use, tilesetMargin);
  424. remaining -= use;
  425. use = min(avaliable, remaining);
  426. }
  427. // Vertical
  428. avaliable = inputImageHeight;
  429. remaining = outputImageHeight;
  430. use = min(avaliable, remaining);
  431. while (remaining > 0)
  432. {
  433. // Left
  434. COPY_CONTENTS(0, 0, 0, outputImageHeight - remaining, tilesetMargin, use);
  435. // Right
  436. COPY_CONTENTS(inputImageWidth - tilesetMargin - 1, 0, inputImageWidth - tilesetMargin - 1, outputImageHeight - remaining, tilesetMargin, use);
  437. remaining -= use;
  438. use = min(avaliable, remaining);
  439. }
  440. }
  441. // Copy the contents of each tile
  442. for (unsigned int y = 0; y < tilesetHeight; y++)
  443. {
  444. for (unsigned int x = 0; x < tilesetWidth; x++)
  445. {
  446. Vector2 src = TMXTileSet::calculateTileOrigin(Vector2(x, y), tileSize, tilesetSpacing, tilesetMargin);
  447. Vector2 dst = TMXTileSet::calculateTileOrigin(Vector2(x, y), tileSize, tilesetSpacing + 2, tilesetMargin + 1);
  448. COPY_CONTENTS(src.x, src.y, dst.x, dst.y, tileSize.x, tileSize.y);
  449. }
  450. }
  451. // Extend the edges of the tiles to produce the "gutter"
  452. unsigned int gutterContents = outputImageHeight - ((tilesetMargin + 1) * 2);
  453. for (unsigned int x = 0; x < tilesetWidth; x++)
  454. {
  455. Vector2 pos = TMXTileSet::calculateTileOrigin(Vector2(x, 0), tileSize, tilesetSpacing + 2, tilesetMargin + 1);
  456. // Left
  457. copyImage(outputData, outputData,
  458. outputImageWidth, outputImageWidth, bpp,
  459. pos.x, pos.y, pos.x - 1, pos.y, 1, gutterContents);
  460. // Right
  461. copyImage(outputData, outputData,
  462. outputImageWidth, outputImageWidth, bpp,
  463. pos.x + tileSize.x - 1, pos.y, pos.x + tileSize.x, pos.y, 1, gutterContents);
  464. }
  465. gutterContents = outputImageWidth - ((tilesetMargin + 1) * 2);
  466. for (unsigned int y = 0; y < tilesetHeight; y++)
  467. {
  468. Vector2 pos = TMXTileSet::calculateTileOrigin(Vector2(0, y), tileSize, tilesetSpacing + 2, tilesetMargin + 1);
  469. // Top
  470. copyImage(outputData, outputData,
  471. outputImageWidth, outputImageWidth, bpp,
  472. pos.x, pos.y, pos.x, pos.y - 1, gutterContents, 1);
  473. // Bottom
  474. copyImage(outputData, outputData,
  475. outputImageWidth, outputImageWidth, bpp,
  476. pos.x, pos.y + tileSize.y - 1, pos.x, pos.y + tileSize.y, gutterContents, 1);
  477. }
  478. // Save and cleanup
  479. outputImage->save(outputFile.c_str());
  480. SAFE_DELETE(inputImage);
  481. SAFE_DELETE(outputImage);
  482. return true;
  483. #undef COPY_CONTENTS
  484. }
  485. //XXX could probably seperate the writing process to a seperate class (PropertyWriter...)
  486. #define WRITE_PROPERTY_BLOCK_START(str) writeLine(file, (str)); \
  487. writeLine(file, "{"); \
  488. _tabCount++
  489. #define WRITE_PROPERTY_BLOCK_END() _tabCount--; \
  490. writeLine(file, "}")
  491. #define WRITE_PROPERTY_BLOCK_VALUE(name, value) writeLine(file, string(name) + " = " + (value))
  492. #define WRITE_PROPERTY_DIRECT(value) writeLine(file, (value))
  493. #define WRITE_PROPERTY_NEWLINE() file << std::endl
  494. void TMXSceneEncoder::writeScene(const TMXMap& map, const string& outputFilepath, const string& sceneName)
  495. {
  496. // Prepare for writing the scene
  497. std::ofstream file(outputFilepath.c_str(), std::ofstream::out | std::ofstream::trunc);
  498. unsigned int layerCount = map.getLayerCount();
  499. // Write initial scene
  500. WRITE_PROPERTY_BLOCK_START("scene " + sceneName);
  501. // Write all layers
  502. for (unsigned int i = 0; i < layerCount; i++)
  503. {
  504. const TMXBaseLayer* layer = map.getLayer(i);
  505. TMXLayerType type = layer->getType();
  506. if (type == TMXLayerType::NormalLayer)
  507. {
  508. writeTileset(map, dynamic_cast<const TMXLayer*>(layer), file);
  509. WRITE_PROPERTY_NEWLINE();
  510. }
  511. else if (type == TMXLayerType::ImageLayer)
  512. {
  513. writeSprite(dynamic_cast<const TMXImageLayer*>(layer), file);
  514. WRITE_PROPERTY_NEWLINE();
  515. }
  516. }
  517. WRITE_PROPERTY_BLOCK_END();
  518. // Cleanup
  519. file.flush();
  520. file.close();
  521. }
  522. // This is actually a misnomer. What is a Layer in Tiled/TMX is a TileSet for GamePlay3d. TileSet in Tiled/TMX is something different.
  523. void TMXSceneEncoder::writeTileset(const TMXMap& map, const TMXLayer* tileset, std::ofstream& file)
  524. {
  525. if (!tileset || !tileset->hasTiles())
  526. {
  527. return;
  528. }
  529. std::set<unsigned int> tilesets = tileset->getTilesetsUsed(map);
  530. if (tilesets.size() == 0)
  531. {
  532. return;
  533. }
  534. char buffer[BUFFER_SIZE];
  535. WRITE_PROPERTY_BLOCK_START("node " + tileset->getName());
  536. if (tilesets.size() > 1)
  537. {
  538. unsigned int i = 0;
  539. for (auto it = tilesets.begin(); it != tilesets.end(); it++, i++)
  540. {
  541. snprintf(buffer, BUFFER_SIZE, "node tileset_%d", i);
  542. WRITE_PROPERTY_BLOCK_START(buffer);
  543. const TMXTileSet& tmxTileset = map.getTileSet(*it);
  544. writeSoloTileset(map, tmxTileset, *tileset, file, *it);
  545. const Vector2& tileOffset = tmxTileset.getOffset();
  546. if (!(tileOffset == Vector2::zero()))
  547. {
  548. // Tile offset moves the tiles, not the origin of each tile
  549. snprintf(buffer, BUFFER_SIZE, "translate = %d, %d, 0", static_cast<int>(tileOffset.x), static_cast<int>(tileOffset.y));
  550. WRITE_PROPERTY_NEWLINE();
  551. WRITE_PROPERTY_DIRECT(buffer);
  552. }
  553. WRITE_PROPERTY_BLOCK_END();
  554. if ((i + 1) != tilesets.size())
  555. {
  556. WRITE_PROPERTY_NEWLINE();
  557. }
  558. }
  559. }
  560. else
  561. {
  562. const TMXTileSet& tmxTileset = map.getTileSet(*(tilesets.begin()));
  563. writeSoloTileset(map, tmxTileset, *tileset, file);
  564. const Vector2& tileOffset = tmxTileset.getOffset();
  565. if (!(tileOffset == Vector2::zero()))
  566. {
  567. // Tile offset moves the tiles, not the origin of each tile
  568. snprintf(buffer, BUFFER_SIZE, "translate = %d, %d, 0", static_cast<int>(tileOffset.x), static_cast<int>(tileOffset.y));
  569. WRITE_PROPERTY_NEWLINE();
  570. WRITE_PROPERTY_DIRECT(buffer);
  571. }
  572. }
  573. writeNodeProperties(tileset->getVisible(), tileset->getProperties(), file);
  574. WRITE_PROPERTY_BLOCK_END();
  575. }
  576. void TMXSceneEncoder::writeSoloTileset(const TMXMap& map, const gameplay::TMXTileSet& tmxTileset, const TMXLayer& tileset, std::ofstream& file, unsigned int resultOnlyForTileset)
  577. {
  578. WRITE_PROPERTY_BLOCK_START("tileset");
  579. // Write tile path
  580. WRITE_PROPERTY_BLOCK_VALUE("path", tmxTileset.getImagePath());
  581. WRITE_PROPERTY_NEWLINE();
  582. // Write tile size
  583. //XXX if tile sizes are incorrect, make sure to update TMXLayer::getTileStart too
  584. char buffer[BUFFER_SIZE];
  585. snprintf(buffer, BUFFER_SIZE, "tileWidth = %u", tmxTileset.getMaxTileWidth());
  586. WRITE_PROPERTY_DIRECT(buffer);
  587. snprintf(buffer, BUFFER_SIZE, "tileHeight = %u", tmxTileset.getMaxTileHeight());
  588. WRITE_PROPERTY_DIRECT(buffer);
  589. // Write tileset size
  590. snprintf(buffer, BUFFER_SIZE, "columns = %u", tileset.getWidth());
  591. WRITE_PROPERTY_DIRECT(buffer);
  592. snprintf(buffer, BUFFER_SIZE, "rows = %u", tileset.getHeight());
  593. WRITE_PROPERTY_DIRECT(buffer);
  594. WRITE_PROPERTY_NEWLINE();
  595. // Write opacity
  596. if (tileset.getOpacity() < 1.0f)
  597. {
  598. snprintf(buffer, BUFFER_SIZE, "opacity = %f", tileset.getOpacity());
  599. WRITE_PROPERTY_DIRECT(buffer);
  600. WRITE_PROPERTY_NEWLINE();
  601. }
  602. // Write tiles
  603. unsigned int tilesetHeight = tileset.getHeight();
  604. unsigned int tilesetWidth = tileset.getWidth();
  605. for (unsigned int y = 0; y < tilesetHeight; y++)
  606. {
  607. bool tilesWritten = false;
  608. for (unsigned int x = 0; x < tilesetWidth; x++)
  609. {
  610. Vector2 startPos = tileset.getTileStart(x, y, map, resultOnlyForTileset);
  611. if (startPos.x < 0 || startPos.y < 0)
  612. {
  613. continue;
  614. }
  615. tilesWritten = true;
  616. WRITE_PROPERTY_BLOCK_START("tile");
  617. snprintf(buffer, BUFFER_SIZE, "cell = %u, %u", x, y);
  618. WRITE_PROPERTY_DIRECT(buffer);
  619. snprintf(buffer, BUFFER_SIZE, "source = %u, %u", static_cast<unsigned int>(startPos.x), static_cast<unsigned int>(startPos.y));
  620. WRITE_PROPERTY_DIRECT(buffer);
  621. WRITE_PROPERTY_BLOCK_END();
  622. }
  623. if (tilesWritten && ((y + 1) != tilesetHeight))
  624. {
  625. WRITE_PROPERTY_NEWLINE();
  626. }
  627. }
  628. WRITE_PROPERTY_BLOCK_END();
  629. }
  630. void TMXSceneEncoder::writeSprite(const gameplay::TMXImageLayer* imageLayer, std::ofstream& file)
  631. {
  632. if (!imageLayer)
  633. {
  634. return;
  635. }
  636. WRITE_PROPERTY_BLOCK_START("node " + imageLayer->getName());
  637. // Sprite
  638. {
  639. WRITE_PROPERTY_BLOCK_START("sprite");
  640. WRITE_PROPERTY_BLOCK_VALUE("path", imageLayer->getImagePath());
  641. WRITE_PROPERTY_NEWLINE();
  642. WRITE_PROPERTY_BLOCK_END();
  643. }
  644. writeNodeProperties(imageLayer->getVisible(), imageLayer->getPosition(), imageLayer->getProperties(), file);
  645. WRITE_PROPERTY_BLOCK_END();
  646. }
  647. void TMXSceneEncoder::writeNodeProperties(bool enabled, const Vector2& pos, const TMXProperties& properties, std::ofstream& file, bool seperatorLineWritten)
  648. {
  649. char buffer[BUFFER_SIZE];
  650. if (!enabled)
  651. {
  652. // Default is true, so only write it false
  653. WRITE_PROPERTY_NEWLINE();
  654. seperatorLineWritten = true;
  655. WRITE_PROPERTY_DIRECT("enabled = false");
  656. }
  657. if (!(pos == Vector2::zero()))
  658. {
  659. if (!seperatorLineWritten)
  660. {
  661. WRITE_PROPERTY_NEWLINE();
  662. seperatorLineWritten = true;
  663. }
  664. snprintf(buffer, BUFFER_SIZE, "translate = %d, %d, 0", static_cast<int>(pos.x), static_cast<int>(pos.y));
  665. WRITE_PROPERTY_DIRECT(buffer);
  666. }
  667. if (properties.size() > 0)
  668. {
  669. WRITE_PROPERTY_NEWLINE();
  670. WRITE_PROPERTY_BLOCK_START("tags");
  671. for (auto it = properties.begin(); it != properties.end(); it++)
  672. {
  673. WRITE_PROPERTY_BLOCK_VALUE(it->first, it->second);
  674. }
  675. WRITE_PROPERTY_BLOCK_END();
  676. }
  677. }
  678. #undef WRITE_PROPERTY_NEWLINE
  679. #undef WRITE_PROPERTY_DIRECT
  680. #undef WRITE_PROPERTY_BLOCK_VALUE
  681. #undef WRITE_PROPERTY_BLOCK_END
  682. #undef WRITE_PROPERTY_BLOCK_START
  683. void TMXSceneEncoder::writeLine(std::ofstream& file, const string& line) const
  684. {
  685. file << TAB_STRING(_tabCount) << line << std::endl;
  686. }
  687. bool isBase64(char c)
  688. {
  689. return (c >= 'a' && c <= 'z') ||
  690. (c >= 'A' && c <= 'Z') ||
  691. (c >= '0' && c <= '9') ||
  692. (c == '=');
  693. }
  694. std::vector<unsigned int> TMXSceneEncoder::loadDataElement(const XMLElement* data)
  695. {
  696. if (!data)
  697. {
  698. return std::vector<unsigned int>();
  699. }
  700. const char* encoding = data->Attribute("encoding");
  701. const char* compression = data->Attribute("compression");
  702. const char* attValue = "0";
  703. unsigned int tileGid;
  704. std::vector<unsigned int> tileData;
  705. if (!compression && !encoding)
  706. {
  707. const XMLElement* xmlTile = data->FirstChildElement("tile");
  708. while (xmlTile)
  709. {
  710. attValue = xmlTile->Attribute("gid");
  711. sscanf(attValue, "%u", &tileGid);
  712. tileData.push_back(tileGid);
  713. xmlTile = xmlTile->NextSiblingElement("tile");
  714. }
  715. }
  716. else
  717. {
  718. if (strcmp(encoding, "csv") == 0)
  719. {
  720. if (compression)
  721. {
  722. LOG(1, "Compression is not supported with CSV encoding.\n");
  723. exit(-1);
  724. }
  725. const char* rawCsvData = data->GetText();
  726. int start = 0;
  727. char* endptr;
  728. // Skip everything before values
  729. while (rawCsvData[start] == ' ' || rawCsvData[start] == '\n' || rawCsvData[start] == '\r' || rawCsvData[start] == '\t')
  730. {
  731. start++;
  732. }
  733. // Iterate through values. Skipping to next value when done
  734. while (rawCsvData[start])
  735. {
  736. tileData.push_back(strtoul(rawCsvData + start, &endptr, 10));
  737. start = endptr - rawCsvData;
  738. while (rawCsvData[start] == ' ' || rawCsvData[start] == ',' || rawCsvData[start] == '\n' || rawCsvData[start] == '\r' || rawCsvData[start] == '\t')
  739. {
  740. start++;
  741. }
  742. }
  743. }
  744. else if (strcmp(encoding, "base64") == 0)
  745. {
  746. string base64Data = data->GetText();
  747. if (base64Data.size() > 0 && (!isBase64(base64Data[0]) || !isBase64(base64Data[base64Data.size() - 1])))
  748. {
  749. int start = 0;
  750. size_t end = base64Data.size() - 1;
  751. while (!isBase64(base64Data[start]))
  752. {
  753. start++;
  754. }
  755. while (!isBase64(base64Data[end]))
  756. {
  757. end--;
  758. }
  759. base64Data = base64Data.substr(start, end - start + 1);
  760. }
  761. string byteData = base64_decode(base64Data);
  762. if (compression)
  763. {
  764. int err;
  765. const unsigned int buffer_size = 4096;
  766. char buffer[buffer_size];
  767. string decomData;
  768. if (strcmp(compression, "zlib") == 0 || strcmp(compression, "gzip") == 0)
  769. {
  770. z_stream dString;
  771. dString.zalloc = Z_NULL;
  772. dString.zfree = Z_NULL;
  773. dString.opaque = Z_NULL;
  774. dString.next_in = (Bytef*)byteData.c_str();
  775. dString.avail_in = byteData.size();
  776. if (strcmp(compression, "zlib") == 0)
  777. {
  778. // zlib
  779. if ((err = inflateInit(&dString)) != Z_OK)
  780. {
  781. LOG(1, "ZLIB inflateInit failed. Error: %d.\n", err);
  782. exit(-1);
  783. }
  784. }
  785. else
  786. {
  787. // gzip
  788. if ((err = inflateInit2(&dString, 16+MAX_WBITS)) != Z_OK)
  789. {
  790. LOG(1, "ZLIB inflateInit2 failed. Error: %d.\n", err);
  791. exit(-1);
  792. }
  793. }
  794. do
  795. {
  796. dString.next_out = (Bytef*)buffer;
  797. dString.avail_out = buffer_size;
  798. err = inflate(&dString, Z_NO_FLUSH);
  799. switch (err)
  800. {
  801. case Z_NEED_DICT:
  802. case Z_DATA_ERROR:
  803. case Z_MEM_ERROR:
  804. inflateEnd(&dString);
  805. LOG(1, "ZLIB inflate failed. Error: %d.\n", err);
  806. exit(-1);
  807. break;
  808. }
  809. string decomBlock(buffer, buffer_size - dString.avail_out);
  810. decomData += decomBlock;
  811. } while (err != Z_STREAM_END);
  812. inflateEnd(&dString);
  813. }
  814. else
  815. {
  816. LOG(1, "Unknown compression: %s.\n", compression);
  817. exit(-1);
  818. }
  819. byteData = decomData;
  820. }
  821. size_t byteDataSize = byteData.size();
  822. for (unsigned int i = 0; i < byteDataSize; i += 4)
  823. {
  824. unsigned int gid = static_cast<unsigned char>(byteData[i + 0]) |
  825. (static_cast<unsigned char>(byteData[i + 1]) << 8u) |
  826. (static_cast<unsigned char>(byteData[i + 2]) << 16u) |
  827. (static_cast<unsigned char>(byteData[i + 3]) << 24u);
  828. tileData.push_back(gid);
  829. }
  830. }
  831. else
  832. {
  833. LOG(1, "Unknown encoding: %s.\n", encoding);
  834. exit(-1);
  835. }
  836. }
  837. return tileData;
  838. }
  839. std::string TMXSceneEncoder::buildFilePath(const std::string& directory, const std::string& file)
  840. {
  841. return EncoderArguments::getRealPath(directory + "/" + file);
  842. }
  843. void TMXSceneEncoder::copyImage(unsigned char* dst, const unsigned char* src,
  844. unsigned int srcWidth, unsigned int dstWidth, unsigned int bpp,
  845. unsigned int srcx, unsigned int srcy, unsigned int dstx, unsigned int dsty, unsigned int width, unsigned int height)
  846. {
  847. unsigned int sizePerRow = width * bpp;
  848. for (unsigned int y = 0; y < height; y++)
  849. {
  850. const unsigned char* srcPtr = &src[((y + srcy) * srcWidth + srcx) * bpp];
  851. unsigned char* dstPtr = &dst[((y + dsty) * dstWidth + dstx) * bpp];
  852. if (src == dst)
  853. {
  854. memmove(dstPtr, srcPtr, sizePerRow);
  855. }
  856. else
  857. {
  858. memcpy(dstPtr, srcPtr, sizePerRow);
  859. }
  860. }
  861. }