├── tools ├── __init__.py ├── build.sh └── process.py ├── searchresult.h ├── bfs.cpp ├── list.h ├── bfs.h ├── dijkstra.cpp ├── config.h ├── dijkstra.h ├── node.h ├── astar.h ├── environmentoptions.cpp ├── theta.h ├── node.cpp ├── environmentoptions.h ├── list.cpp ├── CMakeLists.txt ├── ilogger.h ├── map.h ├── mission.h ├── xmllogger.h ├── ASearch.pro ├── Bresenham.h ├── Queues.h ├── theta.cpp ├── asearch.cpp ├── .gitignore ├── astar.cpp ├── isearch.h ├── examples ├── simple_obstacle.xml └── simple_obstacle_log.xml ├── mission.cpp ├── Bresenham.cpp ├── Queues.cpp ├── gl_const.h ├── README.md ├── xmllogger.cpp ├── isearch.cpp ├── config.cpp ├── map.cpp └── tinyxml2.h /tools/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tools/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | cd ../build 3 | cmake ../ 4 | make -j 3 5 | -------------------------------------------------------------------------------- /searchresult.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PathPlanning/3D-AStar-ThetaStar/HEAD/searchresult.h -------------------------------------------------------------------------------- /bfs.cpp: -------------------------------------------------------------------------------- 1 | #include "bfs.h" 2 | 3 | BFS::BFS() { 4 | hweight = 1; 5 | } 6 | 7 | BFS::~BFS() 8 | { 9 | } 10 | 11 | void BFS::addOpen(Node newNode, uint_least32_t key) { 12 | newNode.F = newNode.H; 13 | ISearch::addOpen(newNode, key); 14 | } -------------------------------------------------------------------------------- /list.h: -------------------------------------------------------------------------------- 1 | #ifndef LIST_H 2 | #define LIST_H 3 | #include "node.h" 4 | #include 5 | 6 | class NodeList 7 | { 8 | public: 9 | NodeList(void); 10 | ~NodeList(void); 11 | 12 | bool find(int x, int y); 13 | std::list::iterator find_i(int x, int y); 14 | 15 | std::list List; 16 | }; 17 | #endif 18 | -------------------------------------------------------------------------------- /bfs.h: -------------------------------------------------------------------------------- 1 | #ifndef BFS_H 2 | #define BFS_H 3 | #include "gl_const.h" 4 | #include "isearch.h" 5 | #include "astar.h" 6 | 7 | // TODO write breadth-first search instead of best-first search algorithm here 8 | class BFS : public Astar 9 | { 10 | protected: 11 | virtual void addOpen(Node newNode, uint_least32_t key); 12 | public: 13 | BFS(); 14 | ~BFS(void); 15 | 16 | }; 17 | 18 | #endif 19 | -------------------------------------------------------------------------------- /dijkstra.cpp: -------------------------------------------------------------------------------- 1 | #include "dijkstra.h" 2 | 3 | Dijkstra::Dijkstra(int i) { 4 | hweight = 0; 5 | breakingties = CN_SP_BT_GMAX; 6 | } 7 | 8 | Dijkstra::~Dijkstra(void) { 9 | } 10 | 11 | double Dijkstra::computeHFromCellToCell(int start_i, int start_j, int start_h, int fin_i, int fin_j, int fin_h, 12 | const EnvironmentOptions &options) { 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /config.h: -------------------------------------------------------------------------------- 1 | #ifndef CONFIG_H 2 | #define CONFIG_H 3 | 4 | #include 5 | 6 | class Config 7 | { 8 | public: 9 | Config(); 10 | Config(const Config& orig); 11 | ~Config(); 12 | 13 | bool getConfig(const char *FileName); 14 | 15 | public: 16 | double* SearchParams; 17 | std::string* LogParams; 18 | unsigned int N; 19 | 20 | }; 21 | 22 | #endif 23 | 24 | -------------------------------------------------------------------------------- /dijkstra.h: -------------------------------------------------------------------------------- 1 | #ifndef DIJKSTRA_H 2 | #define DIJKSTRA_H 3 | 4 | #include "astar.h" 5 | #include "gl_const.h" 6 | 7 | class Dijkstra : public Astar { 8 | public: 9 | Dijkstra(int i); 10 | 11 | ~Dijkstra(void); 12 | 13 | virtual double computeHFromCellToCell(int start_i, int start_j, int start_h, int fin_i, int fin_j, int fin_h, 14 | const EnvironmentOptions &options); 15 | }; 16 | 17 | #endif 18 | -------------------------------------------------------------------------------- /node.h: -------------------------------------------------------------------------------- 1 | #ifndef NODE_H 2 | #define NODE_H 3 | 4 | #include 5 | struct Node 6 | { 7 | int i, j, z; 8 | double F, g, H; 9 | const Node* parent; 10 | 11 | bool operator==(const Node& other) const; 12 | bool operator!=(const Node& other) const; 13 | 14 | uint_least32_t get_id(int map_height, int map_width); 15 | }; 16 | 17 | namespace std { 18 | template<> 19 | struct hash { 20 | size_t operator()(const Node &x) const; 21 | }; 22 | } 23 | #endif 24 | -------------------------------------------------------------------------------- /astar.h: -------------------------------------------------------------------------------- 1 | #ifndef ASTAR_H 2 | #define ASTAR_H 3 | 4 | #include "gl_const.h" 5 | #include "isearch.h" 6 | #include "ilogger.h" 7 | 8 | class Astar : public ISearch { 9 | public: 10 | Astar(); 11 | 12 | Astar(double weight, int BT, int SL, int i); 13 | 14 | ~Astar(); 15 | 16 | protected: 17 | double computeHFromCellToCell(int start_i, int start_j, int start_h, int fin_i, int fin_j, int fin_h, 18 | const EnvironmentOptions &options); 19 | 20 | }; 21 | 22 | #endif 23 | -------------------------------------------------------------------------------- /environmentoptions.cpp: -------------------------------------------------------------------------------- 1 | #include "environmentoptions.h" 2 | #include "gl_const.h" 3 | 4 | EnvironmentOptions::EnvironmentOptions() 5 | { 6 | metrictype = CN_SP_MT_EUCL; 7 | allowsqueeze = CN_SP_AS_FALSE; 8 | linecost = CN_MC_LINE; 9 | diagonalcost = CN_MC_DIAG; 10 | allowdiagonal = CN_SP_AD_TRUE; 11 | allowcutcorners = CN_SP_AC_FALSE; 12 | } 13 | 14 | EnvironmentOptions::EnvironmentOptions(int MT, bool AS, double LC, double DC, int AD, bool AC) 15 | { 16 | metrictype = MT; 17 | allowsqueeze = AS; 18 | linecost = LC; 19 | diagonalcost = DC; 20 | allowdiagonal = AD; 21 | allowcutcorners = AC; 22 | } 23 | 24 | -------------------------------------------------------------------------------- /theta.h: -------------------------------------------------------------------------------- 1 | #ifndef THETA_H 2 | #define THETA_H 3 | #include "gl_const.h" 4 | #include "astar.h" 5 | 6 | class Theta: public Astar 7 | { 8 | public: 9 | Theta(float hweight, int breakingties, int sizelimit, int i):Astar(hweight,breakingties, sizelimit, i){} 10 | ~Theta(void); 11 | 12 | 13 | private: 14 | const double computation_eps = 0.0001; 15 | protected: 16 | double EuclidDistance(const Node &from, const Node &to, const EnvironmentOptions &options) const; 17 | Node resetParent(Node current, Node parent, const Map &map, const EnvironmentOptions &options); 18 | void makePrimaryPath(Node curNode); 19 | void makeSecondaryPath(const Map &map,Node curNode); 20 | 21 | 22 | }; 23 | 24 | 25 | #endif // THETA_H 26 | -------------------------------------------------------------------------------- /node.cpp: -------------------------------------------------------------------------------- 1 | #include "node.h" 2 | 3 | 4 | bool Node::operator==(const Node &other) const { 5 | return i == other.i && j == other.j && z == other.z; 6 | } 7 | 8 | bool Node::operator!=(const Node &other) const { 9 | return !operator==(other); 10 | } 11 | 12 | uint_least32_t Node::get_id(int map_height, int map_width) { 13 | return (uint_least32_t)map_height * map_width * z + map_width * i + j; 14 | } 15 | 16 | size_t std::hash::operator()(const Node &x) const { 17 | size_t seed = 0; 18 | seed ^= std::hash()(x.i) + 0x9e3779b9 19 | + (seed << 6) + (seed >> 2); 20 | seed ^= std::hash()(x.j) + 0x9e3779b9 21 | + (seed << 6) + (seed >> 2); 22 | seed ^= std::hash()(x.z) + 0x9e3779b9 23 | + (seed << 6) + (seed >> 2); 24 | 25 | return seed; 26 | } 27 | -------------------------------------------------------------------------------- /environmentoptions.h: -------------------------------------------------------------------------------- 1 | #ifndef ENVIRONMENTOPTIONS_H 2 | #define ENVIRONMENTOPTIONS_H 3 | 4 | class EnvironmentOptions 5 | { 6 | public: 7 | EnvironmentOptions(int MT, bool AS, double LC, double DC, int AD, bool AC); 8 | EnvironmentOptions(); 9 | int metrictype; //��� ������� ��� �������� ��������� 10 | bool allowsqueeze;//����� �����������/����������� ������ ����� "����� �������" 11 | bool allowcutcorners;//����� �����������/����������� ������ ����� "����� �������" 12 | double linecost; //��������� ����������� �� ����������� � ��������� 13 | double diagonalcost; //��������� ������������ �� ��������� 14 | int allowdiagonal; //����� �����������/����������� ����������� �� ��������� 15 | bool useresetparent; //����� ������������/����������� ������������� ������ resetparent � jp_search 16 | 17 | }; 18 | 19 | #endif // ENVIRONMENTOPTIONS_H 20 | -------------------------------------------------------------------------------- /list.cpp: -------------------------------------------------------------------------------- 1 | #include "list.h" 2 | 3 | 4 | NodeList::NodeList(void) 5 | { 6 | 7 | } 8 | 9 | NodeList::~NodeList(void) 10 | { 11 | 12 | } 13 | 14 | bool NodeList::find(int x, int y) 15 | { 16 | std::list::iterator iter = List.end(); 17 | for(; iter != List.begin(); --iter) 18 | { 19 | if((iter->i == x) && (iter->j == y)) 20 | { 21 | return true; 22 | } 23 | } 24 | if((iter->i == x) && (iter->j == y)) 25 | { 26 | return true; 27 | } 28 | return false; 29 | } 30 | 31 | std::list::iterator NodeList::find_i(int x, int y) 32 | { 33 | std::list::iterator iter = List.begin(); 34 | for(iter = List.begin(); iter != List.end(); ++iter) 35 | { 36 | if((iter->i == x) && (iter->j == y)) 37 | { 38 | break; 39 | } 40 | } 41 | return iter; 42 | } 43 | 44 | 45 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8) 2 | project(3D-AStar-ThetaStar) 3 | 4 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -O2") 5 | 6 | set(SOURCE_FILES 7 | node.cpp 8 | xmllogger.cpp 9 | isearch.cpp 10 | mission.cpp 11 | map.cpp 12 | list.cpp 13 | config.cpp 14 | astar.cpp 15 | asearch.cpp 16 | environmentoptions.cpp 17 | node.h 18 | gl_const.h 19 | xmllogger.h 20 | isearch.h 21 | mission.h 22 | map.h 23 | ilogger.h 24 | list.h 25 | config.h 26 | astar.h 27 | searchresult.h 28 | environmentoptions.h 29 | Bresenham.cpp 30 | Bresenham.h 31 | theta.cpp 32 | theta.h 33 | dijkstra.cpp 34 | dijkstra.h 35 | bfs.cpp 36 | bfs.h 37 | Queues.cpp 38 | Queues.h 39 | tinyxml2.h 40 | tinyxml2.cpp) 41 | add_executable(Astar_heights ${SOURCE_FILES}) -------------------------------------------------------------------------------- /ilogger.h: -------------------------------------------------------------------------------- 1 | #ifndef ILOGGER_H 2 | #define ILOGGER_H 3 | 4 | #include 5 | #include "map.h" 6 | #include "list.h" 7 | #include 8 | #include 9 | #include 10 | 11 | class ILogger 12 | { 13 | public: 14 | virtual bool getLog(const char* FileName, const std::string* LogParams) = 0; 15 | virtual void saveLog() = 0; 16 | virtual void writeToLogMap(const Map& map, const NodeList& path) = 0; 17 | virtual void writeToLogOpenClose(const NodeList *open, const std::unordered_set& close, int size, bool summary=false) = 0; 18 | virtual void writeToLogPath(const NodeList& path) = 0; 19 | virtual void writeToLogHPpath(const NodeList& path) = 0; 20 | virtual void writeToLogNotFound() = 0; 21 | virtual void writeToLogSummary(unsigned int numberofsteps, unsigned int nodescreated, float length, double time) = 0; 22 | virtual ~ILogger() {} 23 | public: 24 | float loglevel; 25 | }; 26 | 27 | #endif 28 | 29 | -------------------------------------------------------------------------------- /map.h: -------------------------------------------------------------------------------- 1 | #ifndef MAP_H 2 | #define MAP_H 3 | #include "tinyxml2.h" 4 | #include 5 | #include "gl_const.h" 6 | #include 7 | #include 8 | #include 9 | class Map 10 | { 11 | public: 12 | Map(); 13 | Map(const Map& orig); 14 | ~Map(); 15 | 16 | bool getMap(const char *FileName); 17 | bool CellIsTraversable (int i, int j) const; 18 | bool CellIsTraversable (int i, int j, int h) const; 19 | bool CellOnGrid (int i, int j) const; 20 | bool CellOnGrid (int i, int j, int height) const; 21 | bool CellIsObstacle(int i, int j) const; 22 | bool CellIsObstacle(int i, int j, int h) const; 23 | int getValue(int i, int j) const; 24 | 25 | public: 26 | int** Grid; 27 | int height, width, altitude; 28 | int min_altitude_limit, max_altitude_limit; // The lowest and highest possible altitude for the path 29 | int start_i, start_j, start_h; 30 | int goal_i, goal_j, goal_h; 31 | }; 32 | 33 | #endif 34 | 35 | -------------------------------------------------------------------------------- /mission.h: -------------------------------------------------------------------------------- 1 | #ifndef MISSION_H 2 | #define MISSION_H 3 | 4 | #include "map.h" 5 | #include "config.h" 6 | #include "isearch.h" 7 | #include "ilogger.h" 8 | #include "searchresult.h" 9 | #include "environmentoptions.h" 10 | #include "gl_const.h" 11 | #include 12 | 13 | 14 | class Mission 15 | { 16 | public: 17 | Mission(); 18 | Mission (const char* fileName); 19 | ~Mission(); 20 | 21 | bool getMap(); 22 | bool getConfig(); 23 | bool createLog(); 24 | void createSearch(); 25 | void createEnvironmentOptions(); 26 | void startSearch(); 27 | void printSearchResultsToConsole(); 28 | void saveSearchResultsToLog(); 29 | 30 | private: 31 | const char* getAlgorithmName(); 32 | 33 | Map map; 34 | Config config; 35 | EnvironmentOptions options; 36 | ISearch* search; 37 | ILogger* logger; 38 | const char* fileName; 39 | SearchResult sr; 40 | }; 41 | 42 | #endif 43 | 44 | -------------------------------------------------------------------------------- /xmllogger.h: -------------------------------------------------------------------------------- 1 | #ifndef XMLLOGGER_H 2 | #define XMLLOGGER_H 3 | 4 | #include 5 | #include "tinyxml2.h" 6 | #include "ilogger.h" 7 | #include "map.h" 8 | #include "list.h" 9 | #include 10 | 11 | class XmlLogger : public ILogger { 12 | 13 | public: 14 | XmlLogger() {} 15 | 16 | virtual ~XmlLogger() {} 17 | 18 | bool getLog(const char *FileName, const std::string *LogParams); 19 | 20 | void saveLog(); 21 | 22 | void writeToLogMap(const Map &Map, const NodeList &path); 23 | 24 | void writeToLogOpenClose(const NodeList *open, const std::unordered_set &close, int size, bool summary); 25 | 26 | void writeToLogPath(const NodeList &path); 27 | 28 | void writeToLogHPpath(const NodeList &hppath); 29 | 30 | void writeToLogNotFound(); 31 | 32 | void writeToLogSummary(unsigned int numberofsteps, 33 | unsigned int nodescreated, 34 | float length, 35 | double time); 36 | 37 | private: 38 | std::string LogFileName; 39 | tinyxml2::XMLDocument doc; 40 | }; 41 | 42 | #endif 43 | 44 | -------------------------------------------------------------------------------- /ASearch.pro: -------------------------------------------------------------------------------- 1 | #------------------------------------------------- 2 | # 3 | # Project created by QtCreator 2011-02-26T12:08:02 4 | # 5 | #------------------------------------------------- 6 | 7 | TARGET = ASearch 8 | CONFIG += console 9 | CONFIG -= app_bundle 10 | TEMPLATE = app 11 | QMAKE_CXXFLAGS += -std=c++11 -O3 12 | 13 | win32 { 14 | QMAKE_LFLAGS += -static -static-libgcc -static-libstdc++ 15 | } 16 | 17 | SOURCES += \ 18 | tinyxml2.cpp \ 19 | node.cpp \ 20 | xmllogger.cpp \ 21 | isearch.cpp \ 22 | mission.cpp \ 23 | map.cpp \ 24 | list.cpp \ 25 | config.cpp \ 26 | astar.cpp \ 27 | asearch.cpp \ 28 | environmentoptions.cpp \ 29 | Bresenham.cpp \ 30 | theta.cpp \ 31 | dijkstra.cpp \ 32 | bfs.cpp 33 | 34 | HEADERS += \ 35 | tinyxml2.h \ 36 | node.h \ 37 | gl_const.h \ 38 | xmllogger.h \ 39 | isearch.h \ 40 | mission.h \ 41 | map.h \ 42 | ilogger.h \ 43 | list.h \ 44 | config.h \ 45 | astar.h \ 46 | searchresult.h \ 47 | environmentoptions.h \ 48 | Bresenham.h \ 49 | theta.h \ 50 | dijkstra.h \ 51 | bfs.h 52 | -------------------------------------------------------------------------------- /Bresenham.h: -------------------------------------------------------------------------------- 1 | #ifndef BRESENHAM_H 2 | #define BRESENHAM_H 3 | 4 | #include "map.h" 5 | #include "node.h" 6 | 7 | #include 8 | 9 | class iBresenham { 10 | protected: 11 | void bresenham3d(int x1, int y1, int z1, const int x2, const int y2, const int z2); // 3D Bresenham algorithm 12 | virtual bool ProcessPoint(int x, int y, int z) = 0; // Processes point in line. Return false, if line processing should be stopped 13 | }; 14 | 15 | class LineOfSight : public iBresenham { 16 | private: 17 | bool force_stopped; 18 | const Map& map; 19 | protected: 20 | virtual bool ProcessPoint(int i, int j, int h); 21 | 22 | public: 23 | LineOfSight(const Map&); 24 | bool line_of_sight(int i0, int j0, int h0, int i1, int j1, int h1); 25 | bool line_of_sight(const Node& from, const Node& to); 26 | }; 27 | 28 | class Liner : public iBresenham { 29 | private: 30 | const Map& map; 31 | std::list *path; 32 | 33 | protected: 34 | virtual bool ProcessPoint(int i, int j, int h); 35 | 36 | public: 37 | Liner(const Map&, std::list *init_path); 38 | void append_line(int i0, int j0, int h0, int i1, int j1, int h1); 39 | void append_line(const Node &from, const Node &to); 40 | }; 41 | 42 | #endif //BRESENHAM_H 43 | -------------------------------------------------------------------------------- /Queues.h: -------------------------------------------------------------------------------- 1 | #ifndef QUEUES_H 2 | #define QUEUES_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #include "node.h" 9 | 10 | class iOpen { 11 | protected: 12 | virtual bool less(const Node &x, const Node &y) const; 13 | int breaking_tie; 14 | public: 15 | iOpen() {}; 16 | 17 | virtual bool Insert(const Node &NewNode) = 0; 18 | 19 | virtual Node FindMin() const = 0; 20 | 21 | virtual void DeleteMin() = 0; 22 | 23 | virtual size_t size() const = 0; 24 | 25 | virtual bool empty() const = 0; 26 | }; 27 | 28 | class SortedList : public iOpen { 29 | private: 30 | std::vector> data; 31 | size_t size_; 32 | 33 | mutable size_t min_pos; 34 | 35 | public: 36 | SortedList() = default; 37 | 38 | SortedList(size_t size, int brakingtie); 39 | 40 | virtual bool Insert(const Node &NewNode); 41 | 42 | virtual Node FindMin() const; 43 | 44 | virtual void DeleteMin(); 45 | 46 | virtual size_t size() const; 47 | 48 | virtual bool empty() const; 49 | }; 50 | 51 | class ClusteredSets : public iOpen { 52 | private: 53 | std::vector loc_mins; 54 | std::vector> data; 55 | size_t size_; 56 | mutable size_t min_pos; 57 | 58 | public: 59 | ClusteredSets() = default; 60 | 61 | ClusteredSets(size_t size, int breakingtie); 62 | 63 | virtual bool Insert(const Node &NewNode); 64 | 65 | virtual Node FindMin() const; 66 | 67 | virtual void DeleteMin(); 68 | 69 | virtual size_t size() const; 70 | 71 | virtual bool empty() const; 72 | }; 73 | 74 | #endif 75 | -------------------------------------------------------------------------------- /theta.cpp: -------------------------------------------------------------------------------- 1 | #include "theta.h" 2 | #include "Bresenham.h" 3 | #include 4 | #include 5 | 6 | Theta::~Theta() { 7 | } 8 | 9 | double Theta::EuclidDistance(const Node &from, const Node &to, const EnvironmentOptions &options) const { 10 | return options.linecost * std::sqrt( 11 | (to.i - from.i) * (to.i - from.i) + (to.j - from.j) * (to.j - from.j) + (to.z - from.z) * (to.z - from.z)); 12 | } 13 | 14 | Node Theta::resetParent(Node current, Node parent, const Map &map, const EnvironmentOptions &options) { 15 | if (current.parent->parent != nullptr && 16 | (parent.parent->g + EuclidDistance(*(parent.parent), current, options) - current.g) < computation_eps 17 | && LineOfSight(map).line_of_sight(*(parent.parent), current)) { 18 | 19 | current.g = parent.parent->g + 20 | EuclidDistance(*(parent.parent), current, options); 21 | current.parent = parent.parent; 22 | } 23 | return current; 24 | } 25 | 26 | void Theta::makeSecondaryPath(const Map &map, Node curNode) { 27 | Liner liner(map, &lppath.List); 28 | std::list::iterator cur; 29 | for (auto it = hppath.List.begin(); it != --hppath.List.end();) { 30 | if (!lppath.List.empty()) { 31 | lppath.List.pop_back(); 32 | } 33 | cur = it; 34 | liner.append_line(*cur, *(++it)); 35 | } 36 | sresult.lppath = &lppath; 37 | } 38 | 39 | void Theta::makePrimaryPath(Node curNode) { 40 | Node current = curNode; 41 | while (current.parent != nullptr) { 42 | hppath.List.push_front(current); 43 | current = *current.parent; 44 | } 45 | hppath.List.push_front(current); 46 | sresult.hppath = &hppath; 47 | } 48 | 49 | -------------------------------------------------------------------------------- /asearch.cpp: -------------------------------------------------------------------------------- 1 | #include "mission.h" 2 | #include 3 | 4 | int main(int argc, char* argv[]) 5 | { 6 | if(argc < 2) 7 | { 8 | std::cout<<"Error! Pathfinding task file (XML) is not specified!"< 3 | #include 4 | #include "isearch.h" 5 | #include 6 | 7 | Astar::Astar() : ISearch() { } 8 | 9 | Astar::Astar(double w, int BT, int SL, int i) { 10 | hweight = w; 11 | breakingties = BT; 12 | } 13 | 14 | Astar::~Astar() { 15 | } 16 | 17 | double Astar::computeHFromCellToCell(int start_i, int start_j, int start_h, int fin_i, int fin_j, int fin_h, 18 | const EnvironmentOptions &options) { 19 | if (options.metrictype == CN_SP_MT_MANH) { 20 | return options.linecost * (abs(fin_i - start_i) + abs(fin_j - start_j) + abs(fin_h - start_h)); 21 | } 22 | if (options.metrictype == CN_SP_MT_CHEB) { 23 | return options.linecost * std::max(std::max(abs(fin_i - start_i), abs(fin_j - start_j)), abs(fin_h - start_h)); 24 | } 25 | if (options.metrictype == CN_SP_MT_EUCL) { 26 | return options.linecost * sqrt((fin_i - start_i) * (fin_i - start_i) + (fin_j - start_j) * (fin_j - start_j) + 27 | (fin_h - start_h) * (fin_h - start_h)); 28 | } 29 | if (options.metrictype == CN_SP_MT_DIAG) { 30 | int d_i = abs(fin_i - start_i); 31 | int d_j = abs(fin_j - start_j); 32 | int d_h = abs(fin_h - start_h); 33 | int diag = std::min(std::min(d_i, d_j), d_h); 34 | d_i -= diag; 35 | d_j -= diag; 36 | d_h -= diag; 37 | if (d_i == 0) { 38 | return options.linecost * sqrt(3) * diag + options.diagonalcost * std::min(d_j, d_h) + 39 | options.linecost * abs(d_j - d_h); 40 | } 41 | if (d_j == 0) { 42 | return options.linecost * sqrt(3) * diag + options.diagonalcost * std::min(d_i, d_h) + 43 | options.linecost * abs(d_i - d_h); 44 | } 45 | if (d_h == 0) { 46 | return options.linecost * sqrt(3) * diag + options.diagonalcost * std::min(d_i, d_j) + 47 | options.linecost * abs(d_i - d_j); 48 | } 49 | } 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /isearch.h: -------------------------------------------------------------------------------- 1 | #ifndef ISEARCH_H 2 | #define ISEARCH_H 3 | 4 | #include "list.h" 5 | #include "map.h" 6 | #include "ilogger.h" 7 | #include "searchresult.h" 8 | #include "environmentoptions.h" 9 | #include "node.h" 10 | 11 | #include 12 | #include 13 | 14 | class ISearch { 15 | public: 16 | ISearch(); 17 | 18 | virtual ~ISearch(void); 19 | 20 | SearchResult startSearch(ILogger *Logger, const Map &Map, const EnvironmentOptions &options); 21 | 22 | protected: 23 | Node findMin(int size); 24 | void deleteMin(Node minNode, uint_least32_t key); 25 | virtual void addOpen(Node newNode, uint_least32_t key); 26 | double MoveCost(int start_i, int start_j, int start_h, int fin_i, int fin_j, int fin_h, const EnvironmentOptions &options); 27 | virtual double computeHFromCellToCell(int start_i, int start_j, int start_h, int fin_i, int fin_j, int fin_h, 28 | const EnvironmentOptions &options) = 0; 29 | // Method which searches the expanded node successor, which satisfies search conditions 30 | virtual std::list findSuccessors(Node curNode, const Map &map, const EnvironmentOptions &options); 31 | virtual void makePrimaryPath(Node curNode); 32 | virtual void makeSecondaryPath(const Map &map, 33 | Node curNode); 34 | // Tries to changed node's parent on better one 35 | virtual Node resetParent(Node current, Node parent, const Map &map, 36 | const EnvironmentOptions &options) { return current; } 37 | virtual bool stopCriterion(); 38 | 39 | SearchResult sresult; 40 | NodeList lppath, hppath; // Found point by point and section paths 41 | std::unordered_map close; 42 | std::unordered_map *open; 43 | std::vector openMinimums; 44 | 45 | int openSize; 46 | float hweight; // Heuristic weight coefficient 47 | int breakingties; // ID of criterion which used for choosing between node with the same f-value 48 | 49 | }; 50 | 51 | #endif 52 | -------------------------------------------------------------------------------- /examples/simple_obstacle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | This file contains a task (map + start-goal location) for a pathfinder as well as some additional data 4 | 5 | Sample 3D Map 6 | 7 | 2 8 | 30 9 | 30 10 | 20 11 | 12 | 0 13 | 0 14 | 0 15 | 6 16 | 14 17 | 0 18 | 19 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 21 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 22 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 23 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 24 | 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 25 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 26 | 0 0 0 0 0 0 0 0 0 0 10 10 10 10 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 27 | 0 0 0 0 0 0 0 0 0 15 15 15 15 15 15 15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 28 | 0 0 0 0 0 0 0 0 0 15 15 15 15 15 15 15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 29 | 0 0 0 0 0 0 0 0 20 20 20 20 20 20 20 20 20 0 0 0 0 0 0 0 0 0 0 0 0 0 30 | 0 0 0 0 0 0 0 0 20 20 20 20 20 20 20 20 20 0 0 0 0 0 0 0 0 0 0 0 0 0 31 | 0 0 0 0 0 0 0 0 20 20 20 20 20 20 20 20 20 0 0 0 0 0 0 0 0 0 0 0 0 0 32 | 0 0 0 0 0 0 0 0 0 15 15 15 15 15 15 15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 33 | 0 0 0 0 0 0 0 0 0 15 15 15 15 15 15 15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 34 | 0 0 0 0 0 0 0 0 0 0 10 10 10 10 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 35 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 36 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 37 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 38 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 39 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 40 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 41 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 42 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 43 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 44 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 45 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 46 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 47 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 48 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 49 | 50 | 51 | 52 | astar 53 | 1 54 | euclid 55 | g-max 56 | 1 57 | 1.4 58 | 1 59 | 0 60 | 61 | 62 | 1 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /mission.cpp: -------------------------------------------------------------------------------- 1 | #include "mission.h" 2 | #include "astar.h" 3 | #include "bfs.h" 4 | #include "dijkstra.h" 5 | #include "theta.h" 6 | #include "xmllogger.h" 7 | #include "gl_const.h" 8 | 9 | Mission::Mission()//у config и map - есть свои конструкторы по умолчанию, их здесь не надо инициализировать. 10 | { 11 | logger = NULL; 12 | search = NULL; 13 | fileName = NULL; 14 | } 15 | 16 | Mission::Mission(const char *FileName) { 17 | fileName = FileName; 18 | logger = NULL; 19 | search = NULL; 20 | } 21 | 22 | Mission::~Mission() { 23 | if (logger != NULL) delete logger; 24 | if (search != NULL) delete search; 25 | } 26 | 27 | bool Mission::getMap() { 28 | return map.getMap(fileName); 29 | } 30 | 31 | bool Mission::getConfig() { 32 | return config.getConfig(fileName); 33 | } 34 | 35 | bool Mission::createLog() { 36 | if (logger != NULL) delete logger; 37 | logger = new XmlLogger(); 38 | logger->loglevel = config.SearchParams[CN_SP_LL]; 39 | return logger->getLog(fileName, config.LogParams); 40 | } 41 | 42 | void Mission::createEnvironmentOptions() { 43 | options.metrictype = config.SearchParams[CN_SP_MT]; 44 | options.allowdiagonal = config.SearchParams[CN_SP_AD]; 45 | options.allowsqueeze = config.SearchParams[CN_SP_AS]; 46 | options.linecost = config.SearchParams[CN_SP_LC]; 47 | options.diagonalcost = config.SearchParams[CN_SP_DC]; 48 | options.useresetparent = config.SearchParams[CN_SP_RP]; 49 | } 50 | 51 | void Mission::createSearch() { 52 | if (search != NULL) delete search; 53 | if (config.SearchParams[CN_SP_ST] == CN_SP_ST_ASTAR) { 54 | search = new Astar(config.SearchParams[CN_SP_HW], config.SearchParams[CN_SP_BT], config.SearchParams[CN_SP_SL], 55 | map.height); 56 | } else if (config.SearchParams[CN_SP_ST] == CN_SP_ST_DIJK) { 57 | search = new Dijkstra(map.height); 58 | } else if (config.SearchParams[CN_SP_ST] == CN_SP_ST_BFS) { 59 | search = new BFS(); 60 | } else if (config.SearchParams[CN_SP_ST] == CN_SP_ST_TH) { 61 | search = new Theta(config.SearchParams[CN_SP_HW], config.SearchParams[CN_SP_BT], config.SearchParams[CN_SP_SL], 62 | map.height); 63 | } else { 64 | std::cout << "Algorithm " << getAlgorithmName() 65 | << " is not implemented. Please use one of implemented algorithms: A*, Theta*, Dijkstra\nProgram halted!\n"; 66 | exit(0); 67 | } 68 | 69 | } 70 | 71 | void Mission::startSearch() { 72 | sr = search->startSearch(logger, map, options); 73 | } 74 | 75 | void Mission::printSearchResultsToConsole() { 76 | 77 | std::cout << "Path "; 78 | if (!sr.pathfound) 79 | std::cout << "NOT "; 80 | std::cout << "found!" << std::endl; 81 | 82 | std::cout << "numberofsteps=" << sr.numberofsteps << std::endl; 83 | std::cout << "nodescreated=" << sr.nodescreated << std::endl; 84 | 85 | if (sr.pathfound) 86 | std::cout << "pathlength=" << sr.pathlength << std::endl; 87 | std::cout << "time=" << sr.time << std::endl; 88 | 89 | } 90 | 91 | void Mission::saveSearchResultsToLog() { 92 | //Логгер - сам разберется писать ему лог или нет 93 | logger->writeToLogSummary(sr.numberofsteps, sr.nodescreated, sr.pathlength, sr.time); 94 | 95 | if (sr.pathfound) { 96 | logger->writeToLogPath(*sr.lppath); 97 | logger->writeToLogHPpath(*sr.hppath); 98 | logger->writeToLogMap(map, *sr.lppath); 99 | } else 100 | logger->writeToLogNotFound(); 101 | logger->saveLog(); 102 | } 103 | 104 | const char *Mission::getAlgorithmName() { 105 | if (config.SearchParams[CN_SP_ST] == CN_SP_ST_ASTAR) { 106 | return CNS_SP_ST_ASTAR; 107 | } else if (config.SearchParams[CN_SP_ST] == CN_SP_ST_DIJK) { 108 | return CNS_SP_ST_DIJK; 109 | } else if (config.SearchParams[CN_SP_ST] == CN_SP_ST_BFS) { 110 | return CNS_SP_ST_BFS; 111 | } else if (config.SearchParams[CN_SP_ST] == CN_SP_ST_JP_SEARCH) { 112 | return CNS_SP_ST_JP_SEARCH; 113 | } else if (config.SearchParams[CN_SP_ST] == CN_SP_ST_TH) { 114 | return CNS_SP_ST_TH; 115 | } else { 116 | return ""; 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /Bresenham.cpp: -------------------------------------------------------------------------------- 1 | #include "Bresenham.h" 2 | #include "node.h" 3 | #include 4 | #include 5 | 6 | void iBresenham::bresenham3d(int x1, int y1, int z1, const int x2, const int y2, const int z2) { 7 | 8 | int i, dx, dy, dz, l, m, n, x_inc, y_inc, z_inc, err_1, err_2, dx2, dy2, dz2; 9 | int point[3]; 10 | 11 | point[0] = x1; 12 | point[1] = y1; 13 | point[2] = z1; 14 | dx = x2 - x1; 15 | dy = y2 - y1; 16 | dz = z2 - z1; 17 | if (dx == 0) { 18 | x_inc = 0; 19 | } else if (dx < 0) { 20 | x_inc = -1; 21 | } else { 22 | x_inc = 1; 23 | } 24 | l = abs(dx); 25 | if (dy == 0) { 26 | y_inc = 0; 27 | } else if (dy < 0) { 28 | y_inc = -1; 29 | } else { 30 | y_inc = 1; 31 | } 32 | m = abs(dy); 33 | if (dz == 0) { 34 | z_inc = 0; 35 | } else if (dz < 0) { 36 | z_inc = -1; 37 | } else { 38 | z_inc = 1; 39 | } 40 | n = abs(dz); 41 | dx2 = l << 1; 42 | dy2 = m << 1; 43 | dz2 = n << 1; 44 | 45 | if ((l >= m) && (l >= n)) { 46 | err_1 = dy2 - l; 47 | err_2 = dz2 - l; 48 | for (i = 0; i < l; i++) { 49 | if (!ProcessPoint(point[0], point[1], point[2])) { 50 | return; 51 | } 52 | if (err_1 > 0) { 53 | point[1] += y_inc; 54 | err_1 -= dx2; 55 | } 56 | if (err_2 > 0) { 57 | point[2] += z_inc; 58 | err_2 -= dx2; 59 | } 60 | err_1 += dy2; 61 | err_2 += dz2; 62 | point[0] += x_inc; 63 | } 64 | } else if ((m >= l) && (m >= n)) { 65 | err_1 = dx2 - m; 66 | err_2 = dz2 - m; 67 | for (i = 0; i < m; i++) { 68 | if (!ProcessPoint(point[0], point[1], point[2])) { 69 | return; 70 | } 71 | if (err_1 > 0) { 72 | point[0] += x_inc; 73 | err_1 -= dy2; 74 | } 75 | if (err_2 > 0) { 76 | point[2] += z_inc; 77 | err_2 -= dy2; 78 | } 79 | err_1 += dx2; 80 | err_2 += dz2; 81 | point[1] += y_inc; 82 | } 83 | } else { 84 | err_1 = dy2 - n; 85 | err_2 = dx2 - n; 86 | for (i = 0; i < n; i++) { 87 | if (!ProcessPoint(point[0], point[1], point[2])) { 88 | return; 89 | } 90 | if (err_1 > 0) { 91 | point[1] += y_inc; 92 | err_1 -= dz2; 93 | } 94 | if (err_2 > 0) { 95 | point[0] += x_inc; 96 | err_2 -= dz2; 97 | } 98 | err_1 += dy2; 99 | err_2 += dx2; 100 | point[2] += z_inc; 101 | } 102 | } 103 | if (!ProcessPoint(point[0], point[1], point[2])) { 104 | return; 105 | } 106 | } 107 | 108 | LineOfSight::LineOfSight(const Map& init_map) : force_stopped(false), map(init_map) {} 109 | 110 | bool LineOfSight::ProcessPoint(int i, int j, int h) { 111 | if (map.CellIsObstacle(i, j, h)) { 112 | force_stopped = true; 113 | return false; 114 | } 115 | return true; 116 | } 117 | 118 | bool LineOfSight::line_of_sight(int i0, int j0, int h0, int i1, int j1, int h1) { 119 | bresenham3d(i0, j0, h0, i1, j1, h1); 120 | return !force_stopped; 121 | } 122 | 123 | bool LineOfSight::line_of_sight(const Node &from, const Node &to) { 124 | return line_of_sight(from.i, from.j, from.z, to.i, to.j, to.z); 125 | } 126 | 127 | Liner::Liner(const Map &init_map, std::list *init_path) : map(init_map), path(init_path) {} 128 | 129 | bool Liner::ProcessPoint(int i, int j, int h) { 130 | Node newNode; 131 | newNode.i = i; 132 | newNode.j = j; 133 | newNode.z = h; 134 | path->push_back(newNode); 135 | return true; 136 | } 137 | 138 | void Liner::append_line(int i0, int j0, int h0, int i1, int j1, int h1) { 139 | bresenham3d(i0, j0, h0, i1, j1, h1); 140 | } 141 | 142 | void Liner::append_line(const Node &from, const Node &to) { 143 | bresenham3d(from.i, from.j, from.z, to.i, to.j, to.z); 144 | } 145 | -------------------------------------------------------------------------------- /Queues.cpp: -------------------------------------------------------------------------------- 1 | #include "Queues.h" 2 | #include "node.h" 3 | #include "gl_const.h" 4 | 5 | bool iOpen::less(const Node &x, const Node &y) const { 6 | if (x.F == y.F) { 7 | switch (breaking_tie) { 8 | case CN_SP_BT_GMIN: 9 | return x.g < y.g; 10 | case CN_SP_BT_GMAX: 11 | default: 12 | return x.g > y.g; 13 | } 14 | } 15 | return x.F < y.F; 16 | } 17 | 18 | SortedList::SortedList(size_t size, int breakingtie) : data(size), size_(0), min_pos(size) { 19 | breaking_tie = breakingtie; 20 | } 21 | 22 | size_t SortedList::size() const { 23 | return size_; 24 | } 25 | 26 | bool SortedList::empty() const { 27 | return (size_ == 0); 28 | } 29 | 30 | bool SortedList::Insert(const Node &newNode) { 31 | std::list::iterator iter, pos; 32 | 33 | bool posFound = false; 34 | 35 | pos = data[newNode.i].end(); 36 | 37 | if (data[newNode.i].empty()) { 38 | data[newNode.i].push_back(newNode); 39 | ++size_; 40 | return true; 41 | } 42 | 43 | for (iter = data[newNode.i].begin(); iter != data[newNode.i].end(); ++iter) { 44 | if (!posFound && !less(*iter, newNode)) { 45 | pos = iter; 46 | posFound = true; 47 | } 48 | 49 | if (iter->j == newNode.j && iter->z == newNode.z) { 50 | if (newNode.F >= iter->F) { 51 | return false; 52 | } else { 53 | if (pos == iter) { 54 | iter->g = newNode.g; 55 | iter->F = newNode.F; 56 | iter->H = newNode.H; 57 | return true; 58 | } 59 | data[newNode.i].erase(iter); 60 | --size_; 61 | break; 62 | } 63 | } 64 | } 65 | ++size_; 66 | data[newNode.i].insert(pos, newNode); 67 | return true; 68 | } 69 | 70 | Node SortedList::FindMin() const { 71 | Node min; 72 | min.F = -1; 73 | for (size_t i = 0; i < data.size(); i++) { 74 | if (!data[i].empty()) 75 | if (min.F == -1 || less(*data[i].begin(), min)) { 76 | min = *data[i].begin(); 77 | min_pos = i; 78 | } 79 | } 80 | return min; 81 | } 82 | 83 | void SortedList::DeleteMin() { 84 | if (min_pos >= data.size()) { 85 | FindMin(); 86 | } 87 | data[min_pos].pop_front(); 88 | --size_; 89 | min_pos = data.size(); 90 | } 91 | 92 | ClusteredSets::ClusteredSets(size_t size, int breakingtie) : loc_mins(size), data(size), size_(0), min_pos(size) { 93 | breaking_tie = breakingtie; 94 | } 95 | 96 | size_t ClusteredSets::size() const { 97 | return size_; 98 | } 99 | 100 | bool ClusteredSets::empty() const { 101 | return (size_ == 0); 102 | } 103 | 104 | bool ClusteredSets::Insert(const Node &NewNode) { 105 | bool node_found = false; 106 | bool updated = false; 107 | 108 | auto pos = data[NewNode.i].find(NewNode); 109 | 110 | if (pos != data[NewNode.i].end()) { 111 | node_found = true; 112 | if (NewNode.g < pos->g) { 113 | data[NewNode.i].erase(pos); 114 | data[NewNode.i].insert(NewNode); 115 | updated = true; 116 | } else { 117 | return false; 118 | } 119 | } 120 | 121 | if (!node_found) { 122 | updated = true; 123 | data[NewNode.i].insert(NewNode); 124 | ++size_; 125 | } 126 | if (data[NewNode.i].size() == 1 || less(NewNode, loc_mins[NewNode.i])) { 127 | loc_mins[NewNode.i] = NewNode; 128 | } 129 | return updated; 130 | } 131 | 132 | Node ClusteredSets::FindMin() const { 133 | for (min_pos = 0; data[min_pos].empty(); ++min_pos) {} 134 | for (size_t i = min_pos + 1; i < loc_mins.size(); ++i) { 135 | if (!data[i].empty() && less(loc_mins[i], loc_mins[min_pos])) { 136 | min_pos = i; 137 | } 138 | } 139 | return loc_mins[min_pos]; 140 | } 141 | 142 | void ClusteredSets::DeleteMin() { 143 | if (min_pos == loc_mins.size()) { 144 | FindMin(); 145 | } 146 | 147 | data[min_pos].erase(loc_mins[min_pos]); 148 | --size_; 149 | Node min; 150 | if (!data[min_pos].empty()) { 151 | auto it = data[min_pos].begin(); 152 | min = *(it++); 153 | for (; it != data[min_pos].end(); ++it) { 154 | if (less(*it, min)) { 155 | min = *it; 156 | } 157 | } 158 | 159 | loc_mins[min_pos] = min; 160 | } 161 | min_pos = loc_mins.size(); 162 | } 163 | -------------------------------------------------------------------------------- /gl_const.h: -------------------------------------------------------------------------------- 1 | #ifndef GL_CONST_H 2 | #define GL_CONST_H 3 | 4 | /* 5 | * XML file tags --------------------------------------------------------------- 6 | */ 7 | #define CNS_TAG_ROOT "root" 8 | 9 | #define CNS_TAG_MAP "map" 10 | #define CNS_TAG_WIDTH "width" 11 | #define CNS_TAG_HEIGHT "height" 12 | #define CNS_TAG_STX "startx" 13 | #define CNS_TAG_STY "starty" 14 | #define CNS_TAG_STZ "startz" 15 | #define CNS_TAG_FINX "finishx" 16 | #define CNS_TAG_FINY "finishy" 17 | #define CNS_TAG_FINZ "finishz" 18 | #define CNS_TAG_GRID "grid" 19 | #define CNS_TAG_ROW "row" 20 | #define CNS_TAG_MAXALT "maxaltitude" 21 | #define CNS_TAG_ALTLIM "altitudelimits" 22 | #define CNS_TAG_ALTLIM_ATTR_MIN "min" 23 | #define CNS_TAG_ALTLIM_ATTR_MAX "max" 24 | 25 | #define CNS_TAG_ALG "algorithm" 26 | #define CNS_TAG_ST "searchtype" 27 | #define CNS_TAG_HW "hweight" 28 | #define CNS_TAG_MT "metrictype" 29 | #define CNS_TAG_BT "breakingties" 30 | #define CNS_TAG_SL "sizelimit" 31 | #define CNS_TAG_AS "allowsqueeze" 32 | #define CNS_TAG_LC "linecost" 33 | #define CNS_TAG_DC "diagonalcost" 34 | #define CNS_TAG_AD "allowdiagonal" 35 | #define CNS_TAG_AC "cutcorners" 36 | #define CNS_TAG_RP "useresetparent" 37 | 38 | #define CNS_TAG_OPT "options" 39 | #define CNS_TAG_LOGLVL "loglevel" 40 | #define CNS_TAG_LOGPATH "logpath" 41 | #define CNS_TAG_LOGFN "logfilename" 42 | 43 | #define CNS_TAG_LOG "log" 44 | #define CNS_TAG_MAPFN "mapfilename" 45 | #define CNS_TAG_SUM "summary" 46 | #define CNS_TAG_PATH "path" 47 | #define CNS_TAG_LPLEVEL "lplevel" 48 | #define CNS_TAG_HPLEVEL "hplevel" 49 | #define CNS_TAG_SECTION "section" 50 | #define CNS_TAG_LOWLEVEL "lowlevel" 51 | #define CNS_TAG_STEP "step" 52 | #define CNS_TAG_OPEN "open" 53 | #define CNS_TAG_POINT "node" 54 | #define CNS_TAG_CLOSE "close" 55 | 56 | /* 57 | * End of XML files tags ------------------------------------------------------- 58 | */ 59 | 60 | /* 61 | * XML files tag's attributes -------------------------------------------------- 62 | */ 63 | #define CNS_TAG_ATTR_NUMOFSTEPS "numberofsteps" 64 | #define CNS_TAG_ATTR_NODESCREATED "nodescreated" 65 | #define CNS_TAG_ATTR_LENGTH "length" 66 | #define CNS_TAG_ATTR_TIME "time" 67 | #define CNS_TAG_ATTR_X "x" 68 | #define CNS_TAG_ATTR_Y "y" 69 | #define CNS_TAG_ATTR_Z "z" 70 | #define CNS_TAG_ATTR_NUM "number" 71 | #define CNS_TAG_ATTR_F "F" 72 | #define CNS_TAG_ATTR_G "g" 73 | #define CNS_TAG_ATTR_PARX "parent_x" 74 | #define CNS_TAG_ATTR_PARY "parent_y" 75 | #define CNS_TAG_ATTR_PARZ "parent_z" 76 | #define CNS_TAG_ATTR_STX "start.x" 77 | #define CNS_TAG_ATTR_STY "start.y" 78 | #define CNS_TAG_ATTR_STZ "start.z" 79 | #define CNS_TAG_ATTR_FINX "finish.x" 80 | #define CNS_TAG_ATTR_FINY "finish.y" 81 | #define CNS_TAG_ATTR_FINZ "finish.z" 82 | 83 | 84 | /* 85 | * End of XML files tag's attributes ------------------------------------------- 86 | */ 87 | 88 | /* 89 | * Configuration. SearchParams array ------------------------------------------- 90 | */ 91 | #define CN_SP_ST 0 92 | 93 | #define CNS_SP_ST_BFS "bfs" 94 | #define CNS_SP_ST_JP_SEARCH "jp_search" 95 | #define CNS_SP_ST_DIJK "dijkstra" 96 | #define CNS_SP_ST_ASTAR "astar" 97 | #define CNS_SP_ST_TH "theta" 98 | 99 | #define CN_SP_ST_BFS 0 100 | #define CN_SP_ST_DIJK 1 101 | #define CN_SP_ST_ASTAR 2 102 | #define CN_SP_ST_JP_SEARCH 3 103 | #define CN_SP_ST_TH 4 104 | 105 | 106 | #define CN_SP_LL 1 107 | 108 | #define CN_SP_LL_NOLOG 0 109 | #define CN_SP_LL_TINY 0.5 110 | #define CN_SP_LL_SMALLLOG 1 111 | #define CN_SP_LL_FULLLOG 2 112 | #define CN_SP_LL_PARTIALLOG 1.5 113 | 114 | #define CN_SP_LL_NOLOG_WORD "none" 115 | #define CN_SP_LL_TINY_WORD "tiny" 116 | #define CN_SP_LL_SMALLLOG_WORD "short" 117 | #define CN_SP_LL_FULLLOG_WORD "medium" 118 | #define CN_SP_LL_PARTIALLOG_WORD "full" 119 | 120 | #define CN_SP_AS 2 //AllowSqueeze 121 | 122 | #define CN_SP_AS_TRUE 1 123 | #define CN_SP_AS_FALSE 0 124 | 125 | #define CN_SP_AC_TRUE 1 126 | #define CN_SP_AC_FALSE 0 127 | 128 | #define CN_SP_LC 3 //LineCost 129 | 130 | #define CN_SP_DC 4 //DiagonalCost 131 | 132 | #define CN_SP_AD 5 //AllowDiagonal 133 | 134 | #define CN_SP_AC 6 //AllowCutcorners 135 | #define CN_SP_AD_TRUE 1 136 | #define CN_SP_AD_FALSE 0 137 | 138 | #define CN_SP_HW 6 //HWeight 139 | 140 | #define CN_SP_MT 7 //MetricType 141 | 142 | #define CNS_SP_MT_DIAG "diagonal" 143 | #define CNS_SP_MT_MANH "manhattan" 144 | #define CNS_SP_MT_EUCL "euclid" 145 | #define CNS_SP_MT_CHEB "chebyshev" 146 | 147 | #define CN_SP_MT_DIAG 0 148 | #define CN_SP_MT_MANH 1 149 | #define CN_SP_MT_EUCL 2 150 | #define CN_SP_MT_CHEB 3 151 | 152 | #define CN_SP_BT 8 153 | 154 | #define CNS_SP_BT_GMIN "g-min" 155 | #define CNS_SP_BT_GMAX "g-max" 156 | 157 | #define CN_SP_BT_GMIN 1 158 | #define CN_SP_BT_GMAX 2 159 | 160 | #define CN_SP_SL 9 161 | #define CN_SP_SL_NOLIMIT -1 //����� ����� ��������� ���� ������ ���� ����� ����! 162 | 163 | #define CN_SP_RP 10 //UseResetParent 164 | 165 | 166 | #define CN_LP_LPATH 0 167 | #define CN_LP_LNAME 1 168 | /* 169 | * End Configuration ----------------------------------------------------------- 170 | */ 171 | 172 | /* 173 | * Move Cost ------------------------------------------------------------------- 174 | */ 175 | #define CN_MC_LINE 10 176 | #define CN_MC_DIAG 14 177 | /* 178 | * End of Move Cost ------------------------------------------------------------ 179 | */ 180 | 181 | /* 182 | * Grid Cell ------------------------------------------------------------------- 183 | */ 184 | #define CN_GC_NOOBS 0 //������ ��������� 185 | //#define CN_GC_OBS 1 //���������� 186 | /* 187 | * End of Grid Cell ------------------------------------------------------------ 188 | */ 189 | 190 | /* 191 | * Other ----------------------------------------------------------------------- 192 | */ 193 | #define CNS_OTHER_PATHSELECTION "*" 194 | #define CNS_OTHER_MATRIXSEPARATOR ' ' 195 | #define CN_OTHER_GVALUEOFNOWAY -1 196 | /* 197 | * End of other ---------------------------------------------------------------- 198 | */ 199 | #endif 200 | 201 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 3D-AStar-ThetaStar 2 | Basic algorithms for grid-based 3D (map of heights) path finding. 3 | 4 | Description 5 | ========== 6 | This project contains implementations of the following algorithms: 7 | >- Dijkstra's algorithm 8 | >- A* 9 | >- Theta* 10 | 11 | Build and Launch 12 | ================ 13 | To build the project you can use QtCreator or CMake. Both .pro and CMakeLists.txt projects files are available in the repository. 14 | 15 | Your compiler must support C++ 11 standard to compile a project 16 | 17 | Input and Output files 18 | ====================== 19 | Project uses specially structured xml files for getting task (map, search options, start and finish coordinates) and generating resulting path. 20 | 21 | You can find examples of input and output files in _examples_ directory in repository. 22 | ####Input file should contain: 23 | - Mandatory tag \. It describes the environment. 24 | * **\** and **\** - mandatory tags that defines size of the map. Origin is in the upper left corner. (0,0) - is upper left, (*width*-1, *height*-1) is lower right. 25 | * **\** - optional tag that defines the maximal height of obstacle on the map. 26 | * **\** - optional tag that means that agent can't move higher than **b** and lower than **a**. **a** and **b** must be _ints_ **≥ 0**. 27 | * **\**, **\** and **\** - mandatory tags that defines coordinates of the start location. it can pe interpreted as horizontal (X) and vertical (Y) offset from the upper left corner anh height (Z) from the ground level of start point. 0 ≤ **startx** ≤ **width** - 1 and 0 ≤ **starty** ≤ **height** - 1. If **\** is specified **a** ≤ **startz** ≤ **b**. 28 | * **\**, **\** and **\** - mandatory tags that defines coordinates of the goal location. The same limitations as for **\**, **\**, **\** tags. 29 | * **\** - mandatory tag that describes the square grid constituting the map. It consists of **\** tags. Each **\** contains a sequence of non negative ints separated by blanks. Each number defines height of obstacle on this cell. "0" means that cell is fully traversable. 30 | * **\** - optional tag that defines the size of one cell. One might add it to calculate scaled length of the path. 31 | * **\**, **\<URL>**, **\<coordinates>**, etc - optional tags containing additional information on the map. 32 | - Mandatory tag <b>\<algorithm></b>. It describes the parameters of the algorithm. 33 | * **\<searchtype>** - mandatory tag that defines the planner algorithm. Possible values - "astar", "theta", "bfs", "dijkstra". 34 | * **\<metrictype>** - defines the type of metric for heuristic function. Possible values - "euclidean", "diagonal", "manhattan", "chebyshev". Default value is "euclidean". 35 | * **\<hweight>** - defines the weight of heuristic function. Default value is "1". 36 | * **\<breakingties>** - defines the priority in OPEN list when nodes have the equal F-values. Possible values - "g-min", "g-max". Default value is "g-max". 37 | * **\<allowdiagonal>** - boolean tag that defines the possibility to make diagonal moves. Setting it to "false" restricts agent to make cardinal (horizonal, vertical) moves only. If Theta* algorithm is chosen, it will generate only cardinal successors during expansion of current node, but after resetting parent it will probably break this restriction. Default value is "true". 38 | * **\<cutcorners>** - boolean tag that defines the possibilty to make diagonal moves when one adjacent cell is untraversable. The tag is ignored if diagonal moves are not allowed. Default value is "false". 39 | * **\<allowsqueeze>** - boolean tag that defines the possibility to make diagonal moves when both adjacent cells are untraversable. The tag is ignored if cutting corners is not allowed. Default value is "false". 40 | - Optional tag <b>\<options></b>. Options that are not related to search. 41 | * **\<loglevel>** - defines the level of detalization of log-file. Default value is "1". Possible values: 42 | * "0" or "none" - log-file is not created. 43 | * "0.5" or "tiny" - All the input data is copied to the log-file plus short **\<summary>** is appended. **\<summary>** contains info of the path length, number of steps, elapsed time, etc. 44 | * "1" or "short" - *0.5*-log plus **\<path>** is appended. It looks like **\<grid>** but cells forming the path are marked by "\*" instead of "0". The following tags are also appended: **\<hplevel>** and **\<lplevel>**. **\<lplevel>** is the sequence of coordinates of cells forming the path (in case Theta* planner is used, this sequence is formed at post-processing step by invoking sequantually line-of-sight procedure on path's segments). **\<hplevel>** is the sequence of sections forming the path (in case planner other from Theta* is used, sections are formed at post-processing step using naive procedure). 45 | * **\<logpath>** - defines the directory where the log-file should be written. If not specified directory of the input file is used. 46 | * **\<logname>** - defines the name of log-file. If not specified the name of the log file is: "input file name"+"_log"+input file extension. 47 | ####Output file structure: 48 | Output file contains the same information as input file. 49 | 50 | Additionally it contains **\<log>** tag. 51 | 52 | Depends on **loglevel** set in the input file **\<log>** tag may contain the next tags: 53 | 54 | - **\<mapfilename>** - tag which defines the path to the source input file. 55 | - **\<summary numberofsteps=(int) nodescreated=(int) length=(double) time=(double)>** - tag that contains summary of search results as tag atributes. 56 | - **\<path>** - tag that contains the path top view. It the same structure as **\<grid>** but cells forming the path are marked by "\*". 57 | - **\<lplevel>** - tag that defines point by point path representation. It contains the list of **\<node x=(int) y=(int) z=(int) number=(int) />** tags, where x, y, z - coordinates of the next cell in path, number - number of node in path. 58 | - **\<hplevel>** - tag that defines section path representation. It contains the list of **\<section number=(int) start.x=(int) start.y=(int) start.z=(int) finish.x=(int) finish.y=(int) finish.z=(int) length=(double) />** tags, where start.x, start.y, start.z - coordinated of section beginning, finish.x, finish.y, finish.z - section ending, length - length of section -------------------------------------------------------------------------------- /tools/process.py: -------------------------------------------------------------------------------- 1 | #!./venv/bin/python3 2 | 3 | import multiprocessing 4 | import subprocess 5 | import fractions 6 | import xml.etree.ElementTree as ET 7 | 8 | import re 9 | from PIL import Image, ImageDraw, ImageFont 10 | 11 | SETTINGS = { 12 | 'max_treads': 5, 13 | 'EMPTY_COLOR': (255, 255, 255), 14 | 'PATH_COLOR': (0, 0, 255), 15 | 'OBSTACLE_COLOR': (0, 0, 0), 16 | 'START_COLOR': (0, 255, 0), 17 | 'FINISH_COLOR': (255, 0, 0), 18 | 'CLOSED_COLOR': (153, 88, 61), 19 | 'OPENED_COLOR': (204, 74, 20), 20 | 'TEXT_COLOR': (0, 0, 0), 21 | } 22 | 23 | 24 | def parse_log(filename, shell=False): 25 | parse_result = {} 26 | 27 | tree = ET.parse(filename) 28 | root = tree.getroot() 29 | map = root.find('map') 30 | try: 31 | parse_result["title"] = map.find('title').text 32 | except AttributeError: 33 | parse_result["title"] = None 34 | parse_result["width"] = int(map.find("width").text) 35 | parse_result["height"] = int(map.find("height").text) 36 | try: 37 | parse_result['max_level'] = int(map.find("maxaltitude").text) 38 | except AttributeError: 39 | parse_result["max_level"] = None 40 | print("Couldn't find <maxaltitude> attribute image will be monochromatic") 41 | 42 | try: 43 | parse_result["cellsize"] = int(map.find("cellsize").text) 44 | except AttributeError: 45 | print("Couldn't find size of cell (attribute <cellsize>) in {}. Would be ignored.".format(filename)) 46 | parse_result['start'] = (int(map.find("startx").text), int(map.find("starty").text)) 47 | parse_result['finish'] = (int(map.find("finishx").text), int(map.find("finishy").text)) 48 | 49 | parse_result['map'] = [] 50 | for plain in map.find('grid'): 51 | parse_result['map'].append([int(i) for i in plain.text.split()]) 52 | 53 | algo_name = root.find('algorithm').find('searchtype').text.lower() 54 | if algo_name in {'bfs', 'jp_search', 'dijkstra', 'astar'}: 55 | any_angle_search = False 56 | else: 57 | any_angle_search = True 58 | 59 | log = root.find('log') 60 | 61 | path = [] 62 | closed = set() 63 | opened = set() 64 | if log.find('path').text != 'Path NOT found!': 65 | level = log.find('lplevel') 66 | # For all paths 'lppath' section is used 67 | if (True or not any_angle_search and level is not None): 68 | path = set() 69 | for node in level.iter('node'): 70 | path.add((int(node.get('x')), int(node.get('y')))) 71 | else: 72 | parse_result['section_path'] = True 73 | level = log.find('hplevel') 74 | section = level.find('section') 75 | path.append((int(section.get('start.x')), int(section.get('start.y')))) 76 | for section in level.iter('section'): 77 | path.append((int(section.get('finish.x')), int(section.get('finish.y')))) 78 | 79 | level = log.find('viewed') 80 | if level is None: 81 | if shell: 82 | print("Can not find viewed section. Points visited by algorithm won't be shown for {}.".format(filename)) 83 | else: 84 | for node in level.iter('node'): 85 | if (node.get('closed')): 86 | closed.add((int(node.get('x')), int(node.get('y')))) 87 | else: 88 | opened.add((int(node.get('x')), int(node.get('y')))) 89 | 90 | parse_result['section_path'] = False 91 | parse_result['closed_list'] = closed 92 | parse_result['opened_list'] = opened 93 | parse_result['path'] = path 94 | 95 | return parse_result 96 | 97 | 98 | def illustrate(parsed_data, output_filename, output_format="PNG", scale=2): 99 | scale = int(scale) 100 | scale = 1 if scale == 0 else scale 101 | height = parsed_data['height'] 102 | width = parsed_data['width'] 103 | start = parsed_data['start'] 104 | finish = parsed_data['finish'] 105 | 106 | text_zone_height = 0 107 | 108 | im = Image.new("RGB", (scale * width, scale * (height + text_zone_height)), color=SETTINGS['EMPTY_COLOR']) 109 | 110 | dr = ImageDraw.Draw(im) 111 | 112 | for x in range(width): 113 | for y in range(height): 114 | if (x, y) in parsed_data['opened_list']: 115 | color = SETTINGS['OPENED_COLOR'] 116 | elif (x, y) in parsed_data['closed_list']: 117 | color = SETTINGS['CLOSED_COLOR'] 118 | elif (x, y) == start: 119 | color = SETTINGS["START_COLOR"] 120 | elif (x, y) == finish: 121 | color = SETTINGS["FINISH_COLOR"] 122 | elif not parsed_data['section_path'] and (x, y) in parsed_data['path']: 123 | color = SETTINGS['PATH_COLOR'] 124 | elif parsed_data['map'][y][x]: 125 | if parsed_data['max_level'] is not None: 126 | color = [0] * len(SETTINGS['OBSTACLE_COLOR']) 127 | for i in range(len(SETTINGS['OBSTACLE_COLOR'])): 128 | color[i] = SETTINGS['EMPTY_COLOR'][i] + parsed_data['map'][y][x] * ( 129 | SETTINGS['OBSTACLE_COLOR'][i] - SETTINGS['EMPTY_COLOR'][i]) / parsed_data['max_level'] 130 | color[i] = int(color[i]) 131 | color = tuple(color) 132 | 133 | else: 134 | color = SETTINGS['OBSTACLE_COLOR'] 135 | else: 136 | color = SETTINGS['EMPTY_COLOR'] 137 | 138 | dr.rectangle([(scale * x, scale * y), (scale * x + scale, scale * y + scale)], fill=color) 139 | 140 | if parsed_data['section_path']: 141 | dr.line(list(map(lambda elem: (scale * elem[0], scale * elem[1]), parsed_data['path'])), 142 | fill=SETTINGS['PATH_COLOR'], width=scale) 143 | del dr 144 | im.save(output_filename, output_format) 145 | 146 | 147 | def get_log_output_filename(task_filename): 148 | tree = ET.parse(task_filename) 149 | root = tree.getroot() 150 | logpath = root.find('options').find('logpath') 151 | path = logpath.text 152 | if path is not None: 153 | return path 154 | m = re.match(r'(?P<name>.+)\.xml', task_filename) 155 | return m.group('name') + "_log.xml" 156 | 157 | 158 | def make_path(exec_filename, input_filename): 159 | subprocess.run([exec_filename, input_filename], 160 | stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) 161 | 162 | 163 | def make_path_and_picture(exec_filename, input_filename, log_filename, picture_filename, scale=2, picture_format='PNG'): 164 | code = subprocess.run([exec_filename, input_filename], 165 | stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT).returncode 166 | if code == 0: 167 | data = parse_log(log_filename) 168 | illustrate(data, picture_filename, picture_format, scale) 169 | print("{} processed successfully".format(input_filename)) 170 | else: 171 | print("Error has occurred during searching path for {}.\ 172 | Program has finished with exit code {}".format(input_filename, code)) 173 | 174 | 175 | if __name__ == "__main__": 176 | import argparse 177 | from os import listdir, cpu_count, path 178 | 179 | parser = argparse.ArgumentParser() 180 | parser.add_argument("--exe", required=True, help="Путь к исполняемому файлу проекта") 181 | parser.add_argument("--test", required=True, help="Путь к папке с заданиями в формате XML или единичному файлу") 182 | parser.add_argument("--scale", required=False, type=int, 183 | help="Масштаб карты, относительно заданного в файле", default=2) 184 | parser.add_argument("--no_image", required=False, help="Не генерировать изображения к результату", type=bool) 185 | args = parser.parse_args() 186 | exec_path = path.abspath(args.exe) 187 | if not path.isfile(exec_path): 188 | print("Incorrect path to the executable") 189 | exit(1) 190 | dir_path = path.abspath(args.test) 191 | if path.isdir(dir_path): 192 | files = listdir(dir_path) 193 | elif path.isfile(dir_path): 194 | files = [dir_path] 195 | dir_path = path.dirname(dir_path) 196 | else: 197 | print("Incorrect path to the test") 198 | exit(1) 199 | 200 | tasks = {} 201 | for filename in files: 202 | m = re.match(r'(?P<name>.+)(?<!_log)\.xml', filename) 203 | if m: 204 | tasks[path.join(dir_path, filename)] = (get_log_output_filename(path.join(dir_path, filename)), 205 | path.join(dir_path, m.group('name') + '.plain.png')) 206 | 207 | with multiprocessing.Pool(min(SETTINGS['max_treads'], cpu_count())) as pool: 208 | for inp_path, val in tasks.items(): 209 | if args.no_image: 210 | pool.apply_async(make_path, [exec_path, inp_path]) 211 | else: 212 | pool.apply_async(make_path_and_picture, [exec_path, inp_path, val[0], val[1], args.scale]) 213 | pool.close() 214 | pool.join() 215 | -------------------------------------------------------------------------------- /xmllogger.cpp: -------------------------------------------------------------------------------- 1 | #include "xmllogger.h" 2 | #include "tinyxml2.h" 3 | #include "gl_const.h" 4 | #include "node.h" 5 | #include <sstream> 6 | #include <iostream> 7 | 8 | using tinyxml2::XMLElement; 9 | using tinyxml2::XMLNode; 10 | 11 | bool XmlLogger::getLog(const char *FileName, const std::string *LogParams) { 12 | if (loglevel == CN_SP_LL_NOLOG) return true; 13 | 14 | if (doc.LoadFile(FileName) != tinyxml2::XMLError::XML_SUCCESS) { 15 | std::cout << "Error opening input XML file" << std::endl; 16 | return false; 17 | } 18 | 19 | if (LogParams[CN_LP_LPATH] == "" && LogParams[CN_LP_LNAME] == "") { 20 | std::string str; 21 | str.append(FileName); 22 | size_t found = str.find_last_of("."); 23 | if (found != std::string::npos) 24 | str.insert(found, "_log"); 25 | else 26 | str.append("_log"); 27 | LogFileName.append(str); 28 | } else if (LogParams[CN_LP_LPATH] == "") { 29 | LogFileName.append(FileName); 30 | std::string::iterator it = LogFileName.end(); 31 | while (*it != '\\') 32 | it--; 33 | it++; 34 | LogFileName.erase(it, LogFileName.end()); 35 | LogFileName.append(LogParams[CN_LP_LNAME]); 36 | } else if (LogParams[CN_LP_LNAME] == "") { 37 | LogFileName.append(LogParams[CN_LP_LPATH]); 38 | if (*(--LogParams[CN_LP_LPATH].end()) != '\\') LogFileName.append("\\"); 39 | std::string lfn; 40 | lfn.append(FileName); 41 | size_t found = lfn.find_last_of("\\"); 42 | std::string str = lfn.substr(found); 43 | found = str.find_last_of("."); 44 | if (found != std::string::npos) 45 | str.insert(found, "_log"); 46 | else 47 | str.append("_log"); 48 | LogFileName.append(str); 49 | } else { 50 | LogFileName.append(LogParams[CN_LP_LPATH]); 51 | if (*(--LogParams[CN_LP_LPATH].end()) != '\\') LogFileName.append("\\"); 52 | LogFileName.append(LogParams[CN_LP_LNAME]); 53 | } 54 | 55 | XMLElement *log, *root = doc.FirstChildElement(CNS_TAG_ROOT); 56 | 57 | if (!root) { 58 | std::cout << "No '" << CNS_TAG_ROOT << "' element found in XML file" << std::endl; 59 | std::cout << "Can not create log" << std::endl; 60 | return false; 61 | } 62 | 63 | root->InsertEndChild(doc.NewElement(CNS_TAG_LOG)); 64 | 65 | root = (root->LastChild())->ToElement(); 66 | 67 | if (loglevel == CN_SP_LL_SMALLLOG || loglevel == CN_SP_LL_FULLLOG || loglevel == CN_SP_LL_PARTIALLOG) { 68 | log = doc.NewElement(CNS_TAG_MAPFN); 69 | log->InsertEndChild(doc.NewText(FileName)); 70 | root->InsertEndChild(log); 71 | 72 | root->InsertEndChild(doc.NewElement(CNS_TAG_SUM)); 73 | 74 | root->InsertEndChild(doc.NewElement(CNS_TAG_PATH)); 75 | 76 | root->InsertEndChild(doc.NewElement(CNS_TAG_LPLEVEL)); 77 | 78 | root->InsertEndChild(doc.NewElement(CNS_TAG_HPLEVEL)); 79 | } 80 | 81 | if (loglevel == CN_SP_LL_FULLLOG || loglevel == CN_SP_LL_PARTIALLOG) { 82 | root->InsertEndChild(doc.NewElement(CNS_TAG_LOWLEVEL)); 83 | } 84 | 85 | return true; 86 | } 87 | 88 | void XmlLogger::saveLog() { 89 | if (loglevel == CN_SP_LL_NOLOG) return; 90 | doc.SaveFile(LogFileName.c_str()); 91 | } 92 | 93 | void XmlLogger::writeToLogMap(const Map &map, const NodeList &path) { 94 | if (loglevel == CN_SP_LL_NOLOG || loglevel == CN_SP_LL_TINY) return; 95 | 96 | int iterate = 0; 97 | std::stringstream stream; 98 | std::string str; 99 | NodeList temp = path; 100 | 101 | XMLElement *mapTag = doc.FirstChildElement(CNS_TAG_ROOT); 102 | mapTag = mapTag->FirstChildElement(CNS_TAG_LOG)->FirstChildElement(CNS_TAG_PATH); 103 | 104 | for (int i = 0; i < map.height; i++, iterate++) { 105 | XMLElement *element = doc.NewElement(CNS_TAG_ROW); 106 | element->SetAttribute(CNS_TAG_ATTR_NUM, iterate); 107 | 108 | for (int j = 0; j < map.width; j++) { 109 | if (!temp.find(i, j)) { 110 | stream << map.Grid[i][j]; 111 | str += stream.str(); 112 | stream.str(""); 113 | stream.clear(); 114 | } else { 115 | str += CNS_OTHER_PATHSELECTION; 116 | } 117 | str += CNS_OTHER_MATRIXSEPARATOR; 118 | } 119 | 120 | element->InsertEndChild(doc.NewText(str.c_str())); 121 | mapTag->InsertEndChild(element); 122 | str.clear(); 123 | } 124 | } 125 | 126 | void XmlLogger::writeToLogOpenClose(const NodeList *open, const std::unordered_set<Node> &close, int size, 127 | bool summary = false) { 128 | 129 | if (loglevel == CN_SP_LL_NOLOG || loglevel == CN_SP_LL_TINY || loglevel == CN_SP_LL_SMALLLOG || 130 | (loglevel == CN_SP_LL_PARTIALLOG && !summary)) 131 | return; 132 | int iterate = 1; 133 | XMLElement *element = doc.NewElement(CNS_TAG_STEP); 134 | XMLElement *child , *lowlevel = doc.FirstChildElement(CNS_TAG_ROOT); 135 | lowlevel = lowlevel->FirstChildElement(CNS_TAG_LOG)->FirstChildElement(CNS_TAG_LOWLEVEL); 136 | child = lowlevel->FirstChildElement(); 137 | 138 | while (child = child->NextSiblingElement()) iterate++; 139 | 140 | element->SetAttribute(CNS_TAG_ATTR_NUM, iterate); 141 | lowlevel->InsertEndChild(element); 142 | lowlevel = lowlevel->LastChildElement(); 143 | 144 | lowlevel->InsertEndChild(doc.NewElement(CNS_TAG_OPEN)); 145 | child = lowlevel->LastChildElement(); 146 | 147 | Node min; 148 | min.F = -1; 149 | int exc = 0; 150 | for (int i = 0; i < size; i++) { 151 | if (open[i].List.size() > 0) { 152 | if (open[i].List.begin()->F <= min.F || min.F == -1) { 153 | if (open[i].List.begin()->F == min.F && open[i].List.begin()->g > min.g) { 154 | min = *open[i].List.begin(); 155 | exc = i; 156 | } else if (open[i].List.begin()->F < min.F || min.F == -1) { 157 | min = *open[i].List.begin(); 158 | exc = i; 159 | } 160 | } 161 | } 162 | } 163 | if (min.F != -1) { 164 | element = doc.NewElement(CNS_TAG_POINT); 165 | element->SetAttribute(CNS_TAG_ATTR_X, min.j); 166 | element->SetAttribute(CNS_TAG_ATTR_Y, min.i); 167 | element->SetAttribute(CNS_TAG_ATTR_F, min.F); 168 | element->SetAttribute(CNS_TAG_ATTR_G, min.g); 169 | if (min.g > 0) { 170 | element->SetAttribute(CNS_TAG_ATTR_PARX, min.parent->j); 171 | element->SetAttribute(CNS_TAG_ATTR_PARY, min.parent->i); 172 | } 173 | child->InsertEndChild(element); 174 | } 175 | for (int i = 0; i < size; i++) { 176 | if (open[i].List.size() > 0) { 177 | for (std::list<Node>::const_iterator it = open[i].List.begin(); it != open[i].List.end(); ++it) { 178 | if (it != open[exc].List.begin()) { 179 | element = doc.NewElement(CNS_TAG_POINT); 180 | element->SetAttribute(CNS_TAG_ATTR_X, it->j); 181 | element->SetAttribute(CNS_TAG_ATTR_Y, it->i); 182 | element->SetAttribute(CNS_TAG_ATTR_F, it->F); 183 | element->SetAttribute(CNS_TAG_ATTR_G, it->g); 184 | if (it->g > 0) { 185 | element->SetAttribute(CNS_TAG_ATTR_PARX, it->parent->j); 186 | element->SetAttribute(CNS_TAG_ATTR_PARY, it->parent->i); 187 | } 188 | child->InsertEndChild(element); 189 | } 190 | } 191 | } 192 | } 193 | 194 | lowlevel->InsertEndChild(doc.NewElement(CNS_TAG_CLOSE)); 195 | child = lowlevel->LastChildElement(); 196 | 197 | for (auto it = close.begin(); it != close.end(); ++it) { 198 | element = doc.NewElement(CNS_TAG_POINT); 199 | element->SetAttribute(CNS_TAG_ATTR_X, it->j); 200 | element->SetAttribute(CNS_TAG_ATTR_Y, it->i); 201 | element->SetAttribute(CNS_TAG_ATTR_Z, it->z); 202 | element->SetAttribute(CNS_TAG_ATTR_F, it->F); 203 | element->SetAttribute(CNS_TAG_ATTR_G, it->g); 204 | if (it->g > 0) { 205 | element->SetAttribute(CNS_TAG_ATTR_PARX, it->parent->j); 206 | element->SetAttribute(CNS_TAG_ATTR_PARY, it->parent->i); 207 | element->SetAttribute(CNS_TAG_ATTR_PARZ, it->parent->z); 208 | } 209 | child->InsertEndChild(element); 210 | } 211 | } 212 | 213 | void XmlLogger::writeToLogPath(const NodeList &path) { 214 | if (loglevel == CN_SP_LL_NOLOG || loglevel == CN_SP_LL_TINY || path.List.size() == 0) return; 215 | int iterate = 0; 216 | XMLElement *lplevel = doc.FirstChildElement(CNS_TAG_ROOT); 217 | lplevel = lplevel->FirstChildElement(CNS_TAG_LOG)->FirstChildElement(CNS_TAG_LPLEVEL); 218 | 219 | for (std::list<Node>::const_iterator it = path.List.begin(); it != path.List.end(); ++it, ++iterate) { 220 | XMLElement *element = doc.NewElement(CNS_TAG_POINT); 221 | element->SetAttribute(CNS_TAG_ATTR_X, it->j); 222 | element->SetAttribute(CNS_TAG_ATTR_Y, it->i); 223 | element->SetAttribute(CNS_TAG_ATTR_Z, it->z); 224 | element->SetAttribute(CNS_TAG_ATTR_NUM, iterate); 225 | lplevel->InsertEndChild(element); 226 | } 227 | } 228 | 229 | void XmlLogger::writeToLogHPpath(const NodeList &hppath) { 230 | if (loglevel < CN_SP_LL_SMALLLOG || loglevel == CN_SP_LL_TINY || hppath.List.size() == 0) return; 231 | int partnumber = 0; 232 | XMLElement *hplevel = doc.FirstChildElement(CNS_TAG_ROOT); 233 | hplevel = hplevel->FirstChildElement(CNS_TAG_LOG)->FirstChildElement(CNS_TAG_HPLEVEL); 234 | std::list<Node>::const_iterator iter = hppath.List.begin(); 235 | std::list<Node>::const_iterator it = hppath.List.begin(); 236 | 237 | while (iter != --hppath.List.end()) { 238 | XMLElement *part = doc.NewElement(CNS_TAG_SECTION); 239 | part->SetAttribute(CNS_TAG_ATTR_NUM, partnumber); 240 | part->SetAttribute(CNS_TAG_ATTR_STX, it->j); 241 | part->SetAttribute(CNS_TAG_ATTR_STY, it->i); 242 | part->SetAttribute(CNS_TAG_ATTR_STZ, it->z); 243 | iter++; 244 | part->SetAttribute(CNS_TAG_ATTR_FINX, iter->j); 245 | part->SetAttribute(CNS_TAG_ATTR_FINY, iter->i); 246 | part->SetAttribute(CNS_TAG_ATTR_FINZ, iter->z); 247 | part->SetAttribute(CNS_TAG_ATTR_LENGTH, iter->g - it->g); 248 | hplevel->LinkEndChild(part); 249 | it++; 250 | partnumber++; 251 | } 252 | } 253 | 254 | void XmlLogger::writeToLogSummary(unsigned int numberofsteps, unsigned int nodescreated, float length, double time) { 255 | if (loglevel == CN_SP_LL_NOLOG) return; 256 | 257 | std::stringstream str; 258 | str << time; 259 | 260 | XMLElement *summary = doc.FirstChildElement(CNS_TAG_ROOT); 261 | summary = summary->FirstChildElement(CNS_TAG_LOG)->FirstChildElement(CNS_TAG_SUM); 262 | XMLElement *element = summary->ToElement(); 263 | element->SetAttribute(CNS_TAG_ATTR_NUMOFSTEPS, numberofsteps); 264 | element->SetAttribute(CNS_TAG_ATTR_NODESCREATED, nodescreated); 265 | element->SetAttribute(CNS_TAG_ATTR_LENGTH, length); 266 | element->SetAttribute(CNS_TAG_ATTR_TIME, str.str().c_str()); 267 | } 268 | 269 | void XmlLogger::writeToLogNotFound() { 270 | if (loglevel == CN_SP_LL_NOLOG) return; 271 | XMLElement *node = doc.FirstChildElement(CNS_TAG_ROOT)->FirstChildElement(CNS_TAG_LOG)->FirstChildElement(CNS_TAG_PATH); 272 | node->InsertEndChild(doc.NewText("Path NOT found!")); 273 | } 274 | -------------------------------------------------------------------------------- /examples/simple_obstacle_log.xml: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" ?> 2 | <root> 3 | <desc>This file contains a task (map + start-goal location) for a pathfinder as well as some additional data</desc> 4 | <map> 5 | <title>Sample 3D Map 6 | 7 | 2 8 | 30 9 | 30 10 | 20 11 | 12 | 0 13 | 0 14 | 0 15 | 6 16 | 14 17 | 0 18 | 19 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 21 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 22 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 23 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 24 | 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 25 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 26 | 0 0 0 0 0 0 0 0 0 0 10 10 10 10 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 27 | 0 0 0 0 0 0 0 0 0 15 15 15 15 15 15 15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 28 | 0 0 0 0 0 0 0 0 0 15 15 15 15 15 15 15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 29 | 0 0 0 0 0 0 0 0 20 20 20 20 20 20 20 20 20 0 0 0 0 0 0 0 0 0 0 0 0 0 30 | 0 0 0 0 0 0 0 0 20 20 20 20 20 20 20 20 20 0 0 0 0 0 0 0 0 0 0 0 0 0 31 | 0 0 0 0 0 0 0 0 20 20 20 20 20 20 20 20 20 0 0 0 0 0 0 0 0 0 0 0 0 0 32 | 0 0 0 0 0 0 0 0 0 15 15 15 15 15 15 15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 33 | 0 0 0 0 0 0 0 0 0 15 15 15 15 15 15 15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 34 | 0 0 0 0 0 0 0 0 0 0 10 10 10 10 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 35 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 36 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 37 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 38 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 39 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 40 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 41 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 42 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 43 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 44 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 45 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 46 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 47 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 48 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 49 | 50 | 51 | 52 | astar 53 | 1 54 | euclid 55 | g-max 56 | 1 57 | 1.4 58 | 1 59 | 0 60 | 61 | 62 | 1 63 | 64 | 65 | 66 | 67 | /examples/simple_obstacle.xml 68 | 69 | 70 | * 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 71 | * 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 72 | * 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 73 | * 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 74 | 0 * 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 75 | 20 20 * 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 76 | 0 0 0 * 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 | 0 0 0 * 0 0 0 0 0 0 10 10 10 10 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 78 | 0 0 0 * 0 0 0 0 0 15 15 15 15 15 15 15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 79 | 0 0 0 * 0 0 0 0 0 15 15 15 15 15 15 15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 80 | 0 0 0 * 0 0 0 0 20 20 20 20 20 20 20 20 20 0 0 0 0 0 0 0 0 0 0 0 0 0 81 | 0 0 0 0 * 0 0 0 20 20 20 20 20 20 20 20 20 0 0 0 0 0 0 0 0 0 0 0 0 0 82 | 0 0 0 0 * 0 0 0 20 20 20 20 20 20 20 20 20 0 0 0 0 0 0 0 0 0 0 0 0 0 83 | 0 0 0 0 0 * 0 0 0 15 15 15 15 15 15 15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 84 | 0 0 0 0 0 0 * 0 0 15 15 15 15 15 15 15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 85 | 0 0 0 0 0 0 0 0 0 0 10 10 10 10 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 86 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 87 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 88 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 89 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 90 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 91 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 92 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 93 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 94 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 95 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 96 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 97 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 98 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 99 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 | 164 | 165 | 166 | -------------------------------------------------------------------------------- /isearch.cpp: -------------------------------------------------------------------------------- 1 | #include "gl_const.h" 2 | #include "isearch.h" 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | ISearch::ISearch() { 11 | //��������� ������ ���� ��������� �������������� ������������, � ����������� �� ����, ����� ������������ "������������" ��������� 12 | hweight = 1; 13 | breakingties = CN_SP_BT_GMAX; 14 | open = NULL; 15 | openSize = 0; 16 | //sresult ���������� �� ���� - � ���� ���� ����������� �� ���������... 17 | } 18 | 19 | ISearch::~ISearch(void) { 20 | if (open) { 21 | delete[] open; 22 | } 23 | } 24 | 25 | double ISearch::MoveCost(int start_i, int start_j, int start_h, int fin_i, int fin_j, int fin_h, 26 | const EnvironmentOptions &options) { 27 | //Assuming that we work in a Euclidean space 28 | int diff = abs(start_i - fin_i) + abs(start_j - fin_j) + abs(start_h - fin_h); 29 | switch (diff) { 30 | case 1: 31 | return options.linecost; 32 | case 2: 33 | return M_SQRT2 * options.linecost; 34 | case 3: 35 | return sqrt(3) * options.linecost; 36 | default: 37 | case 0: 38 | return 0; 39 | } 40 | } 41 | 42 | bool ISearch::stopCriterion() { 43 | if (openSize == 0) { 44 | std::cout << "OPEN list is empty!" << std::endl; 45 | return true; 46 | } 47 | return false; 48 | } 49 | 50 | SearchResult ISearch::startSearch(ILogger *Logger, const Map &map, const EnvironmentOptions &options) { 51 | std::chrono::time_point start, end; 52 | start = std::chrono::system_clock::now(); 53 | open = new std::unordered_map[map.height]; 54 | openMinimums = std::vector(map.height, -1); 55 | 56 | Node curNode; 57 | curNode.i = map.start_i; 58 | curNode.j = map.start_j; 59 | curNode.z = map.start_h; 60 | curNode.g = 0; 61 | curNode.H = computeHFromCellToCell(curNode.i, curNode.j, curNode.z, map.goal_i, map.goal_j, map.goal_h, options); 62 | curNode.F = hweight * curNode.H; 63 | curNode.parent = nullptr; 64 | 65 | addOpen(curNode, curNode.get_id(map.height, map.width)); 66 | bool pathfound = false; 67 | const Node *curIt; 68 | size_t closeSize = 0; 69 | openSize = 1; 70 | while (!stopCriterion()) { 71 | curNode = findMin(map.height); 72 | close.insert({curNode.i * map.width + curNode.j + map.height * map.width * curNode.z, curNode}); 73 | ++closeSize; 74 | deleteMin(curNode, curNode.get_id(map.height, map.width)); 75 | --openSize; 76 | if (curNode.i == map.goal_i && curNode.j == map.goal_j) { 77 | pathfound = true; 78 | break; 79 | } 80 | std::list successors = findSuccessors(curNode, map, options); 81 | auto it = successors.begin(); 82 | auto parent = &(close.find(curNode.i * map.width + curNode.j + map.height * map.width * curNode.z)->second); 83 | while (it != successors.end()) { 84 | it->parent = parent; 85 | it->H = computeHFromCellToCell(it->i, it->j, it->z, map.goal_i, map.goal_j, map.goal_h, options); 86 | *it = resetParent(*it, *it->parent, map, options); 87 | it->F = it->g + hweight * it->H; 88 | addOpen(*it, it->get_id(map.height, map.width)); 89 | it++; 90 | } 91 | } 92 | sresult.pathfound = false; 93 | sresult.nodescreated = closeSize + openSize; 94 | sresult.numberofsteps = closeSize; 95 | //Logger->writeToLogOpenClose(open, close, map.height, true); //������ ��� ��������� ������ ��� � ��� ��� ���. 96 | if (pathfound) { 97 | sresult.pathfound = true; 98 | //���� ��������������� �� �������� ���������� (��� ���� ����������) 99 | makePrimaryPath(curNode); 100 | sresult.hppath = &hppath; 101 | sresult.pathlength = curNode.g; 102 | } 103 | //�.�. �������������� ���� �� �������� ���������� - ������������ ����� ����������, ����� ������������� ������ ������! 104 | end = std::chrono::system_clock::now(); 105 | sresult.time = 106 | static_cast(std::chrono::duration_cast(end - start).count()) / 1000000; 107 | //������������� ���� (hplevel, ���� lplevel, � ����������� �� ���������) 108 | if (pathfound) makeSecondaryPath(map, curNode); 109 | return sresult; 110 | } 111 | 112 | std::list ISearch::findSuccessors(Node curNode, const Map &map, const EnvironmentOptions &options) { 113 | Node newNode; 114 | std::list output; 115 | for (int i = -1; i <= 1; ++i) { 116 | for (int j = -1; j <= 1; ++j) { 117 | for (int h = -1; h <= 1; ++h) { 118 | if ((i != 0 || j != 0 || h != 0) && map.CellOnGrid(curNode.i + i, curNode.j + j, curNode.z + h) && 119 | (map.CellIsTraversable(curNode.i + i, curNode.j + j, curNode.z + h))) { 120 | if (options.allowdiagonal == CN_SP_AD_FALSE && abs(i) + abs(j) + abs(h) > 1) { 121 | continue; 122 | } 123 | if (options.allowsqueeze == CN_SP_AS_FALSE && (i != 0 && j != 0)) { 124 | int min_obs_height = std::min(map.getValue(curNode.i, curNode.j + j), 125 | map.getValue(curNode.i + i, curNode.j)); 126 | if (min_obs_height > std::max(curNode.z, curNode.z + h)) { 127 | continue; 128 | } 129 | } 130 | if (options.allowcutcorners == CN_SP_AC_FALSE && 131 | (map.CellIsObstacle(curNode.i + i, curNode.j + j, curNode.z) || 132 | map.CellIsObstacle(curNode.i + i, curNode.j, curNode.z + h) || map.CellIsObstacle(curNode.i, curNode.j + j, curNode.z + h))) { 133 | continue; 134 | } 135 | newNode.i = curNode.i + i; 136 | newNode.j = curNode.j + j; 137 | newNode.z = curNode.z + h; 138 | if (close.find(newNode.i * map.width + newNode.j + map.height * map.width * newNode.z) == 139 | close.end()) { 140 | newNode.g = curNode.g + MoveCost(curNode.i, curNode.j, curNode.z, curNode.i + i, curNode.j + j, 141 | curNode.z + h, options); 142 | output.push_back(newNode); 143 | } 144 | } 145 | } 146 | } 147 | } 148 | return output; 149 | } 150 | 151 | void ISearch::makePrimaryPath(Node curNode) { 152 | Node current = curNode; 153 | while (current.parent != nullptr) { 154 | lppath.List.push_front(current); 155 | current = *current.parent; 156 | } 157 | lppath.List.push_front(current); 158 | sresult.lppath = &lppath; //����� � sresult - ��������� �� ���������. 159 | } 160 | 161 | void ISearch::makeSecondaryPath(const Map &map, Node curNode) { 162 | std::list::const_iterator iter = lppath.List.begin(); 163 | Node cur, next, move; 164 | hppath.List.push_back(*iter); 165 | 166 | while (iter != --lppath.List.end()) { 167 | cur = *iter; 168 | iter++; 169 | next = *iter; 170 | move.i = next.i - cur.i; 171 | move.j = next.j - cur.j; 172 | move.z = next.z - cur.z; 173 | iter++; 174 | if ((iter->i - next.i) != move.i || (iter->j - next.j) != move.j || (iter->z - next.z) != move.z) 175 | hppath.List.push_back(*(--iter)); 176 | else 177 | iter--; 178 | } 179 | sresult.hppath = &hppath; 180 | } 181 | 182 | Node ISearch::findMin(int size) { 183 | Node min, cur_node; 184 | min.F = std::numeric_limits::infinity(); 185 | for (int i = 0; i < size; i++) { 186 | if (!open[i].empty()) { 187 | cur_node = open[i][openMinimums[i]]; 188 | if (cur_node.F <= min.F) { 189 | if (cur_node.F == min.F) { 190 | switch (breakingties) { 191 | default: 192 | case CN_SP_BT_GMAX: { 193 | if (cur_node.g >= min.g) { 194 | min = cur_node; 195 | } 196 | break; 197 | } 198 | case CN_SP_BT_GMIN: { 199 | if (cur_node.g <= min.g) { 200 | min = cur_node; 201 | } 202 | break; 203 | } 204 | } 205 | } else { 206 | min = cur_node; 207 | } 208 | } 209 | } 210 | } 211 | return min; 212 | } 213 | 214 | void ISearch::deleteMin(Node minNode, uint_least32_t key) { 215 | size_t idx = minNode.i; 216 | open[idx].erase(key); 217 | Node min_node; 218 | min_node.F = std::numeric_limits::infinity(); 219 | if (!open[idx].empty()) { 220 | for (auto it = open[idx].begin(); it != open[idx].end(); ++it) { 221 | if (it->second.F <= min_node.F) { 222 | if (it->second.F == min_node.F) { 223 | switch (breakingties) { 224 | default: 225 | case CN_SP_BT_GMAX: { 226 | if (it->second.g >= min_node.g) { 227 | openMinimums[idx] = it->first; 228 | min_node = it->second; 229 | } 230 | break; 231 | } 232 | case CN_SP_BT_GMIN: { 233 | if (it->second.g <= min_node.g) { 234 | openMinimums[idx] = it->first; 235 | min_node = it->second; 236 | } 237 | break; 238 | } 239 | } 240 | } else { 241 | openMinimums[idx] = it->first; 242 | min_node = it->second; 243 | } 244 | } 245 | } 246 | } 247 | } 248 | 249 | void ISearch::addOpen(Node newNode, uint_least32_t key) { 250 | bool inserted = false; 251 | size_t idx = newNode.i; 252 | if (open[idx].find(key) != open[idx].end()) { 253 | if (newNode.F < open[idx][key].F) { 254 | open[idx][key] = newNode; 255 | inserted = true; 256 | } 257 | } else { 258 | open[idx][key] = newNode; 259 | inserted = true; 260 | ++openSize; 261 | } 262 | 263 | if (open[idx].size() == 1) { 264 | openMinimums[idx] = key; 265 | } else { 266 | Node min_node = open[idx][openMinimums[idx]]; 267 | if (inserted && newNode.F <= min_node.F) { 268 | if (newNode.F == min_node.F) { 269 | switch (breakingties) { 270 | default: 271 | case CN_SP_BT_GMAX: { 272 | if (newNode.g >= min_node.g) { 273 | openMinimums[idx] = key; 274 | } 275 | break; 276 | } 277 | case CN_SP_BT_GMIN: { 278 | if (newNode.g <= min_node.g) { 279 | openMinimums[idx] = key; 280 | } 281 | break; 282 | } 283 | } 284 | } else { 285 | openMinimums[idx] = key; 286 | } 287 | } 288 | } 289 | } -------------------------------------------------------------------------------- /config.cpp: -------------------------------------------------------------------------------- 1 | #include "config.h" 2 | #include "gl_const.h" 3 | #include "tinyxml2.h" 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | Config::Config() { 11 | LogParams = NULL; 12 | SearchParams = NULL; 13 | } 14 | 15 | Config::~Config() { 16 | if (SearchParams) delete[] SearchParams; 17 | if (LogParams) delete[] LogParams; 18 | } 19 | 20 | bool Config::getConfig(const char *FileName) { 21 | std::string value; 22 | std::stringstream stream; 23 | tinyxml2::XMLElement *root = 0, *algorithm = 0, *element = 0, *options = 0; 24 | 25 | tinyxml2::XMLDocument doc; 26 | if (doc.LoadFile(FileName) != tinyxml2::XMLError::XML_SUCCESS) { 27 | std::cout << "Error opening XML file!" << std::endl; 28 | return false; 29 | } 30 | 31 | root = doc.FirstChildElement(CNS_TAG_ROOT); 32 | if (!root) { 33 | std::cout << "Error! No '" << CNS_TAG_ROOT << "' element found in XML file!" << std::endl; 34 | return false; 35 | } 36 | 37 | algorithm = root->FirstChildElement(CNS_TAG_ALG); 38 | if (!algorithm) { 39 | std::cout << "Error! No '" << CNS_TAG_ALG << "' tag found in XML file!" << std::endl; 40 | return false; 41 | } 42 | 43 | element = algorithm->FirstChildElement(CNS_TAG_ST); 44 | if (!element) { 45 | std::cout << "Error! No '" << CNS_TAG_ST << "' tag found in XML file!" << std::endl; 46 | return false; 47 | } 48 | if (element->GetText()) 49 | value = element->GetText(); 50 | std::transform(value.begin(), value.end(), value.begin(), ::tolower); 51 | 52 | if (value == CNS_SP_ST_BFS) { 53 | N = 6; 54 | SearchParams = new double[N]; 55 | SearchParams[CN_SP_ST] = CN_SP_ST_BFS; 56 | } else if (value == CNS_SP_ST_DIJK) { 57 | N = 6; 58 | SearchParams = new double[N]; 59 | SearchParams[CN_SP_ST] = CN_SP_ST_DIJK; 60 | } else if (value == CNS_SP_ST_ASTAR || value == CNS_SP_ST_JP_SEARCH || value == CNS_SP_ST_TH) { 61 | N = 11; 62 | SearchParams = new double[N]; 63 | SearchParams[CN_SP_ST] = CN_SP_ST_ASTAR; 64 | if (value == CNS_SP_ST_JP_SEARCH) 65 | SearchParams[CN_SP_ST] = CN_SP_ST_JP_SEARCH; 66 | if (value == CNS_SP_ST_TH) 67 | SearchParams[CN_SP_ST] = CN_SP_ST_TH; 68 | element = algorithm->FirstChildElement(CNS_TAG_HW); 69 | if (!element) { 70 | std::cout << "Warning! No '" << CNS_TAG_HW << "' tag found in algorithm section." << std::endl; 71 | std::cout << "Value of '" << CNS_TAG_HW << "' was defined to 1." << std::endl; 72 | SearchParams[CN_SP_HW] = 1; 73 | } else { 74 | stream << element->GetText(); 75 | stream >> SearchParams[CN_SP_HW]; 76 | stream.str(""); 77 | stream.clear(); 78 | 79 | if (SearchParams[CN_SP_HW] < 1) { 80 | std::cout << "Warning! Value of '" << CNS_TAG_HW << "' tag is not correctly specified. Should be >= 1." 81 | << std::endl; 82 | std::cout << "Value of '" << CNS_TAG_HW << "' was defined to 1." << std::endl; 83 | SearchParams[CN_SP_HW] = 1; 84 | } 85 | } 86 | 87 | element = algorithm->FirstChildElement(CNS_TAG_MT); 88 | if (!element) { 89 | std::cout << "Warning! No '" << CNS_TAG_MT << "' tag found in XML file." << std::endl; 90 | std::cout << "Value of '" << CNS_TAG_MT << "' was defined to 'euclidean'." << std::endl; 91 | SearchParams[CN_SP_MT] = CN_SP_MT_EUCL; 92 | } else { 93 | if (element->GetText()) 94 | value = element->GetText(); 95 | std::transform(value.begin(), value.end(), value.begin(), ::tolower); 96 | if (value == CNS_SP_MT_MANH) SearchParams[CN_SP_MT] = CN_SP_MT_MANH; 97 | else if (value == CNS_SP_MT_EUCL) SearchParams[CN_SP_MT] = CN_SP_MT_EUCL; 98 | else if (value == CNS_SP_MT_DIAG) SearchParams[CN_SP_MT] = CN_SP_MT_DIAG; 99 | else if (value == CNS_SP_MT_CHEB) SearchParams[CN_SP_MT] = CN_SP_MT_CHEB; 100 | else { 101 | std::cout << "Warning! Value of'" << CNS_TAG_MT << "' is not correctly specified." << std::endl; 102 | std::cout << "Value of '" << CNS_TAG_MT << "' was defined to 'euclidean'" << std::endl; 103 | SearchParams[CN_SP_MT] = CN_SP_MT_EUCL; 104 | } 105 | if (SearchParams[CN_SP_ST] == CN_SP_ST_TH && SearchParams[CN_SP_MT] != CN_SP_MT_EUCL) { 106 | std::cout << "Warning! Theta* cannot work with this type of metric!" << std::endl; 107 | std::cout << "Value of '" << CNS_TAG_MT << "' was defined to 'euclidean'" << std::endl; 108 | SearchParams[CN_SP_MT] = CN_SP_MT_EUCL; 109 | } 110 | } 111 | 112 | 113 | element = algorithm->FirstChildElement(CNS_TAG_BT); 114 | if (!element) { 115 | std::cout << "Warning! No '" << CNS_TAG_BT << "' tag found in XML file" << std::endl; 116 | std::cout << "Value of '" << CNS_TAG_BT << "' was defined to 'g-max'" << std::endl; 117 | SearchParams[CN_SP_BT] = CN_SP_BT_GMAX; 118 | } else { 119 | value = element->GetText(); 120 | std::transform(value.begin(), value.end(), value.begin(), ::tolower); 121 | 122 | if (value == CNS_SP_BT_GMIN) SearchParams[CN_SP_BT] = CN_SP_BT_GMIN; 123 | else if (value == CNS_SP_BT_GMAX) SearchParams[CN_SP_BT] = CN_SP_BT_GMAX; 124 | else { 125 | std::cout << "Warning! Value of '" << CNS_TAG_BT << "' is not correctly specified." << std::endl; 126 | std::cout << "Value of '" << CNS_TAG_BT << "' was defined to 'g-max'" << std::endl; 127 | SearchParams[CN_SP_BT] = CN_SP_BT_GMAX; 128 | } 129 | } 130 | 131 | element = algorithm->FirstChildElement(CNS_TAG_SL); 132 | if (!element) { 133 | std::cout << "Warning! No '" << CNS_TAG_SL << "' element found in XML file." << std::endl; 134 | std::cout << "Value of '" << CNS_TAG_SL << "' was defined to default - " << CN_SP_SL_NOLIMIT << std::endl; 135 | SearchParams[CN_SP_SL] = CN_SP_SL_NOLIMIT; 136 | } else { 137 | stream << element->GetText(); 138 | stream >> SearchParams[CN_SP_SL]; 139 | stream.str(""); 140 | stream.clear(); 141 | 142 | if (SearchParams[CN_SP_SL] == 0) { 143 | std::cout << "Warning! Value of '" << CNS_TAG_SL << "' is not correctly specified." << std::endl; 144 | std::cout << "Value of '" << CNS_TAG_SL << "' was defined to default - " << CN_SP_SL_NOLIMIT 145 | << std::endl; 146 | SearchParams[CN_SP_SL] = CN_SP_SL_NOLIMIT; 147 | } 148 | } 149 | 150 | } else { 151 | std::cout << "Error! Value of '" << CNS_TAG_ST << "' tag (algorithm name) is not correctly specified." 152 | << std::endl; 153 | std::cout << "Supported algorithm's names are: '" << CNS_SP_ST_BFS << "', '" << CNS_SP_ST_DIJK << "', '" 154 | << CNS_SP_ST_ASTAR << "', '" << CNS_SP_ST_TH << "'." << std::endl; 155 | return false; 156 | } 157 | 158 | element = algorithm->FirstChildElement(CNS_TAG_AS); 159 | if (!element) { 160 | std::cout << "Warning! No '" << CNS_TAG_AS << "' element found in XML file." << std::endl; 161 | std::cout << "Value of '" << CNS_TAG_AS << "' was defined to default - 0." << std::endl; 162 | 163 | SearchParams[CN_SP_AS] = CN_SP_AS_FALSE; 164 | } else { 165 | std::string check; 166 | stream << CN_SP_AS_FALSE; 167 | stream >> check; 168 | stream.clear(); 169 | stream.str(""); 170 | stream << element->GetText(); 171 | stream >> SearchParams[CN_SP_AS]; 172 | stream.clear(); 173 | stream.str(""); 174 | if (SearchParams[CN_SP_AS] != CN_SP_AS_TRUE && check != element->GetText()) { 175 | std::cout << "Warning! Value of '" << CNS_TAG_AS << "' is not correctly specified." << std::endl; 176 | std::cout << "Value of '" << CNS_TAG_AS << "' was defined to default - 0." << std::endl; 177 | SearchParams[CN_SP_AS] = CN_SP_AS_FALSE; 178 | } 179 | } 180 | 181 | element = algorithm->FirstChildElement(CNS_TAG_LC); 182 | if (!element) { 183 | std::cout << "Warning! No '" << CNS_TAG_LC << "' element found in XML file." << std::endl; 184 | std::cout << "Value of '" << CNS_TAG_LC << "' was defined to default - " << CN_MC_LINE << std::endl; 185 | 186 | SearchParams[CN_SP_LC] = CN_MC_LINE; 187 | } else { 188 | stream << element->GetText(); 189 | stream >> SearchParams[CN_SP_LC]; 190 | stream.str(""); 191 | stream.clear(); 192 | 193 | if (SearchParams[CN_SP_LC] <= 0) { 194 | std::cout << "Warning! Value of '" << CNS_TAG_LC << "' is not correctly specified." << std::endl; 195 | std::cout << "Value of '" << CNS_TAG_LC << "' was defined to default - " << CN_MC_LINE << std::endl; 196 | SearchParams[CN_SP_LC] = CN_MC_LINE; 197 | } 198 | SearchParams[CN_SP_DC] = SearchParams[CN_SP_LC] * sqrt(2); 199 | } 200 | 201 | element = algorithm->FirstChildElement(CNS_TAG_RP); 202 | if (!element) { 203 | std::cout << "Warning! No '" << CNS_TAG_RP << "' element found in XML file." << std::endl; 204 | std::cout << "Value of '" << CNS_TAG_RP << "' was defined to default - " << CN_SP_AS_FALSE << std::endl; 205 | 206 | SearchParams[CN_SP_RP] = CN_SP_AS_FALSE; 207 | } else { 208 | std::string check; 209 | stream << CN_SP_AS_FALSE; 210 | stream >> check; 211 | stream.clear(); 212 | stream.str(""); 213 | stream << element->GetText(); 214 | stream >> SearchParams[CN_SP_RP]; 215 | stream.clear(); 216 | stream.str(""); 217 | if (SearchParams[CN_SP_RP] != CN_SP_AS_TRUE && check != element->GetText()) { 218 | std::cout << "Warning! Value of '" << CNS_TAG_RP << "' is not correctly specified." << std::endl; 219 | std::cout << "Value of '" << CNS_TAG_RP << "' was defined to default - 0" << std::endl; 220 | SearchParams[CN_SP_RP] = CN_SP_AS_TRUE; 221 | } 222 | } 223 | SearchParams[CN_SP_DC] = SearchParams[CN_SP_LC] * sqrt(2); 224 | 225 | //TODO парсить diagonalcost с проверкой (в случае Theta*), что diagonalcost = sqrt(2) * linecost 226 | /*element = algorithm -> FirstChildElement(CNS_TAG_DC); 227 | if (!element) 228 | { 229 | std::cout << "Warning! No '"<< CNS_TAG_DC <<"' element found in XML file." << std::endl; 230 | std::cout << "Value of '"<< CNS_TAG_DC <<"' was defined to default - "<< CN_MC_DIAG << std::endl; 231 | SearchParams[CN_SP_DC] = CN_MC_DIAG; 232 | } 233 | else 234 | { 235 | stream << element->GetText(); 236 | stream >> SearchParams[CN_SP_DC]; 237 | stream.str(""); 238 | stream.clear(); 239 | 240 | if (SearchParams[CN_SP_DC]<=0) 241 | { 242 | std::cout << "Warning! Value of '" << CNS_TAG_DC <<"' is not correctly specified." << std::endl; 243 | std::cout << "Value of '"<< CNS_TAG_DC <<"' was defined to default - "<< CN_MC_DIAG << std::endl; 244 | SearchParams[CN_SP_DC] = CN_MC_DIAG; 245 | if(SearchParams[CN_SP_ST]==CN_SP_ST_TH) 246 | SearchParams[CN_SP_DC]=SearchParams[CN_SP_LC]*sqrt(2); 247 | } 248 | } 249 | 250 | if(SearchParams[CN_SP_DC]<=SearchParams[CN_SP_LC]) 251 | { 252 | std::cout << "Warning! Value of '" << CNS_TAG_DC << "' should be greater than value of '"<< CNS_TAG_LC <<"'." << std::endl; 253 | std::cout << "Value of '"<< CNS_TAG_DC <<"' was defined to default - "<< CN_MC_DIAG << std::endl; 254 | std::cout << "Value of '"<< CNS_TAG_LC <<"' was defined to default - "<< CN_MC_LINE << std::endl; 255 | SearchParams[CN_SP_LC] = CN_MC_LINE; 256 | SearchParams[CN_SP_DC] = CN_MC_DIAG; 257 | }*/ 258 | 259 | element = algorithm->FirstChildElement(CNS_TAG_AD); 260 | if (!element) { 261 | std::cout << "Warning! No '" << CNS_TAG_AD << "' element found in XML file." << std::endl; 262 | std::cout << "Value of '" << CNS_TAG_AD << "' was defined to default - " << CN_SP_AD_TRUE << std::endl; 263 | SearchParams[CN_SP_AD] = CN_SP_AD_TRUE; 264 | } else { 265 | std::string check; 266 | stream << CN_SP_AD_FALSE; 267 | stream >> check; 268 | stream.clear(); 269 | stream.str(""); 270 | stream << element->GetText(); 271 | stream >> SearchParams[CN_SP_AD]; 272 | stream.str(""); 273 | stream.clear(); 274 | if (SearchParams[CN_SP_AD] != CN_SP_AD_TRUE && check != element->GetText()) { 275 | std::cout << "Warning! Value of '" << CNS_TAG_AD << "' is not correctly specified." << std::endl; 276 | std::cout << "Value of '" << CNS_TAG_AD << "' was defined to default - " << CN_SP_AD_TRUE << std::endl; 277 | SearchParams[CN_SP_AD] = CN_SP_AD_TRUE; 278 | } 279 | if (SearchParams[CN_SP_ST] == CN_SP_ST_TH && SearchParams[CN_SP_AD] != CN_SP_AD_TRUE) { 280 | std::cout << "Warning! Theta* cannot work without diagonal movements!" << std::endl; 281 | std::cout << "Value of '" << CNS_TAG_AD << "' was defined to '1'" << std::endl; 282 | SearchParams[CN_SP_AD] = CN_SP_AD_TRUE; 283 | } 284 | } 285 | 286 | element = algorithm->FirstChildElement(CNS_TAG_AC); 287 | if (!element) { 288 | std::cout << "Warning! No '" << CNS_TAG_AC << "' element found in XML file." << std::endl; 289 | std::cout << "Value of '" << CNS_TAG_AC << "' was defined to default - " << CN_SP_AC_TRUE << std::endl; 290 | SearchParams[CN_SP_AC] = CN_SP_AC_TRUE; 291 | } else { 292 | std::string check; 293 | stream << CN_SP_AC_FALSE; 294 | stream >> check; 295 | stream.clear(); 296 | stream.str(""); 297 | stream << element->GetText(); 298 | stream >> SearchParams[CN_SP_AC]; 299 | stream.str(""); 300 | stream.clear(); 301 | if (SearchParams[CN_SP_AC] != CN_SP_AC_TRUE && check != element->GetText()) { 302 | std::cout << "Warning! Value of '" << CNS_TAG_AC << "' is not correctly specified." << std::endl; 303 | std::cout << "Value of '" << CNS_TAG_AC << "' was defined to default - " << CN_SP_AC_TRUE << std::endl; 304 | SearchParams[CN_SP_AC] = CN_SP_AC_TRUE; 305 | } 306 | } 307 | 308 | options = root->FirstChildElement(CNS_TAG_OPT); 309 | LogParams = new std::string[2]; 310 | LogParams[CN_LP_LPATH] = ""; 311 | LogParams[CN_LP_LNAME] = ""; 312 | if (!options) { 313 | std::cout << "Warning! No '" << CNS_TAG_OPT << "' tag found in XML file." << std::endl; 314 | std::cout << "Value of '" << CNS_TAG_LOGLVL << "' tag was defined to 'short log' (1)." << std::endl; 315 | SearchParams[CN_SP_LL] = CN_SP_LL_SMALLLOG; 316 | } else { 317 | element = options->FirstChildElement(CNS_TAG_LOGLVL); 318 | if (!element) { 319 | std::cout << "Warning! No '" << CNS_TAG_LOGLVL << "' tag found in XML file." << std::endl; 320 | std::cout << "Value of '" << CNS_TAG_LOGLVL << "' tag was defined to 'short log' (1)." << std::endl; 321 | SearchParams[CN_SP_LL] = CN_SP_LL_SMALLLOG; 322 | } else { 323 | double loglevel; 324 | value = element->GetText(); 325 | std::transform(value.begin(), value.end(), value.begin(), std::tolower); 326 | 327 | try { 328 | loglevel = std::stod(value); 329 | } catch (std::invalid_argument) { 330 | loglevel = -1; 331 | } 332 | 333 | int is_converted = 0; 334 | if (loglevel == CN_SP_LL_NOLOG || value == CN_SP_LL_NOLOG_WORD) { 335 | SearchParams[CN_SP_LL] = CN_SP_LL_NOLOG; 336 | is_converted = 1; 337 | } else if (loglevel == CN_SP_LL_SMALLLOG || value == CN_SP_LL_SMALLLOG_WORD) { 338 | SearchParams[CN_SP_LL] = CN_SP_LL_SMALLLOG; 339 | is_converted = 1; 340 | } else if (loglevel == CN_SP_LL_FULLLOG || value == CN_SP_LL_FULLLOG_WORD) { 341 | SearchParams[CN_SP_LL] = CN_SP_LL_FULLLOG; 342 | is_converted = 1; 343 | } else if (loglevel == CN_SP_LL_PARTIALLOG || value == CN_SP_LL_PARTIALLOG_WORD) { 344 | SearchParams[CN_SP_LL] = CN_SP_LL_PARTIALLOG; 345 | is_converted = 1; 346 | } else if (loglevel == CN_SP_LL_TINY || value == CN_SP_LL_TINY_WORD) { 347 | SearchParams[CN_SP_LL] = CN_SP_LL_TINY; 348 | is_converted = 1; 349 | } 350 | if (!is_converted) { 351 | std::cout << "'" << CNS_TAG_LOGLVL << "' is not correctly specified" << '\n' 352 | << "Available logging value are: " << CN_SP_LL_SMALLLOG << " (short log), " 353 | << CN_SP_LL_PARTIALLOG 354 | << " (partial log, prints only final states of opened and closed lists), " 355 | << CN_SP_LL_FULLLOG 356 | << " (full log, prints state of of opened and closed lists on every step)\n" 357 | << "Value of '" << CNS_TAG_LOGLVL << "' tag was defined to 'short log' (1)." << std::endl; 358 | SearchParams[CN_SP_LL] = CN_SP_LL_SMALLLOG; 359 | } 360 | } 361 | 362 | 363 | element = options->FirstChildElement(CNS_TAG_LOGPATH); 364 | if (!element) { 365 | std::cout << "Warning! No '" << CNS_TAG_LOGPATH << "' tag found in XML file." << std::endl; 366 | std::cout << "Value of '" << CNS_TAG_LOGPATH << "' tag was defined to 'current directory'." << std::endl; 367 | } else if (!element->GetText()) { 368 | std::cout << "Warning! Value of '" << CNS_TAG_LOGPATH << "' tag is missing!" << std::endl; 369 | std::cout << "Value of '" << CNS_TAG_LOGPATH << "' tag was defined to 'current directory'." << std::endl; 370 | } else { 371 | LogParams[CN_LP_LPATH] = element->GetText(); 372 | } 373 | 374 | 375 | element = options->FirstChildElement(CNS_TAG_LOGFN); 376 | if (!element) { 377 | std::cout << "Warning! No '" << CNS_TAG_LOGFN << "' tag found in XML file!" << std::endl; 378 | std::cout << "Value of '" << CNS_TAG_LOGFN 379 | << "' tag was defined to default (original filename +'_log' + original file extension." 380 | << std::endl; 381 | } else if (!element->GetText()) { 382 | std::cout << "Warning! Value of '" << CNS_TAG_LOGFN << "' tag is missing." << std::endl; 383 | std::cout << "Value of '" << CNS_TAG_LOGFN 384 | << "' tag was defined to default (original filename +'_log' + original file extension." 385 | << std::endl; 386 | } else { 387 | LogParams[CN_LP_LNAME] = element->GetText(); 388 | } 389 | } 390 | 391 | return true; 392 | } 393 | -------------------------------------------------------------------------------- /map.cpp: -------------------------------------------------------------------------------- 1 | #include "map.h" 2 | #include "tinyxml2.h" 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | 9 | std::vector &split(const std::string &s, char delim, std::vector &elems) { 10 | std::stringstream ss(s); 11 | std::string item; 12 | while (std::getline(ss, item, delim)) { 13 | elems.push_back(item); 14 | } 15 | return elems; 16 | } 17 | 18 | 19 | std::vector split(const std::string &s, char delim) { 20 | std::vector elems; 21 | split(s, delim, elems); 22 | return elems; 23 | } 24 | 25 | Map::Map() { 26 | height = -1; 27 | width = -1; 28 | altitude = 0; 29 | start_i = -1; 30 | start_j = -1; 31 | start_h = -1; 32 | goal_i = -1; 33 | goal_j = -1; 34 | goal_h = -1; 35 | min_altitude_limit = 0; 36 | max_altitude_limit = INT_MAX; 37 | Grid = NULL; 38 | } 39 | 40 | Map::~Map() { 41 | if (Grid) { 42 | for (int i = 0; i < height; i++) 43 | delete[] Grid[i]; 44 | delete[] Grid; 45 | } 46 | } 47 | 48 | bool Map::CellIsTraversable(int i, int j) const { 49 | return Grid[i][j] == CN_GC_NOOBS; 50 | } 51 | 52 | bool Map::CellIsTraversable(int i, int j, int h) const { 53 | return !CellIsObstacle(i, j, h); 54 | } 55 | 56 | bool Map::CellIsObstacle(int i, int j) const { 57 | return (Grid[i][j] != CN_GC_NOOBS); 58 | } 59 | 60 | bool Map::CellIsObstacle(int i, int j, int h) const { 61 | return h < Grid[i][j]; 62 | } 63 | 64 | bool Map::CellOnGrid(int i, int j) const { 65 | return (i < height && i >= 0 && j < width && j >= 0); 66 | } 67 | 68 | bool Map::CellOnGrid(int i, int j, int height) const { 69 | return height >= min_altitude_limit && height <= max_altitude_limit && CellOnGrid(i, j); 70 | } 71 | 72 | bool Map::getMap(const char *FileName) { 73 | tinyxml2::XMLElement *root = 0, *map = 0, *element = 0, *mapnode; 74 | 75 | std::string value; //èìÿ òåãà 76 | std::stringstream stream; //ñîäåðäèìîå (òåêñò) òåãà 77 | 78 | bool hasGridMem = false, hasGrid = false, hasHeight = false, hasWidth = false, hasSTX = false, hasSTY = false; 79 | bool hasSTZ = false, hasFINX = false, hasFINY = false, hasFINZ = false, hasSTH = false, hasFINH = false; 80 | bool hasMAXALT = false, hasALTLIM = false; 81 | 82 | tinyxml2::XMLDocument doc; 83 | 84 | // Load XML File 85 | if (doc.LoadFile(FileName) != tinyxml2::XMLError::XML_SUCCESS) { 86 | std::cout << "Error opening XML file!" << std::endl; 87 | return false; 88 | } 89 | // Get ROOT element 90 | root = doc.FirstChildElement(CNS_TAG_ROOT); 91 | if (!root) { 92 | std::cout << "Error! No '" << CNS_TAG_ROOT << "' tag found in XML file!" << std::endl; 93 | return false; 94 | } 95 | 96 | // Get MAP element 97 | map = root->FirstChildElement(CNS_TAG_MAP); 98 | if (!map) { 99 | std::cout << "Error! No '" << CNS_TAG_MAP << "' tag found in XML file!" << std::endl; 100 | return false; 101 | } 102 | 103 | //Èäåîëîãèÿ èíèöèàëèçàöèÿ "êàðòû": 104 | //Ïåðåáèðàåì ïîñëåäîâàòåëüíî âíóòðåííîñòè òåãà "êàðòà" 105 | //Åñëè âïåðâûå ïîïàëîñü êîððåêòíîå çíà÷åíèå ñòàðòà (õ, ó), ôèíèøà (õ, ó), âûñîòû è øèðèíû - çàïîíèìàåì èõ 106 | //Åñëè ñòàðò-õ, ôèíèø-õ ïîïàäàþòñÿ ðàíüøå øèðèíû - îøèáêà! 107 | //Åñëè ñòàðò-ó, ôèíèø-ó ïîïàäàþòñÿ ðàíüøå âûñîòû - îøèáêà! 108 | //Åñëè ïîïàäàþòñÿ äóáëèêàòû (òåãè ïîâòîðÿþòñÿ), ïîñëå òîãî êàê ìû óæå çàïîìíèëè çíà÷åíèÿ, - âûâîäèì Warning 109 | //ò.å. ÂÑÅÃÄÀ çàïîìèíàåòñÿ è èñïîëüçóåòñÿ ÒÎËÜÊÎ ïåðâîå (êîððåêòíî îïðåäåëåííîå) çíà÷åíèå ñòàðòà (õ, ó), ôèíèøà (õ, ó), âûñîòû, øèðèíû 110 | 111 | 112 | for (mapnode = map->FirstChildElement(); mapnode; mapnode = mapnode->NextSiblingElement()) { 113 | element = mapnode->ToElement(); //î÷åðåäíîé ýëåìåíò (òåã) 114 | value = mapnode->Value(); // èìÿ òåãà 115 | std::transform(value.begin(), value.end(), value.begin(), ::tolower); //"õîðîøåå èìÿ òåãà" 116 | 117 | stream.str(""); //î÷èùàåì 118 | stream.clear(); //áóôåð 119 | stream 120 | << element->GetText(); //è êëàäåì â íåãî ñîäåðæèìîå (òåêñò) òåãà (âíèìàíèå: â òåãå "ãðèä" íåò òåêñòà - òàì âëîæåííûå òåãè, òàì áóäåò NULL. Òàê ÷òî áåñïîêîèòñÿ íå íàäî, âñ¸ ïîä êîíòðîëåì! 121 | 122 | //1. Çàãîòîâêà ïîä ãðèä. 123 | if (!hasGridMem && hasHeight && 124 | hasWidth) //â êàêîé-òî ìîìåíò îêàçàëîñü, ÷òî åñòü óæå âûñîòà è øèðèíà - ñîçäàåì ãðèä 125 | { 126 | Grid = new int *[height]; 127 | for (int i = 0; i < height; i++) 128 | Grid[i] = new int[width]; 129 | hasGridMem = true; 130 | } 131 | 132 | //2. Âûñîòà 133 | if (value == CNS_TAG_HEIGHT) { 134 | if (hasHeight) //Äóáëü. Âûñîòà óæå áûëà. 135 | { 136 | std::cout << "Warning! Duplicate '" << CNS_TAG_HEIGHT << "' encountered." << std::endl; 137 | std::cout << "Only first value of '" << CNS_TAG_HEIGHT << "' =" << height << "will be used." 138 | << std::endl; 139 | } else//Âûñîòû åùå íå áûëî. Èëè áûëà - íî ïëîõàÿ.  îáùåì - ïîêà íå èíèöèàëèçèðîâàëè... 140 | { 141 | if (!((stream >> height) && (height > 0)))//sstream >> height ïðåîáðàçîâûâàåò ñòðîêó â ÷èñëî (int). 142 | //Åñëè íå ìîæåò ïðåîáàçîâàòü (ñòðîêà êîñÿ÷íàÿ) - çíà÷åíèå height îñòàåòñÿ ïðåäûäóùèì. 143 | //Òî åñòü - ïî óìîë÷àíèþ (èç êîíñòðóêòîðà) 0. 144 | //Òî æå ñàìîå êàñàåòñÿ è äðóãèõ ïðåîáðàçîâàíèé íèæå... 145 | { 146 | std::cout << "Warning! Invalid value of '" << CNS_TAG_HEIGHT 147 | << "' tag encountered (or could not convert to integer)." << std::endl; 148 | std::cout << "Value of '" << CNS_TAG_HEIGHT << "' tag should be an integer >=0" << std::endl; 149 | std::cout << "Continue reading XML and hope correct value of '" << CNS_TAG_HEIGHT 150 | << "' tag will be encountered later..." << std::endl; 151 | } else 152 | hasHeight = true; 153 | } 154 | } 155 | //Çàêîí÷èëè ñ âûñîòîé 156 | 157 | 158 | //3. Øèðèíà 159 | else if (value == CNS_TAG_WIDTH) { 160 | if (hasWidth) //Äóáëü. Øèðèíà óæå áûëà. 161 | { 162 | std::cout << "Warning! Duplicate '" << CNS_TAG_WIDTH << "' encountered." << std::endl; 163 | std::cout << "Only first value of '" << CNS_TAG_WIDTH << "' =" << width << "will be used." << std::endl; 164 | } else //Øèðèíû åùå íå áûëî. Èëè áûëà - íî ïëîõàÿ.  îáùåì - ïîêà íå èíèöèàëèçèðîâàëè... 165 | { 166 | if (!((stream >> width) && (width > 0))) { 167 | std::cout << "Warning! Invalid value of '" << CNS_TAG_WIDTH 168 | << "' tag encountered (or could not convert to integer)." << std::endl; 169 | std::cout << "Value of '" << CNS_TAG_WIDTH << "' tag should be an integer AND >=0" << std::endl; 170 | std::cout << "Continue reading XML and hope correct value of '" << CNS_TAG_WIDTH 171 | << "' tag will be encountered later..." << std::endl; 172 | 173 | } else 174 | hasWidth = true; 175 | } 176 | } 177 | //Çàêîí÷èëè ñ øèðèíîé 178 | 179 | else if (value == CNS_TAG_MAXALT) { 180 | if (hasMAXALT) //Äóáëü. Ìàêñèìàëüíàÿ âûñîòà êàðòû óæå áûëà 181 | { 182 | std::cout << "Warning! Duplicate '" << CNS_TAG_MAXALT << "' encountered." << std::endl; 183 | std::cout << "Only first value of '" << CNS_TAG_MAXALT << "' =" << altitude << "will be used." 184 | << std::endl; 185 | } else { 186 | if (!((stream >> altitude) && (altitude >= 0))) { 187 | std::cout << "Warning! Invalid value of '" << CNS_TAG_MAXALT 188 | << "' tag encountered (or could not convert to integer)." << std::endl; 189 | std::cout << "Value of '" << CNS_TAG_MAXALT << "' tag should be an integer AND >=0" << std::endl; 190 | std::cout << "Continue reading XML and hope correct value of '" << CNS_TAG_MAXALT 191 | << "' tag will be encountered later..." << std::endl; 192 | 193 | } else { 194 | hasMAXALT = true; 195 | if (!hasALTLIM) { 196 | max_altitude_limit = altitude; 197 | } 198 | } 199 | } 200 | } else if (value == CNS_TAG_ALTLIM) { 201 | if (hasALTLIM) //Äóáëü. Îãðàíè÷åíèÿ íà âûñîòó 202 | { 203 | std::cout << "Warning! Duplicate '" << CNS_TAG_ALTLIM << "' encountered." << std::endl; 204 | std::cout << "Only first value of '" << CNS_TAG_ALTLIM << "will be used." << std::endl; 205 | } else { 206 | hasALTLIM = true; 207 | if (!((element->QueryAttribute(CNS_TAG_ALTLIM_ATTR_MIN, &min_altitude_limit)) && (min_altitude_limit >= 0))) { 208 | std::cout << "Warning! Invalid value of '" << CNS_TAG_ALTLIM_ATTR_MIN << "' attribute of '" 209 | << CNS_TAG_ALTLIM << "' tag encountered (or could not convert to integer)." << std::endl; 210 | std::cout << "Value of '" << CNS_TAG_ALTLIM_ATTR_MIN << "' tag should be an integer AND >=0" 211 | << std::endl; 212 | std::cout << "Continue reading XML and hope correct value of '" << CNS_TAG_ALTLIM_ATTR_MIN 213 | << "' tag will be encountered later..." << std::endl; 214 | hasALTLIM = false; 215 | } 216 | if (!((element->QueryAttribute(CNS_TAG_ALTLIM_ATTR_MAX, &max_altitude_limit)) && 217 | (max_altitude_limit >= min_altitude_limit))) { 218 | std::cout << "Warning! Invalid value of '" << CNS_TAG_ALTLIM_ATTR_MAX << "' attribute of '" 219 | << CNS_TAG_ALTLIM << "' tag encountered (or could not convert to integer)." << std::endl; 220 | std::cout << "Value of '" << CNS_TAG_ALTLIM_ATTR_MAX 221 | << "' tag should be an integer AND be not less than attribute '" 222 | << CNS_TAG_ALTLIM_ATTR_MIN << "'" << std::endl; 223 | std::cout << "Continue reading XML and hope correct value of '" << CNS_TAG_ALTLIM_ATTR_MIN 224 | << "' tag will be encountered later..." << std::endl; 225 | hasALTLIM = false; 226 | } 227 | } 228 | } 229 | 230 | //4. Ñòàðò-Èêñ 231 | else if (value == CNS_TAG_STX) { 232 | if (!hasWidth) //Òåã "ñòàðò-õ" âñòðåòèëñÿ ðàíüøå ÷åì "øèðèíà" - îøèáêà! 233 | { 234 | std::cout << "Error! '" << CNS_TAG_STX << "' tag encountered before '" << CNS_TAG_WIDTH << "' tag." 235 | << std::endl; 236 | return false; 237 | } 238 | 239 | if (hasSTX) //Äóáëü. Ñòàðò-ÈÊÑ óæå áûë. 240 | { 241 | std::cout << "Warning! Duplicate '" << CNS_TAG_STX << "' encountered." << std::endl; 242 | std::cout << "Only first value of '" << CNS_TAG_STX << "' =" << start_j << "will be used." << std::endl; 243 | } else //Ñòàðò-ÈÊÑ åùå íå âñòðå÷àëñÿ (èëè âñòðå÷àëñÿ, íî êîðÿâûé), â îáùåì - íàäî ïûòàòüñÿ èíèöèàëèçèðîâàòü 244 | { 245 | if (!(stream >> start_j && start_j >= 0 && start_j < width)) { 246 | std::cout << "Warning! Invalid value of '" << CNS_TAG_STX 247 | << "' tag encountered (or could not convert to integer)" << std::endl; 248 | std::cout << "Value of '" << CNS_TAG_STX << "' tag should be an integer AND >=0 AND < '" 249 | << CNS_TAG_WIDTH << "' value, which is " << width << std::endl; 250 | std::cout << "Continue reading XML and hope correct value of '" << CNS_TAG_STX 251 | << "' tag will be encountered later..." << std::endl; 252 | } else 253 | hasSTX = true; 254 | } 255 | } 256 | //Çàêîí÷èëè ñî Còàðò-Èêñ 257 | 258 | 259 | //5. Ñòàðò-Èãðåê 260 | else if (value == CNS_TAG_STY) { 261 | if (!hasHeight) //Òåã "ñòàðò-y" âñòðåòèëñÿ ðàíüøå ÷åì "âûñîòà" - îøèáêà! 262 | { 263 | std::cout << "Error! '" << CNS_TAG_STY << "' tag encountered before '" << CNS_TAG_HEIGHT << "' tag." 264 | << std::endl; 265 | return false; 266 | } 267 | 268 | if (hasSTY) //Äóáëü. Ñòàðò-ÈÊÑ óæå áûë. 269 | { 270 | std::cout << "Warning! Duplicate '" << CNS_TAG_STY << "' encountered." << std::endl; 271 | std::cout << "Only first value of '" << CNS_TAG_STY << "' =" << start_i << "will be used." << std::endl; 272 | } else //Ñòàðò-Èãðåê åùå íå âñòðå÷àëñÿ (èëè âñòðå÷àëñÿ, íî êîðÿâûé), â îáùåì - íàäî ïûòàòüñÿ èíèöèàëèçèðîâàòü 273 | { 274 | if (!(stream >> start_i && start_i >= 0 && start_i < height)) { 275 | std::cout << "Warning! Invalid value of '" << CNS_TAG_STY 276 | << "' tag encountered (or could not convert to integer)" << std::endl; 277 | std::cout << "Value of '" << CNS_TAG_STY << "' tag should be an integer AND >=0 AND < '" 278 | << CNS_TAG_HEIGHT << "' value, which is " << height << std::endl; 279 | std::cout << "Continue reading XML and hope correct value of '" << CNS_TAG_STY 280 | << "' tag will be encountered later..." << std::endl; 281 | } else 282 | hasSTY = true; 283 | } 284 | } 285 | //Çàêîí÷èëè ñî Còàðò-Èãðåê 286 | 287 | // Start Z 288 | else if (value == CNS_TAG_STZ) { 289 | if (hasSTZ) //Äóáëü. Ñòàðò-çåò óæå áûë. 290 | { 291 | std::cout << "Warning! Duplicate '" << CNS_TAG_STZ << "' encountered." << std::endl; 292 | std::cout << "Only first value of '" << CNS_TAG_STZ << "' =" << start_h << "will be used." << std::endl; 293 | } else //Ñòàðò-çåò åùå íå âñòðå÷àëñÿ (èëè âñòðå÷àëñÿ, íî êîðÿâûé), â îáùåì - íàäî ïûòàòüñÿ èíèöèàëèçèðîâàòü 294 | { 295 | if (!(stream >> start_h && start_h >= 0)) { 296 | std::cout << "Warning! Invalid value of '" << CNS_TAG_STZ 297 | << "' tag encountered (or could not convert to integer)" << std::endl; 298 | std::cout << "Value of '" << CNS_TAG_STZ << "' tag should be an integer AND >=0 '" 299 | << std::endl; 300 | std::cout << "Continue reading XML and hope correct value of '" << CNS_TAG_STZ 301 | << "' tag will be encountered later..." << std::endl; 302 | } else 303 | hasSTZ = true; 304 | } 305 | } 306 | 307 | //Ôèíèø-Èêñ 308 | else if (value == CNS_TAG_FINX) { 309 | if (!hasWidth) //Òåã "ôèíèø-èêñ" âñòðåòèëñÿ ðàíüøå ÷åì "øèðèíà" - îøèáêà! 310 | { 311 | std::cout << "Error! '" << CNS_TAG_FINX << "' tag encountered before '" << CNS_TAG_WIDTH << "' tag." 312 | << std::endl; 313 | return false; 314 | } 315 | 316 | if (hasFINX) //Äóáëü. ôèíèø-èêñ óæå áûë. 317 | { 318 | std::cout << "Warning! Duplicate '" << CNS_TAG_FINX << "' encountered." << std::endl; 319 | std::cout << "Only first value of '" << CNS_TAG_FINX << "' =" << goal_j << "will be used." << std::endl; 320 | } else //Ôèíèø-èêñ åùå íå âñòðå÷àëñÿ (èëè âñòðå÷àëñÿ, íî êîðÿâûé), â îáùåì - íàäî ïûòàòüñÿ èíèöèàëèçèðîâàòü 321 | { 322 | if (!(stream >> goal_j && goal_j >= 0 && goal_j < width)) { 323 | std::cout << "Warning! Invalid value of '" << CNS_TAG_FINX 324 | << "' tag encountered (or could not convert to integer)" << std::endl; 325 | std::cout << "Value of '" << CNS_TAG_FINX << "' tag should be an integer AND >=0 AND < '" 326 | << CNS_TAG_WIDTH << "' value, which is " << width << std::endl; 327 | std::cout << "Continue reading XML and hope correct value of '" << CNS_TAG_FINX 328 | << "' tag will be encountered later..." << std::endl; 329 | } else 330 | hasFINX = true; 331 | } 332 | } 333 | //Çàêîí÷èëè ñî Ôèíèø-Èêñ 334 | 335 | 336 | //Ôèíèø-Èãðåê 337 | else if (value == CNS_TAG_FINY) { 338 | if (!hasHeight) //Òåã "ôèíèø-èãðåê" âñòðåòèëñÿ ðàíüøå ÷åì "âûñîòà" - îøèáêà! 339 | { 340 | std::cout << "Error! '" << CNS_TAG_FINY << "' tag encountered before '" << CNS_TAG_HEIGHT << "' tag." 341 | << std::endl; 342 | return false; 343 | } 344 | 345 | if (hasFINY) //Äóáëü. Ôèíèø-èãðåê óæå áûë. 346 | { 347 | std::cout << "Warning! Duplicate '" << CNS_TAG_FINY << "' encountered." << std::endl; 348 | std::cout << "Only first value of '" << CNS_TAG_FINY << "' =" << goal_i << "will be used." << std::endl; 349 | } else //Ôèíèø-Èãðåê åùå íå âñòðå÷àëñÿ (èëè âñòðå÷àëñÿ, íî êîðÿâûé), â îáùåì - íàäî ïûòàòüñÿ èíèöèàëèçèðîâàòü 350 | { 351 | if (!(stream >> goal_i && goal_i >= 0 && goal_i < height)) { 352 | std::cout << "Warning! Invalid value of '" << CNS_TAG_FINY 353 | << "' tag encountered (or could not convert to integer)" << std::endl; 354 | std::cout << "Value of '" << CNS_TAG_FINY << "' tag should be an integer AND >=0 AND < '" 355 | << CNS_TAG_HEIGHT << "' value, which is " << height << std::endl; 356 | std::cout << "Continue reading XML and hope correct value of '" << CNS_TAG_FINY 357 | << "' tag will be encountered later..." << std::endl; 358 | } else 359 | hasFINY = true; 360 | } 361 | } else if (value == CNS_TAG_FINZ) { // Finish Z 362 | if (hasFINZ) //Äóáëü. Ôèíèø-èãðåê óæå áûë. 363 | { 364 | std::cout << "Warning! Duplicate '" << CNS_TAG_FINZ << "' encountered." << std::endl; 365 | std::cout << "Only first value of '" << CNS_TAG_FINZ << "' =" << goal_h << "will be used." << std::endl; 366 | } else //Ôèíèø-Èãðåê åùå íå âñòðå÷àëñÿ (èëè âñòðå÷àëñÿ, íî êîðÿâûé), â îáùåì - íàäî ïûòàòüñÿ èíèöèàëèçèðîâàòü 367 | { 368 | if (!(stream >> goal_h && goal_h >= 0)) { 369 | std::cout << "Warning! Invalid value of '" << CNS_TAG_FINZ 370 | << "' tag encountered (or could not convert to integer)" << std::endl; 371 | std::cout << "Value of '" << CNS_TAG_FINZ << "' tag should be an integer AND >=0 '" 372 | << std::endl; 373 | std::cout << "Continue reading XML and hope correct value of '" << CNS_TAG_FINZ 374 | << "' tag will be encountered later..." << std::endl; 375 | } else 376 | hasFINZ = true; 377 | } 378 | } 379 | //Çàêîí÷èëè ñ Ôèíèø-Çåò 380 | 381 | //Ãðèä 382 | else if (value == CNS_TAG_GRID) { 383 | hasGrid = true; 384 | if (!(hasHeight && hasWidth)) { 385 | std::cout << "Error! No '" << CNS_TAG_WIDTH << "' tag or '" << CNS_TAG_HEIGHT << "' tag before '" 386 | << CNS_TAG_GRID << "'tag encountered!" << std::endl; 387 | return false; 388 | } 389 | element = mapnode->FirstChildElement(); //ïåðåõîäèì îò "ãðèäà" ê "ñòðîêàì ãðèäà" 390 | int val, grid_j; 391 | for (int grid_i = 0; grid_i < height; ++grid_i) { 392 | if (!element) { 393 | std::cout << "Error! Not enough '" << CNS_TAG_ROW << "' tags inside '" << CNS_TAG_GRID << "' tag." 394 | << std::endl; 395 | std::cout << "Number of '" << CNS_TAG_ROW 396 | << "' tags should be equal (or greater) than the value of '" << CNS_TAG_HEIGHT 397 | << "' tag which is " << height << std::endl; 398 | return false; 399 | } 400 | 401 | std::string str = element->GetText(); 402 | std::vector elems = split(str, ' '); 403 | grid_j = 0; 404 | if (elems.size() > 0)//ïðîâåðêà íà òî, ÷òî òåã row íå ïóñòîé 405 | for (; grid_j < width && grid_j < elems.size(); ++grid_j) { 406 | stream.str(""); 407 | stream.clear(); 408 | stream << elems[grid_j]; 409 | stream >> val; 410 | Grid[grid_i][grid_j] = val; 411 | } 412 | 413 | if (grid_j != width) { 414 | std::cout << "Invalid value on " << CNS_TAG_GRID << " in the " << grid_i + 1 << " " << CNS_TAG_ROW 415 | << std::endl; 416 | return false; 417 | } 418 | 419 | element = element->NextSiblingElement(); 420 | } 421 | } 422 | } 423 | //Çàêîí÷èëè ñ ãðèäîì 424 | if (!hasGrid)//ïðîâåðêà íà òî, ÷òî â ôàéëå íåò òåãà grid 425 | { 426 | std::cout << "Error! There is no tag 'grid' in xml-file!\n"; 427 | return false; 428 | } 429 | if (!(hasFINX && hasFINY && hasSTX && 430 | hasSTY))//Ïðîâåðêà íà òî, ÷òî òàê è íå óäàëîñü ñ÷èòàòü íîðìàëüíûé ñòàðò è ôèíèø. 431 | return false; 432 | 433 | if (!(hasFINZ && hasSTZ)) { 434 | start_h = goal_h = min_altitude_limit = max_altitude_limit = 0; 435 | std::cout << "Warning! Couldn't find altitude of start or finish. Map will be interpreted as a 2D.\n"; 436 | } 437 | 438 | if (Grid[start_i][start_j] > start_h) { 439 | std::cout << "Error! Start cell is not traversable (cell's is on a altitude " << start_h 440 | << ", but obstacle has height " << Grid[start_i][start_j] << ")!" << std::endl; 441 | return false; 442 | } 443 | 444 | if (Grid[goal_i][goal_j] > goal_h) { 445 | std::cout << "Error! Goal cell is not traversable (cell's is on a altitude " << goal_h 446 | << ", but obstacle has height " << Grid[goal_i][goal_j] << ")!" << std::endl; 447 | return false; 448 | } 449 | 450 | if (start_h < min_altitude_limit || start_h > max_altitude_limit) { 451 | std::cout << "Error! Start cell is on forbidden altitude: " << start_h 452 | << ", but allowed only alltitude between " << min_altitude_limit << " and " << max_altitude_limit 453 | << ". Please change start cell's altitude or altitude limits." << std::endl; 454 | return false; 455 | } 456 | 457 | if (goal_h < min_altitude_limit || goal_h > max_altitude_limit) { 458 | std::cout << "Error! Goal cell is on forbidden altitude: " << goal_h 459 | << ", but allowed only alltitude between " << min_altitude_limit << " and " << max_altitude_limit 460 | << ". Please change goal cell's altitude or altitude limits." << std::endl; 461 | return false; 462 | } 463 | 464 | return true; 465 | } 466 | 467 | int Map::getValue(int i, int j) const { 468 | if (i < 0 || i >= height) 469 | throw std::out_of_range("i coordinate is out of grid"); 470 | 471 | if (j < 0 || j >= width) 472 | throw std::out_of_range("j coordinate is out of grid"); 473 | 474 | return Grid[i][j]; 475 | } 476 | -------------------------------------------------------------------------------- /tinyxml2.h: -------------------------------------------------------------------------------- 1 | /* 2 | Original code by Lee Thomason (www.grinninglizard.com) 3 | 4 | This software is provided 'as-is', without any express or implied 5 | warranty. In no event will the authors be held liable for any 6 | damages arising from the use of this software. 7 | 8 | Permission is granted to anyone to use this software for any 9 | purpose, including commercial applications, and to alter it and 10 | redistribute it freely, subject to the following restrictions: 11 | 12 | 1. The origin of this software must not be misrepresented; you must 13 | not claim that you wrote the original software. If you use this 14 | software in a product, an acknowledgment in the product documentation 15 | would be appreciated but is not required. 16 | 17 | 2. Altered source versions must be plainly marked as such, and 18 | must not be misrepresented as being the original software. 19 | 20 | 3. This notice may not be removed or altered from any source 21 | distribution. 22 | */ 23 | 24 | #ifndef TINYXML2_INCLUDED 25 | #define TINYXML2_INCLUDED 26 | 27 | #if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__) 28 | # include 29 | # include 30 | # include 31 | # include 32 | # include 33 | # if defined(__PS3__) 34 | # include 35 | # endif 36 | #else 37 | # include 38 | # include 39 | # include 40 | # include 41 | # include 42 | #endif 43 | #include 44 | 45 | /* 46 | TODO: intern strings instead of allocation. 47 | */ 48 | /* 49 | gcc: 50 | g++ -Wall -DDEBUG tinyxml2.cpp xmltest.cpp -o gccxmltest.exe 51 | 52 | Formatting, Artistic Style: 53 | AStyle.exe --style=1tbs --indent-switches --break-closing-brackets --indent-preprocessor tinyxml2.cpp tinyxml2.h 54 | */ 55 | 56 | #if defined( _DEBUG ) || defined( DEBUG ) || defined (__DEBUG__) 57 | # ifndef DEBUG 58 | # define DEBUG 59 | # endif 60 | #endif 61 | 62 | #ifdef _MSC_VER 63 | # pragma warning(push) 64 | # pragma warning(disable: 4251) 65 | #endif 66 | 67 | #ifdef _WIN32 68 | # ifdef TINYXML2_EXPORT 69 | # define TINYXML2_LIB __declspec(dllexport) 70 | # elif defined(TINYXML2_IMPORT) 71 | # define TINYXML2_LIB __declspec(dllimport) 72 | # else 73 | # define TINYXML2_LIB 74 | # endif 75 | #elif __GNUC__ >= 4 76 | # define TINYXML2_LIB __attribute__((visibility("default"))) 77 | #else 78 | # define TINYXML2_LIB 79 | #endif 80 | 81 | 82 | #if defined(DEBUG) 83 | # if defined(_MSC_VER) 84 | # // "(void)0," is for suppressing C4127 warning in "assert(false)", "assert(true)" and the like 85 | # define TIXMLASSERT( x ) if ( !((void)0,(x))) { __debugbreak(); } 86 | # elif defined (ANDROID_NDK) 87 | # include 88 | # define TIXMLASSERT( x ) if ( !(x)) { __android_log_assert( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); } 89 | # else 90 | # include 91 | # define TIXMLASSERT assert 92 | # endif 93 | #else 94 | # define TIXMLASSERT( x ) {} 95 | #endif 96 | 97 | 98 | /* Versioning, past 1.0.14: 99 | http://semver.org/ 100 | */ 101 | static const int TIXML2_MAJOR_VERSION = 4; 102 | static const int TIXML2_MINOR_VERSION = 0; 103 | static const int TIXML2_PATCH_VERSION = 1; 104 | 105 | namespace tinyxml2 106 | { 107 | class XMLDocument; 108 | class XMLElement; 109 | class XMLAttribute; 110 | class XMLComment; 111 | class XMLText; 112 | class XMLDeclaration; 113 | class XMLUnknown; 114 | class XMLPrinter; 115 | 116 | /* 117 | A class that wraps strings. Normally stores the start and end 118 | pointers into the XML file itself, and will apply normalization 119 | and entity translation if actually read. Can also store (and memory 120 | manage) a traditional char[] 121 | */ 122 | class StrPair 123 | { 124 | public: 125 | enum { 126 | NEEDS_ENTITY_PROCESSING = 0x01, 127 | NEEDS_NEWLINE_NORMALIZATION = 0x02, 128 | NEEDS_WHITESPACE_COLLAPSING = 0x04, 129 | 130 | TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, 131 | TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, 132 | ATTRIBUTE_NAME = 0, 133 | ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, 134 | ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, 135 | COMMENT = NEEDS_NEWLINE_NORMALIZATION 136 | }; 137 | 138 | StrPair() : _flags( 0 ), _start( 0 ), _end( 0 ) {} 139 | ~StrPair(); 140 | 141 | void Set( char* start, char* end, int flags ) { 142 | TIXMLASSERT( start ); 143 | TIXMLASSERT( end ); 144 | Reset(); 145 | _start = start; 146 | _end = end; 147 | _flags = flags | NEEDS_FLUSH; 148 | } 149 | 150 | const char* GetStr(); 151 | 152 | bool Empty() const { 153 | return _start == _end; 154 | } 155 | 156 | void SetInternedStr( const char* str ) { 157 | Reset(); 158 | _start = const_cast(str); 159 | } 160 | 161 | void SetStr( const char* str, int flags=0 ); 162 | 163 | char* ParseText( char* in, const char* endTag, int strFlags, int* curLineNumPtr ); 164 | char* ParseName( char* in ); 165 | 166 | void TransferTo( StrPair* other ); 167 | void Reset(); 168 | 169 | private: 170 | void CollapseWhitespace(); 171 | 172 | enum { 173 | NEEDS_FLUSH = 0x100, 174 | NEEDS_DELETE = 0x200 175 | }; 176 | 177 | int _flags; 178 | char* _start; 179 | char* _end; 180 | 181 | StrPair( const StrPair& other ); // not supported 182 | void operator=( StrPair& other ); // not supported, use TransferTo() 183 | }; 184 | 185 | 186 | /* 187 | A dynamic array of Plain Old Data. Doesn't support constructors, etc. 188 | Has a small initial memory pool, so that low or no usage will not 189 | cause a call to new/delete 190 | */ 191 | template 192 | class DynArray 193 | { 194 | public: 195 | DynArray() { 196 | _mem = _pool; 197 | _allocated = INITIAL_SIZE; 198 | _size = 0; 199 | } 200 | 201 | ~DynArray() { 202 | if ( _mem != _pool ) { 203 | delete [] _mem; 204 | } 205 | } 206 | 207 | void Clear() { 208 | _size = 0; 209 | } 210 | 211 | void Push( T t ) { 212 | TIXMLASSERT( _size < INT_MAX ); 213 | EnsureCapacity( _size+1 ); 214 | _mem[_size] = t; 215 | ++_size; 216 | } 217 | 218 | T* PushArr( int count ) { 219 | TIXMLASSERT( count >= 0 ); 220 | TIXMLASSERT( _size <= INT_MAX - count ); 221 | EnsureCapacity( _size+count ); 222 | T* ret = &_mem[_size]; 223 | _size += count; 224 | return ret; 225 | } 226 | 227 | T Pop() { 228 | TIXMLASSERT( _size > 0 ); 229 | --_size; 230 | return _mem[_size]; 231 | } 232 | 233 | void PopArr( int count ) { 234 | TIXMLASSERT( _size >= count ); 235 | _size -= count; 236 | } 237 | 238 | bool Empty() const { 239 | return _size == 0; 240 | } 241 | 242 | T& operator[](int i) { 243 | TIXMLASSERT( i>= 0 && i < _size ); 244 | return _mem[i]; 245 | } 246 | 247 | const T& operator[](int i) const { 248 | TIXMLASSERT( i>= 0 && i < _size ); 249 | return _mem[i]; 250 | } 251 | 252 | const T& PeekTop() const { 253 | TIXMLASSERT( _size > 0 ); 254 | return _mem[ _size - 1]; 255 | } 256 | 257 | int Size() const { 258 | TIXMLASSERT( _size >= 0 ); 259 | return _size; 260 | } 261 | 262 | int Capacity() const { 263 | TIXMLASSERT( _allocated >= INITIAL_SIZE ); 264 | return _allocated; 265 | } 266 | 267 | const T* Mem() const { 268 | TIXMLASSERT( _mem ); 269 | return _mem; 270 | } 271 | 272 | T* Mem() { 273 | TIXMLASSERT( _mem ); 274 | return _mem; 275 | } 276 | 277 | private: 278 | DynArray( const DynArray& ); // not supported 279 | void operator=( const DynArray& ); // not supported 280 | 281 | void EnsureCapacity( int cap ) { 282 | TIXMLASSERT( cap > 0 ); 283 | if ( cap > _allocated ) { 284 | TIXMLASSERT( cap <= INT_MAX / 2 ); 285 | int newAllocated = cap * 2; 286 | T* newMem = new T[newAllocated]; 287 | memcpy( newMem, _mem, sizeof(T)*_size ); // warning: not using constructors, only works for PODs 288 | if ( _mem != _pool ) { 289 | delete [] _mem; 290 | } 291 | _mem = newMem; 292 | _allocated = newAllocated; 293 | } 294 | } 295 | 296 | T* _mem; 297 | T _pool[INITIAL_SIZE]; 298 | int _allocated; // objects allocated 299 | int _size; // number objects in use 300 | }; 301 | 302 | 303 | /* 304 | Parent virtual class of a pool for fast allocation 305 | and deallocation of objects. 306 | */ 307 | class MemPool 308 | { 309 | public: 310 | MemPool() {} 311 | virtual ~MemPool() {} 312 | 313 | virtual int ItemSize() const = 0; 314 | virtual void* Alloc() = 0; 315 | virtual void Free( void* ) = 0; 316 | virtual void SetTracked() = 0; 317 | virtual void Clear() = 0; 318 | }; 319 | 320 | 321 | /* 322 | Template child class to create pools of the correct type. 323 | */ 324 | template< int ITEM_SIZE > 325 | class MemPoolT : public MemPool 326 | { 327 | public: 328 | MemPoolT() : _root(0), _currentAllocs(0), _nAllocs(0), _maxAllocs(0), _nUntracked(0) {} 329 | ~MemPoolT() { 330 | Clear(); 331 | } 332 | 333 | void Clear() { 334 | // Delete the blocks. 335 | while( !_blockPtrs.Empty()) { 336 | Block* b = _blockPtrs.Pop(); 337 | delete b; 338 | } 339 | _root = 0; 340 | _currentAllocs = 0; 341 | _nAllocs = 0; 342 | _maxAllocs = 0; 343 | _nUntracked = 0; 344 | } 345 | 346 | virtual int ItemSize() const { 347 | return ITEM_SIZE; 348 | } 349 | int CurrentAllocs() const { 350 | return _currentAllocs; 351 | } 352 | 353 | virtual void* Alloc() { 354 | if ( !_root ) { 355 | // Need a new block. 356 | Block* block = new Block(); 357 | _blockPtrs.Push( block ); 358 | 359 | Item* blockItems = block->items; 360 | for( int i = 0; i < ITEMS_PER_BLOCK - 1; ++i ) { 361 | blockItems[i].next = &(blockItems[i + 1]); 362 | } 363 | blockItems[ITEMS_PER_BLOCK - 1].next = 0; 364 | _root = blockItems; 365 | } 366 | Item* const result = _root; 367 | TIXMLASSERT( result != 0 ); 368 | _root = _root->next; 369 | 370 | ++_currentAllocs; 371 | if ( _currentAllocs > _maxAllocs ) { 372 | _maxAllocs = _currentAllocs; 373 | } 374 | ++_nAllocs; 375 | ++_nUntracked; 376 | return result; 377 | } 378 | 379 | virtual void Free( void* mem ) { 380 | if ( !mem ) { 381 | return; 382 | } 383 | --_currentAllocs; 384 | Item* item = static_cast( mem ); 385 | #ifdef DEBUG 386 | memset( item, 0xfe, sizeof( *item ) ); 387 | #endif 388 | item->next = _root; 389 | _root = item; 390 | } 391 | void Trace( const char* name ) { 392 | printf( "Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n", 393 | name, _maxAllocs, _maxAllocs * ITEM_SIZE / 1024, _currentAllocs, 394 | ITEM_SIZE, _nAllocs, _blockPtrs.Size() ); 395 | } 396 | 397 | void SetTracked() { 398 | --_nUntracked; 399 | } 400 | 401 | int Untracked() const { 402 | return _nUntracked; 403 | } 404 | 405 | // This number is perf sensitive. 4k seems like a good tradeoff on my machine. 406 | // The test file is large, 170k. 407 | // Release: VS2010 gcc(no opt) 408 | // 1k: 4000 409 | // 2k: 4000 410 | // 4k: 3900 21000 411 | // 16k: 5200 412 | // 32k: 4300 413 | // 64k: 4000 21000 414 | // Declared public because some compilers do not accept to use ITEMS_PER_BLOCK 415 | // in private part if ITEMS_PER_BLOCK is private 416 | enum { ITEMS_PER_BLOCK = (4 * 1024) / ITEM_SIZE }; 417 | 418 | private: 419 | MemPoolT( const MemPoolT& ); // not supported 420 | void operator=( const MemPoolT& ); // not supported 421 | 422 | union Item { 423 | Item* next; 424 | char itemData[ITEM_SIZE]; 425 | }; 426 | struct Block { 427 | Item items[ITEMS_PER_BLOCK]; 428 | }; 429 | DynArray< Block*, 10 > _blockPtrs; 430 | Item* _root; 431 | 432 | int _currentAllocs; 433 | int _nAllocs; 434 | int _maxAllocs; 435 | int _nUntracked; 436 | }; 437 | 438 | 439 | 440 | /** 441 | Implements the interface to the "Visitor pattern" (see the Accept() method.) 442 | If you call the Accept() method, it requires being passed a XMLVisitor 443 | class to handle callbacks. For nodes that contain other nodes (Document, Element) 444 | you will get called with a VisitEnter/VisitExit pair. Nodes that are always leafs 445 | are simply called with Visit(). 446 | 447 | If you return 'true' from a Visit method, recursive parsing will continue. If you return 448 | false, no children of this node or its siblings will be visited. 449 | 450 | All flavors of Visit methods have a default implementation that returns 'true' (continue 451 | visiting). You need to only override methods that are interesting to you. 452 | 453 | Generally Accept() is called on the XMLDocument, although all nodes support visiting. 454 | 455 | You should never change the document from a callback. 456 | 457 | @sa XMLNode::Accept() 458 | */ 459 | class TINYXML2_LIB XMLVisitor 460 | { 461 | public: 462 | virtual ~XMLVisitor() {} 463 | 464 | /// Visit a document. 465 | virtual bool VisitEnter( const XMLDocument& /*doc*/ ) { 466 | return true; 467 | } 468 | /// Visit a document. 469 | virtual bool VisitExit( const XMLDocument& /*doc*/ ) { 470 | return true; 471 | } 472 | 473 | /// Visit an element. 474 | virtual bool VisitEnter( const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/ ) { 475 | return true; 476 | } 477 | /// Visit an element. 478 | virtual bool VisitExit( const XMLElement& /*element*/ ) { 479 | return true; 480 | } 481 | 482 | /// Visit a declaration. 483 | virtual bool Visit( const XMLDeclaration& /*declaration*/ ) { 484 | return true; 485 | } 486 | /// Visit a text node. 487 | virtual bool Visit( const XMLText& /*text*/ ) { 488 | return true; 489 | } 490 | /// Visit a comment node. 491 | virtual bool Visit( const XMLComment& /*comment*/ ) { 492 | return true; 493 | } 494 | /// Visit an unknown node. 495 | virtual bool Visit( const XMLUnknown& /*unknown*/ ) { 496 | return true; 497 | } 498 | }; 499 | 500 | // WARNING: must match XMLDocument::_errorNames[] 501 | enum XMLError { 502 | XML_SUCCESS = 0, 503 | XML_NO_ATTRIBUTE, 504 | XML_WRONG_ATTRIBUTE_TYPE, 505 | XML_ERROR_FILE_NOT_FOUND, 506 | XML_ERROR_FILE_COULD_NOT_BE_OPENED, 507 | XML_ERROR_FILE_READ_ERROR, 508 | XML_ERROR_ELEMENT_MISMATCH, 509 | XML_ERROR_PARSING_ELEMENT, 510 | XML_ERROR_PARSING_ATTRIBUTE, 511 | XML_ERROR_IDENTIFYING_TAG, 512 | XML_ERROR_PARSING_TEXT, 513 | XML_ERROR_PARSING_CDATA, 514 | XML_ERROR_PARSING_COMMENT, 515 | XML_ERROR_PARSING_DECLARATION, 516 | XML_ERROR_PARSING_UNKNOWN, 517 | XML_ERROR_EMPTY_DOCUMENT, 518 | XML_ERROR_MISMATCHED_ELEMENT, 519 | XML_ERROR_PARSING, 520 | XML_CAN_NOT_CONVERT_TEXT, 521 | XML_NO_TEXT_NODE, 522 | 523 | XML_ERROR_COUNT 524 | }; 525 | 526 | 527 | /* 528 | Utility functionality. 529 | */ 530 | class TINYXML2_LIB XMLUtil 531 | { 532 | public: 533 | static const char* SkipWhiteSpace( const char* p, int* curLineNumPtr ) { 534 | TIXMLASSERT( p ); 535 | 536 | while( IsWhiteSpace(*p) ) { 537 | if (curLineNumPtr && *p == '\n') { 538 | ++(*curLineNumPtr); 539 | } 540 | ++p; 541 | } 542 | TIXMLASSERT( p ); 543 | return p; 544 | } 545 | static char* SkipWhiteSpace( char* p, int* curLineNumPtr ) { 546 | return const_cast( SkipWhiteSpace( const_cast(p), curLineNumPtr ) ); 547 | } 548 | 549 | // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't 550 | // correct, but simple, and usually works. 551 | static bool IsWhiteSpace( char p ) { 552 | return !IsUTF8Continuation(p) && isspace( static_cast(p) ); 553 | } 554 | 555 | inline static bool IsNameStartChar( unsigned char ch ) { 556 | if ( ch >= 128 ) { 557 | // This is a heuristic guess in attempt to not implement Unicode-aware isalpha() 558 | return true; 559 | } 560 | if ( isalpha( ch ) ) { 561 | return true; 562 | } 563 | return ch == ':' || ch == '_'; 564 | } 565 | 566 | inline static bool IsNameChar( unsigned char ch ) { 567 | return IsNameStartChar( ch ) 568 | || isdigit( ch ) 569 | || ch == '.' 570 | || ch == '-'; 571 | } 572 | 573 | inline static bool StringEqual( const char* p, const char* q, int nChar=INT_MAX ) { 574 | if ( p == q ) { 575 | return true; 576 | } 577 | TIXMLASSERT( p ); 578 | TIXMLASSERT( q ); 579 | TIXMLASSERT( nChar >= 0 ); 580 | return strncmp( p, q, nChar ) == 0; 581 | } 582 | 583 | inline static bool IsUTF8Continuation( char p ) { 584 | return ( p & 0x80 ) != 0; 585 | } 586 | 587 | static const char* ReadBOM( const char* p, bool* hasBOM ); 588 | // p is the starting location, 589 | // the UTF-8 value of the entity will be placed in value, and length filled in. 590 | static const char* GetCharacterRef( const char* p, char* value, int* length ); 591 | static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ); 592 | 593 | // converts primitive types to strings 594 | static void ToStr( int v, char* buffer, int bufferSize ); 595 | static void ToStr( unsigned v, char* buffer, int bufferSize ); 596 | static void ToStr( bool v, char* buffer, int bufferSize ); 597 | static void ToStr( float v, char* buffer, int bufferSize ); 598 | static void ToStr( double v, char* buffer, int bufferSize ); 599 | static void ToStr(int64_t v, char* buffer, int bufferSize); 600 | 601 | // converts strings to primitive types 602 | static bool ToInt( const char* str, int* value ); 603 | static bool ToUnsigned( const char* str, unsigned* value ); 604 | static bool ToBool( const char* str, bool* value ); 605 | static bool ToFloat( const char* str, float* value ); 606 | static bool ToDouble( const char* str, double* value ); 607 | static bool ToInt64(const char* str, int64_t* value); 608 | 609 | // Changes what is serialized for a boolean value. 610 | // Default to "true" and "false". Shouldn't be changed 611 | // unless you have a special testing or compatibility need. 612 | // Be careful: static, global, & not thread safe. 613 | // Be sure to set static const memory as parameters. 614 | static void SetBoolSerialization(const char* writeTrue, const char* writeFalse); 615 | 616 | private: 617 | static const char* writeBoolTrue; 618 | static const char* writeBoolFalse; 619 | }; 620 | 621 | 622 | /** XMLNode is a base class for every object that is in the 623 | XML Document Object Model (DOM), except XMLAttributes. 624 | Nodes have siblings, a parent, and children which can 625 | be navigated. A node is always in a XMLDocument. 626 | The type of a XMLNode can be queried, and it can 627 | be cast to its more defined type. 628 | 629 | A XMLDocument allocates memory for all its Nodes. 630 | When the XMLDocument gets deleted, all its Nodes 631 | will also be deleted. 632 | 633 | @verbatim 634 | A Document can contain: Element (container or leaf) 635 | Comment (leaf) 636 | Unknown (leaf) 637 | Declaration( leaf ) 638 | 639 | An Element can contain: Element (container or leaf) 640 | Text (leaf) 641 | Attributes (not on tree) 642 | Comment (leaf) 643 | Unknown (leaf) 644 | 645 | @endverbatim 646 | */ 647 | class TINYXML2_LIB XMLNode 648 | { 649 | friend class XMLDocument; 650 | friend class XMLElement; 651 | public: 652 | 653 | /// Get the XMLDocument that owns this XMLNode. 654 | const XMLDocument* GetDocument() const { 655 | TIXMLASSERT( _document ); 656 | return _document; 657 | } 658 | /// Get the XMLDocument that owns this XMLNode. 659 | XMLDocument* GetDocument() { 660 | TIXMLASSERT( _document ); 661 | return _document; 662 | } 663 | 664 | /// Safely cast to an Element, or null. 665 | virtual XMLElement* ToElement() { 666 | return 0; 667 | } 668 | /// Safely cast to Text, or null. 669 | virtual XMLText* ToText() { 670 | return 0; 671 | } 672 | /// Safely cast to a Comment, or null. 673 | virtual XMLComment* ToComment() { 674 | return 0; 675 | } 676 | /// Safely cast to a Document, or null. 677 | virtual XMLDocument* ToDocument() { 678 | return 0; 679 | } 680 | /// Safely cast to a Declaration, or null. 681 | virtual XMLDeclaration* ToDeclaration() { 682 | return 0; 683 | } 684 | /// Safely cast to an Unknown, or null. 685 | virtual XMLUnknown* ToUnknown() { 686 | return 0; 687 | } 688 | 689 | virtual const XMLElement* ToElement() const { 690 | return 0; 691 | } 692 | virtual const XMLText* ToText() const { 693 | return 0; 694 | } 695 | virtual const XMLComment* ToComment() const { 696 | return 0; 697 | } 698 | virtual const XMLDocument* ToDocument() const { 699 | return 0; 700 | } 701 | virtual const XMLDeclaration* ToDeclaration() const { 702 | return 0; 703 | } 704 | virtual const XMLUnknown* ToUnknown() const { 705 | return 0; 706 | } 707 | 708 | /** The meaning of 'value' changes for the specific type. 709 | @verbatim 710 | Document: empty (NULL is returned, not an empty string) 711 | Element: name of the element 712 | Comment: the comment text 713 | Unknown: the tag contents 714 | Text: the text string 715 | @endverbatim 716 | */ 717 | const char* Value() const; 718 | 719 | /** Set the Value of an XML node. 720 | @sa Value() 721 | */ 722 | void SetValue( const char* val, bool staticMem=false ); 723 | 724 | /// Gets the line number the node is in, if the document was parsed from a file. 725 | int GetLineNum() const { return _parseLineNum; } 726 | 727 | /// Get the parent of this node on the DOM. 728 | const XMLNode* Parent() const { 729 | return _parent; 730 | } 731 | 732 | XMLNode* Parent() { 733 | return _parent; 734 | } 735 | 736 | /// Returns true if this node has no children. 737 | bool NoChildren() const { 738 | return !_firstChild; 739 | } 740 | 741 | /// Get the first child node, or null if none exists. 742 | const XMLNode* FirstChild() const { 743 | return _firstChild; 744 | } 745 | 746 | XMLNode* FirstChild() { 747 | return _firstChild; 748 | } 749 | 750 | /** Get the first child element, or optionally the first child 751 | element with the specified name. 752 | */ 753 | const XMLElement* FirstChildElement( const char* name = 0 ) const; 754 | 755 | XMLElement* FirstChildElement( const char* name = 0 ) { 756 | return const_cast(const_cast(this)->FirstChildElement( name )); 757 | } 758 | 759 | /// Get the last child node, or null if none exists. 760 | const XMLNode* LastChild() const { 761 | return _lastChild; 762 | } 763 | 764 | XMLNode* LastChild() { 765 | return _lastChild; 766 | } 767 | 768 | /** Get the last child element or optionally the last child 769 | element with the specified name. 770 | */ 771 | const XMLElement* LastChildElement( const char* name = 0 ) const; 772 | 773 | XMLElement* LastChildElement( const char* name = 0 ) { 774 | return const_cast(const_cast(this)->LastChildElement(name) ); 775 | } 776 | 777 | /// Get the previous (left) sibling node of this node. 778 | const XMLNode* PreviousSibling() const { 779 | return _prev; 780 | } 781 | 782 | XMLNode* PreviousSibling() { 783 | return _prev; 784 | } 785 | 786 | /// Get the previous (left) sibling element of this node, with an optionally supplied name. 787 | const XMLElement* PreviousSiblingElement( const char* name = 0 ) const ; 788 | 789 | XMLElement* PreviousSiblingElement( const char* name = 0 ) { 790 | return const_cast(const_cast(this)->PreviousSiblingElement( name ) ); 791 | } 792 | 793 | /// Get the next (right) sibling node of this node. 794 | const XMLNode* NextSibling() const { 795 | return _next; 796 | } 797 | 798 | XMLNode* NextSibling() { 799 | return _next; 800 | } 801 | 802 | /// Get the next (right) sibling element of this node, with an optionally supplied name. 803 | const XMLElement* NextSiblingElement( const char* name = 0 ) const; 804 | 805 | XMLElement* NextSiblingElement( const char* name = 0 ) { 806 | return const_cast(const_cast(this)->NextSiblingElement( name ) ); 807 | } 808 | 809 | /** 810 | Add a child node as the last (right) child. 811 | If the child node is already part of the document, 812 | it is moved from its old location to the new location. 813 | Returns the addThis argument or 0 if the node does not 814 | belong to the same document. 815 | */ 816 | XMLNode* InsertEndChild( XMLNode* addThis ); 817 | 818 | XMLNode* LinkEndChild( XMLNode* addThis ) { 819 | return InsertEndChild( addThis ); 820 | } 821 | /** 822 | Add a child node as the first (left) child. 823 | If the child node is already part of the document, 824 | it is moved from its old location to the new location. 825 | Returns the addThis argument or 0 if the node does not 826 | belong to the same document. 827 | */ 828 | XMLNode* InsertFirstChild( XMLNode* addThis ); 829 | /** 830 | Add a node after the specified child node. 831 | If the child node is already part of the document, 832 | it is moved from its old location to the new location. 833 | Returns the addThis argument or 0 if the afterThis node 834 | is not a child of this node, or if the node does not 835 | belong to the same document. 836 | */ 837 | XMLNode* InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ); 838 | 839 | /** 840 | Delete all the children of this node. 841 | */ 842 | void DeleteChildren(); 843 | 844 | /** 845 | Delete a child of this node. 846 | */ 847 | void DeleteChild( XMLNode* node ); 848 | 849 | /** 850 | Make a copy of this node, but not its children. 851 | You may pass in a Document pointer that will be 852 | the owner of the new Node. If the 'document' is 853 | null, then the node returned will be allocated 854 | from the current Document. (this->GetDocument()) 855 | 856 | Note: if called on a XMLDocument, this will return null. 857 | */ 858 | virtual XMLNode* ShallowClone( XMLDocument* document ) const = 0; 859 | 860 | /** 861 | Test if 2 nodes are the same, but don't test children. 862 | The 2 nodes do not need to be in the same Document. 863 | 864 | Note: if called on a XMLDocument, this will return false. 865 | */ 866 | virtual bool ShallowEqual( const XMLNode* compare ) const = 0; 867 | 868 | /** Accept a hierarchical visit of the nodes in the TinyXML-2 DOM. Every node in the 869 | XML tree will be conditionally visited and the host will be called back 870 | via the XMLVisitor interface. 871 | 872 | This is essentially a SAX interface for TinyXML-2. (Note however it doesn't re-parse 873 | the XML for the callbacks, so the performance of TinyXML-2 is unchanged by using this 874 | interface versus any other.) 875 | 876 | The interface has been based on ideas from: 877 | 878 | - http://www.saxproject.org/ 879 | - http://c2.com/cgi/wiki?HierarchicalVisitorPattern 880 | 881 | Which are both good references for "visiting". 882 | 883 | An example of using Accept(): 884 | @verbatim 885 | XMLPrinter printer; 886 | tinyxmlDoc.Accept( &printer ); 887 | const char* xmlcstr = printer.CStr(); 888 | @endverbatim 889 | */ 890 | virtual bool Accept( XMLVisitor* visitor ) const = 0; 891 | 892 | /** 893 | Set user data into the XMLNode. TinyXML-2 in 894 | no way processes or interprets user data. 895 | It is initially 0. 896 | */ 897 | void SetUserData(void* userData) { _userData = userData; } 898 | 899 | /** 900 | Get user data set into the XMLNode. TinyXML-2 in 901 | no way processes or interprets user data. 902 | It is initially 0. 903 | */ 904 | void* GetUserData() const { return _userData; } 905 | 906 | protected: 907 | XMLNode( XMLDocument* ); 908 | virtual ~XMLNode(); 909 | 910 | virtual char* ParseDeep( char*, StrPair*, int* ); 911 | 912 | XMLDocument* _document; 913 | XMLNode* _parent; 914 | mutable StrPair _value; 915 | int _parseLineNum; 916 | 917 | XMLNode* _firstChild; 918 | XMLNode* _lastChild; 919 | 920 | XMLNode* _prev; 921 | XMLNode* _next; 922 | 923 | void* _userData; 924 | 925 | private: 926 | MemPool* _memPool; 927 | void Unlink( XMLNode* child ); 928 | static void DeleteNode( XMLNode* node ); 929 | void InsertChildPreamble( XMLNode* insertThis ) const; 930 | const XMLElement* ToElementWithName( const char* name ) const; 931 | 932 | XMLNode( const XMLNode& ); // not supported 933 | XMLNode& operator=( const XMLNode& ); // not supported 934 | }; 935 | 936 | 937 | /** XML text. 938 | 939 | Note that a text node can have child element nodes, for example: 940 | @verbatim 941 | This is bold 942 | @endverbatim 943 | 944 | A text node can have 2 ways to output the next. "normal" output 945 | and CDATA. It will default to the mode it was parsed from the XML file and 946 | you generally want to leave it alone, but you can change the output mode with 947 | SetCData() and query it with CData(). 948 | */ 949 | class TINYXML2_LIB XMLText : public XMLNode 950 | { 951 | friend class XMLDocument; 952 | public: 953 | virtual bool Accept( XMLVisitor* visitor ) const; 954 | 955 | virtual XMLText* ToText() { 956 | return this; 957 | } 958 | virtual const XMLText* ToText() const { 959 | return this; 960 | } 961 | 962 | /// Declare whether this should be CDATA or standard text. 963 | void SetCData( bool isCData ) { 964 | _isCData = isCData; 965 | } 966 | /// Returns true if this is a CDATA text element. 967 | bool CData() const { 968 | return _isCData; 969 | } 970 | 971 | virtual XMLNode* ShallowClone( XMLDocument* document ) const; 972 | virtual bool ShallowEqual( const XMLNode* compare ) const; 973 | 974 | protected: 975 | XMLText( XMLDocument* doc ) : XMLNode( doc ), _isCData( false ) {} 976 | virtual ~XMLText() {} 977 | 978 | char* ParseDeep( char*, StrPair* endTag, int* curLineNumPtr ); 979 | 980 | private: 981 | bool _isCData; 982 | 983 | XMLText( const XMLText& ); // not supported 984 | XMLText& operator=( const XMLText& ); // not supported 985 | }; 986 | 987 | 988 | /** An XML Comment. */ 989 | class TINYXML2_LIB XMLComment : public XMLNode 990 | { 991 | friend class XMLDocument; 992 | public: 993 | virtual XMLComment* ToComment() { 994 | return this; 995 | } 996 | virtual const XMLComment* ToComment() const { 997 | return this; 998 | } 999 | 1000 | virtual bool Accept( XMLVisitor* visitor ) const; 1001 | 1002 | virtual XMLNode* ShallowClone( XMLDocument* document ) const; 1003 | virtual bool ShallowEqual( const XMLNode* compare ) const; 1004 | 1005 | protected: 1006 | XMLComment( XMLDocument* doc ); 1007 | virtual ~XMLComment(); 1008 | 1009 | char* ParseDeep( char*, StrPair* endTag, int* curLineNumPtr); 1010 | 1011 | private: 1012 | XMLComment( const XMLComment& ); // not supported 1013 | XMLComment& operator=( const XMLComment& ); // not supported 1014 | }; 1015 | 1016 | 1017 | /** In correct XML the declaration is the first entry in the file. 1018 | @verbatim 1019 | 1020 | @endverbatim 1021 | 1022 | TinyXML-2 will happily read or write files without a declaration, 1023 | however. 1024 | 1025 | The text of the declaration isn't interpreted. It is parsed 1026 | and written as a string. 1027 | */ 1028 | class TINYXML2_LIB XMLDeclaration : public XMLNode 1029 | { 1030 | friend class XMLDocument; 1031 | public: 1032 | virtual XMLDeclaration* ToDeclaration() { 1033 | return this; 1034 | } 1035 | virtual const XMLDeclaration* ToDeclaration() const { 1036 | return this; 1037 | } 1038 | 1039 | virtual bool Accept( XMLVisitor* visitor ) const; 1040 | 1041 | virtual XMLNode* ShallowClone( XMLDocument* document ) const; 1042 | virtual bool ShallowEqual( const XMLNode* compare ) const; 1043 | 1044 | protected: 1045 | XMLDeclaration( XMLDocument* doc ); 1046 | virtual ~XMLDeclaration(); 1047 | 1048 | char* ParseDeep( char*, StrPair* endTag, int* curLineNumPtr ); 1049 | 1050 | private: 1051 | XMLDeclaration( const XMLDeclaration& ); // not supported 1052 | XMLDeclaration& operator=( const XMLDeclaration& ); // not supported 1053 | }; 1054 | 1055 | 1056 | /** Any tag that TinyXML-2 doesn't recognize is saved as an 1057 | unknown. It is a tag of text, but should not be modified. 1058 | It will be written back to the XML, unchanged, when the file 1059 | is saved. 1060 | 1061 | DTD tags get thrown into XMLUnknowns. 1062 | */ 1063 | class TINYXML2_LIB XMLUnknown : public XMLNode 1064 | { 1065 | friend class XMLDocument; 1066 | public: 1067 | virtual XMLUnknown* ToUnknown() { 1068 | return this; 1069 | } 1070 | virtual const XMLUnknown* ToUnknown() const { 1071 | return this; 1072 | } 1073 | 1074 | virtual bool Accept( XMLVisitor* visitor ) const; 1075 | 1076 | virtual XMLNode* ShallowClone( XMLDocument* document ) const; 1077 | virtual bool ShallowEqual( const XMLNode* compare ) const; 1078 | 1079 | protected: 1080 | XMLUnknown( XMLDocument* doc ); 1081 | virtual ~XMLUnknown(); 1082 | 1083 | char* ParseDeep( char*, StrPair* endTag, int* curLineNumPtr ); 1084 | 1085 | private: 1086 | XMLUnknown( const XMLUnknown& ); // not supported 1087 | XMLUnknown& operator=( const XMLUnknown& ); // not supported 1088 | }; 1089 | 1090 | 1091 | 1092 | /** An attribute is a name-value pair. Elements have an arbitrary 1093 | number of attributes, each with a unique name. 1094 | 1095 | @note The attributes are not XMLNodes. You may only query the 1096 | Next() attribute in a list. 1097 | */ 1098 | class TINYXML2_LIB XMLAttribute 1099 | { 1100 | friend class XMLElement; 1101 | public: 1102 | /// The name of the attribute. 1103 | const char* Name() const; 1104 | 1105 | /// The value of the attribute. 1106 | const char* Value() const; 1107 | 1108 | /// Gets the line number the attribute is in, if the document was parsed from a file. 1109 | int GetLineNum() const { return _parseLineNum; } 1110 | 1111 | /// The next attribute in the list. 1112 | const XMLAttribute* Next() const { 1113 | return _next; 1114 | } 1115 | 1116 | /** IntValue interprets the attribute as an integer, and returns the value. 1117 | If the value isn't an integer, 0 will be returned. There is no error checking; 1118 | use QueryIntValue() if you need error checking. 1119 | */ 1120 | int IntValue() const { 1121 | int i = 0; 1122 | QueryIntValue(&i); 1123 | return i; 1124 | } 1125 | 1126 | int64_t Int64Value() const { 1127 | int64_t i = 0; 1128 | QueryInt64Value(&i); 1129 | return i; 1130 | } 1131 | 1132 | /// Query as an unsigned integer. See IntValue() 1133 | unsigned UnsignedValue() const { 1134 | unsigned i=0; 1135 | QueryUnsignedValue( &i ); 1136 | return i; 1137 | } 1138 | /// Query as a boolean. See IntValue() 1139 | bool BoolValue() const { 1140 | bool b=false; 1141 | QueryBoolValue( &b ); 1142 | return b; 1143 | } 1144 | /// Query as a double. See IntValue() 1145 | double DoubleValue() const { 1146 | double d=0; 1147 | QueryDoubleValue( &d ); 1148 | return d; 1149 | } 1150 | /// Query as a float. See IntValue() 1151 | float FloatValue() const { 1152 | float f=0; 1153 | QueryFloatValue( &f ); 1154 | return f; 1155 | } 1156 | 1157 | /** QueryIntValue interprets the attribute as an integer, and returns the value 1158 | in the provided parameter. The function will return XML_SUCCESS on success, 1159 | and XML_WRONG_ATTRIBUTE_TYPE if the conversion is not successful. 1160 | */ 1161 | XMLError QueryIntValue( int* value ) const; 1162 | /// See QueryIntValue 1163 | XMLError QueryUnsignedValue( unsigned int* value ) const; 1164 | /// See QueryIntValue 1165 | XMLError QueryInt64Value(int64_t* value) const; 1166 | /// See QueryIntValue 1167 | XMLError QueryBoolValue( bool* value ) const; 1168 | /// See QueryIntValue 1169 | XMLError QueryDoubleValue( double* value ) const; 1170 | /// See QueryIntValue 1171 | XMLError QueryFloatValue( float* value ) const; 1172 | 1173 | /// Set the attribute to a string value. 1174 | void SetAttribute( const char* value ); 1175 | /// Set the attribute to value. 1176 | void SetAttribute( int value ); 1177 | /// Set the attribute to value. 1178 | void SetAttribute( unsigned value ); 1179 | /// Set the attribute to value. 1180 | void SetAttribute(int64_t value); 1181 | /// Set the attribute to value. 1182 | void SetAttribute( bool value ); 1183 | /// Set the attribute to value. 1184 | void SetAttribute( double value ); 1185 | /// Set the attribute to value. 1186 | void SetAttribute( float value ); 1187 | 1188 | private: 1189 | enum { BUF_SIZE = 200 }; 1190 | 1191 | XMLAttribute() : _parseLineNum( 0 ), _next( 0 ), _memPool( 0 ) {} 1192 | virtual ~XMLAttribute() {} 1193 | 1194 | XMLAttribute( const XMLAttribute& ); // not supported 1195 | void operator=( const XMLAttribute& ); // not supported 1196 | void SetName( const char* name ); 1197 | 1198 | char* ParseDeep( char* p, bool processEntities, int* curLineNumPtr ); 1199 | 1200 | mutable StrPair _name; 1201 | mutable StrPair _value; 1202 | int _parseLineNum; 1203 | XMLAttribute* _next; 1204 | MemPool* _memPool; 1205 | }; 1206 | 1207 | 1208 | /** The element is a container class. It has a value, the element name, 1209 | and can contain other elements, text, comments, and unknowns. 1210 | Elements also contain an arbitrary number of attributes. 1211 | */ 1212 | class TINYXML2_LIB XMLElement : public XMLNode 1213 | { 1214 | friend class XMLDocument; 1215 | public: 1216 | /// Get the name of an element (which is the Value() of the node.) 1217 | const char* Name() const { 1218 | return Value(); 1219 | } 1220 | /// Set the name of the element. 1221 | void SetName( const char* str, bool staticMem=false ) { 1222 | SetValue( str, staticMem ); 1223 | } 1224 | 1225 | virtual XMLElement* ToElement() { 1226 | return this; 1227 | } 1228 | virtual const XMLElement* ToElement() const { 1229 | return this; 1230 | } 1231 | virtual bool Accept( XMLVisitor* visitor ) const; 1232 | 1233 | /** Given an attribute name, Attribute() returns the value 1234 | for the attribute of that name, or null if none 1235 | exists. For example: 1236 | 1237 | @verbatim 1238 | const char* value = ele->Attribute( "foo" ); 1239 | @endverbatim 1240 | 1241 | The 'value' parameter is normally null. However, if specified, 1242 | the attribute will only be returned if the 'name' and 'value' 1243 | match. This allow you to write code: 1244 | 1245 | @verbatim 1246 | if ( ele->Attribute( "foo", "bar" ) ) callFooIsBar(); 1247 | @endverbatim 1248 | 1249 | rather than: 1250 | @verbatim 1251 | if ( ele->Attribute( "foo" ) ) { 1252 | if ( strcmp( ele->Attribute( "foo" ), "bar" ) == 0 ) callFooIsBar(); 1253 | } 1254 | @endverbatim 1255 | */ 1256 | const char* Attribute( const char* name, const char* value=0 ) const; 1257 | 1258 | /** Given an attribute name, IntAttribute() returns the value 1259 | of the attribute interpreted as an integer. The default 1260 | value will be returned if the attribute isn't present, 1261 | or if there is an error. (For a method with error 1262 | checking, see QueryIntAttribute()). 1263 | */ 1264 | int IntAttribute(const char* name, int defaultValue = 0) const; 1265 | /// See IntAttribute() 1266 | unsigned UnsignedAttribute(const char* name, unsigned defaultValue = 0) const; 1267 | /// See IntAttribute() 1268 | int64_t Int64Attribute(const char* name, int64_t defaultValue = 0) const; 1269 | /// See IntAttribute() 1270 | bool BoolAttribute(const char* name, bool defaultValue = false) const; 1271 | /// See IntAttribute() 1272 | double DoubleAttribute(const char* name, double defaultValue = 0) const; 1273 | /// See IntAttribute() 1274 | float FloatAttribute(const char* name, float defaultValue = 0) const; 1275 | 1276 | /** Given an attribute name, QueryIntAttribute() returns 1277 | XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion 1278 | can't be performed, or XML_NO_ATTRIBUTE if the attribute 1279 | doesn't exist. If successful, the result of the conversion 1280 | will be written to 'value'. If not successful, nothing will 1281 | be written to 'value'. This allows you to provide default 1282 | value: 1283 | 1284 | @verbatim 1285 | int value = 10; 1286 | QueryIntAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 1287 | @endverbatim 1288 | */ 1289 | XMLError QueryIntAttribute( const char* name, int* value ) const { 1290 | const XMLAttribute* a = FindAttribute( name ); 1291 | if ( !a ) { 1292 | return XML_NO_ATTRIBUTE; 1293 | } 1294 | return a->QueryIntValue( value ); 1295 | } 1296 | 1297 | /// See QueryIntAttribute() 1298 | XMLError QueryUnsignedAttribute( const char* name, unsigned int* value ) const { 1299 | const XMLAttribute* a = FindAttribute( name ); 1300 | if ( !a ) { 1301 | return XML_NO_ATTRIBUTE; 1302 | } 1303 | return a->QueryUnsignedValue( value ); 1304 | } 1305 | 1306 | /// See QueryIntAttribute() 1307 | XMLError QueryInt64Attribute(const char* name, int64_t* value) const { 1308 | const XMLAttribute* a = FindAttribute(name); 1309 | if (!a) { 1310 | return XML_NO_ATTRIBUTE; 1311 | } 1312 | return a->QueryInt64Value(value); 1313 | } 1314 | 1315 | /// See QueryIntAttribute() 1316 | XMLError QueryBoolAttribute( const char* name, bool* value ) const { 1317 | const XMLAttribute* a = FindAttribute( name ); 1318 | if ( !a ) { 1319 | return XML_NO_ATTRIBUTE; 1320 | } 1321 | return a->QueryBoolValue( value ); 1322 | } 1323 | /// See QueryIntAttribute() 1324 | XMLError QueryDoubleAttribute( const char* name, double* value ) const { 1325 | const XMLAttribute* a = FindAttribute( name ); 1326 | if ( !a ) { 1327 | return XML_NO_ATTRIBUTE; 1328 | } 1329 | return a->QueryDoubleValue( value ); 1330 | } 1331 | /// See QueryIntAttribute() 1332 | XMLError QueryFloatAttribute( const char* name, float* value ) const { 1333 | const XMLAttribute* a = FindAttribute( name ); 1334 | if ( !a ) { 1335 | return XML_NO_ATTRIBUTE; 1336 | } 1337 | return a->QueryFloatValue( value ); 1338 | } 1339 | 1340 | 1341 | /** Given an attribute name, QueryAttribute() returns 1342 | XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion 1343 | can't be performed, or XML_NO_ATTRIBUTE if the attribute 1344 | doesn't exist. It is overloaded for the primitive types, 1345 | and is a generally more convenient replacement of 1346 | QueryIntAttribute() and related functions. 1347 | 1348 | If successful, the result of the conversion 1349 | will be written to 'value'. If not successful, nothing will 1350 | be written to 'value'. This allows you to provide default 1351 | value: 1352 | 1353 | @verbatim 1354 | int value = 10; 1355 | QueryAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 1356 | @endverbatim 1357 | */ 1358 | int QueryAttribute( const char* name, int* value ) const { 1359 | return QueryIntAttribute( name, value ); 1360 | } 1361 | 1362 | int QueryAttribute( const char* name, unsigned int* value ) const { 1363 | return QueryUnsignedAttribute( name, value ); 1364 | } 1365 | 1366 | int QueryAttribute(const char* name, int64_t* value) const { 1367 | return QueryInt64Attribute(name, value); 1368 | } 1369 | 1370 | int QueryAttribute( const char* name, bool* value ) const { 1371 | return QueryBoolAttribute( name, value ); 1372 | } 1373 | 1374 | int QueryAttribute( const char* name, double* value ) const { 1375 | return QueryDoubleAttribute( name, value ); 1376 | } 1377 | 1378 | int QueryAttribute( const char* name, float* value ) const { 1379 | return QueryFloatAttribute( name, value ); 1380 | } 1381 | 1382 | /// Sets the named attribute to value. 1383 | void SetAttribute( const char* name, const char* value ) { 1384 | XMLAttribute* a = FindOrCreateAttribute( name ); 1385 | a->SetAttribute( value ); 1386 | } 1387 | /// Sets the named attribute to value. 1388 | void SetAttribute( const char* name, int value ) { 1389 | XMLAttribute* a = FindOrCreateAttribute( name ); 1390 | a->SetAttribute( value ); 1391 | } 1392 | /// Sets the named attribute to value. 1393 | void SetAttribute( const char* name, unsigned value ) { 1394 | XMLAttribute* a = FindOrCreateAttribute( name ); 1395 | a->SetAttribute( value ); 1396 | } 1397 | 1398 | /// Sets the named attribute to value. 1399 | void SetAttribute(const char* name, int64_t value) { 1400 | XMLAttribute* a = FindOrCreateAttribute(name); 1401 | a->SetAttribute(value); 1402 | } 1403 | 1404 | /// Sets the named attribute to value. 1405 | void SetAttribute( const char* name, bool value ) { 1406 | XMLAttribute* a = FindOrCreateAttribute( name ); 1407 | a->SetAttribute( value ); 1408 | } 1409 | /// Sets the named attribute to value. 1410 | void SetAttribute( const char* name, double value ) { 1411 | XMLAttribute* a = FindOrCreateAttribute( name ); 1412 | a->SetAttribute( value ); 1413 | } 1414 | /// Sets the named attribute to value. 1415 | void SetAttribute( const char* name, float value ) { 1416 | XMLAttribute* a = FindOrCreateAttribute( name ); 1417 | a->SetAttribute( value ); 1418 | } 1419 | 1420 | /** 1421 | Delete an attribute. 1422 | */ 1423 | void DeleteAttribute( const char* name ); 1424 | 1425 | /// Return the first attribute in the list. 1426 | const XMLAttribute* FirstAttribute() const { 1427 | return _rootAttribute; 1428 | } 1429 | /// Query a specific attribute in the list. 1430 | const XMLAttribute* FindAttribute( const char* name ) const; 1431 | 1432 | /** Convenience function for easy access to the text inside an element. Although easy 1433 | and concise, GetText() is limited compared to getting the XMLText child 1434 | and accessing it directly. 1435 | 1436 | If the first child of 'this' is a XMLText, the GetText() 1437 | returns the character string of the Text node, else null is returned. 1438 | 1439 | This is a convenient method for getting the text of simple contained text: 1440 | @verbatim 1441 | This is text 1442 | const char* str = fooElement->GetText(); 1443 | @endverbatim 1444 | 1445 | 'str' will be a pointer to "This is text". 1446 | 1447 | Note that this function can be misleading. If the element foo was created from 1448 | this XML: 1449 | @verbatim 1450 | This is text 1451 | @endverbatim 1452 | 1453 | then the value of str would be null. The first child node isn't a text node, it is 1454 | another element. From this XML: 1455 | @verbatim 1456 | This is text 1457 | @endverbatim 1458 | GetText() will return "This is ". 1459 | */ 1460 | const char* GetText() const; 1461 | 1462 | /** Convenience function for easy access to the text inside an element. Although easy 1463 | and concise, SetText() is limited compared to creating an XMLText child 1464 | and mutating it directly. 1465 | 1466 | If the first child of 'this' is a XMLText, SetText() sets its value to 1467 | the given string, otherwise it will create a first child that is an XMLText. 1468 | 1469 | This is a convenient method for setting the text of simple contained text: 1470 | @verbatim 1471 | This is text 1472 | fooElement->SetText( "Hullaballoo!" ); 1473 | Hullaballoo! 1474 | @endverbatim 1475 | 1476 | Note that this function can be misleading. If the element foo was created from 1477 | this XML: 1478 | @verbatim 1479 | This is text 1480 | @endverbatim 1481 | 1482 | then it will not change "This is text", but rather prefix it with a text element: 1483 | @verbatim 1484 | Hullaballoo!This is text 1485 | @endverbatim 1486 | 1487 | For this XML: 1488 | @verbatim 1489 | 1490 | @endverbatim 1491 | SetText() will generate 1492 | @verbatim 1493 | Hullaballoo! 1494 | @endverbatim 1495 | */ 1496 | void SetText( const char* inText ); 1497 | /// Convenience method for setting text inside an element. See SetText() for important limitations. 1498 | void SetText( int value ); 1499 | /// Convenience method for setting text inside an element. See SetText() for important limitations. 1500 | void SetText( unsigned value ); 1501 | /// Convenience method for setting text inside an element. See SetText() for important limitations. 1502 | void SetText(int64_t value); 1503 | /// Convenience method for setting text inside an element. See SetText() for important limitations. 1504 | void SetText( bool value ); 1505 | /// Convenience method for setting text inside an element. See SetText() for important limitations. 1506 | void SetText( double value ); 1507 | /// Convenience method for setting text inside an element. See SetText() for important limitations. 1508 | void SetText( float value ); 1509 | 1510 | /** 1511 | Convenience method to query the value of a child text node. This is probably best 1512 | shown by example. Given you have a document is this form: 1513 | @verbatim 1514 | 1515 | 1 1516 | 1.4 1517 | 1518 | @endverbatim 1519 | 1520 | The QueryIntText() and similar functions provide a safe and easier way to get to the 1521 | "value" of x and y. 1522 | 1523 | @verbatim 1524 | int x = 0; 1525 | float y = 0; // types of x and y are contrived for example 1526 | const XMLElement* xElement = pointElement->FirstChildElement( "x" ); 1527 | const XMLElement* yElement = pointElement->FirstChildElement( "y" ); 1528 | xElement->QueryIntText( &x ); 1529 | yElement->QueryFloatText( &y ); 1530 | @endverbatim 1531 | 1532 | @returns XML_SUCCESS (0) on success, XML_CAN_NOT_CONVERT_TEXT if the text cannot be converted 1533 | to the requested type, and XML_NO_TEXT_NODE if there is no child text to query. 1534 | 1535 | */ 1536 | XMLError QueryIntText( int* ival ) const; 1537 | /// See QueryIntText() 1538 | XMLError QueryUnsignedText( unsigned* uval ) const; 1539 | /// See QueryIntText() 1540 | XMLError QueryInt64Text(int64_t* uval) const; 1541 | /// See QueryIntText() 1542 | XMLError QueryBoolText( bool* bval ) const; 1543 | /// See QueryIntText() 1544 | XMLError QueryDoubleText( double* dval ) const; 1545 | /// See QueryIntText() 1546 | XMLError QueryFloatText( float* fval ) const; 1547 | 1548 | int IntText(int defaultValue = 0) const; 1549 | 1550 | /// See QueryIntText() 1551 | unsigned UnsignedText(unsigned defaultValue = 0) const; 1552 | /// See QueryIntText() 1553 | int64_t Int64Text(int64_t defaultValue = 0) const; 1554 | /// See QueryIntText() 1555 | bool BoolText(bool defaultValue = false) const; 1556 | /// See QueryIntText() 1557 | double DoubleText(double defaultValue = 0) const; 1558 | /// See QueryIntText() 1559 | float FloatText(float defaultValue = 0) const; 1560 | 1561 | // internal: 1562 | enum { 1563 | OPEN, // 1564 | CLOSED, // 1565 | CLOSING // 1566 | }; 1567 | int ClosingType() const { 1568 | return _closingType; 1569 | } 1570 | virtual XMLNode* ShallowClone( XMLDocument* document ) const; 1571 | virtual bool ShallowEqual( const XMLNode* compare ) const; 1572 | 1573 | protected: 1574 | char* ParseDeep( char* p, StrPair* endTag, int* curLineNumPtr ); 1575 | 1576 | private: 1577 | XMLElement( XMLDocument* doc ); 1578 | virtual ~XMLElement(); 1579 | XMLElement( const XMLElement& ); // not supported 1580 | void operator=( const XMLElement& ); // not supported 1581 | 1582 | XMLAttribute* FindAttribute( const char* name ) { 1583 | return const_cast(const_cast(this)->FindAttribute( name )); 1584 | } 1585 | XMLAttribute* FindOrCreateAttribute( const char* name ); 1586 | //void LinkAttribute( XMLAttribute* attrib ); 1587 | char* ParseAttributes( char* p, int* curLineNumPtr ); 1588 | static void DeleteAttribute( XMLAttribute* attribute ); 1589 | XMLAttribute* CreateAttribute(); 1590 | 1591 | enum { BUF_SIZE = 200 }; 1592 | int _closingType; 1593 | // The attribute list is ordered; there is no 'lastAttribute' 1594 | // because the list needs to be scanned for dupes before adding 1595 | // a new attribute. 1596 | XMLAttribute* _rootAttribute; 1597 | }; 1598 | 1599 | 1600 | enum Whitespace { 1601 | PRESERVE_WHITESPACE, 1602 | COLLAPSE_WHITESPACE 1603 | }; 1604 | 1605 | 1606 | /** A Document binds together all the functionality. 1607 | It can be saved, loaded, and printed to the screen. 1608 | All Nodes are connected and allocated to a Document. 1609 | If the Document is deleted, all its Nodes are also deleted. 1610 | */ 1611 | class TINYXML2_LIB XMLDocument : public XMLNode 1612 | { 1613 | friend class XMLElement; 1614 | public: 1615 | /// constructor 1616 | XMLDocument( bool processEntities = true, Whitespace = PRESERVE_WHITESPACE ); 1617 | ~XMLDocument(); 1618 | 1619 | virtual XMLDocument* ToDocument() { 1620 | TIXMLASSERT( this == _document ); 1621 | return this; 1622 | } 1623 | virtual const XMLDocument* ToDocument() const { 1624 | TIXMLASSERT( this == _document ); 1625 | return this; 1626 | } 1627 | 1628 | /** 1629 | Parse an XML file from a character string. 1630 | Returns XML_SUCCESS (0) on success, or 1631 | an errorID. 1632 | 1633 | You may optionally pass in the 'nBytes', which is 1634 | the number of bytes which will be parsed. If not 1635 | specified, TinyXML-2 will assume 'xml' points to a 1636 | null terminated string. 1637 | */ 1638 | XMLError Parse( const char* xml, size_t nBytes=(size_t)(-1) ); 1639 | 1640 | /** 1641 | Load an XML file from disk. 1642 | Returns XML_SUCCESS (0) on success, or 1643 | an errorID. 1644 | */ 1645 | XMLError LoadFile( const char* filename ); 1646 | 1647 | /** 1648 | Load an XML file from disk. You are responsible 1649 | for providing and closing the FILE*. 1650 | 1651 | NOTE: The file should be opened as binary ("rb") 1652 | not text in order for TinyXML-2 to correctly 1653 | do newline normalization. 1654 | 1655 | Returns XML_SUCCESS (0) on success, or 1656 | an errorID. 1657 | */ 1658 | XMLError LoadFile( FILE* ); 1659 | 1660 | /** 1661 | Save the XML file to disk. 1662 | Returns XML_SUCCESS (0) on success, or 1663 | an errorID. 1664 | */ 1665 | XMLError SaveFile( const char* filename, bool compact = false ); 1666 | 1667 | /** 1668 | Save the XML file to disk. You are responsible 1669 | for providing and closing the FILE*. 1670 | 1671 | Returns XML_SUCCESS (0) on success, or 1672 | an errorID. 1673 | */ 1674 | XMLError SaveFile( FILE* fp, bool compact = false ); 1675 | 1676 | bool ProcessEntities() const { 1677 | return _processEntities; 1678 | } 1679 | Whitespace WhitespaceMode() const { 1680 | return _whitespace; 1681 | } 1682 | 1683 | /** 1684 | Returns true if this document has a leading Byte Order Mark of UTF8. 1685 | */ 1686 | bool HasBOM() const { 1687 | return _writeBOM; 1688 | } 1689 | /** Sets whether to write the BOM when writing the file. 1690 | */ 1691 | void SetBOM( bool useBOM ) { 1692 | _writeBOM = useBOM; 1693 | } 1694 | 1695 | /** Return the root element of DOM. Equivalent to FirstChildElement(). 1696 | To get the first node, use FirstChild(). 1697 | */ 1698 | XMLElement* RootElement() { 1699 | return FirstChildElement(); 1700 | } 1701 | const XMLElement* RootElement() const { 1702 | return FirstChildElement(); 1703 | } 1704 | 1705 | /** Print the Document. If the Printer is not provided, it will 1706 | print to stdout. If you provide Printer, this can print to a file: 1707 | @verbatim 1708 | XMLPrinter printer( fp ); 1709 | doc.Print( &printer ); 1710 | @endverbatim 1711 | 1712 | Or you can use a printer to print to memory: 1713 | @verbatim 1714 | XMLPrinter printer; 1715 | doc.Print( &printer ); 1716 | // printer.CStr() has a const char* to the XML 1717 | @endverbatim 1718 | */ 1719 | void Print( XMLPrinter* streamer=0 ) const; 1720 | virtual bool Accept( XMLVisitor* visitor ) const; 1721 | 1722 | /** 1723 | Create a new Element associated with 1724 | this Document. The memory for the Element 1725 | is managed by the Document. 1726 | */ 1727 | XMLElement* NewElement( const char* name ); 1728 | /** 1729 | Create a new Comment associated with 1730 | this Document. The memory for the Comment 1731 | is managed by the Document. 1732 | */ 1733 | XMLComment* NewComment( const char* comment ); 1734 | /** 1735 | Create a new Text associated with 1736 | this Document. The memory for the Text 1737 | is managed by the Document. 1738 | */ 1739 | XMLText* NewText( const char* text ); 1740 | /** 1741 | Create a new Declaration associated with 1742 | this Document. The memory for the object 1743 | is managed by the Document. 1744 | 1745 | If the 'text' param is null, the standard 1746 | declaration is used.: 1747 | @verbatim 1748 | 1749 | @endverbatim 1750 | */ 1751 | XMLDeclaration* NewDeclaration( const char* text=0 ); 1752 | /** 1753 | Create a new Unknown associated with 1754 | this Document. The memory for the object 1755 | is managed by the Document. 1756 | */ 1757 | XMLUnknown* NewUnknown( const char* text ); 1758 | 1759 | /** 1760 | Delete a node associated with this document. 1761 | It will be unlinked from the DOM. 1762 | */ 1763 | void DeleteNode( XMLNode* node ); 1764 | 1765 | void SetError( XMLError error, const char* str1, const char* str2, int lineNum ); 1766 | 1767 | void ClearError() { 1768 | SetError(XML_SUCCESS, 0, 0, 0); 1769 | } 1770 | 1771 | /// Return true if there was an error parsing the document. 1772 | bool Error() const { 1773 | return _errorID != XML_SUCCESS; 1774 | } 1775 | /// Return the errorID. 1776 | XMLError ErrorID() const { 1777 | return _errorID; 1778 | } 1779 | const char* ErrorName() const; 1780 | static const char* ErrorIDToName(XMLError errorID); 1781 | 1782 | /// Return a possibly helpful diagnostic location or string. 1783 | const char* GetErrorStr1() const { 1784 | return _errorStr1.GetStr(); 1785 | } 1786 | /// Return a possibly helpful secondary diagnostic location or string. 1787 | const char* GetErrorStr2() const { 1788 | return _errorStr2.GetStr(); 1789 | } 1790 | /// Return the line where the error occured, or zero if unknown. 1791 | int GetErrorLineNum() const 1792 | { 1793 | return _errorLineNum; 1794 | } 1795 | /// If there is an error, print it to stdout. 1796 | void PrintError() const; 1797 | 1798 | /// Clear the document, resetting it to the initial state. 1799 | void Clear(); 1800 | 1801 | // internal 1802 | char* Identify( char* p, XMLNode** node ); 1803 | 1804 | virtual XMLNode* ShallowClone( XMLDocument* /*document*/ ) const { 1805 | return 0; 1806 | } 1807 | virtual bool ShallowEqual( const XMLNode* /*compare*/ ) const { 1808 | return false; 1809 | } 1810 | 1811 | private: 1812 | XMLDocument( const XMLDocument& ); // not supported 1813 | void operator=( const XMLDocument& ); // not supported 1814 | 1815 | bool _writeBOM; 1816 | bool _processEntities; 1817 | XMLError _errorID; 1818 | Whitespace _whitespace; 1819 | mutable StrPair _errorStr1; 1820 | mutable StrPair _errorStr2; 1821 | int _errorLineNum; 1822 | char* _charBuffer; 1823 | int _parseCurLineNum; 1824 | 1825 | MemPoolT< sizeof(XMLElement) > _elementPool; 1826 | MemPoolT< sizeof(XMLAttribute) > _attributePool; 1827 | MemPoolT< sizeof(XMLText) > _textPool; 1828 | MemPoolT< sizeof(XMLComment) > _commentPool; 1829 | 1830 | static const char* _errorNames[XML_ERROR_COUNT]; 1831 | 1832 | void Parse(); 1833 | }; 1834 | 1835 | 1836 | /** 1837 | A XMLHandle is a class that wraps a node pointer with null checks; this is 1838 | an incredibly useful thing. Note that XMLHandle is not part of the TinyXML-2 1839 | DOM structure. It is a separate utility class. 1840 | 1841 | Take an example: 1842 | @verbatim 1843 | 1844 | 1845 | 1846 | 1847 | 1848 | 1849 | @endverbatim 1850 | 1851 | Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very 1852 | easy to write a *lot* of code that looks like: 1853 | 1854 | @verbatim 1855 | XMLElement* root = document.FirstChildElement( "Document" ); 1856 | if ( root ) 1857 | { 1858 | XMLElement* element = root->FirstChildElement( "Element" ); 1859 | if ( element ) 1860 | { 1861 | XMLElement* child = element->FirstChildElement( "Child" ); 1862 | if ( child ) 1863 | { 1864 | XMLElement* child2 = child->NextSiblingElement( "Child" ); 1865 | if ( child2 ) 1866 | { 1867 | // Finally do something useful. 1868 | @endverbatim 1869 | 1870 | And that doesn't even cover "else" cases. XMLHandle addresses the verbosity 1871 | of such code. A XMLHandle checks for null pointers so it is perfectly safe 1872 | and correct to use: 1873 | 1874 | @verbatim 1875 | XMLHandle docHandle( &document ); 1876 | XMLElement* child2 = docHandle.FirstChildElement( "Document" ).FirstChildElement( "Element" ).FirstChildElement().NextSiblingElement(); 1877 | if ( child2 ) 1878 | { 1879 | // do something useful 1880 | @endverbatim 1881 | 1882 | Which is MUCH more concise and useful. 1883 | 1884 | It is also safe to copy handles - internally they are nothing more than node pointers. 1885 | @verbatim 1886 | XMLHandle handleCopy = handle; 1887 | @endverbatim 1888 | 1889 | See also XMLConstHandle, which is the same as XMLHandle, but operates on const objects. 1890 | */ 1891 | class TINYXML2_LIB XMLHandle 1892 | { 1893 | public: 1894 | /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. 1895 | XMLHandle( XMLNode* node ) { 1896 | _node = node; 1897 | } 1898 | /// Create a handle from a node. 1899 | XMLHandle( XMLNode& node ) { 1900 | _node = &node; 1901 | } 1902 | /// Copy constructor 1903 | XMLHandle( const XMLHandle& ref ) { 1904 | _node = ref._node; 1905 | } 1906 | /// Assignment 1907 | XMLHandle& operator=( const XMLHandle& ref ) { 1908 | _node = ref._node; 1909 | return *this; 1910 | } 1911 | 1912 | /// Get the first child of this handle. 1913 | XMLHandle FirstChild() { 1914 | return XMLHandle( _node ? _node->FirstChild() : 0 ); 1915 | } 1916 | /// Get the first child element of this handle. 1917 | XMLHandle FirstChildElement( const char* name = 0 ) { 1918 | return XMLHandle( _node ? _node->FirstChildElement( name ) : 0 ); 1919 | } 1920 | /// Get the last child of this handle. 1921 | XMLHandle LastChild() { 1922 | return XMLHandle( _node ? _node->LastChild() : 0 ); 1923 | } 1924 | /// Get the last child element of this handle. 1925 | XMLHandle LastChildElement( const char* name = 0 ) { 1926 | return XMLHandle( _node ? _node->LastChildElement( name ) : 0 ); 1927 | } 1928 | /// Get the previous sibling of this handle. 1929 | XMLHandle PreviousSibling() { 1930 | return XMLHandle( _node ? _node->PreviousSibling() : 0 ); 1931 | } 1932 | /// Get the previous sibling element of this handle. 1933 | XMLHandle PreviousSiblingElement( const char* name = 0 ) { 1934 | return XMLHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); 1935 | } 1936 | /// Get the next sibling of this handle. 1937 | XMLHandle NextSibling() { 1938 | return XMLHandle( _node ? _node->NextSibling() : 0 ); 1939 | } 1940 | /// Get the next sibling element of this handle. 1941 | XMLHandle NextSiblingElement( const char* name = 0 ) { 1942 | return XMLHandle( _node ? _node->NextSiblingElement( name ) : 0 ); 1943 | } 1944 | 1945 | /// Safe cast to XMLNode. This can return null. 1946 | XMLNode* ToNode() { 1947 | return _node; 1948 | } 1949 | /// Safe cast to XMLElement. This can return null. 1950 | XMLElement* ToElement() { 1951 | return ( _node ? _node->ToElement() : 0 ); 1952 | } 1953 | /// Safe cast to XMLText. This can return null. 1954 | XMLText* ToText() { 1955 | return ( _node ? _node->ToText() : 0 ); 1956 | } 1957 | /// Safe cast to XMLUnknown. This can return null. 1958 | XMLUnknown* ToUnknown() { 1959 | return ( _node ? _node->ToUnknown() : 0 ); 1960 | } 1961 | /// Safe cast to XMLDeclaration. This can return null. 1962 | XMLDeclaration* ToDeclaration() { 1963 | return ( _node ? _node->ToDeclaration() : 0 ); 1964 | } 1965 | 1966 | private: 1967 | XMLNode* _node; 1968 | }; 1969 | 1970 | 1971 | /** 1972 | A variant of the XMLHandle class for working with const XMLNodes and Documents. It is the 1973 | same in all regards, except for the 'const' qualifiers. See XMLHandle for API. 1974 | */ 1975 | class TINYXML2_LIB XMLConstHandle 1976 | { 1977 | public: 1978 | XMLConstHandle( const XMLNode* node ) { 1979 | _node = node; 1980 | } 1981 | XMLConstHandle( const XMLNode& node ) { 1982 | _node = &node; 1983 | } 1984 | XMLConstHandle( const XMLConstHandle& ref ) { 1985 | _node = ref._node; 1986 | } 1987 | 1988 | XMLConstHandle& operator=( const XMLConstHandle& ref ) { 1989 | _node = ref._node; 1990 | return *this; 1991 | } 1992 | 1993 | const XMLConstHandle FirstChild() const { 1994 | return XMLConstHandle( _node ? _node->FirstChild() : 0 ); 1995 | } 1996 | const XMLConstHandle FirstChildElement( const char* name = 0 ) const { 1997 | return XMLConstHandle( _node ? _node->FirstChildElement( name ) : 0 ); 1998 | } 1999 | const XMLConstHandle LastChild() const { 2000 | return XMLConstHandle( _node ? _node->LastChild() : 0 ); 2001 | } 2002 | const XMLConstHandle LastChildElement( const char* name = 0 ) const { 2003 | return XMLConstHandle( _node ? _node->LastChildElement( name ) : 0 ); 2004 | } 2005 | const XMLConstHandle PreviousSibling() const { 2006 | return XMLConstHandle( _node ? _node->PreviousSibling() : 0 ); 2007 | } 2008 | const XMLConstHandle PreviousSiblingElement( const char* name = 0 ) const { 2009 | return XMLConstHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); 2010 | } 2011 | const XMLConstHandle NextSibling() const { 2012 | return XMLConstHandle( _node ? _node->NextSibling() : 0 ); 2013 | } 2014 | const XMLConstHandle NextSiblingElement( const char* name = 0 ) const { 2015 | return XMLConstHandle( _node ? _node->NextSiblingElement( name ) : 0 ); 2016 | } 2017 | 2018 | 2019 | const XMLNode* ToNode() const { 2020 | return _node; 2021 | } 2022 | const XMLElement* ToElement() const { 2023 | return ( _node ? _node->ToElement() : 0 ); 2024 | } 2025 | const XMLText* ToText() const { 2026 | return ( _node ? _node->ToText() : 0 ); 2027 | } 2028 | const XMLUnknown* ToUnknown() const { 2029 | return ( _node ? _node->ToUnknown() : 0 ); 2030 | } 2031 | const XMLDeclaration* ToDeclaration() const { 2032 | return ( _node ? _node->ToDeclaration() : 0 ); 2033 | } 2034 | 2035 | private: 2036 | const XMLNode* _node; 2037 | }; 2038 | 2039 | 2040 | /** 2041 | Printing functionality. The XMLPrinter gives you more 2042 | options than the XMLDocument::Print() method. 2043 | 2044 | It can: 2045 | -# Print to memory. 2046 | -# Print to a file you provide. 2047 | -# Print XML without a XMLDocument. 2048 | 2049 | Print to Memory 2050 | 2051 | @verbatim 2052 | XMLPrinter printer; 2053 | doc.Print( &printer ); 2054 | SomeFunction( printer.CStr() ); 2055 | @endverbatim 2056 | 2057 | Print to a File 2058 | 2059 | You provide the file pointer. 2060 | @verbatim 2061 | XMLPrinter printer( fp ); 2062 | doc.Print( &printer ); 2063 | @endverbatim 2064 | 2065 | Print without a XMLDocument 2066 | 2067 | When loading, an XML parser is very useful. However, sometimes 2068 | when saving, it just gets in the way. The code is often set up 2069 | for streaming, and constructing the DOM is just overhead. 2070 | 2071 | The Printer supports the streaming case. The following code 2072 | prints out a trivially simple XML file without ever creating 2073 | an XML document. 2074 | 2075 | @verbatim 2076 | XMLPrinter printer( fp ); 2077 | printer.OpenElement( "foo" ); 2078 | printer.PushAttribute( "foo", "bar" ); 2079 | printer.CloseElement(); 2080 | @endverbatim 2081 | */ 2082 | class TINYXML2_LIB XMLPrinter : public XMLVisitor 2083 | { 2084 | public: 2085 | /** Construct the printer. If the FILE* is specified, 2086 | this will print to the FILE. Else it will print 2087 | to memory, and the result is available in CStr(). 2088 | If 'compact' is set to true, then output is created 2089 | with only required whitespace and newlines. 2090 | */ 2091 | XMLPrinter( FILE* file=0, bool compact = false, int depth = 0 ); 2092 | virtual ~XMLPrinter() {} 2093 | 2094 | /** If streaming, write the BOM and declaration. */ 2095 | void PushHeader( bool writeBOM, bool writeDeclaration ); 2096 | /** If streaming, start writing an element. 2097 | The element must be closed with CloseElement() 2098 | */ 2099 | void OpenElement( const char* name, bool compactMode=false ); 2100 | /// If streaming, add an attribute to an open element. 2101 | void PushAttribute( const char* name, const char* value ); 2102 | void PushAttribute( const char* name, int value ); 2103 | void PushAttribute( const char* name, unsigned value ); 2104 | void PushAttribute(const char* name, int64_t value); 2105 | void PushAttribute( const char* name, bool value ); 2106 | void PushAttribute( const char* name, double value ); 2107 | /// If streaming, close the Element. 2108 | virtual void CloseElement( bool compactMode=false ); 2109 | 2110 | /// Add a text node. 2111 | void PushText( const char* text, bool cdata=false ); 2112 | /// Add a text node from an integer. 2113 | void PushText( int value ); 2114 | /// Add a text node from an unsigned. 2115 | void PushText( unsigned value ); 2116 | /// Add a text node from an unsigned. 2117 | void PushText(int64_t value); 2118 | /// Add a text node from a bool. 2119 | void PushText( bool value ); 2120 | /// Add a text node from a float. 2121 | void PushText( float value ); 2122 | /// Add a text node from a double. 2123 | void PushText( double value ); 2124 | 2125 | /// Add a comment 2126 | void PushComment( const char* comment ); 2127 | 2128 | void PushDeclaration( const char* value ); 2129 | void PushUnknown( const char* value ); 2130 | 2131 | virtual bool VisitEnter( const XMLDocument& /*doc*/ ); 2132 | virtual bool VisitExit( const XMLDocument& /*doc*/ ) { 2133 | return true; 2134 | } 2135 | 2136 | virtual bool VisitEnter( const XMLElement& element, const XMLAttribute* attribute ); 2137 | virtual bool VisitExit( const XMLElement& element ); 2138 | 2139 | virtual bool Visit( const XMLText& text ); 2140 | virtual bool Visit( const XMLComment& comment ); 2141 | virtual bool Visit( const XMLDeclaration& declaration ); 2142 | virtual bool Visit( const XMLUnknown& unknown ); 2143 | 2144 | /** 2145 | If in print to memory mode, return a pointer to 2146 | the XML file in memory. 2147 | */ 2148 | const char* CStr() const { 2149 | return _buffer.Mem(); 2150 | } 2151 | /** 2152 | If in print to memory mode, return the size 2153 | of the XML file in memory. (Note the size returned 2154 | includes the terminating null.) 2155 | */ 2156 | int CStrSize() const { 2157 | return _buffer.Size(); 2158 | } 2159 | /** 2160 | If in print to memory mode, reset the buffer to the 2161 | beginning. 2162 | */ 2163 | void ClearBuffer() { 2164 | _buffer.Clear(); 2165 | _buffer.Push(0); 2166 | } 2167 | 2168 | protected: 2169 | virtual bool CompactMode( const XMLElement& ) { return _compactMode; } 2170 | 2171 | /** Prints out the space before an element. You may override to change 2172 | the space and tabs used. A PrintSpace() override should call Print(). 2173 | */ 2174 | virtual void PrintSpace( int depth ); 2175 | void Print( const char* format, ... ); 2176 | 2177 | void SealElementIfJustOpened(); 2178 | bool _elementJustOpened; 2179 | DynArray< const char*, 10 > _stack; 2180 | 2181 | private: 2182 | void PrintString( const char*, bool restrictedEntitySet ); // prints out, after detecting entities. 2183 | 2184 | bool _firstElement; 2185 | FILE* _fp; 2186 | int _depth; 2187 | int _textDepth; 2188 | bool _processEntities; 2189 | bool _compactMode; 2190 | 2191 | enum { 2192 | ENTITY_RANGE = 64, 2193 | BUF_SIZE = 200 2194 | }; 2195 | bool _entityFlag[ENTITY_RANGE]; 2196 | bool _restrictedEntityFlag[ENTITY_RANGE]; 2197 | 2198 | DynArray< char, 20 > _buffer; 2199 | }; 2200 | 2201 | 2202 | } // tinyxml2 2203 | 2204 | #if defined(_MSC_VER) 2205 | # pragma warning(pop) 2206 | #endif 2207 | 2208 | #endif // TINYXML2_INCLUDED 2209 | --------------------------------------------------------------------------------