TmxFile2D.cpp 25 KB

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