TmxFile2D.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Graphics/Texture2D.h"
  25. #include "../Graphics/Graphics.h"
  26. #include "../IO/FileSystem.h"
  27. #include "../IO/Log.h"
  28. #include "../Resource/ResourceCache.h"
  29. #include "../Resource/XMLFile.h"
  30. #include "../Resource/Image.h"
  31. #include "../Urho2D/Sprite2D.h"
  32. #include "../Urho2D/TmxFile2D.h"
  33. #include "../Math/AreaAllocator.h"
  34. #include "../DebugNew.h"
  35. namespace Urho3D
  36. {
  37. extern const float PIXEL_SIZE;
  38. TmxLayer2D::TmxLayer2D(TmxFile2D* tmxFile, TileMapLayerType2D type) :
  39. tmxFile_(tmxFile),
  40. type_(type)
  41. {
  42. }
  43. TmxLayer2D::~TmxLayer2D()
  44. {
  45. }
  46. TmxFile2D* TmxLayer2D::GetTmxFile() const
  47. {
  48. return tmxFile_;
  49. }
  50. bool TmxLayer2D::HasProperty(const String& name) const
  51. {
  52. if (!propertySet_)
  53. return false;
  54. return propertySet_->HasProperty(name);
  55. }
  56. const String& TmxLayer2D::GetProperty(const String& name) const
  57. {
  58. if (!propertySet_)
  59. return String::EMPTY;
  60. return propertySet_->GetProperty(name);
  61. }
  62. void TmxLayer2D::LoadInfo(const XMLElement& element)
  63. {
  64. name_ = element.GetAttribute("name");
  65. width_ = element.GetInt("width");
  66. height_ = element.GetInt("height");
  67. if (element.HasAttribute("visible"))
  68. visible_ = element.GetInt("visible") != 0;
  69. else
  70. visible_ = true;
  71. }
  72. void TmxLayer2D::LoadPropertySet(const XMLElement& element)
  73. {
  74. propertySet_ = new PropertySet2D();
  75. propertySet_->Load(element);
  76. }
  77. TmxTileLayer2D::TmxTileLayer2D(TmxFile2D* tmxFile) :
  78. TmxLayer2D(tmxFile, LT_TILE_LAYER)
  79. {
  80. }
  81. enum LayerEncoding {
  82. XML,
  83. CSV,
  84. Base64,
  85. };
  86. bool TmxTileLayer2D::Load(const XMLElement& element, const TileMapInfo2D& info)
  87. {
  88. LoadInfo(element);
  89. XMLElement dataElem = element.GetChild("data");
  90. if (!dataElem)
  91. {
  92. URHO3D_LOGERROR("Could not find data in layer");
  93. return false;
  94. }
  95. LayerEncoding encoding;
  96. if (dataElem.HasAttribute("compression"))
  97. {
  98. URHO3D_LOGERROR("Compression not supported now");
  99. return false;
  100. }
  101. if (dataElem.HasAttribute("encoding"))
  102. {
  103. String encodingAttribute = dataElem.GetAttribute("encoding");
  104. if (encodingAttribute == "xml")
  105. encoding = XML;
  106. else if (encodingAttribute == "csv")
  107. encoding = CSV;
  108. else if (encodingAttribute == "base64")
  109. encoding = Base64;
  110. else
  111. {
  112. URHO3D_LOGERROR("Invalid encoding: " + encodingAttribute);
  113. return false;
  114. }
  115. }
  116. else
  117. encoding = XML;
  118. tiles_.Resize((unsigned)(width_ * height_));
  119. if (encoding == XML)
  120. {
  121. XMLElement tileElem = dataElem.GetChild("tile");
  122. for (int y = 0; y < height_; ++y)
  123. {
  124. for (int x = 0; x < width_; ++x)
  125. {
  126. if (!tileElem)
  127. return false;
  128. int gid = tileElem.GetInt("gid");
  129. if (gid > 0)
  130. {
  131. SharedPtr<Tile2D> tile(new Tile2D());
  132. tile->gid_ = gid;
  133. tile->sprite_ = tmxFile_->GetTileSprite(gid);
  134. tile->propertySet_ = tmxFile_->GetTilePropertySet(gid);
  135. tiles_[y * width_ + x] = tile;
  136. }
  137. tileElem = tileElem.GetNext("tile");
  138. }
  139. }
  140. }
  141. else if (encoding == CSV)
  142. {
  143. String dataValue = dataElem.GetValue();
  144. Vector<String> gidVector = dataValue.Split(',');
  145. int currentIndex = 0;
  146. for (int y = 0; y < height_; ++y)
  147. {
  148. for (int x = 0; x < width_; ++x)
  149. {
  150. gidVector[currentIndex].Replace("\n", "");
  151. int gid = ToInt(gidVector[currentIndex]);
  152. if (gid > 0)
  153. {
  154. SharedPtr<Tile2D> tile(new Tile2D());
  155. tile->gid_ = gid;
  156. tile->sprite_ = tmxFile_->GetTileSprite(gid);
  157. tile->propertySet_ = tmxFile_->GetTilePropertySet(gid);
  158. tiles_[y * width_ + x] = tile;
  159. }
  160. ++currentIndex;
  161. }
  162. }
  163. }
  164. else if (encoding == Base64)
  165. {
  166. String dataValue = dataElem.GetValue();
  167. int startPosition = 0;
  168. while (!IsAlpha(dataValue[startPosition]) && !IsDigit(dataValue[startPosition])
  169. && dataValue[startPosition] != '+' && dataValue[startPosition] != '/') ++startPosition;
  170. dataValue = dataValue.Substring(startPosition);
  171. PODVector<unsigned char> buffer = DecodeBase64(dataValue);
  172. int currentIndex = 0;
  173. for (int y = 0; y < height_; ++y)
  174. {
  175. for (int x = 0; x < width_; ++x)
  176. {
  177. // buffer contains 32-bit integers in little-endian format
  178. int gid = (buffer[currentIndex+3] << 24) | (buffer[currentIndex+2] << 16)
  179. | (buffer[currentIndex+1] << 8) | buffer[currentIndex];
  180. if (gid > 0)
  181. {
  182. SharedPtr<Tile2D> tile(new Tile2D());
  183. tile->gid_ = gid;
  184. tile->sprite_ = tmxFile_->GetTileSprite(gid);
  185. tile->propertySet_ = tmxFile_->GetTilePropertySet(gid);
  186. tiles_[y * width_ + x] = tile;
  187. }
  188. currentIndex += 4;
  189. }
  190. }
  191. }
  192. if (element.HasChild("properties"))
  193. LoadPropertySet(element.GetChild("properties"));
  194. return true;
  195. }
  196. Tile2D* TmxTileLayer2D::GetTile(int x, int y) const
  197. {
  198. if (x < 0 || x >= width_ || y < 0 || y >= height_)
  199. return 0;
  200. return tiles_[y * width_ + x];
  201. }
  202. TmxObjectGroup2D::TmxObjectGroup2D(TmxFile2D* tmxFile) :
  203. TmxLayer2D(tmxFile, LT_OBJECT_GROUP)
  204. {
  205. }
  206. bool TmxObjectGroup2D::Load(const XMLElement& element, const TileMapInfo2D& info)
  207. {
  208. LoadInfo(element);
  209. for (XMLElement objectElem = element.GetChild("object"); objectElem; objectElem = objectElem.GetNext("object"))
  210. {
  211. SharedPtr<TileMapObject2D> object(new TileMapObject2D());
  212. StoreObject(objectElem, object, info);
  213. objects_.Push(object);
  214. }
  215. if (element.HasChild("properties"))
  216. LoadPropertySet(element.GetChild("properties"));
  217. return true;
  218. }
  219. void TmxObjectGroup2D::StoreObject(XMLElement objectElem, SharedPtr<TileMapObject2D> object, const TileMapInfo2D& info, bool isTile)
  220. {
  221. if (objectElem.HasAttribute("name"))
  222. object->name_ = objectElem.GetAttribute("name");
  223. if (objectElem.HasAttribute("type"))
  224. object->type_ = objectElem.GetAttribute("type");
  225. if (objectElem.HasAttribute("gid"))
  226. object->objectType_ = OT_TILE;
  227. else if (objectElem.HasChild("polygon"))
  228. object->objectType_ = OT_POLYGON;
  229. else if (objectElem.HasChild("polyline"))
  230. object->objectType_ = OT_POLYLINE;
  231. else if (objectElem.HasChild("ellipse"))
  232. object->objectType_ = OT_ELLIPSE;
  233. else
  234. object->objectType_ = OT_RECTANGLE;
  235. const Vector2 position(objectElem.GetFloat("x"), objectElem.GetFloat("y"));
  236. const Vector2 size(objectElem.GetFloat("width"), objectElem.GetFloat("height"));
  237. switch (object->objectType_)
  238. {
  239. case OT_RECTANGLE:
  240. case OT_ELLIPSE:
  241. object->position_ = info.ConvertPosition(Vector2(position.x_, position.y_ + size.y_));
  242. object->size_ = Vector2(size.x_ * PIXEL_SIZE, size.y_ * PIXEL_SIZE);
  243. break;
  244. case OT_TILE:
  245. object->position_ = info.ConvertPosition(position);
  246. object->gid_ = objectElem.GetInt("gid");
  247. object->sprite_ = tmxFile_->GetTileSprite(object->gid_);
  248. if (objectElem.HasAttribute("width") || objectElem.HasAttribute("height"))
  249. {
  250. object->size_ = Vector2(size.x_ * PIXEL_SIZE, size.y_ * PIXEL_SIZE);
  251. }
  252. else if (object->sprite_)
  253. {
  254. IntVector2 spriteSize = object->sprite_->GetRectangle().Size();
  255. object->size_ = Vector2(spriteSize.x_, spriteSize.y_);
  256. }
  257. break;
  258. case OT_POLYGON:
  259. case OT_POLYLINE:
  260. {
  261. Vector<String> points;
  262. const char* name = object->objectType_ == OT_POLYGON ? "polygon" : "polyline";
  263. XMLElement polygonElem = objectElem.GetChild(name);
  264. points = polygonElem.GetAttribute("points").Split(' ');
  265. if (points.Size() <= 1)
  266. return;
  267. object->points_.Resize(points.Size());
  268. for (unsigned i = 0; i < points.Size(); ++i)
  269. {
  270. points[i].Replace(',', ' ');
  271. Vector2 point = position + ToVector2(points[i]);
  272. object->points_[i] = info.ConvertPosition(point);
  273. }
  274. }
  275. break;
  276. default: break;
  277. }
  278. if (objectElem.HasChild("properties"))
  279. {
  280. object->propertySet_ = new PropertySet2D();
  281. object->propertySet_->Load(objectElem.GetChild("properties"));
  282. }
  283. }
  284. TileMapObject2D* TmxObjectGroup2D::GetObject(unsigned index) const
  285. {
  286. if (index >= objects_.Size())
  287. return 0;
  288. return objects_[index];
  289. }
  290. TmxImageLayer2D::TmxImageLayer2D(TmxFile2D* tmxFile) :
  291. TmxLayer2D(tmxFile, LT_IMAGE_LAYER)
  292. {
  293. }
  294. bool TmxImageLayer2D::Load(const XMLElement& element, const TileMapInfo2D& info)
  295. {
  296. LoadInfo(element);
  297. XMLElement imageElem = element.GetChild("image");
  298. if (!imageElem)
  299. return false;
  300. position_ = Vector2(0.0f, info.GetMapHeight());
  301. source_ = imageElem.GetAttribute("source");
  302. String textureFilePath = GetParentPath(tmxFile_->GetName()) + source_;
  303. ResourceCache* cache = tmxFile_->GetSubsystem<ResourceCache>();
  304. SharedPtr<Texture2D> texture(cache->GetResource<Texture2D>(textureFilePath));
  305. if (!texture)
  306. {
  307. URHO3D_LOGERROR("Could not load texture " + textureFilePath);
  308. return false;
  309. }
  310. sprite_ = new Sprite2D(tmxFile_->GetContext());
  311. sprite_->SetTexture(texture);
  312. sprite_->SetRectangle(IntRect(0, 0, texture->GetWidth(), texture->GetHeight()));
  313. // Set image hot spot at left top
  314. sprite_->SetHotSpot(Vector2(0.0f, 1.0f));
  315. if (element.HasChild("properties"))
  316. LoadPropertySet(element.GetChild("properties"));
  317. return true;
  318. }
  319. Sprite2D* TmxImageLayer2D::GetSprite() const
  320. {
  321. return sprite_;
  322. }
  323. TmxFile2D::TmxFile2D(Context* context) :
  324. Resource(context)
  325. {
  326. }
  327. TmxFile2D::~TmxFile2D()
  328. {
  329. for (unsigned i = 0; i < layers_.Size(); ++i)
  330. delete layers_[i];
  331. }
  332. void TmxFile2D::RegisterObject(Context* context)
  333. {
  334. context->RegisterFactory<TmxFile2D>();
  335. }
  336. bool TmxFile2D::BeginLoad(Deserializer& source)
  337. {
  338. if (GetName().Empty())
  339. SetName(source.GetName());
  340. loadXMLFile_ = new XMLFile(context_);
  341. if (!loadXMLFile_->Load(source))
  342. {
  343. URHO3D_LOGERROR("Load XML failed " + source.GetName());
  344. loadXMLFile_.Reset();
  345. return false;
  346. }
  347. XMLElement rootElem = loadXMLFile_->GetRoot("map");
  348. if (!rootElem)
  349. {
  350. URHO3D_LOGERROR("Invalid tmx file " + source.GetName());
  351. loadXMLFile_.Reset();
  352. return false;
  353. }
  354. // If we're async loading, request the texture now. Finish during EndLoad().
  355. if (GetAsyncLoadState() == ASYNC_LOADING)
  356. {
  357. for (XMLElement tileSetElem = rootElem.GetChild("tileset"); tileSetElem; tileSetElem = tileSetElem.GetNext("tileset"))
  358. {
  359. // Tile set defined in TSX file
  360. if (tileSetElem.HasAttribute("source"))
  361. {
  362. String source = tileSetElem.GetAttribute("source");
  363. SharedPtr<XMLFile> tsxXMLFile = LoadTSXFile(source);
  364. if (!tsxXMLFile)
  365. return false;
  366. tsxXMLFiles_[source] = tsxXMLFile;
  367. String textureFilePath =
  368. GetParentPath(GetName()) + tsxXMLFile->GetRoot("tileset").GetChild("image").GetAttribute("source");
  369. GetSubsystem<ResourceCache>()->BackgroundLoadResource<Texture2D>(textureFilePath, true, this);
  370. }
  371. else
  372. {
  373. String textureFilePath = GetParentPath(GetName()) + tileSetElem.GetChild("image").GetAttribute("source");
  374. GetSubsystem<ResourceCache>()->BackgroundLoadResource<Texture2D>(textureFilePath, true, this);
  375. }
  376. }
  377. for (XMLElement imageLayerElem = rootElem.GetChild("imagelayer"); imageLayerElem;
  378. imageLayerElem = imageLayerElem.GetNext("imagelayer"))
  379. {
  380. String textureFilePath = GetParentPath(GetName()) + imageLayerElem.GetChild("image").GetAttribute("source");
  381. GetSubsystem<ResourceCache>()->BackgroundLoadResource<Texture2D>(textureFilePath, true, this);
  382. }
  383. }
  384. return true;
  385. }
  386. bool TmxFile2D::EndLoad()
  387. {
  388. if (!loadXMLFile_)
  389. return false;
  390. XMLElement rootElem = loadXMLFile_->GetRoot("map");
  391. String version = rootElem.GetAttribute("version");
  392. if (version != "1.0")
  393. {
  394. URHO3D_LOGERROR("Invalid version");
  395. return false;
  396. }
  397. String orientation = rootElem.GetAttribute("orientation");
  398. if (orientation == "orthogonal")
  399. info_.orientation_ = O_ORTHOGONAL;
  400. else if (orientation == "isometric")
  401. info_.orientation_ = O_ISOMETRIC;
  402. else if (orientation == "staggered")
  403. info_.orientation_ = O_STAGGERED;
  404. else if (orientation == "hexagonal")
  405. info_.orientation_ = O_HEXAGONAL;
  406. else
  407. {
  408. URHO3D_LOGERROR("Unsupported orientation type " + orientation);
  409. return false;
  410. }
  411. info_.width_ = rootElem.GetInt("width");
  412. info_.height_ = rootElem.GetInt("height");
  413. info_.tileWidth_ = rootElem.GetFloat("tilewidth") * PIXEL_SIZE;
  414. info_.tileHeight_ = rootElem.GetFloat("tileheight") * PIXEL_SIZE;
  415. for (unsigned i = 0; i < layers_.Size(); ++i)
  416. delete layers_[i];
  417. layers_.Clear();
  418. for (XMLElement childElement = rootElem.GetChild(); childElement; childElement = childElement.GetNext())
  419. {
  420. bool ret = true;
  421. String name = childElement.GetName();
  422. if (name == "tileset")
  423. ret = LoadTileSet(childElement);
  424. else if (name == "layer")
  425. {
  426. TmxTileLayer2D* tileLayer = new TmxTileLayer2D(this);
  427. ret = tileLayer->Load(childElement, info_);
  428. layers_.Push(tileLayer);
  429. }
  430. else if (name == "objectgroup")
  431. {
  432. TmxObjectGroup2D* objectGroup = new TmxObjectGroup2D(this);
  433. ret = objectGroup->Load(childElement, info_);
  434. layers_.Push(objectGroup);
  435. }
  436. else if (name == "imagelayer")
  437. {
  438. TmxImageLayer2D* imageLayer = new TmxImageLayer2D(this);
  439. ret = imageLayer->Load(childElement, info_);
  440. layers_.Push(imageLayer);
  441. }
  442. if (!ret)
  443. {
  444. loadXMLFile_.Reset();
  445. tsxXMLFiles_.Clear();
  446. return false;
  447. }
  448. }
  449. loadXMLFile_.Reset();
  450. tsxXMLFiles_.Clear();
  451. return true;
  452. }
  453. bool TmxFile2D::SetInfo(Orientation2D orientation, int width, int height, float tileWidth, float tileHeight)
  454. {
  455. if (layers_.Size() > 0)
  456. return false;
  457. info_.orientation_ = orientation;
  458. info_.width_ = width;
  459. info_.height_ = height;
  460. info_.tileWidth_ = tileWidth * PIXEL_SIZE;
  461. info_.tileHeight_ = tileHeight * PIXEL_SIZE;
  462. return true;
  463. }
  464. void TmxFile2D::AddLayer(unsigned index, TmxLayer2D *layer)
  465. {
  466. if (index > layers_.Size())
  467. layers_.Push(layer);
  468. else // index <= layers_.size()
  469. layers_.Insert(index, layer);
  470. }
  471. void TmxFile2D::AddLayer(TmxLayer2D *layer)
  472. {
  473. layers_.Push(layer);
  474. }
  475. Sprite2D* TmxFile2D::GetTileSprite(int gid) const
  476. {
  477. HashMap<int, SharedPtr<Sprite2D> >::ConstIterator i = gidToSpriteMapping_.Find(gid);
  478. if (i == gidToSpriteMapping_.End())
  479. return 0;
  480. return i->second_;
  481. }
  482. Vector<SharedPtr<TileMapObject2D> > TmxFile2D::GetTileCollisionShapes(int gid) const
  483. {
  484. Vector<SharedPtr<TileMapObject2D> > tileShapes;
  485. HashMap<int, Vector<SharedPtr<TileMapObject2D> > >::ConstIterator i = gidToCollisionShapeMapping_.Find(gid);
  486. if (i == gidToCollisionShapeMapping_.End())
  487. return tileShapes;
  488. return i->second_;
  489. }
  490. PropertySet2D* TmxFile2D::GetTilePropertySet(int gid) const
  491. {
  492. HashMap<int, SharedPtr<PropertySet2D> >::ConstIterator i = gidToPropertySetMapping_.Find(gid);
  493. if (i == gidToPropertySetMapping_.End())
  494. return 0;
  495. return i->second_;
  496. }
  497. const TmxLayer2D* TmxFile2D::GetLayer(unsigned index) const
  498. {
  499. if (index >= layers_.Size())
  500. return 0;
  501. return layers_[index];
  502. }
  503. SharedPtr<XMLFile> TmxFile2D::LoadTSXFile(const String& source)
  504. {
  505. String tsxFilePath = GetParentPath(GetName()) + source;
  506. SharedPtr<File> tsxFile = GetSubsystem<ResourceCache>()->GetFile(tsxFilePath);
  507. SharedPtr<XMLFile> tsxXMLFile(new XMLFile(context_));
  508. if (!tsxFile || !tsxXMLFile->Load(*tsxFile))
  509. {
  510. URHO3D_LOGERROR("Load TSX file failed " + tsxFilePath);
  511. return SharedPtr<XMLFile>();
  512. }
  513. return tsxXMLFile;
  514. }
  515. struct TileImageInfo {
  516. Image* image;
  517. int tileGid;
  518. int imageWidth;
  519. int imageHeight;
  520. int x;
  521. int y;
  522. };
  523. bool TmxFile2D::LoadTileSet(const XMLElement& element)
  524. {
  525. int firstgid = element.GetInt("firstgid");
  526. XMLElement tileSetElem;
  527. if (element.HasAttribute("source"))
  528. {
  529. String source = element.GetAttribute("source");
  530. HashMap<String, SharedPtr<XMLFile> >::Iterator i = tsxXMLFiles_.Find(source);
  531. if (i == tsxXMLFiles_.End())
  532. {
  533. SharedPtr<XMLFile> tsxXMLFile = LoadTSXFile(source);
  534. if (!tsxXMLFile)
  535. return false;
  536. // Add to mapping to avoid release
  537. tsxXMLFiles_[source] = tsxXMLFile;
  538. tileSetElem = tsxXMLFile->GetRoot("tileset");
  539. }
  540. else
  541. tileSetElem = i->second_->GetRoot("tileset");
  542. }
  543. else
  544. tileSetElem = element;
  545. int tileWidth = tileSetElem.GetInt("tilewidth");
  546. int tileHeight = tileSetElem.GetInt("tileheight");
  547. int spacing = tileSetElem.GetInt("spacing");
  548. int margin = tileSetElem.GetInt("margin");
  549. int imageWidth;
  550. int imageHeight;
  551. bool isSingleTileSet = false;
  552. ResourceCache* cache = GetSubsystem<ResourceCache>();
  553. {
  554. XMLElement imageElem = tileSetElem.GetChild("image");
  555. // Tileset based on single tileset image
  556. if (imageElem.NotNull()) {
  557. isSingleTileSet = true;
  558. String textureFilePath = GetParentPath(GetName()) + imageElem.GetAttribute("source");
  559. SharedPtr<Texture2D> texture(cache->GetResource<Texture2D>(textureFilePath));
  560. if (!texture)
  561. {
  562. URHO3D_LOGERROR("Could not load texture " + textureFilePath);
  563. return false;
  564. }
  565. // Set hot spot at left bottom
  566. Vector2 hotSpot(0.0f, 0.0f);
  567. if (tileSetElem.HasChild("tileoffset"))
  568. {
  569. XMLElement offsetElem = tileSetElem.GetChild("tileoffset");
  570. hotSpot.x_ += offsetElem.GetFloat("x") / (float)tileWidth;
  571. hotSpot.y_ += offsetElem.GetFloat("y") / (float)tileHeight;
  572. }
  573. imageWidth = imageElem.GetInt("width");
  574. imageHeight = imageElem.GetInt("height");
  575. int gid = firstgid;
  576. for (int y = margin; y + tileHeight <= imageHeight - margin; y += tileHeight + spacing)
  577. {
  578. for (int x = margin; x + tileWidth <= imageWidth - margin; x += tileWidth + spacing)
  579. {
  580. SharedPtr<Sprite2D> sprite(new Sprite2D(context_));
  581. sprite->SetTexture(texture);
  582. sprite->SetRectangle(IntRect(x, y, x + tileWidth, y + tileHeight));
  583. sprite->SetHotSpot(hotSpot);
  584. gidToSpriteMapping_[gid++] = sprite;
  585. }
  586. }
  587. }
  588. }
  589. Vector<TileImageInfo> tileImageInfos;
  590. for (XMLElement tileElem = tileSetElem.GetChild("tile"); tileElem; tileElem = tileElem.GetNext("tile"))
  591. {
  592. int gid = firstgid + tileElem.GetInt("id");
  593. // Tileset based on collection of images
  594. if (!isSingleTileSet)
  595. {
  596. XMLElement imageElem = tileElem.GetChild("image");
  597. if (imageElem.NotNull()) {
  598. String textureFilePath = GetParentPath(GetName()) + imageElem.GetAttribute("source");
  599. SharedPtr<Image> image(cache->GetResource<Image>(textureFilePath));
  600. if (!image)
  601. {
  602. URHO3D_LOGERROR("Could not load image " + textureFilePath);
  603. return false;
  604. }
  605. tileWidth = imageWidth = imageElem.GetInt("width");
  606. tileHeight = imageHeight = imageElem.GetInt("height");
  607. TileImageInfo info = {image, gid, imageWidth, imageHeight, 0, 0};
  608. tileImageInfos.Push(info);
  609. }
  610. }
  611. // Tile collision shape(s)
  612. TmxObjectGroup2D objectGroup(this);
  613. for (XMLElement collisionElem = tileElem.GetChild("objectgroup"); collisionElem; collisionElem = collisionElem.GetNext("objectgroup"))
  614. {
  615. Vector<SharedPtr<TileMapObject2D> > objects;
  616. for (XMLElement objectElem = collisionElem.GetChild("object"); objectElem; objectElem = objectElem.GetNext("object"))
  617. {
  618. SharedPtr<TileMapObject2D> object(new TileMapObject2D());
  619. // Convert Tiled local position (left top) to Urho3D local position (left bottom)
  620. objectElem.SetAttribute("y", String(info_.GetMapHeight() / PIXEL_SIZE - (tileHeight - objectElem.GetFloat("y"))));
  621. objectGroup.StoreObject(objectElem, object, info_, true);
  622. objects.Push(object);
  623. }
  624. gidToCollisionShapeMapping_[gid] = objects;
  625. }
  626. if (tileElem.HasChild("properties"))
  627. {
  628. SharedPtr<PropertySet2D> propertySet(new PropertySet2D());
  629. propertySet->Load(tileElem.GetChild("properties"));
  630. gidToPropertySetMapping_[gid] = propertySet;
  631. }
  632. }
  633. if (!isSingleTileSet)
  634. {
  635. if (tileImageInfos.Empty())
  636. return false;
  637. AreaAllocator allocator(128, 128, 2048, 2048);
  638. for (int i = 0; i < tileImageInfos.Size(); ++i)
  639. {
  640. TileImageInfo& info = tileImageInfos[i];
  641. if (!allocator.Allocate(info.imageWidth + 1, info.imageHeight + 1, info.x, info.y))
  642. {
  643. URHO3D_LOGERROR("Could not allocate area");
  644. return false;
  645. }
  646. }
  647. SharedPtr<Texture2D> texture(new Texture2D(context_));
  648. texture->SetMipsToSkip(QUALITY_LOW, 0);
  649. texture->SetNumLevels(1);
  650. texture->SetSize(allocator.GetWidth(), allocator.GetHeight(), Graphics::GetRGBAFormat());
  651. unsigned textureDataSize = allocator.GetWidth() * allocator.GetHeight() * 4;
  652. SharedArrayPtr<unsigned char> textureData(new unsigned char[textureDataSize]);
  653. memset(textureData.Get(), 0, textureDataSize);
  654. for (int i = 0; i < tileImageInfos.Size(); ++i)
  655. {
  656. TileImageInfo& info = tileImageInfos[i];
  657. Image* image = info.image;
  658. for (int y = 0; y < image->GetHeight(); ++y)
  659. {
  660. memcpy(textureData.Get() + ((info.y + y) * allocator.GetWidth() + info.x) * 4,
  661. image->GetData() + y * image->GetWidth() * 4, image->GetWidth() * 4);
  662. }
  663. SharedPtr<Sprite2D> sprite(new Sprite2D(context_));
  664. sprite->SetTexture(texture);
  665. sprite->SetRectangle(IntRect(info.x, info.y, info.x + info.imageWidth, info.y + + info.imageHeight));
  666. sprite->SetHotSpot(Vector2::ZERO);
  667. gidToSpriteMapping_[info.tileGid] = sprite;
  668. }
  669. texture->SetData(0, 0, 0, allocator.GetWidth(), allocator.GetHeight(), textureData.Get());
  670. }
  671. return true;
  672. }
  673. }