diff --git a/CMakeLists.txt b/CMakeLists.txt index a9d53d1..0904cf1 100755 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,7 +8,7 @@ CMAKE_MINIMUM_REQUIRED(VERSION 2.8) # select build type SET( CMAKE_BUILD_TYPE "${CMAKE_BUILD_TYPE}" ) -PROJECT(graphModel) +PROJECT(Indoor) IF(NOT CMAKE_BUILD_TYPE) MESSAGE(STATUS "No build type selected. Default to Debug") @@ -36,7 +36,7 @@ FILE(GLOB SOURCES ./*.cpp ./*/*.cpp ./*/*/*.cpp - /mnt/firma/kunden/HandyGames/KLib/inc/tinyxml/*.cpp + ../KLib/inc/tinyxml/*.cpp ) @@ -64,6 +64,7 @@ ADD_DEFINITIONS( -O0 -DWITH_TESTS + -DWITH_ASSERTIONS ) diff --git a/floorplan/Floor.h b/floorplan/Floor.h index 226cf84..8074979 100755 --- a/floorplan/Floor.h +++ b/floorplan/Floor.h @@ -2,7 +2,7 @@ #define FLOOR_H #include -#include "../geo/Line2D.h" +#include "../geo/Line2.h" /** * represents one floor by describing all contained obstacles @@ -13,7 +13,7 @@ private: /** all obstacles within the floor */ - std::vector lines; + std::vector lines; /** total width of the floor (in meter) */ double width_cm; @@ -28,12 +28,12 @@ public: Floor(const float width_cm, const float depth_cm) : width_cm(width_cm), depth_cm(depth_cm) {;} /** get all obstacles */ - const std::vector& getObstacles() const { + const std::vector& getObstacles() const { return lines; } /** add a new obstacle to this floor */ - void addObstacle(const Line2D& l ) { + void addObstacle(const Line2& l ) { lines.push_back(l); } diff --git a/floorplan/FloorplanFactorySVG.h b/floorplan/FloorplanFactorySVG.h index 9154431..d4a9515 100755 --- a/floorplan/FloorplanFactorySVG.h +++ b/floorplan/FloorplanFactorySVG.h @@ -2,6 +2,8 @@ #define FLOORPLANFACTORYSVG_H #include "Floor.h" +#include "Stairs.h" + #include #include "../Exception.h" @@ -32,21 +34,21 @@ class FloorplanFactorySVG { } /** scale (x, y) into (_x, _y) */ - void scale(const double x, const double y, double& _x, double& _y) const { + void scale(const double x, const double y, float& _x, float& _y) const { _x = x * scalingFactor; _y = y * scalingFactor; } - /** scale the given point into a new output point */ - K::Point scale(const K::Point p) const { - K::Point ret; - scale (p.x, p.y, ret.x, ret.y); - return ret; - } +// /** scale the given point into a new output point */ +// K::Point scale(const K::Point p) const { +// K::Point ret; +// scale (p.x, p.y, ret.x, ret.y); +// return ret; +// } /** scale the given line into a new output line */ - Line2D scale(const K::Line l) const { - Line2D ret; + Line2 scale(const K::Line l) const { + Line2 ret; scale (l.p1.x, l.p1.y, ret.p1.x, ret.p1.y); scale (l.p2.x, l.p2.y, ret.p2.x, ret.p2.y); return ret; @@ -58,8 +60,8 @@ private: K::SVGFile svg; SVGScaler scaler; - double width; - double depth; + float width; + float depth; public: @@ -88,22 +90,38 @@ public: // create and parse the new floor Floor floor(width, depth); - load(layer, floor); + loadFloor(layer, floor); return floor; } + /** get all stairs within the given layer */ + Stairs getStairs(const std::string& layerName) { + + // get the requested SVG layer + K::SVGComposite* sc = svg.getLayers(); + K::SVGLayer* layer = sc->getContainedLayerNamed(layerName); + if (!layer) {throw Exception("SVG has no layer named '" + layerName + "'");} + + // create and parse the new floor + Stairs stairs; + loadStairs(layer, stairs); + return stairs; + + + } + private: /** recursive loading/parsing of nested SVG elements */ - void load(K::SVGElement* el, Floor& floor) { + void loadFloor(K::SVGElement* el, Floor& floor) { switch (el->getType()) { case SVGElementType::COMPOSITE: { for (K::SVGElement* sub : ((K::SVGComposite*)el)->getChilds()) { - load(sub, floor); + loadFloor(sub, floor); } break; } @@ -111,7 +129,7 @@ private: case SVGElementType::LAYER: { K::SVGLayer* layer = (K::SVGLayer*) el; for (K::SVGElement* sub : layer->getChilds()) { - load(sub, floor); + loadFloor(sub, floor); } break; } @@ -133,6 +151,60 @@ private: } } + /** recursive loading/parsing of nested SVG elements */ + void loadStairs(K::SVGElement* el, Stairs& stairs) { + + switch (el->getType()) { + + case SVGElementType::COMPOSITE: { + for (K::SVGElement* sub : ((K::SVGComposite*)el)->getChilds()) { + loadStairs(sub, stairs); + } + break; + } + + case SVGElementType::LAYER: { + K::SVGLayer* layer = (K::SVGLayer*) el; + for (K::SVGElement* sub : layer->getChilds()) { + loadStairs(sub, stairs); + } + break; + } + + case SVGElementType::PATH: { + + int i = 0; + Line2 start; + Line2 dir; + + for (const K::Line& line : ((K::SVGPath*)el)->getLines()) { + if (++i == 1) { + start = scaler.scale(line); + } else { + Stair s; + Line2 dir = scaler.scale(line); + s.dir = (dir.p2 - dir.p1); + const float d = 9; + s.from.add(start.p1 + Point2(-d,-d)); + s.from.add(start.p1 + Point2(+d,+d)); + s.from.add(start.p2 + Point2(-d,-d)); + s.from.add(start.p2 + Point2(+d,+d)); + stairs.push_back(s); + } + } + break; + } + + case SVGElementType::TEXT: { + break; + } + + default: + throw "should not happen!"; + + } + } + }; #endif // FLOORPLANFACTORYSVG_H diff --git a/floorplan/Stair.h b/floorplan/Stair.h new file mode 100644 index 0000000..e0985d1 --- /dev/null +++ b/floorplan/Stair.h @@ -0,0 +1,17 @@ +#ifndef STAIR_H +#define STAIR_H + +#include "../geo/BBox2.h" +#include "../geo/Point2.h" + +struct Stair { + + /** bbox with all starting points */ + BBox2 from; + + /** the direction to move all the starting points to */ + Point2 dir; + +}; + +#endif // STAIR_H diff --git a/floorplan/Stairs.h b/floorplan/Stairs.h new file mode 100644 index 0000000..2982f7c --- /dev/null +++ b/floorplan/Stairs.h @@ -0,0 +1,11 @@ +#ifndef STAIRS_H +#define STAIRS_H + +#include +#include "Stair.h" + +class Stairs : public std::vector { + +}; + +#endif // STAIRS_H diff --git a/geo/Angle.h b/geo/Angle.h index d3cc1ab..f177cab 100755 --- a/geo/Angle.h +++ b/geo/Angle.h @@ -2,20 +2,34 @@ #define ANGLE_H #include +#include class Angle { public: - /** get the radians from (x1,y1) to (x2,y2) */ - static float getRAD(const float x1, const float y1, const float x2, const float y2) { + /** get the radians from (x1,y1) to (x2,y2) between 0 (to-the-right) and <2_PI */ + static float getRAD_2PI(const float x1, const float y1, const float x2, const float y2) { + _assertFalse( (x1==x2)&&(y1==y2), "(x1,y1) must not equal (x2,y2)!!"); const float tmp = std::atan2(y2-y1, x2-x1); return (tmp < 0) ? (tmp + 2*M_PI) : (tmp); } - /** get the degrees from (x1,y1) to (x2,y2) */ - static float getDEG(const float x1, const float y1, const float x2, const float y2) { - return radToDeg(getRAD(x1,y1,x2,y2)); + /** get the degrees from (x1,y1) to (x2,y2) between 0 (to-the-right) and <360 */ + static float getDEG_360(const float x1, const float y1, const float x2, const float y2) { + return radToDeg(getRAD_2PI(x1,y1,x2,y2)); + } + + /** + * gets the angular difference between + * - the given radians [0:2PI] + * - as a change-in-direction between [0:PI] + */ + static float getDiffRAD_2PI_PI(const float r1, const float r2) { + _assertBetween(r1, 0, 2*M_PI, "r1 out of bounds"); + _assertBetween(r2, 0, 2*M_PI, "r2 out of bounds"); + return fmod(std::abs(r2 - r1), M_PI); + } /** convert degrees to radians */ diff --git a/geo/BBox2.h b/geo/BBox2.h new file mode 100644 index 0000000..35d7535 --- /dev/null +++ b/geo/BBox2.h @@ -0,0 +1,71 @@ +#ifndef BBOX2_H +#define BBOX2_H + +#include "Point2.h" +#include "Line2.h" + +class BBox2 { + +protected: + + static constexpr float MAX = +99999; + static constexpr float MIN = -99999; + + /** minimum */ + Point2 p1; + + /** maximum */ + Point2 p2; + +public: + + BBox2() : p1(MAX,MAX), p2(MIN,MIN) {;} + + /** adjust the bounding-box by adding this point */ + void add(const Point2& p) { + + if (p.x > p2.x) {p2.x = p.x;} + if (p.y > p2.y) {p2.y = p.y;} + + if (p.x < p1.x) {p1.x = p.x;} + if (p.y < p1.y) {p1.y = p.y;} + + } + + /** get the bbox's minimum */ + const Point2& getMin() const {return p1;} + + /** get the bbox's maximum */ + const Point2& getMax() const {return p2;} + + /** equal? */ + bool operator == (const BBox2& o) const { + return (p1.x == o.p1.x) && + (p1.y == o.p1.y) && + (p2.x == o.p2.x) && + (p2.y == o.p2.y); + } + + /** does the BBox intersect with the given line? */ + bool intersects (const Line2& l) const { + Line2 l1(p1.x, p1.y, p2.x, p1.y); // upper + Line2 l2(p1.x, p2.y, p2.x, p2.y); // lower + Line2 l3(p1.x, p1.y, p1.x, p2.y); // left + Line2 l4(p2.x, p1.y, p2.x, p2.y); // right + return l.getSegmentIntersection(l1) || + l.getSegmentIntersection(l2) || + l.getSegmentIntersection(l3) || + l.getSegmentIntersection(l4); + } + + bool contains(const Point2& p) const { + if (p.x < p1.x) {return false;} + if (p.x > p2.x) {return false;} + if (p.y < p1.y) {return false;} + if (p.y > p2.y) {return false;} + return true; + } + +}; + +#endif // BBOX2_H diff --git a/geo/BBox3.h b/geo/BBox3.h new file mode 100644 index 0000000..e270978 --- /dev/null +++ b/geo/BBox3.h @@ -0,0 +1,54 @@ +#ifndef BBOX3_H +#define BBOX3_H + +#include "Point3.h" + +class BBox3 { + +private: + + static constexpr float MAX = +99999; + static constexpr float MIN = -99999; + + /** minimum */ + Point3 p1; + + /** maximum */ + Point3 p2; + +public: + + BBox3() : p1(MAX,MAX,MAX), p2(MIN,MIN,MIN) {;} + + /** adjust the bounding-box by adding this point */ + void add(const Point3& p) { + + if (p.x > p2.x) {p2.x = p.x;} + if (p.y > p2.y) {p2.y = p.y;} + if (p.z > p2.z) {p2.z = p.z;} + + if (p.x < p1.x) {p1.x = p.x;} + if (p.y < p1.y) {p1.y = p.y;} + if (p.z < p1.z) {p1.z = p.z;} + + } + + /** get the bbox's minimum */ + const Point3& getMin() const {return p1;} + + /** get the bbox's maximum */ + const Point3& getMax() const {return p2;} + + /** equal? */ + bool operator == (const BBox3& o) const { + return (p1.x == o.p1.x) && + (p1.y == o.p1.y) && + (p1.z == o.p1.z) && + (p2.x == o.p2.x) && + (p2.y == o.p2.y) && + (p2.z == o.p2.z); + } + +}; + +#endif // BBOX3_H diff --git a/geo/Line2.h b/geo/Line2.h new file mode 100755 index 0000000..64d6c4f --- /dev/null +++ b/geo/Line2.h @@ -0,0 +1,54 @@ +#ifndef LINE2D_H +#define LINE2D_H + +//#include +#include "Point2.h" + +class Line2 { + +public: + + Point2 p1; + + Point2 p2; + +public: + + Line2() : p1(), p2() {;} + + Line2(const float x1, const float y1, const float x2, const float y2) : p1(x1,y1), p2(x2,y2) {;} + +// bool getSegmentIntersection(const Line& other) const { +// static K::Point p; +// return K::Line::getSegmentIntersection(other, p); +// } + + + bool getSegmentIntersection(const Line2& other) const { + + const double bx = p2.x - p1.x; + const double by = p2.y - p1.y; + + const double dx = other.p2.x - other.p1.x; + const double dy = other.p2.y - other.p1.y; + + const double b_dot_d_perp = bx*dy - by*dx; + + if(b_dot_d_perp == 0) {return false;} + + const double cx = other.p1.x - p1.x; + const double cy = other.p1.y - p1.y; + + const double t = (cx * dy - cy * dx) / b_dot_d_perp; + if(t < 0 || t > 1) {return false;} + + const double u = (cx * by - cy * bx) / b_dot_d_perp; + if(u < 0 || u > 1) {return false;} + + return true; + + } + +}; + +#endif // LINE2D_H diff --git a/geo/Line2D.h b/geo/Line2D.h deleted file mode 100755 index a4389b8..0000000 --- a/geo/Line2D.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef LINE2D_H -#define LINE2D_H - -#include - -class Line2D : public K::Line { - -public: - - Line2D() : K::Line() {;} - - Line2D(const float x1, const float y1, const float x2, const float y2) : K::Line(x1,y1,x2,y2) {;} - - bool getSegmentIntersection(const Line& other) const { - static K::Point p; - return K::Line::getSegmentIntersection(other, p); - } - -}; - -#endif // LINE2D_H diff --git a/geo/Point2.h b/geo/Point2.h new file mode 100644 index 0000000..907f145 --- /dev/null +++ b/geo/Point2.h @@ -0,0 +1,24 @@ +#ifndef POINT2_H +#define POINT2_H + +/** + * 2D Point + */ +struct Point2 { + + float x; + float y; + + /** ctor */ + Point2() : x(0), y(0) {;} + + /** ctor */ + Point2(const float x, const float y) : x(x), y(y) {;} + + Point2 operator + (const Point2& o) const {return Point2(x+o.x, y+o.y);} + + Point2 operator - (const Point2& o) const {return Point2(x-o.x, y-o.y);} + +}; + +#endif // POINT2_H diff --git a/geo/Point3.h b/geo/Point3.h new file mode 100644 index 0000000..98963f4 --- /dev/null +++ b/geo/Point3.h @@ -0,0 +1,29 @@ +#ifndef POINT3_H +#define POINT3_H + +/** + * 3D Point + */ +struct Point3 { + + float x; + float y; + float z; + + /** ctor */ + Point3() : x(0), y(0), z(0) {;} + + /** ctor */ + Point3(const float x, const float y, const float z) : x(x), y(y), z(z) {;} + + + + Point3 operator + (const Point3& o) const {return Point3(x+o.x, y+o.y, z+o.z);} + + Point3 operator - (const Point3& o) const {return Point3(x-o.x, y-o.y, z-o.z);} + + Point3 operator * (const float v) const {return Point3(v*x, v*y, v*z);} + +}; + +#endif // POINT3_H diff --git a/grid/Grid.h b/grid/Grid.h index 7f22973..a1db2f5 100755 --- a/grid/Grid.h +++ b/grid/Grid.h @@ -9,6 +9,9 @@ #include "GridNode.h" #include +#include +#include "../geo/BBox3.h" + /** * grid of the given grid-size, storing some value which * extends GridPoint @@ -47,6 +50,11 @@ public: */ int add(const T& elem) { assertAligned(elem); // assert that the to-be-added element is aligned to the grid + return addUnaligned(elem); + } + + /** add the given (not necessarly aligned) element to the grid */ + int addUnaligned(const T& elem) { const int idx = nodes.size(); // next free index const UID uid = getUID(elem); // get the UID for this new element nodes.push_back(elem); // add it to the grid @@ -55,27 +63,39 @@ public: return idx; // done } + /** connect (uni-dir) i1 -> i2 */ + void connectUniDir(const int idx1, const int idx2) { + connectUniDir(nodes[idx1], nodes[idx2]); + } + + /** connect (uni-dir) i1 -> i2 */ + void connectUniDir(T& n1, const T& n2) { + n1._neighbors[n1._numNeighbors] = n2._idx; + ++n1._numNeighbors; + if (n1._numNeighbors > 12) { + int i = 0; + } + _assertBetween(n1._numNeighbors, 0, 12, "number of neighbors out of bounds!"); + } + /** * connect (bi-directional) the two provided nodes * @param idx1 index of the first element * @param idx2 index of the second element */ - void connect(const int idx1, const int idx2) { - T& n1 = nodes[idx1]; // get the first element - T& n2 = nodes[idx2]; // get the second element - connect(n1, n2); + void connectBiDir(const int idx1, const int idx2) { + connectBiDir(nodes[idx1], nodes[idx2]); } + /** * connect (bi-directional) the two provided nodes * @param n1 the first node * @param n2 the second node */ - void connect(T& n1, T& n2) { - n1._neighbors[n1._numNeighbors] = n2._idx; // add them both as neighbors - n2._neighbors[n2._numNeighbors] = n1._idx; - ++n1._numNeighbors; // increment the neighbor-counter - ++n2._numNeighbors; + void connectBiDir(T& n1, T& n2) { + connectUniDir(n1, n2); + connectUniDir(n2, n1); } /** get the number of contained nodes */ @@ -93,6 +113,24 @@ public: return e._numNeighbors; } + /** get the n-th neighbor for the given node */ + T& getNeighbor(const int nodeIdx, const int nth) const { + const T& node = nodes[nodeIdx]; + return getNeighbor(node, nth); + } + + /** get the n-th neighbor for the given node */ + T& getNeighbor(const T& node, const int nth) const { + const T& neighbor = nodes[node._neighbors[nth]]; + return (T&) neighbor; + } + + /** do we have a center-point the given point belongs to? */ + bool hasNodeFor(const GridPoint& p) const { + const UID uid = getUID(p); + return (hashes.find(uid) != hashes.end()); + } + /** get the center-node the given Point belongs to */ const T& getNodeFor(const GridPoint& p) { const UID uid = getUID(p); @@ -123,10 +161,151 @@ public: } /** array access */ - const T& operator [] (const int idx) const { + T& operator [] (const int idx) { return nodes[idx]; } + /** disconnect the two nodes (bidirectional) */ + void disconnectBiDir(const int idx1, const int idx2) { + disconnectBiDir(nodes[idx1], nodes[idx2]); + } + + /** disconnect the two nodes (bidirectional) */ + void disconnectBiDir(T& n1, T& n2) { + disconnectUniDir(n1, n2); + disconnectUniDir(n2, n1); + } + + /** remove the connection from n1 to n2 (not the other way round!) */ + void disconnectUniDir(T& n1, T& n2) { + for (int n = 0; n < n1._numNeighbors; ++n) { + if (n1._neighbors[n] == n2._idx) { + arrayRemove(n1._neighbors, n, n1._numNeighbors); + --n1._numNeighbors; + return; + } + } + } + + /** remove the given array-index by moving all follwing elements down by one */ + template void arrayRemove(X* arr, const int idxToRemove, const int arrayLen) { + for (int i = idxToRemove+1; i < arrayLen; ++i) { + arr[i-1] = arr[i]; + } + } + + /** + * mark the given node for deletion + * see: cleanup() + */ + void remove(const int idx) { + remove(nodes[idx]); + } + + void remove(T& node) { + + // disconnect from all neighbors + while (node._numNeighbors) { + disconnectBiDir(node._idx, node._neighbors[0]); + } + + // remove from hash-list + hashes.erase(getUID(node)); + + // mark for deleteion (see: cleanup()) + node._idx = -1; + + } + + /** + * remove all nodes, marked for deletion. + * BEWARE: this will invalidate all indices used externally! + */ + void cleanup() { + + for (size_t i = 0; i < nodes.size(); ++i) { + if (nodes[i]._idx == -1) { + nodes.erase(nodes.begin()+i); + moveDown(i); + --i; + } + } + + } + + void moveDown(const int idx) { + for (size_t i = 0; i < nodes.size(); ++i) { + if (nodes[i]._idx >= idx) {--nodes[i]._idx;} + for (int n = 0; n < nodes[i]._numNeighbors; ++n) { + if (nodes[i]._neighbors[n] >= idx) {--nodes[i]._neighbors[n];} + } + } + } + + class NeighborIter : std::iterator { + private: + Grid& grid; + int nodeIdx; + int nIdx; + public: + NeighborIter(Grid& grid, const int nodeIdx, const int nIdx) : grid(grid), nodeIdx(nodeIdx), nIdx(nIdx) {;} + NeighborIter& operator++() {++nIdx; return *this;} + NeighborIter operator++(int) {NeighborIter tmp(*this); operator++(); return tmp;} + bool operator==(const NeighborIter& rhs) {return nodeIdx == rhs.nodeIdx && nIdx == rhs.nIdx;} + bool operator!=(const NeighborIter& rhs) {return nodeIdx != rhs.nodeIdx || nIdx != rhs.nIdx;} + T& operator*() {return (T&) grid.nodes[nodeIdx]._neighbors[nIdx];} + }; + + class NeighborForEach { + private: + Grid& grid; + int nodeIdx; + public: + NeighborForEach(Grid& grid, const int nodeIdx) : grid(grid), nodeIdx(nodeIdx) {;} + NeighborIter begin() {return NeighborIter(grid, nodeIdx, 0);} + NeighborIter end() {return NeighborIter(grid, nodeIdx, grid[nodeIdx]._numNeighbors);} + }; + + NeighborForEach neighbors(const int idx) { + return neighbors(nodes[idx]); + } + + NeighborForEach neighbors(const T& node) { + return NeighborForEach(*this, node._idx); + } + + /** get the grid's bounding-box. EXPENSIVE! */ + BBox3 getBBox() const { + BBox3 bb; + for (const T& n : nodes) { + bb.add( Point3(n.x_cm, n.y_cm, n.z_cm) ); + } + return bb; + } + + int kdtree_get_point_count() const { + return nodes.size(); + } + + template bool kdtree_get_bbox(BBOX& bb) const { return false; } + + inline float kdtree_get_pt(const size_t idx, const int dim) const { + const T& p = nodes[idx]; + if (dim == 0) {return p.x_cm;} + if (dim == 1) {return p.y_cm;} + if (dim == 2) {return p.z_cm;} + throw 1; + } + + inline float kdtree_distance(const float* p1, const size_t idx_p2, size_t) const { + const float d0 = p1[0] - nodes[idx_p2].x_cm; + const float d1 = p1[1] - nodes[idx_p2].y_cm; + const float d2 = p1[2] - nodes[idx_p2].z_cm; + return (d0*d0) + (d1*d1) + (d2*d2); + } + + + private: /** asssert that the given element is aligned to the grid */ diff --git a/grid/GridNode.h b/grid/GridNode.h index d07bf32..c092a2f 100755 --- a/grid/GridNode.h +++ b/grid/GridNode.h @@ -4,6 +4,9 @@ #include "GridNodeBBox.h" #include "GridPoint.h" +template class Grid; + + /** * INTERNAL DATASTRUCTURE * this data-structure is internally used by the Grid @@ -17,17 +20,26 @@ class GridNode { /** INTERNAL: array-index */ int _idx = -1; - /** INTERNAL: store neighbors (via index) */ + /** INTERNAL: number of neighbors */ int _numNeighbors = 0; - /** INTERNAL: number of neighbors */ - int _neighbors[10] = {}; + /** INTERNAL: store neighbors (via index) */ + int _neighbors[12] = {}; public: GridNode() {;} + /** get the node's index within its grid */ + int getIdx() const {return _idx;} + /** get the number of neighbors for this node */ + int getNumNeighbors() const {return _numNeighbors;} + + /** get the n-th neighbor for this node */ + template inline T& getNeighbor(const int nth, const Grid& grid) const { + return grid.getNeighbor(_idx, nth); + } }; diff --git a/grid/GridNodeBBox.h b/grid/GridNodeBBox.h index 229f90c..d28c7de 100755 --- a/grid/GridNodeBBox.h +++ b/grid/GridNodeBBox.h @@ -2,43 +2,21 @@ #define GRIDNODEBBOX_H #include "GridPoint.h" -#include "../geo/Line2D.h" + +#include "../geo/BBox2.h" /** * describes the 2D (one floor) * bounding-box for one node on the grid */ -struct GridNodeBBox { - - /** smaller half */ - float x1_cm, y1_cm; - - /** larger half */ - float x2_cm, y2_cm; +struct GridNodeBBox : public BBox2 { /** ctor */ GridNodeBBox(const GridPoint& center, const int gridSize_cm) { - x1_cm = center.x_cm - gridSize_cm/2; // smaller half - y1_cm = center.y_cm - gridSize_cm/2; - x2_cm = center.x_cm + gridSize_cm/2; // larger half - y2_cm = center.y_cm + gridSize_cm/2; - } - - /** equal? */ - bool operator == (const GridNodeBBox& o) const { - return (x1_cm == o.x1_cm) && (y1_cm == o.y1_cm) && (x2_cm == o.x2_cm) && (y2_cm == o.y2_cm); - } - - /** does the BBox intersect with the given line? */ - bool intersects (const Line2D& l) const { - Line2D l1(x1_cm, y1_cm, x2_cm, y1_cm); // upper - Line2D l2(x1_cm, y2_cm, x2_cm, y2_cm); // lower - Line2D l3(x1_cm, y1_cm, x1_cm, y2_cm); // left - Line2D l4(x2_cm, y1_cm, x2_cm, y2_cm); // right - return l.getSegmentIntersection(l1) || - l.getSegmentIntersection(l2) || - l.getSegmentIntersection(l3) || - l.getSegmentIntersection(l4); + p1.x = center.x_cm - gridSize_cm/2; // smaller half + p1.y = center.y_cm - gridSize_cm/2; + p2.x = center.x_cm + gridSize_cm/2; // larger half + p2.y = center.y_cm + gridSize_cm/2; } }; diff --git a/grid/GridPoint.h b/grid/GridPoint.h index 801d807..d8e45a5 100755 --- a/grid/GridPoint.h +++ b/grid/GridPoint.h @@ -6,13 +6,13 @@ struct GridPoint { /** x-position (in centimeter) */ - const float x_cm; + float x_cm; /** y-position (in centimeter) */ - const float y_cm; + float y_cm; /** z-position (in centimeter) */ - const float z_cm; + float z_cm; /** empty ctor */ diff --git a/grid/factory/GridFactory.h b/grid/factory/GridFactory.h index 753c00a..fa10e3c 100755 --- a/grid/factory/GridFactory.h +++ b/grid/factory/GridFactory.h @@ -3,6 +3,8 @@ #include #include "../../floorplan/Floor.h" +#include "../../floorplan/Stairs.h" + #include "../../geo/Units.h" #include "../GridNodeBBox.h" #include "../Grid.h" @@ -22,6 +24,8 @@ public: /** add the given floor at the provided height (in cm) */ void addFloor(const Floor& floor, const float z_cm) { + + // build grid-points for(int x_cm = 0; x_cm < floor.getWidth_cm(); x_cm += gridSize_cm) { for (int y_cm = 0; y_cm < floor.getDepth_cm(); y_cm += gridSize_cm) { @@ -35,7 +39,181 @@ public: } } - int i = 0; + connectAdjacent(z_cm); + + } + + void connectAdjacent(const float z_cm) { + + // connect adjacent grid-points + for (int idx = 0; idx < grid.getNumNodes(); ++idx) { + + T& n1 = (T&) grid[idx]; + if (n1.z_cm != z_cm) {continue;} // ugly... different floor -> skip + + // square around each point + for (int x = -gridSize_cm; x <= gridSize_cm; x += gridSize_cm) { + for (int y = -gridSize_cm; y <= gridSize_cm; y += gridSize_cm) { + + // skip the center (node itself) + if ((x == y) && (x == 0)) {continue;} + + // position of the potential neighbor + int ox = n1.x_cm + x; + int oy = n1.y_cm + y; + GridPoint p(ox, oy, n1.z_cm); + + // does the grid contain the potential neighbor? + if (grid.hasNodeFor(p)) { + T& n2 = (T&) grid.getNodeFor(p); + grid.connectUniDir(n1, n2); + } + + } + } + + } + + } + + + void addStairs(const Stairs& stairs, const float z1_cm, const float z2_cm) { + + for (const Stair& s : stairs) { + + for (int i = 0; i < grid.getNumNodes(); ++i) { + + // potential starting-point for the stair + T& n = (T&) grid[i]; + + // real starting point for the stair? + if (s.from.contains( Point2(n.x_cm, n.y_cm) )) { + + // construct end-point by using the stair's direction + const Point3 end = Point3(n.x_cm, n.y_cm, n.z_cm) + Point3(s.dir.x, s.dir.y, (z2_cm-z1_cm)); + GridPoint gp(end.x, end.y, end.z); + + // does such and end-point exist within the grap? -> construct stair + if (grid.hasNodeFor(gp)) { + T& n2 = (T&) grid.getNodeFor(gp); + + buildStair(n, n2); + + } + int i = 0; + } + } + + } + + } + + /** build a stair (z-transition) from n1 to n2 */ + void buildStair(T& n1, T& n2) { + + //TODO: ensure n1 is below n2 + const float zDiff = n2.z_cm - n1.z_cm; + const float xDiff = n2.x_cm - n1.x_cm; + const float yDiff = n2.y_cm - n1.y_cm; + + int idx1 = n1.getIdx(); + int idx2 = -1; + const int idx3 = n2.getIdx(); + + // move upards in gridSize steps + for (int z = gridSize_cm; z < zDiff; z+= gridSize_cm) { + + // calculate the percentage of reached upwards-distance + const float percent = z/zDiff; + + // adjust (x,y) accordingly (interpolate) + int x = n1.x_cm + xDiff * percent; + int y = n1.y_cm + yDiff * percent; + + // snap (x,y) to the grid??? + //x = std::round(x / gridSize_cm) * gridSize_cm; + //y = std::round(y / gridSize_cm) * gridSize_cm; + + // create a new node add it to the grid, and connect it with the previous one + idx2 = grid.addUnaligned(T(x,y,z)); + grid.connectBiDir(idx1, idx2); + idx1 = idx2; + + } + + // add the last segment + if (idx2 != -1) { + grid.connectBiDir(idx2, idx3); + } + + } + + /** add the inverted version of the given z-layer */ + void addInverted(const Grid& gIn, const float z_cm) { + + // get the original grid's bbox + BBox3 bb = gIn.getBBox(); + + // build new grid-points + for(int x_cm = bb.getMin().x; x_cm <= bb.getMax().x; x_cm += gridSize_cm) { + for (int y_cm = bb.getMin().y; y_cm < bb.getMax().y; y_cm += gridSize_cm) { + + // does the input-grid contain such a point? + GridPoint gp(x_cm, y_cm, z_cm); + if (gIn.hasNodeFor(gp)) {continue;} + + // add to the grid + grid.add(T(x_cm, y_cm, z_cm)); + + } + } + + } + + // TODO: how to determine the starting index?! + + // IDEAS: find all segments: + // start at a random point, add all connected points to the set + // start at a NEW random point ( not part of the already processed points), add connected points to a new set + // repeat until all points processed + // how to handle multiple floor layers?!?! + // run after all floors AND staircases were added?? + // OR: random start, check segment size, < 50% of all nodes? start again + + void removeIsolated() { + + // get largest connected region + std::set set; + do { + const int idxStart = rand() % grid.getNumNodes(); + set.clear(); + getConnected(idxStart, set); + } while (set.size() < 0.5 * grid.getNumNodes()); + + + // remove all other + for (int i = 0; i < grid.getNumNodes(); ++i) { + if (set.find(i) == set.end()) {grid.remove(i);} + } + + // clean the grid + grid.cleanup(); + + } + +private: + + /** recursively get all connected nodes and add them to the set */ + void getConnected(const int idx, std::set& set) { + + T& n1 = (T&) grid[idx]; + set.insert(n1.getIdx()); + + for (T& n2 : grid.neighbors(n1)) { + if (set.find(n2.getIdx()) == set.end()) { + getConnected(n2.getIdx(), set); + } + } } @@ -43,7 +221,7 @@ private: /** does the bbox intersect with any of the floor's walls? */ bool intersects(const GridNodeBBox& bbox, const Floor& floor) { - for (const Line2D l : floor.getObstacles()) { + for (const Line2& l : floor.getObstacles()) { if (bbox.intersects(l)) {return true;} } return false; diff --git a/grid/factory/GridImportance.h b/grid/factory/GridImportance.h new file mode 100644 index 0000000..23d832a --- /dev/null +++ b/grid/factory/GridImportance.h @@ -0,0 +1,84 @@ +#ifndef GRIDIMPORTANCE_H +#define GRIDIMPORTANCE_H + +#include "../Grid.h" +#include "GridFactory.h" +#include "../../misc/KNN.h" + +#include + +class GridImportance { + +public: + + /** attach importance-factors to the grid */ + template void addImportance(Grid& g, const float z_cm) { + + // get an inverted version of the grid + Grid inv; + GridFactory fac(inv); + fac.addInverted(g, z_cm); + + // construct KNN search + KNN, T, 3> knn(inv); + + for (int idx = 0; idx < g.getNumNodes(); ++idx) { + + // process each point + T& n1 = (T&) g[idx]; + +// // get its nearest neighbor +// size_t idxNear; +// float distSquared; +// float point[3] = {n1.x_cm, n1.y_cm, n1.z_cm}; +// knn.getNearest(point, idxNear, distSquared); + +// // calculate importante +// const float imp = importance( Units::cmToM(std::sqrt(distSquared)) ); +// n1.imp = imp; + + size_t indices[10]; + float squaredDist[10]; + float point[3] = {n1.x_cm, n1.y_cm, n1.z_cm}; + knn.get(point, 10, indices, squaredDist); + + const float imp1 = importance( Units::cmToM(std::sqrt(squaredDist[0])) ); + const float imp2 = door( indices ); + n1.imp = (imp1 + imp2)/2; + + } + + + + } + + float door( size_t* indices ) { + + // build covariance + + //if (dist1_m > 1.0) {return 1;} + //return 1.0 - std::abs(dist1_m - dist2_m); + return 1; + } + + float importance(float dist_m) { + + static K::NormalDistribution d1(0.0, 0.5); + //if (dist_m > 1.5) {dist_m = 1.5;} + return 1.0 - d1.getProbability(dist_m) * 0.5; + +// static K::NormalDistribution d1(1.0, 0.75); +// //static K::NormalDistribution d2(3.0, 0.75); + +// if (dist_m > 3.0) {dist_m = 3.0;} +// return 0.8 + d1.getProbability(dist_m);// + d2.getProbability(dist_m); + +// if (dist_m < 0.5) {return 0.8;} +// if (dist_m < 1.5) {return 1.2;} +// if (dist_m < 2.5) {return 0.8;} +// else {return 1.2;} + } + +}; + +#endif // GRIDIMPORTANCE_H diff --git a/lib/nanoflann/nanoflann.hpp b/lib/nanoflann/nanoflann.hpp new file mode 100644 index 0000000..edae826 --- /dev/null +++ b/lib/nanoflann/nanoflann.hpp @@ -0,0 +1,1397 @@ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * Copyright 2011-2014 Jose Luis Blanco (joseluisblancoc@gmail.com). + * All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +/** \mainpage nanoflann C++ API documentation + * nanoflann is a C++ header-only library for building KD-Trees, mostly + * optimized for 2D or 3D point clouds. + * + * nanoflann does not require compiling or installing, just an + * #include in your code. + * + * See: + * - C++ API organized by modules + * - Online README + */ + +#ifndef NANOFLANN_HPP_ +#define NANOFLANN_HPP_ + +#include +#include +#include +#include +#include // for fwrite() +#include // for fabs(),... +#include + +// Avoid conflicting declaration of min/max macros in windows headers +#if !defined(NOMINMAX) && (defined(_WIN32) || defined(_WIN32_) || defined(WIN32) || defined(_WIN64)) +# define NOMINMAX +# ifdef max +# undef max +# undef min +# endif +#endif + +namespace nanoflann +{ +/** @addtogroup nanoflann_grp nanoflann C++ library for ANN + * @{ */ + + /** Library version: 0xMmP (M=Major,m=minor,P=patch) */ + #define NANOFLANN_VERSION 0x119 + + /** @addtogroup result_sets_grp Result set classes + * @{ */ + template + class KNNResultSet + { + IndexType * indices; + DistanceType* dists; + CountType capacity; + CountType count; + + public: + inline KNNResultSet(CountType capacity_) : indices(0), dists(0), capacity(capacity_), count(0) + { + } + + inline void init(IndexType* indices_, DistanceType* dists_) + { + indices = indices_; + dists = dists_; + count = 0; + if (capacity) + dists[capacity-1] = (std::numeric_limits::max)(); + } + + inline CountType size() const + { + return count; + } + + inline bool full() const + { + return count == capacity; + } + + + inline void addPoint(DistanceType dist, IndexType index) + { + CountType i; + for (i=count; i>0; --i) { +#ifdef NANOFLANN_FIRST_MATCH // If defined and two points have the same distance, the one with the lowest-index will be returned first. + if ( (dists[i-1]>dist) || ((dist==dists[i-1])&&(indices[i-1]>index)) ) { +#else + if (dists[i-1]>dist) { +#endif + if (i + class RadiusResultSet + { + public: + const DistanceType radius; + + std::vector >& m_indices_dists; + + inline RadiusResultSet(DistanceType radius_, std::vector >& indices_dists) : radius(radius_), m_indices_dists(indices_dists) + { + init(); + } + + inline ~RadiusResultSet() { } + + inline void init() { clear(); } + inline void clear() { m_indices_dists.clear(); } + + inline size_t size() const { return m_indices_dists.size(); } + + inline bool full() const { return true; } + + inline void addPoint(DistanceType dist, IndexType index) + { + if (dist 0 + */ + std::pair worst_item() const + { + if (m_indices_dists.empty()) throw std::runtime_error("Cannot invoke RadiusResultSet::worst_item() on an empty list of results."); + typedef typename std::vector >::const_iterator DistIt; + DistIt it = std::max_element(m_indices_dists.begin(), m_indices_dists.end()); + return *it; + } + }; + + /** operator "<" for std::sort() */ + struct IndexDist_Sorter + { + /** PairType will be typically: std::pair */ + template + inline bool operator()(const PairType &p1, const PairType &p2) const { + return p1.second < p2.second; + } + }; + + /** @} */ + + + /** @addtogroup loadsave_grp Load/save auxiliary functions + * @{ */ + template + void save_value(FILE* stream, const T& value, size_t count = 1) + { + fwrite(&value, sizeof(value),count, stream); + } + + template + void save_value(FILE* stream, const std::vector& value) + { + size_t size = value.size(); + fwrite(&size, sizeof(size_t), 1, stream); + fwrite(&value[0], sizeof(T), size, stream); + } + + template + void load_value(FILE* stream, T& value, size_t count = 1) + { + size_t read_cnt = fread(&value, sizeof(value), count, stream); + if (read_cnt != count) { + throw std::runtime_error("Cannot read from file"); + } + } + + + template + void load_value(FILE* stream, std::vector& value) + { + size_t size; + size_t read_cnt = fread(&size, sizeof(size_t), 1, stream); + if (read_cnt!=1) { + throw std::runtime_error("Cannot read from file"); + } + value.resize(size); + read_cnt = fread(&value[0], sizeof(T), size, stream); + if (read_cnt!=size) { + throw std::runtime_error("Cannot read from file"); + } + } + /** @} */ + + + /** @addtogroup metric_grp Metric (distance) classes + * @{ */ + + template inline T abs(T x) { return (x<0) ? -x : x; } + template<> inline int abs(int x) { return ::abs(x); } + template<> inline float abs(float x) { return fabsf(x); } + template<> inline double abs(double x) { return fabs(x); } + template<> inline long double abs(long double x) { return fabsl(x); } + + /** Manhattan distance functor (generic version, optimized for high-dimensionality data sets). + * Corresponding distance traits: nanoflann::metric_L1 + * \tparam T Type of the elements (e.g. double, float, uint8_t) + * \tparam _DistanceType Type of distance variables (must be signed) (e.g. float, double, int64_t) + */ + template + struct L1_Adaptor + { + typedef T ElementType; + typedef _DistanceType DistanceType; + + const DataSource &data_source; + + L1_Adaptor(const DataSource &_data_source) : data_source(_data_source) { } + + inline DistanceType operator()(const T* a, const size_t b_idx, size_t size, DistanceType worst_dist = -1) const + { + DistanceType result = DistanceType(); + const T* last = a + size; + const T* lastgroup = last - 3; + size_t d = 0; + + /* Process 4 items with each loop for efficiency. */ + while (a < lastgroup) { + const DistanceType diff0 = nanoflann::abs(a[0] - data_source.kdtree_get_pt(b_idx,d++)); + const DistanceType diff1 = nanoflann::abs(a[1] - data_source.kdtree_get_pt(b_idx,d++)); + const DistanceType diff2 = nanoflann::abs(a[2] - data_source.kdtree_get_pt(b_idx,d++)); + const DistanceType diff3 = nanoflann::abs(a[3] - data_source.kdtree_get_pt(b_idx,d++)); + result += diff0 + diff1 + diff2 + diff3; + a += 4; + if ((worst_dist>0)&&(result>worst_dist)) { + return result; + } + } + /* Process last 0-3 components. Not needed for standard vector lengths. */ + while (a < last) { + result += nanoflann::abs( *a++ - data_source.kdtree_get_pt(b_idx,d++) ); + } + return result; + } + + template + inline DistanceType accum_dist(const U a, const V b, int ) const + { + return nanoflann::abs(a-b); + } + }; + + /** Squared Euclidean distance functor (generic version, optimized for high-dimensionality data sets). + * Corresponding distance traits: nanoflann::metric_L2 + * \tparam T Type of the elements (e.g. double, float, uint8_t) + * \tparam _DistanceType Type of distance variables (must be signed) (e.g. float, double, int64_t) + */ + template + struct L2_Adaptor + { + typedef T ElementType; + typedef _DistanceType DistanceType; + + const DataSource &data_source; + + L2_Adaptor(const DataSource &_data_source) : data_source(_data_source) { } + + inline DistanceType operator()(const T* a, const size_t b_idx, size_t size, DistanceType worst_dist = -1) const + { + DistanceType result = DistanceType(); + const T* last = a + size; + const T* lastgroup = last - 3; + size_t d = 0; + + /* Process 4 items with each loop for efficiency. */ + while (a < lastgroup) { + const DistanceType diff0 = a[0] - data_source.kdtree_get_pt(b_idx,d++); + const DistanceType diff1 = a[1] - data_source.kdtree_get_pt(b_idx,d++); + const DistanceType diff2 = a[2] - data_source.kdtree_get_pt(b_idx,d++); + const DistanceType diff3 = a[3] - data_source.kdtree_get_pt(b_idx,d++); + result += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3; + a += 4; + if ((worst_dist>0)&&(result>worst_dist)) { + return result; + } + } + /* Process last 0-3 components. Not needed for standard vector lengths. */ + while (a < last) { + const DistanceType diff0 = *a++ - data_source.kdtree_get_pt(b_idx,d++); + result += diff0 * diff0; + } + return result; + } + + template + inline DistanceType accum_dist(const U a, const V b, int ) const + { + return (a-b)*(a-b); + } + }; + + /** Squared Euclidean (L2) distance functor (suitable for low-dimensionality datasets, like 2D or 3D point clouds) + * Corresponding distance traits: nanoflann::metric_L2_Simple + * \tparam T Type of the elements (e.g. double, float, uint8_t) + * \tparam _DistanceType Type of distance variables (must be signed) (e.g. float, double, int64_t) + */ + template + struct L2_Simple_Adaptor + { + typedef T ElementType; + typedef _DistanceType DistanceType; + + const DataSource &data_source; + + L2_Simple_Adaptor(const DataSource &_data_source) : data_source(_data_source) { } + + inline DistanceType operator()(const T* a, const size_t b_idx, size_t size) const { + return data_source.kdtree_distance(a,b_idx,size); + } + + template + inline DistanceType accum_dist(const U a, const V b, int ) const + { + return (a-b)*(a-b); + } + }; + + /** Metaprogramming helper traits class for the L1 (Manhattan) metric */ + struct metric_L1 { + template + struct traits { + typedef L1_Adaptor distance_t; + }; + }; + /** Metaprogramming helper traits class for the L2 (Euclidean) metric */ + struct metric_L2 { + template + struct traits { + typedef L2_Adaptor distance_t; + }; + }; + /** Metaprogramming helper traits class for the L2_simple (Euclidean) metric */ + struct metric_L2_Simple { + template + struct traits { + typedef L2_Simple_Adaptor distance_t; + }; + }; + + /** @} */ + + /** @addtogroup param_grp Parameter structs + * @{ */ + + /** Parameters (see README.md) */ + struct KDTreeSingleIndexAdaptorParams + { + KDTreeSingleIndexAdaptorParams(size_t _leaf_max_size = 10) : + leaf_max_size(_leaf_max_size) + {} + + size_t leaf_max_size; + }; + + /** Search options for KDTreeSingleIndexAdaptor::findNeighbors() */ + struct SearchParams + { + /** Note: The first argument (checks_IGNORED_) is ignored, but kept for compatibility with the FLANN interface */ + SearchParams(int checks_IGNORED_ = 32, float eps_ = 0, bool sorted_ = true ) : + checks(checks_IGNORED_), eps(eps_), sorted(sorted_) {} + + int checks; //!< Ignored parameter (Kept for compatibility with the FLANN interface). + float eps; //!< search for eps-approximate neighbours (default: 0) + bool sorted; //!< only for radius search, require neighbours sorted by distance (default: true) + }; + /** @} */ + + + /** @addtogroup memalloc_grp Memory allocation + * @{ */ + + /** + * Allocates (using C's malloc) a generic type T. + * + * Params: + * count = number of instances to allocate. + * Returns: pointer (of type T*) to memory buffer + */ + template + inline T* allocate(size_t count = 1) + { + T* mem = static_cast( ::malloc(sizeof(T)*count)); + return mem; + } + + + /** + * Pooled storage allocator + * + * The following routines allow for the efficient allocation of storage in + * small chunks from a specified pool. Rather than allowing each structure + * to be freed individually, an entire pool of storage is freed at once. + * This method has two advantages over just using malloc() and free(). First, + * it is far more efficient for allocating small objects, as there is + * no overhead for remembering all the information needed to free each + * object or consolidating fragmented memory. Second, the decision about + * how long to keep an object is made at the time of allocation, and there + * is no need to track down all the objects to free them. + * + */ + + const size_t WORDSIZE=16; + const size_t BLOCKSIZE=8192; + + class PooledAllocator + { + /* We maintain memory alignment to word boundaries by requiring that all + allocations be in multiples of the machine wordsize. */ + /* Size of machine word in bytes. Must be power of 2. */ + /* Minimum number of bytes requested at a time from the system. Must be multiple of WORDSIZE. */ + + + size_t remaining; /* Number of bytes left in current block of storage. */ + void* base; /* Pointer to base of current block of storage. */ + void* loc; /* Current location in block to next allocate memory. */ + + void internal_init() + { + remaining = 0; + base = NULL; + usedMemory = 0; + wastedMemory = 0; + } + + public: + size_t usedMemory; + size_t wastedMemory; + + /** + Default constructor. Initializes a new pool. + */ + PooledAllocator() { + internal_init(); + } + + /** + * Destructor. Frees all the memory allocated in this pool. + */ + ~PooledAllocator() { + free_all(); + } + + /** Frees all allocated memory chunks */ + void free_all() + { + while (base != NULL) { + void *prev = *(static_cast( base)); /* Get pointer to prev block. */ + ::free(base); + base = prev; + } + internal_init(); + } + + /** + * Returns a pointer to a piece of new memory of the given size in bytes + * allocated from the pool. + */ + void* malloc(const size_t req_size) + { + /* Round size up to a multiple of wordsize. The following expression + only works for WORDSIZE that is a power of 2, by masking last bits of + incremented size to zero. + */ + const size_t size = (req_size + (WORDSIZE - 1)) & ~(WORDSIZE - 1); + + /* Check whether a new block must be allocated. Note that the first word + of a block is reserved for a pointer to the previous block. + */ + if (size > remaining) { + + wastedMemory += remaining; + + /* Allocate new storage. */ + const size_t blocksize = (size + sizeof(void*) + (WORDSIZE-1) > BLOCKSIZE) ? + size + sizeof(void*) + (WORDSIZE-1) : BLOCKSIZE; + + // use the standard C malloc to allocate memory + void* m = ::malloc(blocksize); + if (!m) { + fprintf(stderr,"Failed to allocate memory.\n"); + return NULL; + } + + /* Fill first word of new block with pointer to previous block. */ + static_cast(m)[0] = base; + base = m; + + size_t shift = 0; + //int size_t = (WORDSIZE - ( (((size_t)m) + sizeof(void*)) & (WORDSIZE-1))) & (WORDSIZE-1); + + remaining = blocksize - sizeof(void*) - shift; + loc = (static_cast(m) + sizeof(void*) + shift); + } + void* rloc = loc; + loc = static_cast(loc) + size; + remaining -= size; + + usedMemory += size; + + return rloc; + } + + /** + * Allocates (using this pool) a generic type T. + * + * Params: + * count = number of instances to allocate. + * Returns: pointer (of type T*) to memory buffer + */ + template + T* allocate(const size_t count = 1) + { + T* mem = static_cast(this->malloc(sizeof(T)*count)); + return mem; + } + + }; + /** @} */ + + /** @addtogroup nanoflann_metaprog_grp Auxiliary metaprogramming stuff + * @{ */ + + // ---------------- CArray ------------------------- + /** A STL container (as wrapper) for arrays of constant size defined at compile time (class imported from the MRPT project) + * This code is an adapted version from Boost, modifed for its integration + * within MRPT (JLBC, Dec/2009) (Renamed array -> CArray to avoid possible potential conflicts). + * See + * http://www.josuttis.com/cppcode + * for details and the latest version. + * See + * http://www.boost.org/libs/array for Documentation. + * for documentation. + * + * (C) Copyright Nicolai M. Josuttis 2001. + * Permission to copy, use, modify, sell and distribute this software + * is granted provided this copyright notice appears in all copies. + * This software is provided "as is" without express or implied + * warranty, and with no claim as to its suitability for any purpose. + * + * 29 Jan 2004 - minor fixes (Nico Josuttis) + * 04 Dec 2003 - update to synch with library TR1 (Alisdair Meredith) + * 23 Aug 2002 - fix for Non-MSVC compilers combined with MSVC libraries. + * 05 Aug 2001 - minor update (Nico Josuttis) + * 20 Jan 2001 - STLport fix (Beman Dawes) + * 29 Sep 2000 - Initial Revision (Nico Josuttis) + * + * Jan 30, 2004 + */ + template + class CArray { + public: + T elems[N]; // fixed-size array of elements of type T + + public: + // type definitions + typedef T value_type; + typedef T* iterator; + typedef const T* const_iterator; + typedef T& reference; + typedef const T& const_reference; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; + + // iterator support + inline iterator begin() { return elems; } + inline const_iterator begin() const { return elems; } + inline iterator end() { return elems+N; } + inline const_iterator end() const { return elems+N; } + + // reverse iterator support +#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) && !defined(BOOST_MSVC_STD_ITERATOR) && !defined(BOOST_NO_STD_ITERATOR_TRAITS) + typedef std::reverse_iterator reverse_iterator; + typedef std::reverse_iterator const_reverse_iterator; +#elif defined(_MSC_VER) && (_MSC_VER == 1300) && defined(BOOST_DINKUMWARE_STDLIB) && (BOOST_DINKUMWARE_STDLIB == 310) + // workaround for broken reverse_iterator in VC7 + typedef std::reverse_iterator > reverse_iterator; + typedef std::reverse_iterator > const_reverse_iterator; +#else + // workaround for broken reverse_iterator implementations + typedef std::reverse_iterator reverse_iterator; + typedef std::reverse_iterator const_reverse_iterator; +#endif + + reverse_iterator rbegin() { return reverse_iterator(end()); } + const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } + reverse_iterator rend() { return reverse_iterator(begin()); } + const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } + // operator[] + inline reference operator[](size_type i) { return elems[i]; } + inline const_reference operator[](size_type i) const { return elems[i]; } + // at() with range check + reference at(size_type i) { rangecheck(i); return elems[i]; } + const_reference at(size_type i) const { rangecheck(i); return elems[i]; } + // front() and back() + reference front() { return elems[0]; } + const_reference front() const { return elems[0]; } + reference back() { return elems[N-1]; } + const_reference back() const { return elems[N-1]; } + // size is constant + static inline size_type size() { return N; } + static bool empty() { return false; } + static size_type max_size() { return N; } + enum { static_size = N }; + /** This method has no effects in this class, but raises an exception if the expected size does not match */ + inline void resize(const size_t nElements) { if (nElements!=N) throw std::logic_error("Try to change the size of a CArray."); } + // swap (note: linear complexity in N, constant for given instantiation) + void swap (CArray& y) { std::swap_ranges(begin(),end(),y.begin()); } + // direct access to data (read-only) + const T* data() const { return elems; } + // use array as C array (direct read/write access to data) + T* data() { return elems; } + // assignment with type conversion + template CArray& operator= (const CArray& rhs) { + std::copy(rhs.begin(),rhs.end(), begin()); + return *this; + } + // assign one value to all elements + inline void assign (const T& value) { for (size_t i=0;i= size()) { throw std::out_of_range("CArray<>: index out of range"); } } + }; // end of CArray + + /** Used to declare fixed-size arrays when DIM>0, dynamically-allocated vectors when DIM=-1. + * Fixed size version for a generic DIM: + */ + template + struct array_or_vector_selector + { + typedef CArray container_t; + }; + /** Dynamic size version */ + template + struct array_or_vector_selector<-1,T> { + typedef std::vector container_t; + }; + /** @} */ + + /** @addtogroup kdtrees_grp KD-tree classes and adaptors + * @{ */ + + /** kd-tree index + * + * Contains the k-d trees and other information for indexing a set of points + * for nearest-neighbor matching. + * + * The class "DatasetAdaptor" must provide the following interface (can be non-virtual, inlined methods): + * + * \code + * // Must return the number of data poins + * inline size_t kdtree_get_point_count() const { ... } + * + * // [Only if using the metric_L2_Simple type] Must return the Euclidean (L2) distance between the vector "p1[0:size-1]" and the data point with index "idx_p2" stored in the class: + * inline DistanceType kdtree_distance(const T *p1, const size_t idx_p2,size_t size) const { ... } + * + * // Must return the dim'th component of the idx'th point in the class: + * inline T kdtree_get_pt(const size_t idx, int dim) const { ... } + * + * // Optional bounding-box computation: return false to default to a standard bbox computation loop. + * // Return true if the BBOX was already computed by the class and returned in "bb" so it can be avoided to redo it again. + * // Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 for point clouds) + * template + * bool kdtree_get_bbox(BBOX &bb) const + * { + * bb[0].low = ...; bb[0].high = ...; // 0th dimension limits + * bb[1].low = ...; bb[1].high = ...; // 1st dimension limits + * ... + * return true; + * } + * + * \endcode + * + * \tparam DatasetAdaptor The user-provided adaptor (see comments above). + * \tparam Distance The distance metric to use: nanoflann::metric_L1, nanoflann::metric_L2, nanoflann::metric_L2_Simple, etc. + * \tparam DIM Dimensionality of data points (e.g. 3 for 3D points) + * \tparam IndexType Will be typically size_t or int + */ + template + class KDTreeSingleIndexAdaptor + { + private: + /** Hidden copy constructor, to disallow copying indices (Not implemented) */ + KDTreeSingleIndexAdaptor(const KDTreeSingleIndexAdaptor&); + public: + typedef typename Distance::ElementType ElementType; + typedef typename Distance::DistanceType DistanceType; + protected: + + /** + * Array of indices to vectors in the dataset. + */ + std::vector vind; + + size_t m_leaf_max_size; + + + /** + * The dataset used by this index + */ + const DatasetAdaptor &dataset; //!< The source of our data + + const KDTreeSingleIndexAdaptorParams index_params; + + size_t m_size; //!< Number of current poins in the dataset + size_t m_size_at_index_build; //!< Number of points in the dataset when the index was built + int dim; //!< Dimensionality of each data point + + + /*--------------------- Internal Data Structures --------------------------*/ + struct Node + { + /** Union used because a node can be either a LEAF node or a non-leaf node, so both data fields are never used simultaneously */ + union { + struct { + IndexType left, right; //!< Indices of points in leaf node + } lr; + struct { + int divfeat; //!< Dimension used for subdivision. + DistanceType divlow, divhigh; //!< The values used for subdivision. + } sub; + }; + Node* child1, * child2; //!< Child nodes (both=NULL mean its a leaf node) + }; + typedef Node* NodePtr; + + + struct Interval + { + ElementType low, high; + }; + + /** Define "BoundingBox" as a fixed-size or variable-size container depending on "DIM" */ + typedef typename array_or_vector_selector::container_t BoundingBox; + + /** Define "distance_vector_t" as a fixed-size or variable-size container depending on "DIM" */ + typedef typename array_or_vector_selector::container_t distance_vector_t; + + /** The KD-tree used to find neighbours */ + NodePtr root_node; + BoundingBox root_bbox; + + /** + * Pooled memory allocator. + * + * Using a pooled memory allocator is more efficient + * than allocating memory directly when there is a large + * number small of memory allocations. + */ + PooledAllocator pool; + + public: + + Distance distance; + + /** + * KDTree constructor + * + * Refer to docs in README.md or online in https://github.com/jlblancoc/nanoflann + * + * The KD-Tree point dimension (the length of each point in the datase, e.g. 3 for 3D points) + * is determined by means of: + * - The \a DIM template parameter if >0 (highest priority) + * - Otherwise, the \a dimensionality parameter of this constructor. + * + * @param inputData Dataset with the input features + * @param params Basically, the maximum leaf node size + */ + KDTreeSingleIndexAdaptor(const int dimensionality, const DatasetAdaptor& inputData, const KDTreeSingleIndexAdaptorParams& params = KDTreeSingleIndexAdaptorParams() ) : + dataset(inputData), index_params(params), root_node(NULL), distance(inputData) + { + m_size = dataset.kdtree_get_point_count(); + m_size_at_index_build = m_size; + dim = dimensionality; + if (DIM>0) dim=DIM; + m_leaf_max_size = params.leaf_max_size; + + // Create a permutable array of indices to the input vectors. + init_vind(); + } + + /** Standard destructor */ + ~KDTreeSingleIndexAdaptor() { } + + /** Frees the previously-built index. Automatically called within buildIndex(). */ + void freeIndex() + { + pool.free_all(); + root_node=NULL; + m_size_at_index_build = 0; + } + + /** + * Builds the index + */ + void buildIndex() + { + init_vind(); + freeIndex(); + m_size_at_index_build = m_size; + if(m_size == 0) return; + computeBoundingBox(root_bbox); + root_node = divideTree(0, m_size, root_bbox ); // construct the tree + } + + /** Returns number of points in dataset */ + size_t size() const { return m_size; } + + /** Returns the length of each point in the dataset */ + size_t veclen() const { + return static_cast(DIM>0 ? DIM : dim); + } + + /** + * Computes the inde memory usage + * Returns: memory used by the index + */ + size_t usedMemory() const + { + return pool.usedMemory+pool.wastedMemory+dataset.kdtree_get_point_count()*sizeof(IndexType); // pool memory and vind array memory + } + + /** \name Query methods + * @{ */ + + /** + * Find set of nearest neighbors to vec[0:dim-1]. Their indices are stored inside + * the result object. + * + * Params: + * result = the result object in which the indices of the nearest-neighbors are stored + * vec = the vector for which to search the nearest neighbors + * + * \tparam RESULTSET Should be any ResultSet + * \return True if the requested neighbors could be found. + * \sa knnSearch, radiusSearch + */ + template + bool findNeighbors(RESULTSET& result, const ElementType* vec, const SearchParams& searchParams) const + { + assert(vec); + if (size() == 0) + return false; + if (!root_node) + throw std::runtime_error("[nanoflann] findNeighbors() called before building the index."); + float epsError = 1+searchParams.eps; + + distance_vector_t dists; // fixed or variable-sized container (depending on DIM) + dists.assign((DIM>0 ? DIM : dim) ,0); // Fill it with zeros. + DistanceType distsq = computeInitialDistances(vec, dists); + searchLevel(result, vec, root_node, distsq, dists, epsError); // "count_leaf" parameter removed since was neither used nor returned to the user. + return result.full(); + } + + /** + * Find the "num_closest" nearest neighbors to the \a query_point[0:dim-1]. Their indices are stored inside + * the result object. + * \sa radiusSearch, findNeighbors + * \note nChecks_IGNORED is ignored but kept for compatibility with the original FLANN interface. + */ + inline void knnSearch(const ElementType *query_point, const size_t num_closest, IndexType *out_indices, DistanceType *out_distances_sq, const int /* nChecks_IGNORED */ = 10) const + { + nanoflann::KNNResultSet resultSet(num_closest); + resultSet.init(out_indices, out_distances_sq); + this->findNeighbors(resultSet, query_point, nanoflann::SearchParams()); + } + + /** + * Find all the neighbors to \a query_point[0:dim-1] within a maximum radius. + * The output is given as a vector of pairs, of which the first element is a point index and the second the corresponding distance. + * Previous contents of \a IndicesDists are cleared. + * + * If searchParams.sorted==true, the output list is sorted by ascending distances. + * + * For a better performance, it is advisable to do a .reserve() on the vector if you have any wild guess about the number of expected matches. + * + * \sa knnSearch, findNeighbors, radiusSearchCustomCallback + * \return The number of points within the given radius (i.e. indices.size() or dists.size() ) + */ + size_t radiusSearch(const ElementType *query_point,const DistanceType radius, std::vector >& IndicesDists, const SearchParams& searchParams) const + { + RadiusResultSet resultSet(radius,IndicesDists); + const size_t nFound = radiusSearchCustomCallback(query_point,resultSet,searchParams); + if (searchParams.sorted) + std::sort(IndicesDists.begin(),IndicesDists.end(), IndexDist_Sorter() ); + return nFound; + } + + /** + * Just like radiusSearch() but with a custom callback class for each point found in the radius of the query. + * See the source of RadiusResultSet<> as a start point for your own classes. + * \sa radiusSearch + */ + template + size_t radiusSearchCustomCallback(const ElementType *query_point,SEARCH_CALLBACK &resultSet, const SearchParams& searchParams = SearchParams() ) const + { + this->findNeighbors(resultSet, query_point, searchParams); + return resultSet.size(); + } + + /** @} */ + + private: + /** Make sure the auxiliary list \a vind has the same size than the current dataset, and re-generate if size has changed. */ + void init_vind() + { + // Create a permutable array of indices to the input vectors. + m_size = dataset.kdtree_get_point_count(); + if (vind.size()!=m_size) vind.resize(m_size); + for (size_t i = 0; i < m_size; i++) vind[i] = i; + } + + /// Helper accessor to the dataset points: + inline ElementType dataset_get(size_t idx, int component) const { + return dataset.kdtree_get_pt(idx,component); + } + + + void save_tree(FILE* stream, NodePtr tree) + { + save_value(stream, *tree); + if (tree->child1!=NULL) { + save_tree(stream, tree->child1); + } + if (tree->child2!=NULL) { + save_tree(stream, tree->child2); + } + } + + + void load_tree(FILE* stream, NodePtr& tree) + { + tree = pool.allocate(); + load_value(stream, *tree); + if (tree->child1!=NULL) { + load_tree(stream, tree->child1); + } + if (tree->child2!=NULL) { + load_tree(stream, tree->child2); + } + } + + + void computeBoundingBox(BoundingBox& bbox) + { + bbox.resize((DIM>0 ? DIM : dim)); + if (dataset.kdtree_get_bbox(bbox)) + { + // Done! It was implemented in derived class + } + else + { + const size_t N = dataset.kdtree_get_point_count(); + if (!N) throw std::runtime_error("[nanoflann] computeBoundingBox() called but no data points found."); + for (int i=0; i<(DIM>0 ? DIM : dim); ++i) { + bbox[i].low = + bbox[i].high = dataset_get(0,i); + } + for (size_t k=1; k0 ? DIM : dim); ++i) { + if (dataset_get(k,i)bbox[i].high) bbox[i].high = dataset_get(k,i); + } + } + } + } + + + /** + * Create a tree node that subdivides the list of vecs from vind[first] + * to vind[last]. The routine is called recursively on each sublist. + * + * @param left index of the first vector + * @param right index of the last vector + */ + NodePtr divideTree(const IndexType left, const IndexType right, BoundingBox& bbox) + { + NodePtr node = pool.allocate(); // allocate memory + + /* If too few exemplars remain, then make this a leaf node. */ + if ( (right-left) <= m_leaf_max_size) { + node->child1 = node->child2 = NULL; /* Mark as leaf node. */ + node->lr.left = left; + node->lr.right = right; + + // compute bounding-box of leaf points + for (int i=0; i<(DIM>0 ? DIM : dim); ++i) { + bbox[i].low = dataset_get(vind[left],i); + bbox[i].high = dataset_get(vind[left],i); + } + for (IndexType k=left+1; k0 ? DIM : dim); ++i) { + if (bbox[i].low>dataset_get(vind[k],i)) bbox[i].low=dataset_get(vind[k],i); + if (bbox[i].highsub.divfeat = cutfeat; + + BoundingBox left_bbox(bbox); + left_bbox[cutfeat].high = cutval; + node->child1 = divideTree(left, left+idx, left_bbox); + + BoundingBox right_bbox(bbox); + right_bbox[cutfeat].low = cutval; + node->child2 = divideTree(left+idx, right, right_bbox); + + node->sub.divlow = left_bbox[cutfeat].high; + node->sub.divhigh = right_bbox[cutfeat].low; + + for (int i=0; i<(DIM>0 ? DIM : dim); ++i) { + bbox[i].low = std::min(left_bbox[i].low, right_bbox[i].low); + bbox[i].high = std::max(left_bbox[i].high, right_bbox[i].high); + } + } + + return node; + } + + + void computeMinMax(IndexType* ind, IndexType count, int element, ElementType& min_elem, ElementType& max_elem) + { + min_elem = dataset_get(ind[0],element); + max_elem = dataset_get(ind[0],element); + for (IndexType i=1; imax_elem) max_elem = val; + } + } + + void middleSplit_(IndexType* ind, IndexType count, IndexType& index, int& cutfeat, DistanceType& cutval, const BoundingBox& bbox) + { + const DistanceType EPS=static_cast(0.00001); + ElementType max_span = bbox[0].high-bbox[0].low; + for (int i=1; i<(DIM>0 ? DIM : dim); ++i) { + ElementType span = bbox[i].high-bbox[i].low; + if (span>max_span) { + max_span = span; + } + } + ElementType max_spread = -1; + cutfeat = 0; + for (int i=0; i<(DIM>0 ? DIM : dim); ++i) { + ElementType span = bbox[i].high-bbox[i].low; + if (span>(1-EPS)*max_span) { + ElementType min_elem, max_elem; + computeMinMax(ind, count, cutfeat, min_elem, max_elem); + ElementType spread = max_elem-min_elem;; + if (spread>max_spread) { + cutfeat = i; + max_spread = spread; + } + } + } + // split in the middle + DistanceType split_val = (bbox[cutfeat].low+bbox[cutfeat].high)/2; + ElementType min_elem, max_elem; + computeMinMax(ind, count, cutfeat, min_elem, max_elem); + + if (split_valmax_elem) cutval = max_elem; + else cutval = split_val; + + IndexType lim1, lim2; + planeSplit(ind, count, cutfeat, cutval, lim1, lim2); + + if (lim1>count/2) index = lim1; + else if (lim2cutval + */ + void planeSplit(IndexType* ind, const IndexType count, int cutfeat, DistanceType cutval, IndexType& lim1, IndexType& lim2) + { + /* Move vector indices for left subtree to front of list. */ + IndexType left = 0; + IndexType right = count-1; + for (;; ) { + while (left<=right && dataset_get(ind[left],cutfeat)=cutval) --right; + if (left>right || !right) break; // "!right" was added to support unsigned Index types + std::swap(ind[left], ind[right]); + ++left; + --right; + } + /* If either list is empty, it means that all remaining features + * are identical. Split in the middle to maintain a balanced tree. + */ + lim1 = left; + right = count-1; + for (;; ) { + while (left<=right && dataset_get(ind[left],cutfeat)<=cutval) ++left; + while (right && left<=right && dataset_get(ind[right],cutfeat)>cutval) --right; + if (left>right || !right) break; // "!right" was added to support unsigned Index types + std::swap(ind[left], ind[right]); + ++left; + --right; + } + lim2 = left; + } + + DistanceType computeInitialDistances(const ElementType* vec, distance_vector_t& dists) const + { + assert(vec); + DistanceType distsq = DistanceType(); + + for (int i = 0; i < (DIM>0 ? DIM : dim); ++i) { + if (vec[i] < root_bbox[i].low) { + dists[i] = distance.accum_dist(vec[i], root_bbox[i].low, i); + distsq += dists[i]; + } + if (vec[i] > root_bbox[i].high) { + dists[i] = distance.accum_dist(vec[i], root_bbox[i].high, i); + distsq += dists[i]; + } + } + + return distsq; + } + + /** + * Performs an exact search in the tree starting from a node. + * \tparam RESULTSET Should be any ResultSet + */ + template + void searchLevel(RESULTSET& result_set, const ElementType* vec, const NodePtr node, DistanceType mindistsq, + distance_vector_t& dists, const float epsError) const + { + /* If this is a leaf node, then do check and return. */ + if ((node->child1 == NULL)&&(node->child2 == NULL)) { + //count_leaf += (node->lr.right-node->lr.left); // Removed since was neither used nor returned to the user. + DistanceType worst_dist = result_set.worstDist(); + for (IndexType i=node->lr.left; ilr.right; ++i) { + const IndexType index = vind[i];// reorder... : i; + DistanceType dist = distance(vec, index, (DIM>0 ? DIM : dim)); + if (distsub.divfeat; + ElementType val = vec[idx]; + DistanceType diff1 = val - node->sub.divlow; + DistanceType diff2 = val - node->sub.divhigh; + + NodePtr bestChild; + NodePtr otherChild; + DistanceType cut_dist; + if ((diff1+diff2)<0) { + bestChild = node->child1; + otherChild = node->child2; + cut_dist = distance.accum_dist(val, node->sub.divhigh, idx); + } + else { + bestChild = node->child2; + otherChild = node->child1; + cut_dist = distance.accum_dist( val, node->sub.divlow, idx); + } + + /* Call recursively to search next level down. */ + searchLevel(result_set, vec, bestChild, mindistsq, dists, epsError); + + DistanceType dst = dists[idx]; + mindistsq = mindistsq + cut_dist - dst; + dists[idx] = cut_dist; + if (mindistsq*epsError<=result_set.worstDist()) { + searchLevel(result_set, vec, otherChild, mindistsq, dists, epsError); + } + dists[idx] = dst; + } + + public: + /** Stores the index in a binary file. + * IMPORTANT NOTE: The set of data points is NOT stored in the file, so when loading the index object it must be constructed associated to the same source of data points used while building it. + * See the example: examples/saveload_example.cpp + * \sa loadIndex */ + void saveIndex(FILE* stream) + { + save_value(stream, m_size); + save_value(stream, dim); + save_value(stream, root_bbox); + save_value(stream, m_leaf_max_size); + save_value(stream, vind); + save_tree(stream, root_node); + } + + /** Loads a previous index from a binary file. + * IMPORTANT NOTE: The set of data points is NOT stored in the file, so the index object must be constructed associated to the same source of data points used while building the index. + * See the example: examples/saveload_example.cpp + * \sa loadIndex */ + void loadIndex(FILE* stream) + { + load_value(stream, m_size); + load_value(stream, dim); + load_value(stream, root_bbox); + load_value(stream, m_leaf_max_size); + load_value(stream, vind); + load_tree(stream, root_node); + } + + }; // class KDTree + + + /** An L2-metric KD-tree adaptor for working with data directly stored in an Eigen Matrix, without duplicating the data storage. + * Each row in the matrix represents a point in the state space. + * + * Example of usage: + * \code + * Eigen::Matrix mat; + * // Fill out "mat"... + * + * typedef KDTreeEigenMatrixAdaptor< Eigen::Matrix > my_kd_tree_t; + * const int max_leaf = 10; + * my_kd_tree_t mat_index(dimdim, mat, max_leaf ); + * mat_index.index->buildIndex(); + * mat_index.index->... + * \endcode + * + * \tparam DIM If set to >0, it specifies a compile-time fixed dimensionality for the points in the data set, allowing more compiler optimizations. + * \tparam Distance The distance metric to use: nanoflann::metric_L1, nanoflann::metric_L2, nanoflann::metric_L2_Simple, etc. + */ + template + struct KDTreeEigenMatrixAdaptor + { + typedef KDTreeEigenMatrixAdaptor self_t; + typedef typename MatrixType::Scalar num_t; + typedef typename MatrixType::Index IndexType; + typedef typename Distance::template traits::distance_t metric_t; + typedef KDTreeSingleIndexAdaptor< metric_t,self_t,DIM,IndexType> index_t; + + index_t* index; //! The kd-tree index for the user to call its methods as usual with any other FLANN index. + + /// Constructor: takes a const ref to the matrix object with the data points + KDTreeEigenMatrixAdaptor(const int dimensionality, const MatrixType &mat, const int leaf_max_size = 10) : m_data_matrix(mat) + { + const IndexType dims = mat.cols(); + if (dims!=dimensionality) throw std::runtime_error("Error: 'dimensionality' must match column count in data matrix"); + if (DIM>0 && static_cast(dims)!=DIM) + throw std::runtime_error("Data set dimensionality does not match the 'DIM' template argument"); + index = new index_t( dims, *this /* adaptor */, nanoflann::KDTreeSingleIndexAdaptorParams(leaf_max_size ) ); + index->buildIndex(); + } + private: + /** Hidden copy constructor, to disallow copying this class (Not implemented) */ + KDTreeEigenMatrixAdaptor(const self_t&); + public: + + ~KDTreeEigenMatrixAdaptor() { + delete index; + } + + const MatrixType &m_data_matrix; + + /** Query for the \a num_closest closest points to a given point (entered as query_point[0:dim-1]). + * Note that this is a short-cut method for index->findNeighbors(). + * The user can also call index->... methods as desired. + * \note nChecks_IGNORED is ignored but kept for compatibility with the original FLANN interface. + */ + inline void query(const num_t *query_point, const size_t num_closest, IndexType *out_indices, num_t *out_distances_sq, const int /* nChecks_IGNORED */ = 10) const + { + nanoflann::KNNResultSet resultSet(num_closest); + resultSet.init(out_indices, out_distances_sq); + index->findNeighbors(resultSet, query_point, nanoflann::SearchParams()); + } + + /** @name Interface expected by KDTreeSingleIndexAdaptor + * @{ */ + + const self_t & derived() const { + return *this; + } + self_t & derived() { + return *this; + } + + // Must return the number of data points + inline size_t kdtree_get_point_count() const { + return m_data_matrix.rows(); + } + + // Returns the L2 distance between the vector "p1[0:size-1]" and the data point with index "idx_p2" stored in the class: + inline num_t kdtree_distance(const num_t *p1, const IndexType idx_p2,IndexType size) const + { + num_t s=0; + for (IndexType i=0; i + bool kdtree_get_bbox(BBOX& /*bb*/) const { + return false; + } + + /** @} */ + + }; // end of KDTreeEigenMatrixAdaptor + /** @} */ + +/** @} */ // end of grouping +} // end of NS + + +#endif /* NANOFLANN_HPP_ */ diff --git a/main.cpp b/main.cpp index 73cfa5f..f334a09 100755 --- a/main.cpp +++ b/main.cpp @@ -15,7 +15,7 @@ int main(int argc, char** argv) { #ifdef WITH_TESTS ::testing::InitGoogleTest(&argc, argv); - //::testing::GTEST_FLAG(filter) = "*first*"; + //::testing::GTEST_FLAG(filter) = "*bbox*"; return RUN_ALL_TESTS(); #endif diff --git a/misc/KNN.h b/misc/KNN.h new file mode 100644 index 0000000..7c941b9 --- /dev/null +++ b/misc/KNN.h @@ -0,0 +1,76 @@ +#ifndef KNN_H +#define KNN_H + +#include "../lib/nanoflann/nanoflann.hpp" + +/** + * helper class to extract k-nearest-neighbors + * from a given input data structure. + * uses nanoflann + * + * usage: + * KNN, T, 3> knn(theGrid); + * float search[] = {0,0,0}; + * std::vector elems = knn.get(search, 3); + */ +template class KNN { + +private: + + /** type-definition for the nanoflann KD-Tree used for searching */ + typedef nanoflann::KDTreeSingleIndexAdaptor, DataStructure, dim> Tree; + + /** the maximum depth of the tree */ + static constexpr int maxLeafs = 10; + + /** the constructed tree used for searching */ + Tree tree; + + /** the underlying data-structure we want to search within */ + DataStructure& data; + +public: + + /** ctor */ + KNN(DataStructure& data) : tree(dim, data, nanoflann::KDTreeSingleIndexAdaptorParams(maxLeafs)), data(data) { + tree.buildIndex(); + } + + /** get the k-nearest-neighbors for the given input point */ + std::vector get(const Scalar* point, const int numNeighbors, const float maxDistSquared = 99999) const { + + // buffer for to-be-fetched neighbors + size_t indices[numNeighbors]; + float distances[numNeighbors]; + + // find k-nearest-neighbors + tree.knnSearch(point, numNeighbors, indices, distances); + + // construct output + std::vector elements; + for (int i = 0; i < numNeighbors; ++i) { + if (distances[i] > maxDistSquared) {continue;} // too far away? + elements.push_back(data[indices[i]]); + } + return elements; + + } + + /** get the nearest neighbor and its distance */ + void getNearest(const Scalar* point, size_t& idx, float& distSquared) { + + // find 1-nearest-neighbors + tree.knnSearch(point, 1, &idx, &distSquared); + + } + + void get(const Scalar* point, const int numNeighbors, size_t* indices, float* squaredDist) { + + // find k-nearest-neighbors + tree.knnSearch(point, numNeighbors, indices, squaredDist); + + } + +}; + +#endif // KNN_H diff --git a/tests/Tests.h b/tests/Tests.h index 909c8be..e4bafd9 100755 --- a/tests/Tests.h +++ b/tests/Tests.h @@ -6,7 +6,7 @@ #include static inline std::string getDataFile(const std::string& name) { - return "/mnt/firma/kunden/indoor/tests/data/" + name; + return "/apps/workspaces/Indoor/tests/data/" + name; } #endif diff --git a/tests/data/fp1.svg b/tests/data/fp1.svg new file mode 100644 index 0000000..9392a34 --- /dev/null +++ b/tests/data/fp1.svg @@ -0,0 +1,269 @@ + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/geo/TestAngle.cpp b/tests/geo/TestAngle.cpp index 244afe6..ff20ce6 100755 --- a/tests/geo/TestAngle.cpp +++ b/tests/geo/TestAngle.cpp @@ -6,15 +6,55 @@ TEST(Angle, calc) { - ASSERT_EQ(0, Angle::getDEG(0,0, +1,0)); // to the right - ASSERT_EQ(90, Angle::getDEG(0,0, 0,+1)); // upwards - ASSERT_EQ(180, Angle::getDEG(0,0, -1,0)); // to the left - ASSERT_EQ(270, Angle::getDEG(0,0, 0,-1)); // downwards + ASSERT_EQ(0, Angle::getDEG_360(0,0, +1,0)); // to the right + ASSERT_EQ(90, Angle::getDEG_360(0,0, 0,+1)); // upwards + ASSERT_EQ(180, Angle::getDEG_360(0,0, -1,0)); // to the left + ASSERT_EQ(270, Angle::getDEG_360(0,0, 0,-1)); // downwards - ASSERT_EQ(45, Angle::getDEG(0,0, +1,+1)); // to the upper right - ASSERT_EQ(135, Angle::getDEG(0,0, -1,+1)); // to the upper left - ASSERT_EQ(225, Angle::getDEG(0,0, -1,-1)); // to the lower left - ASSERT_EQ(315, Angle::getDEG(0,0, +1,-1)); // to the lower right + ASSERT_EQ(45, Angle::getDEG_360(0,0, +1,+1)); // to the upper right + ASSERT_EQ(135, Angle::getDEG_360(0,0, -1,+1)); // to the upper left + ASSERT_EQ(225, Angle::getDEG_360(0,0, -1,-1)); // to the lower left + ASSERT_EQ(315, Angle::getDEG_360(0,0, +1,-1)); // to the lower right + +} + +TEST(Angle, diff) { + + const float r = Angle::getRAD_2PI(0,0, +1,0); // to the right + const float u = Angle::getRAD_2PI(0,0, 0,+1); // upwards + const float l = Angle::getRAD_2PI(0,0, -1,0); // to the left + const float d = Angle::getRAD_2PI(0,0, 0,-1); // downwards + + const float ur = Angle::getRAD_2PI(0,0, +1,+1); // to the upper right + const float ul = Angle::getRAD_2PI(0,0, -1,+1); // to the upper left + const float dl = Angle::getRAD_2PI(0,0, -1,-1); // to the lower left + const float dr = Angle::getRAD_2PI(0,0, +1,-1); // to the lower right + + + ASSERT_NEAR(M_PI_2, Angle::getDiffRAD_2PI_PI(r, u), 0.0001); + ASSERT_NEAR(M_PI_2, Angle::getDiffRAD_2PI_PI(u, r), 0.0001); + + ASSERT_NEAR(M_PI_2, Angle::getDiffRAD_2PI_PI(u, l), 0.0001); + ASSERT_NEAR(M_PI_2, Angle::getDiffRAD_2PI_PI(l, u), 0.0001); + + ASSERT_NEAR(M_PI_2, Angle::getDiffRAD_2PI_PI(l, d), 0.0001); + ASSERT_NEAR(M_PI_2, Angle::getDiffRAD_2PI_PI(d, l), 0.0001); + + ASSERT_NEAR(M_PI_2, Angle::getDiffRAD_2PI_PI(d, r), 0.0001); + ASSERT_NEAR(M_PI_2, Angle::getDiffRAD_2PI_PI(r, d), 0.0001); + + + ASSERT_NEAR(M_PI_2, Angle::getDiffRAD_2PI_PI(ur, ul), 0.0001); + ASSERT_NEAR(M_PI_2, Angle::getDiffRAD_2PI_PI(ul, ur), 0.0001); + + ASSERT_NEAR(M_PI_2, Angle::getDiffRAD_2PI_PI(ul, dl), 0.0001); + ASSERT_NEAR(M_PI_2, Angle::getDiffRAD_2PI_PI(dl, ul), 0.0001); + + ASSERT_NEAR(M_PI_2, Angle::getDiffRAD_2PI_PI(dl, dr), 0.0001); + ASSERT_NEAR(M_PI_2, Angle::getDiffRAD_2PI_PI(dr, dl), 0.0001); + + ASSERT_NEAR(M_PI_2, Angle::getDiffRAD_2PI_PI(dr, ur), 0.0001); + ASSERT_NEAR(M_PI_2, Angle::getDiffRAD_2PI_PI(ur, dr), 0.0001); } diff --git a/tests/grid/GridImportance.cpp b/tests/grid/GridImportance.cpp new file mode 100644 index 0000000..308af40 --- /dev/null +++ b/tests/grid/GridImportance.cpp @@ -0,0 +1,29 @@ +#ifdef WITH_TESTS + +#include "../Tests.h" +#include "../../grid/factory/GridImportance.h" +#include "../../grid/factory/GridFactory.h" +#include "../../floorplan/FloorplanFactorySVG.h" + +#include "Plot.h" + +TEST(GridImportance, a) { + + + + Grid<20, GP> g; + GridFactory<20, GP> gf(g); + FloorplanFactorySVG fpf(getDataFile("fp1.svg"), 6); + + Floor f1 = fpf.getFloor("1"); + gf.addFloor(f1, 20); + gf.removeIsolated(); + + GridImportance gi; + gi.addImportance(g, 20); + + plot(g); + +} + +#endif diff --git a/tests/grid/Plot.h b/tests/grid/Plot.h new file mode 100644 index 0000000..f14c343 --- /dev/null +++ b/tests/grid/Plot.h @@ -0,0 +1,66 @@ +#ifndef PLOT_H +#define PLOT_H + + +#include +#include +#include +#include +#include + + +class GP : public GridNode, public GridPoint { +public: + float imp = 1.0f; +public: + GP() : GridNode(), GridPoint() {;} + GP(int x, int y, int z) : GridNode(), GridPoint(x,y,z) {;} + +}; + +template void plot(Grid& g) { + + K::Gnuplot gp; + K::GnuplotSplot splot; + K::GnuplotSplotElementColorPoints points; + K::GnuplotSplotElementLines lines; + + gp << "set ticslevel 0\n"; + gp << "set view equal xyz\n"; + gp << "set cbrange[0.5:1.0]\n"; + gp << "set palette gray negative\n"; + + std::set done; + + int cnt = 0; + for (int i = 0; i < g.getNumNodes(); ++i) { + const GP& n1 = g[i]; + points.add(K::GnuplotPoint3(n1.x_cm, n1.y_cm, n1.z_cm), n1.imp); + + for (int n = 0; n < n1.getNumNeighbors(); ++n) { + const GP& n2 = n1.getNeighbor(n, g); + if (done.find(g.getUID(n2)) == done.end()) { + K::GnuplotPoint3 p1(n1.x_cm, n1.y_cm, n1.z_cm); + K::GnuplotPoint3 p2(n2.x_cm, n2.y_cm, n2.z_cm); + lines.addSegment(p1, p2); + ++cnt; + } + } + + done.insert(g.getUID(n1)); + + } + + points.setPointSize(1); + //splot.add(&lines); + splot.add(&points); + + gp.draw(splot); + gp.flush(); + + sleep(100); + +} + + +#endif // PLOT_H diff --git a/tests/grid/TestBBox.cpp b/tests/grid/TestBBox.cpp index cd19a2d..fb980dc 100755 --- a/tests/grid/TestBBox.cpp +++ b/tests/grid/TestBBox.cpp @@ -27,20 +27,20 @@ TEST(BBox, intersect) { GridNodeBBox bb1(GridPoint(20,20,20), 20); // left - ASSERT_FALSE(bb1.intersects( Line2D(9, -999, 9, +999) )); - ASSERT_TRUE (bb1.intersects( Line2D(11, -999, 11, +999) )); + ASSERT_FALSE(bb1.intersects( Line2(9, -999, 9, +999) )); + ASSERT_TRUE (bb1.intersects( Line2(11, -999, 11, +999) )); // right - ASSERT_TRUE (bb1.intersects( Line2D(29, -999, 29, +999) )); - ASSERT_FALSE(bb1.intersects( Line2D(31, -999, 31, +999) )); + ASSERT_TRUE (bb1.intersects( Line2(29, -999, 29, +999) )); + ASSERT_FALSE(bb1.intersects( Line2(31, -999, 31, +999) )); // top - ASSERT_FALSE(bb1.intersects( Line2D(-999, 9, +999, 9) )); - ASSERT_TRUE (bb1.intersects( Line2D(-999, 11, +999, 11) )); + ASSERT_FALSE(bb1.intersects( Line2(-999, 9, +999, 9) )); + ASSERT_TRUE (bb1.intersects( Line2(-999, 11, +999, 11) )); // bottom - ASSERT_TRUE (bb1.intersects( Line2D(-999, 29, +999, 29) )); - ASSERT_FALSE(bb1.intersects( Line2D(-999, 31, +999, 31) )); + ASSERT_TRUE (bb1.intersects( Line2(-999, 29, +999, 29) )); + ASSERT_FALSE(bb1.intersects( Line2(-999, 31, +999, 31) )); } diff --git a/tests/grid/TestGrid.cpp b/tests/grid/TestGrid.cpp index 9acc3a3..0557c1c 100755 --- a/tests/grid/TestGrid.cpp +++ b/tests/grid/TestGrid.cpp @@ -36,15 +36,15 @@ TEST(Grid, BBox) { Grid<20, GP> grid; int idx = grid.add(GP(40,40,40)); - ASSERT_EQ(30, grid.getBBox(idx).x1_cm); - ASSERT_EQ(50, grid.getBBox(idx).x2_cm); - ASSERT_EQ(30, grid.getBBox(idx).y1_cm); - ASSERT_EQ(50, grid.getBBox(idx).y2_cm); + ASSERT_EQ(30, grid.getBBox(idx).getMin().x); + ASSERT_EQ(50, grid.getBBox(idx).getMax().x); + ASSERT_EQ(30, grid.getBBox(idx).getMin().y); + ASSERT_EQ(50, grid.getBBox(idx).getMax().y); } -TEST(Grid, neighbors) { +TEST(Grid, connectBiDir) { Grid<1, GP> grid; @@ -54,10 +54,10 @@ TEST(Grid, neighbors) { int idx4 = grid.add(GP( 1, 0, 0)); int idx5 = grid.add(GP(-1, 0, 0)); - grid.connect(idx1, idx2); - grid.connect(idx1, idx3); - grid.connect(idx1, idx4); - grid.connect(idx1, idx5); + grid.connectBiDir(idx1, idx2); + grid.connectBiDir(idx1, idx3); + grid.connectBiDir(idx1, idx4); + grid.connectBiDir(idx1, idx5); ASSERT_EQ(4, grid.getNumNeighbors(idx1)); ASSERT_EQ(1, grid.getNumNeighbors(idx2)); @@ -65,6 +65,54 @@ TEST(Grid, neighbors) { ASSERT_EQ(1, grid.getNumNeighbors(idx4)); ASSERT_EQ(1, grid.getNumNeighbors(idx5)); + ASSERT_EQ(grid[idx2], grid.getNeighbor(idx1, 0)); + ASSERT_EQ(grid[idx3], grid.getNeighbor(idx1, 1)); + ASSERT_EQ(grid[idx4], grid.getNeighbor(idx1, 2)); + ASSERT_EQ(grid[idx5], grid.getNeighbor(idx1, 3)); + +} + +TEST(Grid, disconnectBiDir) { + + Grid<1, GP> grid; + + int idx1 = grid.add(GP( 0, 0, 0)); + int idx2 = grid.add(GP( 0, 1, 0)); + int idx3 = grid.add(GP( 0,-1, 0)); + int idx4 = grid.add(GP( 1, 0, 0)); + int idx5 = grid.add(GP(-1, 0, 0)); + + grid.connectBiDir(idx1, idx2); + grid.connectBiDir(idx1, idx3); + grid.connectBiDir(idx1, idx4); + grid.connectBiDir(idx1, idx5); + + // remove 1 <-> 4 + grid.disconnectBiDir(idx1, idx4); + ASSERT_EQ(3, grid.getNumNeighbors(idx1)); + ASSERT_EQ(0, grid.getNumNeighbors(idx4)); + ASSERT_EQ(grid[idx2], grid.getNeighbor(idx1, 0)); + ASSERT_EQ(grid[idx3], grid.getNeighbor(idx1, 1)); + ASSERT_EQ(grid[idx5], grid.getNeighbor(idx1, 2)); + + // remove 1 <-> 5 + grid.disconnectBiDir(idx1, idx5); + ASSERT_EQ(2, grid.getNumNeighbors(idx1)); + ASSERT_EQ(0, grid.getNumNeighbors(idx5)); + ASSERT_EQ(grid[idx2], grid.getNeighbor(idx1, 0)); + ASSERT_EQ(grid[idx3], grid.getNeighbor(idx1, 1)); + + // remove 1 <-> 2 + grid.disconnectBiDir(idx1, idx2); + ASSERT_EQ(1, grid.getNumNeighbors(idx1)); + ASSERT_EQ(0, grid.getNumNeighbors(idx2)); + ASSERT_EQ(grid[idx3], grid.getNeighbor(idx1, 0)); + + // remove 1 <-> 2 + grid.disconnectBiDir(idx1, idx3); + ASSERT_EQ(0, grid.getNumNeighbors(idx1)); + ASSERT_EQ(0, grid.getNumNeighbors(idx3)); + } TEST(Grid, uid) { @@ -81,6 +129,87 @@ TEST(Grid, uid) { } +TEST(Grid, remove) { + + Grid<1, GP> grid; + + GP gp1( 0, 0, 0); + GP gp2( 0, 1, 0); + GP gp3( 0,-1, 0); + GP gp4( 1, 0, 0); + GP gp5(-1, 0, 0); + + int idx1 = grid.add(gp1); + int idx2 = grid.add(gp2); + int idx3 = grid.add(gp3); + int idx4 = grid.add(gp4); + int idx5 = grid.add(gp5); + + grid.connectBiDir(idx1, idx2); + grid.connectBiDir(idx1, idx3); + grid.connectBiDir(idx1, idx4); + grid.connectBiDir(idx1, idx5); + + grid.remove(idx1); + grid.cleanup(); + + ASSERT_EQ(4, grid.getNumNodes()); + ASSERT_EQ(gp2, grid[0]); + ASSERT_EQ(gp3, grid[1]); + ASSERT_EQ(gp4, grid[2]); + ASSERT_EQ(gp5, grid[3]); + + ASSERT_EQ(0, grid.getNumNeighbors(grid[0])); + ASSERT_EQ(0, grid.getNumNeighbors(grid[1])); + ASSERT_EQ(0, grid.getNumNeighbors(grid[2])); + ASSERT_EQ(0, grid.getNumNeighbors(grid[3])); + +} + +TEST(Grid, neighborIter) { + + Grid<1, GP> grid; + + int idx1 = grid.add(GP( 0, 0, 0)); + int idx2 = grid.add(GP( 0, 1, 0)); + int idx3 = grid.add(GP( 0,-1, 0)); + int idx4 = grid.add(GP( 1, 0, 0)); + int idx5 = grid.add(GP(-1, 0, 0)); + + grid.connectBiDir(idx1, idx2); + grid.connectBiDir(idx1, idx3); + grid.connectBiDir(idx1, idx4); + grid.connectBiDir(idx1, idx5); + + int i = 0; + for (GP& node : grid.neighbors(idx1)) {++i;} + ASSERT_EQ(4, i); + +} + +TEST(Grid, bbox) { + + Grid<1, GP> grid; + + int idx1 = grid.add(GP( 0, 0, 0)); + int idx2 = grid.add(GP( 0, 1, 0)); + int idx3 = grid.add(GP( 0,-1, 0)); + int idx4 = grid.add(GP( 1, 0, 0)); + int idx5 = grid.add(GP(-1, 0, 0)); + + BBox3 bb = grid.getBBox(); + + ASSERT_EQ(bb.getMin().x, -1); + ASSERT_EQ(bb.getMin().y, -1); + ASSERT_EQ(bb.getMin().z, 0); + + ASSERT_EQ(bb.getMax().x, +1); + ASSERT_EQ(bb.getMax().y, +1); + ASSERT_EQ(bb.getMax().z, 0); + + +} + TEST(Grid, nearest) { Grid<20, GP> grid; diff --git a/tests/grid/TestGridFactory.cpp b/tests/grid/TestGridFactory.cpp index a68a01c..91bcfe6 100755 --- a/tests/grid/TestGridFactory.cpp +++ b/tests/grid/TestGridFactory.cpp @@ -4,42 +4,35 @@ #include "../../grid/factory/GridFactory.h" #include "../../floorplan/FloorplanFactorySVG.h" -#include -#include -#include -class GP : public GridNode, public GridPoint { -public: - GP() : GridNode(), GridPoint() {;} - GP(int x, int y, int z) : GridNode(), GridPoint(x,y,z) {;} -}; +#include "Plot.h" TEST(GridFactory, create) { Grid<20, GP> g; + Grid<20, GP> gInv; + GridFactory<20, GP> gf(g); - FloorplanFactorySVG fpf(getDataFile("test.svg"), 2); + FloorplanFactorySVG fpf(getDataFile("fp1.svg"), 4); Floor f1 = fpf.getFloor("1"); + Floor f2 = fpf.getFloor("2"); + Stairs s1_2 = fpf.getStairs("1_2"); - gf.addFloor(f1, 0); + gf.addFloor(f1, 20); + gf.addFloor(f2, 340); + gf.addStairs(s1_2, 20, 340); + gf.removeIsolated(); - K::Gnuplot gp; - K::GnuplotSplot splot; - K::GnuplotSplotElementPoints points; + GridFactory<20, GP> gfInv(gInv); + gfInv.addInverted(g, 20); + gfInv.addInverted(g, 340); - for (int i = 0; i < g.getNumNodes(); ++i) { - const GP& node = g[i]; - points.add(K::GnuplotPoint3(node.x_cm, node.y_cm, node.z_cm)); - } - - splot.add(&points); - gp.draw(splot); - gp.flush(); - - sleep(10); +// plot(gInv); } + + #endif