Tired of using different solutions that only gave me a headache, I decided to write a .tmx
parser that works in the simplest way possible.
It’s just a class that has a static member function (so no need to instantiate) and it returns a vector<vector<int>>
to implement quickly.
The only dependency is the TinyXML2 which we will detail later.
For more information about TinyXML2, see this post:
To use it, you need to either install TinyXML2 or use it without installing in this repository in short that I did a fork.
But the best option is to install it on your system. Below example of installation on Ubuntu and derivatives:
sudo apt install libtinyxml2-dev
Now just clone with your preferred version control, example with Git
git clone https://github.com/terroo/loadtmx
And copy the
loadtmx.hpp
file to your project.
To implement it, just create any file, include loadtmx.hpp
and use either std::vector<std::vector<int>>
or auto
, for example:
vim main.cpp
#include "loadtmx.hpp"
int main( int argc , char **argv ){
auto map = LoadTmx::tilemap("file.tmx");
}
Suppose you have this .tmx
and you want to parser each number in it:
To download this example use raw from Gist or run the command below:
wget https://cutt.ly/tilemaptmx -O tilemap.tmx
Now add it to your code and print each position with a for
loop:
#include "loadtmx.hpp"
int main( int argc , char **argv ){
auto map = LoadTmx::tilemap("tilemap.tmx");
for(auto &line : map){
for(auto &col : line){
std::cout << col;
}
std::cout << '\n';
}
return 0;
}
To compile, run:
g++ main.cpp -ltinyxml2
./a.out
The possible output will be precisely the position numbers that were stored in
line
andcol
If you want to use a classic loop it would be:
for(std::size_t i{}; i < map.size(); ++i){
for(std::size_t j{}; j < map[i].size(); ++j){
std::cout << map[i][j];
}
std::cout << '\n';
}
If using local TinyXML2 instead of installed on your system, compile along with the TinyXML2 .cpp
file, eg g++ main.cpp tinyxml2/tinyxml2.cpp
.
Note: It already includes the
<iostream>
and<vector>
by default, so including it you can already remove any other use of these libraries in your code to avoid overhead.